diff --git a/cmd/tsgo/lsp.go b/cmd/tsgo/lsp.go index bc1a63b6d9a..dea9af796ea 100644 --- a/cmd/tsgo/lsp.go +++ b/cmd/tsgo/lsp.go @@ -15,6 +15,7 @@ import ( "github.com/microsoft/typescript-go/internal/lsp" "github.com/microsoft/typescript-go/internal/pprof" "github.com/microsoft/typescript-go/internal/vfs/osvfs" + "github.com/microsoft/typescript-go/internal/vfs/zipoverlay" ) func runLSP(args []string) int { @@ -40,7 +41,7 @@ func runLSP(args []string) int { defer profileSession.Stop() } - fs := bundled.WrapFS(osvfs.FS()) + fs := bundled.WrapFS(zipoverlay.Wrap(osvfs.FS())) defaultLibraryPath := bundled.LibPath() typingsLocation := osvfs.GetGlobalTypingsCacheLocation() diff --git a/cmd/tsgo/sys.go b/cmd/tsgo/sys.go index e5b2b8d569a..866c745f76e 100644 --- a/cmd/tsgo/sys.go +++ b/cmd/tsgo/sys.go @@ -11,6 +11,7 @@ import ( "github.com/microsoft/typescript-go/internal/tspath" "github.com/microsoft/typescript-go/internal/vfs" "github.com/microsoft/typescript-go/internal/vfs/osvfs" + "github.com/microsoft/typescript-go/internal/vfs/zipoverlay" "golang.org/x/term" ) @@ -68,7 +69,7 @@ func newSystem() *osSys { return &osSys{ cwd: tspath.NormalizePath(cwd), - fs: bundled.WrapFS(osvfs.FS()), + fs: bundled.WrapFS(zipoverlay.Wrap(osvfs.FS())), defaultLibraryPath: bundled.LibPath(), writer: os.Stdout, start: time.Now(), diff --git a/internal/api/server.go b/internal/api/server.go index ef5ca2a99ee..4c77715e749 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -9,6 +9,7 @@ import ( "github.com/microsoft/typescript-go/internal/lsp/lsproto" "github.com/microsoft/typescript-go/internal/project" "github.com/microsoft/typescript-go/internal/vfs/osvfs" + "github.com/microsoft/typescript-go/internal/vfs/zipoverlay" ) // StdioServerOptions configures the STDIO-based API server. @@ -69,7 +70,7 @@ func (s *StdioServer) Run(ctx context.Context) error { transport = t } - fs := bundled.WrapFS(osvfs.FS()) + fs := bundled.WrapFS(zipoverlay.Wrap(osvfs.FS())) // Wrap the base FS with callbackFS if callbacks are requested var callbackFS *callbackFS diff --git a/internal/module/resolver.go b/internal/module/resolver.go index 52400dc2b98..3817459c9c4 100644 --- a/internal/module/resolver.go +++ b/internal/module/resolver.go @@ -12,6 +12,7 @@ import ( "github.com/microsoft/typescript-go/internal/core" "github.com/microsoft/typescript-go/internal/diagnostics" "github.com/microsoft/typescript-go/internal/packagejson" + "github.com/microsoft/typescript-go/internal/pnp" "github.com/microsoft/typescript-go/internal/stringutil" "github.com/microsoft/typescript-go/internal/tspath" "github.com/microsoft/typescript-go/internal/vfs/vfsmatch" @@ -159,6 +160,31 @@ type Resolver struct { typingsLocation string projectName string // reportDiagnostic: DiagnosticReporter + + pnpOnce sync.Once + pnpManifest *pnp.Manifest +} + +// getPnpManifest discovers and loads the Yarn PnP manifest governing this +// program, once. It returns nil when the project is not a PnP project. Discovery +// walks up from the tsconfig directory (or the current directory) for a +// .pnp.data.json / .pnp.cjs sidecar. +func (r *Resolver) getPnpManifest() *pnp.Manifest { + r.pnpOnce.Do(func() { + fs := r.host.FS() + startDir := r.host.GetCurrentDirectory() + if r.compilerOptions.ConfigFilePath != "" { + startDir = tspath.GetDirectoryPath(r.compilerOptions.ConfigFilePath) + } + manifestPath := pnp.Find(startDir, fs.FileExists) + if manifestPath == "" { + return + } + if m, ok := pnp.Load(manifestPath, fs.ReadFile); ok { + r.pnpManifest = m + } + }) + return r.pnpManifest } type ResolverOptions struct { @@ -979,6 +1005,26 @@ func (r *resolutionState) getOutputDirectoriesForBaseDirectory(commonSourceDirGu } func (r *resolutionState) loadModuleFromNearestNodeModulesDirectory(typesScopeOnly bool) *resolved { + // Under Yarn PnP there is no node_modules tree; the manifest maps a package + // to its on-disk location. PnP governs package resolution for any importer it + // owns; when it doesn't own the importer (an ignored path) it reports + // "not governed" and the classic walk below runs. + if manifest := r.resolver.getPnpManifest(); manifest != nil { + result, governed := r.loadModuleFromPnp(manifest, typesScopeOnly) + if !result.shouldContinueSearching() { + return result + } + if governed { + // PnP owns this importer but the specifier is not resolvable through the + // manifest (undeclared dependency, unfulfilled peer, or a declared + // package whose file is missing). Do NOT fall through to the classic + // ancestor node_modules walk — that would resolve a phantom dependency + // from a stray node_modules the manifest does not sanction. Report "not + // found" so the caller still consults typeRoots but skips the walk. + return continueSearching() + } + } + mode := core.ResolutionModeCommonJS if r.esmMode || r.conditionMatches("import") { mode = core.ResolutionModeESM @@ -1010,6 +1056,66 @@ func (r *resolutionState) loadModuleFromNearestNodeModulesDirectory(typesScopeOn return continueSearching() } +// loadModuleFromPnp resolves r.name through the Yarn PnP manifest, mirroring the +// classic walk's shape: preferred (TS/DTS) extensions on the implementation +// package first, then a DTS lookup in the matching @types package, then fallback +// (JS/JSON) extensions on the implementation. It returns a hit (governed true), +// or continueSearching() together with whether PnP governs the importer: +// governed is false only when the importer is outside PnP's control (an ignored +// path), in which case the caller runs the classic walk; when governed is true +// but nothing resolved, the caller must not run the classic walk. +func (r *resolutionState) loadModuleFromPnp(manifest *pnp.Manifest, typesScopeOnly bool) (*resolved, bool) { + tryLoad := func(ext extensions, res pnp.Result) *resolved { + if res.Status != pnp.Success { + return continueSearching() + } + rest := strings.TrimPrefix(res.Subpath, "/") + candidate := res.PackageDir + if rest != "" { + candidate = tspath.RemoveTrailingDirectorySeparator(tspath.NormalizePath(tspath.CombinePaths(res.PackageDir, rest))) + } + return r.loadModuleFromResolvedPackageDirectory(ext, candidate, rest, res.PackageDir) + } + + priorityExtensions := r.extensions & (extensionsTypeScript | extensionsDeclaration) + secondaryExtensions := r.extensions & ^(extensionsTypeScript | extensionsDeclaration) + + implResult := manifest.Resolve(r.name, r.containingDirectory) + // An ignored importer (not owned by PnP) short-circuits to the classic walk. + if implResult.Status == pnp.Skipped { + return continueSearching(), false + } + + // (1) preferred extensions in the implementation package + if priorityExtensions != 0 && !typesScopeOnly { + if result := tryLoad(priorityExtensions, implResult); !result.shouldContinueSearching() { + return result, true + } + } + + // (1ii) DTS in the @types package + if r.extensions&extensionsDeclaration != 0 { + packageName, subpath := ParsePackageName(r.name) + typesSpecifier := GetTypesPackageName(packageName) + if subpath != "" { + typesSpecifier += "/" + subpath + } + typesResult := manifest.Resolve(typesSpecifier, r.containingDirectory) + if result := tryLoad(extensionsDeclaration, typesResult); !result.shouldContinueSearching() { + return result, true + } + } + + // (2) fallback extensions in the implementation package + if secondaryExtensions != 0 && !typesScopeOnly { + if result := tryLoad(secondaryExtensions, implResult); !result.shouldContinueSearching() { + return result, true + } + } + + return continueSearching(), true +} + func (r *resolutionState) loadModuleFromNearestNodeModulesDirectoryWorker(ext extensions, mode core.ResolutionMode, typesScopeOnly bool) *resolved { result, _ := tspath.ForEachAncestorDirectory( r.containingDirectory, @@ -1069,7 +1175,16 @@ func (r *resolutionState) loadModuleFromSpecificNodeModulesDirectory(ext extensi if packageName == "" { packageDirectory = candidate } + return r.loadModuleFromResolvedPackageDirectory(ext, candidate, rest, packageDirectory) +} +// loadModuleFromResolvedPackageDirectory performs file / directory / exports / +// typesVersions resolution once the package's on-disk directory is known. It is +// shared by the classic node_modules walk (which derives packageDirectory from a +// node_modules folder) and Yarn PnP (which gets packageDirectory from the PnP +// manifest). candidate is packageDirectory joined with rest (the subpath within +// the package, "" for a bare package specifier). +func (r *resolutionState) loadModuleFromResolvedPackageDirectory(ext extensions, candidate string, rest string, packageDirectory string) *resolved { if r.resolvePackageDirectoryOnly { if r.resolver.host.FS().DirectoryExists(packageDirectory) { return &resolved{path: packageDirectory} diff --git a/internal/pnp/edgecases_test.go b/internal/pnp/edgecases_test.go new file mode 100644 index 00000000000..06e019e5634 --- /dev/null +++ b/internal/pnp/edgecases_test.go @@ -0,0 +1,168 @@ +package pnp + +import ( + "strings" + "testing" +) + +// A manifest exercising the top-level fallback: enableTopLevelFallback is on, the +// top-level package declares "shared", and app-b is on the fallbackExclusionList. +// app-a (not excluded) can reach "shared" through the fallback even though it does +// not declare it; app-b (excluded) cannot. +const fallbackManifest = `{ + "dependencyTreeRoots": [{"name": "root", "reference": "workspace:."}], + "enableTopLevelFallback": true, + "fallbackExclusionList": [["app-b", ["workspace:packages/app-b"]]], + "fallbackPool": [["pooled", "npm:9.0.0"]], + "packageRegistryData": [ + [null, [[null, { + "packageLocation": "./", + "packageDependencies": [ + ["app-a", "workspace:packages/app-a"], + ["app-b", "workspace:packages/app-b"], + ["shared", "npm:1.0.0"] + ], + "linkType": "SOFT" + }]]], + ["app-a", [["workspace:packages/app-a", { + "packageLocation": "./packages/app-a/", + "packageDependencies": [["app-a", "workspace:packages/app-a"]], + "linkType": "SOFT" + }]]], + ["app-b", [["workspace:packages/app-b", { + "packageLocation": "./packages/app-b/", + "packageDependencies": [["app-b", "workspace:packages/app-b"]], + "linkType": "SOFT" + }]]], + ["shared", [["npm:1.0.0", { + "packageLocation": "./.yarn/cache/shared-npm-1.0.0-abc.zip/node_modules/shared/", + "packageDependencies": [["shared", "npm:1.0.0"]], + "linkType": "HARD" + }]]], + ["pooled", [["npm:9.0.0", { + "packageLocation": "./.yarn/cache/pooled-npm-9.0.0-def.zip/node_modules/pooled/", + "packageDependencies": [["pooled", "npm:9.0.0"]], + "linkType": "HARD" + }]]] + ] +}` + +func loadFallback(t *testing.T) *Manifest { + t.Helper() + const manifestPath = "/proj/.pnp.data.json" + m, ok := Load(manifestPath, func(p string) (string, bool) { + if p == manifestPath { + return fallbackManifest, true + } + return "", false + }) + if !ok { + t.Fatal("failed to load fallback manifest") + } + return m +} + +func TestResolveTopLevelFallback(t *testing.T) { + t.Parallel() + m := loadFallback(t) + // app-a does not declare "shared", but the top-level package does and app-a is + // not on the exclusion list: the fallback resolves it. + if r := m.Resolve("shared", "/proj/packages/app-a"); r.Status != Success || + !strings.Contains(r.PackageDir, "shared-npm-1.0.0-abc.zip") { + t.Fatalf("app-a fallback to shared: status %d dir %q", r.Status, r.PackageDir) + } + // The fallback pool (distinct from the top-level deps) also satisfies an + // undeclared specifier. + if r := m.Resolve("pooled", "/proj/packages/app-a"); r.Status != Success || + !strings.Contains(r.PackageDir, "pooled-npm-9.0.0-def.zip") { + t.Fatalf("app-a fallback to pooled: status %d dir %q", r.Status, r.PackageDir) + } +} + +func TestResolveFallbackExclusion(t *testing.T) { + t.Parallel() + m := loadFallback(t) + // app-b IS on the fallbackExclusionList, so the top-level fallback does not + // apply: an undeclared specifier is NotFound, not silently resolved. + if r := m.Resolve("shared", "/proj/packages/app-b"); r.Status != NotFound { + t.Fatalf("app-b (excluded) resolving shared: status %d, want NotFound", r.Status) + } +} + +func TestResolveTopLevelDoesNotFallBack(t *testing.T) { + t.Parallel() + m := loadFallback(t) + // The synthetic top-level (root) locator never uses fallbacks — it is the + // fallback source. "pooled" lives only in the fallback pool, so a non-root + // package reaches it but the root does not (an undeclared specifier from the + // root is NotFound, matching Yarn's `issuerLocator.name !== null` guard). + if r := m.Resolve("pooled", "/proj/packages/app-a"); r.Status != Success { + t.Fatalf("app-a resolving pooled: status %d, want Success", r.Status) + } + if r := m.Resolve("pooled", "/proj"); r.Status != NotFound { + t.Fatalf("root resolving pooled via pool: status %d, want NotFound (root must not fall back)", r.Status) + } +} + +func TestResolveBareIdentifierParse(t *testing.T) { + t.Parallel() + m := loadFixture(t) + cases := []struct { + specifier string + wantFail bool + }{ + {"@scope", true}, // scoped name with no second segment is invalid + {"@scope/pkg/sub", false}, // scoped name + subpath parses (then resolves/NotFound) + {"pkg/sub/deep", false}, // unscoped name + multi-segment subpath parses + } + for _, c := range cases { + r := m.Resolve(c.specifier, "/proj/packages/util") + if c.wantFail && r.Status != Failed { + t.Errorf("Resolve(%q) status = %d, want Failed", c.specifier, r.Status) + } + if !c.wantFail && r.Status == Failed { + t.Errorf("Resolve(%q) status = Failed, want a parse success", c.specifier) + } + } +} + +func TestResolveCarriesScopedSubpath(t *testing.T) { + t.Parallel() + m := loadFixture(t) + // The subpath after a scoped package name is carried through unresolved-file + // resolution as the Subpath (here the package @t/util resolves and "/deep/x" + // rides along). + r := m.Resolve("@t/util/deep/x", "/proj") + if r.Status != Success || r.Subpath != "/deep/x" { + t.Fatalf("@t/util/deep/x: status %d subpath %q", r.Status, r.Subpath) + } +} + +func TestLoadRejectsMalformed(t *testing.T) { + t.Parallel() + read := func(contents string) func(string) (string, bool) { + return func(p string) (string, bool) { + if p == "/proj/.pnp.data.json" || p == "/proj/.pnp.cjs" { + return contents, true + } + return "", false + } + } + // Malformed JSON sidecar. + if _, ok := Load("/proj/.pnp.data.json", read(`{not json`)); ok { + t.Error("Load accepted malformed JSON") + } + // A .pnp.cjs with no RAW_RUNTIME_STATE marker. + if _, ok := Load("/proj/.pnp.cjs", read("module.exports = {};\n")); ok { + t.Error("Load accepted a .cjs with no manifest marker") + } + // The marker present but NOT an assignment (e.g. only the JSON.parse use): + // requiring "=" keeps a stray textual mention from being mis-extracted. + if _, ok := Load("/proj/.pnp.cjs", read("hydrate(JSON.parse(RAW_RUNTIME_STATE));\n")); ok { + t.Error("Load accepted a RAW_RUNTIME_STATE use with no assignment") + } + // A missing file. + if _, ok := Load("/proj/.pnp.data.json", func(string) (string, bool) { return "", false }); ok { + t.Error("Load accepted a missing manifest file") + } +} diff --git a/internal/pnp/find.go b/internal/pnp/find.go new file mode 100644 index 00000000000..122a003d329 --- /dev/null +++ b/internal/pnp/find.go @@ -0,0 +1,26 @@ +package pnp + +import ( + "github.com/microsoft/typescript-go/internal/tspath" +) + +// Manifest filenames, in the discovery order Yarn and esbuild use. Yarn writes +// .pnp.cjs always; .pnp.data.json additionally when pnpEnableInlining is false. +var manifestNames = []string{".pnp.data.json", ".pnp.cjs", ".pnp.js"} + +// Find walks up from startDir (an absolute, normalized directory) looking for a +// PnP manifest, and returns the absolute path of the manifest file to load +// (preferring a .pnp.data.json sidecar, else the .pnp.cjs the data is inlined +// into), or "" if there is no PnP manifest above startDir. +func Find(startDir string, fileExists func(string) bool) string { + manifest, _ := tspath.ForEachAncestorDirectory(tspath.NormalizePath(startDir), func(dir string) (string, bool) { + for _, name := range manifestNames { + candidate := tspath.CombinePaths(dir, name) + if fileExists(candidate) { + return candidate, true + } + } + return "", false + }) + return manifest +} diff --git a/internal/pnp/pnp.go b/internal/pnp/pnp.go new file mode 100644 index 00000000000..7fae9633ecd --- /dev/null +++ b/internal/pnp/pnp.go @@ -0,0 +1,567 @@ +// Package pnp implements Yarn Plug'n'Play module resolution. A PnP project has +// no node_modules tree; instead a manifest (.pnp.data.json, or .pnp.cjs with the +// data embedded) maps every (package, importer) pair to the on-disk location of +// the dependency. This package loads that manifest and answers the one question +// the module resolver needs: given a bare specifier's package identifier and the +// directory it is imported from, where does that package live? +// +// The algorithm is a transcription of the Yarn PnP specification's +// RESOLVE_TO_UNQUALIFIED, following the reference resolver's actual behavior where +// it diverges from the spec (the trailing-slash longest-prefix locator loop). It +// deliberately mirrors esbuild's Go implementation so the two agree. +package pnp + +import ( + "regexp" + "strconv" + "strings" + + "github.com/microsoft/typescript-go/internal/json" + "github.com/microsoft/typescript-go/internal/tspath" +) + +// identAndRef is a dependency target: a reference (ident==""), an alias (both +// set), or an unfulfilled peer dependency (both ""). An absent entry is distinct +// from a present-but-null one, so callers check presence separately. +type identAndRef struct { + ident string + reference string +} + +type pkg struct { + packageLocation string + packageDependencies map[string]identAndRef +} + +type locatorByLocation struct { + locator identAndRef + discardFromLookup bool +} + +// Manifest is a compiled PnP manifest. +type Manifest struct { + // manifestDir is the absolute, normalized directory the manifest lives in; + // all packageLocation values are relative to it. + manifestDir string + + enableTopLevelFallback bool + fallbackPool map[string]identAndRef + fallbackExclusionList map[string]map[string]bool + ignorePattern *regexp.Regexp + + // packageRegistry[ident][reference] -> package. The top-level package is + // keyed by ("", ""). + packageRegistry map[string]map[string]pkg + // packageLocatorsByLocation reverse-indexes a package location (verbatim, + // as stored in the manifest, relative and trailing-slashed) to its locator. + packageLocatorsByLocation map[string]locatorByLocation +} + +// --- raw JSON shapes ------------------------------------------------------- + +// The manifest tables are arrays of pairs, e.g. packageRegistryData is +// [[ident|null, [[reference|null, packageObject], ...]], ...]. json.Value +// preserves the null-vs-string distinction the spec depends on. +type rawManifest struct { + EnableTopLevelFallback bool `json:"enableTopLevelFallback"` + IgnorePatternData string `json:"ignorePatternData"` + FallbackPool [][2]json.Value `json:"fallbackPool"` + FallbackExclusionList [][2]json.Value `json:"fallbackExclusionList"` + PackageRegistryData [][2]json.Value `json:"packageRegistryData"` +} + +type rawPackage struct { + PackageLocation string `json:"packageLocation"` + PackageDependencies [][2]json.Value `json:"packageDependencies"` + DiscardFromLookup bool `json:"discardFromLookup"` +} + +// stringOrNull decodes a JSON string or null; null yields ("", true), matching +// the spec's convention of encoding a null ident/reference as the empty string. +func stringOrNull(raw json.Value) (string, bool) { + var s *string + if err := json.Unmarshal(raw, &s); err != nil { + return "", false + } + if s == nil { + return "", true + } + return *s, true +} + +// dependencyTarget decodes a packageDependencies value: a string reference, a +// [ident, reference] alias array, or null (unfulfilled peer). ok is false only +// on a malformed value. +func dependencyTarget(raw json.Value) (identAndRef, bool) { + trimmed := strings.TrimSpace(string(raw)) + if trimmed == "null" { + return identAndRef{}, true + } + if strings.HasPrefix(trimmed, "[") { + var pair [2]string + if err := json.Unmarshal(raw, &pair); err != nil { + return identAndRef{}, false + } + return identAndRef{ident: pair[0], reference: pair[1]}, true + } + var s string + if err := json.Unmarshal(raw, &s); err != nil { + return identAndRef{}, false + } + return identAndRef{reference: s}, true +} + +// Load parses and compiles a PnP manifest. manifestPath is the absolute, +// normalized path of a .pnp.data.json sidecar or the .pnp.cjs the data is inlined +// into (Yarn's default); readFile reads it. +func Load(manifestPath string, readFile func(string) (string, bool)) (*Manifest, bool) { + contents, ok := readFile(manifestPath) + if !ok { + return nil, false + } + if !strings.HasSuffix(manifestPath, ".json") { + // A .pnp.cjs/.pnp.js embeds the data as a JS string literal; extract it. + contents, ok = extractInlinedManifest(contents) + if !ok { + return nil, false + } + } + var raw rawManifest + if err := json.Unmarshal([]byte(contents), &raw); err != nil { + return nil, false + } + + m := &Manifest{ + manifestDir: tspath.GetDirectoryPath(manifestPath), + enableTopLevelFallback: raw.EnableTopLevelFallback, + fallbackPool: map[string]identAndRef{}, + fallbackExclusionList: map[string]map[string]bool{}, + packageRegistry: map[string]map[string]pkg{}, + packageLocatorsByLocation: map[string]locatorByLocation{}, + } + + if raw.IgnorePatternData != "" { + m.ignorePattern = compileIgnorePattern(raw.IgnorePatternData) + } + + for _, entry := range raw.FallbackExclusionList { + ident, ok := stringOrNull(entry[0]) + if !ok { + continue + } + var refs []string + if err := json.Unmarshal(entry[1], &refs); err != nil { + continue + } + set := make(map[string]bool, len(refs)) + for _, r := range refs { + set[r] = true + } + m.fallbackExclusionList[ident] = set + } + + for _, entry := range raw.FallbackPool { + ident, ok := stringOrNull(entry[0]) + if !ok { + continue + } + if target, ok := dependencyTarget(entry[1]); ok { + m.fallbackPool[ident] = target + } + } + + for _, entry := range raw.PackageRegistryData { + ident, ok := stringOrNull(entry[0]) + if !ok { + continue + } + var refList [][2]json.Value + if err := json.Unmarshal(entry[1], &refList); err != nil { + continue + } + refs := m.packageRegistry[ident] + if refs == nil { + refs = map[string]pkg{} + m.packageRegistry[ident] = refs + } + for _, refEntry := range refList { + reference, ok := stringOrNull(refEntry[0]) + if !ok { + continue + } + var rp rawPackage + if err := json.Unmarshal(refEntry[1], &rp); err != nil { + continue + } + deps := make(map[string]identAndRef, len(rp.PackageDependencies)) + for _, dep := range rp.PackageDependencies { + var depIdent string + if err := json.Unmarshal(dep[0], &depIdent); err != nil { + continue + } + if target, ok := dependencyTarget(dep[1]); ok { + deps[depIdent] = target + } + } + refs[reference] = pkg{ + packageLocation: rp.PackageLocation, + packageDependencies: deps, + } + + // Replicate Yarn's hydrateRuntimeState: first locator at a location + // wins unless discarded; a later non-discarded entry overwrites a + // discarded one; the discard flag is AND-ed across entries. + if existing, ok := m.packageLocatorsByLocation[rp.PackageLocation]; !ok { + m.packageLocatorsByLocation[rp.PackageLocation] = locatorByLocation{ + locator: identAndRef{ident: ident, reference: reference}, + discardFromLookup: rp.DiscardFromLookup, + } + } else { + existing.discardFromLookup = existing.discardFromLookup && rp.DiscardFromLookup + if !rp.DiscardFromLookup { + existing.locator = identAndRef{ident: ident, reference: reference} + } + m.packageLocatorsByLocation[rp.PackageLocation] = existing + } + } + } + + return m, true +} + +// compileIgnorePattern strips the negative-lookahead sequences Yarn emits (Go's +// RE2 rejects them; they only exclude "."/".." path segments that never occur +// here) and compiles the rest, or returns nil if it still won't compile. +func compileIgnorePattern(src string) *regexp.Regexp { + for _, la := range []string{ + `(?!\.)`, + `(?!(?:^|\/)\.)`, + `(?!\.{1,2}(?:\/|$))`, + `(?!(?:^|\/)\.{1,2}(?:\/|$))`, + } { + src = strings.ReplaceAll(src, la, "") + } + reg, err := regexp.Compile(src) + if err != nil { + return nil + } + return reg +} + +// extractInlinedManifest pulls the JSON payload out of a .pnp.cjs. Yarn embeds it +// as `const RAW_RUNTIME_STATE = '';` — a single-quoted JS string literal +// whose newlines are backslash line-continuations — and passes it to +// hydrateRuntimeState(JSON.parse(RAW_RUNTIME_STATE)). This finds that literal and +// unescapes it back to JSON without a JS parser. Returns false if the marker or a +// closing quote is absent. +func extractInlinedManifest(contents string) (string, bool) { + const marker = "RAW_RUNTIME_STATE" + _, rest, found := strings.Cut(contents, marker) + if !found { + return "", false + } + // Require the assignment operator (so an earlier textual mention of + // RAW_RUNTIME_STATE — a comment, or the JSON.parse(RAW_RUNTIME_STATE) use — + // cannot be mistaken for the declaration), tolerating any spacing/newlines + // around it (`RAW_RUNTIME_STATE =`, `RAW_RUNTIME_STATE=`, `... =\n'`). Then + // find the opening quote of the string literal. + rest = strings.TrimLeft(rest, " \t\r\n") + rest, found = strings.CutPrefix(rest, "=") + if !found { + return "", false + } + q := strings.IndexAny(rest, "'\"`") + if q < 0 { + return "", false + } + quote := rest[q] + body := rest[q+1:] + var sb strings.Builder + for j := 0; j < len(body); j++ { + c := body[j] + if c == quote { + return sb.String(), true + } + if c != '\\' || j+1 >= len(body) { + sb.WriteByte(c) + continue + } + n := body[j+1] + j++ + switch n { + case '\n': // line continuation: emit nothing + case '\r': + if j+1 < len(body) && body[j+1] == '\n' { + j++ + } + case 'n': + sb.WriteByte('\n') + case 't': + sb.WriteByte('\t') + case 'r': + sb.WriteByte('\r') + case 'b': + sb.WriteByte('\b') + case 'f': + sb.WriteByte('\f') + case 'v': + sb.WriteByte('\v') + case '0': + sb.WriteByte(0) + default: + // \\, \', \", \`, and any other escape: the following character + // verbatim (JS treats an unknown escape as the character itself). + sb.WriteByte(n) + } + } + return "", false +} + +// DerefVirtualPath rewrites a Yarn PnP virtual path +// (/__virtual__///) to its real backing path by applying +// the ".." operation n times to the prefix, so file access reaches the real cache +// archive. A path with no virtual segment is returned unchanged. Ported from +// esbuild's ParseYarnPnPVirtualPath; forward-slash paths only (tsgo normalizes). +func DerefVirtualPath(path string) string { + i := 0 + for { + start := i + slash := strings.IndexByte(path[i:], '/') + if slash == -1 { + return path + } + i += slash + 1 + segment := path[start : i-1] + if segment != "__virtual__" && segment != "$$virtual" { + continue + } + slash = strings.IndexByte(path[i:], '/') + if slash == -1 { + return path + } + j := i + slash + 1 + var count, suffix string + if s := strings.IndexByte(path[j:], '/'); s != -1 { + count = path[j : j+s] + suffix = path[j+s:] + } else { + count = path[j:] + } + n, err := strconv.ParseInt(count, 10, 64) + if err != nil { + continue + } + prefix := path[:start] + for n > 0 && strings.HasSuffix(prefix, "/") { + s := strings.LastIndexByte(prefix[:len(prefix)-1], '/') + if s == -1 { + break + } + prefix = prefix[:s+1] + n-- + } + if suffix == "" && strings.IndexByte(prefix, '/') != strings.LastIndexByte(prefix, '/') { + prefix = prefix[:len(prefix)-1] + } else if prefix == "" { + prefix = "." + } else if strings.HasPrefix(suffix, "/") { + suffix = suffix[1:] + } + return prefix + suffix + } +} + +// parseBareIdentifier splits a specifier into its package identifier and the +// subpath within the package. A scoped name without a "/" is invalid. +func parseBareIdentifier(specifier string) (ident string, modulePath string, ok bool) { + slash := strings.IndexByte(specifier, '/') + if strings.HasPrefix(specifier, "@") { + if slash == -1 { + return "", "", false + } + if slash2 := strings.IndexByte(specifier[slash+1:], '/'); slash2 != -1 { + ident = specifier[:slash+1+slash2] + } else { + ident = specifier + } + } else if slash != -1 { + ident = specifier[:slash] + } else { + ident = specifier + } + modulePath = specifier[len(ident):] + return ident, modulePath, true +} + +// Status is the outcome of a PnP resolution. +type Status uint8 + +const ( + // Skipped: the importer is not governed by PnP (ignored path, or no locator + // found). The caller should fall back to classic node_modules resolution. + Skipped Status = iota + // Success: the package was located. + Success + // NotFound: the specifier is not a declared dependency of the importer. + NotFound + // UnfulfilledPeer: the dependency is a null-valued (unfulfilled) peer. + UnfulfilledPeer + // Failed: a manifest invariant was violated (should not happen). + Failed +) + +// Result of a resolution. +type Result struct { + Status Status + // PackageDir is the absolute, normalized directory the resolved package + // lives in (may be inside a Yarn cache .zip). Valid only when Status is + // Success. + PackageDir string + // Subpath is the portion of the specifier after the package identifier + // (including a leading "/" when present). + Subpath string +} + +// Resolve locates the package named by specifier as imported from importerDir +// (an absolute, normalized directory). It answers RESOLVE_TO_UNQUALIFIED: the +// package directory, before file/extension/exports resolution runs on it. +func (m *Manifest) Resolve(specifier string, importerDir string) Result { + ident, modulePath, ok := parseBareIdentifier(specifier) + if !ok { + return Result{Status: Failed} + } + + parentLocator, ok := m.findLocator(importerDir) + if !ok { + return Result{Status: Skipped} + } + + parentPkg, ok := m.getPackage(parentLocator.ident, parentLocator.reference) + if !ok { + return Result{Status: Failed} + } + + target, ok := parentPkg.packageDependencies[ident] + if !ok || target.reference == "" { + // Not listed (or null-valued): try the fallback set. The synthetic + // top-level locator (empty ident, name===null in Yarn) never uses + // fallbacks — it IS the fallback source, so a specifier the root does not + // declare is genuinely NotFound rather than pulled from the pool. Workspaces + // are kept out separately via the fallbackExclusionList. (Mirrors berry + // makeApi resolveToUnqualified: `if (issuerLocator.name !== null)` guarding + // the fallback block, plus the exclusion check.) + if m.enableTopLevelFallback && parentLocator.ident != "" { + if set := m.fallbackExclusionList[parentLocator.ident]; !set[parentLocator.reference] { + if fallback, found := m.resolveViaFallback(ident); found && fallback.reference != "" { + target = fallback + ok = true + } + } + } + } + + if !ok { + return Result{Status: NotFound} + } + if target.reference == "" { + return Result{Status: UnfulfilledPeer} + } + + var dependencyPkg pkg + if target.ident != "" { + // Aliased dependency. + if dependencyPkg, ok = m.getPackage(target.ident, target.reference); !ok { + return Result{Status: Failed} + } + } else { + if dependencyPkg, ok = m.getPackage(ident, target.reference); !ok { + return Result{Status: Failed} + } + } + + // path.resolve(manifestDir, packageLocation, modulePath). packageLocation is + // relative (e.g. "./packages/util/" or "./.yarn/cache/x.zip/node_modules/x/"), + // and for a peer-dependency-virtualized package it is a __virtual__// + // path. The location is returned as-is (virtual paths are NOT dereferenced + // here): the package registry's locator table is keyed by these raw locations, + // so a file resolved under a virtual path must keep that path for findLocator to + // identify its owning package when resolving its own imports. The zip overlay + // dereferences virtual paths when it actually reads from the filesystem. + // Canonicalize to a directory path with no trailing separator; the resolver + // joins file names onto it. + pkgDir := tspath.RemoveTrailingDirectorySeparator(tspath.NormalizePath(tspath.CombinePaths(m.manifestDir, dependencyPkg.packageLocation))) + return Result{ + Status: Success, + PackageDir: pkgDir, + Subpath: modulePath, + } +} + +// findLocator finds the package that owns importerDir, walking up path prefixes. +func (m *Manifest) findLocator(importerDir string) (identAndRef, bool) { + // A non-absolute importer directory cannot be located against the manifest's + // absolute locations; treat it as not PnP-governed rather than risk a relative + // path accidentally prefix-matching a locator. + if !tspath.IsRootedDiskPath(importerDir) { + return identAndRef{}, false + } + // Relative path from the manifest directory to the importer, forward-slashed. + rel := tspath.GetRelativePathFromDirectory(m.manifestDir, importerDir, tspath.ComparePathsOptions{ + UseCaseSensitiveFileNames: true, + CurrentDirectory: m.manifestDir, + }) + rel = tspath.NormalizeSlashes(rel) + rel = strings.TrimPrefix(rel, "./") + + if m.ignorePattern != nil && m.ignorePattern.MatchString(rel) { + return identAndRef{}, false + } + + // Locations in the manifest are trailing-slashed and start with ./ or ../. + if !strings.HasSuffix(rel, "/") { + rel += "/" + } + if !strings.HasPrefix(rel, "./") && !strings.HasPrefix(rel, "../") { + rel = "./" + rel + } + + // Longest-prefix loop, per the reference implementation (not the spec's + // hypothetical algorithm). + for { + entry, ok := m.packageLocatorsByLocation[rel] + if !ok || entry.discardFromLookup { + idx := strings.LastIndexByte(rel[:len(rel)-1], '/') + if idx < 0 { + break + } + rel = rel[:idx+1] + if rel == "" { + break + } + continue + } + return entry.locator, true + } + return identAndRef{}, false +} + +func (m *Manifest) resolveViaFallback(ident string) (identAndRef, bool) { + topLevel, ok := m.getPackage("", "") + if !ok { + return identAndRef{}, false + } + if target, found := topLevel.packageDependencies[ident]; found { + return target, true + } + target, found := m.fallbackPool[ident] + return target, found +} + +func (m *Manifest) getPackage(ident string, reference string) (pkg, bool) { + if refs, ok := m.packageRegistry[ident]; ok { + if p, ok := refs[reference]; ok { + return p, true + } + } + return pkg{}, false +} diff --git a/internal/pnp/pnp_test.go b/internal/pnp/pnp_test.go new file mode 100644 index 00000000000..761db277c35 --- /dev/null +++ b/internal/pnp/pnp_test.go @@ -0,0 +1,419 @@ +package pnp + +import ( + "strings" + "testing" +) + +// A hand-written manifest mirroring the shape Yarn emits: a top-level package, a +// workspace package (SOFT link, on-disk location) that depends on an npm package +// (HARD link, a location inside a cache .zip), plus an aliased dependency and an +// unfulfilled peer. +const fixtureManifest = `{ + "__info": ["generated"], + "dependencyTreeRoots": [{"name": "root", "reference": "workspace:."}], + "enableTopLevelFallback": true, + "ignorePatternData": "(^(?:\\.yarn\\/sdks(?:\\/(?!\\.{1,2}(?:\\/|$))(?:(?:(?!(?:^|\\/)\\.{1,2}(?:\\/|$)).)*?)|$))$)", + "fallbackExclusionList": [["root", ["workspace:."]]], + "fallbackPool": [], + "packageRegistryData": [ + [null, [["workspace:.", { + "packageLocation": "./", + "packageDependencies": [["@t/util", "workspace:packages/util"]], + "linkType": "SOFT" + }]]], + ["@t/util", [["workspace:packages/util", { + "packageLocation": "./packages/util/", + "packageDependencies": [ + ["@t/util", "workspace:packages/util"], + ["lodash", "npm:4.17.21"], + ["aliased", ["real-pkg", "npm:1.0.0"]], + ["peer-dep", null] + ], + "linkType": "SOFT" + }]]], + ["lodash", [["npm:4.17.21", { + "packageLocation": "./.yarn/cache/lodash-npm-4.17.21-abc.zip/node_modules/lodash/", + "packageDependencies": [["lodash", "npm:4.17.21"]], + "linkType": "HARD" + }]]], + ["real-pkg", [["npm:1.0.0", { + "packageLocation": "./.yarn/cache/real-pkg-npm-1.0.0-def.zip/node_modules/real-pkg/", + "packageDependencies": [["real-pkg", "npm:1.0.0"]], + "linkType": "HARD" + }]]] + ] +}` + +func loadFixture(t *testing.T) *Manifest { + t.Helper() + const manifestPath = "/proj/.pnp.data.json" + m, ok := Load(manifestPath, func(p string) (string, bool) { + if p == manifestPath { + return fixtureManifest, true + } + return "", false + }) + if !ok { + t.Fatal("failed to load fixture manifest") + } + return m +} + +func TestResolveWorkspaceDependency(t *testing.T) { + t.Parallel() + m := loadFixture(t) + r := m.Resolve("@t/util", "/proj") + if r.Status != Success { + t.Fatalf("status = %d, want Success", r.Status) + } + if r.PackageDir != "/proj/packages/util" { + t.Fatalf("PackageDir = %q", r.PackageDir) + } +} + +func TestResolveNpmDependencyInsideZip(t *testing.T) { + t.Parallel() + m := loadFixture(t) + r := m.Resolve("lodash", "/proj/packages/util") + if r.Status != Success { + t.Fatalf("status = %d, want Success", r.Status) + } + want := "/proj/.yarn/cache/lodash-npm-4.17.21-abc.zip/node_modules/lodash" + if r.PackageDir != want { + t.Fatalf("PackageDir = %q, want %q", r.PackageDir, want) + } +} + +func TestResolveSubpathCarriedThrough(t *testing.T) { + t.Parallel() + m := loadFixture(t) + r := m.Resolve("lodash/fp", "/proj/packages/util") + if r.Status != Success || r.Subpath != "/fp" { + t.Fatalf("status = %d subpath = %q", r.Status, r.Subpath) + } +} + +func TestResolveAliasedDependency(t *testing.T) { + t.Parallel() + m := loadFixture(t) + // "aliased" points at ["real-pkg","npm:1.0.0"]; it must resolve to real-pkg's location. + r := m.Resolve("aliased", "/proj/packages/util") + if r.Status != Success { + t.Fatalf("status = %d, want Success", r.Status) + } + if !strings.Contains(r.PackageDir, ".zip/") || r.PackageDir != "/proj/.yarn/cache/real-pkg-npm-1.0.0-def.zip/node_modules/real-pkg" { + t.Fatalf("aliased PackageDir = %q", r.PackageDir) + } +} + +func TestResolveUnfulfilledPeer(t *testing.T) { + t.Parallel() + m := loadFixture(t) + r := m.Resolve("peer-dep", "/proj/packages/util") + if r.Status != UnfulfilledPeer { + t.Fatalf("status = %d, want UnfulfilledPeer", r.Status) + } +} + +func TestResolveNotADependency(t *testing.T) { + t.Parallel() + m := loadFixture(t) + // lodash is a dep of @t/util but not of the top-level package, and there is + // no fallback pool entry, so resolving it from the root fails. + r := m.Resolve("lodash", "/proj") + if r.Status == Success { + t.Fatalf("unexpectedly resolved lodash from root to %q", r.PackageDir) + } +} + +func TestResolveIgnoredImporterSkips(t *testing.T) { + t.Parallel() + m := loadFixture(t) + // A .yarn/sdks path matches ignorePatternData -> Skipped (fall back to classic). + r := m.Resolve("lodash", "/proj/.yarn/sdks/typescript") + if r.Status != Skipped { + t.Fatalf("status = %d, want Skipped", r.Status) + } +} + +func TestResolveGovernedNotFoundDistinctFromSkipped(t *testing.T) { + t.Parallel() + m := loadFixture(t) + // The root workspace IS governed by PnP, but "lodash" is not one of its + // declared dependencies and there is no fallback pool entry: the status is + // NotFound, NOT Skipped. The resolver relies on this distinction — a governed + // NotFound must stop the classic node_modules walk (so a phantom dependency in + // a stray node_modules is not resolved), whereas Skipped falls through to it. + if r := m.Resolve("lodash", "/proj"); r.Status != NotFound { + t.Fatalf("undeclared dep from governed importer: status = %d, want NotFound", r.Status) + } + // An unfulfilled peer is also governed (not Skipped). + if r := m.Resolve("peer-dep", "/proj/packages/util"); r.Status != UnfulfilledPeer { + t.Fatalf("unfulfilled peer: status = %d, want UnfulfilledPeer", r.Status) + } + // A non-absolute importer directory cannot be located against the absolute + // manifest: Skipped (fall back to the classic walk), never a false match. + if r := m.Resolve("lodash", "packages/util"); r.Status != Skipped { + t.Fatalf("relative importer: status = %d, want Skipped", r.Status) + } +} + +func TestLoadInlinedCjsTightSpacing(t *testing.T) { + t.Parallel() + // Yarn's spacing around the assignment is not guaranteed; the extractor must + // tolerate `RAW_RUNTIME_STATE=` (no spaces) as well as `RAW_RUNTIME_STATE =`. + jsEscaped := strings.ReplaceAll(fixtureManifest, `\`, `\\`) + jsEscaped = strings.ReplaceAll(jsEscaped, "\n", "\\\n") + cjs := "const RAW_RUNTIME_STATE='" + jsEscaped + "';\n" + const manifestPath = "/proj/.pnp.cjs" + m, ok := Load(manifestPath, func(p string) (string, bool) { + if p == manifestPath { + return cjs, true + } + return "", false + }) + if !ok { + t.Fatal("failed to load tightly-spaced inlined .pnp.cjs") + } + if r := m.Resolve("@t/util", "/proj"); r.Status != Success { + t.Fatalf("@t/util from tight-spacing manifest: status %d", r.Status) + } +} + +// A manifest whose dependency locations are Yarn __virtual__ paths (the shape +// emitted for packages with peer dependencies): a workspace lib virtualized into +// a plain directory (count 1) and an npm package virtualized into a cache .zip +// (count 0). +const virtualFixtureManifest = `{ + "dependencyTreeRoots": [{"name": "root", "reference": "workspace:."}], + "enableTopLevelFallback": true, + "fallbackExclusionList": [], + "fallbackPool": [], + "packageRegistryData": [ + [null, [["workspace:.", { + "packageLocation": "./", + "packageDependencies": [ + ["@w/ui", "virtual:aaa#workspace:packages/ui"], + ["react-dom", "virtual:bbb#npm:18.3.1"] + ], + "linkType": "SOFT" + }]]], + ["@w/ui", [["virtual:aaa#workspace:packages/ui", { + "packageLocation": "./.yarn/__virtual__/w-ui-virtual-aaa/1/packages/ui/", + "packageDependencies": [["@w/ui", "virtual:aaa#workspace:packages/ui"]], + "linkType": "SOFT" + }]]], + ["react-dom", [["virtual:bbb#npm:18.3.1", { + "packageLocation": "./.yarn/__virtual__/react-dom-virtual-bbb/0/cache/react-dom-npm-18.3.1-abc.zip/node_modules/react-dom/", + "packageDependencies": [ + ["react-dom", "virtual:bbb#npm:18.3.1"], + ["scheduler", "npm:0.23.0"] + ], + "linkType": "HARD" + }]]], + ["scheduler", [["npm:0.23.0", { + "packageLocation": "./.yarn/cache/scheduler-npm-0.23.0-xyz.zip/node_modules/scheduler/", + "packageDependencies": [["scheduler", "npm:0.23.0"]], + "linkType": "HARD" + }]]] + ] +}` + +func TestResolveKeepsVirtualLocation(t *testing.T) { + t.Parallel() + const manifestPath = "/proj/.pnp.data.json" + m, ok := Load(manifestPath, func(p string) (string, bool) { + if p == manifestPath { + return virtualFixtureManifest, true + } + return "", false + }) + if !ok { + t.Fatal("failed to load virtual fixture manifest") + } + // A virtualized package's PackageDir is returned as the __virtual__ path, NOT + // dereferenced: the locator table is keyed by these raw locations, so a file + // resolved under the virtual path must keep it for findLocator to identify its + // owning package when resolving the package's own imports. The zip overlay + // dereferences the path only when it actually reads from the filesystem. + wantUI := "/proj/.yarn/__virtual__/w-ui-virtual-aaa/1/packages/ui" + if r := m.Resolve("@w/ui", "/proj"); r.Status != Success || r.PackageDir != wantUI { + t.Fatalf("@w/ui: status %d dir %q, want Success %q", r.Status, r.PackageDir, wantUI) + } + wantRD := "/proj/.yarn/__virtual__/react-dom-virtual-bbb/0/cache/react-dom-npm-18.3.1-abc.zip/node_modules/react-dom" + if r := m.Resolve("react-dom", "/proj"); r.Status != Success || r.PackageDir != wantRD { + t.Fatalf("react-dom: status %d dir %q, want %q", r.Status, r.PackageDir, wantRD) + } + // findLocator round-trips the virtual location back to the owning package, so + // an import made from inside the virtualized package resolves against that + // package's own dependency map (not the root's). + locator, found := m.findLocator(wantUI) + if !found || locator.ident != "@w/ui" { + t.Fatalf("findLocator(%q) = %+v found=%v, want @w/ui", wantUI, locator, found) + } +} + +// TestResolveTransitiveDepFromVirtualizedPackage is the direct regression for the +// bug where dereferencing PackageDir broke findLocator: "scheduler" is a +// dependency of react-dom but NOT of the root. A file inside react-dom's +// virtualized location importing "scheduler" must resolve through react-dom's own +// dependency map. If the virtual location were collapsed to its real .zip path, +// findLocator would miss react-dom's (virtual-keyed) locator, fall through to the +// root — which does not declare scheduler — and the import would be NotFound. +func TestResolveTransitiveDepFromVirtualizedPackage(t *testing.T) { + t.Parallel() + const manifestPath = "/proj/.pnp.data.json" + m, ok := Load(manifestPath, func(p string) (string, bool) { + if p == manifestPath { + return virtualFixtureManifest, true + } + return "", false + }) + if !ok { + t.Fatal("failed to load virtual fixture manifest") + } + // Sanity: scheduler is not resolvable from the root (it is not a root dep and + // the root does not fall back), so a successful resolution below can only come + // from react-dom's own dependency map. + if r := m.Resolve("scheduler", "/proj"); r.Status == Success { + t.Fatalf("scheduler unexpectedly resolvable from root: %q", r.PackageDir) + } + // Model the real resolver flow: react-dom's resolved PackageDir becomes the + // importer directory for react-dom's own imports. Feeding that returned + // location straight back into Resolve is what exposes the bug — if PackageDir + // were dereferenced to the real .zip path, the importer would no longer be in + // the virtual locator space and findLocator would miss react-dom. + rd := m.Resolve("react-dom", "/proj") + if rd.Status != Success { + t.Fatalf("react-dom from root: status %d, want Success", rd.Status) + } + r := m.Resolve("scheduler", rd.PackageDir) + if r.Status != Success { + t.Fatalf("scheduler from inside react-dom (importer %q): status %d, want Success (findLocator must match the virtual locator)", rd.PackageDir, r.Status) + } + if !strings.Contains(r.PackageDir, "scheduler-npm-0.23.0-xyz.zip") { + t.Fatalf("scheduler PackageDir = %q, want the scheduler cache zip", r.PackageDir) + } +} + +func TestFindWalksUp(t *testing.T) { + t.Parallel() + // Only .pnp.cjs exists (Yarn's inlining default): Find returns it. + got := Find("/proj/packages/app/src", func(p string) bool { return p == "/proj/.pnp.cjs" }) + if got != "/proj/.pnp.cjs" { + t.Fatalf("Find = %q, want /proj/.pnp.cjs", got) + } + // When both exist, the .pnp.data.json sidecar is preferred. + got = Find("/proj/packages/app/src", func(p string) bool { + return p == "/proj/.pnp.cjs" || p == "/proj/.pnp.data.json" + }) + if got != "/proj/.pnp.data.json" { + t.Fatalf("Find = %q, want /proj/.pnp.data.json", got) + } + if Find("/elsewhere", func(string) bool { return false }) != "" { + t.Fatal("Find should return empty when no manifest exists") + } +} + +func TestLoadInlinedCjs(t *testing.T) { + t.Parallel() + // Emulate a .pnp.cjs: the manifest JSON embedded as a backslash-continued, + // single-quoted RAW_RUNTIME_STATE literal (backslashes doubled, newlines + // continued), the shape Yarn writes by default (pnpEnableInlining). + jsEscaped := strings.ReplaceAll(fixtureManifest, `\`, `\\`) + jsEscaped = strings.ReplaceAll(jsEscaped, "\n", "\\\n") + cjs := "/* prologue */\nconst RAW_RUNTIME_STATE =\n'" + jsEscaped + + "'\n;\nfunction $$SETUP_STATE(h){return h(JSON.parse(RAW_RUNTIME_STATE));}\n" + + const manifestPath = "/proj/.pnp.cjs" + m, ok := Load(manifestPath, func(p string) (string, bool) { + if p == manifestPath { + return cjs, true + } + return "", false + }) + if !ok { + t.Fatal("failed to load inlined .pnp.cjs") + } + if r := m.Resolve("@t/util", "/proj"); r.Status != Success || r.PackageDir != "/proj/packages/util" { + t.Fatalf("@t/util from inlined manifest: status %d dir %q", r.Status, r.PackageDir) + } +} + +func TestDerefVirtualPath(t *testing.T) { + t.Parallel() + cases := []struct{ in, want string }{ + // n=0: no ".." applied, the __virtual__//0 segment is removed. + { + "/proj/.yarn/__virtual__/react-dom-virtual-7b/0/cache/react-dom.zip/node_modules/react-dom/index.js", + "/proj/.yarn/cache/react-dom.zip/node_modules/react-dom/index.js", + }, + // n=1 into a plain directory (a workspace lib with a peer dep): pops the + // ".yarn" segment before the triple. This is the non-.zip virtual path that + // the overlay must dereference and delegate. Mirrors the real Yarn location + // ./.yarn/__virtual__/@w-ui-virtual-/1/packages/ui/. + { + "/proj/.yarn/__virtual__/w-ui-virtual-aaa/1/packages/ui/src/index.ts", + "/proj/packages/ui/src/index.ts", + }, + // $$virtual: the legacy (Yarn <3) spelling is handled identically. + { + "/proj/.yarn/$$virtual/w-ui-virtual-aaa/1/packages/ui/src/index.ts", + "/proj/packages/ui/src/index.ts", + }, + // n=2 pops two parent segments. + { + "/proj/a/b/__virtual__/h/2/x/y.ts", + "/proj/x/y.ts", + }, + // Non-numeric count: NOT a Yarn virtual path, returned unchanged. This is + // the guard that keeps a real directory literally named "__virtual__" from + // being corrupted. + { + "/proj/src/__virtual__/fixtures/index.ts", + "/proj/src/__virtual__/fixtures/index.ts", + }, + // __virtual__ as the last segment (no hash/count following): unchanged. + { + "/proj/src/__virtual__", + "/proj/src/__virtual__", + }, + // Ported from Yarn berry VirtualFS.test.ts "should ignore non-hash virtual + // components": a __virtual__ dir with a child but no count segment after it + // is left unchanged. + { + "/proj/__virtual__/package.json", + "/proj/__virtual__/package.json", + }, + // berry "should map numbered virtual components (1, no file)": the package + // dir itself at depth 1. + { + "/proj/__virtual__/12345/1", + "/", + }, + // berry "should preserve dots when mapping" and "empty strings". + {".", "."}, + {"", ""}, + // Count larger than the available parents: the pop clamps at the root + // rather than underflowing. + { + "/__virtual__/h/9/x.ts", + "/x.ts", + }, + // Count with no suffix after it (the package dir itself): the trailing + // separator is dropped rather than left dangling. + { + "/root/.yarn/__virtual__/h/0", + "/root/.yarn", + }, + // no virtual segment: unchanged. + {"/proj/.yarn/cache/react.zip/node_modules/react/index.js", "/proj/.yarn/cache/react.zip/node_modules/react/index.js"}, + {"/proj/packages/app/src/index.ts", "/proj/packages/app/src/index.ts"}, + } + for _, c := range cases { + if got := DerefVirtualPath(c.in); got != c.want { + t.Errorf("DerefVirtualPath(%q) = %q, want %q", c.in, got, c.want) + } + } +} diff --git a/internal/vfs/zipoverlay/zipoverlay.go b/internal/vfs/zipoverlay/zipoverlay.go new file mode 100644 index 00000000000..99af6598921 --- /dev/null +++ b/internal/vfs/zipoverlay/zipoverlay.go @@ -0,0 +1,362 @@ +// Package zipoverlay wraps a vfs.FS so the compiler can read files that live +// inside Yarn PnP cache archives. Under PnP a package's on-disk location can be a +// path whose middle component is a .zip file, e.g. +// +// /proj/.yarn/cache/react-npm-18.3.1-.zip/node_modules/react/index.d.ts +// +// The OS reports the .zip as a regular file, so every path inside it fails +// FileExists/DirectoryExists and the module resolver's parent-directory checks +// abort. This overlay intercepts any path that resolves into a cache archive and +// serves it from the archive, reporting the archive and its interior directories +// as directories so those checks pass. +// +// It also dereferences Yarn's __virtual__// paths (peer-dependency +// virtualization) to their backing location before touching the filesystem — a +// cache .zip for an npm package, or a plain on-disk directory for a +// workspace/unplugged package. The virtual path itself is preserved everywhere +// above the filesystem (the resolver's locator table is keyed by it), so only the +// actual read is redirected. All other paths delegate to the inner FS unchanged. +// +// Zip-internal lookups are case-sensitive. On a case-insensitive host a module +// specifier whose case differs from the archived entry will not resolve; that is +// a known limitation (see #460). +package zipoverlay + +import ( + "archive/zip" + "io" + "io/fs" + "strings" + "sync" + "time" + + "github.com/microsoft/typescript-go/internal/pnp" + "github.com/microsoft/typescript-go/internal/tspath" + "github.com/microsoft/typescript-go/internal/vfs" +) + +const zipMarker = ".zip/" + +type overlay struct { + inner vfs.FS + + mu sync.Mutex + archive map[string]*archiveIndex // keyed by on-disk .zip path +} + +var _ vfs.FS = (*overlay)(nil) + +// Wrap returns a vfs.FS that serves paths inside Yarn cache .zip archives from +// those archives (dereferencing PnP virtual paths first) and delegates everything +// else to inner. +func Wrap(inner vfs.FS) vfs.FS { + return &overlay{ + inner: inner, + archive: map[string]*archiveIndex{}, + } +} + +// split resolves a path for the overlay. It dereferences a PnP virtual segment, +// then reports whether the result addresses a real .zip archive. target is the +// path to delegate to the inner FS when ok is false (the dereferenced path for a +// virtual location backed by a plain directory, or the original path otherwise). +func (o *overlay) split(path string) (zipPath string, internal string, target string, ok bool) { + target = path + if strings.Contains(path, "__virtual__") || strings.Contains(path, "$$virtual") { + target = pnp.DerefVirtualPath(path) + } else if !strings.Contains(path, ".zip") { + // Fast path: not virtual and no archive component. The overlay wraps the OS + // FS unconditionally, so this runs on every filesystem probe in every + // project; keep it a single scan. + return "", "", path, false + } + if idx := strings.Index(target, zipMarker); idx >= 0 { + zipPath = target[:idx+len(zipMarker)-1] // include ".zip", drop the "/" + internal = strings.Trim(target[idx+len(zipMarker):], "/") + } else if strings.HasSuffix(target, ".zip") { + zipPath = target + internal = "" + } else { + // A virtual path backed by a plain directory (workspace / unplugged + // package): delegate the dereferenced path to the inner FS. + return "", "", target, false + } + if !o.inner.FileExists(zipPath) { + return "", "", target, false + } + return zipPath, internal, target, true +} + +// index lazily opens and indexes the archive at zipPath. +func (o *overlay) index(zipPath string) *archiveIndex { + o.mu.Lock() + defer o.mu.Unlock() + if a, ok := o.archive[zipPath]; ok { + return a + } + a := o.load(zipPath) + // Only cache a successful load. A nil load means the .zip exists but could not + // be read yet (e.g. a still-writing install); caching nil would poison the + // path for the life of a long-running LSP process even after the archive + // becomes valid. + if a != nil { + o.archive[zipPath] = a + } + return a +} + +func (o *overlay) load(zipPath string) *archiveIndex { + contents, ok := o.inner.ReadFile(zipPath) + if !ok { + return nil + } + r, err := zip.NewReader(strings.NewReader(contents), int64(len(contents))) + if err != nil { + return nil + } + a := &archiveIndex{ + files: map[string]*zip.File{}, + dirs: map[string]bool{"": true}, + } + for _, f := range r.File { + name := strings.Trim(f.Name, "/") + if name == "" { + continue + } + if strings.HasSuffix(f.Name, "/") { + a.dirs[name] = true + } else { + a.files[name] = f + } + // Register every ancestor directory of this entry. + for i := range len(name) { + if name[i] == '/' { + a.dirs[name[:i]] = true + } + } + } + return a +} + +type archiveIndex struct { + files map[string]*zip.File // interior path -> file + dirs map[string]bool // interior dir paths (plus "") +} + +func (o *overlay) UseCaseSensitiveFileNames() bool { + return o.inner.UseCaseSensitiveFileNames() +} + +func (o *overlay) FileExists(path string) bool { + zipPath, internal, target, ok := o.split(path) + if !ok { + return o.inner.FileExists(target) + } + if a := o.index(zipPath); a != nil { + _, isFile := a.files[internal] + return isFile + } + return false +} + +func (o *overlay) DirectoryExists(path string) bool { + zipPath, internal, target, ok := o.split(path) + if !ok { + return o.inner.DirectoryExists(target) + } + if a := o.index(zipPath); a != nil { + return a.dirs[internal] + } + return false +} + +func (o *overlay) ReadFile(path string) (string, bool) { + zipPath, internal, target, ok := o.split(path) + if !ok { + return o.inner.ReadFile(target) + } + a := o.index(zipPath) + if a == nil { + return "", false + } + f, isFile := a.files[internal] + if !isFile { + return "", false + } + rc, err := f.Open() + if err != nil { + return "", false + } + defer rc.Close() + b, err := io.ReadAll(rc) + if err != nil { + return "", false + } + return string(b), true +} + +func (o *overlay) Stat(path string) vfs.FileInfo { + zipPath, internal, target, ok := o.split(path) + if !ok { + return o.inner.Stat(target) + } + a := o.index(zipPath) + if a == nil { + return nil + } + if a.dirs[internal] { + return &fileInfo{name: tspath.GetBaseFileName(internal), mode: fs.ModeDir} + } + if f, isFile := a.files[internal]; isFile { + return &fileInfo{name: tspath.GetBaseFileName(internal), size: int64(f.UncompressedSize64)} + } + return nil +} + +func (o *overlay) GetAccessibleEntries(path string) vfs.Entries { + zipPath, internal, target, ok := o.split(path) + if !ok { + return o.inner.GetAccessibleEntries(target) + } + var entries vfs.Entries + a := o.index(zipPath) + if a == nil { + return entries + } + prefix := internal + if prefix != "" { + prefix += "/" + } + for name := range a.files { + if child, isChild := immediateChild(prefix, name); isChild { + entries.Files = append(entries.Files, child) + } + } + seenDir := map[string]bool{} + for name := range a.dirs { + if name == "" { + continue + } + if child, isChild := immediateChild(prefix, name); isChild && !seenDir[child] { + seenDir[child] = true + entries.Directories = append(entries.Directories, child) + } + } + return entries +} + +func (o *overlay) WalkDir(root string, walkFn vfs.WalkDirFunc) error { + zipPath, internal, target, ok := o.split(root) + if !ok { + return o.inner.WalkDir(target, walkFn) + } + a := o.index(zipPath) + if a == nil { + return nil + } + return o.walk(zipPath, a, internal, walkFn) +} + +func (o *overlay) walk(zipPath string, a *archiveIndex, dir string, walkFn vfs.WalkDirFunc) error { + full := zipPath + "/" + dir + if dir == "" { + full = zipPath + } + if err := walkFn(full, fs.FileInfoToDirEntry(&fileInfo{name: tspath.GetBaseFileName(dir), mode: fs.ModeDir}), nil); err != nil { + if err == fs.SkipDir || err == fs.SkipAll { //nolint:errorlint + return nil + } + return err + } + entries := o.GetAccessibleEntries(full) + for _, f := range entries.Files { + child := joinInternal(dir, f) + size := int64(0) + if zf, ok := a.files[child]; ok { + size = int64(zf.UncompressedSize64) + } + if err := walkFn(zipPath+"/"+child, fs.FileInfoToDirEntry(&fileInfo{name: f, size: size}), nil); err != nil { + if err == fs.SkipAll { //nolint:errorlint + return nil + } + if err == fs.SkipDir { //nolint:errorlint + continue + } + return err + } + } + for _, d := range entries.Directories { + if err := o.walk(zipPath, a, joinInternal(dir, d), walkFn); err != nil { + return err + } + } + return nil +} + +func (o *overlay) Realpath(path string) string { + // Zip-internal and PnP virtual paths are already canonical for the compiler's + // purposes (cache filenames are content-addressed; there are no symlinks inside + // an archive) and, crucially, must be returned unchanged: the resolver's PnP + // locator table is keyed by the virtual path, so canonicalizing to the real + // backing location here would desync findLocator for imports made from inside a + // virtualized package. + if strings.Contains(path, zipMarker) || + strings.HasSuffix(path, ".zip") || + strings.Contains(path, "__virtual__") || + strings.Contains(path, "$$virtual") { + return path + } + return o.inner.Realpath(path) +} + +// Mutating operations never target zip-internal or virtual paths in this +// compiler; delegate the original path unchanged. +func (o *overlay) WriteFile(path string, data string) error { return o.inner.WriteFile(path, data) } + +func (o *overlay) AppendFile(path string, data string) error { + return o.inner.AppendFile(path, data) +} +func (o *overlay) Remove(path string) error { return o.inner.Remove(path) } +func (o *overlay) Chtimes(path string, aTime time.Time, mTime time.Time) error { + return o.inner.Chtimes(path, aTime, mTime) +} + +// immediateChild reports whether name is a direct child of prefix ("" = root), +// returning the child's base name. +func immediateChild(prefix, name string) (string, bool) { + if !strings.HasPrefix(name, prefix) { + return "", false + } + rest := name[len(prefix):] + if rest == "" || strings.Contains(rest, "/") { + return "", false + } + return rest, true +} + +func joinInternal(dir, child string) string { + if dir == "" { + return child + } + return dir + "/" + child +} + +type fileInfo struct { + name string + size int64 + mode fs.FileMode +} + +var ( + _ fs.FileInfo = (*fileInfo)(nil) + _ fs.DirEntry = (*fileInfo)(nil) +) + +func (fi *fileInfo) IsDir() bool { return fi.mode.IsDir() } +func (fi *fileInfo) ModTime() time.Time { return time.Time{} } +func (fi *fileInfo) Mode() fs.FileMode { return fi.mode } +func (fi *fileInfo) Name() string { return fi.name } +func (fi *fileInfo) Size() int64 { return fi.size } +func (fi *fileInfo) Sys() any { return nil } +func (fi *fileInfo) Info() (fs.FileInfo, error) { return fi, nil } +func (fi *fileInfo) Type() fs.FileMode { return fi.mode.Type() } diff --git a/internal/vfs/zipoverlay/zipoverlay_test.go b/internal/vfs/zipoverlay/zipoverlay_test.go new file mode 100644 index 00000000000..43152283434 --- /dev/null +++ b/internal/vfs/zipoverlay/zipoverlay_test.go @@ -0,0 +1,226 @@ +package zipoverlay + +import ( + "archive/zip" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/microsoft/typescript-go/internal/vfs/osvfs" +) + +// writeFixtureZip creates a zip archive that looks like a Yarn cache entry: +// node_modules/pkg/{package.json,index.js,cjs/impl.js}. +func writeFixtureZip(t *testing.T, path string) { + t.Helper() + f, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + defer f.Close() + w := zip.NewWriter(f) + entries := map[string]string{ + "node_modules/pkg/package.json": `{"name":"pkg","version":"1.0.0"}`, + "node_modules/pkg/index.js": "module.exports = 1;\n", + "node_modules/pkg/cjs/impl.js": "module.exports = 2;\n", + } + for name, body := range entries { + fw, err := w.Create(name) + if err != nil { + t.Fatal(err) + } + if _, err := fw.Write([]byte(body)); err != nil { + t.Fatal(err) + } + } + if err := w.Close(); err != nil { + t.Fatal(err) + } +} + +func TestZipOverlay(t *testing.T) { + t.Parallel() + dir := t.TempDir() + zipPath := filepath.ToSlash(filepath.Join(dir, "pkg-npm-1.0.0-abc.zip")) + writeFixtureZip(t, zipPath) + + o := Wrap(osvfs.FS()) + pkgDir := zipPath + "/node_modules/pkg" + + // The .zip file and its interior directories all report as directories, so + // the module resolver's parent-directory checks pass. + for _, d := range []string{zipPath, zipPath + "/node_modules", pkgDir, pkgDir + "/cjs"} { + if !o.DirectoryExists(d) { + t.Errorf("DirectoryExists(%q) = false, want true", d) + } + } + + // Files inside the zip exist and are readable; a file is not a directory. + indexJS := pkgDir + "/index.js" + if !o.FileExists(indexJS) { + t.Errorf("FileExists(%q) = false", indexJS) + } + if o.DirectoryExists(indexJS) { + t.Errorf("a file reported as a directory: %q", indexJS) + } + if c, ok := o.ReadFile(pkgDir + "/package.json"); !ok || c != `{"name":"pkg","version":"1.0.0"}` { + t.Errorf("ReadFile package.json = %q, ok=%v", c, ok) + } + if fi := o.Stat(indexJS); fi == nil || fi.IsDir() || fi.Size() == 0 { + t.Errorf("Stat(index.js) wrong: %+v", fi) + } + + // A missing file inside the zip does not exist. + if o.FileExists(pkgDir + "/missing.js") { + t.Error("missing file reported as existing") + } + + // GetAccessibleEntries lists immediate children only. + entries := o.GetAccessibleEntries(pkgDir) + if !slices.Contains(entries.Files, "index.js") || !slices.Contains(entries.Files, "package.json") { + t.Errorf("entries.Files missing expected: %v", entries.Files) + } + if !slices.Contains(entries.Directories, "cjs") { + t.Errorf("entries.Directories missing cjs: %v", entries.Directories) + } + if slices.Contains(entries.Files, "impl.js") { + t.Error("GetAccessibleEntries returned a non-immediate child") + } + + // WalkDir visits every entry inside the zip. + seen := map[string]bool{} + if err := o.WalkDir(pkgDir, func(path string, d os.DirEntry, err error) error { + seen[path] = true + return nil + }); err != nil { + t.Fatal(err) + } + if !seen[indexJS] || !seen[pkgDir+"/cjs/impl.js"] { + t.Errorf("WalkDir did not visit all entries: %v", seen) + } + + // A non-zip path delegates to the inner FS: the .zip file itself is a real + // file on disk, and a missing sibling reads back as not-ok. + if !osvfs.FS().FileExists(zipPath) { + t.Fatal("fixture zip missing on disk") + } + if _, ok := o.ReadFile(dir + "/does-not-exist"); ok { + t.Error("delegated ReadFile of a missing file returned ok") + } +} + +// TestNonZipVirtualDelegates covers a PnP __virtual__ path whose backing +// location is a plain on-disk directory (a workspace or unplugged package with a +// peer dependency), not a cache .zip. The overlay must dereference the virtual +// segment and delegate the resulting real path to the inner FS. Regression for +// the bug where split() fast-rejected any path without ".zip" before +// dereferencing, so these paths returned "not found" and the resolver reported +// TS2307 for a workspace library that has a peer dependency. +func TestNonZipVirtualDelegates(t *testing.T) { + t.Parallel() + dir := filepath.ToSlash(t.TempDir()) + libDir := filepath.Join(dir, "lib") + if err := os.MkdirAll(libDir, 0o755); err != nil { + t.Fatal(err) + } + realFile := filepath.Join(libDir, "index.d.ts") + if err := os.WriteFile(realFile, []byte("export const ui: number;\n"), 0o644); err != nil { + t.Fatal(err) + } + + o := Wrap(osvfs.FS()) + // /x/__virtual__//1/lib/index.d.ts dereferences to /lib/index.d.ts + // (n=1 pops the "x" segment before the __virtual__ triple). + virtual := dir + "/x/__virtual__/w-ui-virtual-aaa/1/lib/index.d.ts" + if !o.FileExists(virtual) { + t.Fatalf("FileExists(%q) = false; virtual path did not dereference to the real file", virtual) + } + if c, ok := o.ReadFile(virtual); !ok || c != "export const ui: number;\n" { + t.Fatalf("ReadFile(virtual) = %q ok=%v", c, ok) + } + // The virtual directory dereferences too. + virtualDir := dir + "/x/__virtual__/w-ui-virtual-aaa/1/lib" + if !o.DirectoryExists(virtualDir) { + t.Errorf("DirectoryExists(%q) = false", virtualDir) + } + // Realpath keeps the virtual path in its own space (no desync with the PnP + // locator table). + if got := o.Realpath(virtual); got != virtual { + t.Errorf("Realpath(virtual) = %q, want identity", got) + } +} + +// TestZipBackedVirtualReadsFromArchive covers a PnP __virtual__ path whose +// backing location is inside a cache .zip (an npm package with a peer +// dependency). The overlay dereferences the virtual segment to the .zip path and +// serves the file from the archive, while Realpath keeps the virtual path. +func TestZipBackedVirtualReadsFromArchive(t *testing.T) { + t.Parallel() + dir := filepath.ToSlash(t.TempDir()) + cacheDir := filepath.Join(dir, ".yarn", "cache") + if err := os.MkdirAll(cacheDir, 0o755); err != nil { + t.Fatal(err) + } + zipPath := filepath.ToSlash(filepath.Join(cacheDir, "pkg-npm-1.0.0-abc.zip")) + writeFixtureZip(t, zipPath) + + o := Wrap(osvfs.FS()) + // The Yarn shape for a peer-virtualized npm package: the cache .zip lives at + // .yarn/cache/, and the virtual location is + // .yarn/__virtual__//0/cache//node_modules/pkg/. Dereferencing + // (count 0) pops nothing and rejoins onto .yarn/, landing on the real .zip. + virtual := dir + "/.yarn/__virtual__/pkg-virtual-abc/0/cache/pkg-npm-1.0.0-abc.zip/node_modules/pkg/index.js" + if !o.FileExists(virtual) { + t.Fatalf("FileExists(%q) = false; zip-backed virtual path not served", virtual) + } + if c, ok := o.ReadFile(virtual); !ok || c != "module.exports = 1;\n" { + t.Fatalf("ReadFile(zip-backed virtual) = %q ok=%v", c, ok) + } + if got := o.Realpath(virtual); got != virtual { + t.Errorf("Realpath(virtual) = %q, want identity", got) + } +} + +// TestZipEdgeCases covers the overlay's boundary conditions: a path referencing a +// .zip that does not exist on disk falls through to the inner FS (not a crash or a +// false hit), the legacy $$virtual spelling is handled, and a path that merely +// contains ".zip" as a substring is not treated as an archive. +func TestZipEdgeCases(t *testing.T) { + t.Parallel() + dir := filepath.ToSlash(t.TempDir()) + o := Wrap(osvfs.FS()) + + // A .zip archive that does not exist on disk: split() finds no real archive and + // delegates, so the interior path simply does not exist (no panic). + ghost := dir + "/missing-npm-1.0.0.zip/node_modules/pkg/index.js" + if o.FileExists(ghost) { + t.Error("interior path of a non-existent .zip reported as existing") + } + if _, ok := o.ReadFile(ghost); ok { + t.Error("ReadFile of a non-existent .zip interior returned ok") + } + + // A real file whose name merely contains ".zip" (not ".zip/…" and not a + // ".zip" suffix) is delegated, read as an ordinary file. + plain := filepath.Join(dir, "notes.zip.txt") + if err := os.WriteFile(plain, []byte("hello\n"), 0o644); err != nil { + t.Fatal(err) + } + if c, ok := o.ReadFile(filepath.ToSlash(plain)); !ok || c != "hello\n" { + t.Errorf("delegated read of a .zip-substring file = %q ok=%v", c, ok) + } + + // The legacy $$virtual spelling dereferences like __virtual__. + libDir := filepath.Join(dir, "lib") + if err := os.MkdirAll(libDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(libDir, "i.d.ts"), []byte("export const z=1;\n"), 0o644); err != nil { + t.Fatal(err) + } + legacy := dir + "/x/$$virtual/h/1/lib/i.d.ts" + if !o.FileExists(legacy) { + t.Errorf("FileExists(%q) = false; $$virtual not dereferenced", legacy) + } +}