Skip to content
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

feat: add polyfills option to auto-imports #30332

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

wattanx
Copy link
Collaborator

@wattanx wattanx commented Dec 22, 2024

🔗 Linked issue

ref: nuxt/test-utils#1035

📚 Description

Mocking native APIs like setInterval could make it difficult to mock in tests.
We would like to add a polyfills option to allow the choice of not overriding APIs like setInterval.

Copy link

stackblitz bot commented Dec 22, 2024

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

@wattanx wattanx marked this pull request as ready for review December 22, 2024 14:13
@wattanx wattanx requested a review from danielroe as a code owner December 22, 2024 14:13
Copy link

coderabbitai bot commented Dec 22, 2024

Walkthrough

The pull request introduces modifications to the Nuxt imports module and related configuration files to enhance compatibility and provide more flexible import options. The changes primarily focus on adding a new optional polyfills configuration that allows developers to control the inclusion of specific compatibility presets.

Key modifications include:

  • Adding a new appCompatPresets array in the presets module
  • Introducing a polyfills option in the imports configuration schema
  • Updating the imports module to conditionally include compatibility presets
  • Extending the test suite to verify the new import behaviour

The changes are implemented across multiple files:

  • packages/nuxt/src/imports/module.ts
  • packages/nuxt/src/imports/presets.ts
  • packages/schema/src/types/imports.ts
  • test/nuxt/client.test.ts
  • vitest.nuxt.config.ts

The modifications aim to provide more granular control over auto-imports and compatibility features within the Nuxt framework, allowing developers to opt-in or opt-out of specific polyfill and compatibility imports as needed.

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
packages/schema/src/types/imports.ts (1)

35-40: Enhance documentation for the polyfills option

The documentation should provide a comprehensive list of all polyfills that will be included when this option is enabled. This helps developers make informed decisions about whether to enable or disable the feature.

Consider expanding the documentation like this:

  /**
-  * Add polyfills for setInterval, requestIdleCallback, and others
+  * Add polyfills for native APIs to improve testing capabilities.
+  * Currently includes:
+  * - setInterval
+  * - requestIdleCallback
+  * - [list other included polyfills]
+  *
+  * When disabled, these APIs must be mocked manually in tests.
   * @default true
   */
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 201323d and 2db638b.

📒 Files selected for processing (5)
  • packages/nuxt/src/imports/module.ts (1 hunks)
  • packages/nuxt/src/imports/presets.ts (1 hunks)
  • packages/schema/src/types/imports.ts (1 hunks)
  • test/nuxt/client.test.ts (2 hunks)
  • vitest.nuxt.config.ts (1 hunks)
🔇 Additional comments (4)
vitest.nuxt.config.ts (1)

24-26: Configuration looks good

The polyfills: false setting in the test configuration aligns with the PR objectives, allowing for manual mocking of native APIs during testing.

packages/nuxt/src/imports/presets.ts (1)

251-260: LGTM! Clean separation of polyfills into a dedicated preset.

The implementation cleanly separates polyfills into their own preset array, making them optional through the new polyfills configuration option.

Let's verify if there are any other native API polyfills that should be included:

✅ Verification successful

Let's search for the actual polyfill implementations to ensure we haven't missed any.


The polyfill list in appCompatPresets is complete and correctly implemented

The implementation covers all the compatibility-related functionality in the codebase:

  • idle-callback.ts: Polyfills for requestIdleCallback and cancelIdleCallback
  • interval.ts: Server-safe wrapper for setInterval
  • Other files in the compat directory (capi.ts and vue-demi.ts) are Vue-specific compatibility layers rather than browser API polyfills
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other potential polyfills in the codebase
rg -g '!*.test.*' -g '!*.spec.*' "from.*compat.*" 

Length of output: 1744


Script:

#!/bin/bash
# Search for polyfill implementations in the compat directory
fd "compat" --type d
fd . --full-path "*/compat/*" --type f --exec cat {}

Length of output: 205


Script:

