Skip to content

perf: install global state lazily so executeAsync tree-shakes - #157

Open
danielroe wants to merge 2 commits into
unjs:mainfrom
danielroe:perf/lazy-globals
Open

danielroe wants to merge 2 commits into
unjs:mainfrom
danielroe:perf/lazy-globals

Conversation

@danielroe

@danielroe danielroe commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

the change to globalThis currently means it's impossible tree-shake executeAsync

that might be as designed/acceptable, but I hit this in nuxt because we previously imported unctx in the browser and it meant nothing could be tree shaken even if executeAsync was unused...

Summary by CodeRabbit

  • Performance

    • Improved lazy initialization of asynchronous handling and default namespaces.
    • Reduced unnecessary runtime setup for consumers that use only asynchronous execution.
  • Behavior

    • Default context namespaces are now created when first accessed while preserving existing values and reuse.
  • Tests

    • Added coverage verifying optimized builds retain asynchronous execution while excluding unused context-related code.
    • Added coverage for creating, storing, and retrieving values through the default namespace.

@coderabbitai

coderabbitai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 825b956c-1bf9-46dc-ad52-420d2ebca39f
📥 Commits

Reviewing files that changed from the base of the PR and between 14eebe4 and 7360908.

📒 Files selected for processing: 1
  • test/index.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 2 remain after this review.

📝 Walkthrough

The module now lazily initializes and caches the default namespace and async handlers. Tests verify first-use context registration and tree shaking for an executeAsync-only bundle.

Changes: Lazy initialization

Layer / File(s) Summary
Lazy storage and consumers
src/index.ts
The default namespace and async handlers are initialized on first use and reuse existing global values. callAsync and executeAsync use the async-handler accessor.
Behavior and bundle validation
test/index.test.ts, test/treeshake.test.ts
Tests verify namespace installation, keyed context access, and removal of unused context machinery from an executeAsync-only bundle.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Refactor

Merge Risk: ⚪ Minimal · up to 73609

No merge-blocking issue was identified.

Architecture risk: 🔵 Low · up to 73609

The change affects 2 systems.

Changed systems: test, src

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — test (service) was modified; 2 changed files map to changed impact.
  • observed — src (service) was modified; 1 changed file maps to changed impact.

Before / after behavior

  • observed — Modified behavior in src/index.ts: callAsync now obtains its handler set through _getAsyncHandlers() before registering the leave handler.
  • observed — Modified behavior in src/index.ts: Default namespace creation is now lazy: _getDefaultNamespace() caches and reuses the global namespace, and exported defaultNamespace.get delegates to it instead of eagerly creating the namespace during module initialization.
  • observed — Modified behavior in src/index.ts: Async handler storage is now lazily initialized through _getAsyncHandlers(), which caches or reuses the global handler set; executeAsync iterates over that accessor rather than a module-initialized set.
  • observed — Modified behavior in test/treeshake.test.ts: Added a Vitest tree-shaking test that builds an entry exporting only executeAsync and asserts context machinery is removed from the minified ESM output.
Pre-merge checks: Passed 4 · Failed 1

Failed 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%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed 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 clearly and concisely describes the main change: lazy global state initialization to enable tree-shaking for executeAsync.
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.
  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Some tools did not complete. Review the errors below.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install timed out. The project may have too many dependencies for the sandbox.

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.

@codecov

codecov Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.90%. Comparing base (6586739) to head (7360908).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #157      +/-   ##
==========================================
+ Coverage   93.28%   94.90%   +1.62%     
==========================================
  Files           3        3              
  Lines         268      275       +7     
  Branches      100      100              
==========================================
+ Hits          250      261      +11     
+ Misses         18       14       -4     

☔ View full report in Codecov by Harness.
📢 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.

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.

1 participant