Skip to content

fix(bundler): resolve runtime app baseDir mappings#5920

Open
killagu wants to merge 6 commits intonextfrom
agent/egg-dev/4aefd865
Open

fix(bundler): resolve runtime app baseDir mappings#5920
killagu wants to merge 6 commits intonextfrom
agent/egg-dev/4aefd865

Conversation

@killagu
Copy link
Copy Markdown
Contributor

@killagu killagu commented May 3, 2026

Summary

  • Read bundle-manifest.json at worker runtime to distinguish the packaged output directory from the original app baseDir/framework.
  • Register bundled module aliases for relKey, original app absolute paths, output absolute paths, and manifest resolveCache request paths.
  • Start bundled workers with an explicit framework option while keeping startEgg imported from egg.

Tests

  • pnpm run typecheck (tools/egg-bundler)
  • pnpm run lint (tools/egg-bundler)
  • pnpm test (tools/egg-bundler)

Refs EGG-65.

Summary by CodeRabbit

  • Refactor

    • Resolve framework and app/output directories at runtime from the bundle manifest; normalize module map keys and register multiple path aliases for reliable cross-platform module resolution.
  • Tests

    • Updated expectations for runtime-derived values, expanded aliasing behavior, and the revised startup call shape.
  • Documentation

    • Bundle manifest is now documented as required runtime metadata that must accompany the worker; missing or malformed manifest causes startup failure.

Copilot AI review requested due to automatic review settings May 3, 2026 07:41
@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

Generated worker entries now compute __outputDir from process.argv[1], synchronously read bundle-manifest.json at startup to obtain __appBaseDir and __framework, root runtime createRequire at __appBaseDir, normalize and alias bundle-map keys for multiple path forms, update the global module loader lookup, and remove compile-time framework-specifier helpers. Tests and docs updated.

Changes

Worker Entry Runtime & Bundle Map

