@formatjs/cli-lib 5.1.8 → 5.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/index.d.ts +8 -0
  2. package/index.d.ts.map +1 -0
  3. package/index.js +12 -0
  4. package/main.d.ts +2 -0
  5. package/main.d.ts.map +1 -0
  6. package/main.js +3 -0
  7. package/package.json +1 -1
  8. package/src/cli.d.ts +3 -0
  9. package/src/cli.d.ts.map +1 -0
  10. package/src/cli.js +165 -0
  11. package/src/compile.d.ts +48 -0
  12. package/src/compile.d.ts.map +1 -0
  13. package/src/compile.js +97 -0
  14. package/src/compile_folder.d.ts +3 -0
  15. package/src/compile_folder.d.ts.map +1 -0
  16. package/src/compile_folder.js +11 -0
  17. package/src/console_utils.d.ts +10 -0
  18. package/src/console_utils.d.ts.map +1 -0
  19. package/src/console_utils.js +76 -0
  20. package/src/extract.d.ts +75 -0
  21. package/src/extract.d.ts.map +1 -0
  22. package/src/extract.js +177 -0
  23. package/src/formatters/crowdin.d.ts +8 -0
  24. package/src/formatters/crowdin.d.ts.map +1 -0
  25. package/src/formatters/crowdin.js +27 -0
  26. package/src/formatters/default.d.ts +6 -0
  27. package/src/formatters/default.d.ts.map +1 -0
  28. package/src/formatters/default.js +13 -0
  29. package/src/formatters/index.d.ts +9 -0
  30. package/src/formatters/index.d.ts.map +1 -0
  31. package/src/formatters/index.js +42 -0
  32. package/src/formatters/lokalise.d.ts +10 -0
  33. package/src/formatters/lokalise.d.ts.map +1 -0
  34. package/src/formatters/lokalise.js +24 -0
  35. package/src/formatters/simple.d.ts +5 -0
  36. package/src/formatters/simple.d.ts.map +1 -0
  37. package/src/formatters/simple.js +12 -0
  38. package/src/formatters/smartling.d.ts +24 -0
  39. package/src/formatters/smartling.d.ts.map +1 -0
  40. package/src/formatters/smartling.js +50 -0
  41. package/src/formatters/transifex.d.ts +10 -0
  42. package/src/formatters/transifex.d.ts.map +1 -0
  43. package/src/formatters/transifex.js +24 -0
  44. package/src/parse_script.d.ts +8 -0
  45. package/src/parse_script.d.ts.map +1 -0
  46. package/src/parse_script.js +51 -0
  47. package/src/pseudo_locale.d.ts +7 -0
  48. package/src/pseudo_locale.d.ts.map +1 -0
  49. package/src/pseudo_locale.js +100 -0
  50. package/src/vue_extractor.d.ts +3 -0
  51. package/src/vue_extractor.d.ts.map +1 -0
  52. package/src/vue_extractor.js +62 -0
  53. package/BUILD +0 -118
  54. package/CHANGELOG.md +0 -1147
  55. package/index.ts +0 -7
  56. package/main.ts +0 -5
  57. package/src/cli.ts +0 -240
  58. package/src/compile.ts +0 -141
  59. package/src/compile_folder.ts +0 -15
  60. package/src/console_utils.ts +0 -78
  61. package/src/extract.ts +0 -273
  62. package/src/formatters/crowdin.ts +0 -34
  63. package/src/formatters/default.ts +0 -19
  64. package/src/formatters/index.ts +0 -46
  65. package/src/formatters/lokalise.ts +0 -33
  66. package/src/formatters/simple.ts +0 -12
  67. package/src/formatters/smartling.ts +0 -73
  68. package/src/formatters/transifex.ts +0 -33
  69. package/src/parse_script.ts +0 -49
  70. package/src/pseudo_locale.ts +0 -113
  71. package/src/vue_extractor.ts +0 -96
  72. package/tests/unit/__snapshots__/pseudo_locale.test.ts.snap +0 -24
  73. package/tests/unit/__snapshots__/unit.test.ts.snap +0 -42
  74. package/tests/unit/__snapshots__/vue_extractor.test.ts.snap +0 -36
  75. package/tests/unit/fixtures/bind.vue +0 -46
  76. package/tests/unit/fixtures/comp.vue +0 -17
  77. package/tests/unit/pseudo_locale.test.ts +0 -7
  78. package/tests/unit/unit.test.ts +0 -44
  79. package/tests/unit/vue_extractor.test.ts +0 -38
  80. package/tsconfig.json +0 -5
