Skip to content

fix(utils): preserve bundled native import fallback#5924

Merged
killagu merged 1 commit intonextfrom
agent/egg-dev/06640e7b
May 5, 2026
Merged

fix(utils): preserve bundled native import fallback#5924
killagu merged 1 commit intonextfrom
agent/egg-dev/06640e7b

Conversation

@killagu
Copy link
Copy Markdown
Contributor

@killagu killagu commented May 3, 2026

Summary

  • keep bundled importModule loader misses on an opaque native dynamic import fallback
  • preserve the existing direct import path for non-bundled runtime behavior
  • add a Node fixture covering bundled loader miss fallback and a source-shape guard against bundler expression rewrites

Tests

  • pnpm install
  • pnpm exec vitest run packages/utils/test/bundle-import.test.ts packages/utils/test/import.test.ts packages/utils/test/snapshot-import.test.ts
  • pnpm exec vitest run packages/utils/test
  • pnpm --filter @eggjs/utils typecheck
  • pnpm exec oxfmt --check packages/utils/src/import.ts packages/utils/test/bundle-import.test.ts packages/utils/test/fixtures/bundle-native-fallback/run.mjs
  • pnpm exec oxlint --type-aware --type-check packages/utils/src/import.ts packages/utils/test/bundle-import.test.ts
  • git diff --check

Summary by CodeRabbit

  • New Features

    • Added a conditional native dynamic-import fallback to improve module loading when a bundle loader is present but does not handle a request.
  • Tests

    • Added end-to-end tests exercising the native-import fallback and verifying expected runtime output.
    • Added tests ensuring the fallback isn’t created in restricted code-generation modes.

Copilot AI review requested due to automatic review settings May 3, 2026 16:34
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 3, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a lazy helper that builds an opaque native import(specifier) via new Function and uses it as a guarded fallback in importModule()'s ESM path when a bundle module loader is registered. Adds an E2E fixture and tests validating runtime fallback and source gating.

Changes

Native dynamic-import fallback

Layer / File(s) Summary
Helper / Data shape
packages/utils/src/import.ts
Adds NativeDynamicImport and getNativeDynamicImport() which lazily constructs and caches new Function('specifier', 'return import(specifier);').
Core wiring
packages/utils/src/import.ts
In importModule() ESM branch, when _bundleModuleLoader is truthy call getNativeDynamicImport()(fileUrl); otherwise continue to use await import(fileUrl).
E2E fixture
packages/utils/test/fixtures/bundle-native-fallback/run.mjs
New script registers setBundleModuleLoader that records requested filepaths and returns undefined, invokes importModule() against ../esm, asserts the loader saw the fixture path, and prints result.default.foo.
Tests / Assertions
packages/utils/test/bundle-import.test.ts
Replaces prior undefined-loader unit with a Node subprocess running the fixture; adds a spawn test with --disallow-code-generation-from-strings to ensure helper isn't created at module load; adds source-inspection assertions for the new Function('specifier','return import(specifier);') snippet and _bundleModuleLoader-gated getNativeDynamicImport()(fileUrl) call.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant ImportCaller as importModule()
    participant BundleLoader as _bundleModuleLoader
    participant NativeImport as getNativeDynamicImport()
    participant Module as ESM module

    ImportCaller->>BundleLoader: ask to load specifier
    alt loader returns module
        BundleLoader->>ImportCaller: module (short-circuit)
        ImportCaller->>Module: return loaded module
    else loader returns undefined
        BundleLoader->>ImportCaller: undefined
        ImportCaller->>NativeImport: call(nativeImport, fileUrl)
        NativeImport->>Module: dynamic import(fileUrl)
        Module->>ImportCaller: resolved module
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • jerryliang64

Poem

🐰
I nibble at imports through the night,
A Function wind beneath my flight.
Loaders point, then sometimes pass,
I leap and fetch the module fast.
Foo prints bright — a rabbit's delight!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix(utils): preserve bundled native import fallback' clearly and specifically describes the main change: ensuring the bundled import module loader correctly falls back to a native dynamic import mechanism when needed, which aligns with the actual modifications across all three files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch agent/egg-dev/06640e7b

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 3, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.06%. Comparing base (22fc588) to head (597e4d9).

Additional details and impacted files
@@            Coverage Diff             @@
##             next    #5924      +/-   ##
==========================================
+ Coverage   85.04%   85.06%   +0.01%     
==========================================
  Files         667      667              
  Lines       19128    19129       +1     
  Branches     3725     3725              
==========================================
+ Hits        16268    16272       +4     
+ Misses       2467     2465       -2     
+ Partials      393      392       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@cloudflare-workers-and-pages
Copy link
Copy Markdown

cloudflare-workers-and-pages Bot commented May 3, 2026

Deploying egg with  Cloudflare Pages  Cloudflare Pages

Latest commit: 597e4d9
Status: ✅  Deploy successful!
Preview URL: https://403b48ae.egg-cci.pages.dev
Branch Preview URL: https://agent-egg-dev-06640e7b.egg-cci.pages.dev