Layer / File(s) Summary
Runtime bootstrap / I/O
tools/egg-bundler/src/lib/EntryGenerator.ts
Generated worker imports startEgg from "egg", computes __outputDir from process.argv[1], reads/parses bundle-manifest.json, and sets __appBaseDir and __framework from that manifest.
External require wiring
tools/egg-bundler/src/lib/EntryGenerator.ts
Runtime createRequire is initialized from path.join(__appBaseDir, 'package.json') so runtime require resolution is rooted at the recovered app base dir.
Bundle map normalization & aliasing
tools/egg-bundler/src/lib/EntryGenerator.ts
Adds __toMapKey and __setBundleMapAlias; populates __BUNDLE_MAP by aliasing entries from __BUNDLE_MAP_REL and manifest resolveCache under rel, path.resolve(__appBaseDir, rel), and path.resolve(__outputDir, rel) keys.
Module loader lookup
tools/egg-bundler/src/lib/EntryGenerator.ts
Global loader (__EGG_BUNDLE_MODULE_LOADER__) resolves modules using __toMapKey(filepath) against __BUNDLE_MAP.
Manifest wiring / ManifestStore
tools/egg-bundler/src/lib/EntryGenerator.ts
ManifestStore.fromBundle(...) and related manifest wiring use __appBaseDir at runtime.
StartEgg invocation
tools/egg-bundler/src/lib/EntryGenerator.ts, tools/egg-bundler/test/EntryGenerator.test.ts
Worker calls startEgg({ baseDir: __appBaseDir, framework: __framework, mode: 'single' }); tests updated to assert this runtime-derived shape.
Cleanup (compile-time helpers removed)
tools/egg-bundler/src/lib/EntryGenerator.ts
Removed compile-time framework-specifier helpers (e.g., #toFrameworkImportSpecifier, related helpers).
Tests
tools/egg-bundler/test/EntryGenerator.test.ts
Assertions updated for __outputDir/__appBaseDir derivation, __framework from manifest, new startEgg call shape, and additional __setBundleMapAlias expectations (including resolveCache aliases).
Docs
tools/egg-bundler/docs/output-structure.md
bundle-manifest.json documented as runtime-consumed metadata (must be deployed with worker.js); running-the-bundle text updated to describe manifest-driven resolution and inlined bundle-map usage.

Sequence Diagram

sequenceDiagram
    participant Worker as Generated Worker Entry
    participant FS as File System
    participant ManifestStore as ManifestStore
    participant Loader as Bundle Module Loader
    participant Egg as startEgg()

    Worker->>FS: read "bundle-manifest.json"
    FS-->>Worker: manifest (baseDir, framework, resolveCache...)
    Worker->>Worker: set __outputDir from process.argv[1]\ncompute __appBaseDir and __framework
    Worker->>Loader: populate __BUNDLE_MAP\n__setBundleMapAlias(rel, app-resolved, output-resolved)
    Worker->>ManifestStore: ManifestStore.fromBundle(__appBaseDir)
    Worker->>Loader: register module loader (use __toMapKey lookups)
    Worker->>Egg: startEgg({ baseDir: __appBaseDir, framework: __framework, mode: 'single' })
    Egg-->>Worker: initialized
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly Related PRs

Suggested Reviewers

  • jerryliang64

Poem

🐇
I nibble manifests by moonlit code,
Map keys curled down every road,
BaseDir found, the framework wakes,
Loader springs for bundled crates,
Egg and I hop home with golden oaten loads.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly summarizes the main change: refactoring runtime module resolution to use bundle-manifest.json for baseDir/framework information and registering proper module aliases.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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/4aefd865

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.

@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: 9dbf101
Status: ✅  Deploy successful!
Preview URL: https://9e06f080.egg-cci.pages.dev
Branch Preview URL: https://agent-egg-dev-4aefd865.egg-cci.pages.dev

View logs

@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.04%. Comparing base (9ae1df0) to head (9dbf101).
⚠️ Report is 2 commits behind head on next.

Additional details and impacted files
@@           Coverage Diff           @@
##             next    #5920   +/-   ##
=======================================
  Coverage   85.04%   85.04%           
=======================================
  Files         667      667           
  Lines       19123    19123           
  Branches     3723     3723           
=======================================
  Hits        16263    16263           
  Misses       2467     2467           
  Partials      393      393           

☔ 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.

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 refactors the EntryGenerator to support runtime configuration via a bundle-manifest.json file, enabling dynamic resolution of the application base directory and framework. It also enhances the bundle mapping logic with path normalization and resolveCache alias support. Feedback focuses on improving the robustness of path resolution for __appBaseDir and __outputDir in the generated entry file to prevent issues in varied execution environments.

Comment thread tools/egg-bundler/src/lib/EntryGenerator.ts Outdated
Comment thread tools/egg-bundler/src/lib/EntryGenerator.ts Outdated
@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: 9dbf101
Status: ✅  Deploy successful!
Preview URL: https://15ac5804.egg-v3.pages.dev
Branch Preview URL: https://agent-egg-dev-4aefd865.egg-v3.pages.dev

View logs

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

This PR updates @eggjs/egg-bundler’s generated worker entry to correctly distinguish the bundle output directory from the original app baseDir/framework at runtime by reading bundle-manifest.json, and expands runtime module aliasing to cover more path forms used during manifest-backed resolution.

Changes:

  • Read bundle-manifest.json at worker runtime to derive __appBaseDir and __framework (while still importing startEgg from egg).
  • Expand bundle module map aliasing to include relKey, app absolute paths, output absolute paths, and manifest.resolveCache request aliases.
  • Update snapshots/tests to reflect the new generated worker output.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
tools/egg-bundler/src/lib/EntryGenerator.ts Generate worker entry that reads bundle-manifest.json, uses __appBaseDir/__framework, and registers additional bundle map aliases.
tools/egg-bundler/test/EntryGenerator.test.ts Adjust assertions and test cases to match the new generated worker runtime behavior and aliasing strategy.
tools/egg-bundler/test/snapshots/EntryGenerator.worker.canonical.snap Update canonical snapshot for the worker entry output.

Comment thread tools/egg-bundler/src/lib/EntryGenerator.ts Outdated
Comment thread tools/egg-bundler/src/lib/EntryGenerator.ts Outdated
Copilot AI review requested due to automatic review settings May 3, 2026 07:49
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 `@tools/egg-bundler/src/lib/EntryGenerator.ts`:
- Around line 227-238: The current __readBundleManifest function swallows all
errors reading/parsing bundle-manifest.json causing __bundleManifest,
__appBaseDir, and __framework to silently fall back and produce misleading
runtime failures; change __readBundleManifest to let failures surface (either
rethrow the error or log and abort startup) when fs.readFileSync or JSON.parse
fails, so that reading bundle-manifest.json throws on invalid/unreadable
content; ensure __bundleManifest is only assigned from this function when it
succeeds, and do not fallback to __outputDir or default framework values
silently.
🪄 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: e5d0a1d4-8cc4-421c-9ffb-d3193b0c32b3

📥 Commits

Reviewing files that changed from the base of the PR and between 3de9998 and 2bbd3ba.

⛔ Files ignored due to path filters (1)
  • tools/egg-bundler/test/__snapshots__/EntryGenerator.worker.canonical.snap is excluded by !**/*.snap
📒 Files selected for processing (2)
  • tools/egg-bundler/src/lib/EntryGenerator.ts
  • tools/egg-bundler/test/EntryGenerator.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • tools/egg-bundler/test/EntryGenerator.test.ts

Comment thread tools/egg-bundler/src/lib/EntryGenerator.ts Outdated
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.

🧹 Nitpick comments (1)
tools/egg-bundler/docs/output-structure.md (1)

45-47: ⚡ Quick win

Document fallback behavior when bundle-manifest.json is missing/invalid.

This section currently reads as a hard requirement, but runtime code falls back to defaults (baseDir = __outputDir, framework = compiled default) when manifest read/parse fails or fields are absent. Please add one sentence clarifying fallback + likely consequence (app may start with wrong baseDir mappings). Cross-file evidence: tools/egg-bundler/src/lib/EntryGenerator.ts Line 227-246 and Line 282-288.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tools/egg-bundler/docs/output-structure.md` around lines 45 - 47, Update the
docs to note that reading/parsing bundle-manifest.json is not fatal: when
Bundler/worker fails to read or parse the manifest or misses fields, the runtime
falls back to defaults (baseDir is set to __outputDir and framework is set to
the compiled default) — add one sentence stating this fallback behavior and the
likely consequence that the app may start with incorrect baseDir mappings or an
unexpected framework value; reference the relevant symbols bundle-manifest.json,
baseDir, framework, __outputDir and EntryGenerator.ts to locate the code path.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@tools/egg-bundler/docs/output-structure.md`:
- Around line 45-47: Update the docs to note that reading/parsing
bundle-manifest.json is not fatal: when Bundler/worker fails to read or parse
the manifest or misses fields, the runtime falls back to defaults (baseDir is
set to __outputDir and framework is set to the compiled default) — add one
sentence stating this fallback behavior and the likely consequence that the app
may start with incorrect baseDir mappings or an unexpected framework value;
reference the relevant symbols bundle-manifest.json, baseDir, framework,
__outputDir and EntryGenerator.ts to locate the code path.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7f3a3322-09d9-4ce2-ba9e-142e05dce580

📥 Commits

Reviewing files that changed from the base of the PR and between 2bbd3ba and 6cc283c.

⛔ Files ignored due to path filters (1)
  • tools/egg-bundler/test/__snapshots__/EntryGenerator.worker.canonical.snap is excluded by !**/*.snap
📒 Files selected for processing (2)
  • tools/egg-bundler/docs/output-structure.md
  • tools/egg-bundler/src/lib/EntryGenerator.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • tools/egg-bundler/src/lib/EntryGenerator.ts

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 4 out of 4 changed files in this pull request and generated 2 comments.

Comments suppressed due to low confidence (1)

tools/egg-bundler/docs/output-structure.md:56

  • The bundle-manifest.json example shows an absolute baseDir (e.g. /abs/path/to/app), but the worker now uses this value to compute __appBaseDir and pass it into startEgg. If the bundle is meant to be relocatable/self-contained under <outputDir>/, the docs should clarify whether baseDir is expected to be relative to <outputDir> (recommended) vs an absolute build-time path (in which case relocations require rewriting the manifest or keeping the original path layout).
A runtime metadata file produced by `Bundler`. The worker reads `baseDir` and
`framework` from this file during startup, so deployment must keep it next to
`worker.js`. The remaining fields are reference / debug metadata. Shape:

```json
{
  "version": 1,
  "generatedAt": "2026-04-11T00:00:00.000Z",
  "mode": "production",
  "baseDir": "/abs/path/to/app",
  "framework": "egg",
  "entries": [{ "name": "worker", "source": "/abs/path/to/app/.egg-bundle/entries/worker.entry.ts" }],

Comment thread tools/egg-bundler/src/lib/EntryGenerator.ts Outdated
Comment thread tools/egg-bundler/src/lib/EntryGenerator.ts
Copilot AI review requested due to automatic review settings May 3, 2026 08:05
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.

🧹 Nitpick comments (1)
tools/egg-bundler/src/lib/EntryGenerator.ts (1)

215-216: 💤 Low value

Minor: Inconsistent quote style in generated imports.

Line 215 uses single quotes while line 216 uses double quotes. This is cosmetic but could be unified for consistency.

 import { ManifestStore } from '@eggjs/core';
-import { startEgg } from "egg";
+import { startEgg } from 'egg';
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tools/egg-bundler/src/lib/EntryGenerator.ts` around lines 215 - 216, The two
import statements use inconsistent quote styles; update the import for startEgg
to match the project's single-quote style used by ManifestStore (i.e., change
the double quotes around "egg" to single quotes) so both imports use single
quotes; look for the import lines referencing ManifestStore and startEgg in
EntryGenerator (symbols: ManifestStore, startEgg) and make the quote style
consistent across them.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@tools/egg-bundler/src/lib/EntryGenerator.ts`:
- Around line 215-216: The two import statements use inconsistent quote styles;
update the import for startEgg to match the project's single-quote style used by
ManifestStore (i.e., change the double quotes around "egg" to single quotes) so
both imports use single quotes; look for the import lines referencing
ManifestStore and startEgg in EntryGenerator (symbols: ManifestStore, startEgg)
and make the quote style consistent across them.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2d49d52b-618f-4aed-a9e6-cc0b94bfec5d

📥 Commits

Reviewing files that changed from the base of the PR and between 6cc283c and 82c13b4.

⛔ Files ignored due to path filters (1)
  • tools/egg-bundler/test/__snapshots__/EntryGenerator.worker.canonical.snap is excluded by !**/*.snap
📒 Files selected for processing (3)
  • tools/egg-bundler/docs/output-structure.md
  • tools/egg-bundler/src/lib/EntryGenerator.ts
  • tools/egg-bundler/test/EntryGenerator.test.ts
✅ Files skipped from review due to trivial changes (1)
  • tools/egg-bundler/docs/output-structure.md

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 4 out of 4 changed files in this pull request and generated 1 comment.

Comments suppressed due to low confidence (1)

tools/egg-bundler/test/EntryGenerator.test.ts:290

  • This test passes framework into new EntryGenerator(...), but EntryGenerator no longer uses that option; the assertions only check that the worker reads __framework from bundle-manifest.json at runtime. Keeping the unused option in the unit test setup is misleading. Prefer removing framework here (and validating bundle-manifest.json.framework via Bundler/integration tests instead).
  it('reads a custom framework specifier from bundle-manifest.json at runtime', async () => {
    const gen = new EntryGenerator({
      baseDir: tmpDir,
      framework: '@my-org/framework',
      manifestLoader: createFakeLoader(makeManifest()),
    });

Comment thread tools/egg-bundler/src/lib/EntryGenerator.ts
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