package/index.d.ts ADDED
@@ -0,0 +1,8 @@
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';
8
+ //# sourceMappingURL=index.d.ts.map
package/index.d.ts.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,OAAO,IAAI,eAAe,EAAE,OAAO,EAAC,MAAM,eAAe,CAAA;AACjE,YAAY,EAAC,iBAAiB,EAAE,WAAW,EAAC,MAAM,eAAe,CAAA;AACjE,YAAY,EAAC,iBAAiB,EAAC,MAAM,0BAA0B,CAAA;AAC/D,YAAY,EAAC,QAAQ,EAAE,SAAS,EAAC,MAAM,0BAA0B,CAAA;AACjE,YAAY,EAAC,OAAO,EAAE,UAAU,EAAC,MAAM,uBAAuB,CAAA;AAC9D,OAAO,EAAC,OAAO,IAAI,eAAe,EAAE,OAAO,EAAC,MAAM,eAAe,CAAA;AACjE,YAAY,EAAC,cAAc,EAAE,IAAI,IAAI,WAAW,EAAC,MAAM,eAAe,CAAA"}
package/index.js ADDED
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.compile = exports.compileAndWrite = exports.extract = exports.extractAndWrite = void 0;
7
+ var extract_1 = require("./src/extract");
8
+ Object.defineProperty(exports, "extractAndWrite", { enumerable: true, get: function () { return __importDefault(extract_1).default; } });
9
+ Object.defineProperty(exports, "extract", { enumerable: true, get: function () { return extract_1.extract; } });
10
+ var compile_1 = require("./src/compile");
11
+ Object.defineProperty(exports, "compileAndWrite", { enumerable: true, get: function () { return __importDefault(compile_1).default; } });
12
+ Object.defineProperty(exports, "compile", { enumerable: true, get: function () { return compile_1.compile; } });
package/main.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ //# sourceMappingURL=main.d.ts.map
package/main.d.ts.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["main.ts"],"names":[],"mappings":""}
package/main.js ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ require('./src/cli').default(process.argv);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@formatjs/cli-lib",
3
- "version": "5.1.8",
3
+ "version": "5.1.10",
4
4
  "description": "Lib for CLI for formatjs.",
