@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 228 lines 7.99 KB
Raw
1 import { existsSync, readFileSync, statSync } from "node:fs";
2 import path from "node:path";
3 import { resolveTsconfig } from "rolldown/experimental";
4 import { parseSync, transformSync, TsconfigCache, type TransformOptions } from "rolldown/utils";
5 import { resolveCacheDirectory, TransformCache } from "./cache.ts";
6 import type { LoaderOptions } from "./hooks.ts";
7 import { attachSourceMap, storedSourceMap } from "./source-map.ts";
8
9 /** Extensions Oxc transpiles; everything else is JavaScript Node can run. */
10 export const transformExtensions = new Set([".ts", ".tsx", ".mts", ".cts", ".jsx"]);
11
12 export type ModuleFormat = "module" | "commonjs";
13
14 /**
15 * Module format from Node's `load` hook context. Node derives these from the
16 * extension and the nearest `package.json#type`; `*-typescript` variants are
17 * its TypeScript-aware spellings and mean the same thing.
18 */
19 const nodeFormat = (format: string | null | undefined): ModuleFormat | undefined => {
20 switch (format) {
21 case "module":
22 case "module-typescript":
23 return "module";
24 case "commonjs":
25 case "commonjs-typescript":
26 return "commonjs";
27 default:
28 return undefined;
29 }
30 };
31
32 /**
33 * Format of a module Node gave no format for — resolved by our own
34 * resolver, so Node never looked at it: the extension, then the nearest
35 * `package.json#type`, memoized per directory.
36 */
37 const packageTypes = new Map<string, ModuleFormat>();
38 const packageType = (directory: string): ModuleFormat => {
39 let format = packageTypes.get(directory);
40 if (format !== undefined) return format;
41 const packageJson = path.join(directory, "package.json");
42 const parent = path.dirname(directory);
43 if (existsSync(packageJson)) {
44 try {
45 format =
46 JSON.parse(readFileSync(packageJson, "utf8")).type === "module" ? "module" : "commonjs";
47 } catch {
48 format = "commonjs";
49 }
50 } else {
51 format = parent === directory ? "commonjs" : packageType(parent);
52 }
53 packageTypes.set(directory, format);
54 return format;
55 };
56
57 const inferFormat = (filePath: string): ModuleFormat => {
58 const extension = path.extname(filePath);
59 if (extension === ".mts" || extension === ".mjs") return "module";
60 if (extension === ".cts" || extension === ".cjs") return "commonjs";
61 return packageType(path.dirname(filePath));
62 };
63
64 const language = (filePath: string): TransformOptions["lang"] => {
65 switch (path.extname(filePath)) {
66 case ".tsx":
67 return "tsx";
68 case ".ts":
69 case ".mts":
70 case ".cts":
71 return "ts";
72 case ".jsx":
73 return "jsx";
74 default:
75 return "js";
76 }
77 };
78
79 export interface TransformedSource {
80 readonly format: ModuleFormat;
81 readonly source: string;
82 }
83
84 export class SourceTransformer {
85 readonly #options: LoaderOptions;
86 readonly #tsconfigCache = new TsconfigCache();
87 readonly #cache: TransformCache | undefined;
88 /**
89 * Serialized merged tsconfig per discovered config chain. Discovery runs
90 * per file (a solution-style tsconfig assigns files of one directory to
91 * different referenced projects), but thousands of files share a chain
92 * and the serialization is the expensive part of the key.
93 */
94 readonly #tsconfigKeys = new Map<string, string>();
95
96 constructor(options: LoaderOptions) {
97 this.#options = options;
98 const directory = resolveCacheDirectory(options.cache);
99 this.#cache = directory === undefined ? undefined : new TransformCache(directory);
100 }
101
102 /**
103 * Cache key for one transform, or `undefined` when the result must not be
104 * cached. Every input Oxc's output depends on is part of it: the file's
105 * path (source maps name it), its size and mtime standing in for its
106 * contents — a stat instead of a read plus a hash per module on the warm
107 * path — the effective transform options, Node's module format, and the
108 * tsconfig that would be discovered for the file, resolved through the
109 * same cache `transformSync` uses with the `extends` chain already
110 * merged, so editing any tsconfig in the chain is a new key.
111 */
112 #cacheKey(filePath: string, options: TransformOptions, format: ModuleFormat): string | undefined {
113 if (this.#cache === undefined) return undefined;
114 let stat: { size: bigint; mtimeNs: bigint };
115 try {
116 stat = statSync(filePath, { bigint: true });
117 } catch {
118 return undefined;
119 }
120 let tsconfig = "null";
121 try {
122 if (options.tsconfig === true) {
123 const resolved = resolveTsconfig(filePath, this.#tsconfigCache);
124 if (resolved != null) {
125 const chain = resolved.tsconfigFilePaths.join("\0");
126 let serialized = this.#tsconfigKeys.get(chain);
127 if (serialized === undefined) {
128 serialized = JSON.stringify(resolved.tsconfig);
129 this.#tsconfigKeys.set(chain, serialized);
130 }
131 tsconfig = serialized;
132 }
133 } else if (typeof options.tsconfig === "string") {
134 tsconfig = readFileSync(options.tsconfig, "utf8");
135 }
136 } catch {
137 // A broken tsconfig is the transform's error to report; don't cache.
138 return undefined;
139 }
140 return this.#cache.key([
141 filePath,
142 `${stat.size}:${stat.mtimeNs}`,
143 JSON.stringify(options),
144 tsconfig,
145 format,
146 ]);
147 }
148
149 /**
150 * Transpiles `filePath` for Node, or returns `undefined` when the file is
151 * JavaScript that needs no work. `format` is what Node's `load` hook was
152 * told; it decides `sourceType` and the format handed back.
153 */
154 transform(filePath: string, format: string | null | undefined): TransformedSource | undefined {
155 const extension = path.extname(filePath);
156 if (!transformExtensions.has(extension)) return undefined;
157
158 let moduleFormat = nodeFormat(format) ?? inferFormat(filePath);
159 const lang = language(filePath);
160 const options: TransformOptions = {
161 tsconfig: this.#options.tsconfig ?? true,
162 sourcemap: true,
163 lang,
164 };
165 // The key is taken before the source is read so a hit costs one stat
166 // and one cache read, never the source itself.
167 const key = this.#cacheKey(filePath, options, moduleFormat);
168 const cached = key === undefined ? undefined : this.#cache?.get(key);
169 if (cached !== undefined) {
170 const { mapFile } = cached;
171 return {
172 format: cached.format,
173 source:
174 mapFile === undefined
175 ? cached.code
176 : attachSourceMap(
177 cached.code,
178 { file: mapFile, text: () => readFileSync(mapFile, "utf8") },
179 () => readFileSync(filePath, "utf8"),
180 ),
181 };
182 }
183 const source = readFileSync(filePath, "utf8");
184 // A `.ts` file in a CommonJS package that uses `import`/`export` runs
185 // as ESM — the same call Node's own module-syntax detection makes for
186 // `.js`. Explicit `.cts` stays CommonJS regardless.
187 if (
188 moduleFormat === "commonjs" &&
189 extension !== ".cts" &&
190 parseSync(filePath, source, { lang, sourceType: "unambiguous" }).module.hasModuleSyntax
191 ) {
192 moduleFormat = "module";
193 }
194 const transformed = transformSync(
195 filePath,
196 source,
197 { ...options, sourceType: moduleFormat },
198 this.#tsconfigCache,
199 );
200 if (transformed.errors.length > 0) {
201 const [error] = transformed.errors;
202 throw error instanceof Error
203 ? error
204 : new SyntaxError(
205 `${filePath}: ${(error as { message?: string }).message ?? String(error)}`,
206 );
207 }
208 const map =
209 transformed.map === undefined ? undefined : storedSourceMap(transformed.map, filePath);
210 // The map is stored next to the cache entry and referenced by path; see
211 // `attachSourceMap` for when it is inlined instead.
212 const mapFile =
213 key === undefined || map === undefined
214 ? undefined
215 : this.#cache?.set(key, {
216 format: moduleFormat,
217 code: transformed.code,
218 map,
219 });
220 return {
221 format: moduleFormat,
222 source:
223 map === undefined
224 ? transformed.code
225 : attachSourceMap(transformed.code, { file: mapFile, text: () => map }, () => source),
226 };
227 }
228 }