@@ -23,24 +23,7 @@ export function patchWranglerDeps(config: Config) {
23
23
24
24
writeFileSync ( pagesRuntimeFile , patchedPagesRuntime ) ;
25
25
26
- // Patch .next/standalone/node_modules/next/dist/server/lib/trace/tracer.js
27
- //
28
- // Remove the need for an alias in wrangler.toml:
29
- //
30
- // [alias]
31
- // # @opentelemetry /api is `require`d when running wrangler dev, so we need to stub it out
32
- // # IMPORTANT: we shim @opentelemetry /api to the throwing shim so that it will throw right away, this is so that we throw inside the
33
- // # try block here: https://github.com/vercel/next.js/blob/9e8266a7/packages/next/src/server/lib/trace/tracer.ts#L27-L31
34
- // # causing the code to require the 'next/dist/compiled/@opentelemetry/api' module instead (which properly works)
35
- // #"@opentelemetry/api" = "./.next/standalone/node_modules/cf/templates/shims/throw.ts"
36
- const tracerFile = join ( distPath , "server" , "lib" , "trace" , "tracer.js" ) ;
37
-
38
- const patchedTracer = readFileSync ( tracerFile , "utf-8" ) . replaceAll (
39
- / \w + \s * = \s * r e q u i r e \( [ ^ / ] * o p e n t e l e m e t r y .* \) / g,
40
- `throw new Error("@opentelemetry/api")`
41
- ) ;
42
-
43
- writeFileSync ( tracerFile , patchedTracer ) ;
26
+ patchTracerFile ( join ( distPath , "server" , "lib" , "trace" , "tracer.js" ) ) ;
44
27
}
45
28
46
29
/**
@@ -67,3 +50,27 @@ function getDistPath(config: Config): string {
67
50
68
51
throw new Error ( "Unexpected error: unable to detect the node_modules/next/dist directory" ) ;
69
52
}
53
+
54
+ /**
55
+ * Patch trace/tracer.js files that require from `@opentelemetry/api` by replacing such `require`
56
+ * calls with error throwing expressions.
57
+ *
58
+ * The replacement works because code that requires from `@opentelementry/api` is `try-catch`ed
59
+ * and a supported alternative is imported in the catch blocks
60
+ * (see: https://github.com/vercel/next.js/blob/9e8266a7/packages/next/src/server/lib/trace/tracer.ts#L27-L31)
61
+ *
62
+ * @param tracerFilePath path to the tracer file to patch
63
+ */
64
+ export function patchTracerFile ( tracerFilePath : string ) {
65
+ const tracerFileContent = readFileSync ( tracerFilePath , "utf-8" ) ;
66
+ const patchedTracerFileContent = tracerFileContent . replaceAll (
67
+ / \w + \s * = \s * r e q u i r e \( [ ^ / ] * o p e n t e l e m e t r y .* \) / g,
68
+ `throw new Error("@opentelemetry/api")`
69
+ ) ;
70
+
71
+ if ( patchedTracerFileContent === tracerFileContent ) {
72
+ throw new Error ( `Failed to patch tracer file at ${ tracerFilePath } ` ) ;
73
+ }
74
+
75
+ writeFileSync ( tracerFilePath , patchedTracerFileContent ) ;
76
+ }
0 commit comments