From fd6db0cf53618680fc762475df4e284745b6cd80 Mon Sep 17 00:00:00 2001 From: umbrik <693254+umbrik@users.noreply.github.com> Date: Thu, 14 May 2026 13:40:23 +0200 Subject: [PATCH 1/2] Refactor argument handling in ArgsParser and update related usages --- src/commands/watch.ts | 2 +- src/core/args.ts | 64 +++++++++--------------------- src/core/build.ts | 8 ++-- src/index.ts | 4 +- src/transformers/remove_exports.ts | 4 +- 5 files changed, 27 insertions(+), 55 deletions(-) diff --git a/src/commands/watch.ts b/src/commands/watch.ts index f80c030..50c6254 100644 --- a/src/commands/watch.ts +++ b/src/commands/watch.ts @@ -3,7 +3,7 @@ import { watchNonTypescriptFiles, watchTypescriptFiles } from '../core/build.js' import { getTSConfig } from '../core/config.js'; export function watch(cwd: string) { - const configuration = getTSConfig(cwd, args.getArg('project')); + const configuration = getTSConfig(cwd, args['project']); watchTypescriptFiles(configuration); watchNonTypescriptFiles(configuration); } \ No newline at end of file diff --git a/src/core/args.ts b/src/core/args.ts index 9dbda2a..5cf669a 100644 --- a/src/core/args.ts +++ b/src/core/args.ts @@ -1,52 +1,24 @@ -export enum ArgsFlags { - INCLUDE_NON_TS_FILES = 'include-non-ts-files', - RETAIN_IMPORTS_AS_COMMENTS = 'retain-imports-as-comments', - RETAIN_NON_ASCII_CHARACTERS = 'retain-non-ascii-characters', -} +import { parseArgs } from "node:util"; -export class ArgsParser { - #command: string = ''; - #argv: string[] = []; +class ArgsParser { + command: string = ''; + args: Record = {} ; constructor() { - this.#parse(); - } - - getArg(argName: string) { - const argumentsList = process.argv.slice(2); - - for (let i = 0; i < argumentsList.length; i++) { - const argument = argumentsList[i]; - - if (!argument.startsWith(`--${argName}`)) { - continue; - } - - if (argument === `--${argName}`) { - const nextArgument = argumentsList[i + 1]; - return nextArgument?.startsWith('--') ? undefined : nextArgument; - } - - if (argument.startsWith(`--${argName}=`)) { - return argument.slice(argName.length + 3); - } - } - - return undefined; - } - - getCommand() { - return this.#command; - } - - has(argumentName: ArgsFlags) { - return this.#argv.includes(argumentName); - } - - #parse() { - this.#command = process.argv.slice(2)[0]; - this.#argv = process.argv.slice(3).filter((x: string) => x.startsWith('--')).map((x: string) => x.slice(2)); + const { values: args, positionals: [command] } = parseArgs({ + options: { + help: { type: 'boolean', short: 'h', default: false }, + version: { type: 'boolean', short: 'v', default: false }, + project: { type: 'string', short: 'p', default: 'tsconfig.json' }, + 'include-non-ts-files': { type: 'boolean', default: false }, + 'retain-imports-as-comments': { type: 'boolean', default: false }, + 'retain-non-ascii-characters': { type: 'boolean', default: false }, + }, + allowPositionals: true + }); + this.command = command || ''; + this.args = args; } } -export const args = new ArgsParser(); +export const { args, command } = new ArgsParser(); diff --git a/src/core/build.ts b/src/core/build.ts index 368de39..8e2c25e 100644 --- a/src/core/build.ts +++ b/src/core/build.ts @@ -8,7 +8,7 @@ import { removeExports } from '../transformers/remove_exports.js'; import { convertTemplateStrings } from '../transformers/template_strings.js'; import { transformNamespaces } from '../transformers/transform_namespaces.js'; import { noDeclarationInLoop } from '../checks/no-declaration-in-loop.js'; -import { args, ArgsFlags } from './args.js'; +import { args } from './args.js'; import { logger } from './logger.js'; export function buildTypescriptFiles(configuration: ts.ParsedCommandLine) { @@ -93,7 +93,7 @@ function decorateHostWriteFile(host: ts.CompilerHost) { fileName = fileName.replace('.js', '.html'); } - if (!args.has(ArgsFlags.RETAIN_NON_ASCII_CHARACTERS)) { + if (!args['retain-non-ascii-characters']) { // Decode non ASCII characters data = data.replace(/\\u[\dA-Fa-f]{4}/g, (match) => { return String.fromCharCode(parseInt(match.substr(2), 16)); @@ -148,7 +148,7 @@ export function watchTypescriptFiles(configuration: ts.ParsedCommandLine) { } export function watchNonTypescriptFiles(configuration: ts.ParsedCommandLine) { - if (!args.has(ArgsFlags.INCLUDE_NON_TS_FILES)) { + if (!args['include-non-ts-files']) { return; } @@ -170,7 +170,7 @@ export function watchNonTypescriptFiles(configuration: ts.ParsedCommandLine) { } export function buildNonTypescriptFiles(configuration: ts.ParsedCommandLine) { - if (!args.has(ArgsFlags.INCLUDE_NON_TS_FILES)) { + if (!args['include-non-ts-files']) { return; } diff --git a/src/index.ts b/src/index.ts index 308dc18..a026860 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,12 +1,12 @@ #!/usr/bin/env node -import { args } from './core/args.js'; +import * as args from './core/args.js'; import { commands } from './commands/index.js'; import { help } from './commands/help.js'; const cwd = process.cwd(); -const command = commands.get(args.getCommand()); +const command = commands.get(args.command); if (command) { command.callback(cwd); diff --git a/src/transformers/remove_exports.ts b/src/transformers/remove_exports.ts index 181cdd3..20dcce0 100644 --- a/src/transformers/remove_exports.ts +++ b/src/transformers/remove_exports.ts @@ -1,6 +1,6 @@ import ts from 'typescript'; -import { args, ArgsFlags } from '../core/args.js'; +import { args } from '../core/args.js'; export function removeExports(): ts.TransformerFactory { return (context) => (sourceFile: ts.SourceFile) => { @@ -30,7 +30,7 @@ export function removeExports(): ts.TransformerFactory { } if (ts.isImportDeclaration(node)) { - if (args.has(ArgsFlags.RETAIN_IMPORTS_AS_COMMENTS)) { + if (args['retain-imports-as-comments']) { const commentedStatement = ts.factory.createNotEmittedStatement(node); ts.addSyntheticLeadingComment( commentedStatement, From 2d0b8cbc4086786321c99225de71a770140a2535 Mon Sep 17 00:00:00 2001 From: umbrik <693254+umbrik@users.noreply.github.com> Date: Thu, 14 May 2026 13:53:43 +0200 Subject: [PATCH 2/2] Enhance build command argument handling and add comprehensive tests --- src/commands/build.ts | 4 +- src/core/build.ts | 23 ++- test/commands/build-args.test.js | 94 ++++++++++++ .../configs/tsconfig.custom.json | 11 ++ test/commands/build_args_fixture/src/index.ts | 11 ++ .../build_args_fixture/src/submodule.ts | 1 + .../build_args_fixture/src/template.xml | 3 + .../commands/build_args_fixture/tsconfig.json | 10 ++ test/core/args/args.test.js | 137 ++++++++++++------ 9 files changed, 242 insertions(+), 52 deletions(-) create mode 100644 test/commands/build-args.test.js create mode 100644 test/commands/build_args_fixture/configs/tsconfig.custom.json create mode 100644 test/commands/build_args_fixture/src/index.ts create mode 100644 test/commands/build_args_fixture/src/submodule.ts create mode 100644 test/commands/build_args_fixture/src/template.xml create mode 100644 test/commands/build_args_fixture/tsconfig.json diff --git a/src/commands/build.ts b/src/commands/build.ts index 8e126cd..45139aa 100644 --- a/src/commands/build.ts +++ b/src/commands/build.ts @@ -5,7 +5,7 @@ import { logger } from '../core/logger.js'; export function build(cwd: string) { logger.success(`🔨 ${new Date().toLocaleTimeString()} Project building started`); - const configuration = getTSConfig(cwd, args.getArg('project')); + const configuration = getTSConfig(cwd, args['project']); const result = buildTypescriptFiles(configuration); @@ -18,4 +18,4 @@ export function build(cwd: string) { logger.success(`✅ ${new Date().toLocaleTimeString()} Project building finished`); process.exit(0); -} \ No newline at end of file +} diff --git a/src/core/build.ts b/src/core/build.ts index 8e2c25e..5adfdf3 100644 --- a/src/core/build.ts +++ b/src/core/build.ts @@ -152,11 +152,12 @@ export function watchNonTypescriptFiles(configuration: ts.ParsedCommandLine) { return; } - const { rootDir, outDir } = configuration.options; + const sourceRootPath = getSourceRootPath(configuration); + const { outDir } = configuration.options; const entries = collectNonTypescriptFiles(configuration); entries.forEach((x: string) => { - const filePath = rootDir ? relative(rootDir, x) : x; + const filePath = relative(sourceRootPath, x); const outputFilePath = resolve(outDir!, filePath); fs.watch(resolve(x), (event: fs.WatchEventType) => { @@ -174,13 +175,27 @@ export function buildNonTypescriptFiles(configuration: ts.ParsedCommandLine) { return; } - const { rootDir, outDir } = configuration.options; + const sourceRootPath = getSourceRootPath(configuration); + const { outDir } = configuration.options; const entries = collectNonTypescriptFiles(configuration); entries.forEach((x: string) => { - const filePath = rootDir ? relative(rootDir, x) : x; + const filePath = relative(sourceRootPath, x); const outputFilePath = resolve(outDir!, filePath); fs.mkdirSync(dirname(outputFilePath), { recursive: true }); fs.writeFileSync(outputFilePath, fs.readFileSync(resolve(x), 'utf-8')); }); } + +function getSourceRootPath(configuration: ts.ParsedCommandLine) { + const configFilePath = typeof configuration.options.configFilePath === 'string' + ? configuration.options.configFilePath + : resolve('tsconfig.json'); + const configDirectoryPath = dirname(configFilePath); + + if (typeof configuration.options.rootDir === 'string') { + return resolve(configDirectoryPath, configuration.options.rootDir); + } + + return configDirectoryPath; +} diff --git a/test/commands/build-args.test.js b/test/commands/build-args.test.js new file mode 100644 index 0000000..5ddee03 --- /dev/null +++ b/test/commands/build-args.test.js @@ -0,0 +1,94 @@ +import { match, ok, strictEqual } from 'node:assert'; +import { cpSync, existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { execFileSync } from 'node:child_process'; +import { suite, test } from 'node:test'; + +const fixturePath = resolve(import.meta.dirname, 'build_args_fixture'); +const cliEntryPath = resolve(import.meta.dirname, '..', '..', 'dist', 'index.js'); + +function createProject(t) { + const tempRootPath = mkdtempSync(join(tmpdir(), 'wshcmx-build-args-')); + const projectPath = join(tempRootPath, 'project'); + cpSync(fixturePath, projectPath, { recursive: true }); + t.after(() => rmSync(tempRootPath, { recursive: true, force: true })); + return projectPath; +} + +function runBuild(projectPath, cliArgs = []) { + execFileSync(process.execPath, [cliEntryPath, 'build', ...cliArgs], { + cwd: projectPath, + stdio: 'pipe', + }); +} + +function getBuiltIndexPath(projectPath, outputDirectoryName) { + const candidatePaths = [ + join(projectPath, outputDirectoryName, 'index.bs'), + join(projectPath, outputDirectoryName, 'index.js'), + join(projectPath, outputDirectoryName, 'src', 'index.bs'), + join(projectPath, outputDirectoryName, 'src', 'index.js'), + ]; + + return candidatePaths.find((candidatePath) => existsSync(candidatePath)) ?? candidatePaths[0]; +} + +function hasBuiltIndex(projectPath, outputDirectoryName) { + return getBuiltIndexPath(projectPath, outputDirectoryName) !== join(projectPath, outputDirectoryName, 'index.bs') + || existsSync(join(projectPath, outputDirectoryName, 'index.bs')); +} + +suite('build command arguments', () => { + test('--project and -p select the tsconfig used for the build', (t) => { + const longOptionProjectPath = createProject(t); + const shortOptionProjectPath = createProject(t); + + runBuild(longOptionProjectPath, ['--project', 'configs\\tsconfig.custom.json']); + runBuild(shortOptionProjectPath, ['-p', 'configs\\tsconfig.custom.json']); + + ok(hasBuiltIndex(longOptionProjectPath, 'dist-custom')); + ok(hasBuiltIndex(shortOptionProjectPath, 'dist-custom')); + strictEqual(hasBuiltIndex(longOptionProjectPath, 'dist-default'), false); + strictEqual(hasBuiltIndex(shortOptionProjectPath, 'dist-default'), false); + }); + + test('--include-non-ts-files copies non-TypeScript assets into the output', (t) => { + const withoutFlagProjectPath = createProject(t); + const withFlagProjectPath = createProject(t); + + runBuild(withoutFlagProjectPath); + runBuild(withFlagProjectPath, ['--include-non-ts-files']); + + strictEqual(existsSync(join(withoutFlagProjectPath, 'dist-default', 'src', 'template.xml')), false); + ok(existsSync(join(withFlagProjectPath, 'dist-default', 'src', 'template.xml'))); + }); + + test('--retain-imports-as-comments preserves imports as commented lines in the emitted file', (t) => { + const withoutFlagProjectPath = createProject(t); + const withFlagProjectPath = createProject(t); + + runBuild(withoutFlagProjectPath); + runBuild(withFlagProjectPath, ['--retain-imports-as-comments']); + + const withoutFlagOutput = readFileSync(getBuiltIndexPath(withoutFlagProjectPath, 'dist-default'), 'utf-8'); + const withFlagOutput = readFileSync(getBuiltIndexPath(withFlagProjectPath, 'dist-default'), 'utf-8'); + + strictEqual(withoutFlagOutput.includes("import { value } from './submodule';"), false); + ok(withFlagOutput.includes("// import { value } from './submodule';")); + }); + + test('--retain-non-ascii-characters keeps unicode escapes in emitted output', (t) => { + const withoutFlagProjectPath = createProject(t); + const withFlagProjectPath = createProject(t); + + runBuild(withoutFlagProjectPath); + runBuild(withFlagProjectPath, ['--retain-non-ascii-characters']); + + const withoutFlagOutput = readFileSync(getBuiltIndexPath(withoutFlagProjectPath, 'dist-default'), 'utf-8'); + const withFlagOutput = readFileSync(getBuiltIndexPath(withFlagProjectPath, 'dist-default'), 'utf-8'); + + ok(withoutFlagOutput.includes('Результат: ')); + match(withFlagOutput, /\\u0420\\u0435\\u0437\\u0443\\u043b\\u044c\\u0442\\u0430\\u0442: /i); + }); +}); diff --git a/test/commands/build_args_fixture/configs/tsconfig.custom.json b/test/commands/build_args_fixture/configs/tsconfig.custom.json new file mode 100644 index 0000000..4b66360 --- /dev/null +++ b/test/commands/build_args_fixture/configs/tsconfig.custom.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "rootDir": "../src", + "target": "esnext", + "module": "Preserve", + "outDir": "../dist-custom" + }, + "include": [ + "../src/**/*" + ] +} diff --git a/test/commands/build_args_fixture/src/index.ts b/test/commands/build_args_fixture/src/index.ts new file mode 100644 index 0000000..742e02d --- /dev/null +++ b/test/commands/build_args_fixture/src/index.ts @@ -0,0 +1,11 @@ +import { value } from './submodule'; + +export namespace Module { + export function method(a: number, b: number): string { + return `Результат: ${a + b}`; + } +} + +export function readValue() { + return value; +} diff --git a/test/commands/build_args_fixture/src/submodule.ts b/test/commands/build_args_fixture/src/submodule.ts new file mode 100644 index 0000000..1f34be2 --- /dev/null +++ b/test/commands/build_args_fixture/src/submodule.ts @@ -0,0 +1 @@ +export const value = 'submodule value'; diff --git a/test/commands/build_args_fixture/src/template.xml b/test/commands/build_args_fixture/src/template.xml new file mode 100644 index 0000000..b55c62e --- /dev/null +++ b/test/commands/build_args_fixture/src/template.xml @@ -0,0 +1,3 @@ + diff --git a/test/commands/build_args_fixture/tsconfig.json b/test/commands/build_args_fixture/tsconfig.json new file mode 100644 index 0000000..7bb8ec6 --- /dev/null +++ b/test/commands/build_args_fixture/tsconfig.json @@ -0,0 +1,10 @@ +{ + "compilerOptions": { + "target": "esnext", + "module": "Preserve", + "outDir": "dist-default" + }, + "include": [ + "src/**/*" + ] +} diff --git a/test/core/args/args.test.js b/test/core/args/args.test.js index 16822b6..05ee0cb 100644 --- a/test/core/args/args.test.js +++ b/test/core/args/args.test.js @@ -1,64 +1,109 @@ import { strictEqual } from 'node:assert'; -import { resolve } from 'node:path'; -import { test, suite } from 'node:test'; +import { suite, test } from 'node:test'; -import { ArgsParser } from '#dist/core/args.js'; +const argsModuleUrl = new URL('../../../dist/core/args.js', import.meta.url); +let importCounter = 0; -suite('ArgsParser.getArg', () => { - test('returns undefined when project argument is omitted', () => { - const originalArgv = process.argv; - process.argv = ['node', 'cli', 'build']; +async function loadArgs(argv) { + const originalArgv = process.argv; - try { - strictEqual(new ArgsParser().getArg('project'), undefined); - } finally { - process.argv = originalArgv; - } + process.argv = argv; + + try { + return await import(`${argsModuleUrl.href}?test=${importCounter += 1}`); + } finally { + process.argv = originalArgv; + } +} + +suite('args parser', () => { + test('uses defaults when no command or flags are provided', async () => { + const { args, command } = await loadArgs([ + 'node', + 'wshcmx', + ]); + + strictEqual(command, ''); + strictEqual(args.help, false); + strictEqual(args.version, false); + strictEqual(args.project, 'tsconfig.json'); + strictEqual(args['include-non-ts-files'], false); + strictEqual(args['retain-imports-as-comments'], false); + strictEqual(args['retain-non-ascii-characters'], false); + }); + + test('parses the positional command', async () => { + const { command } = await loadArgs([ + 'node', + 'wshcmx', + 'build', + ]); + + strictEqual(command, 'build'); }); - test('reads a relative project argument from a separate value', () => { - const originalArgv = process.argv; - process.argv = ['node', 'cli', 'build', '--project', 'configs/custom.tsconfig.json']; + test('parses help from long and short flags', async () => { + const fromLong = await loadArgs([ + 'node', + 'wshcmx', + '--help', + ]); + const fromShort = await loadArgs([ + 'node', + 'wshcmx', + '-h', + ]); - try { - strictEqual(new ArgsParser().getArg('project'), 'configs/custom.tsconfig.json'); - } finally { - process.argv = originalArgv; - } + strictEqual(fromLong.args.help, true); + strictEqual(fromShort.args.help, true); }); - test('reads an absolute project argument from a separate value', () => { - const originalArgv = process.argv; - const absolutePath = resolve('test', 'core', 'config', 'fixture', 'configs', 'custom.tsconfig.json'); - process.argv = ['node', 'cli', 'build', '--project', absolutePath]; + test('parses version from long and short flags', async () => { + const fromLong = await loadArgs([ + 'node', + 'wshcmx', + '--version', + ]); + const fromShort = await loadArgs([ + 'node', + 'wshcmx', + '-v', + ]); - try { - strictEqual(new ArgsParser().getArg('project'), absolutePath); - } finally { - process.argv = originalArgv; - } + strictEqual(fromLong.args.version, true); + strictEqual(fromShort.args.version, true); }); - test('reads a relative project argument from equals syntax', () => { - const originalArgv = process.argv; - process.argv = ['node', 'cli', 'build', '--project=configs/custom.tsconfig.json']; + test('parses project from long and short options', async () => { + const fromLong = await loadArgs([ + 'node', + 'wshcmx', + '--project', + 'configs\\custom.tsconfig.json', + ]); + const fromShort = await loadArgs([ + 'node', + 'wshcmx', + '-p', + 'configs\\short.tsconfig.json', + ]); - try { - strictEqual(new ArgsParser().getArg('project'), 'configs/custom.tsconfig.json'); - } finally { - process.argv = originalArgv; - } + strictEqual(fromLong.args.project, 'configs\\custom.tsconfig.json'); + strictEqual(fromShort.args.project, 'configs\\short.tsconfig.json'); }); - test('reads an absolute project argument from equals syntax', () => { - const originalArgv = process.argv; - const absolutePath = resolve('test', 'core', 'config', 'fixture', 'configs', 'custom.tsconfig.json'); - process.argv = ['node', 'cli', 'build', `--project=${absolutePath}`]; + test('parses all supported boolean build flags', async () => { + const { args } = await loadArgs([ + 'node', + 'wshcmx', + 'build', + '--include-non-ts-files', + '--retain-imports-as-comments', + '--retain-non-ascii-characters', + ]); - try { - strictEqual(new ArgsParser().getArg('project'), absolutePath); - } finally { - process.argv = originalArgv; - } + strictEqual(args['include-non-ts-files'], true); + strictEqual(args['retain-imports-as-comments'], true); + strictEqual(args['retain-non-ascii-characters'], true); }); });