-
Notifications
You must be signed in to change notification settings - Fork 329
feat(instrumentation): support nextConfig.instrumentationClientInject #1416
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 4 commits
489bea8
13a640b
6339697
1ae9ab4
2b44231
b37769f
dd39e20
bf0e1ee
5ce7226
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| /** | ||
| * Generate a virtual ESM module that implements the Next.js | ||
| * `instrumentationClientInject` contract for client bootstrap. | ||
| * | ||
| * When `injects` is empty, this is a transparent passthrough (or no-op | ||
| * when no user file exists). Otherwise it generates side-effect imports | ||
| * for each inject in array order, then the user's instrumentation-client | ||
| * file last, and exports a single composed `onRouterTransitionStart` that | ||
| * fans out to every module's hook. | ||
| * | ||
| * @param injects - Module specifiers from `nextConfig.instrumentationClientInject` | ||
| * @param userPath - Absolute path to the user's `instrumentation-client` file, | ||
| * or `null` when the file doesn't exist | ||
| */ | ||
| export function generateInstrumentationClientInjectModule( | ||
| injects: readonly string[], | ||
| userPath: string | null, | ||
| ): string { | ||
| const EMPTY_MODULE = "vinext/client/empty-module"; | ||
|
|
||
| // No injects: Next.js keeps the current transparent passthrough. | ||
| // The alias already handles the user file or empty-module, so emit | ||
| // nothing that could shadow what the alias resolves. | ||
| if (injects.length === 0) { | ||
| return "export {};"; | ||
| } | ||
|
|
||
| const lines: string[] = []; | ||
|
|
||
| for (let i = 0; i < injects.length; i++) { | ||
| lines.push(`import * as __vinj_${i} from ${JSON.stringify(injects[i])};`); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Next.js resolves inject specifiers against the project root before emitting |
||
| } | ||
|
|
||
| const lastIndex = injects.length; | ||
| lines.push(`import * as __vinj_${lastIndex} from ${JSON.stringify(userPath ?? EMPTY_MODULE)};`); | ||
|
|
||
| const hookCalls: string[] = []; | ||
| for (let i = 0; i <= lastIndex; i++) { | ||
| hookCalls.push( | ||
| ` if (typeof __vinj_${i}.onRouterTransitionStart === "function") {`, | ||
| ` __vinj_${i}.onRouterTransitionStart(url, type);`, | ||
| ` }`, | ||
| ); | ||
| } | ||
|
|
||
| lines.push(""); | ||
| lines.push("export function onRouterTransitionStart(url, type) {"); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit: the generated function signature has no type annotations. This is fine since it's a virtual module consumed by Vite (not user-facing code), and Vite will treat it as JS regardless. But for consistency with Not blocking — just a polish suggestion. |
||
| lines.push(...hookCalls); | ||
| lines.push(`}`); | ||
| lines.push(""); | ||
|
|
||
| return lines.join("\n"); | ||
| } | ||
| Original file line number | Diff line number | Diff line change | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -211,6 +211,12 @@ export type NextConfig = { | |||||||||||||
| output?: "export" | "standalone"; | ||||||||||||||
| /** File extensions treated as routable pages/routes (Next.js pageExtensions) */ | ||||||||||||||
| pageExtensions?: string[]; | ||||||||||||||
| /** | ||||||||||||||
| * Module specifiers that are required for side effects on the client before | ||||||||||||||
| * hydration, in array order, ahead of the user's `instrumentation-client.{ts,js}`. | ||||||||||||||
| * Each entry may be a bare npm package name or a path relative to the project root. | ||||||||||||||
| */ | ||||||||||||||
| instrumentationClientInject?: string[]; | ||||||||||||||
| /** Extra origins allowed to access the dev server. */ | ||||||||||||||
| allowedDevOrigins?: string[]; | ||||||||||||||
| /** Maximum age in seconds for stale ISR entries before blocking regeneration. */ | ||||||||||||||
|
|
@@ -290,6 +296,7 @@ export type ResolvedNextConfig = { | |||||||||||||
| trailingSlash: boolean; | ||||||||||||||
| output: "" | "export" | "standalone"; | ||||||||||||||
| pageExtensions: string[]; | ||||||||||||||
| instrumentationClientInject: string[]; | ||||||||||||||
| cacheComponents: boolean; | ||||||||||||||
| redirects: NextRedirect[]; | ||||||||||||||
| rewrites: { | ||||||||||||||
|
|
@@ -951,6 +958,7 @@ export async function resolveNextConfig( | |||||||||||||
| buildId, | ||||||||||||||
| deploymentId, | ||||||||||||||
| sassOptions: null, | ||||||||||||||
| instrumentationClientInject: [], | ||||||||||||||
| }; | ||||||||||||||
| detectNextIntlConfig(root, resolved); | ||||||||||||||
| return resolved; | ||||||||||||||
|
|
@@ -1130,6 +1138,9 @@ export async function resolveNextConfig( | |||||||||||||
| trailingSlash: config.trailingSlash ?? false, | ||||||||||||||
| output: output === "export" || output === "standalone" ? output : "", | ||||||||||||||
| pageExtensions, | ||||||||||||||
| instrumentationClientInject: Array.isArray(config.instrumentationClientInject) | ||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Minor: this validates that
Suggested change
This is consistent with how |
||||||||||||||
| ? (config.instrumentationClientInject as string[]) | ||||||||||||||
| : [], | ||||||||||||||
| cacheComponents: config.cacheComponents ?? false, | ||||||||||||||
| redirects, | ||||||||||||||
| rewrites, | ||||||||||||||
|
|
||||||||||||||
| Original file line number | Diff line number | Diff line change | ||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -93,6 +93,7 @@ import { clientReferenceDedupPlugin } from "./plugins/client-reference-dedup.js" | |||||||||||||||
| import { dataUrlCssPlugin } from "./plugins/css-data-url.js"; | ||||||||||||||||
| import { createRscClientReferenceLoadersPlugin } from "./plugins/rsc-client-reference-loaders.js"; | ||||||||||||||||
| import { createInstrumentationClientTransformPlugin } from "./plugins/instrumentation-client.js"; | ||||||||||||||||
| import { generateInstrumentationClientInjectModule } from "./client/instrumentation-client-inject.js"; | ||||||||||||||||
| import { createMiddlewareServerOnlyPlugin } from "./plugins/middleware-server-only.js"; | ||||||||||||||||
| import { createOptimizeImportsPlugin } from "./plugins/optimize-imports.js"; | ||||||||||||||||
| import { createOgInlineFetchAssetsPlugin, ogAssetsPlugin } from "./plugins/og-assets.js"; | ||||||||||||||||
|
|
@@ -423,6 +424,9 @@ const VIRTUAL_APP_BROWSER_ENTRY = "virtual:vinext-app-browser-entry"; | |||||||||||||||
| const RESOLVED_APP_BROWSER_ENTRY = "\0" + VIRTUAL_APP_BROWSER_ENTRY; | ||||||||||||||||
| const VIRTUAL_ROOT_PARAMS = "virtual:vinext-root-params"; | ||||||||||||||||
| const RESOLVED_ROOT_PARAMS = "\0" + VIRTUAL_ROOT_PARAMS; | ||||||||||||||||
| /** Virtual module for composed instrumentation-client bootstrap. */ | ||||||||||||||||
| const VIRTUAL_INSTRUMENTATION_CLIENT = "private-next-instrumentation-client"; | ||||||||||||||||
| const RESOLVED_INSTRUMENTATION_CLIENT = "\0" + VIRTUAL_INSTRUMENTATION_CLIENT; | ||||||||||||||||
| /** Image file extensions handled by the vinext:image-imports plugin. | ||||||||||||||||
| * Shared between the Rolldown hook filter and the transform handler regex. */ | ||||||||||||||||
| const IMAGE_EXTS = "png|jpe?g|gif|webp|avif|svg|ico|bmp|tiff?"; | ||||||||||||||||
|
|
@@ -639,6 +643,7 @@ export default function vinext(options: VinextOptions = {}): PluginOption[] { | |||||||||||||||
| let middlewarePath: string | null = null; | ||||||||||||||||
| let instrumentationPath: string | null = null; | ||||||||||||||||
| let instrumentationClientPath: string | null = null; | ||||||||||||||||
| let clientInjectModule: string | null = null; | ||||||||||||||||
| let hasCloudflarePlugin = false; | ||||||||||||||||
| let warnedInlineNextConfigOverride = false; | ||||||||||||||||
| let hasNitroPlugin = false; | ||||||||||||||||
|
|
@@ -1057,6 +1062,12 @@ export default function vinext(options: VinextOptions = {}): PluginOption[] { | |||||||||||||||
| instrumentationPath = findInstrumentationFile(root, fileMatcher); | ||||||||||||||||
| instrumentationClientPath = findInstrumentationClientFile(root, fileMatcher); | ||||||||||||||||
| middlewarePath = findMiddlewareFile(root, fileMatcher); | ||||||||||||||||
| if (nextConfig.instrumentationClientInject.length > 0) { | ||||||||||||||||
| clientInjectModule = generateInstrumentationClientInjectModule( | ||||||||||||||||
| nextConfig.instrumentationClientInject, | ||||||||||||||||
| instrumentationClientPath, | ||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The module string is only computed when This is fine today because
Suggested change
This makes the assignment unconditional and self-clearing, which is safer against future refactors. |
||||||||||||||||
| ); | ||||||||||||||||
| } | ||||||||||||||||
| if (env?.command === "build") { | ||||||||||||||||
| await writeRouteTypes(); | ||||||||||||||||
| } | ||||||||||||||||
|
|
@@ -2298,6 +2309,28 @@ export default function vinext(options: VinextOptions = {}): PluginOption[] { | |||||||||||||||
| // Stub node:async_hooks in client builds — see src/plugins/async-hooks-stub.ts | ||||||||||||||||
| asyncHooksStubPlugin, | ||||||||||||||||
| createInstrumentationClientTransformPlugin(() => instrumentationClientPath), | ||||||||||||||||
| // Generate a virtual `private-next-instrumentation-client` module when | ||||||||||||||||
| // `nextConfig.instrumentationClientInject` is non-empty. Side-effect imports | ||||||||||||||||
| // run in array order, ending with the user's `instrumentation-client` file | ||||||||||||||||
| // (or empty-module), and a single composed `onRouterTransitionStart` fans | ||||||||||||||||
| // out to every module's hook. | ||||||||||||||||
| { | ||||||||||||||||
| name: "vinext:instrumentation-client-inject", | ||||||||||||||||
| enforce: "pre", | ||||||||||||||||
|
|
||||||||||||||||
| resolveId(id) { | ||||||||||||||||
| if (id !== VIRTUAL_INSTRUMENTATION_CLIENT) return null; | ||||||||||||||||
| // The module was generated in config() if there are injects to compose. | ||||||||||||||||
| // When empty, resolve.alias handles passthrough to the user file or empty-module. | ||||||||||||||||
| return clientInjectModule !== null ? RESOLVED_INSTRUMENTATION_CLIENT : null; | ||||||||||||||||
| }, | ||||||||||||||||
|
|
||||||||||||||||
| load(id) { | ||||||||||||||||
| if (id !== RESOLVED_INSTRUMENTATION_CLIENT) return null; | ||||||||||||||||
| // Deterministic output precomputed once in config(). | ||||||||||||||||
| return clientInjectModule; | ||||||||||||||||
| }, | ||||||||||||||||
| }, | ||||||||||||||||
| // Dedup client references from RSC proxy modules — see src/plugins/client-reference-dedup.ts | ||||||||||||||||
| ...(options.experimental?.clientReferenceDedup ? [clientReferenceDedupPlugin()] : []), | ||||||||||||||||
| // Proxy plugin for @mdx-js/rollup. The real MDX plugin is created lazily | ||||||||||||||||
|
|
||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,6 +6,7 @@ import { | |
| findInstrumentationClientFile, | ||
| findInstrumentationFile, | ||
| } from "../packages/vinext/src/server/instrumentation.js"; | ||
| import { generateInstrumentationClientInjectModule } from "../packages/vinext/src/client/instrumentation-client-inject.js"; | ||
| import { createValidFileMatcher } from "../packages/vinext/src/routing/file-matcher.js"; | ||
|
|
||
| // The runInstrumentation/reportRequestError describe blocks re-import via | ||
|
|
@@ -342,3 +343,55 @@ describe("reportRequestError", () => { | |
| expect(onRequestError).toHaveBeenCalledOnce(); | ||
| }); | ||
| }); | ||
|
|
||
| describe("generateInstrumentationClientInjectModule", () => { | ||
| it("returns passthrough when injects is empty", () => { | ||
| const code = generateInstrumentationClientInjectModule([], null); | ||
| expect(code).toBe("export {};"); | ||
| }); | ||
|
|
||
| it("generates a single import for one inject entry", () => { | ||
| const code = generateInstrumentationClientInjectModule(["./inject-a.js"], null); | ||
| expect(code).toContain('import * as __vinj_0 from "./inject-a.js"'); | ||
| expect(code).toContain("export function onRouterTransitionStart(url, type)"); | ||
| expect(code).toContain('typeof __vinj_0.onRouterTransitionStart === "function"'); | ||
| expect(code).toContain("\n __vinj_0.onRouterTransitionStart(url, type);\n"); | ||
| }); | ||
|
|
||
| it("generates imports in config order with user file last", () => { | ||
| const code = generateInstrumentationClientInjectModule( | ||
| ["./inject-a.js", "some-npm-pkg"], | ||
| "/project/instrumentation-client.ts", | ||
| ); | ||
| expect(code).toContain('import * as __vinj_0 from "./inject-a.js"'); | ||
| expect(code).toContain('import * as __vinj_1 from "some-npm-pkg"'); | ||
| expect(code).toContain('import * as __vinj_2 from "/project/instrumentation-client.ts"'); | ||
| }); | ||
|
|
||
| it("falls back to empty-module when user file is absent", () => { | ||
| const code = generateInstrumentationClientInjectModule(["./inject-a.js"], null); | ||
| expect(code).toContain('import * as __vinj_1 from "vinext/client/empty-module"'); | ||
| }); | ||
|
|
||
| it("composes hook calls for every module in array order", () => { | ||
| const code = generateInstrumentationClientInjectModule( | ||
| ["./inject-a.js", "./inject-b.js"], | ||
| "/project/instrumentation-client.ts", | ||
| ); | ||
| // Each module should have its own hook-check-and-call | ||
| expect(code).toContain('typeof __vinj_0.onRouterTransitionStart === "function"'); | ||
| expect(code).toContain("__vinj_0.onRouterTransitionStart(url, type)"); | ||
| expect(code).toContain('typeof __vinj_1.onRouterTransitionStart === "function"'); | ||
| expect(code).toContain("__vinj_1.onRouterTransitionStart(url, type)"); | ||
| expect(code).toContain('typeof __vinj_2.onRouterTransitionStart === "function"'); | ||
| expect(code).toContain("__vinj_2.onRouterTransitionStart(url, type)"); | ||
| }); | ||
|
|
||
| it("exports empty object when injects is empty and user file is present", () => { | ||
| const code = generateInstrumentationClientInjectModule( | ||
| [], | ||
| "/project/instrumentation-client.ts", | ||
| ); | ||
| expect(code).toBe("export {};"); | ||
| }); | ||
| }); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good test coverage for the pure code-generation function. One edge case worth adding: what happens when an inject specifier contains characters that could break the generated import (e.g., a specifier with quotes or backslashes)? it("escapes special characters in specifier paths", () => {
const code = generateInstrumentationClientInjectModule(
['./path/with"quote.js'],
null,
);
expect(code).toContain('from "./path/with\\"quote.js"');
});Also, there's no integration-level test that verifies the Vite plugin wiring end-to-end (i.e., that the virtual module is actually served when |
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When
injectsis empty, this returns"export {};"regardless of whether the user has aninstrumentation-clientfile. The PR description says this is intentional ("the alias already handles the user file or empty-module"), which is correct — theresolve.aliasat index.ts:1261 mapsprivate-next-instrumentation-clientto the user file or empty-module and takes effect when this plugin returnsnullfromresolveId.However, this means there's an asymmetry in the hook composition path: when injects are present, the composed
onRouterTransitionStartfans out to all modules including the user file. When injects are empty, the user'sonRouterTransitionStartflows directly through the alias. Both paths work, but it's worth documenting this explicitly in the function's JSDoc (the current doc hints at it but doesn't state the two resolution paths clearly).