Skip to content

refactor(development): inline loader trace template as string constant - #5869

Merged
killagu merged 4 commits into
eggjs:nextfrom
killagu:split/03-development-inline-template
Apr 26, 2026
Merged

refactor(development): inline loader trace template as string constant#5869
killagu merged 4 commits into
eggjs:nextfrom
killagu:split/03-development-inline-template

Conversation

@killagu

@killagu killagu commented Apr 14, 2026

Copy link
Copy Markdown
Contributor

Summary

Inlines the loader trace HTML template into `plugins/development/src/app/middleware/loader_trace_template.ts` as a string constant. Removes the runtime fs read in `egg_loader_trace.ts` middleware.

Why

This is batch 1, part of a 19-PR split of #5863 (the egg-bundler PR). #5863 is kept open as a tracking reference. This PR is independent of the other batch-1 PRs.

Same motivation as the parallel onerror inline change: turbopack and other static bundlers cannot follow `import.meta.dirname + readFileSync` lookups to plugin template files. Inlining the template as a string constant lets the plugin be statically bundled.

Pure refactor — runtime behavior is identical.

Test plan

  • `pnpm --filter=@eggjs/development test` — 12 passed + 5 skipped (1 unrelated pre-existing watcher-timing flake when full suite runs in parallel; passes in isolation)
  • typecheck clean

Stack context

Other batch-1 PRs (independent, can land in any order):

  • `feat(utils): add setBundleModuleLoader runtime hook`
  • `refactor(onerror): inline error page template as string constant`
  • `refactor(watcher): use direct class imports for event sources`

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Loader trace endpoint now escapes HTML/JS characters in timing data to prevent injection in the inline trace script.
  • Performance

    • Loader trace is served from a static in-memory template, reducing per-request file reads and improving response efficiency.
  • Tests

    • Added integration test validating safe serialization, escaping, and successful round-trip parsing of loader trace data.

Copilot AI review requested due to automatic review settings April 14, 2026 03:59
@coderabbitai

coderabbitai Bot commented Apr 14, 2026

Copy link
Copy Markdown
Contributor

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

The loader-trace endpoint now serves a pre-imported HTML template and injects timing data via a new serializeLoaderTraceData function that JSON-stringifies and escapes <, >, &, U+2028, U+2029 before replacing the template placeholder. A test verifies malicious payloads are safely escaped.

Changes

Cohort / File(s) Summary
Loader Trace Middleware & Template
plugins/development/src/app/middleware/egg_loader_trace.ts, plugins/development/src/app/middleware/loader-trace-template.ts
Middleware switched from reading loader_trace.html at runtime to using exported LOADER_TRACE_TEMPLATE. Introduced serializeLoaderTraceData to JSON-stringify and escape HTML/JS-sensitive characters. Template script binding changed from var to const while keeping {{placeholder}}.
Tests for Escaping / Safety
plugins/development/test/timing.test.ts
Added integration test that writes a timing fixture with a script-like payload, requests /__loader_trace__, asserts the inline script does not contain raw </script> sequences, parses the injected JSON, validates payload retention, and cleans up the fixture file.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • jerryliang64

Poem

🐰 I tucked the template in a burrow bright,
I wrapped the data snug and safe at night,
With escaped hops and careful little tracks,
No stray </script> will burst my map of snacks,
Carrots, code, and cozy traces — delight!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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 accurately describes the primary change: inlining the loader trace template as a string constant instead of reading from disk. It directly aligns with the main refactoring objective.
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

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.

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

Copy link
Copy Markdown
Contributor

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 egg_loader_trace middleware by inlining the HTML visualization template into a new TypeScript module, which eliminates the need for runtime file system reads. The review identified a potential XSS vulnerability where data is injected into the script block, suggesting character escaping as a fix. Additionally, it is recommended to remove the new internal template module from the package exports to keep the public API clean and to update the template's JavaScript to use const instead of var for better practice.

Comment thread plugins/development/src/app/middleware/egg_loader_trace.ts Outdated
Comment thread plugins/development/package.json Outdated
Comment thread plugins/development/package.json Outdated
Comment thread plugins/development/src/app/middleware/loader_trace_template.ts Outdated
@codecov

codecov Bot commented Apr 14, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.49%. Comparing base (4a345cc) to head (1e74e27).
⚠️ Report is 1 commits behind head on next.

Additional details and impacted files
@@           Coverage Diff           @@
##             next    #5869   +/-   ##
=======================================
  Coverage   85.48%   85.49%           
=======================================
  Files         660      661    +1     
  Lines       18828    18830    +2     
  Branches     3646     3646           
=======================================
+ Hits        16096    16099    +3     
+ Misses       2361     2360    -1     
  Partials      371      371           

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (1)
plugins/development/src/app/middleware/loader_trace_template.ts (1)

1-2: Align file and exported variable naming with repo conventions.

Please rename the file to hyphen-case and the exported constant to camelCase to match project standards (and then update import/export paths accordingly).

♻️ Suggested rename pattern
-/** Loader trace visualization template - inlined from loader_trace.html */
-export const LOADER_TRACE_TEMPLATE = `<!doctype html>
+/** Loader trace visualization template - inlined from loader_trace.html */
+export const loaderTraceTemplate = `<!doctype html>

And update references, e.g.:

-import { LOADER_TRACE_TEMPLATE } from './loader_trace_template.ts';
+import { loaderTraceTemplate } from './loader-trace-template.ts';

As per coding guidelines, "{packages,plugins}/**/*.{ts,tsx,js,mjs}: Name files in lowercase with hyphens" and "**/*.{ts,tsx}: Name functions and variables in camelCase".

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

In `@plugins/development/src/app/middleware/loader_trace_template.ts` around lines
1 - 2, The file name and exported constant violate naming conventions: rename
the file from loader_trace_template.ts to loader-trace-template.ts (hyphen-case)
and rename the exported constant LOADER_TRACE_TEMPLATE to loaderTraceTemplate
(camelCase); update all import/export sites that reference
loader_trace_template.ts and LOADER_TRACE_TEMPLATE to use the new file name and
new symbol (loader-trace-template and loaderTraceTemplate) so builds and imports
resolve correctly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@plugins/development/src/app/middleware/egg_loader_trace.ts`:
- Line 16: The current insertion uses raw JSON.stringify(data) into
LOADER_TRACE_TEMPLATE which can allow string fields like </script> to break out;
update the assignment that sets ctx.body (the call using
LOADER_TRACE_TEMPLATE.replace(...)) to first harden the serialization by
escaping it via the framework helper (e.g. use
ctx.helper.escape(JSON.stringify(data))) or equivalent escaping that neutralizes
</script> and other HTML-sensitive characters, then call replace with that
escaped string so the inline script cannot be broken out.

---

Nitpick comments:
In `@plugins/development/src/app/middleware/loader_trace_template.ts`:
- Around line 1-2: The file name and exported constant violate naming
conventions: rename the file from loader_trace_template.ts to
loader-trace-template.ts (hyphen-case) and rename the exported constant
LOADER_TRACE_TEMPLATE to loaderTraceTemplate (camelCase); update all
import/export sites that reference loader_trace_template.ts and
LOADER_TRACE_TEMPLATE to use the new file name and new symbol
(loader-trace-template and loaderTraceTemplate) so builds and imports resolve
correctly.
🪄 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: 79bfc717-0fa3-4976-b5f8-264fd4b68b87

📥 Commits

Reviewing files that changed from the base of the PR and between 490f849 and f5d9b74.

📒 Files selected for processing (3)
  • plugins/development/package.json
  • plugins/development/src/app/middleware/egg_loader_trace.ts
  • plugins/development/src/app/middleware/loader_trace_template.ts

Comment thread plugins/development/src/app/middleware/egg_loader_trace.ts Outdated

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

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 refactors @eggjs/development’s loader-trace middleware to inline the HTML template as a TypeScript string constant, removing the runtime filesystem read so the plugin can be statically bundled (e.g., by turbopack).

Changes:

  • Added LOADER_TRACE_TEMPLATE constant containing the inlined loader-trace HTML.
  • Updated egg_loader_trace middleware to use the inlined template instead of reading loader_trace.html at runtime.
  • Exposed the new template module via package.json subpath exports.

Reviewed changes

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

File Description
plugins/development/src/app/middleware/loader_trace_template.ts Introduces the inlined HTML template as an exported string constant.
plugins/development/src/app/middleware/egg_loader_trace.ts Switches middleware rendering from fs.readFile() to the inlined template constant.
plugins/development/package.json Adds a new exported subpath for the template module (src + dist).

Comment thread plugins/development/src/app/middleware/loader_trace_template.ts Outdated
Comment thread plugins/development/package.json
@killagu
killagu force-pushed the split/03-development-inline-template branch from f5d9b74 to d60ef6e Compare April 21, 2026 15:17

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (1)
plugins/development/src/app/middleware/loader_trace_template.ts (1)

1-1: Filename uses underscores instead of hyphens.

Per the repo convention, files under plugins/** should be named in lowercase with hyphens (e.g. loader-trace-template.ts). That said, the sibling egg_loader_trace.ts already uses snake_case, so feel free to defer this if you prefer consistency with the surrounding middleware files or address it in a broader rename.

As per coding guidelines: "Name files in lowercase with hyphens (e.g. loader-context.ts)".

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

In `@plugins/development/src/app/middleware/loader_trace_template.ts` at line 1,
The file name uses underscores instead of the repo convention of lowercase
hyphens; rename the module from loader_trace_template.ts to
loader-trace-template.ts and update all import sites that reference
loader_trace_template (and any sibling references like egg_loader_trace.ts) to
the new hyphenated filename so module resolution continues to work; ensure
export names inside the file remain unchanged and run the test/build to catch
any missed imports.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@plugins/development/src/app/middleware/loader_trace_template.ts`:
- Line 11: The template insertion currently uses
LOADER_TRACE_TEMPLATE.replace('{{placeholder}}', JSON.stringify(data)) which
lets `$` sequences in the JSON be interpreted as replacement patterns; change
that call to use a replacer function instead, e.g.
LOADER_TRACE_TEMPLATE.replace('{{placeholder}}', () => JSON.stringify(data)), so
the payload is inserted literally and any `$` in trace entry names (module
ids/paths) won't be misinterpreted by String.prototype.replace.

