( wrappedCode: string, muxTypes: string, compilerOptions: ts.CompilerOptions )
| 76 | }; |
| 77 | |
| 78 | function createProgramForCode( |
| 79 | wrappedCode: string, |
| 80 | muxTypes: string, |
| 81 | compilerOptions: ts.CompilerOptions |
| 82 | ): { |
| 83 | program: ts.Program; |
| 84 | host: ts.CompilerHost; |
| 85 | getSourceFile: () => ts.SourceFile; |
| 86 | setSourceFile: (newWrappedCode: string) => void; |
| 87 | } { |
| 88 | const scriptTarget = compilerOptions.target ?? ts.ScriptTarget.ES2020; |
| 89 | let sourceFile = ts.createSourceFile("agent.ts", wrappedCode, scriptTarget, true); |
| 90 | const muxSourceFile = getCachedMuxSourceFile(muxTypes, scriptTarget); |
| 91 | const setSourceFile = (newWrappedCode: string) => { |
| 92 | sourceFile = ts.createSourceFile("agent.ts", newWrappedCode, scriptTarget, true); |
| 93 | }; |
| 94 | const host = ts.createCompilerHost(compilerOptions); |
| 95 | |
| 96 | // Override to read lib files from our bundled directory |
| 97 | host.getDefaultLibLocation = () => LIB_DIR; |
| 98 | host.getDefaultLibFileName = (options) => path.join(LIB_DIR, ts.getDefaultLibFileName(options)); |
| 99 | |
| 100 | const originalGetSourceFile = host.getSourceFile.bind(host); |
| 101 | const originalFileExists = host.fileExists.bind(host); |
| 102 | const originalReadFile = host.readFile.bind(host); |
| 103 | |
| 104 | host.getSourceFile = (fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) => { |
| 105 | // languageVersionOrOptions can be ScriptTarget or CreateSourceFileOptions |
| 106 | const target = |
| 107 | typeof languageVersionOrOptions === "number" ? languageVersionOrOptions : scriptTarget; |
| 108 | if (fileName === "agent.ts") return sourceFile; |
| 109 | if (fileName === MUX_TYPES_FILE) return muxSourceFile; |
| 110 | |
| 111 | const isLibFile = fileName.includes("lib.") && fileName.endsWith(".d.ts"); |
| 112 | if (isLibFile) { |
| 113 | const cached = getCachedLibSourceFile(fileName, target, () => { |
| 114 | if (IS_PRODUCTION) { |
| 115 | const libPath = resolveLibPath(fileName); |
| 116 | return fs.existsSync(libPath) ? fs.readFileSync(libPath, "utf-8") : undefined; |
| 117 | } |
| 118 | return originalReadFile(fileName) ?? undefined; |
| 119 | }); |
| 120 | if (cached) return cached; |
| 121 | } |
| 122 | |
| 123 | return originalGetSourceFile( |
| 124 | fileName, |
| 125 | languageVersionOrOptions, |
| 126 | onError, |
| 127 | shouldCreateNewSourceFile |
| 128 | ); |
| 129 | }; |
| 130 | host.fileExists = (fileName) => { |
| 131 | if (fileName === "agent.ts" || fileName === MUX_TYPES_FILE) return true; |
| 132 | // In production, check bundled lib directory for lib files |
| 133 | if (IS_PRODUCTION && fileName.includes("lib.") && fileName.endsWith(".d.ts")) { |
| 134 | return fs.existsSync(resolveLibPath(fileName)); |
| 135 | } |
no test coverage detected