diff --git a/tsc/internal/execute/incremental/program.go b/tsc/internal/execute/incremental/program.go index 1cb83801fd70a..42221ba4ae0dc 100644 --- a/tsc/internal/execute/incremental/program.go +++ b/tsc/internal/execute/incremental/program.go @@ -117,6 +117,23 @@ func (p *Program) GetProgram() *compiler.Program { return p.program } +func (p *Program) ForEachEmittedDeclarationFile(action func(tspath.RootedFilePath, *ast.SourceFile)) { + p.panicIfNoProgram("ForEachEmittedDeclarationFile") + if p.Options().NoEmit.IsTrue() { + return + } + p.snapshot.emitSignatures.Range(func(path tspath.PathKey, _ *emitSignature) bool { + sourceFile := p.program.GetSourceFileByPath(path) + if sourceFile != nil && p.program.SourceFileMayBeEmitted(sourceFile, false) { + output := outputpaths.GetOutputPathsFor(sourceFile, p.Options(), p.program, outputpaths.ForceEmitPaths{}).DeclarationFilePath() + if output != "" { + action(output, sourceFile) + } + } + return true + }) +} + func (p *Program) HasChangedDtsFile() bool { return p.snapshot.hasChangedDtsFile } diff --git a/tsc/internal/execute/tsctests/contentmapper_watch_test.go b/tsc/internal/execute/tsctests/contentmapper_watch_test.go index cb8d9aaa372ba..1dc8b0002e6d9 100644 --- a/tsc/internal/execute/tsctests/contentmapper_watch_test.go +++ b/tsc/internal/execute/tsctests/contentmapper_watch_test.go @@ -567,6 +567,54 @@ func TestContentMapperWatchManifestChangeIgnoresCase(t *testing.T) { assert.Equal(t, spawner.closes.Load(), int32(1)) } +func TestContentMapperWatchNewUppercaseExtension(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + ignoreCase bool + }{ + {name: "case sensitive"}, + {name: "case insensitive", ignoreCase: true}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + synctest.Test(t, func(t *testing.T) { + const root = "/home/src/workspaces/project/" + testSys := newTestSys(&tscInput{ + ignoreCase: test.ignoreCase, + files: FileMap{ + root + "tsconfig.json": `{ + "compilerOptions":{"listFiles":true}, + "contentMappers":[{"package":"mapper","extensions":[".BOX"]}] + }`, + root + "first.ts": "export const first = 1;", + root + "node_modules/mapper/package.json": contentmappertest.PackageJSON(contentmappertest.VerbatimMapper), + }, + }, false) + sys := &recordingContentMapperSystem{ + TestSys: testSys, + spawner: &recordingContentMapperSpawner{inner: contentmappertest.NewSpawner()}, + } + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + result := execute.CommandLine(ctx, sys, []string{"--watch", "--runExternalCode"}, testSys) + w := result.Watcher.(*execute.Watcher) + assert.Assert(t, !strings.Contains(testSys.getOutput(false), "error TS"), testSys.getOutput(false)) + + path := root + "new.BOX" + testSys.writeFileNoError(path, "export const added = 2;") + testSys.clearOutput() + builds := w.FullBuilds() + testSys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: path}}) + w.DoCycle(ctx) + assert.Equal(t, w.FullBuilds(), builds+1) + // The root-file set must refresh even if compiling the newly discovered file reports an error. + assert.Assert(t, strings.Contains(testSys.getOutput(false), path), testSys.getOutput(false)) + }) + }) + } +} + func TestContentMapperBuildWatchSymlinkedManifestDelete(t *testing.T) { t.Parallel() const manifestTarget = "/home/src/workspaces/mapper/package.json" diff --git a/tsc/internal/execute/tsctests/watch_shallow_test.go b/tsc/internal/execute/tsctests/watch_shallow_test.go index 48eeac0f0f1c5..14add70bd802b 100644 --- a/tsc/internal/execute/tsctests/watch_shallow_test.go +++ b/tsc/internal/execute/tsctests/watch_shallow_test.go @@ -2,6 +2,7 @@ package tsctests import ( "context" + "fmt" "strings" "testing" @@ -11,6 +12,466 @@ import ( "gotest.tools/v3/assert" ) +func TestWatchWildcardFiltersFiles(t *testing.T) { + t.Parallel() + for _, allowJS := range []bool{false, true} { + t.Run(fmt.Sprintf("allowJs=%v", allowJS), func(t *testing.T) { + t.Parallel() + sys := newTestSys(&tscInput{ + cwd: "/app", + files: FileMap{ + "/app/tsconfig.json": fmt.Sprintf(`{"compilerOptions":{"allowJs":%v,"declaration":true,"sourceMap":true,"outDir":"out","noLib":true},"include":["**/*"]}`, allowJS), + "/app/index.ts": `export const x = 1;`, + }, + }, false) + result := execute.CommandLine(t.Context(), sys, []string{"--watch"}, sys) + w := result.Watcher.(*execute.Watcher) + for _, name := range []string{"index.js", "index.d.ts", "index.js.map"} { + assert.Assert(t, sys.fsFromFileMap().FileExists(tspath.RootedFilePathFromNormalized("/app/out/"+name))) + } + checkIgnored := func(path string, kind fswatch.EventKind) { + t.Helper() + builds := w.FullBuilds() + w.FastPathBuilds() + sys.clearOutput() + sys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: kind, Path: path}}) + w.DoCycle(t.Context()) + if got := w.FullBuilds() + w.FastPathBuilds(); got != builds { + t.Errorf("unexpected rebuild for %s (%s): builds changed from %d to %d", path, kind, builds, got) + } + if strings.Contains(sys.getOutput(false), "File change detected") { + t.Errorf("unexpected compilation for %s (%s)", path, kind) + } + } + for _, path := range []string{"/app/build.log", "/app/out/index.js", "/app/out/index.d.ts", "/app/out/index.js.map"} { + sys.writeFileNoError(path, "unrelated") + checkIgnored(path, fswatch.EventUpdate) + sys.removeNoError(path) + checkIgnored(path, fswatch.EventDelete) + } + if !allowJS { + sys.writeFileNoError("/app/unrelated.js", "const unrelated = 1;") + checkIgnored("/app/unrelated.js", fswatch.EventUpdate) + } + + extension := ".ts" + if allowJS { + extension = ".js" + } + path := "/app/new" + extension + sys.writeFileNoError(path, "export const added = 2;") + sys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: path}}) + w.DoCycle(t.Context()) + assert.Assert(t, strings.Contains(sys.readFileNoError("/app/out/new.js"), "added = 2")) + + sys.writeFileNoError("/app/index.ts", "export const x = 3;") + sys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: "/app/index.ts"}}) + w.DoCycle(t.Context()) + assert.Assert(t, strings.Contains(sys.readFileNoError("/app/out/index.js"), "x = 3")) + }) + } +} + +func TestWatchWildcardDirectoryEvents(t *testing.T) { + t.Parallel() + sys := newTestSys(&tscInput{ + cwd: "/app", + files: FileMap{ + "/app/tsconfig.json": `{"compilerOptions":{"outDir":"out","noLib":true,"listFiles":true},"include":["**/*"]}`, + "/app/index.ts": `export const x = 1;`, + }, + }, false) + result := execute.CommandLine(t.Context(), sys, []string{"--watch"}, sys) + w := result.Watcher.(*execute.Watcher) + + // Deliver only the directory event, as when a populated directory is moved into the project. + sys.writeFileNoError("/app/generated.log/added.ts", "export const added = 2;") + sys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: "/app/generated.log"}}) + w.DoCycle(t.Context()) + assert.Assert(t, strings.Contains(sys.readFileNoError("/app/out/generated.log/added.js"), "added = 2")) + assert.Assert(t, strings.Contains(sys.getOutput(false), "/app/generated.log/added.ts")) + + sys.removeNoError("/app/generated.log/added.ts") + sys.removeNoError("/app/generated.log") + builds := w.FullBuilds() + sys.clearOutput() + sys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventDelete, Path: "/app/generated.log"}}) + w.DoCycle(t.Context()) + assert.Equal(t, w.FullBuilds(), builds+1) + assert.Assert(t, !strings.Contains(sys.getOutput(false), "/app/generated.log/added.ts"), + "the removed directory's source must no longer belong to the program") +} + +func TestWatchWildcardFiltersSameDirectoryOutputs(t *testing.T) { + t.Parallel() + sys := newTestSys(&tscInput{ + cwd: "/app", + files: FileMap{ + "/app/tsconfig.json": `{"compilerOptions":{"allowJs":true,"declaration":true},"include":["**/*"]}`, + "/app/index.ts": `export const value = 1;`, + }, + }, false) + result := execute.CommandLine(t.Context(), sys, []string{"--watch"}, sys) + w := result.Watcher.(*execute.Watcher) + for _, path := range []string{"/app/index.js", "/app/index.d.ts"} { + assert.Assert(t, sys.fsFromFileMap().FileExists(tspath.RootedFilePathFromNormalized(path))) + for _, kind := range []fswatch.EventKind{fswatch.EventUpdate, fswatch.EventDelete} { + builds := w.FullBuilds() + w.FastPathBuilds() + sys.clearOutput() + if kind == fswatch.EventDelete { + sys.removeNoError(path) + } + sys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: kind, Path: path}}) + w.DoCycle(t.Context()) + if got := w.FullBuilds() + w.FastPathBuilds(); got != builds { + t.Errorf("unexpected compilation for %s (%s): builds changed from %d to %d", path, kind, builds, got) + } + if strings.Contains(sys.getOutput(false), "File change detected") { + t.Errorf("unexpected compilation status for %s (%s)", path, kind) + } + } + } +} + +func TestWatchWildcardUnwrittenDeclarationIsInput(t *testing.T) { + t.Parallel() + sys := newTestSys(&tscInput{ + cwd: "/app", + files: FileMap{ + "/app/tsconfig.json": `{ + "compilerOptions":{"declaration":true,"declarationDir":"types","rootDir":"src","noEmitOnError":true,"listFiles":true}, + "include":["src","types"],"exclude":[] + }`, + "/app/src/a.ts": `export const value: number = "error";`, + "/app/types/keep.txt": "", + }, + }, false) + result := execute.CommandLine(t.Context(), sys, []string{"--watch"}, sys) + w := result.Watcher.(*execute.Watcher) + assert.Assert(t, strings.Contains(sys.getOutput(false), "TS2322")) + assert.Assert(t, !sys.fsFromFileMap().FileExists("/app/types/a.d.ts")) + + sys.writeFileNoError("/app/types/a.d.ts", "declare const suppliedExternally: true;") + sys.clearOutput() + builds := w.FullBuilds() + sys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: "/app/types/a.d.ts"}}) + w.DoCycle(t.Context()) + assert.Equal(t, w.FullBuilds(), builds+1, "an unwritten potential output must be accepted as a new input") + assert.Assert(t, strings.Contains(sys.getOutput(false), "/app/types/a.d.ts")) +} + +func TestWatchWildcardTracksFirstFastPathOutputs(t *testing.T) { + t.Parallel() + sys := newTestSys(&tscInput{ + cwd: "/app", + files: FileMap{ + "/app/tsconfig.json": `{"compilerOptions":{"allowJs":true,"declaration":true,"noEmitOnError":true},"include":["**/*"]}`, + "/app/index.ts": `export const value: number = "error";`, + }, + }, false) + result := execute.CommandLine(t.Context(), sys, []string{"--watch"}, sys) + w := result.Watcher.(*execute.Watcher) + assert.Assert(t, strings.Contains(sys.getOutput(false), "TS2322")) + assert.Assert(t, !sys.fsFromFileMap().FileExists("/app/index.js")) + assert.Assert(t, !sys.fsFromFileMap().FileExists("/app/index.d.ts")) + + sys.writeFileNoError("/app/index.ts", "export const value: number = 2;") + sys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: "/app/index.ts"}}) + w.DoCycle(t.Context()) + assert.Equal(t, w.FastPathBuilds(), 1) + assert.Assert(t, strings.Contains(sys.readFileNoError("/app/index.js"), "value = 2")) + assert.Assert(t, strings.Contains(sys.readFileNoError("/app/index.d.ts"), "value: number")) + for _, path := range []string{"/app/index.js", "/app/index.d.ts"} { + sys.clearOutput() + builds := w.FullBuilds() + w.FastPathBuilds() + sys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: path}}) + w.DoCycle(t.Context()) + assert.Equal(t, w.FullBuilds()+w.FastPathBuilds(), builds) + assert.Assert(t, !strings.Contains(sys.getOutput(false), "File change detected")) + } +} + +func TestWatchWildcardRetiresRemovedSourceOutputs(t *testing.T) { + t.Parallel() + sys := newTestSys(&tscInput{ + cwd: "/app", + files: FileMap{ + "/app/tsconfig.json": `{"compilerOptions":{"composite":true,"emitDeclarationOnly":true,"listFiles":true},"include":["**/*"]}`, + "/app/a.ts": "export const a = 1;", + "/app/b.ts": "export const b = 2;", + }, + }, false) + result := execute.CommandLine(t.Context(), sys, []string{"--watch"}, sys) + w := result.Watcher.(*execute.Watcher) + assert.Assert(t, sys.fsFromFileMap().FileExists("/app/a.d.ts")) + bModTime := sys.FS().Stat("/app/b.d.ts").ModTime() + + sys.removeNoError("/app/a.ts") + sys.removeNoError("/app/a.d.ts") + sys.clearOutput() + sys.mockWatchBackend.SendEvents([]fswatch.Event{ + {Kind: fswatch.EventDelete, Path: "/app/a.ts"}, + {Kind: fswatch.EventDelete, Path: "/app/a.d.ts"}, + }) + w.DoCycle(t.Context()) + assert.Assert(t, !strings.Contains(sys.getOutput(false), "/app/a.ts")) + assert.Equal(t, sys.FS().Stat("/app/b.d.ts").ModTime(), bModTime, "unchanged declarations must not be rewritten") + + sys.clearOutput() + builds := w.FullBuilds() + w.FastPathBuilds() + sys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: "/app/b.d.ts"}}) + w.DoCycle(t.Context()) + assert.Equal(t, w.FullBuilds()+w.FastPathBuilds(), builds, "a skipped but still active output must remain ignored") + assert.Assert(t, !strings.Contains(sys.getOutput(false), "File change detected")) + + sys.writeFileNoError("/app/a.d.ts", "declare const suppliedExternally: true;") + sys.clearOutput() + builds = w.FullBuilds() + sys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: "/app/a.d.ts"}}) + w.DoCycle(t.Context()) + assert.Equal(t, w.FullBuilds(), builds+1, "an old output must become discoverable after its source is removed") + assert.Assert(t, strings.Contains(sys.getOutput(false), "/app/a.d.ts")) +} + +func TestWatchWildcardRetiresReconfiguredOutputs(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + options string + }{ + {name: "moved declaration directory", options: `"declarationDir":"next"`}, + {name: "disabled emission", options: `"declarationDir":"types","noEmit":true`}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + config := func(options string) string { + return `{"compilerOptions":{"declaration":true,"emitDeclarationOnly":true,"rootDir":"src","listFiles":true,` + options + `},"include":["src","types"],"exclude":[]}` + } + sys := newTestSys(&tscInput{ + cwd: "/app", + files: FileMap{ + "/app/tsconfig.json": config(`"declarationDir":"types"`), + "/app/src/a.ts": "export const a = 1;", + }, + }, false) + result := execute.CommandLine(t.Context(), sys, []string{"--watch"}, sys) + w := result.Watcher.(*execute.Watcher) + assert.Assert(t, sys.fsFromFileMap().FileExists("/app/types/a.d.ts")) + + sys.removeNoError("/app/types/a.d.ts") + sys.writeFileNoError("/app/tsconfig.json", config(test.options)) + sys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: "/app/tsconfig.json"}}) + w.DoCycle(t.Context()) + + sys.writeFileNoError("/app/types/a.d.ts", "declare const suppliedExternally: true;") + sys.clearOutput() + builds := w.FullBuilds() + sys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: "/app/types/a.d.ts"}}) + w.DoCycle(t.Context()) + assert.Equal(t, w.FullBuilds(), builds+1, "a retired output must become discoverable after reconfiguration") + assert.Assert(t, strings.Contains(sys.getOutput(false), "/app/types/a.d.ts")) + }) + } +} + +func TestWatchReplacedDirectoryMixedUpdate(t *testing.T) { + t.Parallel() + sys := newTestSys(&tscInput{ + cwd: "/app", + files: FileMap{ + "/app/tsconfig.json": `{"compilerOptions":{"outDir":"out"},"include":["**/*"]}`, + "/app/main.ts": `import { value } from "./lib/value"; export const main = value;`, + "/app/lib/value.ts": "export const value = 1;", + }, + }, false) + result := execute.CommandLine(t.Context(), sys, []string{"--watch"}, sys) + w := result.Watcher.(*execute.Watcher) + modTime := sys.FS().Stat("/app/lib/value.ts").ModTime() + sys.removeNoError("/app/lib/value.ts") + sys.removeNoError("/app/lib") + sys.writeFileNoError("/app/lib/value.ts", "export const value = 2;") + assert.NilError(t, sys.FS().Chtimes("/app/lib/value.ts", modTime, modTime)) + sys.writeFileNoError("/app/main.ts", `import { value } from "./lib/value"; export const updated = value;`) + builds := w.FullBuilds() + sys.mockWatchBackend.SendEvents([]fswatch.Event{ + {Kind: fswatch.EventUpdate, Path: "/app/lib"}, + {Kind: fswatch.EventUpdate, Path: "/app/main.ts"}, + }) + w.DoCycle(t.Context()) + assert.Assert(t, strings.Contains(sys.readFileNoError("/app/out/lib/value.js"), "value = 2"), + "replacing a directory with preserved timestamps must invalidate its cached sources") + assert.Equal(t, w.FullBuilds(), builds+1) +} + +func TestWatchDirectoryReplacedByFile(t *testing.T) { + t.Parallel() + for _, directory := range []string{"lib", "lib.ts"} { + for _, roots := range []struct { + name string + config string + }{ + {name: "wildcard", config: `"include":["**/*"]`}, + {name: "explicit", config: `"files":["main.ts"]`}, + } { + for _, mixed := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/%s/mixed=%v", directory, roots.name, mixed), func(t *testing.T) { + t.Parallel() + source := "/app/" + directory + "/nested/value.ts" + main := fmt.Sprintf(`import { value } from "./%s/nested/value"; export const main = value;`, directory) + sys := newTestSys(&tscInput{ + cwd: "/app", + files: FileMap{ + "/app/tsconfig.json": `{"compilerOptions":{"outDir":"out","listFiles":true},` + roots.config + `}`, + "/app/main.ts": main, + source: "export const value = 1;", + "/app/" + directory + "/nested/package.json": `{"type":"commonjs"}`, + }, + }, false) + result := execute.CommandLine(t.Context(), sys, []string{"--watch"}, sys) + w := result.Watcher.(*execute.Watcher) + assert.Assert(t, strings.Contains(sys.getOutput(false), source)) + assert.Assert(t, strings.Contains(sys.getOutput(false), "Found 0 errors"), sys.getOutput(false)) + + sys.removeNoError(source) + sys.removeNoError("/app/" + directory + "/nested/package.json") + sys.removeNoError("/app/" + directory + "/nested") + sys.removeNoError("/app/" + directory) + sys.writeFileNoError("/app/"+directory, "export const replacement = 2;") + events := []fswatch.Event{{Kind: fswatch.EventUpdate, Path: "/app/" + directory}} + if mixed { + sys.writeFileNoError("/app/main.ts", main+"\nexport const updated = true;") + events = append(events, fswatch.Event{Kind: fswatch.EventUpdate, Path: "/app/main.ts"}) + } + sys.clearOutput() + sys.mockWatchBackend.SendEvents(events) + w.DoCycle(t.Context()) + assert.Assert(t, strings.Contains(sys.getOutput(false), "TS2307"), + "replacing an imported directory with a file must invalidate module resolution") + assert.Assert(t, !strings.Contains(sys.getOutput(false), source), + "the removed directory's source must no longer belong to the program") + if directory == "lib.ts" && roots.name == "wildcard" { + assert.Assert(t, strings.Contains(sys.getOutput(false), "/app/lib.ts\n"), + "the replacement source file must be discovered") + } + }) + } + } + } +} + +func TestWatchExcludedBuildDirectoryEvents(t *testing.T) { + t.Parallel() + for _, exclude := range []string{"build", "build/**", "build/**/*"} { + t.Run(exclude, func(t *testing.T) { + t.Parallel() + sys := newTestSys(&tscInput{ + cwd: "/app", + files: FileMap{ + "/app/tsconfig.json": fmt.Sprintf(`{ + "compilerOptions":{"incremental":true,"outDir":"out","tsBuildInfoFile":"./build/tsconfig.tsbuildinfo"}, + "include":["**/*"],"exclude":[%q,"out"] + }`, exclude), + "/app/main.ts": "export const main = 1;", + }, + }, false) + result := execute.CommandLine(t.Context(), sys, []string{"--watch"}, sys) + w := result.Watcher.(*execute.Watcher) + assert.Assert(t, sys.fsFromFileMap().FileExists("/app/build/tsconfig.tsbuildinfo")) + sys.clearOutput() + builds := w.FullBuilds() + w.FastPathBuilds() + sys.mockWatchBackend.SendEvents([]fswatch.Event{ + {Kind: fswatch.EventUpdate, Path: "/app/build"}, + {Kind: fswatch.EventUpdate, Path: "/app/build/tsconfig.tsbuildinfo"}, + }) + w.DoCycle(t.Context()) + assert.Equal(t, w.FullBuilds()+w.FastPathBuilds(), builds) + assert.Assert(t, !strings.Contains(sys.getOutput(false), "File change detected")) + + sys.writeFileNoError("/app/build-other/new.ts", "export const added = 2;") + sys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: "/app/build-other"}}) + w.DoCycle(t.Context()) + assert.Assert(t, strings.Contains(sys.readFileNoError("/app/out/build-other/new.js"), "added = 2")) + }) + } +} + +func TestWatchExcludedDirectoryKeepsImportedDependencies(t *testing.T) { + t.Parallel() + sys := newTestSys(&tscInput{ + cwd: "/app", + files: FileMap{ + "/app/tsconfig.json": `{ + "compilerOptions":{"incremental":true,"outDir":"out","tsBuildInfoFile":"./build/tsconfig.tsbuildinfo"}, + "include":["**/*"],"exclude":["build","out"] + }`, + "/app/main.ts": `export { value } from "./build/dependency";`, + "/app/build/dependency.ts": "export const value = 1;", + }, + }, false) + result := execute.CommandLine(t.Context(), sys, []string{"--watch"}, sys) + w := result.Watcher.(*execute.Watcher) + sys.writeFileNoError("/app/build/dependency.ts", "export const value = 2;") + sys.mockWatchBackend.SendEvents([]fswatch.Event{ + {Kind: fswatch.EventUpdate, Path: "/app/build"}, + {Kind: fswatch.EventUpdate, Path: "/app/build/tsconfig.tsbuildinfo"}, + }) + w.DoCycle(t.Context()) + assert.Assert(t, strings.Contains(sys.readFileNoError("/app/out/build/dependency.js"), "value = 2")) +} + +func TestWatchRestoredDeclarationOutputEvents(t *testing.T) { + t.Parallel() + sys := newTestSys(&tscInput{ + cwd: "/app", + files: FileMap{ + "/app/tsconfig.json": `{"compilerOptions":{"composite":true,"emitDeclarationOnly":true}}`, + "/app/main.ts": "export const main = 1;", + }, + }, false) + prebuild := execute.CommandLine(t.Context(), sys, nil, sys) + assert.Equal(t, int(prebuild.Status), 0) + modTime := sys.FS().Stat("/app/main.d.ts").ModTime() + assert.Assert(t, sys.fsFromFileMap().FileExists("/app/tsconfig.tsbuildinfo")) + result := execute.CommandLine(t.Context(), sys, []string{"--watch"}, sys) + w := result.Watcher.(*execute.Watcher) + assert.Equal(t, sys.FS().Stat("/app/main.d.ts").ModTime(), modTime, "restart must skip unchanged declaration writes") + + sys.clearOutput() + builds := w.FullBuilds() + w.FastPathBuilds() + sys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: "/app/main.d.ts"}}) + w.DoCycle(t.Context()) + assert.Equal(t, w.FullBuilds()+w.FastPathBuilds(), builds) + assert.Assert(t, !strings.Contains(sys.getOutput(false), "File change detected")) +} + +func TestWatchRestoredUnwrittenDeclarationIsInput(t *testing.T) { + t.Parallel() + sys := newTestSys(&tscInput{ + cwd: "/app", + files: FileMap{ + "/app/tsconfig.json": `{ + "compilerOptions":{"composite":true,"noEmitOnError":true,"rootDir":"src","declarationDir":"types","listFiles":true}, + "include":["src","types"],"exclude":[] + }`, + "/app/src/a.ts": `export const value: number = "error";`, + "/app/types/keep.txt": "", + }, + }, false) + prebuild := execute.CommandLine(t.Context(), sys, nil, sys) + assert.Equal(t, int(prebuild.Status), 1) + assert.Assert(t, sys.fsFromFileMap().FileExists("/app/tsconfig.tsbuildinfo")) + assert.Assert(t, !sys.fsFromFileMap().FileExists("/app/types/a.d.ts")) + result := execute.CommandLine(t.Context(), sys, []string{"--watch"}, sys) + w := result.Watcher.(*execute.Watcher) + + sys.writeFileNoError("/app/types/a.d.ts", "declare const suppliedExternally: true;") + sys.clearOutput() + builds := w.FullBuilds() + sys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: "/app/types/a.d.ts"}}) + w.DoCycle(t.Context()) + assert.Equal(t, w.FullBuilds(), builds+1) + assert.Assert(t, strings.Contains(sys.getOutput(false), "/app/types/a.d.ts")) +} + // shallowProjectFiles is a project close to the filesystem root (a common Docker WORKDIR) that imports a file from a // sibling directory which is not part of "include", plus a bare import whose failed lookups walk up to /node_modules. func shallowProjectFiles(compilerOptions string) FileMap { diff --git a/tsc/internal/execute/watcher.go b/tsc/internal/execute/watcher.go index b5097d5617585..e6977f54665c9 100644 --- a/tsc/internal/execute/watcher.go +++ b/tsc/internal/execute/watcher.go @@ -16,6 +16,7 @@ import ( "github.com/microsoft/TypeScript/tsc/internal/execute/tsc" "github.com/microsoft/TypeScript/tsc/internal/execute/watchmanager" "github.com/microsoft/TypeScript/tsc/internal/fswatch" + "github.com/microsoft/TypeScript/tsc/internal/outputpaths" "github.com/microsoft/TypeScript/tsc/internal/tsoptions" "github.com/microsoft/TypeScript/tsc/internal/tspath" "github.com/microsoft/TypeScript/tsc/internal/vfs/cachedvfs" @@ -80,10 +81,12 @@ type Watcher struct { sourceFileCache *collections.SyncMap[tspath.PathKey, *cachedSourceFile] - wm *watchmanager.WatchManager - seenFiles *collections.Set[tspath.PathKey] // all build dependencies (for event filtering) - configMtimes map[tspath.RootedFilePath]time.Time - watchSetDirty bool + wm *watchmanager.WatchManager + seenFiles *collections.Set[tspath.PathKey] // all build dependencies (for event filtering) + seenDirectories collections.Set[tspath.PathKey] + emittedFiles collections.SyncMap[tspath.PathKey, tspath.PathKey] // output → source; empty source for build info + configMtimes map[tspath.RootedFilePath]time.Time + watchSetDirty bool // forceFullRebuild records a reason that requires a full NewProgram rebuild // (e.g. an event overflow, a mid-cycle watch failure, a newly appeared // project file, or a changed non-source dependency). Unlike watchSetDirty, @@ -304,7 +307,9 @@ func (w *Watcher) DoCycle(ctx context.Context) { if hasEvents && !overflow && !w.configModified { // Filter fswatch events against known dependencies - if w.isRelevantChange(changedPaths) { + eventCount := len(changedPaths) + w.filterRelevantChanges(changedPaths) + if len(changedPaths) > 0 { w.evictChangedSourceFiles(changedPaths) caseSensitivity := w.sys.FS().CaseSensitivity() programFiles := w.program.GetProgram().FilesByPath() @@ -312,11 +317,14 @@ func (w *Watcher) DoCycle(ctx context.Context) { return caseSensitivity.PathKey(tspath.RootedPath(fileName)) })...) contentMapperConfigChanged := false - for eventPath := range changedPaths { - if w.sys.FS().DirectoryExists(tspath.RootedDirectoryPathFromPath(eventPath)) { + for eventPath, kind := range changedPaths { + if w.isDirectoryChange(eventPath) { // A watched directory changed: the wildcard file set may have // changed, so reload file names on the next build. w.watchSetDirty = true + if kind == fswatch.EventDelete || w.seenDirectories.Has(w.caseSensitivity().PathKey(eventPath)) { + w.forceFullRebuild = true + } continue } p := w.caseSensitivity().PathKey(eventPath) @@ -356,7 +364,7 @@ func (w *Watcher) DoCycle(ctx context.Context) { } } else { if w.wm.DebugLog != nil { - fmt.Fprintf(w.wm.DebugLog, "[watch] DoCycle: %d event(s) not relevant to compilation, skipping rebuild\n", len(changedPaths)) + fmt.Fprintf(w.wm.DebugLog, "[watch] DoCycle: %d event(s) not relevant to compilation, skipping rebuild\n", eventCount) } if w.testing != nil { w.testing.OnProgram(w.program) @@ -390,33 +398,48 @@ func (w *Watcher) DoCycle(ctx context.Context) { } } -func (w *Watcher) isRelevantChange(changedPaths map[tspath.RootedPath]fswatch.EventKind) bool { +func (w *Watcher) filterRelevantChanges(changedPaths map[tspath.RootedPath]fswatch.EventKind) { caseSensitivity := w.sys.FS().CaseSensitivity() - opts := w.caseSensitivity() + supportedExtensions := tsoptions.GetSupportedExtensionsWithJsonIfResolveJsonModule( + w.config.CompilerOptions(), + tsoptions.GetSupportedExtensions(w.config.CompilerOptions(), w.config.ContentMapperExtensions()), + ) + if !caseSensitivity.IsCaseSensitive() { + supportedExtensions = core.Map(supportedExtensions, func(extensions []string) []string { + return core.Map(extensions, caseSensitivity.Canonicalize) + }) + } contentMapperWatchedFiles := collections.NewSetFromItems(core.Map(w.contentMapperWatchedFiles(), func(fileName tspath.RootedFilePath) tspath.PathKey { return caseSensitivity.PathKey(tspath.RootedPath(fileName)) })...) for eventPath := range changedPaths { - p := opts.PathKey(eventPath) - if contentMapperWatchedFiles.Has(p) { - return true - } - if w.seenFiles.Has(p) { - return true - } - if w.config.ConfigFile != nil && w.config.PossiblyMatchesFileName(tspath.RootedFilePathFromPath(eventPath)) { - return true - } - if w.config.ConfigFile != nil && w.config.PossiblyMatchesDirectoryName(p) { - return true + p := caseSensitivity.PathKey(eventPath) + if contentMapperWatchedFiles.Has(p) || w.seenFiles.Has(p) { + continue } - if w.sys.FS().DirectoryExists(tspath.RootedDirectoryPathFromPath(eventPath)) { - if w.wm.IsPathUnderWatch(eventPath) { - return true + if w.isDirectoryChange(eventPath) { + if w.wm.IsPathUnderWatch(eventPath) && + (w.seenDirectories.Has(p) || !w.config.IsExcludedDirectory(tspath.RootedDirectoryPathFromPath(eventPath))) { + continue } + } else if _, emitted := w.emittedFiles.Load(p); !emitted && + slices.ContainsFunc(supportedExtensions, p.ExtensionIsOneOf) && + w.config.ConfigFile != nil && + w.config.PossiblyMatchesFileName(tspath.RootedFilePathFromPath(eventPath)) { + continue } + delete(changedPaths, eventPath) } - return false +} + +func (w *Watcher) isDirectoryChange(path tspath.RootedPath) bool { + if w.sys.FS().DirectoryExists(tspath.RootedDirectoryPathFromPath(path)) { + return true + } + // Events do not distinguish files from directories. A former directory may + // now be absent or a file after a coalesced update, but its dependencies + // must still invalidate the file set and module resolutions. + return w.seenDirectories.Has(w.caseSensitivity().PathKey(path)) } func (w *Watcher) doBuild(ctx context.Context) error { @@ -520,6 +543,15 @@ func (w *Watcher) doBuild(ctx context.Context) error { return err } w.program = incremental.NewProgram(program, w.program, nil, w.sys.Now, w.testing != nil) + if !w.programReady { + w.program.ForEachEmittedDeclarationFile(func(output tspath.RootedFilePath, sourceFile *ast.SourceFile) { + // Restored emit signatures confirm prior emission. Do not track these + // output probes as input dependencies. + if w.sys.FS().FileExists(output) { + w.emittedFiles.Store(w.caseSensitivity().PathKey(output.AsPath()), sourceFile.PathKey()) + } + }) + } w.programReady = true w.fullBuilds++ @@ -532,8 +564,15 @@ func (w *Watcher) doBuild(ctx context.Context) error { caseSensitivity := w.sys.FS().CaseSensitivity() seenSlice := tfs.SeenFiles.ToSlice() w.seenFiles = collections.NewSetWithSizeHint[tspath.PathKey](len(seenSlice)) + w.seenDirectories.Clear() for _, p := range seenSlice { - w.seenFiles.Add(caseSensitivity.PathKey(p)) + path := caseSensitivity.PathKey(p) + w.seenFiles.Add(path) + for dir := path.Parent(); ; dir = dir.Parent() { + if !w.seenDirectories.AddIfAbsent(dir) { + break + } + } } w.configMtimes = make(map[tspath.RootedFilePath]time.Time, len(w.configFilePaths)) @@ -631,8 +670,12 @@ func equalJSXImplicitImport(options *core.CompilerOptions, oldFile *ast.SourceFi func (w *Watcher) evictChangedSourceFiles(changedPaths map[tspath.RootedPath]fswatch.EventKind) { caseSensitivity := w.sys.FS().CaseSensitivity() + var changedDirectories collections.Set[tspath.PathKey] for eventPath := range changedPaths { p := caseSensitivity.PathKey(eventPath) + if w.seenDirectories.Has(p) { + changedDirectories.Add(p) + } if _, ok := w.sourceFileCache.Load(p); ok { if w.wm.DebugLog != nil { fmt.Fprintf(w.wm.DebugLog, "[watch] evicting cached source file: %s\n", p) @@ -640,19 +683,79 @@ func (w *Watcher) evictChangedSourceFiles(changedPaths map[tspath.RootedPath]fsw w.sourceFileCache.Delete(p) } } + if changedDirectories.Len() == 0 { + return + } + w.sourceFileCache.Range(func(path tspath.PathKey, _ *cachedSourceFile) bool { + for dir := path.Parent(); ; dir = dir.Parent() { + if changedDirectories.Has(dir) { + w.sourceFileCache.Delete(path) + break + } + if dir == dir.Parent() { + break + } + } + return true + }) +} + +func (w *Watcher) pruneEmittedFiles(program *compiler.Program) { + caseSensitivity := w.caseSensitivity() + buildInfoPath := caseSensitivity.PathKey(w.config.GetBuildInfoFileName().AsPath()) + w.emittedFiles.Range(func(outputPath, sourcePath tspath.PathKey) bool { + if sourcePath == "" { + if outputPath != buildInfoPath { + w.emittedFiles.Delete(outputPath) + } + return true + } + sourceFile := program.GetSourceFileByPath(sourcePath) + if sourceFile == nil || program.Options().NoEmit.IsTrue() || !program.SourceFileMayBeEmitted(sourceFile, false) { + w.emittedFiles.Delete(outputPath) + return true + } + paths := outputpaths.GetOutputPathsFor(sourceFile, program.Options(), program, outputpaths.ForceEmitPaths{}) + if !slices.ContainsFunc([]tspath.RootedFilePath{ + paths.JsFilePath(), + paths.SourceMapFilePath(), + paths.DeclarationFilePath(), + paths.DeclarationMapPath(), + paths.ExternalOutputFilePath(), + }, func(path tspath.RootedFilePath) bool { + return path != "" && caseSensitivity.PathKey(path.AsPath()) == outputPath + }) { + w.emittedFiles.Delete(outputPath) + } + return true + }) } func (w *Watcher) compileAndEmit(ctx context.Context) tsc.CompileAndEmitResult { + program := w.program.GetProgram() + w.pruneEmittedFiles(program) + caseSensitivity := w.caseSensitivity() return tsc.EmitFilesAndReportErrors(ctx, tsc.EmitInput{ Sys: w.sys, ProgramLike: w.program, - Program: w.program.GetProgram(), + Program: program, Config: w.config, ReportDiagnostic: w.reportDiagnostic, ReportErrorSummary: w.reportErrorSummary, Writer: w.sys.Writer(), CompileTimes: &tsc.CompileTimes{}, Testing: w.testing, + WriteFile: func(fileName tspath.RootedFilePath, text string, data *compiler.WriteFileData) error { + if err := program.Host().FS().WriteFile(fileName, text); err != nil { + return err + } + var sourcePath tspath.PathKey + if data != nil && data.SourceFile != nil { + sourcePath = data.SourceFile.PathKey() + } + w.emittedFiles.Store(caseSensitivity.PathKey(fileName.AsPath()), sourcePath) + return nil + }, }) } diff --git a/tsc/internal/tsoptions/parsedcommandline.go b/tsc/internal/tsoptions/parsedcommandline.go index 45492e6981af7..8a116bf3fcb46 100644 --- a/tsc/internal/tsoptions/parsedcommandline.go +++ b/tsc/internal/tsoptions/parsedcommandline.go @@ -526,6 +526,25 @@ func (p *ParsedCommandLine) PossiblyMatchesDirectoryName(directoryPath tspath.Pa return false } +func (p *ParsedCommandLine) IsExcludedDirectory(directoryPath tspath.RootedDirectoryPath) bool { + specs := p.getConfigFileSpecs() + if specs == nil { + return false + } + // Match excluded directories themselves, not just the files beneath them. + directorySpecs := core.Map(specs.validatedExcludeSpecs, func(spec tspath.PathPattern) tspath.PathPattern { + text := spec.AsString() + if before, ok := strings.CutSuffix(text, "/*"); ok { + text = before + "/**" + } else if vfsmatch.IsImplicitGlob(tspath.GetBaseFileName(text)) { + text = tspath.CombinePaths(text, "**") + } + return tspath.ToPathPattern(text) + }) + matcher := vfsmatch.NewSpecMatcher(directorySpecs, p.BaseDirectory(), vfsmatch.UsageExclude, p.CaseSensitivity()) + return matcher != nil && matcher.MatchString(directoryPath.AsString()) +} + func (p *ParsedCommandLine) GetMatchedFileSpec(fileName tspath.RootedFilePath) string { return p.getConfigFileSpecs().getMatchedFileSpec(p.caseSensitivity.PathKey(tspath.RootedPath(fileName))).AsString() }