Skip to content

Commit 544d095

Browse files
Merge pull request #46 from ServerlessLife/44-fix-CDK-ES-module
fix: [#44] CDK ES module
2 parents e03d43c + aa3f3e3 commit 544d095

File tree

42 files changed

+3165
-60
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+3165
-60
lines changed

.github/workflows/common-test.yml

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,53 @@ jobs:
7272
- name: Test - observable mode
7373
run: OBSERVABLE_MODE=true npx vitest --retry 1 test/cdk-basic.test.ts
7474

75+
test-cdk-esm:
76+
runs-on: ubuntu-latest
77+
concurrency:
78+
group: test-cdk-esm
79+
steps:
80+
- uses: actions/checkout@v4
81+
- name: Use Node.js
82+
uses: actions/setup-node@v4
83+
with:
84+
node-version: ${{ env.node_version }}
85+
registry-url: 'https://registry.npmjs.org'
86+
- name: Install dependencies
87+
run: npm ci
88+
- name: Download build artifact
89+
uses: actions/download-artifact@v4
90+
if: ${{ inputs.mode == 'build' }}
91+
with:
92+
name: dist
93+
path: dist
94+
- name: Install lambda-live-debugger globally
95+
if: ${{ inputs.mode == 'global' }}
96+
run: |
97+
npm i lambda-live-debugger -g
98+
working-directory: test
99+
- name: Install lambda-live-debugger locally
100+
if: ${{ inputs.mode == 'local' }}
101+
run: |
102+
npm i lambda-live-debugger
103+
working-directory: test
104+
- name: Configure AWS Credentials
105+
uses: aws-actions/configure-aws-credentials@v4
106+
with:
107+
aws-region: eu-west-1
108+
role-to-assume: ${{ secrets.AWS_ROLE }}
109+
role-session-name: GitHubActions
110+
- name: Destroy
111+
run: npm run destroy
112+
working-directory: test/cdk-esm
113+
continue-on-error: true
114+
- name: Deploy
115+
run: npm run deploy
116+
working-directory: test/cdk-esm
117+
- name: Test
118+
run: npx vitest --retry 1 test/cdk-esm.test.ts
119+
- name: Test - observable mode
120+
run: OBSERVABLE_MODE=true npx vitest --retry 1 test/cdk-esm.test.ts
121+
75122
test-sls-basic:
76123
runs-on: ubuntu-latest
77124
concurrency:

.vscode/launch.json

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,26 @@
2424
"type": "node",
2525
"cwd": "${workspaceRoot}/test/cdk-basic"
2626
},
27+
{
28+
"name": "LLDebugger - CDK ESM",
29+
"program": "${workspaceRoot}/node_modules/tsx/dist/cli.mjs",
30+
"args": ["../../src/lldebugger.ts", "-c environment=test"],
31+
"request": "launch",
32+
"skipFiles": ["<node_internals>/**"],
33+
"console": "integratedTerminal",
34+
"type": "node",
35+
"cwd": "${workspaceRoot}/test/cdk-esm"
36+
},
37+
{
38+
"name": "LLDebugger - CDK ESM - observable",
39+
"program": "${workspaceRoot}/node_modules/tsx/dist/cli.mjs",
40+
"args": ["../../src/lldebugger.ts", "-c environment=test", "-o"],
41+
"request": "launch",
42+
"skipFiles": ["<node_internals>/**"],
43+
"console": "integratedTerminal",
44+
"type": "node",
45+
"cwd": "${workspaceRoot}/test/cdk-esm"
46+
},
2747
{
2848
"name": "LLDebugger - SLS basic",
2949
"program": "${workspaceRoot}/node_modules/tsx/dist/cli.mjs",

package-lock.json

Lines changed: 29 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@
4949
"test": "npm run build && RUN_TEST_FROM_CLI=true vitest run && RUN_TEST_FROM_CLI=true OBSERVABLE_MODE=true vitest run",
5050
"test-cdk-basic": "npm run build && RUN_TEST_FROM_CLI=true vitest run test/cdk-basic.test.ts",
5151
"test-cdk-basic-observable": "npm run build && RUN_TEST_FROM_CLI=true OBSERVABLE_MODE=true vitest run test/cdk-basic.test.ts",
52+
"test-cdk-esm": "npm run build && RUN_TEST_FROM_CLI=true vitest run test/cdk-esm.test.ts",
53+
"test-cdk-esm-observable": "npm run build && RUN_TEST_FROM_CLI=true OBSERVABLE_MODE=true vitest run test/cdk-esm.test.ts",
5254
"test-sls-basic": "npm run build && RUN_TEST_FROM_CLI=true vitest run test/sls-basic.test.ts",
5355
"test-sls-basic-observable": "npm run build && RUN_TEST_FROM_CLI=true OBSERVABLE_MODE=true vitest run test/sls-basic.test.ts",
5456
"test-sls-esbuild-cjs": "npm run build && RUN_TEST_FROM_CLI=true vitest run test/sls-esbuild-cjs.test.ts",
@@ -130,6 +132,7 @@
130132
"src/extension/*",
131133
"test",
132134
"test/cdk-basic",
135+
"test/cdk-esm",
133136
"test/cdk-config",
134137
"test/sls-basic",
135138
"test/sls-esbuild",

src/frameworks/cdkFramework.ts

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -280,21 +280,70 @@ export class CdkFramework implements IFramework {
280280
},
281281
};
282282

283+
let isESM = false;
284+
// get packgage.json
285+
const packageJsonPath = await findPackageJson(entryFile);
286+
287+
if (packageJsonPath) {
288+
try {
289+
const packageJson = JSON.parse(
290+
await fs.readFile(packageJsonPath, { encoding: 'utf-8' }),
291+
);
292+
if (packageJson.type === 'module') {
293+
isESM = true;
294+
Logger.verbose(`[CDK] Using ESM format`);
295+
}
296+
} catch (err: any) {
297+
Logger.error(
298+
`Error reading CDK package.json (${packageJsonPath}): ${err.message}`,
299+
err,
300+
);
301+
}
302+
}
303+
283304
const compileOutput = path.join(
284305
getProjectDirname(),
285306
outputFolder,
286-
`compiledCdk.js`,
307+
`compiledCdk.${isESM ? 'mjs' : 'cjs'}`,
287308
);
309+
288310
try {
289311
// Build CDK code
290312
await esbuild.build({
291313
entryPoints: [entryFile],
292314
bundle: true,
293315
platform: 'node',
294-
target: 'node18',
316+
keepNames: true,
295317
outfile: compileOutput,
296318
sourcemap: false,
297319
plugins: [injectCodePlugin],
320+
...(isESM
321+
? {
322+
format: 'esm',
323+
target: 'esnext',
324+
mainFields: ['module', 'main'],
325+
banner: {
326+
js: [
327+
`import { createRequire as topLevelCreateRequire } from 'module';`,
328+
`global.require = global.require ?? topLevelCreateRequire(import.meta.url);`,
329+
`import { fileURLToPath as topLevelFileUrlToPath, URL as topLevelURL } from "url"`,
330+
`global.__dirname = global.__dirname ?? topLevelFileUrlToPath(new topLevelURL(".", import.meta.url))`,
331+
].join('\n'),
332+
},
333+
}
334+
: {
335+
format: 'cjs',
336+
target: 'node18',
337+
banner: {
338+
js: [
339+
`__dirname = '${path.join(
340+
...([getProjectDirname(), config.subfolder, 'x'].filter(
341+
(p) => p,
342+
) as string[]),
343+
)}';`,
344+
].join('\n'),
345+
},
346+
}),
298347
});
299348
} catch (error: any) {
300349
throw new Error(`Error building CDK code: ${error.message}`, {
@@ -428,6 +477,14 @@ export class CdkFramework implements IFramework {
428477
}
429478
});
430479

480+
// worker.stdout.on('data', (data: Buffer) => {
481+
// Logger.log(`[CDK]`, data.toString());
482+
// });
483+
484+
// worker.stderr.on('data', (data: Buffer) => {
485+
// Logger.error(`[CDK]`, data.toString());
486+
// });
487+
431488
worker.postMessage({
432489
compileOutput: compileCodeFile,
433490
});

src/frameworks/cdkFrameworkWorker.mjs

Lines changed: 42 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -4,56 +4,53 @@ const require = topLevelCreateRequire(import.meta.url);
44
import path from 'path';
55

66
import { workerData, parentPort } from 'node:worker_threads';
7-
import fs from 'fs/promises';
7+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
8+
import fs from 'fs/promises'; // do not delete this line
89

910
import { Logger } from '../logger.mjs';
1011

1112
Logger.setVerbose(workerData.verbose);
12-
// eslint-disable-next-line @typescript-eslint/no-unused-vars
13-
const __dirname = path.resolve(
14-
path.join(
15-
...[workerData.projectDirname, workerData.subfolder, 'x'].filter((p) => p),
16-
),
17-
);
1813

1914
Logger.verbose(`[CDK] [Worker] Started`);
2015

2116
parentPort.on('message', async (data) => {
22-
// this is global variable to store the data from the CDK code once it is executed
23-
global.lambdas = [];
24-
25-
Logger.verbose(`[Worker ${workerData.workerId}] Received message`, data);
26-
27-
// execute code to get the data into global.lambdas
28-
const codeFile = await fs.readFile(data.compileOutput, 'utf8');
29-
30-
await fixCdkPaths(workerData.awsCdkLibPath);
31-
32-
eval(codeFile);
33-
34-
if (!global.lambdas || global.lambdas?.length === 0) {
35-
throw new Error('No Lambda functions found in the CDK code');
17+
try {
18+
// this is global variable to store the data from the CDK code once it is executed
19+
global.lambdas = [];
20+
21+
Logger.verbose(`[Worker ${workerData.workerId}] Received message`, data);
22+
23+
// execute code to get the data into global.lambdas
24+
await fixCdkPaths(workerData.awsCdkLibPath);
25+
await import(data.compileOutput);
26+
27+
if (!global.lambdas || global.lambdas?.length === 0) {
28+
throw new Error('No Lambda functions found in the CDK code');
29+
}
30+
31+
const lambdas = global.lambdas.map((lambda) => ({
32+
handler: lambda.handler,
33+
stackName: lambda.stackName,
34+
codePath: lambda.codePath,
35+
code: {
36+
path: lambda.code?.path,
37+
},
38+
cdkPath: lambda.node.defaultChild.node.path,
39+
bundling: {
40+
...lambda.bundling,
41+
commandHooks: undefined, // can not be serialized
42+
},
43+
}));
44+
45+
Logger.verbose(
46+
`[CDK] [Worker] Sending found lambdas`,
47+
JSON.stringify(lambdas, null, 2),
48+
);
49+
parentPort.postMessage(lambdas);
50+
} catch (error) {
51+
Logger.error(`[CDK] [Worker] Error`, error);
52+
throw error;
3653
}
37-
38-
const lambdas = global.lambdas.map((lambda) => ({
39-
handler: lambda.handler,
40-
stackName: lambda.stackName,
41-
codePath: lambda.codePath,
42-
code: {
43-
path: lambda.code?.path,
44-
},
45-
cdkPath: lambda.node.defaultChild.node.path,
46-
bundling: {
47-
...lambda.bundling,
48-
commandHooks: undefined, // can not be serialized
49-
},
50-
}));
51-
52-
Logger.verbose(
53-
`[CDK] [Worker] Sending found lambdas`,
54-
JSON.stringify(lambdas, null, 2),
55-
);
56-
parentPort.postMessage(lambdas);
5754
});
5855

5956
/**
@@ -105,3 +102,7 @@ async function fixCdkPaths(awsCdkLibPath) {
105102
exports: pathProxy,
106103
};
107104
}
105+
106+
process.on('unhandledRejection', (error) => {
107+
Logger.error(`[CDK] [Worker] Unhandled Rejection`, error);
108+
});

src/nodeWorker.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ function startWorker(input: WorkerRequest) {
110110
Logger.log(`[Function ${input.functionId}]`, data.toString());
111111
});
112112
worker.stderr.on('data', (data: Buffer) => {
113-
Logger.log(`[Function ${input.functionId}]`, data.toString());
113+
Logger.error(`[Function ${input.functionId}]`, data.toString());
114114
});
115115
worker.on('exit', () => {
116116
Logger.verbose(

test/cdk-config/services/testJsCommonJs/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"name": "cdk-basic-test-js-commonjs",
2+
"name": "cdk-config-test-js-commonjs",
33
"version": "1.0.0",
44
"type": "commonjs",
55
"dependencies": {

test/cdk-config/services/testJsEsModule/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"name": "cdk-basic-test-js-esmodule",
2+
"name": "cdk-config-test-js-esmodule",
33
"version": "1.0.0",
44
"type": "module",
55
"dependencies": {

test/cdk-config/services/testTsCommonJs/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"name": "cdk-basic-test-ts-commonjs",
2+
"name": "cdk-config-test-ts-commonjs",
33
"version": "1.0.0",
44
"type": "commonjs",
55
"devDependencies": {

0 commit comments

Comments
 (0)