-
Notifications
You must be signed in to change notification settings - Fork 125
Expand file tree
/
Copy pathesm-bundle.unit.js
More file actions
241 lines (197 loc) · 6.92 KB
/
esm-bundle.unit.js
File metadata and controls
241 lines (197 loc) · 6.92 KB
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
'use strict';
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const os = require('os');
describe('ESM Bundle Tests', () => {
let tempDir;
let bundlePath;
let testFilePath;
beforeEach(() => {
// Create a temporary directory for test files
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lambda-api-esm-test-'));
bundlePath = path.join(tempDir, 'bundle.mjs');
testFilePath = path.join(tempDir, 'test-entry.js');
});
afterEach(() => {
// Clean up temporary files
try {
if (fs.existsSync(tempDir)) {
fs.rmSync(tempDir, { recursive: true, force: true });
}
} catch (e) {
// Ignore cleanup errors
}
});
it('should bundle with esbuild for ESM without requiring banner', () => {
// Create a test entry file that imports from the .mjs entry point
const testCode = `
import api from '${path.resolve(__dirname, '../index.mjs')}';
const app = api();
app.get('/test', (req, res) => {
res.json({ message: 'Hello from ESM bundle' });
});
export const handler = async (event, context) => {
return await app.run(event, context);
};
`;
fs.writeFileSync(testFilePath, testCode);
// Bundle with esbuild (mark AWS SDK as external since they're peer dependencies)
try {
execSync(
`npx esbuild ${testFilePath} --bundle --platform=node --format=esm --outfile=${bundlePath} --external:@aws-sdk/client-s3 --external:@aws-sdk/s3-request-presigner`,
{ cwd: path.resolve(__dirname, '..'), stdio: 'pipe' }
);
} catch (e) {
throw new Error(`Bundling failed: ${e.message}`);
}
// Verify the bundle was created
expect(fs.existsSync(bundlePath)).toBe(true);
// Test that the bundle executes without errors
const testEvent = JSON.stringify({
httpMethod: 'GET',
path: '/test',
headers: {},
body: null,
isBase64Encoded: false,
});
const testScript = `
import { handler } from '${bundlePath}';
const event = ${testEvent};
const result = await handler(event, {});
console.log(JSON.stringify(result));
`;
const scriptPath = path.join(tempDir, 'test-run.mjs');
fs.writeFileSync(scriptPath, testScript);
let output;
try {
output = execSync(`node ${scriptPath}`, {
encoding: 'utf-8',
cwd: tempDir,
});
} catch (e) {
throw new Error(`Bundle execution failed: ${e.message}\n${e.stderr}`);
}
const result = JSON.parse(output.trim());
// Verify the response
expect(result).toHaveProperty('statusCode', 200);
expect(result).toHaveProperty('headers');
expect(result.headers).toHaveProperty('content-type', 'application/json');
expect(result).toHaveProperty('body');
const body = JSON.parse(result.body);
expect(body).toEqual({ message: 'Hello from ESM bundle' });
});
it('should work with CommonJS require (backward compatibility)', async () => {
const api = require('../index.js');
expect(typeof api).toBe('function');
const app = api();
expect(app).toBeDefined();
expect(typeof app.get).toBe('function');
expect(typeof app.post).toBe('function');
expect(typeof app.run).toBe('function');
// Test full end-to-end functionality with CommonJS
app.get('/test-commonjs', (req, res) => {
res.json({ message: 'CommonJS works', method: req.method });
});
const event = {
httpMethod: 'GET',
path: '/test-commonjs',
headers: {},
body: null,
isBase64Encoded: false,
};
const result = await app.run(event, {});
expect(result).toHaveProperty('statusCode', 200);
expect(result).toHaveProperty('headers');
expect(result.headers).toHaveProperty('content-type', 'application/json');
expect(result).toHaveProperty('body');
const body = JSON.parse(result.body);
expect(body).toEqual({ message: 'CommonJS works', method: 'GET' });
});
it('should work with ESM import', async () => {
// Test that the .mjs file can be imported in Node.js
const testScript = `
import api from '${path.resolve(__dirname, '../index.mjs')}';
console.log(JSON.stringify({
isFunction: typeof api === 'function',
hasDefault: api.default !== undefined
}));
`;
const scriptPath = path.join(tempDir, 'test-import.mjs');
fs.writeFileSync(scriptPath, testScript);
let output;
try {
output = execSync(`node ${scriptPath}`, {
encoding: 'utf-8',
cwd: tempDir,
});
} catch (e) {
throw new Error(`ESM import failed: ${e.message}\n${e.stderr}`);
}
const result = JSON.parse(output.trim());
expect(result.isFunction).toBe(true);
});
it('should bundle with esbuild for CommonJS without breaking (backward compatibility)', () => {
// Create a test entry file that requires from the CommonJS entry point
const testCode = `
const api = require('${path.resolve(__dirname, '../index.js')}');
const app = api();
app.get('/test', (req, res) => {
res.json({ message: 'Hello from CommonJS bundle' });
});
module.exports.handler = async (event, context) => {
return await app.run(event, context);
};
`;
fs.writeFileSync(testFilePath, testCode);
const cjsBundlePath = path.join(tempDir, 'bundle-cjs.js');
// Bundle with esbuild using CommonJS format (mark AWS SDK as external since they're peer dependencies)
try {
execSync(
`npx esbuild ${testFilePath} --bundle --platform=node --format=cjs --outfile=${cjsBundlePath} --external:@aws-sdk/client-s3 --external:@aws-sdk/s3-request-presigner`,
{ cwd: path.resolve(__dirname, '..'), stdio: 'pipe' }
);
} catch (e) {
throw new Error(`CommonJS bundling failed: ${e.message}`);
}
// Verify the bundle was created
expect(fs.existsSync(cjsBundlePath)).toBe(true);
// Test that the bundle executes without errors
const testEvent = JSON.stringify({
httpMethod: 'GET',
path: '/test',
headers: {},
body: null,
isBase64Encoded: false,
});
const testScript = `
const { handler } = require('${cjsBundlePath}');
const event = ${testEvent};
handler(event, {}).then(result => {
console.log(JSON.stringify(result));
}).catch(err => {
console.error(err.message);
process.exit(1);
});
`;
const scriptPath = path.join(tempDir, 'test-run-cjs.js');
fs.writeFileSync(scriptPath, testScript);
let output;
try {
output = execSync(`node ${scriptPath}`, {
encoding: 'utf-8',
cwd: tempDir,
});
} catch (e) {
throw new Error(`CommonJS bundle execution failed: ${e.message}\n${e.stderr}`);
}
const result = JSON.parse(output.trim());
// Verify the response
expect(result).toHaveProperty('statusCode', 200);
expect(result).toHaveProperty('headers');
expect(result.headers).toHaveProperty('content-type', 'application/json');
expect(result).toHaveProperty('body');
const body = JSON.parse(result.body);
expect(body).toEqual({ message: 'Hello from CommonJS bundle' });
});
});