diff --git a/src/commands/build.ts b/src/commands/build.ts index bd79dff..82397a5 100644 --- a/src/commands/build.ts +++ b/src/commands/build.ts @@ -12,7 +12,7 @@ import * as Preprocessor from '../utilities/preprocessor'; import { bold, magentaBright } from 'colorette'; import { parseTsConfig } from '../utilities/parseTsconfig'; import { execa, type ExecaChildProcess } from 'execa'; -import { setTimeout } from 'node:timers/promises'; +import { InvalidArgumentError } from 'commander'; const VALID_EXTENSIONS = ['.ts', '.js' ]; @@ -50,12 +50,16 @@ type BuildOptions = { * flag: default false */ sourcemap?: boolean; - /** - * command to run. - * defaults to your package - * manager's start command. - */ - watchCommand?: string; + + watch?: { + /** + * command to run. + * defaults to your package + * manager's start command. + */ + command?: string; + } + }; const CommandHandlerPlugin = (buildConfig: Partial, ambientFilePath: string, sernTsConfigPath: string) => { @@ -82,7 +86,7 @@ const CommandOnEndPlugin = (watching: boolean, watchCommand?: string) => { // for some reason it runs the command twice on first build let isFirstBuild = true; let currentProcess: ExecaChildProcess | null = null; - + let restartTimeout: NodeJS.Timeout | null = null; return { name: 'watchRunCommand', setup(build: esbuild.PluginBuild) { @@ -113,15 +117,20 @@ const CommandOnEndPlugin = (watching: boolean, watchCommand?: string) => { throw new Error('[watch] default package manager start command not found'); })(); - console.log(`[watch] waiting 1 second before running command...`); - await setTimeout(1000); + // Clear any pending restart + if (restartTimeout) clearTimeout(restartTimeout); - console.log(`[watch] running command: ${cmd}`); - currentProcess = execa(cmd, { stdio: 'inherit', shell: true }); - currentProcess.catch(error => { - if (error.isCanceled) return; - console.error(`[watch] command execution error: ${error.message}`); - }); + console.log('[watch] debouncing command for 1.5 seconds...'); + + // Set new debounced timeout + restartTimeout = setTimeout(() => { + console.log(`[watch] running command: ${cmd}`); + currentProcess = execa(cmd, { stdio: 'inherit', shell: true }); + currentProcess.catch(error => { + if (error.isCanceled) return; + console.error(`[watch] command execution error: ${error.message}`); + }); + }, 1500); }); } } as esbuild.Plugin; @@ -134,10 +143,15 @@ const resolveBuildConfig = (path: string | undefined, language: string) => { } export async function build(options: Record) { + //console.log(options) if (!options.supressWarnings) { console.info(`${magentaBright('EXPERIMENTAL')}: This API has not been stabilized. add -W or --suppress-warnings flag to suppress`); } - console.log(options) + // if watch was not enabled and watchCommand is present + if(!options.watch && options.watchCommand) { + throw new InvalidArgumentError("enable watch to use --watch-command") + } + const sernConfig = await getConfig(); let buildConfig: BuildOptions; const buildConfigPath = p.resolve(options.project ?? 'sern.build.js'); @@ -150,22 +164,34 @@ export async function build(options: Record) { sourcemap: options.sourceMaps, tsconfig: resolveBuildConfig(options.tsconfig, sernConfig.language), env: options.env ?? '.env', - include: [] + include: [], + watch: { + command: options.watchCommand + } }; + + // merging configuration with sern.build.js, if exists buildConfigPath if (pathExistsSync(buildConfigPath)) { - //throwable, buildConfigPath may not exist - buildConfig = { ...defaultBuildConfig, ...(await import('file:///' + buildConfigPath)).default }; + let fileConfig; + try { fileConfig=await import('file:///' + buildConfigPath).then(r=>r.default) } + catch(e) { + console.error("Could not find buildConfigPath") + throw e; + } + //throwable, buildConfigPath may not exist, todo, merge + buildConfig = { ...defaultBuildConfig, ...fileConfig }; } else { buildConfig = defaultBuildConfig; console.log('No build config found, defaulting'); } + configDotenv({ path: buildConfig.env }); if (process.env.NODE_ENV) { buildConfig.mode = process.env.NODE_ENV as 'production' | 'development'; console.log(magentaBright('NODE_ENV:'), 'Found NODE_ENV variable, setting `mode` to this.'); } - assert(buildConfig.mode === 'development' || buildConfig.mode === 'production', 'Mode is not `production` or `development`'); + assert(buildConfig.mode === 'development' || buildConfig.mode === 'production', 'NODE_ENV is not `production` or `development`'); try { let config = await parseTsConfig(buildConfig.tsconfig!); config?.extends && console.warn("Extend the generated tsconfig") @@ -186,7 +212,7 @@ export async function build(options: Record) { console.log(' ', magentaBright('sourceMaps'), buildConfig.sourcemap); const sernDir = p.resolve('.sern'), - [ambientFilePath, sernTsConfigPath, genDir] = + [ambientFilePath, sernTsConfigPath, genDir] = // resolves the file paths in the .sern dir ['ambient.d.ts', 'tsconfig.json', 'generated'].map(f => p.resolve(sernDir, f)); if (!(await pathExists(genDir))) { @@ -204,7 +230,7 @@ export async function build(options: Record) { entryPoints, plugins: [ CommandHandlerPlugin(buildConfig, ambientFilePath, sernTsConfigPath), - CommandOnEndPlugin(options.watch, buildConfig.watchCommand) + CommandOnEndPlugin(options.watch, buildConfig.watch?.command) ], sourcemap: buildConfig.sourcemap, ...defaultEsbuild(buildConfig.format!, buildConfig.tsconfig), diff --git a/src/index.ts b/src/index.ts index 2ee63eb..bd1f4ae 100644 --- a/src/index.ts +++ b/src/index.ts @@ -58,6 +58,7 @@ program .option('-f --format [fmt]', 'The module system of your application. `cjs` or `esm`', 'esm') .option('-m --mode [mode]', 'the mode for sern to build in. `production` or `development`', 'development') .option('-w --watch') + .option('--watch-command [cmd]', 'the command for sern to watch. if watch is not enabled, an error is thrown', '') .option('-W --suppress-warnings', 'suppress experimental warning') .option('-p --project [filePath]', 'build with the provided sern.build file') .option('-e --env', 'path to .env file')