/* * @adonisjs/assembler * * (c) AdonisJS * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import dedent from 'dedent' import fs from 'node:fs/promises' import type tsStatic from 'typescript' import { cliui } from '@poppinss/cliui' import { fileURLToPath } from 'node:url' import type Hooks from '@poppinss/hooks' import string from '@poppinss/utils/string' import { join, relative } from 'node:path/posix' import { detectPackageManager } from '@antfu/install-pkg' import type { BundlerOptions } from './types/common.ts' import { run, copyFiles, loadHooks, readTsConfig } from './utils.ts' import { type HookParams, type BundlerHooks, type CommonHooks } from './types/hooks.ts' import { type SupportedPackageManager } from './types/code_transformer.ts' import { IndexGenerator } from './index_generator/main.ts' /** * List of package managers we support in order to * copy lockfiles */ export const SUPPORTED_PACKAGE_MANAGERS: { [K in SupportedPackageManager]: { packageManagerFiles: string[] installCommand: string } } = { 'npm': { packageManagerFiles: ['package-lock.json'], installCommand: 'npm ci --omit="dev"', }, 'yarn': { packageManagerFiles: ['yarn.lock'], installCommand: 'yarn install --production', }, 'yarn@berry': { packageManagerFiles: ['yarn.lock', '.yarn/**/*', '.yarnrc.yml'], installCommand: 'yarn workspaces focus --production', }, 'pnpm': { packageManagerFiles: ['pnpm-lock.yaml'], installCommand: 'pnpm i --prod', }, 'bun': { packageManagerFiles: ['bun.lock', 'bun.lockb'], installCommand: 'bun install --production', }, 'nub': { packageManagerFiles: ['nub.lock'], installCommand: 'nub install --prod', }, 'aube': { packageManagerFiles: ['aube-lock.yaml'], installCommand: 'aube install --prod', }, } /** * The bundler class exposes the API to build an AdonisJS project. * * @example * const bundler = new Bundler(new URL('./'), ts, { hooks: [] }) * const success = await bundler.bundle() */ export class Bundler { /** * Hooks to execute custom actions during the build process */ #hooks!: Hooks< { [K in keyof CommonHooks]: [HookParams, HookParams] } & { [K in keyof BundlerHooks]: [HookParams, HookParams] } > /** * Index generator for managing auto-generated index files */ #indexGenerator!: IndexGenerator /** * CLI UI instance for displaying colorful messages and progress information */ ui = cliui() /** * Package manager detected from the project environment */ declare packageManager: SupportedPackageManager /** * The current working directory URL */ cwd: URL /** * The current working project directory path as string */ cwdPath: string /** * Bundler configuration options including hooks and meta files */ options: BundlerOptions /** * Create a new bundler instance * * @param cwd - The current working directory URL * @param _ts - TypeScript module reference retained for backward compatibility * @param options - Bundler configuration options */ constructor(cwd: URL, _ts: typeof tsStatic, options: BundlerOptions) { this.cwd = cwd this.options = options this.cwdPath = string.toUnixSlash(fileURLToPath(this.cwd)) } /** * Returns the relative unix path for an absolute * file path */ #getRelativeName(filePath: string) { return string.toUnixSlash(relative(this.cwdPath, filePath)) } /** * Cleans up the build directory */ async #cleanupBuildDirectory(outDir: string) { await fs.rm(outDir, { recursive: true, force: true, maxRetries: 5 }) } /** * Runs tsc command to build the source. */ async #runTsc(args: { outDir: string; project?: string }): Promise { try { await run(this.cwd, { stdio: 'inherit', script: 'tsc', scriptArgs: Object.entries(args).flatMap(([key, value]) => value ? [`--${key}`, value] : [] ), }) return true } catch { return false } } /** * Copy meta files to the output directory */ async #copyMetaFiles(outDir: string, additionalFilesToCopy: string[]) { const metaFiles = (this.options.metaFiles || []) .map((file) => file.pattern) .concat(additionalFilesToCopy) await copyFiles(metaFiles, this.cwdPath, outDir) } /** * Detect the package manager used by the project */ async #detectPackageManager(): Promise { const pkgManager = await detectPackageManager(this.cwdPath) if (pkgManager === 'deno') { return 'npm' } /** * "upm" is detected by "@antfu/install-pkg", but is not a package * manager we support. Treat it as not detected. */ if (pkgManager === 'upm') { return null } /** * Rush controls pnpm from the monorepo root. The compiled application is * standalone, so it should use the regular pnpm metadata and command. */ if (pkgManager === 'pnpm@6' || pkgManager === 'pnpm-rush') { return 'pnpm' } return pkgManager } /** * Rewrite the ace file since the original one * is importing ts-node which is not installed * in a production environment. */ async #createAceFile(outDir: string) { const aceFileLocation = join(outDir, 'ace.js') const aceFileContent = dedent(/* JavaScript */ ` /** * This file is auto-generated by the build process. * If you had any custom code inside this file, then * instead write it inside the "bin/console.js" file. */ await import('./bin/console.js') `) await fs.writeFile(aceFileLocation, aceFileContent) this.ui.logger.info('created ace file', { suffix: this.#getRelativeName(aceFileLocation) }) } /** * Bundles the application to be run in production * * @param stopOnError - Whether to stop the build process on TypeScript errors * @param client - Override the detected package manager * @returns Promise that resolves to true if build succeeded, false otherwise * * @example * const success = await bundler.bundle(true, 'npm') */ async bundle( stopOnError: boolean = true, client?: SupportedPackageManager, options: { tsconfigPath?: string } = {} ): Promise { this.packageManager = client ?? (await this.#detectPackageManager()) ?? 'npm' /** * Step 1: Parse config file to get the build output directory */ const tsConfig = readTsConfig(this.cwdPath, options.tsconfigPath) if (!tsConfig) { return false } const outDir = tsConfig.getNormalizedOutDir() this.ui.logger.info('loading hooks...') this.#hooks = await loadHooks(this.options.hooks, ['init', 'buildStarting', 'buildFinished']) this.#indexGenerator = new IndexGenerator(this.cwdPath, this.ui.logger) /** * Step 2: Run init hook and the index generator */ await this.#hooks.runner('init').run(this, this.#hooks, this.#indexGenerator) this.#hooks.clear('init') this.ui.logger.info('generating indexes...') await this.#indexGenerator.generate() /** * Step 3: Cleanup existing build directory (if any) */ this.ui.logger.info('cleaning up output directory', { suffix: this.#getRelativeName(outDir) }) await this.#cleanupBuildDirectory(outDir) /** * Step 4: Execute build starting hook */ await this.#hooks.runner('buildStarting').run(this) /** * Step 5: Build typescript source code */ this.ui.logger.info('compiling typescript source', { suffix: 'tsc' }) const buildCompleted = await this.#runTsc({ outDir, project: options.tsconfigPath, }) await this.#createAceFile(outDir) /** * Remove incomplete build directory when tsc build * failed and stopOnError is set to true. */ if (!buildCompleted && stopOnError) { await this.#cleanupBuildDirectory(outDir) const instructions = this.ui .sticker() .fullScreen() .drawBorder((borderChar, colors) => colors.red(borderChar)) instructions.add( this.ui.colors.red('Cannot complete the build process as there are TypeScript errors.') ) instructions.add( this.ui.colors.red( 'Use "--ignore-ts-errors" flag to ignore TypeScript errors and continue the build.' ) ) this.ui.logger.logError(instructions.prepare()) return false } /** * Step 6: Copy meta files to the build directory */ const pkgFiles = [ 'package.json', ...SUPPORTED_PACKAGE_MANAGERS[this.packageManager].packageManagerFiles, ] this.ui.logger.info('copying meta files to the output directory') await this.#copyMetaFiles(outDir, pkgFiles) this.ui.logger.success('build completed') this.ui.logger.log('') const displayMessage = this.ui .instructions() .heading('Run the following commands to start the server in production') /** * Step 7: Execute build completed hook */ await this.#hooks.runner('buildFinished').run(this, displayMessage) /** * Display next steps */ displayMessage .add(this.ui.colors.cyan(`cd ${this.#getRelativeName(outDir)}`)) .add(this.ui.colors.cyan(SUPPORTED_PACKAGE_MANAGERS[this.packageManager].installCommand)) .add(this.ui.colors.cyan('node bin/server.js')) .render() return true } }