UNPKG

2.38 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.scanForPackage = exports.tryResolvePackage = void 0;
4const fs = require("fs");
5const path = require("path");
6/**
7 * Tries to resolve a package using Node.js resolution.
8 * Directory names differing from the package name and alternate lookup paths can be passed.
9 */
10function tryResolvePackage(possiblePaths, lookupPaths) {
11 for (const pkg of possiblePaths) {
12 try {
13 // package.json is guaranteed to be in the module root folder
14 // so once that is resolved, take the dirname and we're done
15 const possiblePath = require.resolve(`${pkg}/package.json`, (lookupPaths === null || lookupPaths === void 0 ? void 0 : lookupPaths.length) ? { paths: lookupPaths } : undefined);
16 if (fs.existsSync(possiblePath)) {
17 return path.dirname(possiblePath);
18 }
19 }
20 catch (_a) {
21 /* not found */
22 }
23 }
24}
25exports.tryResolvePackage = tryResolvePackage;
26/**
27 * Scans for a package by walking up the directory tree and inspecting package.json
28 * Directory names differing from the package name and an alternate start dir can be passed.
29 */
30function scanForPackage(possiblePaths, startDir = __dirname) {
31 // We start in the node_modules subfolder of adapter-core, which is the deepest we should be able to expect the controller
32 let curDir = path.join(startDir, "../node_modules");
33 while (true) {
34 for (const pkg of possiblePaths) {
35 const possiblePath = path.join(curDir, pkg, "package.json");
36 try {
37 // If package.json exists in the directory and its name field matches, we've found js-controller
38 if (fs.existsSync(possiblePath) &&
39 JSON.parse(fs.readFileSync(possiblePath, "utf8")).name ===
40 pkg.toLowerCase()) {
41 return path.dirname(possiblePath);
42 }
43 }
44 catch (_a) {
45 // don't care
46 }
47 }
48 // Nothing found here, go up one level
49 const parentDir = path.dirname(curDir);
50 if (parentDir === curDir) {
51 // we've reached the root without finding js-controller
52 break;
53 }
54 curDir = parentDir;
55 }
56}
57exports.scanForPackage = scanForPackage;