#!/bin/bash
# List and show content of files in the compat directory
ls -la packages/nuxt/src/app/compat/
cat packages/nuxt/src/app/compat/*

Length of output: 2351

packages/nuxt/src/imports/module.ts (2)

12-12: LGTM! Clean import of the new preset.

The import statement is correctly placed and follows the existing import style.


19-36: LGTM! Well-implemented conditional polyfills inclusion.

The implementation:

  • Maintains backwards compatibility by defaulting polyfills to true
  • Correctly implements conditional inclusion of polyfills
  • Follows the existing code structure

Let's verify the default behaviour remains unchanged:

✅ Verification successful

Let me verify the polyfills implementation further by checking the imports configuration and usage.


Let me check one final aspect - the definition of appCompatPresets to fully understand what polyfills are being conditionally included.


Polyfills implementation verified and working as expected

The implementation correctly handles polyfills by:

  • Conditionally including requestIdleCallback, cancelIdleCallback, and setInterval from compatibility layer
  • Maintaining proper imports from #app/compat/* modules
  • Preserving existing functionality through default presets
  • Allowing opt-out via imports.polyfills configuration

The implementation is safe as the polyfills are:

  • Properly isolated in dedicated compatibility modules
  • Used consistently throughout the codebase
  • Have appropriate server-side handling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing usages of these polyfills to ensure we don't break anything
rg -g '!*.test.*' -g '!*.spec.*' "requestIdleCallback|setInterval" 

Length of output: 1741


Script:

#!/bin/bash
# Check the imports configuration and polyfills setup
ast-grep --pattern 'export const defaultPresets = $$$'

# Check for any conditional polyfills usage
rg -g '!*.test.*' -g '!*.spec.*' "imports\.polyfills" -A 2 -B 2

Length of output: 491


Script:

#!/bin/bash
# Check the definition of appCompatPresets
ast-grep --pattern 'export const appCompatPresets = $$$'

# Also check if there are any other references to these presets
rg -g '!*.test.*' -g '!*.spec.*' "appCompatPresets"

Length of output: 437


Script:

#!/bin/bash
# Let's see the actual content of the presets file to understand the polyfills
cat packages/nuxt/src/imports/presets.ts

Length of output: 6080

Comment on lines +80 to +92
it('setInterval is not auto-imported', async () => {
vi.useFakeTimers()

const wrapper = mount(Component)

vi.advanceTimersByTime(1000)

await wrapper.vm.$nextTick()

expect(wrapper.find('#child').exists()).toBe(true)

vi.useRealTimers()
})
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve test robustness and coverage

Several improvements could enhance the test:

  1. The test should clean up timers in an afterEach hook to prevent leaks if the test fails
  2. The test description should be more specific about what's being tested
  3. Consider adding a complementary test with polyfills enabled

Here's how to improve the test:

+  afterEach(() => {
+    vi.useRealTimers()
+  })
-  it('setInterval is not auto-imported', async () => {
+  it('should toggle visibility after timeout when using native setInterval', async () => {
     vi.useFakeTimers()
     const wrapper = mount(Component)
     vi.advanceTimersByTime(1000)
     await wrapper.vm.$nextTick()
     expect(wrapper.find('#child').exists()).toBe(true)
-    vi.useRealTimers()
   })

Consider adding this complementary test:

  it('should work with polyfills enabled', async () => {
    // TODO: Add test with imports.polyfills = true
    // This would verify the feature works in both configurations
  })

Comment on lines +72 to +75
const visible = ref(false)
setInterval(() => {
visible.value = true
}, 1000)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add missing ref import

The code uses ref but the import statement is missing.

Add this import at the top of the file:

-import { Suspense, defineComponent, h, toDisplayString, useAttrs } from 'vue'
+import { Suspense, defineComponent, h, toDisplayString, useAttrs, ref } from 'vue'

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +69 to +93
describe('app/compat', () => {
const Component = defineComponent({
setup () {
const visible = ref(false)
setInterval(() => {
visible.value = true
}, 1000)

return () => h('div', {}, visible.value ? h('span', { id: 'child' }) : {})
},
})
it('setInterval is not auto-imported', async () => {
vi.useFakeTimers()

const wrapper = mount(Component)

vi.advanceTimersByTime(1000)

await wrapper.vm.$nextTick()

expect(wrapper.find('#child').exists()).toBe(true)

vi.useRealTimers()
})
})
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Add test coverage for requestIdleCallback polyfill

The codebase includes polyfills for both setInterval and requestIdleCallback, but only setInterval is currently tested. A test for requestIdleCallback is needed as it's the only other significant polyfill implemented in the compat layer.

Key points to test:

  • packages/nuxt/src/app/compat/idle-callback.ts provides polyfill for browsers without native support
  • The polyfill includes both requestIdleCallback and cancelIdleCallback
  • The implementation provides a fallback using setTimeout
🔗 Analysis chain

Verify test coverage for other polyfilled APIs

The test suite only covers setInterval. Consider adding tests for other APIs mentioned in the polyfills option, such as requestIdleCallback.

Let's check what other APIs might need testing:


Let me gather more information about the polyfills and their test coverage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other polyfilled APIs in the codebase
rg -l "requestIdleCallback|setInterval" --type ts

Length of output: 379


Script:

#!/bin/bash
# Check the polyfills configuration and implementation
cat packages/nuxt/src/app/compat/idle-callback.ts
cat packages/nuxt/src/app/compat/interval.ts
cat packages/schema/src/types/imports.ts

# Check existing test coverage
rg -A 5 "describe.*compat" test/

Length of output: 3568

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants