@fgv/ts-res-browser-cli 5.0.0-22 → 5.0.0-24

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fgv/ts-res-browser-cli",
3
- "version": "5.0.0-22",
3
+ "version": "5.0.0-24",
4
4
  "description": "Command-line interface to launch ts-res-browser with specified options",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",
@@ -22,21 +22,21 @@
22
22
  },
23
23
  "dependencies": {
24
24
  "commander": "^11.0.0",
25
- "@fgv/ts-res": "5.0.0-22",
26
- "@fgv/ts-utils": "5.0.0-22",
27
- "@fgv/ts-json": "5.0.0-22",
28
- "@fgv/ts-json-base": "5.0.0-22",
29
- "@fgv/ts-res-browser": "5.0.0-22"
25
+ "@fgv/ts-res": "5.0.0-24",
26
+ "@fgv/ts-utils": "5.0.0-24",
27
+ "@fgv/ts-json": "5.0.0-24",
28
+ "@fgv/ts-json-base": "5.0.0-24",
29
+ "@fgv/ts-res-browser": "5.0.0-24"
30
30
  },
31
31
  "devDependencies": {
32
- "@rushstack/heft": "~0.74.2",
33
- "@rushstack/heft-node-rig": "~2.9.3",
32
+ "@rushstack/heft": "0.74.3",
33
+ "@rushstack/heft-node-rig": "2.9.4",
34
34
  "@types/jest": "^29.5.14",
35
35
  "@types/node": "^20.14.9",
36
36
  "eslint": "^8.57.0",
37
37
  "jest": "^29.7.0",
38
- "typescript": "^5.8.3",
39
- "@fgv/ts-utils-jest": "5.0.0-22"
38
+ "typescript": "5.8.3",
39
+ "@fgv/ts-utils-jest": "5.0.0-24"
40
40
  },
41
41
  "scripts": {
42
42
  "build": "heft build --clean",
package/src/cli.ts DELETED
@@ -1,420 +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 * as TsRes from '@fgv/ts-res';
26
- import { promises as fs } from 'fs';
27
- import * as path from 'path';
28
-
29
- import { IBrowseOptions, IBrowseCommandOptions } from './options';
30
- import { SimpleBrowserLauncher } from './simpleBrowserLauncher';
31
-
32
- /**
33
- * Main CLI class for ts-res-browser-cli
34
- */
35
- export class TsResBrowserCliApp {
36
- private readonly _program: Command;
37
- private readonly _launcher: SimpleBrowserLauncher;
38
-
39
- public constructor() {
40
- this._program = new Command();
41
- this._launcher = new SimpleBrowserLauncher();
42
- this._setupCommands();
43
- }
44
-
45
- /**
46
- * Runs the CLI with the provided arguments
47
- */
48
- public async run(argv: string[]): Promise<void> {
49
- await this._program.parseAsync(argv);
50
- }
51
-
52
- /**
53
- * Sets up the CLI commands and options
54
- */
55
- private _setupCommands(): void {
56
- this._program
57
- .name('ts-res-browser-cli')
58
- .description('Launch ts-res-browser with specified resources and configuration')
59
- .version('1.0.0');
60
-
61
- // Default behavior (no command) - launch with options or show help
62
- this._program
63
- .option('-i, --input <path>', 'Input file or directory path')
64
- .option(
65
- '--config <name|path>',
66
- 'Predefined configuration name or system configuration file path (JSON, ISystemConfiguration format)'
67
- )
68
- .option('-c, --context <json>', 'Context filter for resources (JSON string)')
69
- .option(
70
- '--context-filter <token>',
71
- 'Context filter token (pipe-separated, e.g., "language=en-US|territory=US")'
72
- )
73
- .option(
74
- '--qualifier-defaults <token>',
75
- 'Qualifier default values token (pipe-separated, e.g., "language=en-US,en-CA|territory=US")'
76
- )
77
- .option('--resource-types <types>', 'Resource type filter (comma-separated)')
78
- .option('--max-distance <number>', 'Maximum distance for language matching', parseInt)
79
- .option(
80
- '--reduce-qualifiers',
81
- 'Remove perfectly matching qualifier conditions from filtered resources',
82
- false
83
- )
84
- .option('-v, --verbose', 'Verbose output', false)
85
- .option('-q, --quiet', 'Quiet output', false)
86
- .option('-p, --port <number>', 'Port for local browser instance', parseInt)
87
- .option('--url <url>', 'URL of remote browser instance')
88
- .option('--no-open', 'Do not open browser automatically')
89
- .option('--interactive', 'Launch in interactive mode with sample data', false)
90
- .option('--dev', 'Automatically start development server locally', false)
91
- .option(
92
- '--serve',
93
- 'Start server (dev in monorepo, serve in published packages) and connect automatically',
94
- false
95
- )
96
- .action(async (options) => {
97
- // If no options provided, show help
98
- if (!this._hasOptions(options)) {
99
- this._program.help();
100
- } else {
101
- await this._handleBrowseCommand(options);
102
- }
103
- });
104
-
105
- // Browse command (explicit)
106
- this._program
107
- .command('browse')
108
- .description('Launch browser with specified resources and configuration')
109
- .option('-i, --input <path>', 'Input file or directory path')
110
- .option(
111
- '--config <name|path>',
112
- 'Predefined configuration name or system configuration file path (JSON, ISystemConfiguration format)'
113
- )
114
- .option('-c, --context <json>', 'Context filter for resources (JSON string)')
115
- .option(
116
- '--context-filter <token>',
117
- 'Context filter token (pipe-separated, e.g., "language=en-US|territory=US")'
118
- )
119
- .option(
120
- '--qualifier-defaults <token>',
121
- 'Qualifier default values token (pipe-separated, e.g., "language=en-US,en-CA|territory=US")'
122
- )
123
- .option('--resource-types <types>', 'Resource type filter (comma-separated)')
124
- .option('--max-distance <number>', 'Maximum distance for language matching', parseInt)
125
- .option(
126
- '--reduce-qualifiers',
127
- 'Remove perfectly matching qualifier conditions from filtered resources',
128
- false
129
- )
130
- .option('-v, --verbose', 'Verbose output', false)
131
- .option('-q, --quiet', 'Quiet output', false)
132
- .option('-p, --port <number>', 'Port for local browser instance', parseInt)
133
- .option('--url <url>', 'URL of remote browser instance')
134
- .option('--no-open', 'Do not open browser automatically')
135
- .option('--interactive', 'Launch in interactive mode with sample data', false)
136
- .option('--dev', 'Automatically start development server locally', false)
137
- .option(
138
- '--serve',
139
- 'Start server (dev in monorepo, serve in published packages) and connect automatically',
140
- false
141
- )
142
- .action(async (options) => {
143
- await this._handleBrowseCommand(options);
144
- });
145
-
146
- // Config command (similar to ts-res-cli)
147
- this._program
148
- .command('config')
149
- .description('Manage system configurations')
150
- .option('-n, --name <name>', 'Predefined configuration name to print')
151
- .option('-o, --output <path>', 'Output file path to save configuration')
152
- .option('--validate <path>', 'Validate a configuration file')
153
- .option('--normalize <path>', 'Normalize and validate a configuration file')
154
- .option(
155
- '--qualifier-defaults <token>',
156
- 'Qualifier default values token (pipe-separated, e.g., "language=en-US,en-CA|territory=US")'
157
- )
158
- .option('-l, --list', 'List all available predefined configurations')
159
- .action(async (options) => {
160
- await this._handleConfigCommand(options);
161
- });
162
- }
163
-
164
- /**
165
- * Check if any meaningful options were provided
166
- */
167
- private _hasOptions(options: IBrowseCommandOptions): boolean {
168
- return !!(
169
- options.input ||
170
- options.config ||
171
- options.context ||
172
- options.contextFilter ||
173
- options.qualifierDefaults ||
174
- options.resourceTypes ||
175
- options.maxDistance !== undefined ||
176
- options.reduceQualifiers ||
177
- options.interactive ||
178
- options.url ||
179
- options.dev ||
180
- options.serve
181
- );
182
- }
183
-
184
- /**
185
- * Handles the browse command
186
- */
187
- private async _handleBrowseCommand(options: IBrowseCommandOptions): Promise<void> {
188
- const browseOptions = this._parseBrowseOptions(options);
189
- if (browseOptions.isFailure()) {
190
- console.error(`Error: ${browseOptions.message}`);
191
- process.exit(1);
192
- }
193
-
194
- const result = await this._launcher.launch(browseOptions.value);
195
- if (result.isFailure()) {
196
- console.error(`Error: ${result.message}`);
197
- process.exit(1);
198
- }
199
- }
200
-
201
- /**
202
- * Handles the config command (similar to ts-res-cli)
203
- */
204
- private async _handleConfigCommand(options: any): Promise<void> {
205
- try {
206
- // List all predefined configurations
207
- if (options.list) {
208
- console.log('Available predefined configurations:');
209
- console.log('- default');
210
- console.log('- language-priority');
211
- console.log('- territory-priority');
212
- console.log('- extended-example');
213
- return;
214
- }
215
-
216
- // Print a specific predefined configuration
217
- if (options.name) {
218
- const predefinedNames: TsRes.Config.PredefinedSystemConfiguration[] = [
219
- 'default',
220
- 'language-priority',
221
- 'territory-priority',
222
- 'extended-example'
223
- ];
224
-
225
- if (!predefinedNames.includes(options.name as TsRes.Config.PredefinedSystemConfiguration)) {
226
- console.error(`Error: Predefined configuration '${options.name}' not found`);
227
- console.error(
228
- 'Available configurations: default, language-priority, territory-priority, extended-example'
229
- );
230
- process.exit(1);
231
- }
232
-
233
- const configResult = TsRes.Config.getPredefinedDeclaration(
234
- options.name as TsRes.Config.PredefinedSystemConfiguration
235
- );
236
- if (configResult.isFailure()) {
237
- console.error(
238
- `Error: Failed to load predefined configuration '${options.name}': ${configResult.message}`
239
- );
240
- process.exit(1);
241
- }
242
-
243
- let config = configResult.value;
244
-
245
- // Apply qualifier defaults if provided
246
- if (options.qualifierDefaults) {
247
- const tempSystemConfigResult = TsRes.Config.SystemConfiguration.create(config);
248
- if (tempSystemConfigResult.isFailure()) {
249
- console.error(`Error: Failed to create system configuration: ${tempSystemConfigResult.message}`);
250
- process.exit(1);
251
- }
252
-
253
- const tokens = new TsRes.Qualifiers.QualifierDefaultValueTokens(
254
- tempSystemConfigResult.value.qualifiers
255
- );
256
- const defaultsResult = tokens.qualifierDefaultValuesTokenToDecl(options.qualifierDefaults);
257
- if (defaultsResult.isFailure()) {
258
- console.error(`Error: Failed to parse qualifier defaults: ${defaultsResult.message}`);
259
- process.exit(1);
260
- }
261
-
262
- const updatedConfigResult = TsRes.Config.updateSystemConfigurationQualifierDefaultValues(
263
- config,
264
- defaultsResult.value
265
- );
266
- if (updatedConfigResult.isFailure()) {
267
- console.error(`Error: Failed to apply qualifier defaults: ${updatedConfigResult.message}`);
268
- process.exit(1);
269
- }
270
-
271
- config = updatedConfigResult.value;
272
- }
273
-
274
- const output = JSON.stringify(config, null, 2);
275
-
276
- if (options.output) {
277
- const outputPath = path.resolve(options.output);
278
- const outputDir = path.dirname(outputPath);
279
-
280
- await fs.mkdir(outputDir, { recursive: true });
281
- await fs.writeFile(outputPath, output, 'utf-8');
282
- console.log(`Configuration saved to: ${outputPath}`);
283
- } else {
284
- console.log(output);
285
- }
286
- return;
287
- }
288
-
289
- // Validate a configuration file
290
- if (options.validate) {
291
- const configPath = path.resolve(options.validate);
292
- const configContent = await fs.readFile(configPath, 'utf-8');
293
- const configData = JSON.parse(configContent);
294
-
295
- const configResult = TsRes.Config.Convert.systemConfiguration.convert(configData);
296
- if (configResult.isFailure()) {
297
- console.error(`Validation failed: ${configResult.message}`);
298
- process.exit(1);
299
- }
300
-
301
- console.log(`Configuration file '${configPath}' is valid`);
302
- return;
303
- }
304
-
305
- // Normalize a configuration file
306
- if (options.normalize) {
307
- const configPath = path.resolve(options.normalize);
308
- const configContent = await fs.readFile(configPath, 'utf-8');
309
- const configData = JSON.parse(configContent);
310
-
311
- const configResult = TsRes.Config.Convert.systemConfiguration.convert(configData);
312
- if (configResult.isFailure()) {
313
- console.error(`Normalization failed: ${configResult.message}`);
314
- process.exit(1);
315
- }
316
-
317
- let normalizedConfig = configResult.value;
318
-
319
- // Apply qualifier defaults if provided
320
- if (options.qualifierDefaults) {
321
- const tempSystemConfigResult = TsRes.Config.SystemConfiguration.create(normalizedConfig);
322
- if (tempSystemConfigResult.isFailure()) {
323
- console.error(`Error: Failed to create system configuration: ${tempSystemConfigResult.message}`);
324
- process.exit(1);
325
- }
326
-
327
- const tokens = new TsRes.Qualifiers.QualifierDefaultValueTokens(
328
- tempSystemConfigResult.value.qualifiers
329
- );
330
- const defaultsResult = tokens.qualifierDefaultValuesTokenToDecl(options.qualifierDefaults);
331
- if (defaultsResult.isFailure()) {
332
- console.error(`Error: Failed to parse qualifier defaults: ${defaultsResult.message}`);
333
- process.exit(1);
334
- }
335
-
336
- const updatedConfigResult = TsRes.Config.updateSystemConfigurationQualifierDefaultValues(
337
- normalizedConfig,
338
- defaultsResult.value
339
- );
340
- if (updatedConfigResult.isFailure()) {
341
- console.error(`Error: Failed to apply qualifier defaults: ${updatedConfigResult.message}`);
342
- process.exit(1);
343
- }
344
-
345
- normalizedConfig = updatedConfigResult.value;
346
- }
347
-
348
- const output = JSON.stringify(normalizedConfig, null, 2);
349
-
350
- if (options.output) {
351
- const outputPath = path.resolve(options.output);
352
- const outputDir = path.dirname(outputPath);
353
-
354
- await fs.mkdir(outputDir, { recursive: true });
355
- await fs.writeFile(outputPath, output, 'utf-8');
356
- console.log(`Normalized configuration saved to: ${outputPath}`);
357
- } else {
358
- console.log(output);
359
- }
360
- return;
361
- }
362
-
363
- // If no specific action, print default configuration
364
- const defaultResult = TsRes.Config.getPredefinedDeclaration('default');
365
- if (defaultResult.isFailure()) {
366
- console.error(`Error: Default configuration not available`);
367
- process.exit(1);
368
- }
369
-
370
- console.log(JSON.stringify(defaultResult.value, null, 2));
371
- } catch (error) {
372
- console.error(`Error: ${error}`);
373
- process.exit(1);
374
- }
375
- }
376
-
377
- /**
378
- * Parses and validates browse options
379
- */
380
- private _parseBrowseOptions(options: IBrowseCommandOptions): Result<IBrowseOptions> {
381
- try {
382
- // Convert JSON context to contextFilter if provided
383
- let contextFilter = options.contextFilter;
384
- if (options.context && !contextFilter) {
385
- try {
386
- const contextObj = JSON.parse(options.context);
387
- const tokens: string[] = [];
388
- for (const [key, value] of Object.entries(contextObj)) {
389
- tokens.push(`${key}=${value}`);
390
- }
391
- contextFilter = tokens.join('|');
392
- } catch (error) {
393
- return fail(`Invalid context JSON: ${error}`);
394
- }
395
- }
396
-
397
- const browseOptions: IBrowseOptions = {
398
- input: options.input,
399
- config: options.config,
400
- contextFilter,
401
- qualifierDefaults: options.qualifierDefaults,
402
- resourceTypes: options.resourceTypes,
403
- maxDistance: options.maxDistance,
404
- reduceQualifiers: options.reduceQualifiers || false,
405
- verbose: options.verbose || false,
406
- quiet: options.quiet || false,
407
- port: options.port,
408
- url: options.url,
409
- open: options.open,
410
- interactive: options.interactive || false,
411
- dev: options.dev || false,
412
- serve: options.serve || false
413
- };
414
-
415
- return succeed(browseOptions);
416
- } catch (error) {
417
- return fail(`Failed to parse options: ${error}`);
418
- }
419
- }
420
- }
package/src/index.ts DELETED
@@ -1,26 +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
- // Export main components
24
- export * from './cli';
25
- export * from './options';
26
- export * from './simpleBrowserLauncher';
package/src/options.ts DELETED
@@ -1,139 +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
- /**
24
- * Options for launching the ts-res browser
25
- */
26
- export interface IBrowseOptions {
27
- /**
28
- * Input file or directory path
29
- */
30
- input?: string;
31
-
32
- /**
33
- * System configuration file path (JSON file in ISystemConfiguration format)
34
- * or predefined configuration name
35
- */
36
- config?: string;
37
-
38
- /**
39
- * Context filter token (pipe-separated qualifier=value pairs, e.g., 'language=en-US|territory=US')
40
- */
41
- contextFilter?: string;
42
-
43
- /**
44
- * Qualifier default values token (pipe-separated qualifier=value pairs, e.g., 'language=en-US,en-CA|territory=US')
45
- */
46
- qualifierDefaults?: string;
47
-
48
- /**
49
- * Resource types filter (comma-separated, e.g., 'json,string')
50
- */
51
- resourceTypes?: string;
52
-
53
- /**
54
- * Maximum distance for language matching
55
- */
56
- maxDistance?: number;
57
-
58
- /**
59
- * Whether to reduce qualifiers when filtering by context
60
- */
61
- reduceQualifiers?: boolean;
62
-
63
- /**
64
- * Whether to run in verbose mode
65
- */
66
- verbose?: boolean;
67
-
68
- /**
69
- * Whether to run in quiet mode
70
- */
71
- quiet?: boolean;
72
-
73
- /**
74
- * Port to run the development server on (for launching locally)
75
- */
76
- port?: number;
77
-
78
- /**
79
- * Whether to open the browser automatically
80
- */
81
- open?: boolean;
82
-
83
- /**
84
- * Whether to launch in interactive mode (with sample data)
85
- */
86
- interactive?: boolean;
87
-
88
- /**
89
- * Browser URL to launch (for remote instances)
90
- */
91
- url?: string;
92
-
93
- /**
94
- * Whether to automatically start the development server
95
- */
96
- dev?: boolean;
97
-
98
- /**
99
- * Whether to start server (dev in monorepo, serve in published packages) and connect automatically
100
- */
101
- serve?: boolean;
102
-
103
- /**
104
- * Whether to use ZIP loading mode (internal flag)
105
- */
106
- loadZip?: boolean;
107
-
108
- /**
109
- * Path to ZIP file to load (internal flag)
110
- */
111
- zipPath?: string;
112
-
113
- /**
114
- * Name of ZIP file to load (internal flag)
115
- */
116
- zipFile?: string;
117
- }
118
-
119
- /**
120
- * Command-line options for the browse command
121
- */
122
- export interface IBrowseCommandOptions {
123
- input?: string;
124
- config?: string;
125
- context?: string;
126
- contextFilter?: string;
127
- qualifierDefaults?: string;
128
- resourceTypes?: string;
129
- maxDistance?: number;
130
- reduceQualifiers?: boolean;
131
- verbose?: boolean;
132
- quiet?: boolean;
133
- port?: number;
134
- open?: boolean;
135
- interactive?: boolean;
136
- url?: string;
137
- dev?: boolean;
138
- serve?: boolean;
139
- }
@@ -1,278 +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 { exec } from 'child_process';
24
- import * as path from 'path';
25
- import * as http from 'http';
26
- import { Result, succeed, fail } from '@fgv/ts-utils';
27
- import { IBrowseOptions } from './options';
28
- import { zipArchiver } from './zipArchiver';
29
-
30
- /**
31
- * Simplified browser launcher using direct dependency on ts-res-browser
32
- */
33
- export class SimpleBrowserLauncher {
34
- /**
35
- * Launches the browser with the specified options
36
- */
37
- public async launch(options: IBrowseOptions): Promise<Result<void>> {
38
- try {
39
- // Validate options before proceeding
40
- if (options.interactive && !options.dev && !options.serve && !options.url) {
41
- return fail(
42
- 'Interactive mode requires either --dev/--serve to start a local server or --url to specify a remote server.\n\n' +
43
- 'Examples:\n' +
44
- ' ts-res-browser-cli --interactive --dev\n' +
45
- ' ts-res-browser-cli --interactive --serve\n' +
46
- ' ts-res-browser-cli --interactive --url https://example.com/ts-res-browser'
47
- );
48
- }
49
-
50
- // Check if we need to create a ZIP archive for file-based inputs
51
- let zipCreated = false;
52
- let finalOptions = { ...options };
53
-
54
- if (this._shouldCreateZip(options)) {
55
- if (!options.quiet) {
56
- console.log('Creating ZIP archive for file-based resources...');
57
- }
58
-
59
- const zipResult = await this._createZipArchive(options);
60
- if (zipResult.isFailure()) {
61
- return fail(`Failed to create ZIP archive: ${zipResult.message}`);
62
- }
63
-
64
- if (!options.quiet) {
65
- console.log(`ZIP archive created: ${zipResult.value.zipPath}`);
66
- }
67
-
68
- // Modify options to use ZIP loading instead of file paths
69
- const zipFileName = path.basename(zipResult.value.zipPath);
70
- finalOptions = {
71
- ...options,
72
- input: undefined,
73
- config: undefined,
74
- // Add ZIP loading parameters
75
- loadZip: true,
76
- zipFile: zipFileName,
77
- zipPath: zipResult.value.zipPath
78
- };
79
- zipCreated = true;
80
- }
81
-
82
- // Start server if requested
83
- if ((finalOptions.dev || finalOptions.serve) && !finalOptions.url) {
84
- if (!finalOptions.quiet) {
85
- console.log('Starting TS-RES Browser server...');
86
- }
87
-
88
- const serverResult = await this._startServer(finalOptions);
89
- if (serverResult.isFailure()) {
90
- return serverResult;
91
- }
92
- }
93
-
94
- // Build URL with parameters
95
- const url = this._buildUrl(finalOptions);
96
-
97
- if (!finalOptions.quiet) {
98
- console.log('Opening TS-RES Browser...');
99
- if (zipCreated) {
100
- console.log('ZIP archive created - browser will load from Downloads folder');
101
- } else {
102
- if (finalOptions.input) {
103
- console.log(`Resource file: ${finalOptions.input}`);
104
- }
105
- if (finalOptions.config) {
106
- console.log(`Configuration: ${finalOptions.config}`);
107
- }
108
- }
109
- if (finalOptions.contextFilter) {
110
- console.log(`Context filter: ${finalOptions.contextFilter}`);
111
- }
112
- console.log(`URL: ${url}`);
113
- }
114
-
115
- // Open browser if requested (default to true)
116
- const shouldOpen = finalOptions.open !== false;
117
- if (shouldOpen) {
118
- const openResult = await this._openBrowser(url, finalOptions.verbose || false);
119
- if (openResult.isFailure()) {
120
- return fail(`Could not open browser: ${openResult.message}`);
121
- }
122
-
123
- if (!finalOptions.quiet) {
124
- console.log('Browser opened successfully');
125
- }
126
- } else {
127
- console.log(`Browser URL: ${url}`);
128
- }
129
-
130
- return succeed(undefined);
131
- } catch (error) {
132
- return fail(`Failed to launch browser: ${error}`);
133
- }
134
- }
135
-
136
- /**
137
- * Starts the server using ts-res-browser CLI directly
138
- */
139
- private async _startServer(options: IBrowseOptions): Promise<Result<void>> {
140
- try {
141
- // Use ts-res-browser directly from node_modules
142
- const browserPath = require.resolve('@fgv/ts-res-browser/cli.js');
143
- const command = `node "${browserPath}" ${options.dev ? 'dev' : 'serve'}`;
144
-
145
- if (options.verbose) {
146
- console.log(`Running: ${command}`);
147
- }
148
-
149
- return new Promise((resolve) => {
150
- const child = exec(command, (error) => {
151
- if (error) {
152
- resolve(fail(`Failed to start server: ${error.message}`));
153
- } else {
154
- resolve(succeed(undefined));
155
- }
156
- });
157
-
158
- // Give server time to start, then assume success
159
- setTimeout(() => {
160
- if (options.verbose) {
161
- console.log('Server startup initiated');
162
- }
163
- resolve(succeed(undefined));
164
- }, 2000);
165
- });
166
- } catch (error) {
167
- return fail(`Failed to start server: ${error}`);
168
- }
169
- }
170
-
171
- /**
172
- * Opens the browser to the specified URL
173
- */
174
- private async _openBrowser(url: string, verbose: boolean): Promise<Result<void>> {
175
- return new Promise((resolve) => {
176
- const command =
177
- process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start ""' : 'xdg-open';
178
-
179
- exec(`${command} "${url}"`, (error) => {
180
- if (error) {
181
- resolve(fail(`Failed to open browser: ${error.message}`));
182
- } else {
183
- if (verbose) {
184
- console.log(`Opened browser to: ${url}`);
185
- }
186
- resolve(succeed(undefined));
187
- }
188
- });
189
- });
190
- }
191
-
192
- /**
193
- * Builds the URL with query parameters based on options
194
- */
195
- private _buildUrl(options: IBrowseOptions): string {
196
- // Use provided URL or default based on server type
197
- const defaultPort = options.dev ? 3000 : 8080;
198
- const baseUrl = options.url || `http://localhost:${options.port || defaultPort}`;
199
- const params = new URLSearchParams();
200
-
201
- if (options.input) {
202
- params.set('input', options.input);
203
- }
204
-
205
- if (options.config) {
206
- params.set('config', options.config);
207
- }
208
-
209
- if (options.contextFilter) {
210
- params.set('contextFilter', options.contextFilter);
211
- }
212
-
213
- if (options.qualifierDefaults) {
214
- params.set('qualifierDefaults', options.qualifierDefaults);
215
- }
216
-
217
- if (options.resourceTypes) {
218
- params.set('resourceTypes', options.resourceTypes);
219
- }
220
-
221
- if (options.maxDistance !== undefined) {
222
- params.set('maxDistance', options.maxDistance.toString());
223
- }
224
-
225
- if (options.reduceQualifiers) {
226
- params.set('reduceQualifiers', 'true');
227
- }
228
-
229
- if (options.interactive) {
230
- params.set('interactive', 'true');
231
- }
232
-
233
- if (options.loadZip) {
234
- params.set('loadZip', 'true');
235
- }
236
-
237
- if (options.zipFile) {
238
- params.set('zipFile', options.zipFile);
239
- }
240
-
241
- if (options.zipPath) {
242
- params.set('zipPath', options.zipPath);
243
- }
244
-
245
- const queryString = params.toString();
246
- return queryString ? `${baseUrl}?${queryString}` : baseUrl;
247
- }
248
-
249
- /**
250
- * Determines if a ZIP archive should be created based on the options
251
- */
252
- private _shouldCreateZip(options: IBrowseOptions): boolean {
253
- // Create ZIP if input or config are file paths (not predefined names)
254
- const hasFilePath = (path: string | undefined): boolean => {
255
- if (!path) return false;
256
- // Check if it's a file path (contains directory separators or file extensions)
257
- return path.includes('/') || path.includes('\\') || (path.includes('.') && !path.startsWith('.'));
258
- };
259
-
260
- return hasFilePath(options.input) || hasFilePath(options.config);
261
- }
262
-
263
- /**
264
- * Creates a ZIP archive containing the input and config files
265
- */
266
- private async _createZipArchive(
267
- options: IBrowseOptions
268
- ): Promise<Result<{ zipPath: string; manifest: any }>> {
269
- try {
270
- return await zipArchiver.createArchive({
271
- input: options.input,
272
- config: options.config
273
- });
274
- } catch (error) {
275
- return fail(`Failed to create ZIP archive: ${error instanceof Error ? error.message : String(error)}`);
276
- }
277
- }
278
- }
@@ -1,68 +0,0 @@
1
- import * as fs from 'fs';
2
- import * as path from 'path';
3
- import * as os from 'os';
4
- import { Result, succeed, fail } from '@fgv/ts-utils';
5
- import { ZipArchive } from '@fgv/ts-res';
6
-
7
- export interface ZipArchiveOptions {
8
- input?: string;
9
- config?: string;
10
- outputDir?: string;
11
- }
12
-
13
- export interface ZipArchiveResult {
14
- zipPath: string;
15
- manifest: ZipArchive.IZipArchiveManifest;
16
- }
17
-
18
- export class ZipArchiver {
19
- /**
20
- * Create a ZIP archive containing the specified input and config files/directories
21
- */
22
- async createArchive(options: ZipArchiveOptions): Promise<Result<ZipArchiveResult>> {
23
- try {
24
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
25
- const outputDir = options.outputDir || path.join(os.homedir(), 'Downloads');
26
- const zipFileName = `ts-res-bundle-${timestamp}.zip`;
27
- const zipPath = path.join(outputDir, zipFileName);
28
-
29
- // Ensure output directory exists
30
- if (!fs.existsSync(outputDir)) {
31
- fs.mkdirSync(outputDir, { recursive: true });
32
- }
33
-
34
- // Create ZIP archive using the new zip-archive packlet
35
- const creator = new ZipArchive.ZipArchiveCreator();
36
- const createResult = await creator.createFromBuffer({
37
- inputPath: options.input,
38
- configPath: options.config
39
- });
40
-
41
- if (createResult.isFailure()) {
42
- return fail(createResult.message);
43
- }
44
-
45
- const { zipBuffer, manifest } = createResult.value;
46
-
47
- // Write the ZIP buffer to disk
48
- fs.writeFileSync(zipPath, zipBuffer);
49
-
50
- return succeed({
51
- zipPath,
52
- manifest
53
- });
54
- } catch (error) {
55
- return fail(`Failed to create ZIP archive: ${error instanceof Error ? error.message : String(error)}`);
56
- }
57
- }
58
-
59
- /**
60
- * Get the default downloads directory path
61
- */
62
- getDefaultDownloadsDir(): string {
63
- return path.join(os.homedir(), 'Downloads');
64
- }
65
- }
66
-
67
- // Export singleton instance
68
- export const zipArchiver = new ZipArchiver();