-
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 6 commits
489bea8
13a640b
6339697
1ae9ab4
2b44231
b37769f
dd39e20
bf0e1ee
5ce7226
2bf9777
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,60 @@ | ||
| /** | ||
| * Generate a virtual ESM module that implements the Next.js | ||
| * `instrumentationClientInject` contract for client bootstrap. | ||
| * | ||
| * Resolution follows two paths depending on whether injects are configured: | ||
| * | ||
| * **Empty injects (`injects.length === 0`):** Returns `export {}` and the | ||
| * plugin does not serve a virtual module. The `resolve.alias` for | ||
| * `private-next-instrumentation-client` resolves directly to the user's | ||
| * `instrumentation-client` file (or `vinext/client/empty-module` when absent), | ||
| * so the user's `onRouterTransitionStart` is used as-is with no composition. | ||
| * | ||
| * **Non-empty injects:** The plugin serves this generated module via | ||
| * `resolveId`/`load`. It side-effect-imports each inject in config order, then | ||
| * the user's 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: string, type: string) {"); | ||
|
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 from the previous review that's still applicable — the generated function has TypeScript type annotations (
Not blocking — the current behavior is correct under Vite 8. |
||
| 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; | ||||||||||||||
|
|
@@ -1138,6 +1146,11 @@ 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 unknown[]).filter( | ||||||||||||||
| (x): x is string => typeof x === "string", | ||||||||||||||
| ) | ||||||||||||||
| : [], | ||||||||||||||
| cacheComponents: config.cacheComponents ?? false, | ||||||||||||||
| redirects, | ||||||||||||||
| rewrites, | ||||||||||||||
|
|
||||||||||||||
| 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,60 @@ 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: string, type: string)"); | ||
| 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 {};"); | ||
| }); | ||
|
|
||
| it("escapes special characters in specifier paths", () => { | ||
| const code = generateInstrumentationClientInjectModule(['./path/with"quote.js'], null); | ||
| expect(code).toContain('from "./path/with\\"quote.js"'); | ||
| }); | ||
| }); | ||
|
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).