@fgv/ts-res-cli 5.0.0-9 → 5.0.1-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/src/cli.ts DELETED
@@ -1,607 +0,0 @@
1
- /*
2
- * Copyright (c) 2025 Erik Fortune
3
- *
4
- * Permission is hereby granted, free of charge, to any person obtaining a copy
5
- * of this software and associated documentation files (the "Software"), to deal
6
- * in the Software without restriction, including without limitation the rights
7
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- * copies of the Software, and to permit persons to whom the Software is
9
- * furnished to do so, subject to the following conditions:
10
- *
11
- * The above copyright notice and this permission notice shall be included in all
12
- * copies or substantial portions of the Software.
13
- *
14
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
- * SOFTWARE.
21
- */
22
-
23
- import { Command } from 'commander';
24
- import { Result, succeed, fail } from '@fgv/ts-utils';
25
- import { ICompileOptions, OutputFormat } from './options';
26
- import * as TsRes from '@fgv/ts-res';
27
-
28
- /**
29
- * Command-line options for the compile command
30
- */
31
- interface ICompileCommandOptions {
32
- input: string;
33
- output: string;
34
- config?: string;
35
- context?: string;
36
- contextFilter?: string;
37
- qualifierDefaults?: string;
38
- format: string;
39
- debug?: boolean;
40
- verbose?: boolean;
41
- quiet?: boolean;
42
- validate?: boolean;
43
- includeMetadata?: boolean;
44
- resourceTypes?: string;
45
- maxDistance?: number;
46
- reduceQualifiers?: boolean;
47
- }
48
-
49
- /**
50
- * Command-line options for the validate command
51
- */
52
- interface IValidateCommandOptions {
53
- input: string;
54
- config?: string;
55
- context?: string;
56
- contextFilter?: string;
57
- qualifierDefaults?: string;
58
- verbose?: boolean;
59
- quiet?: boolean;
60
- reduceQualifiers?: boolean;
61
- }
62
-
63
- /**
64
- * Command-line options for the info command
65
- */
66
- interface IInfoCommandOptions {
67
- input: string;
68
- config?: string;
69
- context?: string;
70
- contextFilter?: string;
71
- qualifierDefaults?: string;
72
- resourceTypes?: string;
73
- maxDistance?: number;
74
- reduceQualifiers?: boolean;
75
- }
76
-
77
- /**
78
- * Command-line options for the config command
79
- */
80
- interface IConfigCommandOptions {
81
- name?: string;
82
- output?: string;
83
- validate?: string;
84
- normalize?: string;
85
- qualifierDefaults?: string;
86
- list?: boolean;
87
- }
88
-
89
- import { ResourceCompiler } from './compiler';
90
-
91
- /**
92
- * Main CLI class for ts-res-compile
93
- */
94
- export class TsResCliApp {
95
- private readonly _program: Command;
96
-
97
- public constructor() {
98
- this._program = new Command();
99
- this._setupCommands();
100
- }
101
-
102
- /**
103
- * Runs the CLI with the provided arguments
104
- */
105
- public async run(argv: string[]): Promise<void> {
106
- await this._program.parseAsync(argv);
107
- }
108
-
109
- /**
110
- * Sets up the CLI commands and options
111
- */
112
- private _setupCommands(): void {
113
- this._program
114
- .name('ts-res-compile')
115
- .description('Compile and optimize ts-res resources')
116
- .version('1.0.0');
117
-
118
- this._program
119
- .command('compile')
120
- .description('Compile resources from input to output format')
121
- .requiredOption('-i, --input <path>', 'Input file or directory path')
122
- .requiredOption('-o, --output <path>', 'Output file path')
123
- .option(
124
- '--config <name|path>',
125
- 'Predefined configuration name or system configuration file path (JSON, ISystemConfiguration format)'
126
- )
127
- .option('-c, --context <json>', 'Context filter for resources (JSON string)')
128
- .option(
129
- '--context-filter <token>',
130
- 'Context filter token (pipe-separated, e.g., "language=en-US|territory=US")'
131
- )
132
- .option(
133
- '--qualifier-defaults <token>',
134
- 'Qualifier default values token (pipe-separated, e.g., "language=en-US,en-CA|territory=US")'
135
- )
136
- .option('-f, --format <format>', 'Output format (compiled, source, js, ts, binary, bundle)', 'compiled')
137
- .option('--debug', 'Include debug information', false)
138
- .option('-v, --verbose', 'Verbose output', false)
139
- .option('-q, --quiet', 'Quiet output', false)
140
- .option('--validate', 'Validate resources during compilation', true)
141
- .option('--include-metadata', 'Include resource metadata in output', false)
142
- .option('--resource-types <types>', 'Resource type filter (comma-separated)')
143
- .option('--max-distance <number>', 'Maximum distance for language matching', parseInt)
144
- .option(
145
- '--reduce-qualifiers',
146
- 'Remove perfectly matching qualifier conditions from filtered resources',
147
- false
148
- )
149
- .action(async (options) => {
150
- await this._handleCompileCommand(options);
151
- });
152
-
153
- this._program
154
- .command('validate')
155
- .description('Validate resources without compilation')
156
- .requiredOption('-i, --input <path>', 'Input file or directory path')
157
- .option(
158
- '--config <name|path>',
159
- 'Predefined configuration name or system configuration file path (JSON, ISystemConfiguration format)'
160
- )
161
- .option('-c, --context <json>', 'Context filter for resources (JSON string)')
162
- .option(
163
- '--context-filter <token>',
164
- 'Context filter token (pipe-separated, e.g., "language=en-US|territory=US")'
165
- )
166
- .option(
167
- '--qualifier-defaults <token>',
168
- 'Qualifier default values token (pipe-separated, e.g., "language=en-US,en-CA|territory=US")'
169
- )
170
- .option('-v, --verbose', 'Verbose output', false)
171
- .option('-q, --quiet', 'Quiet output', false)
172
- .option(
173
- '--reduce-qualifiers',
174
- 'Remove perfectly matching qualifier conditions from filtered resources',
175
- false
176
- )
177
- .action(async (options) => {
178
- await this._handleValidateCommand(options);
179
- });
180
-
181
- this._program
182
- .command('info')
183
- .description('Show information about resources')
184
- .requiredOption('-i, --input <path>', 'Input file or directory path')
185
- .option(
186
- '--config <name|path>',
187
- 'Predefined configuration name or system configuration file path (JSON, ISystemConfiguration format)'
188
- )
189
- .option('-c, --context <json>', 'Context filter for resources (JSON string)')
190
- .option(
191
- '--context-filter <token>',
192
- 'Context filter token (pipe-separated, e.g., "language=en-US|territory=US")'
193
- )
194
- .option(
195
- '--qualifier-defaults <token>',
196
- 'Qualifier default values token (pipe-separated, e.g., "language=en-US,en-CA|territory=US")'
197
- )
198
- .option('--resource-types <types>', 'Resource type filter (comma-separated)')
199
- .option('--max-distance <number>', 'Maximum distance for language matching', parseInt)
200
- .option(
201
- '--reduce-qualifiers',
202
- 'Remove perfectly matching qualifier conditions from filtered resources',
203
- false
204
- )
205
- .action(async (options) => {
206
- await this._handleInfoCommand(options);
207
- });
208
-
209
- this._program
210
- .command('config')
211
- .description('Manage system configurations')
212
- .option('-n, --name <name>', 'Predefined configuration name to print')
213
- .option('-o, --output <path>', 'Output file path to save configuration')
214
- .option('--validate <path>', 'Validate a configuration file')
215
- .option('--normalize <path>', 'Normalize and validate a configuration file')
216
- .option(
217
- '--qualifier-defaults <token>',
218
- 'Qualifier default values token (pipe-separated, e.g., "language=en-US,en-CA|territory=US")'
219
- )
220
- .option('-l, --list', 'List all available predefined configurations')
221
- .action(async (options) => {
222
- await this._handleConfigCommand(options);
223
- });
224
- }
225
-
226
- /**
227
- * Handles the compile command
228
- */
229
- private async _handleCompileCommand(options: ICompileCommandOptions): Promise<void> {
230
- const compileOptions = this._parseCompileOptions(options);
231
- if (compileOptions.isFailure()) {
232
- console.error(`Error: ${compileOptions.message}`);
233
- process.exit(1);
234
- }
235
-
236
- const compiler = new ResourceCompiler(compileOptions.value);
237
- const result = await compiler.compile();
238
-
239
- if (result.isFailure()) {
240
- console.error(`Error: ${result.message}`);
241
- process.exit(1);
242
- }
243
-
244
- if (!options.quiet && options.output) {
245
- console.log(`Successfully compiled resources to ${options.output}`);
246
- }
247
- }
248
-
249
- /**
250
- * Handles the validate command
251
- */
252
- private async _handleValidateCommand(options: IValidateCommandOptions): Promise<void> {
253
- // Convert JSON context to contextFilter if provided
254
- let contextFilter = options.contextFilter;
255
- if (options.context && !contextFilter) {
256
- try {
257
- const contextObj = JSON.parse(options.context);
258
- const tokens: string[] = [];
259
- for (const [key, value] of Object.entries(contextObj)) {
260
- tokens.push(`${key}=${value}`);
261
- }
262
- contextFilter = tokens.join('|');
263
- } catch (error) {
264
- console.error(`Error: Invalid context JSON: ${error}`);
265
- process.exit(1);
266
- }
267
- }
268
-
269
- const validateOptions: ICompileOptions = {
270
- input: options.input,
271
- output: '', // Not used for validation
272
- config: options.config,
273
- contextFilter,
274
- qualifierDefaults: options.qualifierDefaults,
275
- format: 'compiled',
276
- debug: false,
277
- verbose: options.verbose || false,
278
- quiet: options.quiet || false,
279
- validate: true,
280
- includeMetadata: false,
281
- reduceQualifiers: options.reduceQualifiers || false
282
- };
283
-
284
- const compiler = new ResourceCompiler(validateOptions);
285
- const result = await compiler.validate();
286
-
287
- if (result.isFailure()) {
288
- console.error(`Validation failed: ${result.message}`);
289
- process.exit(1);
290
- }
291
-
292
- if (!options.quiet) {
293
- console.log('Resources validated successfully');
294
- }
295
- }
296
-
297
- /**
298
- * Handles the info command
299
- */
300
- private async _handleInfoCommand(options: IInfoCommandOptions): Promise<void> {
301
- // Convert JSON context to contextFilter if provided
302
- let contextFilter = options.contextFilter;
303
- if (options.context && !contextFilter) {
304
- try {
305
- const contextObj = JSON.parse(options.context);
306
- const tokens: string[] = [];
307
- for (const [key, value] of Object.entries(contextObj)) {
308
- tokens.push(`${key}=${value}`);
309
- }
310
- contextFilter = tokens.join('|');
311
- } catch (error) {
312
- console.error(`Error: Invalid context JSON: ${error}`);
313
- process.exit(1);
314
- }
315
- }
316
-
317
- const infoOptions: ICompileOptions = {
318
- input: options.input,
319
- output: '', // Not used for info
320
- config: options.config,
321
- format: 'compiled',
322
- debug: false,
323
- verbose: false,
324
- quiet: false,
325
- validate: false,
326
- includeMetadata: true,
327
- contextFilter,
328
- qualifierDefaults: options.qualifierDefaults,
329
- resourceTypes: options.resourceTypes,
330
- maxDistance: options.maxDistance,
331
- reduceQualifiers: options.reduceQualifiers || false
332
- };
333
-
334
- const compiler = new ResourceCompiler(infoOptions);
335
- const result = await compiler.getInfo();
336
-
337
- if (result.isFailure()) {
338
- console.error(`Error: ${result.message}`);
339
- process.exit(1);
340
- }
341
-
342
- console.log(JSON.stringify(result.value, null, 2));
343
- }
344
-
345
- /**
346
- * Handles the config command
347
- */
348
- private async _handleConfigCommand(options: IConfigCommandOptions): Promise<void> {
349
- try {
350
- // List all predefined configurations
351
- if (options.list) {
352
- console.log('Available predefined configurations:');
353
- console.log('- default');
354
- console.log('- language-priority');
355
- console.log('- territory-priority');
356
- console.log('- extended-example');
357
- return;
358
- }
359
-
360
- // Print a specific predefined configuration
361
- if (options.name) {
362
- const predefinedNames: TsRes.Config.PredefinedSystemConfiguration[] = [
363
- 'default',
364
- 'language-priority',
365
- 'territory-priority',
366
- 'extended-example'
367
- ];
368
-
369
- if (!predefinedNames.includes(options.name as TsRes.Config.PredefinedSystemConfiguration)) {
370
- console.error(`Error: Predefined configuration '${options.name}' not found`);
371
- console.error(
372
- 'Available configurations: default, language-priority, territory-priority, extended-example'
373
- );
374
- process.exit(1);
375
- }
376
-
377
- const configResult = TsRes.Config.getPredefinedDeclaration(
378
- options.name as TsRes.Config.PredefinedSystemConfiguration
379
- );
380
- if (configResult.isFailure()) {
381
- console.error(
382
- `Error: Failed to load predefined configuration '${options.name}': ${configResult.message}`
383
- );
384
- process.exit(1);
385
- }
386
-
387
- let config = configResult.value;
388
-
389
- // Apply qualifier defaults if provided
390
- if (options.qualifierDefaults) {
391
- const tempSystemConfigResult = TsRes.Config.SystemConfiguration.create(config);
392
- if (tempSystemConfigResult.isFailure()) {
393
- console.error(`Error: Failed to create system configuration: ${tempSystemConfigResult.message}`);
394
- process.exit(1);
395
- }
396
-
397
- const tokens = new TsRes.Qualifiers.QualifierDefaultValueTokens(
398
- tempSystemConfigResult.value.qualifiers
399
- );
400
- const defaultsResult = tokens.qualifierDefaultValuesTokenToDecl(options.qualifierDefaults);
401
- if (defaultsResult.isFailure()) {
402
- console.error(`Error: Failed to parse qualifier defaults: ${defaultsResult.message}`);
403
- process.exit(1);
404
- }
405
-
406
- const updatedConfigResult = TsRes.Config.updateSystemConfigurationQualifierDefaultValues(
407
- config,
408
- defaultsResult.value
409
- );
410
- if (updatedConfigResult.isFailure()) {
411
- console.error(`Error: Failed to apply qualifier defaults: ${updatedConfigResult.message}`);
412
- process.exit(1);
413
- }
414
-
415
- config = updatedConfigResult.value;
416
- }
417
-
418
- const output = JSON.stringify(config, null, 2);
419
-
420
- if (options.output) {
421
- const fs = await import('fs').then((m) => m.promises);
422
- const path = await import('path');
423
- const outputPath = path.resolve(options.output);
424
- const outputDir = path.dirname(outputPath);
425
-
426
- await fs.mkdir(outputDir, { recursive: true });
427
- await fs.writeFile(outputPath, output, 'utf-8');
428
- console.log(`Configuration saved to: ${outputPath}`);
429
- } else {
430
- console.log(output);
431
- }
432
- return;
433
- }
434
-
435
- // Validate a configuration file
436
- if (options.validate) {
437
- const fs = await import('fs').then((m) => m.promises);
438
- const path = await import('path');
439
-
440
- const configPath = path.resolve(options.validate);
441
- const configContent = await fs.readFile(configPath, 'utf-8');
442
- const configData = JSON.parse(configContent);
443
-
444
- const configResult = TsRes.Config.Convert.systemConfiguration.convert(configData);
445
- if (configResult.isFailure()) {
446
- console.error(`Validation failed: ${configResult.message}`);
447
- process.exit(1);
448
- }
449
-
450
- console.log(`Configuration file '${configPath}' is valid`);
451
- return;
452
- }
453
-
454
- // Normalize a configuration file
455
- if (options.normalize) {
456
- const fs = await import('fs').then((m) => m.promises);
457
- const path = await import('path');
458
-
459
- const configPath = path.resolve(options.normalize);
460
- const configContent = await fs.readFile(configPath, 'utf-8');
461
- const configData = JSON.parse(configContent);
462
-
463
- const configResult = TsRes.Config.Convert.systemConfiguration.convert(configData);
464
- if (configResult.isFailure()) {
465
- console.error(`Normalization failed: ${configResult.message}`);
466
- process.exit(1);
467
- }
468
-
469
- let normalizedConfig = configResult.value;
470
-
471
- // Apply qualifier defaults if provided
472
- if (options.qualifierDefaults) {
473
- const tempSystemConfigResult = TsRes.Config.SystemConfiguration.create(normalizedConfig);
474
- if (tempSystemConfigResult.isFailure()) {
475
- console.error(`Error: Failed to create system configuration: ${tempSystemConfigResult.message}`);
476
- process.exit(1);
477
- }
478
-
479
- const tokens = new TsRes.Qualifiers.QualifierDefaultValueTokens(
480
- tempSystemConfigResult.value.qualifiers
481
- );
482
- const defaultsResult = tokens.qualifierDefaultValuesTokenToDecl(options.qualifierDefaults);
483
- if (defaultsResult.isFailure()) {
484
- console.error(`Error: Failed to parse qualifier defaults: ${defaultsResult.message}`);
485
- process.exit(1);
486
- }
487
-
488
- const updatedConfigResult = TsRes.Config.updateSystemConfigurationQualifierDefaultValues(
489
- normalizedConfig,
490
- defaultsResult.value
491
- );
492
- if (updatedConfigResult.isFailure()) {
493
- console.error(`Error: Failed to apply qualifier defaults: ${updatedConfigResult.message}`);
494
- process.exit(1);
495
- }
496
-
497
- normalizedConfig = updatedConfigResult.value;
498
- }
499
-
500
- const output = JSON.stringify(normalizedConfig, null, 2);
501
-
502
- if (options.output) {
503
- const outputPath = path.resolve(options.output);
504
- const outputDir = path.dirname(outputPath);
505
-
506
- await fs.mkdir(outputDir, { recursive: true });
507
- await fs.writeFile(outputPath, output, 'utf-8');
508
- console.log(`Normalized configuration saved to: ${outputPath}`);
509
- } else {
510
- console.log(output);
511
- }
512
- return;
513
- }
514
-
515
- // If no specific action, print default configuration
516
- const defaultResult = TsRes.Config.getPredefinedDeclaration('default');
517
- if (defaultResult.isFailure()) {
518
- console.error(`Error: Default configuration not available`);
519
- process.exit(1);
520
- }
521
-
522
- let defaultConfig = defaultResult.value;
523
-
524
- // Apply qualifier defaults if provided
525
- if (options.qualifierDefaults) {
526
- const tempSystemConfigResult = TsRes.Config.SystemConfiguration.create(defaultConfig);
527
- if (tempSystemConfigResult.isFailure()) {
528
- console.error(`Error: Failed to create system configuration: ${tempSystemConfigResult.message}`);
529
- process.exit(1);
530
- }
531
-
532
- const tokens = new TsRes.Qualifiers.QualifierDefaultValueTokens(
533
- tempSystemConfigResult.value.qualifiers
534
- );
535
- const defaultsResult = tokens.qualifierDefaultValuesTokenToDecl(options.qualifierDefaults);
536
- if (defaultsResult.isFailure()) {
537
- console.error(`Error: Failed to parse qualifier defaults: ${defaultsResult.message}`);
538
- process.exit(1);
539
- }
540
-
541
- const updatedConfigResult = TsRes.Config.updateSystemConfigurationQualifierDefaultValues(
542
- defaultConfig,
543
- defaultsResult.value
544
- );
545
- if (updatedConfigResult.isFailure()) {
546
- console.error(`Error: Failed to apply qualifier defaults: ${updatedConfigResult.message}`);
547
- process.exit(1);
548
- }
549
-
550
- defaultConfig = updatedConfigResult.value;
551
- }
552
-
553
- console.log(JSON.stringify(defaultConfig, null, 2));
554
- } catch (error) {
555
- console.error(`Error: ${error}`);
556
- process.exit(1);
557
- }
558
- }
559
-
560
- /**
561
- * Parses and validates compile options
562
- */
563
- private _parseCompileOptions(options: ICompileCommandOptions): Result<ICompileOptions> {
564
- try {
565
- const format = options.format as OutputFormat;
566
- if (!['compiled', 'source', 'js', 'ts', 'binary', 'bundle'].includes(format)) {
567
- return fail(`Invalid format: ${format}`);
568
- }
569
-
570
- // Convert JSON context to contextFilter if provided
571
- let contextFilter = options.contextFilter;
572
- if (options.context && !contextFilter) {
573
- try {
574
- const contextObj = JSON.parse(options.context);
575
- const tokens: string[] = [];
576
- for (const [key, value] of Object.entries(contextObj)) {
577
- tokens.push(`${key}=${value}`);
578
- }
579
- contextFilter = tokens.join('|');
580
- } catch (error) {
581
- return fail(`Invalid context JSON: ${error}`);
582
- }
583
- }
584
-
585
- const compileOptions: ICompileOptions = {
586
- input: options.input,
587
- output: options.output,
588
- config: options.config,
589
- contextFilter,
590
- qualifierDefaults: options.qualifierDefaults,
591
- format,
592
- debug: options.debug || false,
593
- verbose: options.verbose || false,
594
- quiet: options.quiet || false,
595
- validate: options.validate !== false,
596
- includeMetadata: options.includeMetadata || false,
597
- resourceTypes: options.resourceTypes,
598
- maxDistance: options.maxDistance,
599
- reduceQualifiers: options.reduceQualifiers || false
600
- };
601
-
602
- return succeed(compileOptions);
603
- } catch (error) {
604
- return fail(`Failed to parse options: ${error}`);
605
- }
606
- }
607
- }