-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathfetchDependencyTypings.ts
456 lines (387 loc) · 11.8 KB
/
fetchDependencyTypings.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
/* eslint-disable no-param-reassign */
import * as ts from "./lib/typescriptServices";
const splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
function splitPath(filename: string) {
return splitPathRe.exec(filename).slice(1);
}
// resolves . and .. elements in a path array with directory names there
// must be no slashes or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
const res = [];
for (let i = 0; i < parts.length; i += 1) {
const p = parts[i];
// ignore empty parts
if (!p || p === ".") continue; // eslint-disable-line no-continue
if (p === "..") {
if (res.length && res[res.length - 1] !== "..") {
res.pop();
} else if (allowAboveRoot) {
res.push("..");
}
} else {
res.push(p);
}
}
return res;
}
export function isAbsolute(path: string) {
return path.charAt(0) === "/";
}
export function normalize(path: string) {
const isAbs = isAbsolute(path);
const trailingSlash = path && path[path.length - 1] === "/";
let newPath = path;
// Normalize the path
newPath = normalizeArray(newPath.split("/"), !isAbs).join("/");
if (!newPath && !isAbs) {
newPath = ".";
}
if (newPath && trailingSlash) {
newPath += "/";
}
return (isAbs ? "/" : "") + newPath;
}
export function join(...paths: Array<any>) {
let path = "";
for (let i = 0; i < paths.length; i += 1) {
const segment = paths[i];
if (typeof segment !== "string") {
throw new TypeError("Arguments to path.join must be strings");
}
if (segment) {
if (!path) {
path += segment;
} else {
path += `/${segment}`;
}
}
}
return normalize(path);
}
export function dirname(path: string) {
const result = splitPath(path);
const root = result[0];
let dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return ".";
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
}
export function basename(p: string, ext: string = "") {
// Special case: Normalize will modify this to '.'
if (p === "") {
return p;
}
// Normalize the string first to remove any weirdness.
const path = normalize(p);
// Get the last part of the string.
const sections = path.split("/");
const lastPart = sections[sections.length - 1];
// Special case: If it's empty, then we have a string like so: foo/
// Meaning, 'foo' is guaranteed to be a directory.
if (lastPart === "" && sections.length > 1) {
return sections[sections.length - 2];
}
// Remove the extension, if need be.
if (ext.length > 0) {
const lastPartExt = lastPart.substr(lastPart.length - ext.length);
if (lastPartExt === ext) {
return lastPart.substr(0, lastPart.length - ext.length);
}
}
return lastPart;
}
export function absolute(path: string) {
if (path.indexOf("/") === 0) {
return path;
}
if (path.indexOf("./") === 0) {
return path.replace("./", "/");
}
return "/" + path;
}
const UNPKG = true;
const ROOT_URL = UNPKG ? `https://unpkg.com/` : `https://cdn.jsdelivr.net/npm/`;
const loadedTypings = [];
/**
* Send the typings library to the editor, the editor can then add them to the
* registry
* @param {string} virtualPath Path of typings
* @param {string} typings Typings
*/
const addLib = (virtualPath, typings, fetchedPaths) => {
fetchedPaths[virtualPath] = typings;
};
const fetchCache = new Map();
const doFetch = url => {
const cached = fetchCache.get(url);
if (cached) {
return cached;
}
const promise = fetch(url)
.then(response => {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response);
}
const error = new Error(response.statusText || `${response.status}`);
// @ts-ignore
error.response = response;
return Promise.reject(error);
})
.then(response => response.text());
fetchCache.set(url, promise);
return promise;
};
const fetchFromDefinitelyTyped = (dependency, version, fetchedPaths) => {
const depUrl = `${ROOT_URL}@types/${dependency
.replace("@", "")
.replace(/\//g, "__")}`;
return doFetch(`${depUrl}/package.json`).then(async typings => {
const rootVirtualPath = `node_modules/@types/${dependency}`;
const referencedPath = `${rootVirtualPath}/package.json`;
addLib(referencedPath, typings, fetchedPaths);
// const typeVersion = await doFetch(`${depUrl}/package.json`).then(res => {
// const packagePath = `${rootVirtualPath}/package.json`;
// addLib(packagePath, res, fetchedPaths);
// return JSON.parse(res).version;
// })
// get all files in the specified directory
return getFileMetaData(
`@types/${dependency}`,
JSON.parse(typings).version,
"/"
).then(fileData =>
getFileTypes(
depUrl,
`@types/${dependency}`,
"/index.d.ts",
fetchedPaths,
fileData
)
);
});
};
const getRequireStatements = (title: string, code: string) => {
const requires = [];
const sourceFile = ts.createSourceFile(
title,
code,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TS
);
// Check the reference comments
sourceFile.referencedFiles.forEach(ref => {
requires.push(ref.fileName);
});
ts.forEachChild(sourceFile, node => {
switch (node.kind) {
case ts.SyntaxKind.ImportDeclaration: {
// @ts-ignore
if (node.moduleSpecifier) {
// @ts-ignore
requires.push(node.moduleSpecifier.text);
}
break;
}
case ts.SyntaxKind.ExportDeclaration: {
// For syntax 'export ... from '...'''
// @ts-ignore
if (node.moduleSpecifier) {
// @ts-ignore
requires.push(node.moduleSpecifier.text);
}
break;
}
default: {
/* */
}
}
});
// Early exit with too many imports, takes too much CPU
return requires.length > 400 ? [] : requires;
};
const tempTransformFiles = files => {
const finalObj = {};
files.forEach(d => {
finalObj[d.name] = d;
});
return finalObj;
};
const transformFiles = dir =>
dir.files
? dir.files.reduce((prev, next) => {
if (next.type === "file") {
return { ...prev, [next.path]: next };
}
return { ...prev, ...transformFiles(next) };
}, {})
: {};
const getFileMetaData = (dependency, version, depPath) => {
if (UNPKG) {
const usedDepPath = /\/$/.test(depPath) ? depPath : (depPath + '/');
return doFetch(`https://unpkg.com/${dependency}@${version}${usedDepPath}?meta`)
.then(response => JSON.parse(response))
.then(transformFiles);
}
return doFetch(
`https://data.jsdelivr.com/v1/package/npm/${dependency}@${version}/flat`
)
.then(response => JSON.parse(response))
.then(response =>
response.files.filter(f => f.name.startsWith("/" + depPath))
)
.then(tempTransformFiles);
};
const resolveAppropiateFile = (fileMetaData, absolutePath) => {
if (fileMetaData[`${absolutePath}.d.ts`]) return `${absolutePath}.d.ts`;
if (fileMetaData[`${absolutePath}.ts`]) return `${absolutePath}.ts`;
if (fileMetaData[absolutePath]) return absolutePath;
if (fileMetaData[`${absolutePath}/index.d.ts`])
return `${absolutePath}/index.d.ts`;
return absolutePath;
};
const getDependencyName = (depPath:string) => {
const parts= depPath.split('/');
if (depPath.indexOf('@') === 0) {
return parts[0] + '/' + parts[1];
}
return parts[0];
}
const getFileTypes = (
depUrl,
dependency,
depPath,
fetchedPaths,
fileMetaData
) => {
const virtualPath = join("node_modules", dependency, depPath);
if (fetchedPaths[virtualPath]) return null;
return doFetch(`${depUrl}${depPath}`).then(typings => {
if (fetchedPaths[virtualPath]) return null;
addLib(virtualPath, typings, fetchedPaths);
const requireStatements = getRequireStatements(depPath, typings);
const isNoDependency = dep => dep.startsWith(".") || dep.endsWith(".d.ts");
const dependencies = requireStatements.filter(x => !isNoDependency(x));
// console.log(fileMetaData, new Error().stack)
// Now find all require statements, so we can download those types too
return Promise.all(
dependencies
.map(depPath =>
fetchAndAddDependencies(getDependencyName(depPath), "latest", fetchedPaths).catch(
() => {
/* ignore */
}
)
)
.concat(
requireStatements
.filter(
// Don't add global deps, only if those are typing files as they are often relative
isNoDependency
)
.map(relativePath => join(dirname(depPath), relativePath))
.map(relativePath =>
resolveAppropiateFile(fileMetaData, relativePath)
)
.map(nextDepPath =>
getFileTypes(
depUrl,
dependency,
nextDepPath,
fetchedPaths,
fileMetaData
)
)
)
);
});
};
function fetchFromMeta(dependency, version, fetchedPaths) {
return getFileMetaData(dependency, version, "/").then(meta => {
let dtsFiles = Object.keys(meta).filter(f => /\.d\.ts$/.test(f));
if (dtsFiles.length === 0) {
// if no .d.ts files found, fallback to .ts files
dtsFiles = Object.keys(meta).filter(f => /\.ts$/.test(f));
}
if (dtsFiles.length === 0) {
throw new Error("No inline typings found.");
}
return Promise.all(
dtsFiles.map(file =>
getFileTypes(`${ROOT_URL}${dependency}@${version}`, dependency, file, fetchedPaths, meta)
)
);
});
}
function fetchFromTypings(dependency, version, fetchedPaths) {
const depUrl = `${ROOT_URL}${dependency}@${version}`;
return doFetch(`${depUrl}/package.json`)
.then(response => JSON.parse(response))
.then(packageJSON => {
// Add package.json, since this defines where all types lie
addLib(
`node_modules/${dependency}/package.json`,
JSON.stringify(packageJSON),
fetchedPaths
);
const types = packageJSON.typings || packageJSON.types;
if (types) {
// get all files in the specified directory
return getFileMetaData(
dependency,
version,
join("/", dirname(types))
).then(fileData =>
getFileTypes(
depUrl,
dependency,
resolveAppropiateFile(fileData, join("/", types)),
fetchedPaths,
fileData
)
);
}
throw new Error("Could not find root typings file");
});
}
export async function fetchAndAddDependencies(
dep,
version,
fetchedPaths = {}
) {
try {
if (loadedTypings.indexOf(dep) === -1) {
loadedTypings.push(dep);
let depVersion = version;
try {
await doFetch(`https://cdn.jsdelivr.net/npm/${dep}@${version}/package.json`)
.then(x => JSON.parse(x))
.then(x => {
depVersion = x.version;
});
} catch (e) {}
// eslint-disable-next-line no-await-in-loop
await fetchFromTypings(dep, depVersion, fetchedPaths).catch(() =>
// not available in package.json, try checking meta for inline .d.ts files
fetchFromMeta(dep, depVersion, fetchedPaths).catch(() =>
// Not available in package.json or inline from meta, try checking in @types/
fetchFromDefinitelyTyped(dep, depVersion, fetchedPaths)
)
);
}
} catch (e) {
// // Don't show these cryptic messages to users, because this is not vital
// if (process.env.NODE_ENV === 'development') {
// console.error(`Couldn't find typings for ${dep}`, e);
// }
}
return fetchedPaths;
}