Skip to content

Commit 4b7f906

Browse files
committed
fix: use custom preseveration logic for nextjs templates
1 parent 30cbf6a commit 4b7f906

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

packages/nextjs/rollup.npm.config.mjs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,49 @@ export default [
7272
'__SENTRY_WRAPPING_TARGET_FILE__',
7373
'__SENTRY_NEXTJS_REQUEST_ASYNC_STORAGE_SHIM__',
7474
],
75+
plugins: [
76+
{
77+
name: 'sentry-fix-rolldown-generated-identifiers',
78+
renderChunk(code, chunk) {
79+
// Rolldown generates import identifiers like `__SENTRY_WRAPPING_TARGET_FILE___default` for default imports
80+
// from our placeholder modules. When the wrapping loader later replaces `__SENTRY_WRAPPING_TARGET_FILE__`
81+
// with `__SENTRY_WRAPPING_TARGET_FILE__.cjs`, this creates invalid syntax like
82+
// `__SENTRY_WRAPPING_TARGET_FILE__.cjs_default`, where `.cjs` breaks the identifier.
83+
// We fix this by replacing the problematic identifier pattern with a safe one that uses a different
84+
// separator that won't be confused with property access when the placeholder is replaced.
85+
let fixedCode = code
86+
.replace(
87+
/__SENTRY_WRAPPING_TARGET_FILE___default/g,
88+
'__SENTRY_WRAPPING_TARGET_FILE_PLACEHOLDER_DEFAULT__',
89+
)
90+
.replace(/__SENTRY_CONFIG_IMPORT_PATH___default/g, '__SENTRY_CONFIG_IMPORT_PATH_PLACEHOLDER_DEFAULT__')
91+
.replace(
92+
/__SENTRY_NEXTJS_REQUEST_ASYNC_STORAGE_SHIM___default/g,
93+
'__SENTRY_NEXTJS_REQUEST_ASYNC_STORAGE_SHIM_PLACEHOLDER_DEFAULT__',
94+
);
95+
96+
// Rolldown has a bug where it removes namespace imports for external modules even when they're still
97+
// referenced in the code (specifically when there's a `declare const` with the same name in the source).
98+
// We need to add back the missing import for serverComponentModule in the serverComponentWrapperTemplate.
99+
if (
100+
chunk.facadeModuleId?.includes('serverComponentWrapperTemplate') &&
101+
fixedCode.includes('serverComponentModule') &&
102+
!fixedCode.includes('import * as serverComponentModule')
103+
) {
104+
// Find the position after the last import statement to insert our missing import
105+
const lastImportMatch = fixedCode.match(/^import[^;]*;/gm);
106+
if (lastImportMatch) {
107+
const lastImport = lastImportMatch[lastImportMatch.length - 1];
108+
const lastImportEnd = fixedCode.indexOf(lastImport) + lastImport.length;
109+
fixedCode = `${fixedCode.slice(0, lastImportEnd)}
110+
import * as serverComponentModule from "__SENTRY_WRAPPING_TARGET_FILE__";${fixedCode.slice(lastImportEnd)}`;
111+
}
112+
}
113+
114+
return { code: fixedCode };
115+
},
116+
},
117+
],
75118
},
76119
}),
77120
),

0 commit comments

Comments
 (0)