@formatjs/cli-lib 5.0.4 → 5.0.7

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/BUILD +118 -0
  2. package/CHANGELOG.md +1097 -0
  3. package/LICENSE.md +0 -0
  4. package/README.md +0 -0
  5. package/index.ts +7 -0
  6. package/main.ts +5 -0
  7. package/package.json +61 -61
  8. package/src/cli.ts +240 -0
  9. package/src/compile.ts +141 -0
  10. package/src/compile_folder.ts +15 -0
  11. package/src/console_utils.ts +78 -0
  12. package/src/extract.ts +273 -0
  13. package/src/formatters/crowdin.ts +34 -0
  14. package/src/formatters/default.ts +19 -0
  15. package/src/formatters/index.ts +46 -0
  16. package/src/formatters/lokalise.ts +33 -0
  17. package/src/formatters/simple.ts +12 -0
  18. package/src/formatters/smartling.ts +73 -0
  19. package/src/formatters/transifex.ts +33 -0
  20. package/src/parse_script.ts +49 -0
  21. package/src/pseudo_locale.ts +113 -0
  22. package/src/vue_extractor.ts +96 -0
  23. package/tests/unit/__snapshots__/unit.test.ts.snap +42 -0
  24. package/tests/unit/__snapshots__/vue_extractor.test.ts.snap +36 -0
  25. package/tests/unit/fixtures/bind.vue +46 -0
  26. package/tests/unit/fixtures/comp.vue +17 -0
  27. package/tests/unit/unit.test.ts +44 -0
  28. package/tests/unit/vue_extractor.test.ts +38 -0
  29. package/tsconfig.json +5 -0
  30. package/index.d.ts +0 -8
  31. package/index.d.ts.map +0 -1
  32. package/index.js +0 -12
  33. package/main.d.ts +0 -2
  34. package/main.d.ts.map +0 -1
  35. package/main.js +0 -3
  36. package/src/cli.d.ts +0 -3
  37. package/src/cli.d.ts.map +0 -1
  38. package/src/cli.js +0 -142
  39. package/src/compile.d.ts +0 -48
  40. package/src/compile.d.ts.map +0 -1
  41. package/src/compile.js +0 -122
  42. package/src/compile_folder.d.ts +0 -3
  43. package/src/compile_folder.d.ts.map +0 -1
  44. package/src/compile_folder.js +0 -22
  45. package/src/console_utils.d.ts +0 -9
  46. package/src/console_utils.d.ts.map +0 -1
  47. package/src/console_utils.js +0 -141
  48. package/src/extract.d.ts +0 -75
  49. package/src/extract.d.ts.map +0 -1
  50. package/src/extract.js +0 -220
  51. package/src/formatters/crowdin.d.ts +0 -8
  52. package/src/formatters/crowdin.d.ts.map +0 -1
  53. package/src/formatters/crowdin.js +0 -29
  54. package/src/formatters/default.d.ts +0 -6
  55. package/src/formatters/default.d.ts.map +0 -1
  56. package/src/formatters/default.js +0 -13
  57. package/src/formatters/index.d.ts +0 -9
  58. package/src/formatters/index.d.ts.map +0 -1
  59. package/src/formatters/index.js +0 -45
  60. package/src/formatters/lokalise.d.ts +0 -10
  61. package/src/formatters/lokalise.d.ts.map +0 -1
  62. package/src/formatters/lokalise.js +0 -26
  63. package/src/formatters/simple.d.ts +0 -5
  64. package/src/formatters/simple.d.ts.map +0 -1
  65. package/src/formatters/simple.js +0 -12
  66. package/src/formatters/smartling.d.ts +0 -24
  67. package/src/formatters/smartling.d.ts.map +0 -1
  68. package/src/formatters/smartling.js +0 -52
  69. package/src/formatters/transifex.d.ts +0 -10
  70. package/src/formatters/transifex.d.ts.map +0 -1
  71. package/src/formatters/transifex.js +0 -26
  72. package/src/parse_script.d.ts +0 -8
  73. package/src/parse_script.d.ts.map +0 -1
  74. package/src/parse_script.js +0 -50
  75. package/src/pseudo_locale.d.ts +0 -7
  76. package/src/pseudo_locale.d.ts.map +0 -1
  77. package/src/pseudo_locale.js +0 -104
  78. package/src/vue_extractor.d.ts +0 -3
  79. package/src/vue_extractor.d.ts.map +0 -1
  80. package/src/vue_extractor.js +0 -62
