-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathhandleRunAfterProductionCompile.test.ts
More file actions
539 lines (451 loc) · 17.5 KB
/
handleRunAfterProductionCompile.test.ts
File metadata and controls
539 lines (451 loc) · 17.5 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
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
import { loadModule } from '@sentry/core';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
handleRunAfterProductionCompile,
stripSourceMappingURLComments,
} from '../../src/config/handleRunAfterProductionCompile';
import type { SentryBuildOptions } from '../../src/config/types';
vi.mock('@sentry/core', () => ({
loadModule: vi.fn(),
}));
vi.mock('../../src/config/getBuildPluginOptions', () => ({
getBuildPluginOptions: vi.fn(() => ({
org: 'test-org',
project: 'test-project',
sourcemaps: {},
})),
}));
describe('handleRunAfterProductionCompile', () => {
const mockCreateSentryBuildPluginManager = vi.fn();
const mockSentryBuildPluginManager = {
telemetry: {
emitBundlerPluginExecutionSignal: vi.fn().mockResolvedValue(undefined),
},
createRelease: vi.fn().mockResolvedValue(undefined),
injectDebugIds: vi.fn().mockResolvedValue(undefined),
uploadSourcemaps: vi.fn().mockResolvedValue(undefined),
deleteArtifacts: vi.fn().mockResolvedValue(undefined),
};
const mockSentryBuildOptions: SentryBuildOptions = {
org: 'test-org',
project: 'test-project',
authToken: 'test-token',
};
beforeEach(() => {
vi.clearAllMocks();
mockCreateSentryBuildPluginManager.mockReturnValue(mockSentryBuildPluginManager);
(loadModule as any).mockReturnValue({
createSentryBuildPluginManager: mockCreateSentryBuildPluginManager,
});
});
describe('turbopack builds', () => {
it('executes all build steps for turbopack builds', async () => {
await handleRunAfterProductionCompile(
{
releaseName: 'test-release',
distDir: '/path/to/.next',
buildTool: 'turbopack',
},
mockSentryBuildOptions,
);
expect(mockSentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal).toHaveBeenCalledTimes(1);
expect(mockSentryBuildPluginManager.createRelease).toHaveBeenCalledTimes(1);
expect(mockSentryBuildPluginManager.injectDebugIds).toHaveBeenCalledWith(['/path/to/.next']);
expect(mockSentryBuildPluginManager.uploadSourcemaps).toHaveBeenCalledWith(['/path/to/.next'], {
prepareArtifacts: false,
});
expect(mockSentryBuildPluginManager.deleteArtifacts).toHaveBeenCalledTimes(1);
});
it('calls createSentryBuildPluginManager with correct options', async () => {
await handleRunAfterProductionCompile(
{
releaseName: 'test-release',
distDir: '/path/to/.next',
buildTool: 'turbopack',
},
mockSentryBuildOptions,
);
expect(mockCreateSentryBuildPluginManager).toHaveBeenCalledWith(
expect.objectContaining({
org: 'test-org',
project: 'test-project',
sourcemaps: expect.any(Object),
}),
{
buildTool: 'turbopack',
loggerPrefix: '[@sentry/nextjs - After Production Compile]',
},
);
});
it('handles debug mode correctly', async () => {
const consoleSpy = vi.spyOn(console, 'debug').mockImplementation(() => {});
const debugOptions = {
...mockSentryBuildOptions,
debug: true,
};
await handleRunAfterProductionCompile(
{
releaseName: 'test-release',
distDir: '/path/to/.next',
buildTool: 'turbopack',
},
debugOptions,
);
expect(consoleSpy).toHaveBeenCalledWith('[@sentry/nextjs] Running runAfterProductionCompile logic.');
consoleSpy.mockRestore();
});
});
describe('webpack builds', () => {
it('executes all build steps for webpack builds', async () => {
await handleRunAfterProductionCompile(
{
releaseName: 'test-release',
distDir: '/path/to/.next',
buildTool: 'webpack',
},
mockSentryBuildOptions,
);
expect(mockSentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal).toHaveBeenCalledTimes(1);
expect(mockSentryBuildPluginManager.createRelease).toHaveBeenCalledTimes(1);
expect(mockSentryBuildPluginManager.injectDebugIds).toHaveBeenCalledWith(['/path/to/.next']);
expect(mockSentryBuildPluginManager.uploadSourcemaps).toHaveBeenCalledWith(['/path/to/.next'], {
prepareArtifacts: false,
});
expect(mockSentryBuildPluginManager.deleteArtifacts).toHaveBeenCalledTimes(1);
});
it('logs debug message for webpack builds when debug is enabled', async () => {
const consoleSpy = vi.spyOn(console, 'debug').mockImplementation(() => {});
const debugOptions = {
...mockSentryBuildOptions,
debug: true,
};
await handleRunAfterProductionCompile(
{
releaseName: 'test-release',
distDir: '/path/to/.next',
buildTool: 'webpack',
},
debugOptions,
);
expect(consoleSpy).toHaveBeenCalledWith('[@sentry/nextjs] Running runAfterProductionCompile logic.');
consoleSpy.mockRestore();
});
});
describe('error handling', () => {
it('handles missing bundler plugin core gracefully', async () => {
(loadModule as any).mockReturnValue(null);
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
await handleRunAfterProductionCompile(
{
releaseName: 'test-release',
distDir: '/path/to/.next',
buildTool: 'turbopack',
},
mockSentryBuildOptions,
);
expect(consoleWarnSpy).toHaveBeenCalledWith(
'[@sentry/nextjs] Could not load build manager package. Will not run runAfterProductionCompile logic.',
);
expect(mockCreateSentryBuildPluginManager).not.toHaveBeenCalled();
consoleWarnSpy.mockRestore();
});
it('handles missing createSentryBuildPluginManager export gracefully', async () => {
(loadModule as any).mockReturnValue({});
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
await handleRunAfterProductionCompile(
{
releaseName: 'test-release',
distDir: '/path/to/.next',
buildTool: 'turbopack',
},
mockSentryBuildOptions,
);
expect(consoleWarnSpy).toHaveBeenCalledWith(
'[@sentry/nextjs] Could not load build manager package. Will not run runAfterProductionCompile logic.',
);
expect(mockCreateSentryBuildPluginManager).not.toHaveBeenCalled();
consoleWarnSpy.mockRestore();
});
it('propagates errors from build plugin manager operations', async () => {
const mockError = new Error('Test error');
mockSentryBuildPluginManager.createRelease.mockRejectedValue(mockError);
await expect(
handleRunAfterProductionCompile(
{
releaseName: 'test-release',
distDir: '/path/to/.next',
buildTool: 'turbopack',
},
mockSentryBuildOptions,
),
).rejects.toThrow('Test error');
});
});
describe('step execution order', () => {
it('executes build steps in correct order', async () => {
const executionOrder: string[] = [];
mockSentryBuildPluginManager.telemetry.emitBundlerPluginExecutionSignal.mockImplementation(async () => {
executionOrder.push('telemetry');
});
mockSentryBuildPluginManager.createRelease.mockImplementation(async () => {
executionOrder.push('createRelease');
});
mockSentryBuildPluginManager.injectDebugIds.mockImplementation(async () => {
executionOrder.push('injectDebugIds');
});
mockSentryBuildPluginManager.uploadSourcemaps.mockImplementation(async () => {
executionOrder.push('uploadSourcemaps');
});
mockSentryBuildPluginManager.deleteArtifacts.mockImplementation(async () => {
executionOrder.push('deleteArtifacts');
});
await handleRunAfterProductionCompile(
{
releaseName: 'test-release',
distDir: '/path/to/.next',
buildTool: 'turbopack',
},
mockSentryBuildOptions,
);
expect(executionOrder).toEqual([
'telemetry',
'createRelease',
'injectDebugIds',
'uploadSourcemaps',
'deleteArtifacts',
]);
});
});
describe('sourcemaps disabled', () => {
it('skips debug ID injection when sourcemaps.disable is true', async () => {
const optionsWithDisabledSourcemaps: SentryBuildOptions = {
...mockSentryBuildOptions,
sourcemaps: {
disable: true,
},
};
await handleRunAfterProductionCompile(
{
releaseName: 'test-release',
distDir: '/path/to/.next',
buildTool: 'turbopack',
},
optionsWithDisabledSourcemaps,
);
expect(mockSentryBuildPluginManager.injectDebugIds).not.toHaveBeenCalled();
expect(mockSentryBuildPluginManager.uploadSourcemaps).toHaveBeenCalled();
});
it('still injects debug IDs when sourcemaps.disable is false', async () => {
const optionsWithEnabledSourcemaps: SentryBuildOptions = {
...mockSentryBuildOptions,
sourcemaps: {
disable: false,
},
};
await handleRunAfterProductionCompile(
{
releaseName: 'test-release',
distDir: '/path/to/.next',
buildTool: 'turbopack',
},
optionsWithEnabledSourcemaps,
);
expect(mockSentryBuildPluginManager.injectDebugIds).toHaveBeenCalledWith(['/path/to/.next']);
});
it('still injects debug IDs when sourcemaps option is undefined', async () => {
await handleRunAfterProductionCompile(
{
releaseName: 'test-release',
distDir: '/path/to/.next',
buildTool: 'turbopack',
},
mockSentryBuildOptions,
);
expect(mockSentryBuildPluginManager.injectDebugIds).toHaveBeenCalledWith(['/path/to/.next']);
});
});
describe('sourceMappingURL stripping', () => {
let readdirSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
// Spy on fs.promises.readdir to detect whether stripping was attempted.
// The actual readdir will fail (dir doesn't exist), which is fine — we just
// need to know if it was called.
readdirSpy = vi.spyOn(fs.promises, 'readdir').mockRejectedValue(new Error('ENOENT'));
});
afterEach(() => {
readdirSpy.mockRestore();
});
it('strips sourceMappingURL comments for turbopack builds with deleteSourcemapsAfterUpload', async () => {
await handleRunAfterProductionCompile(
{
releaseName: 'test-release',
distDir: '/path/to/.next',
buildTool: 'turbopack',
},
{
...mockSentryBuildOptions,
sourcemaps: { deleteSourcemapsAfterUpload: true },
},
);
expect(readdirSpy).toHaveBeenCalledWith(
path.join('/path/to/.next', 'static'),
expect.objectContaining({ recursive: true }),
);
});
it('does NOT strip sourceMappingURL comments for webpack builds even with deleteSourcemapsAfterUpload', async () => {
await handleRunAfterProductionCompile(
{
releaseName: 'test-release',
distDir: '/path/to/.next',
buildTool: 'webpack',
},
{
...mockSentryBuildOptions,
sourcemaps: { deleteSourcemapsAfterUpload: true },
},
);
expect(readdirSpy).not.toHaveBeenCalled();
});
it('does NOT strip sourceMappingURL comments when deleteSourcemapsAfterUpload is false', async () => {
await handleRunAfterProductionCompile(
{
releaseName: 'test-release',
distDir: '/path/to/.next',
buildTool: 'turbopack',
},
{
...mockSentryBuildOptions,
sourcemaps: { deleteSourcemapsAfterUpload: false },
},
);
expect(readdirSpy).not.toHaveBeenCalled();
});
it('does NOT strip sourceMappingURL comments when deleteSourcemapsAfterUpload is undefined', async () => {
await handleRunAfterProductionCompile(
{
releaseName: 'test-release',
distDir: '/path/to/.next',
buildTool: 'turbopack',
},
mockSentryBuildOptions,
);
expect(readdirSpy).not.toHaveBeenCalled();
});
});
describe('path handling', () => {
it('correctly passes distDir to debug ID injection', async () => {
const customDistDir = '/custom/dist/path';
await handleRunAfterProductionCompile(
{
releaseName: 'test-release',
distDir: customDistDir,
buildTool: 'turbopack',
},
mockSentryBuildOptions,
);
expect(mockSentryBuildPluginManager.injectDebugIds).toHaveBeenCalledWith([customDistDir]);
expect(mockSentryBuildPluginManager.uploadSourcemaps).toHaveBeenCalledWith([customDistDir], {
prepareArtifacts: false,
});
});
it('works with relative paths', async () => {
const relativeDistDir = '.next';
await handleRunAfterProductionCompile(
{
releaseName: 'test-release',
distDir: relativeDistDir,
buildTool: 'turbopack',
},
mockSentryBuildOptions,
);
expect(mockSentryBuildPluginManager.injectDebugIds).toHaveBeenCalledWith([relativeDistDir]);
expect(mockSentryBuildPluginManager.uploadSourcemaps).toHaveBeenCalledWith([relativeDistDir], {
prepareArtifacts: false,
});
});
});
});
describe('stripSourceMappingURLComments', () => {
let tmpDir: string;
beforeEach(async () => {
tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'sentry-test-'));
await fs.promises.mkdir(path.join(tmpDir, 'chunks'), { recursive: true });
});
afterEach(async () => {
await fs.promises.rm(tmpDir, { recursive: true, force: true });
});
it('strips sourceMappingURL comment from JS files', async () => {
const filePath = path.join(tmpDir, 'chunks', 'abc123.js');
await fs.promises.writeFile(filePath, 'console.log("hello");\n//# sourceMappingURL=abc123.js.map');
await stripSourceMappingURLComments(tmpDir);
const content = await fs.promises.readFile(filePath, 'utf-8');
expect(content).toBe('console.log("hello");');
expect(content).not.toContain('sourceMappingURL');
});
it('strips sourceMappingURL comment from MJS files', async () => {
const filePath = path.join(tmpDir, 'chunks', 'module.mjs');
await fs.promises.writeFile(filePath, 'export default 42;\n//# sourceMappingURL=module.mjs.map');
await stripSourceMappingURLComments(tmpDir);
const content = await fs.promises.readFile(filePath, 'utf-8');
expect(content).toBe('export default 42;');
});
it('strips sourceMappingURL comment from CSS files', async () => {
const filePath = path.join(tmpDir, 'chunks', 'styles.css');
await fs.promises.writeFile(filePath, '.foo { color: red; }\n/*# sourceMappingURL=styles.css.map */');
await stripSourceMappingURLComments(tmpDir);
const content = await fs.promises.readFile(filePath, 'utf-8');
expect(content).toBe('.foo { color: red; }');
});
it('does not modify files without sourceMappingURL comments', async () => {
const filePath = path.join(tmpDir, 'chunks', 'clean.js');
const originalContent = 'console.log("no source map ref");';
await fs.promises.writeFile(filePath, originalContent);
await stripSourceMappingURLComments(tmpDir);
const content = await fs.promises.readFile(filePath, 'utf-8');
expect(content).toBe(originalContent);
});
it('handles files in nested subdirectories', async () => {
const nestedDir = path.join(tmpDir, 'chunks', 'app', 'page');
await fs.promises.mkdir(nestedDir, { recursive: true });
const filePath = path.join(nestedDir, 'layout.js');
await fs.promises.writeFile(filePath, 'var x = 1;\n//# sourceMappingURL=layout.js.map');
await stripSourceMappingURLComments(tmpDir);
const content = await fs.promises.readFile(filePath, 'utf-8');
expect(content).toBe('var x = 1;');
});
it('handles non-existent directory gracefully', async () => {
await expect(stripSourceMappingURLComments('/nonexistent/path')).resolves.toBeUndefined();
});
it('handles sourceMappingURL with @-style comment', async () => {
const filePath = path.join(tmpDir, 'chunks', 'legacy.js');
await fs.promises.writeFile(filePath, 'var y = 2;\n//@ sourceMappingURL=legacy.js.map');
await stripSourceMappingURLComments(tmpDir);
const content = await fs.promises.readFile(filePath, 'utf-8');
expect(content).toBe('var y = 2;');
});
it('ignores non-JS/CSS files', async () => {
const filePath = path.join(tmpDir, 'chunks', 'data.json');
const originalContent = '{"key": "value"}\n//# sourceMappingURL=data.json.map';
await fs.promises.writeFile(filePath, originalContent);
await stripSourceMappingURLComments(tmpDir);
const content = await fs.promises.readFile(filePath, 'utf-8');
expect(content).toBe(originalContent);
});
it('processes multiple files concurrently', async () => {
const files = ['a.js', 'b.mjs', 'c.cjs', 'd.css'];
for (const file of files) {
const ext = path.extname(file);
const comment = ext === '.css' ? `/*# sourceMappingURL=${file}.map */` : `//# sourceMappingURL=${file}.map`;
await fs.promises.writeFile(path.join(tmpDir, file), `content_${file}\n${comment}`);
}
await stripSourceMappingURLComments(tmpDir);
for (const file of files) {
const content = await fs.promises.readFile(path.join(tmpDir, file), 'utf-8');
expect(content).toBe(`content_${file}`);
expect(content).not.toContain('sourceMappingURL');
}
});
});