@formatjs/cli-lib 6.6.6 → 7.0.1
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/lib_esnext/index.d.ts +7 -0
- package/lib_esnext/index.js +2 -0
- package/lib_esnext/main.d.ts +1 -0
- package/lib_esnext/main.js +3 -0
- package/lib_esnext/src/cli.d.ts +2 -0
- package/lib_esnext/src/cli.js +153 -0
- package/lib_esnext/src/compile.d.ts +54 -0
- package/lib_esnext/src/compile.js +90 -0
- package/lib_esnext/src/compile_folder.d.ts +2 -0
- package/lib_esnext/src/compile_folder.js +8 -0
- package/lib_esnext/src/console_utils.d.ts +7 -0
- package/lib_esnext/src/console_utils.js +67 -0
- package/lib_esnext/src/extract.d.ts +74 -0
- package/lib_esnext/src/extract.js +192 -0
- package/lib_esnext/src/formatters/crowdin.d.ts +7 -0
- package/lib_esnext/src/formatters/crowdin.js +22 -0
- package/lib_esnext/src/formatters/default.d.ts +6 -0
- package/lib_esnext/src/formatters/default.js +8 -0
- package/lib_esnext/src/formatters/index.d.ts +9 -0
- package/lib_esnext/src/formatters/index.js +36 -0
- package/lib_esnext/src/formatters/lokalise.d.ts +9 -0
- package/lib_esnext/src/formatters/lokalise.js +19 -0
- package/lib_esnext/src/formatters/simple.d.ts +4 -0
- package/lib_esnext/src/formatters/simple.js +7 -0
- package/lib_esnext/src/formatters/smartling.d.ts +23 -0
- package/lib_esnext/src/formatters/smartling.js +44 -0
- package/lib_esnext/src/formatters/transifex.d.ts +9 -0
- package/lib_esnext/src/formatters/transifex.js +19 -0
- package/lib_esnext/src/gts_extractor.d.ts +1 -0
- package/lib_esnext/src/gts_extractor.js +14 -0
- package/lib_esnext/src/hbs_extractor.d.ts +1 -0
- package/lib_esnext/src/hbs_extractor.js +45 -0
- package/lib_esnext/src/parse_script.d.ts +7 -0
- package/lib_esnext/src/parse_script.js +46 -0
- package/lib_esnext/src/pseudo_locale.d.ts +22 -0
- package/lib_esnext/src/pseudo_locale.js +115 -0
- package/lib_esnext/src/vue_extractor.d.ts +2 -0
- package/lib_esnext/src/vue_extractor.js +68 -0
- package/package.json +10 -9
- package/index.js.map +0 -1
- package/main.js.map +0 -1
- package/src/cli.js.map +0 -1
- package/src/compile.js.map +0 -1
- package/src/compile_folder.js.map +0 -1
- package/src/console_utils.js.map +0 -1
- package/src/extract.js.map +0 -1
- package/src/formatters/crowdin.js.map +0 -1
- package/src/formatters/default.js.map +0 -1
- package/src/formatters/index.js.map +0 -1
- package/src/formatters/lokalise.js.map +0 -1
- package/src/formatters/simple.js.map +0 -1
- package/src/formatters/smartling.js.map +0 -1
- package/src/formatters/transifex.js.map +0 -1
- package/src/gts_extractor.js.map +0 -1
- package/src/hbs_extractor.js.map +0 -1
- package/src/parse_script.js.map +0 -1
- package/src/pseudo_locale.js.map +0 -1
- package/src/vue_extractor.js.map +0 -1
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { default as extractAndWrite, extract } from './src/extract';
|
|
2
|
+
export type { ExtractCLIOptions, ExtractOpts } from './src/extract';
|
|
3
|
+
export type { MessageDescriptor } from '@formatjs/ts-transformer';
|
|
4
|
+
export type { FormatFn, CompileFn } from './src/formatters/default';
|
|
5
|
+
export type { Element, Comparator } from 'json-stable-stringify';
|
|
6
|
+
export { default as compileAndWrite, compile } from './src/compile';
|
|
7
|
+
export type { CompileCLIOpts, Opts as CompileOpts } from './src/compile';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { program } from 'commander';
|
|
2
|
+
import { sync as globSync } from 'fast-glob';
|
|
3
|
+
import loudRejection from 'loud-rejection';
|
|
4
|
+
import compile from './compile';
|
|
5
|
+
import compileFolder from './compile_folder';
|
|
6
|
+
import { debug } from './console_utils';
|
|
7
|
+
import extract from './extract';
|
|
8
|
+
const KNOWN_COMMANDS = ['extract'];
|
|
9
|
+
async function main(argv) {
|
|
10
|
+
loudRejection();
|
|
11
|
+
program
|
|
12
|
+
// TODO: fix this
|
|
13
|
+
.version('5.0.6', '-v, --version')
|
|
14
|
+
.usage('<command> [flags]')
|
|
15
|
+
.action(command => {
|
|
16
|
+
if (!KNOWN_COMMANDS.includes(command)) {
|
|
17
|
+
program.help();
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
program
|
|
21
|
+
.command('help', { isDefault: true })
|
|
22
|
+
.description('Show this help message.')
|
|
23
|
+
.action(() => program.help());
|
|
24
|
+
// Long text wrapping to available terminal columns: https://github.com/tj/commander.js/pull/956
|
|
25
|
+
// NOTE: please keep the help text in sync with babel-plugin-formatjs documentation.
|
|
26
|
+
program
|
|
27
|
+
.command('extract [files...]')
|
|
28
|
+
.description(`Extract string messages from React components that use react-intl.
|
|
29
|
+
The input language is expected to be TypeScript or ES2017 with JSX.`)
|
|
30
|
+
.option('--format <path>', `Path to a formatter file that controls the shape of JSON file from \`--out-file\`.
|
|
31
|
+
The formatter file must export a function called \`format\` with the signature
|
|
32
|
+
\`\`\`
|
|
33
|
+
type FormatFn = <T = Record<string, MessageDescriptor>>(
|
|
34
|
+
msgs: Record<string, MessageDescriptor>
|
|
35
|
+
) => T
|
|
36
|
+
\`\`\`
|
|
37
|
+
This is especially useful to convert from our extracted format to a TMS-specific format.
|
|
38
|
+
`)
|
|
39
|
+
.option('--out-file <path>', `The target file path where the plugin will output an aggregated
|
|
40
|
+
\`.json\` file of all the translations from the \`files\` supplied.`)
|
|
41
|
+
.option('--id-interpolation-pattern <pattern>', `If certain message descriptors don't have id, this \`pattern\` will be used to automatically
|
|
42
|
+
generate IDs for them. Default to \`[sha512:contenthash:base64:6]\` where \`contenthash\` is the hash of
|
|
43
|
+
\`defaultMessage\` and \`description\`.
|
|
44
|
+
See https://github.com/webpack/loader-utils#interpolatename for sample patterns`, '[sha512:contenthash:base64:6]')
|
|
45
|
+
.option('--extract-source-location', `Whether the metadata about the location of the message in the source file should be
|
|
46
|
+
extracted. If \`true\`, then \`file\`, \`start\`, and \`end\` fields will exist for each
|
|
47
|
+
extracted message descriptors.`, false)
|
|
48
|
+
.option('--remove-default-message', 'Remove `defaultMessage` field in generated js after extraction', false)
|
|
49
|
+
.option('--additional-component-names <comma-separated-names>', `Additional component names to extract messages from, e.g: \`'FormattedFooBarMessage'\`.
|
|
50
|
+
**NOTE**: By default we check for the fact that \`FormattedMessage\`
|
|
51
|
+
is imported from \`moduleSourceName\` to make sure variable alias
|
|
52
|
+
works. This option does not do that so it's less safe.`, (val) => val.split(','))
|
|
53
|
+
.option('--additional-function-names <comma-separated-names>', `Additional function names to extract messages from, e.g: \`'$t'\`.`, (val) => val.split(','))
|
|
54
|
+
.option('--ignore <files...>', 'List of glob paths to **not** extract translations from.')
|
|
55
|
+
.option('--throws', 'Whether to throw an exception when we fail to process any file in the batch.')
|
|
56
|
+
.option('--pragma <pragma>', `parse specific additional custom pragma. This allows you to tag certain file with metadata such as \`project\`. For example with this file:
|
|
57
|
+
|
|
58
|
+
\`\`\`
|
|
59
|
+
// @intl-meta project:my-custom-project
|
|
60
|
+
import {FormattedMessage} from 'react-intl';
|
|
61
|
+
|
|
62
|
+
<FormattedMessage defaultMessage="foo" id="bar" />;
|
|
63
|
+
\`\`\`
|
|
64
|
+
|
|
65
|
+
and with option \`{pragma: "intl-meta"}\`, we'll parse out \`// @intl-meta project:my-custom-project\` into \`{project: 'my-custom-project'}\` in the result file.`)
|
|
66
|
+
.option('--preserve-whitespace', 'Whether to preserve whitespace and newlines.')
|
|
67
|
+
.option('--flatten', `Whether to hoist selectors & flatten sentences as much as possible. E.g:
|
|
68
|
+
"I have {count, plural, one{a dog} other{many dogs}}"
|
|
69
|
+
becomes "{count, plural, one{I have a dog} other{I have many dogs}}".
|
|
70
|
+
The goal is to provide as many full sentences as possible since fragmented
|
|
71
|
+
sentences are not translator-friendly.`)
|
|
72
|
+
.action(async (filePatterns, cmdObj) => {
|
|
73
|
+
debug('File pattern:', filePatterns);
|
|
74
|
+
debug('Options:', cmdObj);
|
|
75
|
+
const files = globSync(filePatterns, {
|
|
76
|
+
ignore: cmdObj.ignore,
|
|
77
|
+
});
|
|
78
|
+
debug('Files to extract:', files);
|
|
79
|
+
await extract(files, {
|
|
80
|
+
outFile: cmdObj.outFile,
|
|
81
|
+
idInterpolationPattern: cmdObj.idInterpolationPattern || '[sha1:contenthash:base64:6]',
|
|
82
|
+
extractSourceLocation: cmdObj.extractSourceLocation,
|
|
83
|
+
removeDefaultMessage: cmdObj.removeDefaultMessage,
|
|
84
|
+
additionalComponentNames: cmdObj.additionalComponentNames,
|
|
85
|
+
additionalFunctionNames: cmdObj.additionalFunctionNames,
|
|
86
|
+
throws: cmdObj.throws,
|
|
87
|
+
pragma: cmdObj.pragma,
|
|
88
|
+
format: cmdObj.format,
|
|
89
|
+
// It is possible that the glob pattern does NOT match anything.
|
|
90
|
+
// But so long as the glob pattern is provided, don't read from stdin.
|
|
91
|
+
readFromStdin: filePatterns.length === 0,
|
|
92
|
+
preserveWhitespace: cmdObj.preserveWhitespace,
|
|
93
|
+
flatten: cmdObj.flatten,
|
|
94
|
+
});
|
|
95
|
+
process.exit(0);
|
|
96
|
+
});
|
|
97
|
+
program
|
|
98
|
+
.command('compile [translation_files...]')
|
|
99
|
+
.description(`Compile extracted translation file into react-intl consumable JSON We also verify that the messages are valid ICU and not malformed. <translation_files> can be a glob like "foo/**/en.json"`)
|
|
100
|
+
.option('--format <path>', `Path to a formatter file that converts \`<translation_file>\` to \`Record<string, string>\` so we can compile. The file must export a function named \`compile\` with the signature:
|
|
101
|
+
\`\`\`
|
|
102
|
+
type CompileFn = <T = Record<string, MessageDescriptor>>(
|
|
103
|
+
msgs: T
|
|
104
|
+
) => Record<string, string>;
|
|
105
|
+
\`\`\`
|
|
106
|
+
This is especially useful to convert from a TMS-specific format back to react-intl format
|
|
107
|
+
`)
|
|
108
|
+
.option('--out-file <path>', `Compiled translation output file. If this is not provided, result will be printed to stdout`)
|
|
109
|
+
.option('--ast', `Whether to compile to AST. See https://formatjs.github.io/docs/guides/advanced-usage#pre-parsing-messages for more information`)
|
|
110
|
+
.option('--skip-errors', `Whether to continue compiling messages after encountering an error. Any keys with errors will not be included in the output file.`)
|
|
111
|
+
.option('--pseudo-locale <pseudoLocale>', `Whether to generate pseudo-locale files. See https://formatjs.github.io/docs/tooling/cli#--pseudo-locale-pseudolocale for possible values. "--ast" is required for this to work.`)
|
|
112
|
+
.option('--ignore-tag', `Whether the parser to treat HTML/XML tags as string literal instead of parsing them as tag token. When this is false we only allow simple tags without any attributes.`)
|
|
113
|
+
.action(async (filePatterns, opts) => {
|
|
114
|
+
debug('File pattern:', filePatterns);
|
|
115
|
+
debug('Options:', opts);
|
|
116
|
+
const files = globSync(filePatterns);
|
|
117
|
+
if (!files.length) {
|
|
118
|
+
throw new Error(`No input file found with pattern ${filePatterns}`);
|
|
119
|
+
}
|
|
120
|
+
debug('Files to compile:', files);
|
|
121
|
+
await compile(files, opts);
|
|
122
|
+
});
|
|
123
|
+
program
|
|
124
|
+
.command('compile-folder <folder> <outFolder>')
|
|
125
|
+
.description(`Batch compile all extracted translation JSON files in <folder> to <outFolder> containing react-intl consumable JSON. We also verify that the messages are valid ICU and not malformed.`)
|
|
126
|
+
.option('--format <path>', `Path to a formatter file that converts JSON files in \`<folder>\` to \`Record<string, string>\` so we can compile. The file must export a function named \`compile\` with the signature:
|
|
127
|
+
\`\`\`
|
|
128
|
+
type CompileFn = <T = Record<string, MessageDescriptor>>(
|
|
129
|
+
msgs: T
|
|
130
|
+
) => Record<string, string>;
|
|
131
|
+
\`\`\`
|
|
132
|
+
This is especially useful to convert from a TMS-specific format back to react-intl format
|
|
133
|
+
`)
|
|
134
|
+
.option('--ast', `Whether to compile to AST. See https://formatjs.github.io/docs/guides/advanced-usage#pre-parsing-messages for more information`)
|
|
135
|
+
.action(async (folder, outFolder, opts) => {
|
|
136
|
+
debug('Folder:', folder);
|
|
137
|
+
debug('Options:', opts);
|
|
138
|
+
// fast-glob expect `/` in Windows as well
|
|
139
|
+
const files = globSync(`${folder}/*.json`);
|
|
140
|
+
if (!files.length) {
|
|
141
|
+
throw new Error(`No JSON file found in ${folder}`);
|
|
142
|
+
}
|
|
143
|
+
debug('Files to compile:', files);
|
|
144
|
+
await compileFolder(files, outFolder, opts);
|
|
145
|
+
});
|
|
146
|
+
if (argv.length < 3) {
|
|
147
|
+
program.help();
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
program.parse(argv);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
export default main;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { Formatter } from './formatters';
|
|
2
|
+
export type CompileFn = (msgs: any) => Record<string, string>;
|
|
3
|
+
export type PseudoLocale = 'xx-LS' | 'xx-AC' | 'xx-HA' | 'en-XA' | 'en-XB';
|
|
4
|
+
export interface CompileCLIOpts extends Opts {
|
|
5
|
+
/**
|
|
6
|
+
* The target file that contains compiled messages.
|
|
7
|
+
*/
|
|
8
|
+
outFile?: string;
|
|
9
|
+
}
|
|
10
|
+
export interface Opts {
|
|
11
|
+
/**
|
|
12
|
+
* Whether to compile message into AST instead of just string
|
|
13
|
+
*/
|
|
14
|
+
ast?: boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Whether to continue compiling messages after encountering an error.
|
|
17
|
+
* Any keys with errors will not be included in the output file.
|
|
18
|
+
*/
|
|
19
|
+
skipErrors?: boolean;
|
|
20
|
+
/**
|
|
21
|
+
* Path to a formatter file that converts <translation_files> to
|
|
22
|
+
* `Record<string, string>` so we can compile.
|
|
23
|
+
*/
|
|
24
|
+
format?: string | Formatter<unknown>;
|
|
25
|
+
/**
|
|
26
|
+
* Whether to compile to pseudo locale
|
|
27
|
+
*/
|
|
28
|
+
pseudoLocale?: PseudoLocale;
|
|
29
|
+
/**
|
|
30
|
+
* Whether the parser to treat HTML/XML tags as string literal
|
|
31
|
+
* instead of parsing them as tag token.
|
|
32
|
+
* When this is false we only allow simple tags without
|
|
33
|
+
* any attributes
|
|
34
|
+
*/
|
|
35
|
+
ignoreTag?: boolean;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Aggregate `inputFiles` into a single JSON blob and compile.
|
|
39
|
+
* Also checks for conflicting IDs.
|
|
40
|
+
* Then returns the serialized result as a `string` since key order
|
|
41
|
+
* makes a difference in some vendor.
|
|
42
|
+
* @param inputFiles Input files
|
|
43
|
+
* @param opts Options
|
|
44
|
+
* @returns serialized result in string format
|
|
45
|
+
*/
|
|
46
|
+
export declare function compile(inputFiles: string[], opts?: Opts): Promise<string>;
|
|
47
|
+
/**
|
|
48
|
+
* Aggregate `inputFiles` into a single JSON blob and compile.
|
|
49
|
+
* Also checks for conflicting IDs and write output to `outFile`.
|
|
50
|
+
* @param inputFiles Input files
|
|
51
|
+
* @param compileOpts options
|
|
52
|
+
* @returns A `Promise` that resolves if file was written successfully
|
|
53
|
+
*/
|
|
54
|
+
export default function compileAndWrite(inputFiles: string[], compileOpts?: CompileCLIOpts): Promise<void>;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { parse } from '@formatjs/icu-messageformat-parser';
|
|
2
|
+
import { outputFile, readJSON } from 'fs-extra';
|
|
3
|
+
import stringify from 'json-stable-stringify';
|
|
4
|
+
import { debug, warn, writeStdout } from './console_utils';
|
|
5
|
+
import { resolveBuiltinFormatter } from './formatters';
|
|
6
|
+
import { generateENXA, generateENXB, generateXXAC, generateXXHA, generateXXLS, } from './pseudo_locale';
|
|
7
|
+
/**
|
|
8
|
+
* Aggregate `inputFiles` into a single JSON blob and compile.
|
|
9
|
+
* Also checks for conflicting IDs.
|
|
10
|
+
* Then returns the serialized result as a `string` since key order
|
|
11
|
+
* makes a difference in some vendor.
|
|
12
|
+
* @param inputFiles Input files
|
|
13
|
+
* @param opts Options
|
|
14
|
+
* @returns serialized result in string format
|
|
15
|
+
*/
|
|
16
|
+
export async function compile(inputFiles, opts = {}) {
|
|
17
|
+
debug('Compiling files:', inputFiles);
|
|
18
|
+
const { ast, format, pseudoLocale, skipErrors, ignoreTag } = opts;
|
|
19
|
+
const formatter = await resolveBuiltinFormatter(format);
|
|
20
|
+
const messages = {};
|
|
21
|
+
const messageAsts = {};
|
|
22
|
+
const idsWithFileName = {};
|
|
23
|
+
const compiledFiles = await Promise.all(inputFiles.map(f => readJSON(f).then(formatter.compile)));
|
|
24
|
+
debug('Compiled files:', compiledFiles);
|
|
25
|
+
for (let i = 0; i < inputFiles.length; i++) {
|
|
26
|
+
const inputFile = inputFiles[i];
|
|
27
|
+
debug('Processing file:', inputFile);
|
|
28
|
+
const compiled = compiledFiles[i];
|
|
29
|
+
for (const id in compiled) {
|
|
30
|
+
if (messages[id] && messages[id] !== compiled[id]) {
|
|
31
|
+
throw new Error(`Conflicting ID "${id}" with different translation found in these 2 files:
|
|
32
|
+
ID: ${id}
|
|
33
|
+
Message from ${idsWithFileName[id]}: ${messages[id]}
|
|
34
|
+
Message from ${inputFile}: ${compiled[id]}
|
|
35
|
+
`);
|
|
36
|
+
}
|
|
37
|
+
try {
|
|
38
|
+
const msgAst = parse(compiled[id], { ignoreTag });
|
|
39
|
+
messages[id] = compiled[id];
|
|
40
|
+
switch (pseudoLocale) {
|
|
41
|
+
case 'xx-LS':
|
|
42
|
+
messageAsts[id] = generateXXLS(msgAst);
|
|
43
|
+
break;
|
|
44
|
+
case 'xx-AC':
|
|
45
|
+
messageAsts[id] = generateXXAC(msgAst);
|
|
46
|
+
break;
|
|
47
|
+
case 'xx-HA':
|
|
48
|
+
messageAsts[id] = generateXXHA(msgAst);
|
|
49
|
+
break;
|
|
50
|
+
case 'en-XA':
|
|
51
|
+
messageAsts[id] = generateENXA(msgAst);
|
|
52
|
+
break;
|
|
53
|
+
case 'en-XB':
|
|
54
|
+
messageAsts[id] = generateENXB(msgAst);
|
|
55
|
+
break;
|
|
56
|
+
default:
|
|
57
|
+
messageAsts[id] = msgAst;
|
|
58
|
+
break;
|
|
59
|
+
}
|
|
60
|
+
idsWithFileName[id] = inputFile;
|
|
61
|
+
}
|
|
62
|
+
catch (e) {
|
|
63
|
+
warn('Error validating message "%s" with ID "%s" in file "%s"', compiled[id], id, inputFile);
|
|
64
|
+
if (!skipErrors) {
|
|
65
|
+
throw e;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return stringify(ast ? messageAsts : messages, {
|
|
71
|
+
space: 2,
|
|
72
|
+
cmp: formatter.compareMessages || undefined,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Aggregate `inputFiles` into a single JSON blob and compile.
|
|
77
|
+
* Also checks for conflicting IDs and write output to `outFile`.
|
|
78
|
+
* @param inputFiles Input files
|
|
79
|
+
* @param compileOpts options
|
|
80
|
+
* @returns A `Promise` that resolves if file was written successfully
|
|
81
|
+
*/
|
|
82
|
+
export default async function compileAndWrite(inputFiles, compileOpts = {}) {
|
|
83
|
+
const { outFile, ...opts } = compileOpts;
|
|
84
|
+
const serializedResult = (await compile(inputFiles, opts)) + '\n';
|
|
85
|
+
if (outFile) {
|
|
86
|
+
debug('Writing output file:', outFile);
|
|
87
|
+
return outputFile(outFile, serializedResult);
|
|
88
|
+
}
|
|
89
|
+
await writeStdout(serializedResult);
|
|
90
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { outputFile } from 'fs-extra';
|
|
2
|
+
import { basename, join } from 'path';
|
|
3
|
+
import { compile } from './compile';
|
|
4
|
+
export default async function compileFolder(files, outFolder, opts = {}) {
|
|
5
|
+
const results = await Promise.all(files.map(f => compile([f], opts)));
|
|
6
|
+
const outFiles = files.map(f => join(outFolder, basename(f)));
|
|
7
|
+
return Promise.all(outFiles.map((outFile, i) => outputFile(outFile, results[i])));
|
|
8
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare const writeStderr: (arg1: string | Uint8Array) => Promise<void>;
|
|
2
|
+
export declare const writeStdout: (arg1: string | Uint8Array) => Promise<void>;
|
|
3
|
+
export declare function clearLine(terminal: (typeof process)['stderr']): Promise<void>;
|
|
4
|
+
export declare function debug(message: string, ...args: any[]): Promise<void>;
|
|
5
|
+
export declare function warn(message: string, ...args: any[]): Promise<void>;
|
|
6
|
+
export declare function error(message: string, ...args: any[]): Promise<void>;
|
|
7
|
+
export declare function getStdinAsString(): Promise<string>;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { green, red, supportsColor, yellow } from 'chalk';
|
|
2
|
+
import readline from 'readline';
|
|
3
|
+
import { format, promisify } from 'util';
|
|
4
|
+
const CLEAR_WHOLE_LINE = 0;
|
|
5
|
+
export const writeStderr = promisify(process.stderr.write).bind(process.stderr);
|
|
6
|
+
export const writeStdout = promisify(process.stdout.write).bind(process.stdout);
|
|
7
|
+
const nativeClearLine = promisify(readline.clearLine).bind(readline);
|
|
8
|
+
const nativeCursorTo = promisify(readline.cursorTo).bind(readline);
|
|
9
|
+
// From:
|
|
10
|
+
// https://github.com/yarnpkg/yarn/blob/53d8004229f543f342833310d5af63a4b6e59c8a/src/reporters/console/util.js
|
|
11
|
+
export async function clearLine(terminal) {
|
|
12
|
+
if (!supportsColor) {
|
|
13
|
+
if (terminal.isTTY) {
|
|
14
|
+
// terminal
|
|
15
|
+
if (terminal.columns > 0) {
|
|
16
|
+
await writeStderr(`\r${' '.repeat(terminal.columns - 1)}`);
|
|
17
|
+
}
|
|
18
|
+
await writeStderr(`\r`);
|
|
19
|
+
}
|
|
20
|
+
// ignore piping to file
|
|
21
|
+
}
|
|
22
|
+
else {
|
|
23
|
+
await nativeClearLine(terminal, CLEAR_WHOLE_LINE);
|
|
24
|
+
await nativeCursorTo(terminal, 0, undefined);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const LEVEL_COLORS = {
|
|
28
|
+
debug: green,
|
|
29
|
+
warn: yellow,
|
|
30
|
+
error: red,
|
|
31
|
+
};
|
|
32
|
+
function label(level, message) {
|
|
33
|
+
return `[@formatjs/cli] [${LEVEL_COLORS[level](level.toUpperCase())}] ${message}`;
|
|
34
|
+
}
|
|
35
|
+
export async function debug(message, ...args) {
|
|
36
|
+
if (process.env.LOG_LEVEL !== 'debug') {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
await clearLine(process.stderr);
|
|
40
|
+
await writeStderr(format(label('debug', message), ...args));
|
|
41
|
+
await writeStderr('\n');
|
|
42
|
+
}
|
|
43
|
+
export async function warn(message, ...args) {
|
|
44
|
+
await clearLine(process.stderr);
|
|
45
|
+
await writeStderr(format(label('warn', message), ...args));
|
|
46
|
+
await writeStderr('\n');
|
|
47
|
+
}
|
|
48
|
+
export async function error(message, ...args) {
|
|
49
|
+
await clearLine(process.stderr);
|
|
50
|
+
await writeStderr(format(label('error', message), ...args));
|
|
51
|
+
await writeStderr('\n');
|
|
52
|
+
}
|
|
53
|
+
export function getStdinAsString() {
|
|
54
|
+
let result = '';
|
|
55
|
+
return new Promise(resolve => {
|
|
56
|
+
process.stdin.setEncoding('utf-8');
|
|
57
|
+
process.stdin.on('readable', () => {
|
|
58
|
+
let chunk;
|
|
59
|
+
while ((chunk = process.stdin.read())) {
|
|
60
|
+
result += chunk;
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
process.stdin.on('end', () => {
|
|
64
|
+
resolve(result);
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { MessageDescriptor, Opts } from '@formatjs/ts-transformer';
|
|
2
|
+
import { Formatter } from './formatters';
|
|
3
|
+
export interface ExtractionResult<M = Record<string, string>> {
|
|
4
|
+
/**
|
|
5
|
+
* List of extracted messages
|
|
6
|
+
*/
|
|
7
|
+
messages: MessageDescriptor[];
|
|
8
|
+
/**
|
|
9
|
+
* Metadata extracted w/ `pragma`
|
|
10
|
+
*/
|
|
11
|
+
meta?: M;
|
|
12
|
+
}
|
|
13
|
+
export interface ExtractedMessageDescriptor extends MessageDescriptor {
|
|
14
|
+
/**
|
|
15
|
+
* Line number
|
|
16
|
+
*/
|
|
17
|
+
line?: number;
|
|
18
|
+
/**
|
|
19
|
+
* Column number
|
|
20
|
+
*/
|
|
21
|
+
col?: number;
|
|
22
|
+
/**
|
|
23
|
+
* Metadata extracted from pragma
|
|
24
|
+
*/
|
|
25
|
+
meta?: Record<string, string>;
|
|
26
|
+
}
|
|
27
|
+
export type ExtractCLIOptions = Omit<ExtractOpts, 'overrideIdFn' | 'onMsgExtracted' | 'onMetaExtracted'> & {
|
|
28
|
+
/**
|
|
29
|
+
* Output File
|
|
30
|
+
*/
|
|
31
|
+
outFile?: string;
|
|
32
|
+
/**
|
|
33
|
+
* Ignore file glob pattern
|
|
34
|
+
*/
|
|
35
|
+
ignore?: string[];
|
|
36
|
+
};
|
|
37
|
+
export type ExtractOpts = Opts & {
|
|
38
|
+
/**
|
|
39
|
+
* Whether to throw an error if we had any issues with
|
|
40
|
+
* 1 of the source files
|
|
41
|
+
*/
|
|
42
|
+
throws?: boolean;
|
|
43
|
+
/**
|
|
44
|
+
* Message ID interpolation pattern
|
|
45
|
+
*/
|
|
46
|
+
idInterpolationPattern?: string;
|
|
47
|
+
/**
|
|
48
|
+
* Whether we read from stdin instead of a file
|
|
49
|
+
*/
|
|
50
|
+
readFromStdin?: boolean;
|
|
51
|
+
/**
|
|
52
|
+
* Either path to a formatter file that controls the shape of JSON file from `outFile` or {@link Formatter} object.
|
|
53
|
+
*/
|
|
54
|
+
format?: string | Formatter<any>;
|
|
55
|
+
/**
|
|
56
|
+
* Whether to hoist selectors & flatten sentences
|
|
57
|
+
*/
|
|
58
|
+
flatten?: boolean;
|
|
59
|
+
} & Pick<Opts, 'onMsgExtracted' | 'onMetaExtracted'>;
|
|
60
|
+
/**
|
|
61
|
+
* Extract strings from source files
|
|
62
|
+
* @param files list of files
|
|
63
|
+
* @param extractOpts extract options
|
|
64
|
+
* @returns messages serialized as JSON string since key order
|
|
65
|
+
* matters for some `format`
|
|
66
|
+
*/
|
|
67
|
+
export declare function extract(files: readonly string[], extractOpts: ExtractOpts): Promise<string>;
|
|
68
|
+
/**
|
|
69
|
+
* Extract strings from source files, also writes to a file.
|
|
70
|
+
* @param files list of files
|
|
71
|
+
* @param extractOpts extract options
|
|
72
|
+
* @returns A Promise that resolves if output file was written successfully
|
|
73
|
+
*/
|
|
74
|
+
export default function extractAndWrite(files: readonly string[], extractOpts: ExtractCLIOptions): Promise<void>;
|