-
Notifications
You must be signed in to change notification settings - Fork 619
/
Copy pathWorkspaceLayoutCache.ts
218 lines (190 loc) · 7.37 KB
/
WorkspaceLayoutCache.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import { sep as directorySeparator } from 'node:path';
import { LookupByPath, type IPrefixMatch } from '@rushstack/lookup-by-path';
/**
* Information about a local or installed npm package.
* @beta
*/
export interface ISerializedResolveContext {
/**
* The path to the root folder of this context.
* This path is normalized to use `/` as the separator and should not end with a trailing `/`.
*/
root: string;
/**
* The name of this package. Used to inject a self-reference into the dependency map.
*/
name: string;
/**
* Map of declared dependencies (if any) to the ordinal of the corresponding context.
*/
deps?: Record<string, number>;
/**
* Set of relative paths to nested `package.json` files within this context.
* These paths are normalized to use `/` as the separator and should not begin with a leading `./`.
*/
dirInfoFiles?: string[];
}
/**
* The serialized form of the cache file. This file is expected to be generated by a separate tool from
* information known to the package manager. Namely, the dependency relationships between packages, and
* all the `package.json` files in the workspace (installed or local).
* @beta
*/
export interface IResolverCacheFile {
/**
* The base path. All paths in context entries are prefixed by this path.
*/
basePath: string;
/**
* The ordered list of all contexts in the cache
*/
contexts: ISerializedResolveContext[];
}
/**
* A context for resolving dependencies in a workspace.
* @beta
*/
export interface IResolveContext {
/**
* The absolute path to the root folder of this context
*/
descriptionFileRoot: string;
/**
* Find the context that corresponds to a module specifier, when requested in the current context.
* @param request - The module specifier to resolve
*/
findDependency(request: string): IPrefixMatch<IResolveContext> | undefined;
}
/**
* Options for creating a `WorkspaceLayoutCache`.
* @beta
*/
export interface IWorkspaceLayoutCacheOptions {
/**
* The parsed cache data. File reading is left as an exercise for the caller.
*/
cacheData: IResolverCacheFile;
/**
* The directory separator used in the `path` field of the resolver inputs.
* Will usually be `path.sep`.
*/
resolverPathSeparator?: '/' | '\\';
}
/**
* A function that normalizes a path to a platform-specific format (if needed).
* Will be undefined if the platform uses `/` as the path separator.
*
* @beta
*/
export type IPathNormalizationFunction = ((input: string) => string) | undefined;
function backslashToSlash(path: string): string {
return path.replace(/\\/g, '/');
}
function slashToBackslash(path: string): string {
return path.replace(/\//g, '\\');
}
/**
* A cache of workspace layout information.
* @beta
*/
export class WorkspaceLayoutCache {
/**
* A lookup of context roots to their corresponding context objects
*/
public readonly contextLookup: LookupByPath<IResolveContext>;
/**
* A weak map of package JSON contents to their corresponding context objects
*/
public readonly contextForPackage: WeakMap<object, IPrefixMatch<IResolveContext>>;
public readonly resolverPathSeparator: string;
public readonly normalizeToSlash: IPathNormalizationFunction;
public readonly normalizeToPlatform: IPathNormalizationFunction;
public constructor(options: IWorkspaceLayoutCacheOptions) {
const { cacheData, resolverPathSeparator = directorySeparator } = options;
if (resolverPathSeparator !== '/' && resolverPathSeparator !== '\\') {
throw new Error(`Unsupported directory separator: ${resolverPathSeparator}`);
}
const { basePath } = cacheData;
const resolveContexts: ResolveContext[] = [];
const contextLookup: LookupByPath<IResolveContext> = new LookupByPath(undefined, resolverPathSeparator);
this.contextLookup = contextLookup;
this.contextForPackage = new WeakMap<object, IPrefixMatch<IResolveContext>>();
const normalizeToSlash: IPathNormalizationFunction =
resolverPathSeparator === '\\' ? backslashToSlash : undefined;
const normalizeToPlatform: IPathNormalizationFunction =
resolverPathSeparator === '\\' ? slashToBackslash : undefined;
this.resolverPathSeparator = resolverPathSeparator;
this.normalizeToSlash = normalizeToSlash;
this.normalizeToPlatform = normalizeToPlatform;
// Internal class due to coupling to `resolveContexts`
class ResolveContext implements IResolveContext {
private readonly _serialized: ISerializedResolveContext;
private _descriptionFileRoot: string | undefined;
private _dependencies: LookupByPath<IResolveContext> | undefined;
public constructor(serialized: ISerializedResolveContext) {
this._serialized = serialized;
this._descriptionFileRoot = undefined;
this._dependencies = undefined;
}
public get descriptionFileRoot(): string {
if (!this._descriptionFileRoot) {
const merged: string = `${basePath}${this._serialized.root}`;
this._descriptionFileRoot = normalizeToPlatform?.(merged) ?? merged;
}
return this._descriptionFileRoot;
}
public findDependency(request: string): IPrefixMatch<IResolveContext> | undefined {
if (!this._dependencies) {
// Lazy initialize this object since most packages won't be requested.
const dependencies: LookupByPath<IResolveContext> = new LookupByPath(undefined, '/');
const { name, deps } = this._serialized;
// Handle the self-reference scenario
dependencies.setItem(name, this);
if (deps) {
for (const [key, ordinal] of Object.entries(deps)) {
// This calls into the array of instances that is owned by WorkpaceLayoutCache
dependencies.setItem(key, resolveContexts[ordinal]);
}
}
this._dependencies = dependencies;
}
return this._dependencies.findLongestPrefixMatch(request);
}
}
for (const serialized of cacheData.contexts) {
const resolveContext: ResolveContext = new ResolveContext(serialized);
resolveContexts.push(resolveContext);
contextLookup.setItemFromSegments(
concat<string>(
// All paths in the cache file are platform-agnostic
LookupByPath.iteratePathSegments(basePath, '/'),
LookupByPath.iteratePathSegments(serialized.root, '/')
),
resolveContext
);
// Handle nested package.json files. These may modify some properties, but the dependency resolution
// will match the original package root. Typically these are used to set the `type` field to `module`.
if (serialized.dirInfoFiles) {
for (const file of serialized.dirInfoFiles) {
contextLookup.setItemFromSegments(
concat<string>(
// All paths in the cache file are platform-agnostic
concat<string>(
LookupByPath.iteratePathSegments(basePath, '/'),
LookupByPath.iteratePathSegments(serialized.root, '/')
),
LookupByPath.iteratePathSegments(file, '/')
),
resolveContext
);
}
}
}
}
}
function* concat<T>(a: Iterable<T>, b: Iterable<T>): IterableIterator<T> {
yield* a;
yield* b;
}