๐Ÿ“ฆ colinhacks / zshy

๐Ÿ“„ compile.ts ยท 302 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302import * as fs from "node:fs";
import * as path from "node:path";
import * as ts from "typescript";
import { createCjsInteropTransformer } from "./tx-cjs-interop.js";
import { createCjsInteropDeclarationTransformer } from "./tx-cjs-interop-declaration.js";
import { createExportEqualsTransformer } from "./tx-export-equals.js";
import { createExtensionRewriteTransformer } from "./tx-extension-rewrite.js";
import { createImportMetaShimTransformer } from "./tx-import-meta-shim.js";
import { createPathsResolverTransformer } from "./tx-paths-resolver.js";
import * as utils from "./utils.js";

export interface BuildContext {
  writtenFiles: Set<string>;
  copiedAssets: Set<string>;
  errorCount: number;
  warningCount: number;
}

export interface ProjectOptions {
  configPath: string;
  compilerOptions: ts.CompilerOptions & Required<Pick<ts.CompilerOptions, "module" | "moduleResolution" | "outDir">>;
  ext: "cjs" | "js" | "mjs";
  format: "cjs" | "esm";
  pkgJsonDir: string; // Add package root for relative path display
  rootDir: string; // Add source root for asset copying
  verbose: boolean;
  dryRun: boolean;
  cjsInterop?: boolean; // Enable CJS interop for single default exports
  paths?: Record<string, string[]>; // TypeScript paths configuration
  baseUrl?: string; // TypeScript baseUrl configuration
}

export async function compileProject(config: ProjectOptions, entryPoints: string[], ctx: BuildContext): Promise<void> {
  // Deduplicate entry points before compilation

  // Track asset imports encountered during transformation
  const assetImports = new Set<string>();

  // Create compiler host
  const host = ts.createCompilerHost(config.compilerOptions);
  const originalWriteFile = host.writeFile;

  const jsExt = "." + config.ext;
  const dtsExt = config.ext === "mjs" ? ".d.mts" : config.ext === "cjs" ? ".d.cts" : ".d.ts";

  // Track if we should write files (will be set after diagnostics check)
  let shouldWriteFiles = true;

  host.writeFile = (fileName, data, writeByteOrderMark, onError, sourceFiles) => {
    // Transform output file extensions
    let outputFileName = fileName;
    const processedData = data;
    if (fileName.endsWith(".js")) {
      outputFileName = fileName.replace(/\.js$/, jsExt);
    }

    if (fileName.endsWith(".d.ts")) {
      outputFileName = fileName.replace(/\.d\.ts$/, dtsExt);
    }
    // Handle source map files
    if (fileName.endsWith(".js.map")) {
      outputFileName = fileName.replace(/\.js\.map$/, jsExt + ".map");
    }

    if (fileName.endsWith(".d.ts.map")) {
      outputFileName = fileName.replace(/\.d\.ts\.map$/, dtsExt + ".map");
    }

    // Track the file that would be written
    ctx.writtenFiles.add(outputFileName);

    if (!config.dryRun && shouldWriteFiles && originalWriteFile) {
      originalWriteFile(outputFileName, processedData, writeByteOrderMark, onError, sourceFiles);
    }
  };

  // Create the TypeScript program using unique entry points
  // For CJS builds, set noEmitOnError to false to allow emission despite ts1343 errors
  const programOptions = config.compilerOptions;

  const program = ts.createProgram({
    rootNames: entryPoints,
    options: programOptions,
    host,
  });

  // Create a transformer factory to resolve tsconfig paths
  const pathsResolverTransformer = config.paths
    ? createPathsResolverTransformer({
        baseUrl: config.baseUrl,
        paths: config.paths,
        tsconfigDir: path.dirname(config.configPath),
        rootDir: config.rootDir,
      })
    : null;

  // Create a transformer factory to rewrite extensions
  const extensionRewriteTransformer = createExtensionRewriteTransformer({
    rootDir: config.rootDir,
    ext: jsExt,
    onAssetImport: (assetPath: string) => {
      assetImports.add(assetPath);
    },
  });

  // Check for semantic errors
  const diagnostics = ts.getPreEmitDiagnostics(program);

  if (diagnostics.length > 0) {
    // Filter out ts1343 errors for CJS builds
    const filteredDiagnostics = diagnostics.filter((d) => {
      if (config.format === "cjs") {
        return d.code !== 1343 && d.code !== 1259;
      }
    }); // Ignore ts1343 (import.meta not available) for CJS

    const errorCount = filteredDiagnostics.filter((d) => d.category === ts.DiagnosticCategory.Error).length;
    const warningCount = filteredDiagnostics.filter((d) => d.category === ts.DiagnosticCategory.Warning).length;

    // Update the build context with error and warning counts
    ctx.errorCount += errorCount;
    ctx.warningCount += warningCount;

    // Set shouldWriteFiles to false if there are errors (excluding ts1343 for CJS)
    if (errorCount > 0) {
      shouldWriteFiles = false;
    }

    if (errorCount > 0 || warningCount > 0) {
      utils.log.warn(`Found ${errorCount} error(s) and ${warningCount} warning(s)`);
    }

    // Format diagnostics with color and context like tsc, keeping original order
    const formatHost: ts.FormatDiagnosticsHost = {
      getCurrentDirectory: () => process.cwd(),
      getCanonicalFileName: (fileName) => fileName,
      getNewLine: () => ts.sys.newLine,
    };

    // Keep errors and warnings intermixed in their original order
    const relevantDiagnostics = filteredDiagnostics.filter(
      (d) => d.category === ts.DiagnosticCategory.Error || d.category === ts.DiagnosticCategory.Warning
    );

    if (relevantDiagnostics.length > 0) {
      console.log(ts.formatDiagnosticsWithColorAndContext(relevantDiagnostics, formatHost));
    }
  }

  // Prepare transformers
  const before: ts.TransformerFactory<ts.SourceFile>[] = [];

  // Add paths resolver transformer first if paths are configured
  if (pathsResolverTransformer) {
    before.push(pathsResolverTransformer as ts.TransformerFactory<ts.SourceFile>);
  }

  // Then add extension rewriter
  before.push(extensionRewriteTransformer as ts.TransformerFactory<ts.SourceFile>);

  const after: ts.TransformerFactory<ts.SourceFile>[] = [];
  const afterDeclarations: ts.TransformerFactory<ts.SourceFile | ts.Bundle>[] = [];

  // Add transformers for declarations
  if (pathsResolverTransformer) {
    afterDeclarations.push(pathsResolverTransformer);
  }
  afterDeclarations.push(extensionRewriteTransformer);

  // Add import.meta shim transformer for CJS builds
  if (config.format === "cjs") {
    before.unshift(createImportMetaShimTransformer());
  }

  // Add export = to export default transformer for ESM builds
  if (config.format === "esm") {
    createExportEqualsTransformer<ts.SourceFile>();
    // before.push(createExportEqualsTransformer<ts.SourceFile>());
    // afterDeclarations.push(createExportEqualsTransformer<ts.SourceFile | ts.Bundle>());
  }

  // Add CJS interop transformer for single default exports
  if (config.cjsInterop && config.format === "cjs") {
    if (config.verbose) {
      utils.log.info(`Enabling CJS interop transform...`);
    }
    before.push(createCjsInteropTransformer());
  }

  // Add CJS interop transformer for declaration files (export = transformation)
  if (config.cjsInterop && config.format === "cjs") {
    afterDeclarations.push(createCjsInteropDeclarationTransformer());
  }

  // emit the files
  const emitResult = program.emit(undefined, undefined, undefined, undefined, {
    before,
    after,
    afterDeclarations,
  });

  if (emitResult.emitSkipped) {
    utils.log.error("Emit was skipped due to errors");
  } else {
    // console.log(`โœ… Emitted ${config.jsExtension} and ${config.dtsExtension}
    // files`);
  }

  // Report any emit diagnostics
  if (emitResult.diagnostics.length > 0) {
    // Filter out ts1343 errors for CJS builds
    const filteredEmitDiagnostics =
      config.format === "cjs"
        ? emitResult.diagnostics.filter((d) => d.code !== 1343) // Ignore ts1343 for CJS
        : emitResult.diagnostics;

    const emitErrors = filteredEmitDiagnostics.filter((d) => d.category === ts.DiagnosticCategory.Error);
    const emitWarnings = filteredEmitDiagnostics.filter((d) => d.category === ts.DiagnosticCategory.Warning);

    // Update the build context with emit error and warning counts
    ctx.errorCount += emitErrors.length;
    ctx.warningCount += emitWarnings.length;

    utils.log.error(
      `Found ${emitErrors.length} error(s) and ${emitWarnings.length} warning(s) during emit:`
    );
    console.log();

    const formatHost: ts.FormatDiagnosticsHost = {
      getCurrentDirectory: () => process.cwd(),
      getCanonicalFileName: (fileName) => fileName,
      getNewLine: () => ts.sys.newLine,
    };

    // Keep errors and warnings intermixed in their original order
    const relevantEmitDiagnostics = filteredEmitDiagnostics.filter(
      (d) => d.category === ts.DiagnosticCategory.Error || d.category === ts.DiagnosticCategory.Warning
    );

    if (relevantEmitDiagnostics.length > 0) {
      console.log(ts.formatDiagnosticsWithColorAndContext(relevantEmitDiagnostics, formatHost));
    }
  }

  // Copy assets if any were found and rootDir is provided
  if (assetImports.size > 0) {
    if (config.verbose) {
      utils.log.info(`Found ${assetImports.size} asset import(s), copying to output directory...`);
    }

    // utils.copyAssets(assetImports, config, ctx);
    for (const assetPath of assetImports) {
      try {
        // Asset paths are now relative to rootDir
        const sourceFile = path.resolve(config.rootDir, assetPath);

        if (!fs.existsSync(sourceFile)) {
          if (config.verbose) {
            utils.log.warn(`Asset not found: ${assetPath} (resolved to ${sourceFile})`);
          }
          continue;
        }

        // Create the destination path in outDir, maintaining the same relative structure
        const destFile = path.resolve(config.compilerOptions.outDir, assetPath);
        const posixDestFile = utils.toPosix(destFile);

        // Skip if this asset has already been copied
        if (ctx.copiedAssets.has(posixDestFile)) {
          continue;
        }

        const destDir = path.dirname(destFile);

        // Track the file that would be copied
        // Use posix paths here because typescript also outputs them posix
        // style.
        ctx.writtenFiles.add(posixDestFile);
        ctx.copiedAssets.add(posixDestFile);

        if (!config.dryRun) {
          // Ensure destination directory exists
          fs.mkdirSync(destDir, { recursive: true });

          // Copy the file
          fs.copyFileSync(sourceFile, destFile);
        }

        if (config.verbose) {
          const relativeSource = config.pkgJsonDir ? utils.relativePosix(config.pkgJsonDir, sourceFile) : sourceFile;
          const relativeDest = config.pkgJsonDir ? utils.relativePosix(config.pkgJsonDir, destFile) : destFile;
          utils.log.info(
            `${config.dryRun ? "[dryrun] " : ""}Copied asset: ./${relativeSource} โ†’ ./${relativeDest}`
          );
        }
      } catch (error) {
        utils.log.error(`Failed to copy asset ${assetPath}: ${error}`);
      }
    }
  }
}