View logs

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a mechanism to hide dynamic imports from bundlers like Turbopack by wrapping the import() call within a new Function constructor. This ensures that the fallback to native dynamic import remains opaque to static analysis and transformation tools when a bundle loader is active. The changes include the implementation of nativeDynamicImport in packages/utils/src/import.ts and the addition of integration tests and fixtures to verify the fallback behavior and the presence of the obfuscation in the source code. I have no feedback to provide.

@cloudflare-workers-and-pages
Copy link
Copy Markdown

cloudflare-workers-and-pages Bot commented May 3, 2026

Deploying egg-v3 with  Cloudflare Pages  Cloudflare Pages

Latest commit: 597e4d9
Status: ✅  Deploy successful!
Preview URL: https://fc491c95.egg-v3.pages.dev
Branch Preview URL: https://agent-egg-dev-06640e7b.egg-v3.pages.dev

View logs

Copy link
Copy Markdown
Contributor

@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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/utils/test/bundle-import.test.ts`:
- Around line 75-79: The regex in the test "hides dynamic import fallback from
bundled expression transforms" is line-ending sensitive; update the second
assert.match that currently uses a literal '\n' to use '\r?\n' so it matches
both LF and CRLF checkouts—locate the test block, the 'source' variable and the
assert.match that checks /if \(_bundleModuleLoader\) \{\n\s+obj = await
nativeDynamicImport\(fileUrl\);/ and replace the '\n' with '\r?\n' to make the
pattern platform-agnostic.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c8570142-b272-48d9-ad91-419c1712cfbe

📥 Commits

Reviewing files that changed from the base of the PR and between 22fc588 and 5d79f2e.

📒 Files selected for processing (3)
  • packages/utils/src/import.ts
  • packages/utils/test/bundle-import.test.ts
  • packages/utils/test/fixtures/bundle-native-fallback/run.mjs

Comment thread packages/utils/test/bundle-import.test.ts Outdated
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Fixes bundled-runtime behavior in @eggjs/utils’s importModule() so that when a bundle module loader is installed but returns undefined (miss), the code reliably falls back to Node’s native dynamic import rather than a bundler-rewritten import path.

Changes:

  • Add an “opaque” native dynamic import helper (via new Function) and use it for ESM fallback when a bundle loader is present.
  • Add a fixture + spawned Node test to verify bundle-loader miss falls through to native dynamic import.
  • Add a source-shape guard test to prevent regressions from bundler expression rewrites.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
packages/utils/src/import.ts Uses an opaque native dynamic import fallback when a bundle loader is registered, preserving correct runtime behavior on bundle misses.
packages/utils/test/bundle-import.test.ts Adds an integration-style spawn test for the fallback and a source-shape assertion guarding against bundler rewrites.
packages/utils/test/fixtures/bundle-native-fallback/run.mjs New Node fixture that installs a miss-only bundle loader and exercises importModule() fallback behavior.

Comment thread packages/utils/test/bundle-import.test.ts Outdated
@killagu killagu force-pushed the agent/egg-dev/06640e7b branch 2 times, most recently from b238c93 to e522a08 Compare May 3, 2026 17:14
Copilot AI review requested due to automatic review settings May 3, 2026 17:14
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

Comment thread packages/utils/src/import.ts Outdated
@killagu killagu force-pushed the agent/egg-dev/06640e7b branch from e522a08 to 83c8d23 Compare May 3, 2026 17:55
Copy link
Copy Markdown
Contributor

@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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/utils/src/import.ts`:
- Around line 473-478: Move the V8 coverage directive to the if-statement itself
so the branch miss is suppressed: replace the inline comment inside the
true-branch with a branch-targeted directive on the `if (_bundleModuleLoader)`
line (use `/* v8 ignore if */`), leaving the dynamic import logic (`obj = await
getNativeDynamicImport()(fileUrl);` and the `else` path `obj = await
import(fileUrl);`) unchanged; ensure the directive sits immediately after `if
(_bundleModuleLoader)` so the coverage tool recognizes and ignores that branch.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6c02b2fd-60eb-44d6-90f9-b3db5dc46c6c

📥 Commits

Reviewing files that changed from the base of the PR and between e522a08 and 83c8d23.

📒 Files selected for processing (3)
  • packages/utils/src/import.ts
  • packages/utils/test/bundle-import.test.ts
  • packages/utils/test/fixtures/bundle-native-fallback/run.mjs
✅ Files skipped from review due to trivial changes (1)
  • packages/utils/test/fixtures/bundle-native-fallback/run.mjs

Comment thread packages/utils/src/import.ts
@killagu killagu force-pushed the agent/egg-dev/06640e7b branch from 83c8d23 to de8f064 Compare May 3, 2026 18:22
Copilot AI review requested due to automatic review settings May 3, 2026 18:22
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

Comment thread packages/utils/src/import.ts Outdated
@killagu killagu force-pushed the agent/egg-dev/06640e7b branch from de8f064 to 597e4d9 Compare May 3, 2026 18:38
@killagu killagu merged commit fffda63 into next May 5, 2026
26 checks passed
@killagu killagu deleted the agent/egg-dev/06640e7b branch May 5, 2026 06:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants