Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions cmd/tsgo/lsp.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ import (
"fmt"
"io"
"os"
"runtime"

"github.com/microsoft/typescript-go/internal/bundled"
"github.com/microsoft/typescript-go/internal/core"
"github.com/microsoft/typescript-go/internal/lsp"
"github.com/microsoft/typescript-go/internal/pprof"
"github.com/microsoft/typescript-go/internal/tspath"
"github.com/microsoft/typescript-go/internal/vfs/osvfs"
)

Expand Down Expand Up @@ -39,6 +41,7 @@ func runLSP(args []string) int {

fs := bundled.WrapFS(osvfs.FS())
defaultLibraryPath := bundled.LibPath()
typingsLocation := getGlobalTypingsCacheLocation()

s := lsp.NewServer(&lsp.ServerOptions{
In: os.Stdin,
Expand All @@ -47,10 +50,79 @@ func runLSP(args []string) int {
Cwd: core.Must(os.Getwd()),
FS: fs,
DefaultLibraryPath: defaultLibraryPath,
TypingsLocation: typingsLocation,
})

if err := s.Run(); err != nil && !errors.Is(err, io.EOF) {
return 1
}
return 0
}

func getGlobalTypingsCacheLocation() string {
switch runtime.GOOS {
Comment thread
sheetalkamat marked this conversation as resolved.
case "windows":
{
basePath, err := os.UserCacheDir()
if err != nil {
if basePath, err = os.UserConfigDir(); err != nil {
if basePath, err = os.UserHomeDir(); err != nil {
if userProfile := os.Getenv("USERPROFILE"); userProfile != "" {
basePath = userProfile
} else if homeDrive, homePath := os.Getenv("HOMEDRIVE"), os.Getenv("HOMEPATH"); homeDrive != "" && homePath != "" {
basePath = homeDrive + homePath
} else {
basePath = os.TempDir()
}
}
}
}
return tspath.CombinePaths(tspath.CombinePaths(basePath, "Microsoft/TypeScript"), core.VersionMajorMinor)
}
case "openbsd", "freebsd", "netbsd", "darwin", "linux", "android":
{
cacheLocation := getNonWindowsCacheLocation()
return tspath.CombinePaths(tspath.CombinePaths(cacheLocation, "typescript"), core.VersionMajorMinor)
}
default:
panic("unsupported platform: " + runtime.GOOS)
}
}

Comment thread
sheetalkamat marked this conversation as resolved.
Outdated
func getNonWindowsCacheLocation() string {
if xdgCacheHome := os.Getenv("XDG_CACHE_HOME"); xdgCacheHome != "" {
return xdgCacheHome
}
const platformIsDarwin = runtime.GOOS == "darwin"
var usersDir string
if platformIsDarwin {
usersDir = "Users"
} else {
usersDir = "home"
}
homePath, err := os.UserHomeDir()
if err != nil {
if home := os.Getenv("HOME"); home != "" {
homePath = home
} else {
var userName string
if logName := os.Getenv("LOGNAME"); logName != "" {
userName = logName
} else if user := os.Getenv("USER"); user != "" {
userName = user
}
if userName != "" {
homePath = "/" + usersDir + "/" + userName
} else {
homePath = os.TempDir()
}
}
}
var cacheFolder string
if platformIsDarwin {
cacheFolder = "Library/Caches"
} else {
cacheFolder = ".cache"
}
return tspath.CombinePaths(homePath, cacheFolder)
}
5 changes: 5 additions & 0 deletions internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ func (api *API) DefaultLibraryPath() string {
return api.host.DefaultLibraryPath()
}

// TypingsInstaller implements ProjectHost
func (api *API) TypingsInstaller() *project.TypingsInstaller {
return nil
}

// DocumentRegistry implements ProjectHost.
func (api *API) DocumentRegistry() *project.DocumentRegistry {
return api.documentRegistry
Expand Down
5 changes: 5 additions & 0 deletions internal/compiler/program.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ type ProgramOptions struct {
SingleThreaded core.Tristate
ProjectReference []core.ProjectReference
ConfigFileParsingDiagnostics []*ast.Diagnostic

TypingsLocation string
ProjectName string
}

type Program struct {
Expand Down Expand Up @@ -136,6 +139,8 @@ func NewProgram(options ProgramOptions) *Program {
}

p.resolver = module.NewResolver(p.host, p.compilerOptions)
p.resolver.TypingsLocation = p.programOptions.TypingsLocation
p.resolver.ProjectName = p.programOptions.ProjectName
Comment thread
sheetalkamat marked this conversation as resolved.
Outdated

var libs []string

Expand Down
94 changes: 94 additions & 0 deletions internal/core/nodemodules.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package core

import (
"maps"
"sync"
)

var UnprefixedNodeCoreModules = map[string]bool{
"assert": true,
"assert/strict": true,
"async_hooks": true,
"buffer": true,
"child_process": true,
"cluster": true,
"console": true,
"constants": true,
"crypto": true,
"dgram": true,
"diagnostics_channel": true,
"dns": true,
"dns/promises": true,
"domain": true,
"events": true,
"fs": true,
"fs/promises": true,
"http": true,
"http2": true,
"https": true,
"inspector": true,
"inspector/promises": true,
"module": true,
"net": true,
"os": true,
"path": true,
"path/posix": true,
"path/win32": true,
"perf_hooks": true,
"process": true,
"punycode": true,
"querystring": true,
"readline": true,
"readline/promises": true,
"repl": true,
"stream": true,
"stream/consumers": true,
"stream/promises": true,
"stream/web": true,
"string_decoder": true,
"sys": true,
"test/mock_loader": true,
"timers": true,
"timers/promises": true,
"tls": true,
"trace_events": true,
"tty": true,
"url": true,
"util": true,
"util/types": true,
"v8": true,
"vm": true,
"wasi": true,
"worker_threads": true,
"zlib": true,
}

var ExclusivelyPrefixedNodeCoreModules = map[string]bool{
"node:sea": true,
"node:sqlite": true,
"node:test": true,
"node:test/reporters": true,
}

var (
nodeCoreModules = map[string]bool{}
nodeCoreModulesOnce sync.Once
)

func ensureNodeCoreModules() {
nodeCoreModulesOnce.Do(func() {
for unprefixed := range UnprefixedNodeCoreModules {
nodeCoreModules[unprefixed] = true
nodeCoreModules["node:"+unprefixed] = true
}
maps.Copy(nodeCoreModules, ExclusivelyPrefixedNodeCoreModules)
})
}

func NonRelativeModuleNameForTypingCache(moduleName string) string {
ensureNodeCoreModules()
if nodeCoreModules[moduleName] {
Comment thread
sheetalkamat marked this conversation as resolved.
Outdated
return "node"
}
return moduleName
}
12 changes: 12 additions & 0 deletions internal/lsp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ type ServerOptions struct {
NewLine core.NewLineKind
FS vfs.FS
DefaultLibraryPath string
TypingsLocation string
}

func NewServer(opts *ServerOptions) *Server {
Expand All @@ -40,6 +41,7 @@ func NewServer(opts *ServerOptions) *Server {
newLine: opts.NewLine,
fs: opts.FS,
defaultLibraryPath: opts.DefaultLibraryPath,
typingsLocation: opts.TypingsLocation,
}
}

Expand All @@ -62,6 +64,7 @@ type Server struct {
newLine core.NewLineKind
fs vfs.FS
defaultLibraryPath string
typingsLocation string

initializeParams *lsproto.InitializeParams
positionEncoding lsproto.PositionEncodingKind
Expand All @@ -84,6 +87,11 @@ func (s *Server) DefaultLibraryPath() string {
return s.defaultLibraryPath
}

// TypingsLocation implements project.ServiceHost.
func (s *Server) TypingsLocation() string {
return s.typingsLocation
}

// GetCurrentDirectory implements project.ServiceHost.
func (s *Server) GetCurrentDirectory() string {
return s.cwd
Expand Down Expand Up @@ -371,6 +379,10 @@ func (s *Server) handleInitialized(req *lsproto.RequestMessage) error {
Logger: s.logger,
WatchEnabled: s.watchEnabled,
PositionEncoding: s.positionEncoding,
TypingsInstallerOptions: project.TypingsInstallerOptions{
ThrottleLimit: 5,
NpmInstall: project.NpmInstall,
},
})

s.converters = ls.NewConverters(s.positionEncoding, func(fileName string) ls.ScriptInfo {
Expand Down
32 changes: 32 additions & 0 deletions internal/module/resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ type Resolver struct {
caches
host ResolutionHost
compilerOptions *core.CompilerOptions
TypingsLocation string
ProjectName string
// reportDiagnostic: DiagnosticReporter
}

Expand Down Expand Up @@ -229,6 +231,36 @@ func (r *Resolver) ResolveModuleName(moduleName string, containingFile string, r
}
}

return r.tryResolveFromTypingsLocation(moduleName, containingDirectory, result)
}

func (r *Resolver) tryResolveFromTypingsLocation(moduleName string, containingDirectory string, originalResult *ResolvedModule) *ResolvedModule {
if r.TypingsLocation == "" ||
tspath.IsExternalModuleNameRelative(moduleName) ||
(originalResult.ResolvedFileName != "" && tspath.ExtensionIsOneOf(originalResult.Extension, tspath.SupportedTSExtensionsWithJsonFlat)) {
return originalResult
}

state := newResolutionState(
moduleName,
containingDirectory,
false, /*isTypeReferenceDirective*/
core.ModuleKindNone, // resolutionMode,
r.compilerOptions,
nil, // redirectedReference,
r,
)
if r.traceEnabled() {
r.host.Trace(diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2.Format(r.ProjectName, moduleName, r.TypingsLocation))
}
globalResolved := state.loadModuleFromImmediateNodeModulesDirectory(extensionsDeclaration, r.TypingsLocation, false)
if globalResolved == nil {
return originalResult
}
result := state.createResolvedModule(globalResolved, true)
result.FailedLookupLocations = append(originalResult.FailedLookupLocations, result.FailedLookupLocations...)
result.AffectingLocations = append(originalResult.AffectingLocations, result.AffectingLocations...)
result.ResolutionDiagnostics = append(originalResult.ResolutionDiagnostics, result.ResolutionDiagnostics...)
return result
}

Expand Down
1 change: 1 addition & 0 deletions internal/packagejson/packagejson.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ type PathFields struct {

type DependencyFields struct {
Dependencies Expected[map[string]string] `json:"dependencies"`
DevDependencies Expected[map[string]string] `json:"devDependencies"`
PeerDependencies Expected[map[string]string] `json:"peerDependencies"`
OptionalDependencies Expected[map[string]string] `json:"optionalDependencies"`
}
Expand Down
Loading