5
5
  "keywords": [
6
6
  "intl",
package/src/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ declare function main(argv: string[]): Promise<void>;
2
+ export default main;
3
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["cli.ts"],"names":[],"mappings":"AAUA,iBAAe,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,iBAoOjC;AACD,eAAe,IAAI,CAAA"}
package/src/cli.js ADDED
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ const commander_1 = require("commander");
5
+ const loud_rejection_1 = tslib_1.__importDefault(require("loud-rejection"));
6
+ const extract_1 = tslib_1.__importDefault(require("./extract"));
7
+ const compile_1 = tslib_1.__importDefault(require("./compile"));
8
+ const compile_folder_1 = tslib_1.__importDefault(require("./compile_folder"));
9
+ const fast_glob_1 = require("fast-glob");
10
+ const console_utils_1 = require("./console_utils");
11
+ const KNOWN_COMMANDS = ['extract'];
12
+ async function main(argv) {
13
+ (0, loud_rejection_1.default)();
14
+ commander_1.program
15
+ // TODO: fix this
16
+ .version('5.0.6', '-v, --version')
17
+ .usage('<command> [flags]')
18
+ .action(command => {
19
+ if (!KNOWN_COMMANDS.includes(command)) {
20
+ commander_1.program.help();
21
+ }
22
+ });
23
+ commander_1.program
24
+ .command('help', { isDefault: true })
25
+ .description('Show this help message.')
26
+ .action(() => commander_1.program.help());
27
+ // Long text wrapping to available terminal columns: https://github.com/tj/commander.js/pull/956
28
+ // NOTE: please keep the help text in sync with babel-plugin-formatjs documentation.
29
+ commander_1.program
30
+ .command('extract [files...]')
31
+ .description(`Extract string messages from React components that use react-intl.
32
+ The input language is expected to be TypeScript or ES2017 with JSX.`)
33
+ .option('--format <path>', `Path to a formatter file that controls the shape of JSON file from \`--out-file\`.
34
+ The formatter file must export a function called \`format\` with the signature
35
+ \`\`\`
36
+ type FormatFn = <T = Record<string, MessageDescriptor>>(
37
+ msgs: Record<string, MessageDescriptor>
38
+ ) => T
39
+ \`\`\`
40
+ This is especially useful to convert from our extracted format to a TMS-specific format.
41
+ `)
42
+ .option('--out-file <path>', `The target file path where the plugin will output an aggregated
43
+ \`.json\` file of all the translations from the \`files\` supplied.`)
44
+ .option('--id-interpolation-pattern <pattern>', `If certain message descriptors don't have id, this \`pattern\` will be used to automatically
45
+ generate IDs for them. Default to \`[sha512:contenthash:base64:6]\` where \`contenthash\` is the hash of
46
+ \`defaultMessage\` and \`description\`.
47
+ See https://github.com/webpack/loader-utils#interpolatename for sample patterns`, '[sha512:contenthash:base64:6]')
48
+ .option('--extract-source-location', `Whether the metadata about the location of the message in the source file should be
49
+ extracted. If \`true\`, then \`file\`, \`start\`, and \`end\` fields will exist for each
50
+ extracted message descriptors.`, false)
51
+ .option('--remove-default-message', 'Remove `defaultMessage` field in generated js after extraction', false)
52
+ .option('--additional-component-names <comma-separated-names>', `Additional component names to extract messages from, e.g: \`'FormattedFooBarMessage'\`.
53
+ **NOTE**: By default we check for the fact that \`FormattedMessage\`
54
+ is imported from \`moduleSourceName\` to make sure variable alias
55
+ works. This option does not do that so it's less safe.`, (val) => val.split(','))
56
+ .option('--additional-function-names <comma-separated-names>', `Additional function names to extract messages from, e.g: \`'$t'\`.`, (val) => val.split(','))
57
+ .option('--ignore <files...>', 'List of glob paths to **not** extract translations from.')
58
+ .option('--throws', 'Whether to throw an exception when we fail to process any file in the batch.')
59
+ .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:
60
+
61
+ \`\`\`
62
+ // @intl-meta project:my-custom-project
63
+ import {FormattedMessage} from 'react-intl';
64
+
65
+ <FormattedMessage defaultMessage="foo" id="bar" />;
66
+ \`\`\`
67
+
68
+ 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.`)
69
+ .option('--preserve-whitespace', 'Whether to preserve whitespace and newlines.')
70
+ .option('--flatten', `Whether to hoist selectors & flatten sentences as much as possible. E.g:
71
+ "I have {count, plural, one{a dog} other{many dogs}}"
72
+ becomes "{count, plural, one{I have a dog} other{I have many dogs}}".
73
+ The goal is to provide as many full sentences as possible since fragmented
74
+ sentences are not translator-friendly.`)
75
+ .action(async (filePatterns, cmdObj) => {
76
+ (0, console_utils_1.debug)('File pattern:', filePatterns);
77
+ (0, console_utils_1.debug)('Options:', cmdObj);
78
+ const files = (0, fast_glob_1.sync)(filePatterns, {
79
+ ignore: cmdObj.ignore,
80
+ });
81
+ (0, console_utils_1.debug)('Files to extract:', files);
82
+ await (0, extract_1.default)(files, {
83
+ outFile: cmdObj.outFile,
84
+ idInterpolationPattern: cmdObj.idInterpolationPattern || '[sha1:contenthash:base64:6]',
85
+ extractSourceLocation: cmdObj.extractSourceLocation,
86
+ removeDefaultMessage: cmdObj.removeDefaultMessage,
87
+ additionalComponentNames: cmdObj.additionalComponentNames,
88
+ additionalFunctionNames: cmdObj.additionalFunctionNames,
89
+ throws: cmdObj.throws,
90
+ pragma: cmdObj.pragma,
91
+ format: cmdObj.format,
92
+ // It is possible that the glob pattern does NOT match anything.
93
+ // But so long as the glob pattern is provided, don't read from stdin.
94
+ readFromStdin: filePatterns.length === 0,
95
+ preserveWhitespace: cmdObj.preserveWhitespace,
96
+ flatten: cmdObj.flatten,
97
+ });
98
+ process.exit(0);
99
+ });
100
+ commander_1.program
101
+ .command('compile [translation_files...]')
102
+ .description(`Compile extracted translation file into react-intl consumable JSON
103
+ We also verify that the messages are valid ICU and not malformed.
104
+ <translation_files> can be a glob like "foo/**/en.json"`)
105
+ .option('--format <path>', `Path to a formatter file that converts \`<translation_file>\` to \`Record<string, string>\`
106
+ so we can compile. The file must export a function named \`compile\` with the signature:
107
+ \`\`\`
108
+ type CompileFn = <T = Record<string, MessageDescriptor>>(
109
+ msgs: T
110
+ ) => Record<string, string>;
111
+ \`\`\`
112
+ This is especially useful to convert from a TMS-specific format back to react-intl format
113
+ `)
114
+ .option('--out-file <path>', `Compiled translation output file.
115
+ If this is not provided, result will be printed to stdout`)
116
+ .option('--ast', `Whether to compile to AST. See https://formatjs.io/docs/guides/advanced-usage#pre-parsing-messages
117
+ for more information`)
118
+ .option('--skip-errors', `Whether to continue compiling messages after encountering an error. Any keys with errors will not be included in the output file.`)
119
+ .option('--pseudo-locale <pseudoLocale>', `Whether to generate pseudo-locale files. See https://formatjs.io/docs/tooling/cli#--pseudo-locale-pseudolocale for possible values.
120
+ "--ast" is required for this to work.`)
121
+ .action(async (filePatterns, opts) => {
122
+ (0, console_utils_1.debug)('File pattern:', filePatterns);
123
+ (0, console_utils_1.debug)('Options:', opts);
124
+ const files = (0, fast_glob_1.sync)(filePatterns);
125
+ if (!files.length) {
126
+ throw new Error(`No input file found with pattern ${filePatterns}`);
127
+ }
128
+ (0, console_utils_1.debug)('Files to compile:', files);
129
+ await (0, compile_1.default)(files, opts);
130
+ });
131
+ commander_1.program
132
+ .command('compile-folder <folder> <outFolder>')
133
+ .description(`Batch compile all extracted translation JSON files in <folder> to <outFolder> containing
134
+ react-intl consumable JSON. We also verify that the messages are
135
+ valid ICU and not malformed.`)
136
+ .option('--format <path>', `Path to a formatter file that converts JSON files in \`<folder>\` to \`Record<string, string>\`
137
+ so we can compile. The file must export a function named \`compile\` with the signature:
138
+ \`\`\`
139
+ type CompileFn = <T = Record<string, MessageDescriptor>>(
140
+ msgs: T
141
+ ) => Record<string, string>;
142
+ \`\`\`
143
+ This is especially useful to convert from a TMS-specific format back to react-intl format
144
+ `)
145
+ .option('--ast', `Whether to compile to AST. See https://formatjs.io/docs/guides/advanced-usage#pre-parsing-messages
146
+ for more information`)
147
+ .action(async (folder, outFolder, opts) => {
148
+ (0, console_utils_1.debug)('Folder:', folder);
149
+ (0, console_utils_1.debug)('Options:', opts);
150
+ // fast-glob expect `/` in Windows as well
151
+ const files = (0, fast_glob_1.sync)(`${folder}/*.json`);
152
+ if (!files.length) {
153
+ throw new Error(`No JSON file found in ${folder}`);
154
+ }
155
+ (0, console_utils_1.debug)('Files to compile:', files);
156
+ await (0, compile_folder_1.default)(files, outFolder, opts);
157
+ });
158
+ if (argv.length < 3) {
159
+ commander_1.program.help();
160
+ }
161
+ else {
162
+ commander_1.program.parse(argv);
163
+ }
164
+ }
165
+ exports.default = main;
@@ -0,0 +1,48 @@
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;
25
+ /**
26
+ * Whether to compile to pseudo locale
27
+ */
28
+ pseudoLocale?: PseudoLocale;
29
+ }
30
+ /**
31
+ * Aggregate `inputFiles` into a single JSON blob and compile.
32
+ * Also checks for conflicting IDs.
33
+ * Then returns the serialized result as a `string` since key order
34
+ * makes a difference in some vendor.
35
+ * @param inputFiles Input files
36
+ * @param opts Options
37
+ * @returns serialized result in string format
38
+ */
39
+ export declare function compile(inputFiles: string[], opts?: Opts): Promise<string>;
40
+ /**
41
+ * Aggregate `inputFiles` into a single JSON blob and compile.
42
+ * Also checks for conflicting IDs and write output to `outFile`.
43
+ * @param inputFiles Input files
44
+ * @param compileOpts options
45
+ * @returns A `Promise` that resolves if file was written successfully
46
+ */
47
+ export default function compileAndWrite(inputFiles: string[], compileOpts?: CompileCLIOpts): Promise<void>;
48
+ //# sourceMappingURL=compile.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compile.d.ts","sourceRoot":"","sources":["compile.ts"],"names":[],"mappings":"AAIA,OAAO,EAA0B,SAAS,EAAC,MAAM,cAAc,CAAA;AAS/D,MAAM,MAAM,SAAS,GAAG,CAAC,IAAI,EAAE,GAAG,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAE7D,MAAM,MAAM,YAAY,GAAG,OAAO,GAAG,OAAO,GAAG,OAAO,GAAG,OAAO,GAAG,OAAO,CAAA;AAE1E,MAAM,WAAW,cAAe,SAAQ,IAAI;IAC1C;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB;AACD,MAAM,WAAW,IAAI;IACnB;;OAEG;IACH,GAAG,CAAC,EAAE,OAAO,CAAA;IACb;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC3B;;OAEG;IACH,YAAY,CAAC,EAAE,YAAY,CAAA;CAC5B;AAED;;;;;;;;GAQG;AACH,wBAAsB,OAAO,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,IAAI,GAAE,IAAS,mBAkElE;AAED;;;;;;GAMG;AACH,wBAA8B,eAAe,CAC3C,UAAU,EAAE,MAAM,EAAE,EACpB,WAAW,GAAE,cAAmB,iBAUjC"}
package/src/compile.js ADDED
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.compile = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const icu_messageformat_parser_1 = require("@formatjs/icu-messageformat-parser");
6
+ const fs_extra_1 = require("fs-extra");
7
+ const json_stable_stringify_1 = tslib_1.__importDefault(require("json-stable-stringify"));
8
+ const console_utils_1 = require("./console_utils");
9
+ const formatters_1 = require("./formatters");
10
+ const pseudo_locale_1 = require("./pseudo_locale");
11
+ /**
12
+ * Aggregate `inputFiles` into a single JSON blob and compile.
13
+ * Also checks for conflicting IDs.
14
+ * Then returns the serialized result as a `string` since key order
15
+ * makes a difference in some vendor.
16
+ * @param inputFiles Input files
17
+ * @param opts Options
18
+ * @returns serialized result in string format
19
+ */
20
+ async function compile(inputFiles, opts = {}) {
21
+ (0, console_utils_1.debug)('Compiling files:', inputFiles);
22
+ const { ast, format, pseudoLocale, skipErrors } = opts;
23
+ const formatter = await (0, formatters_1.resolveBuiltinFormatter)(format);
24
+ const messages = {};
25
+ const messageAsts = {};
26
+ const idsWithFileName = {};
27
+ const compiledFiles = await Promise.all(inputFiles.map(f => (0, fs_extra_1.readJSON)(f).then(formatter.compile)));
28
+ (0, console_utils_1.debug)('Compiled files:', compiledFiles);
29
+ for (let i = 0; i < inputFiles.length; i++) {
30
+ const inputFile = inputFiles[i];
31
+ (0, console_utils_1.debug)('Processing file:', inputFile);
32
+ const compiled = compiledFiles[i];
33
+ for (const id in compiled) {
34
+ if (messages[id] && messages[id] !== compiled[id]) {
35
+ throw new Error(`Conflicting ID "${id}" with different translation found in these 2 files:
36
+ ID: ${id}
37
+ Message from ${idsWithFileName[id]}: ${messages[id]}
38
+ Message from ${compiled[id]}: ${inputFile}
39
+ `);
40
+ }
41
+ try {
42
+ const msgAst = (0, icu_messageformat_parser_1.parse)(compiled[id]);
43
+ messages[id] = compiled[id];
44
+ switch (pseudoLocale) {
45
+ case 'xx-LS':
46
+ messageAsts[id] = (0, pseudo_locale_1.generateXXLS)(msgAst);
47
+ break;
48
+ case 'xx-AC':
49
+ messageAsts[id] = (0, pseudo_locale_1.generateXXAC)(msgAst);
50
+ break;
51
+ case 'xx-HA':
52
+ messageAsts[id] = (0, pseudo_locale_1.generateXXHA)(msgAst);
53
+ break;
54
+ case 'en-XA':
55
+ messageAsts[id] = (0, pseudo_locale_1.generateENXA)(msgAst);
56
+ break;
57
+ case 'en-XB':
58
+ messageAsts[id] = (0, pseudo_locale_1.generateENXB)(msgAst);
59
+ break;
60
+ default:
61
+ messageAsts[id] = msgAst;
62
+ break;
63
+ }
64
+ idsWithFileName[id] = inputFile;
65
+ }
66
+ catch (e) {
67
+ (0, console_utils_1.warn)('Error validating message "%s" with ID "%s" in file "%s"', compiled[id], id, inputFile);
68
+ if (!skipErrors) {
69
+ throw e;
70
+ }
71
+ }
72
+ }
73
+ }
74
+ return (0, json_stable_stringify_1.default)(ast ? messageAsts : messages, {
75
+ space: 2,
76
+ cmp: formatter.compareMessages || undefined,
77
+ });
78
+ }
79
+ exports.compile = compile;
80
+ /**
81
+ * Aggregate `inputFiles` into a single JSON blob and compile.
82
+ * Also checks for conflicting IDs and write output to `outFile`.
83
+ * @param inputFiles Input files
84
+ * @param compileOpts options
85
+ * @returns A `Promise` that resolves if file was written successfully
86
+ */
87
+ async function compileAndWrite(inputFiles, compileOpts = {}) {
88
+ const { outFile, ...opts } = compileOpts;
89
+ const serializedResult = await compile(inputFiles, opts);
90
+ if (outFile) {
91
+ (0, console_utils_1.debug)('Writing output file:', outFile);
92
+ return (0, fs_extra_1.outputFile)(outFile, serializedResult);
93
+ }
94
+ await (0, console_utils_1.writeStdout)(serializedResult);
95
+ await (0, console_utils_1.writeStdout)('\n');
96
+ }
97
+ exports.default = compileAndWrite;
@@ -0,0 +1,3 @@
1
+ import { Opts } from './compile';
2
+ export default function compileFolder(files: string[], outFolder: string, opts?: Opts): Promise<void[]>;
3
+ //# sourceMappingURL=compile_folder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compile_folder.d.ts","sourceRoot":"","sources":["compile_folder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,IAAI,EAAU,MAAM,WAAW,CAAA;AAGvC,wBAA8B,aAAa,CACzC,KAAK,EAAE,MAAM,EAAE,EACf,SAAS,EAAE,MAAM,EACjB,IAAI,GAAE,IAAS,mBAQhB"}
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const compile_1 = require("./compile");
4
+ const path_1 = require("path");
5
+ const fs_extra_1 = require("fs-extra");
6
+ async function compileFolder(files, outFolder, opts = {}) {
7
+ const results = await Promise.all(files.map(f => (0, compile_1.compile)([f], opts)));
8
+ const outFiles = files.map(f => (0, path_1.join)(outFolder, (0, path_1.basename)(f)));
9
+ return Promise.all(outFiles.map((outFile, i) => (0, fs_extra_1.outputFile)(outFile, results[i])));
10
+ }
11
+ exports.default = compileFolder;
@@ -0,0 +1,10 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ export declare const writeStderr: (arg1: string | Uint8Array) => Promise<void>;
4
+ export declare const writeStdout: (arg1: string | Uint8Array) => Promise<void>;
5
+ export declare function clearLine(terminal: typeof process['stderr']): Promise<void>;
6
+ export declare function debug(message: string, ...args: any[]): Promise<void>;
7
+ export declare function warn(message: string, ...args: any[]): Promise<void>;
8
+ export declare function error(message: string, ...args: any[]): Promise<void>;
9
+ export declare function getStdinAsString(): Promise<string>;
10
+ //# sourceMappingURL=console_utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"console_utils.d.ts","sourceRoot":"","sources":["console_utils.ts"],"names":[],"mappings":";;AAMA,eAAO,MAAM,WAAW,8CAAuD,CAAA;AAC/E,eAAO,MAAM,WAAW,8CAAuD,CAAA;AAO/E,wBAAsB,SAAS,CAAC,QAAQ,EAAE,OAAO,OAAO,CAAC,QAAQ,CAAC,iBAcjE;AAcD,wBAAsB,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,iBAO1D;AAED,wBAAsB,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,iBAIzD;AAED,wBAAsB,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,iBAI1D;AAED,wBAAgB,gBAAgB,IAAI,OAAO,CAAC,MAAM,CAAC,CAclD"}
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getStdinAsString = exports.error = exports.warn = exports.debug = exports.clearLine = exports.writeStdout = exports.writeStderr = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const chalk_1 = require("chalk");
6
+ const readline_1 = tslib_1.__importDefault(require("readline"));
7
+ const util_1 = require("util");
8
+ const CLEAR_WHOLE_LINE = 0;
9
+ exports.writeStderr = (0, util_1.promisify)(process.stderr.write).bind(process.stderr);
10
+ exports.writeStdout = (0, util_1.promisify)(process.stdout.write).bind(process.stdout);
11
+ const nativeClearLine = (0, util_1.promisify)(readline_1.default.clearLine).bind(readline_1.default);
12
+ const nativeCursorTo = (0, util_1.promisify)(readline_1.default.cursorTo).bind(readline_1.default);
13
+ // From:
14
+ // https://github.com/yarnpkg/yarn/blob/53d8004229f543f342833310d5af63a4b6e59c8a/src/reporters/console/util.js
15
+ async function clearLine(terminal) {
16
+ if (!chalk_1.supportsColor) {
17
+ if (terminal.isTTY) {
18
+ // terminal
19
+ if (terminal.columns > 0) {
20
+ await (0, exports.writeStderr)(`\r${' '.repeat(terminal.columns - 1)}`);
21
+ }
22
+ await (0, exports.writeStderr)(`\r`);
23
+ }
24
+ // ignore piping to file
25
+ }
26
+ else {
27
+ await nativeClearLine(terminal, CLEAR_WHOLE_LINE);
28
+ await nativeCursorTo(terminal, 0, undefined);
29
+ }
30
+ }
31
+ exports.clearLine = clearLine;
32
+ const LEVEL_COLORS = {
33
+ debug: chalk_1.green,
34
+ warn: chalk_1.yellow,
35
+ error: chalk_1.red,
36
+ };
37
+ function label(level, message) {
38
+ return `[@formatjs/cli] [${LEVEL_COLORS[level](level.toUpperCase())}] ${message}`;
39
+ }
40
+ async function debug(message, ...args) {
41
+ if (process.env.LOG_LEVEL !== 'debug') {
42
+ return;
43
+ }
44
+ await clearLine(process.stderr);
45
+ await (0, exports.writeStderr)((0, util_1.format)(label('debug', message), ...args));
46
+ await (0, exports.writeStderr)('\n');
47
+ }
48
+ exports.debug = debug;
49
+ async function warn(message, ...args) {
50
+ await clearLine(process.stderr);
51
+ await (0, exports.writeStderr)((0, util_1.format)(label('warn', message), ...args));
52
+ await (0, exports.writeStderr)('\n');
53
+ }
54
+ exports.warn = warn;
55
+ async function error(message, ...args) {
56
+ await clearLine(process.stderr);
57
+ await (0, exports.writeStderr)((0, util_1.format)(label('error', message), ...args));
58
+ await (0, exports.writeStderr)('\n');
59
+ }
60
+ exports.error = error;
61
+ function getStdinAsString() {
62
+ let result = '';
63
+ return new Promise(resolve => {
64
+ process.stdin.setEncoding('utf-8');
65
+ process.stdin.on('readable', () => {
66
+ let chunk;
67
+ while ((chunk = process.stdin.read())) {
68
+ result += chunk;
69
+ }
70
+ });
71
+ process.stdin.on('end', () => {
72
+ resolve(result);
73
+ });
74
+ });
75
+ }
76
+ exports.getStdinAsString = getStdinAsString;
@@ -0,0 +1,75 @@
1
+ import { Opts, MessageDescriptor } 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
+ * Path to a formatter file that controls the shape of JSON file from `outFile`.
53
+ */
54
+ format?: string | Formatter;
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>;
75
+ //# sourceMappingURL=extract.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extract.d.ts","sourceRoot":"","sources":["extract.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,IAAI,EACJ,iBAAiB,EAClB,MAAM,0BAA0B,CAAA;AAEjC,OAAO,EAA0B,SAAS,EAAC,MAAM,cAAc,CAAA;AAM/D,MAAM,WAAW,gBAAgB,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IAC1D;;OAEG;IACH,QAAQ,EAAE,iBAAiB,EAAE,CAAA;IAC7B;;OAEG;IACH,IAAI,CAAC,EAAE,CAAC,CAAA;CACT;AAED,MAAM,WAAW,0BAA2B,SAAQ,iBAAiB;IACnE;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,CAAA;IACb;;OAEG;IACH,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAC9B;AAED,MAAM,MAAM,iBAAiB,GAAG,IAAI,CAClC,WAAW,EACX,cAAc,GAAG,gBAAgB,GAAG,iBAAiB,CACtD,GAAG;IACF;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,EAAE,CAAA;CAClB,CAAA;AAED,MAAM,MAAM,WAAW,GAAG,IAAI,GAAG;IAC/B;;;OAGG;IACH,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB;;OAEG;IACH,sBAAsB,CAAC,EAAE,MAAM,CAAA;IAC/B;;OAEG;IACH,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC3B;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAA;CAClB,GAAG,IAAI,CAAC,IAAI,EAAE,gBAAgB,GAAG,iBAAiB,CAAC,CAAA;AAqFpD;;;;;;GAMG;AACH,wBAAsB,OAAO,CAC3B,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,WAAW,EAAE,WAAW,mBAmFzB;AAED;;;;;GAKG;AACH,wBAA8B,eAAe,CAC3C,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,WAAW,EAAE,iBAAiB,iBAS/B"}