---

Nitpick comments:
In `@plugins/development/src/app/middleware/loader_trace_template.ts`:
- Line 1: The file name uses underscores instead of the repo convention of
lowercase hyphens; rename the module from loader_trace_template.ts to
loader-trace-template.ts and update all import sites that reference
loader_trace_template (and any sibling references like egg_loader_trace.ts) to
the new hyphenated filename so module resolution continues to work; ensure
export names inside the file remain unchanged and run the test/build to catch
any missed imports.
🪄 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: 8b83133b-b711-4901-a551-6101a072ebf1

📥 Commits

Reviewing files that changed from the base of the PR and between f5d9b74 and d60ef6e.

📒 Files selected for processing (3)
  • plugins/development/package.json
  • plugins/development/src/app/middleware/egg_loader_trace.ts
  • plugins/development/src/app/middleware/loader_trace_template.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • plugins/development/src/app/middleware/egg_loader_trace.ts
  • plugins/development/package.json

Comment thread plugins/development/src/app/middleware/loader_trace_template.ts Outdated
Copilot AI review requested due to automatic review settings April 25, 2026 12:13

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 `@plugins/development/test/timing.test.ts`:
- Around line 44-68: The test 'should safely serialize trace data into inline
script' writes agent_timing_safe_serialize.json into app.config.rundir but never
removes it; wrap the test body in a try-finally (around the fs.writeFile,
request, and assertions) and in the finally remove the fixture (use fs.unlink or
fs.unlinkSync) targeting the file named "agent_timing_safe_serialize.json" in
app.config.rundir so subsequent tests aren't contaminated; ensure the file
removal runs regardless of test outcome and handle missing-file errors 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: 11e78b26-f7c8-4b90-98dd-6e9cf25aadc9

