-
Notifications
You must be signed in to change notification settings - Fork 419
chore(nextjs): Improve type safety of #safe-node-apis #6597
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
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
📝 WalkthroughWalkthrough
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
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.
Actionable comments posted: 1
🧹 Nitpick comments (7)
.changeset/sharp-suits-lay.md (1)
5-5: Consider documenting the internal runtime tweak in the changeset.This PR also switches keyless telemetry writes to synchronous I/O. Even if internal, calling that out helps consumers scanning release notes.
Apply this diff to make the note explicit:
--- '@clerk/nextjs': patch --- -Add types to safe-node-apis modules. +Add types to safe-node-apis modules. + +Internal: +- Switch keyless telemetry flag creation to synchronous FS APIs to simplify control flow.packages/nextjs/src/types/safe-node-apis.d.ts (1)
9-16: Tighten typings: prefer optional + readonly properties and readonly export.Using optional properties communicates intent better than
| undefined, andreadonlyprevents accidental mutation at type level.Apply this diff:
interface FileSystem { - existsSync: typeof existsSync; - writeFileSync: typeof writeFileSync; - readFileSync: typeof readFileSync; - appendFileSync: typeof appendFileSync; - mkdirSync: typeof mkdirSync; - rmSync: typeof rmSync; + readonly existsSync: typeof existsSync; + readonly writeFileSync: typeof writeFileSync; + readonly readFileSync: typeof readFileSync; + readonly appendFileSync: typeof appendFileSync; + readonly mkdirSync: typeof mkdirSync; + readonly rmSync: typeof rmSync; } interface SafeNodeApis { - fs: FileSystem | undefined; - path: typeof nodePath | undefined; - cwd: (() => string) | undefined; + readonly fs?: FileSystem; + readonly path?: typeof nodePath; + readonly cwd?: () => string; } - declare const safeNodeApis: SafeNodeApis; + declare const safeNodeApis: Readonly<SafeNodeApis>;Also applies to: 18-24
packages/nextjs/src/server/keyless-telemetry.ts (5)
44-44: Sync I/O: verify impact and concurrency behavior.Switching to sync FS is simpler and fine given one-time flag creation, but it blocks the event loop on a hot path if drift detection is invoked during requests. Validate that this code runs during boot or a non-latency-critical path.
If you want non-blocking I/O without promises at the call site, consider a small worker or deferring flag creation to a background tick:
-function tryMarkTelemetryEventAsFired(): boolean { +function tryMarkTelemetryEventAsFired(): boolean { try { if (canUseKeyless) { const { mkdirSync, writeFileSync } = nodeFsOrThrow(); // ...Optionally, gate with a cheap in-memory boolean to avoid hitting disk after the first attempt in-process.
52-53: Set explicit directory permissions (defense-in-depth).While telemetry data here isn’t sensitive, it’s good practice to restrict perms for internal dirs.
Apply this diff:
- mkdirSync(flagDirectory, { recursive: true }); + mkdirSync(flagDirectory, { recursive: true, mode: 0o700 });
58-59: Specify encoding and file mode for the telemetry flag file.Avoids platform defaults and ensures restrictive perms.
Apply this diff:
- writeFileSync(flagFilePath, JSON.stringify(flagData, null, 2), { flag: 'wx' }); + writeFileSync(flagFilePath, JSON.stringify(flagData, null, 2), { + flag: 'wx', + encoding: 'utf8', + mode: 0o600, + });
29-31: Optional: use the typed safe path/cwd wrappers for consistency.This module imports
pathand usesprocess.cwd(). To stay aligned with the#safe-node-apissurface, you can switch tonodePathOrThrow()andnodeCwdOrThrow(). Not required if this file is guaranteed to be server-only.Outside the changed lines, here is a concrete refactor sketch:
// Replace imports: import { nodeFsOrThrow, nodePathOrThrow, nodeCwdOrThrow } from './fs/utils'; // Update implementation: function getTelemetryFlagFilePath(): string { const cwd = nodeCwdOrThrow(); const { join } = nodePathOrThrow(); return join(cwd(), TELEMETRY_FLAG_FILE); } // Where dirname is needed: const { dirname } = nodePathOrThrow(); const flagDirectory = dirname(flagFilePath);Also applies to: 47-50
44-70: Add targeted tests for the new sync behavior.
- Creating the flag when it doesn’t exist returns true and writes file with 0o600 perms.
- Subsequent calls return false (EEXIST path).
- Errors other than EEXIST log a warning and return false.
I can scaffold a test harness that stubs
nodeFsOrThrow()to a temp dir FS and asserts the above without touching real disk. Want me to push a test file?
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (4)
.changeset/sharp-suits-lay.md(1 hunks)packages/nextjs/src/server/fs/utils.ts(1 hunks)packages/nextjs/src/server/keyless-telemetry.ts(2 hunks)packages/nextjs/src/types/safe-node-apis.d.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
.changeset/**
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Automated releases must use Changesets.
Files:
.changeset/sharp-suits-lay.md
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/nextjs/src/types/safe-node-apis.d.tspackages/nextjs/src/server/keyless-telemetry.tspackages/nextjs/src/server/fs/utils.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/nextjs/src/types/safe-node-apis.d.tspackages/nextjs/src/server/keyless-telemetry.tspackages/nextjs/src/server/fs/utils.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/nextjs/src/types/safe-node-apis.d.tspackages/nextjs/src/server/keyless-telemetry.tspackages/nextjs/src/server/fs/utils.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/nextjs/src/types/safe-node-apis.d.tspackages/nextjs/src/server/keyless-telemetry.tspackages/nextjs/src/server/fs/utils.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertionsfor literal types:as const
Usesatisfiesoperator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports:import type { ... } from ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/nextjs/src/types/safe-node-apis.d.tspackages/nextjs/src/server/keyless-telemetry.tspackages/nextjs/src/server/fs/utils.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/nextjs/src/types/safe-node-apis.d.tspackages/nextjs/src/server/keyless-telemetry.tspackages/nextjs/src/server/fs/utils.ts
**/*
⚙️ CodeRabbit configuration file
If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.
Files:
packages/nextjs/src/types/safe-node-apis.d.tspackages/nextjs/src/server/keyless-telemetry.tspackages/nextjs/src/server/fs/utils.ts
🧬 Code graph analysis (1)
packages/nextjs/src/server/keyless-telemetry.ts (2)
packages/nextjs/src/utils/feature-flags.ts (1)
canUseKeyless(12-12)packages/nextjs/src/server/fs/utils.ts (1)
nodeFsOrThrow(29-29)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: Analyze (actions)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (6)
.changeset/sharp-suits-lay.md (1)
1-6: Changeset present and scoped correctly.Patch bump for @clerk/nextjs looks appropriate for a types-focused PR.
packages/nextjs/src/types/safe-node-apis.d.ts (2)
6-7: Good use of type-only imports.Keeps the ambient declaration purely structural with no runtime impact.
24-26: I’m gathering your tsconfig details to confirm default-import compatibility.packages/nextjs/src/server/keyless-telemetry.ts (2)
47-47: Correctly narrows to the safe Node FS surface.Destructuring from
nodeFsOrThrow()keeps the safe import boundary localized.
180-181: No remainingawaitusages fortryMarkTelemetryEventAsFiredfound. The call site update is correct and no further changes are needed.packages/nextjs/src/server/fs/utils.ts (1)
14-27: Wrappers look solid and make return types explicit.Clear NonNullable returns with a single guard keep call sites clean.
| if (!nodeRuntime.cwd) { | ||
| throwMissingFsModule('cwd'); | ||
| } | ||
| const nodeCwdOrThrow = (): NonNullable<typeof nodeRuntime.cwd> => { |
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.
Now that we have the assertion function, what happens if we remove the explicit return type here?
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 building @clerk/nextjs I am getting this error unless the explicit return types exist
"Exported variable 'nodeFsOrThrow' has or is using name 'FileSystem' from external module "#safe-node-apis" but cannot be named."
# Conflicts: # packages/nextjs/src/server/keyless-telemetry.ts
🦋 Changeset detectedLatest commit: b25921d The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Description
Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit