Skip to content

Commit eab48a3

Browse files
authored
fix: type-check included files missed by transform (type-only files) (#345)
* fix: type-check `include`d files missed by transform (type-only files) - type-only files never get processed by Rollup as their imports are elided/removed by TS in the resulting compiled JS file - so, as a workaround, make sure that all files in the `tsconfig` `include` (i.e. in `parsedConfig.fileNames`) are also type-checked - note that this will not catch _all_ type-only imports, in particular if one is using `tsconfig` `files` (or in general _not_ using glob patterns in `include`) -- this is just a workaround, that requires a separate fix - we do the same process for generating declarations for "missed" files right now in `_onwrite`, so basically do the same thing but for type-checking in `_ongenerate` (_technically_ speaking, there could be full TS files (i.e. _not_ type-only) that are in the `include` and weren't transformed - these would basically be independent TS files not part of the bundle that the user wanted type-checking and declarations for (as we _already_ generate declarations for those files)) * move misssed type-checking to `buildEnd` hook, remove declarations check - `buildEnd` is a more correct place for it, since this does not generate any output files - (unlike the missed declarations) - and this means it's only called once per build, vs. once per output - remove the check against the `declarations` dict as one can type-check without outputting declarations - i.e. if `declaration: false`; not the most common use-case for rpt2, but it is one * add new checkedFiles Set to not duplicate type-checking - since `parsedConfig.fileNames` could include files that were already checked during the `transform` hook - and because `declarations` dict is empty when `declaration: false`, so can't check against that * move checkedFiles.add to the beginning of typecheckFile - because printing diagnostics can bail if the category was error - that can result in a file being type-checked but not added to checkedFiles * wip: fuse _ongenerate functionality into buildEnd, _onwrite into generateBundle - per ezolenko, the whole generateRound etc stuff was a workaround because the buildEnd hook actually _didn't exist_ before - so now that it does, we can use it to simplify some logic - no longer need `_ongenerate` as that should be in `buildEnd`, and no longer need `_onwrite` as it is the only thing called in `generateBundle`, so just combine them - importantly, `buildEnd` also occurs before output generation, so this ensures that type-checking still occurs even if `bundle.generate()` is not called - also move the `walkTree` call to above the "missed" type-checking as it needs to come first - it does unconditional type-checking once per watch cycle, whereas "missed" only type-checks those that were, well, "missed" - so in order to not have duplication, make "missed" come after, when the `checkedFiles` Set has been filled by `walkTree` already - and for simplification, just return early on error to match the current behavior - in the future, may want to print the error and continue type-checking other files - so that all type-check errors are reported, not just the first one NOTE: this is WIP because the `cache.done()` call and the `!noErrors` message are incorrectly blocked behind the `pluginOptions.check` conditional right now - `cache.done()` needs to be called regardless of check or error or not, i.e. in all scenarios - but ideally it should be called after all the type-checking here - `!noErrors` should be logged regardless of check or not - and similarly, after the type-checking * call `cache().done()` and `!noErrors` in check and non-check conditions - instead of making a big `if` statement, decided to split out a `buildDone` function - to always call at the end of the input phase - we can also move the `cache().done()` in `emitSkipped` into `buildEnd`, as `buildEnd` gets called when an error occurs as well - and this way we properly print for errors as well - `buildDone` will have more usage in other PRs as well, so I figure it makes sense to split it out now as well * use `RollupContext` for type-only files - i.e. bail out when `abortOnError: true`, which `ConsoleContext` can't do - `ConsoleContext` is basically meant for everywhere `RollupContext` can't be used - which is effectively only in the `options` hook, per the Rollup docs: https://rollupjs.org/guide/en/#options * add test for type-only file with type errors - now that the integration tests exist, we can actually test this scenario - refactor: give each test their own `onwarn` mock when necessary - while `restoreMocks` is set in the `jest.config.js`, Jest apparently has poor isolation of mocks: jestjs/jest#7136 - if two tests ran in parallel, `onwarn` was getting results from both, screwing up the `toBeCalledTimes` number - couldn't get the syntax error to work with `toBeCalledTimes` either - if no mock is given, it _does_ print warnings, but if a mock is given, it doesn't print, yet isn't called? - I think the mock is getting screwed up by the error being thrown here; maybe improperly saved or something
1 parent af271af commit eab48a3

File tree

4 files changed

+97
-35
lines changed

4 files changed

+97
-35
lines changed

__tests__/integration/errors.spec.ts

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { jest, afterAll, test, expect } from "@jest/globals";
2+
import { Mock } from "jest-mock"
23
import * as path from "path";
34
import { normalizePath as normalize } from "@rollup/pluginutils";
45
import * as fs from "fs-extra";
@@ -11,15 +12,14 @@ jest.setTimeout(15000);
1112

1213
const local = (x: string) => path.resolve(__dirname, x);
1314
const cacheRoot = local("__temp/errors/rpt2-cache"); // don't use the one in node_modules
14-
const onwarn = jest.fn();
1515

1616
afterAll(async () => {
1717
// workaround: there seems to be some race condition causing fs.remove to fail, so give it a sec first (c.f. https://github.com/jprichardson/node-fs-extra/issues/532)
1818
await new Promise(resolve => setTimeout(resolve, 1000));
1919
await fs.remove(cacheRoot);
2020
});
2121

22-
async function genBundle(relInput: string, extraOpts?: RPT2Options) {
22+
async function genBundle(relInput: string, extraOpts?: RPT2Options, onwarn?: Mock) {
2323
const input = normalize(local(`fixtures/errors/${relInput}`));
2424
return helpers.genBundle({
2525
input,
@@ -42,9 +42,10 @@ test("integration - semantic error", async () => {
4242
});
4343

4444
test("integration - semantic error - abortOnError: false / check: false", async () => {
45+
const onwarn = jest.fn();
4546
// either warning or not type-checking should result in the same bundle
46-
const { output } = await genBundle("semantic.ts", { abortOnError: false });
47-
const { output: output2 } = await genBundle("semantic.ts", { check: false });
47+
const { output } = await genBundle("semantic.ts", { abortOnError: false }, onwarn);
48+
const { output: output2 } = await genBundle("semantic.ts", { check: false }, onwarn);
4849
expect(output).toEqual(output2);
4950

5051
expect(output[0].fileName).toEqual("index.js");
@@ -59,7 +60,38 @@ test("integration - syntax error", () => {
5960
});
6061

6162
test("integration - syntax error - abortOnError: false / check: false", () => {
63+
const onwarn = jest.fn();
6264
const err = "Unexpected token (Note that you need plugins to import files that are not JavaScript)";
63-
expect(genBundle("syntax.ts", { abortOnError: false })).rejects.toThrow(err);
64-
expect(genBundle("syntax.ts", { check: false })).rejects.toThrow(err);
65+
expect(genBundle("syntax.ts", { abortOnError: false }, onwarn)).rejects.toThrow(err);
66+
expect(genBundle("syntax.ts", { check: false }, onwarn)).rejects.toThrow(err);
67+
});
68+
69+
const typeOnlyIncludes = ["**/import-type-error.ts", "**/type-only-import-with-error.ts"];
70+
71+
test("integration - type-only import error", () => {
72+
expect(genBundle("import-type-error.ts", {
73+
include: typeOnlyIncludes,
74+
})).rejects.toThrow("Property 'nonexistent' does not exist on type 'someObj'.");
75+
});
76+
77+
test("integration - type-only import error - abortOnError: false / check: false", async () => {
78+
const onwarn = jest.fn();
79+
// either warning or not type-checking should result in the same bundle
80+
const { output } = await genBundle("import-type-error.ts", {
81+
include: typeOnlyIncludes,
82+
abortOnError: false,
83+
}, onwarn);
84+
const { output: output2 } = await genBundle("import-type-error.ts", {
85+
include: typeOnlyIncludes,
86+
check: false,
87+
}, onwarn);
88+
expect(output).toEqual(output2);
89+
90+
expect(output[0].fileName).toEqual("index.js");
91+
expect(output[1].fileName).toEqual("import-type-error.d.ts");
92+
expect(output[2].fileName).toEqual("import-type-error.d.ts.map");
93+
expect(output[3].fileName).toEqual("type-only-import-with-error.d.ts");
94+
expect(output[4].fileName).toEqual("type-only-import-with-error.d.ts.map");
95+
expect(output.length).toEqual(5); // no other files
96+
expect(onwarn).toBeCalledTimes(1);
6597
});
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// this file has no errors itself; it is used an entry file to test an error in a type-only import
2+
3+
export type { typeError } from "./type-only-import-with-error";
4+
5+
// some code so this file isn't empty
6+
export function sum(a: number, b: number) {
7+
return a + b;
8+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
type someObj = {};
2+
export type typeError = someObj['nonexistent'];

src/index.ts

Lines changed: 49 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { relative, dirname, normalize as pathNormalize, resolve } from "path";
22
import * as tsTypes from "typescript";
3-
import { PluginImpl, PluginContext, InputOptions, OutputOptions, TransformResult, SourceMap, Plugin } from "rollup";
3+
import { PluginImpl, InputOptions, TransformResult, SourceMap, Plugin } from "rollup";
44
import { normalizePath as normalize } from "@rollup/pluginutils";
55
import { blue, red, yellow, green } from "colors/safe";
66
import findCacheDir from "find-cache-dir";
@@ -33,6 +33,7 @@ const typescript: PluginImpl<RPT2Options> = (options) =>
3333
let service: tsTypes.LanguageService;
3434
let noErrors = true;
3535
const declarations: { [name: string]: { type: tsTypes.OutputFile; map?: tsTypes.OutputFile } } = {};
36+
const checkedFiles = new Set<string>();
3637

3738
let _cache: TsCache;
3839
const cache = (): TsCache =>
@@ -55,13 +56,24 @@ const typescript: PluginImpl<RPT2Options> = (options) =>
5556

5657
const typecheckFile = (id: string, snapshot: tsTypes.IScriptSnapshot, tcContext: IContext) =>
5758
{
59+
checkedFiles.add(id); // must come before print, as that could bail
60+
5861
const diagnostics = getDiagnostics(id, snapshot);
5962
printDiagnostics(tcContext, diagnostics, parsedConfig.options.pretty !== false);
6063

6164
if (diagnostics.length > 0)
6265
noErrors = false;
6366
}
6467

68+
/** to be called at the end of Rollup's build phase, before output generation */
69+
const buildDone = (): void =>
70+
{
71+
if (!watchMode && !noErrors)
72+
context.info(yellow("there were errors or warnings."));
73+
74+
cache().done();
75+
}
76+
6577
const pluginOptions: IOptions = Object.assign({},
6678
{
6779
check: true,
@@ -86,7 +98,7 @@ const typescript: PluginImpl<RPT2Options> = (options) =>
8698
}
8799
setTypescriptModule(pluginOptions.typescript);
88100

89-
const self: Plugin & { _ongenerate: () => void, _onwrite: (this: PluginContext, _output: OutputOptions) => void } = {
101+
const self: Plugin = {
90102

91103
name: "rpt2",
92104

@@ -141,6 +153,7 @@ const typescript: PluginImpl<RPT2Options> = (options) =>
141153
{
142154
const key = normalize(id);
143155
delete declarations[key];
156+
checkedFiles.delete(key);
144157
},
145158

146159
resolveId(importee, importer)
@@ -201,9 +214,7 @@ const typescript: PluginImpl<RPT2Options> = (options) =>
201214
noErrors = false;
202215
// always checking on fatal errors, even if options.check is set to false
203216
typecheckFile(id, snapshot, contextWrapper);
204-
205217
// since no output was generated, aborting compilation
206-
cache().done();
207218
this.error(red(`failed to transpile '${id}'`));
208219
}
209220

@@ -254,28 +265,22 @@ const typescript: PluginImpl<RPT2Options> = (options) =>
254265

255266
buildEnd(err)
256267
{
257-
if (!err)
258-
return
259-
260-
// workaround: err.stack contains err.message and Rollup prints both, causing duplication, so split out the stack itself if it exists (c.f. https://github.com/ezolenko/rollup-plugin-typescript2/issues/103#issuecomment-1172820658)
261-
const stackOnly = err.stack?.split(err.message)[1];
262-
if (stackOnly)
263-
this.error({ ...err, message: err.message, stack: stackOnly });
264-
else
265-
this.error(err);
266-
},
267-
268-
generateBundle(bundleOptions)
269-
{
270-
self._ongenerate();
271-
self._onwrite.call(this, bundleOptions);
272-
},
268+
if (err)
269+
{
270+
buildDone();
271+
// workaround: err.stack contains err.message and Rollup prints both, causing duplication, so split out the stack itself if it exists (c.f. https://github.com/ezolenko/rollup-plugin-typescript2/issues/103#issuecomment-1172820658)
272+
const stackOnly = err.stack?.split(err.message)[1];
273+
if (stackOnly)
274+
this.error({ ...err, message: err.message, stack: stackOnly });
275+
else
276+
this.error(err);
277+
}
273278

274-
_ongenerate(): void
275-
{
276-
context.debug(() => `generating target ${generateRound + 1}`);
279+
if (!pluginOptions.check)
280+
return buildDone();
277281

278-
if (pluginOptions.check && watchMode && generateRound === 0)
282+
// walkTree once on each cycle when in watch mode
283+
if (watchMode)
279284
{
280285
cache().walkTree((id) =>
281286
{
@@ -288,15 +293,30 @@ const typescript: PluginImpl<RPT2Options> = (options) =>
288293
});
289294
}
290295

291-
if (!watchMode && !noErrors)
292-
context.info(yellow("there were errors or warnings."));
296+
const contextWrapper = new RollupContext(pluginOptions.verbosity, pluginOptions.abortOnError, this, "rpt2: ");
293297

294-
cache().done();
295-
generateRound++;
298+
// type-check missed files as well
299+
parsedConfig.fileNames.forEach((name) =>
300+
{
301+
const key = normalize(name);
302+
if (checkedFiles.has(key) || !filter(key)) // don't duplicate if it's already been checked
303+
return;
304+
305+
context.debug(() => `type-checking missed '${key}'`);
306+
307+
const snapshot = servicesHost.getScriptSnapshot(key);
308+
if (snapshot)
309+
typecheckFile(key, snapshot, contextWrapper);
310+
});
311+
312+
buildDone();
296313
},
297314

298-
_onwrite(this: PluginContext, _output: OutputOptions): void
315+
generateBundle(this, _output)
299316
{
317+
context.debug(() => `generating target ${generateRound + 1}`);
318+
generateRound++;
319+
300320
if (!parsedConfig.options.declaration)
301321
return;
302322

0 commit comments

Comments
 (0)