📥 Commits

Reviewing files that changed from the base of the PR and between d60ef6e and 120e62c.

📒 Files selected for processing (3)
  • plugins/development/src/app/middleware/egg_loader_trace.ts
  • plugins/development/src/app/middleware/loader-trace-template.ts
  • plugins/development/test/timing.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • plugins/development/src/app/middleware/egg_loader_trace.ts

Comment thread plugins/development/test/timing.test.ts

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

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 refactors the @eggjs/development loader-trace middleware to inline the HTML template as a TypeScript string constant, removing the runtime filesystem read so the plugin can be bundled by static bundlers (e.g. turbopack).

Changes:

  • Inline loader trace HTML into LOADER_TRACE_TEMPLATE and import it from the middleware.
  • Remove readFile of the template at runtime and instead replace a placeholder in the inlined string.
  • Add a test to ensure trace JSON is safely serialized for embedding into an inline <script>.

Reviewed changes

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

File Description
plugins/development/src/app/middleware/loader-trace-template.ts Adds an inlined HTML template constant for loader trace rendering.
plugins/development/src/app/middleware/egg_loader_trace.ts Switches middleware to use the inlined template and adds safe JSON serialization for inline script embedding.
plugins/development/test/timing.test.ts Adds coverage for safe serialization when trace data contains </script>-style payloads.
Comments suppressed due to low confidence (1)

plugins/development/src/app/middleware/loader-trace-template.ts:2

  • This file uses kebab-case (loader-trace-template.ts), but middleware modules in this repo/plugins are typically named with snake_case (e.g. packages/egg/src/app/middleware/override_method.ts, plugins/mock/src/app/middleware/cluster_app_mock.ts) and this directory already has egg_loader_trace.ts. Consider renaming this file to loader_trace_template.ts (and updating the import) to match established conventions and avoid inconsistent paths.

Comment thread plugins/development/test/timing.test.ts Outdated
Comment thread plugins/development/test/timing.test.ts Outdated
killagu and others added 3 commits April 26, 2026 09:17
Inline the loader trace visualization HTML as a string constant in
src/app/middleware/loader_trace_template.ts so the plugin can be
statically bundled by turbopack. Previously the template was read
from disk via `import.meta.dirname + fs.readFile`, which breaks when
modules are embedded in a single bundled chunk.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings April 26, 2026 01:20
@killagu
killagu force-pushed the split/03-development-inline-template branch from a718a43 to f4ac1b7 Compare April 26, 2026 01:20

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

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 refactors the @eggjs/development loader-trace middleware to be friendlier to static bundlers (e.g. turbopack) by inlining the HTML template into a TypeScript string constant and removing runtime filesystem reads. It also adds safe serialization when embedding trace data into an inline <script> and introduces a regression test for that behavior.

Changes:

  • Inline loader trace HTML into LOADER_TRACE_TEMPLATE (TypeScript constant) instead of reading an external template file at request time.
  • Add serializeLoaderTraceData() to safely embed JSON into an inline script and update middleware to use it.
  • Add a test to validate escaping/round-trip parsing of potentially hostile trace payloads.

Reviewed changes

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

File Description
plugins/development/test/timing.test.ts Adds a test ensuring trace data is safely serialized into the inline script and still parses back correctly.
plugins/development/src/app/middleware/loader-trace-template.ts Introduces the inlined HTML template as a exported string constant.
plugins/development/src/app/middleware/egg_loader_trace.ts Switches from runtime template file reads to the inlined constant and adds safe JSON serialization for script embedding.
Comments suppressed due to low confidence (1)

plugins/development/src/app/middleware/loader-trace-template.ts:2

  • PR description references plugins/development/src/app/middleware/loader_trace_template.ts, but the actual inlined template module in this change is loader-trace-template.ts. Please align the description (or the filename) so future readers can find the file quickly.

Comment thread plugins/development/src/app/middleware/egg_loader_trace.ts Outdated
@killagu
killagu merged commit 7b8a664 into eggjs:next Apr 26, 2026
21 checks passed
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