Skip to content

Commit fc8e561

Browse files
fix: finding path of aws-cdk-lib module
1 parent 884ca21 commit fc8e561

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

src/frameworks/cdkFramework.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { Logger } from "../logger.js";
1212
import { Worker } from "node:worker_threads";
1313
import { getModuleDirname, getProjectDirname } from "../getDirname.js";
1414
import { Configuration } from "../configuration.js";
15+
import { findNpmPath } from "../utils/findNpmPath.js";
1516

1617
/**
1718
* Support for AWS CDK framework
@@ -308,6 +309,12 @@ export class CdkFramework implements IFramework {
308309
process.env.CDK_CONTEXT_JSON = JSON.stringify(CDK_CONTEXT_JSON);
309310
Logger.verbose(`[CDK] Context:`, JSON.stringify(CDK_CONTEXT_JSON, null, 2));
310311

312+
const awsCdkLibPath = await findNpmPath(
313+
path.join(getProjectDirname(), config.subfolder ?? "/"),
314+
"aws-cdk-lib"
315+
);
316+
Logger.verbose(`[CDK] aws-cdk-lib path: ${awsCdkLibPath}`);
317+
311318
const lambdas: any[] = await new Promise((resolve, reject) => {
312319
const worker = new Worker(
313320
path.resolve(
@@ -316,6 +323,7 @@ export class CdkFramework implements IFramework {
316323
{
317324
workerData: {
318325
verbose: Configuration.config.verbose,
326+
awsCdkLibPath,
319327
},
320328
}
321329
);

src/utils/findNpmPath.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import fs from "fs/promises";
2+
import path from "path";
3+
4+
/**
5+
* Function to find the path of a module in the directory and parent directories
6+
* @param {*} dir
7+
* @param {*} moduleName
8+
*/
9+
export async function findNpmPath(dir: string, moduleName: string) {
10+
if (dir === "/") return undefined;
11+
12+
try {
13+
await fs.access(path.join(dir, "package.json"));
14+
15+
const modulePath = await checkModuleInPackageJson(dir, moduleName);
16+
if (modulePath) {
17+
return modulePath;
18+
}
19+
} catch {
20+
// ignore, no package.json in this directory
21+
}
22+
23+
return await findNpmPath(path.resolve(path.join(dir, "..")), moduleName);
24+
}
25+
26+
/**
27+
* Function to check if a module exists in package.json and return the path
28+
* @param {*} dir
29+
* @param {*} moduleName
30+
* @returns
31+
*/
32+
async function checkModuleInPackageJson(dir: string, moduleName: string) {
33+
const packageJsonPath = path.join(dir, "package.json");
34+
const packageJson = JSON.parse(await fs.readFile(packageJsonPath, "utf8"));
35+
const dependencies = packageJson.dependencies || {};
36+
const devDependencies = packageJson.devDependencies || {};
37+
if (dependencies[moduleName] || devDependencies[moduleName]) {
38+
const modulePath = path.join(dir, "node_modules", moduleName);
39+
return modulePath;
40+
}
41+
return undefined;
42+
}

0 commit comments

Comments
 (0)