@@ -0,0 +1,96 @@
1
+ import {parse} from '@vue/compiler-sfc'
2
+ import type {
3
+ TemplateChildNode,
4
+ SimpleExpressionNode,
5
+ ElementNode,
6
+ InterpolationNode,
7
+ CompoundExpressionNode,
8
+ DirectiveNode,
9
+ } from '@vue/compiler-core'
10
+ import {NodeTypes} from '@vue/compiler-core'
11
+
12
+ export type ScriptParseFn = (source: string) => void
13
+
14
+ function walk(
15
+ node: TemplateChildNode | CompoundExpressionNode['children'][0],
16
+ visitor: (
17
+ node:
18
+ | ElementNode
19
+ | InterpolationNode
20
+ | CompoundExpressionNode
21
+ | SimpleExpressionNode
22
+ ) => void
23
+ ) {
24
+ if (typeof node !== 'object') {
25
+ return
26
+ }
27
+ if (
28
+ node.type !== NodeTypes.ELEMENT &&
29
+ node.type !== NodeTypes.COMPOUND_EXPRESSION &&
30
+ node.type !== NodeTypes.INTERPOLATION
31
+ ) {
32
+ return
33
+ }
34
+ visitor(node)
35
+ if (node.type === NodeTypes.INTERPOLATION) {
36
+ visitor(node.content)
37
+ } else if (node.type === NodeTypes.ELEMENT) {
38
+ node.children.forEach(n => walk(n, visitor))
39
+ node.props
40
+ .filter(
41
+ (prop): prop is DirectiveNode => prop.type === NodeTypes.DIRECTIVE
42
+ )
43
+ .filter(prop => !!prop.exp)
44
+ .forEach(prop => visitor(prop.exp!))
45
+ } else {
46
+ node.children.forEach(n => walk(n, visitor))
47
+ }
48
+ }
49
+
50
+ function templateSimpleExpressionNodeVisitor(parseScriptFn: ScriptParseFn) {
51
+ return (
52
+ n:
53
+ | ElementNode
54
+ | CompoundExpressionNode
55
+ | CompoundExpressionNode['children'][0]
56
+ ) => {
57
+ if (typeof n !== 'object') {
58
+ return
59
+ }
60
+ if (n.type !== NodeTypes.SIMPLE_EXPRESSION) {
61
+ return
62
+ }
63
+
64
+ const {content} = n as SimpleExpressionNode
65
+ // Wrap this in () since a vue comp node attribute can just be
66
+ // an object literal which, by itself is invalid TS
67
+ // but with () it becomes an ExpressionStatement
68
+ parseScriptFn(`(${content})`)
69
+ }
70
+ }
71
+
72
+ export function parseFile(
73
+ source: string,
74
+ filename: string,
75
+ parseScriptFn: ScriptParseFn
76
+ ): any {
77
+ const {descriptor, errors} = parse(source, {
78
+ filename,
79
+ })
80
+ if (errors.length) {
81
+ throw errors[0]
82
+ }
83
+ const {script, scriptSetup, template} = descriptor
84
+
85
+ if (template) {
86
+ walk(template.ast, templateSimpleExpressionNodeVisitor(parseScriptFn))
87
+ }
88
+
89
+ if (script) {
90
+ parseScriptFn(script.content)
91
+ }
92
+
93
+ if (scriptSetup) {
94
+ parseScriptFn(scriptSetup.content)
95
+ }
96
+ }
@@ -0,0 +1,42 @@
1
+ // Jest Snapshot v1, https://goo.gl/fbAQLP
2
+
3
+ exports[`unit it passes camelCase-converted arguments to typescript API 1`] = `
4
+ Array [
5
+ Array [
6
+ ";",
7
+ Object {
8
+ "compilerOptions": Object {
9
+ "allowJs": true,
10
+ "experimentalDecorators": true,
11
+ "noEmit": true,
12
+ "target": 99,
13
+ },
14
+ "fileName": "file1.js",
15
+ "reportDiagnostics": true,
16
+ "transformers": Object {
17
+ "before": Array [
18
+ [Function],
19
+ ],
20
+ },
21
+ },
22
+ ],
23
+ Array [
24
+ ";",
25
+ Object {
26
+ "compilerOptions": Object {
27
+ "allowJs": true,
28
+ "experimentalDecorators": true,
29
+ "noEmit": true,
30
+ "target": 99,
31
+ },
32
+ "fileName": "file2.tsx",
33
+ "reportDiagnostics": true,
34
+ "transformers": Object {
35
+ "before": Array [
36
+ [Function],
37
+ ],
38
+ },
39
+ },
40
+ ],
41
+ ]
42
+ `;
@@ -0,0 +1,36 @@
1
+ // Jest Snapshot v1, https://goo.gl/fbAQLP
2
+
3
+ exports[`vue_extractor 1`] = `
4
+ Array [
5
+ Object {
6
+ "defaultMessage": "in template",
7
+ "description": "in template desc",
8
+ "id": "f6d14",
9
+ },
10
+ Object {
11
+ "defaultMessage": "in script",
12
+ "description": "in script desc",
13
+ "id": "1ebd4",
14
+ },
15
+ ]
16
+ `;
17
+
18
+ exports[`vue_extractor for bind attr 1`] = `
19
+ Array [
20
+ Object {
21
+ "defaultMessage": "Delete",
22
+ "description": "delete button text",
23
+ "id": "0705a",
24
+ },
25
+ Object {
26
+ "defaultMessage": "Send the item to the trash.",
27
+ "description": "delete button title",
28
+ "id": "5b09c",
29
+ },
30
+ Object {
31
+ "defaultMessage": "The item has been deleted.",
32
+ "description": "delete result message",
33
+ "id": "8fba7",
34
+ },
35
+ ]
36
+ `;
@@ -0,0 +1,46 @@
1
+ <template>
2
+ <p>
3
+ Hello!
4
+
5
+ <button
6
+ target="_blank"
7
+ :title="
8
+ $formatMessage({
9
+ description: 'delete button title',
10
+ defaultMessage: 'Send the item to the trash.',
11
+ })
12
+ "
13
+ :class="{
14
+ toggled: toggle,
15
+ }"
16
+ @click="
17
+ alert(
18
+ $formatMessage({
19
+ description: 'delete result message',
20
+ defaultMessage: 'The item has been deleted.',
21
+ })
22
+ )
23
+ "
24
+ >
25
+ {{
26
+ $formatMessage({
27
+ description: 'delete button text',
28
+ defaultMessage: 'Delete',
29
+ })
30
+ }}
31
+ </button>
32
+ </p>
33
+ </template>
34
+
35
+ <script lang="ts">
36
+ import {defineComponent} from 'vue'
37
+ export default defineComponent({
38
+ name: 'App',
39
+
40
+ setup() {
41
+ const toggle = true
42
+
43
+ return {toggle, alert: (text: any) => alert(text)}
44
+ },
45
+ })
46
+ </script>
@@ -0,0 +1,17 @@
1
+ <template>
2
+ <p>
3
+ {{
4
+ $formatMessage({
5
+ defaultMessage: 'in template',
6
+ description: 'in template desc',
7
+ })
8
+ }}
9
+ </p>
10
+ </template>
11
+
12
+ <script>
13
+ intl.formatMessage({
14
+ defaultMessage: 'in script',
15
+ description: 'in script desc',
16
+ })
17
+ </script>
@@ -0,0 +1,44 @@
1
+ import cliMain from '../../src/cli'
2
+ const glob = require('fast-glob')
3
+ const ts = require('typescript')
4
+ const transpileModule = jest.spyOn(ts, 'transpileModule')
5
+ // Commander.js will call this.
6
+ jest.spyOn(process, 'exit').mockImplementation((() => null) as any)
7
+ jest.spyOn(glob, 'sync').mockImplementation(p => (Array.isArray(p) ? p : [p]))
8
+
9
+ jest.mock('fs-extra', () => ({
10
+ outputJSONSync: () => Promise.resolve(),
11
+ readFile: () => Promise.resolve(';'),
12
+ }))
13
+
14
+ describe('unit', function () {
15
+ beforeEach(() => {
16
+ jest.clearAllMocks()
17
+ })
18
+
19
+ it('it passes camelCase-converted arguments to typescript API', async () => {
20
+ await cliMain([
21
+ 'node',
22
+ 'path/to/formatjs-cli',
23
+ 'extract',
24
+ '--extract-source-location',
25
+ '--remove-default-message',
26
+ '--throws',
27
+ '--additional-component-names',
28
+ 'Foo,Bar',
29
+ '--ignore=file3.ts',
30
+ 'file1.js',
31
+ 'file2.tsx',
32
+ ])
33
+
34
+ expect(transpileModule.mock.calls).toMatchSnapshot()
35
+ })
36
+
37
+ it('does not read from stdin when the glob pattern does NOT match anything', async () => {
38
+ // Does not match anything
39
+ jest.spyOn(glob, 'sync').mockImplementation(() => [])
40
+ // This should not hang
41
+ await cliMain(['node', 'path/to/formatjs-cli', 'extract', '*.doesnotexist'])
42
+ expect(transpileModule).not.toHaveBeenCalled()
43
+ }, 500) // 500ms timeout
44
+ })
@@ -0,0 +1,38 @@
1
+ import {MessageDescriptor} from '@formatjs/ts-transformer'
2
+ import {parseScript} from '../../src/parse_script'
3
+ import {parseFile} from '../../src/vue_extractor'
4
+ import {readFile} from 'fs-extra'
5
+ import {join} from 'path'
6
+ test('vue_extractor', async function () {
7
+ let messages: MessageDescriptor[] = []
8
+ const fixturePath = join(__dirname, './fixtures/comp.vue')
9
+ parseFile(
10
+ await readFile(fixturePath, 'utf8'),
11
+ fixturePath,
12
+ parseScript({
13
+ additionalFunctionNames: ['$formatMessage'],
14
+ onMsgExtracted(_, msgs) {
15
+ messages = messages.concat(msgs)
16
+ },
17
+ overrideIdFn: '[contenthash:5]',
18
+ })
19
+ )
20
+ expect(messages).toMatchSnapshot()
21
+ })
22
+
23
+ test('vue_extractor for bind attr', async function () {
24
+ let messages: MessageDescriptor[] = []
25
+ const fixturePath = join(__dirname, './fixtures/bind.vue')
26
+ parseFile(
27
+ await readFile(fixturePath, 'utf8'),
28
+ fixturePath,
29
+ parseScript({
30
+ additionalFunctionNames: ['$formatMessage'],
31
+ onMsgExtracted(_, msgs) {
32
+ messages = messages.concat(msgs)
33
+ },
34
+ overrideIdFn: '[contenthash:5]',
35
+ })
36
+ )
37
+ expect(messages).toMatchSnapshot()
38
+ })
package/tsconfig.json ADDED
@@ -0,0 +1,5 @@
1
+ // @generated
2
+ {
3
+ // This is purely for IDE, not for compilation
4
+ "extends": "../../tsconfig.json"
5
+ }
package/index.d.ts DELETED
@@ -1,8 +0,0 @@
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 DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../packages/cli-lib/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 DELETED
@@ -1,12 +0,0 @@
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 DELETED
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- //# sourceMappingURL=main.d.ts.map
package/main.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../../../../../packages/cli-lib/main.ts"],"names":[],"mappings":""}
package/main.js DELETED
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- 'use strict';
3
- require('./src/cli').default(process.argv);
package/src/cli.d.ts DELETED
@@ -1,3 +0,0 @@
1
- declare function main(argv: string[]): Promise<void>;
2
- export default main;
3
- //# sourceMappingURL=cli.d.ts.map
package/src/cli.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../../../../../../packages/cli-lib/src/cli.ts"],"names":[],"mappings":"AAWA,iBAAe,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,iBAmOjC;AACD,eAAe,IAAI,CAAA"}
package/src/cli.js DELETED
@@ -1,142 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- var tslib_1 = require("tslib");
4
- var commander_1 = require("commander");
5
- var loud_rejection_1 = (0, tslib_1.__importDefault)(require("loud-rejection"));
6
- var extract_1 = (0, tslib_1.__importDefault)(require("./extract"));
7
- var compile_1 = (0, tslib_1.__importDefault)(require("./compile"));
8
- var compile_folder_1 = (0, tslib_1.__importDefault)(require("./compile_folder"));
9
- var fast_glob_1 = require("fast-glob");
10
- var console_utils_1 = require("./console_utils");
11
- var package_json_1 = require("../package.json");
12
- var KNOWN_COMMANDS = ['extract'];
13
- function main(argv) {
14
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {
15
- var _this = this;
16
- return (0, tslib_1.__generator)(this, function (_a) {
17
- (0, loud_rejection_1.default)();
18
- commander_1.program
19
- .version(package_json_1.version, '-v, --version')
20
- .usage('<command> [flags]')
21
- .action(function (command) {
22
- if (!KNOWN_COMMANDS.includes(command)) {
23
- commander_1.program.help();
24
- }
25
- });
26
- commander_1.program
27
- .command('help', { isDefault: true })
28
- .description('Show this help message.')
29
- .action(function () { return commander_1.program.help(); });
30
- // Long text wrapping to available terminal columns: https://github.com/tj/commander.js/pull/956
31
- // NOTE: please keep the help text in sync with babel-plugin-formatjs documentation.
32
- commander_1.program
33
- .command('extract [files...]')
34
- .description("Extract string messages from React components that use react-intl.\nThe input language is expected to be TypeScript or ES2017 with JSX.")
35
- .option('--format <path>', "Path to a formatter file that controls the shape of JSON file from `--out-file`.\nThe formatter file must export a function called `format` with the signature\n```\ntype FormatFn = <T = Record<string, MessageDescriptor>>(\n msgs: Record<string, MessageDescriptor>\n) => T\n``` \nThis is especially useful to convert from our extracted format to a TMS-specific format.\n")
36
- .option('--out-file <path>', "The target file path where the plugin will output an aggregated \n`.json` file of all the translations from the `files` supplied.")
37
- .option('--id-interpolation-pattern <pattern>', "If certain message descriptors don't have id, this `pattern` will be used to automatically\ngenerate IDs for them. Default to `[sha512:contenthash:base64:6]` where `contenthash` is the hash of\n`defaultMessage` and `description`.\nSee https://github.com/webpack/loader-utils#interpolatename for sample patterns", '[sha512:contenthash:base64:6]')
38
- .option('--extract-source-location', "Whether the metadata about the location of the message in the source file should be \nextracted. If `true`, then `file`, `start`, and `end` fields will exist for each \nextracted message descriptors.", false)
39
- .option('--remove-default-message', 'Remove `defaultMessage` field in generated js after extraction', false)
40
- .option('--additional-component-names <comma-separated-names>', "Additional component names to extract messages from, e.g: `'FormattedFooBarMessage'`. \n**NOTE**: By default we check for the fact that `FormattedMessage` \nis imported from `moduleSourceName` to make sure variable alias \nworks. This option does not do that so it's less safe.", function (val) { return val.split(','); })
41
- .option('--additional-function-names <comma-separated-names>', "Additional function names to extract messages from, e.g: `'$t'`.", function (val) { return val.split(','); })
42
- .option('--ignore <files...>', 'List of glob paths to **not** extract translations from.')
43
- .option('--throws', 'Whether to throw an exception when we fail to process any file in the batch.')
44
- .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:\n\n ```\n // @intl-meta project:my-custom-project\n import {FormattedMessage} from 'react-intl';\n\n <FormattedMessage defaultMessage=\"foo\" id=\"bar\" />;\n ```\n\n 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.")
45
- .option('--preserve-whitespace', 'Whether to preserve whitespace and newlines.')
46
- .option('--flatten', "Whether to hoist selectors & flatten sentences as much as possible. E.g:\n\"I have {count, plural, one{a dog} other{many dogs}}\"\nbecomes \"{count, plural, one{I have a dog} other{I have many dogs}}\".\nThe goal is to provide as many full sentences as possible since fragmented\nsentences are not translator-friendly.")
47
- .action(function (filePatterns, cmdObj) { return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () {
48
- var files;
49
- return (0, tslib_1.__generator)(this, function (_a) {
50
- switch (_a.label) {
51
- case 0:
52
- (0, console_utils_1.debug)('File pattern:', filePatterns);
53
- (0, console_utils_1.debug)('Options:', cmdObj);
54
- files = (0, fast_glob_1.sync)(filePatterns, {
55
- ignore: cmdObj.ignore,
56
- });
57
- (0, console_utils_1.debug)('Files to extract:', files);
58
- return [4 /*yield*/, (0, extract_1.default)(files, {
59
- outFile: cmdObj.outFile,
60
- idInterpolationPattern: cmdObj.idInterpolationPattern || '[sha1:contenthash:base64:6]',
61
- extractSourceLocation: cmdObj.extractSourceLocation,
62
- removeDefaultMessage: cmdObj.removeDefaultMessage,
63
- additionalComponentNames: cmdObj.additionalComponentNames,
64
- additionalFunctionNames: cmdObj.additionalFunctionNames,
65
- throws: cmdObj.throws,
66
- pragma: cmdObj.pragma,
67
- format: cmdObj.format,
68
- // It is possible that the glob pattern does NOT match anything.
69
- // But so long as the glob pattern is provided, don't read from stdin.
70
- readFromStdin: filePatterns.length === 0,
71
- preserveWhitespace: cmdObj.preserveWhitespace,
72
- flatten: cmdObj.flatten,
73
- })];
74
- case 1:
75
- _a.sent();
76
- process.exit(0);
77
- return [2 /*return*/];
78
- }
79
- });
80
- }); });
81
- commander_1.program
82
- .command('compile [translation_files...]')
83
- .description("Compile extracted translation file into react-intl consumable JSON\nWe also verify that the messages are valid ICU and not malformed. \n<translation_files> can be a glob like \"foo/**/en.json\"")
84
- .option('--format <path>', "Path to a formatter file that converts `<translation_file>` to `Record<string, string>`\nso we can compile. The file must export a function named `compile` with the signature:\n```\ntype CompileFn = <T = Record<string, MessageDescriptor>>(\n msgs: T\n) => Record<string, string>;\n```\nThis is especially useful to convert from a TMS-specific format back to react-intl format\n")
85
- .option('--out-file <path>', "Compiled translation output file.\nIf this is not provided, result will be printed to stdout")
86
- .option('--ast', "Whether to compile to AST. See https://formatjs.io/docs/guides/advanced-usage#pre-parsing-messages\nfor more information")
87
- .option('--skip-errors', "Whether to continue compiling messages after encountering an error. Any keys with errors will not be included in the output file.")
88
- .option('--pseudo-locale <pseudoLocale>', "Whether to generate pseudo-locale files. See https://formatjs.io/docs/tooling/cli#--pseudo-locale-pseudolocale for possible values. \n\"--ast\" is required for this to work.")
89
- .action(function (filePatterns, opts) { return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () {
90
- var files;
91
- return (0, tslib_1.__generator)(this, function (_a) {
92
- switch (_a.label) {
93
- case 0:
94
- (0, console_utils_1.debug)('File pattern:', filePatterns);
95
- (0, console_utils_1.debug)('Options:', opts);
96
- files = (0, fast_glob_1.sync)(filePatterns);
97
- if (!files.length) {
98
- throw new Error("No input file found with pattern ".concat(filePatterns));
99
- }
100
- (0, console_utils_1.debug)('Files to compile:', files);
101
- return [4 /*yield*/, (0, compile_1.default)(files, opts)];
102
- case 1:
103
- _a.sent();
104
- return [2 /*return*/];
105
- }
106
- });
107
- }); });
108
- commander_1.program
109
- .command('compile-folder <folder> <outFolder>')
110
- .description("Batch compile all extracted translation JSON files in <folder> to <outFolder> containing\nreact-intl consumable JSON. We also verify that the messages are \nvalid ICU and not malformed.")
111
- .option('--format <path>', "Path to a formatter file that converts JSON files in `<folder>` to `Record<string, string>`\nso we can compile. The file must export a function named `compile` with the signature:\n```\ntype CompileFn = <T = Record<string, MessageDescriptor>>(\n msgs: T\n) => Record<string, string>;\n```\nThis is especially useful to convert from a TMS-specific format back to react-intl format\n")
112
- .option('--ast', "Whether to compile to AST. See https://formatjs.io/docs/guides/advanced-usage#pre-parsing-messages\nfor more information")
113
- .action(function (folder, outFolder, opts) { return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () {
114
- var files;
115
- return (0, tslib_1.__generator)(this, function (_a) {
116
- switch (_a.label) {
117
- case 0:
118
- (0, console_utils_1.debug)('Folder:', folder);
119
- (0, console_utils_1.debug)('Options:', opts);
120
- files = (0, fast_glob_1.sync)("".concat(folder, "/*.json"));
121
- if (!files.length) {
122
- throw new Error("No JSON file found in ".concat(folder));
123
- }
124
- (0, console_utils_1.debug)('Files to compile:', files);
125
- return [4 /*yield*/, (0, compile_folder_1.default)(files, outFolder, opts)];
126
- case 1:
127
- _a.sent();
128
- return [2 /*return*/];
129
- }
130
- });
131
- }); });
132
- if (argv.length < 3) {
133
- commander_1.program.help();
134
- }
135
- else {
136
- commander_1.program.parse(argv);
137
- }
138
- return [2 /*return*/];
139
- });
140
- });
141
- }
142
- exports.default = main;
package/src/compile.d.ts DELETED
@@ -1,48 +0,0 @@
1
- import { Formatter } from './formatters';
2
- export declare type CompileFn = (msgs: any) => Record<string, string>;
3
- export declare 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
@@ -1 +0,0 @@
1
- {"version":3,"file":"compile.d.ts","sourceRoot":"","sources":["../../../../../../packages/cli-lib/src/compile.ts"],"names":[],"mappings":"AAIA,OAAO,EAA0B,SAAS,EAAC,MAAM,cAAc,CAAA;AAS/D,oBAAY,SAAS,GAAG,CAAC,IAAI,EAAE,GAAG,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAE7D,oBAAY,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"}