Skip to content

Latest commit

 

History

History
425 lines (311 loc) · 22.2 KB

BUNDLING.md

File metadata and controls

425 lines (311 loc) · 22.2 KB

Core Package Bundling Architecture

This document explains how @voidzero-dev/vite-plus-core bundles multiple upstream projects into a single unified package.

Overview

The core package uses a multi-project bundling strategy that combines 4 upstream projects:

Project Source Location Purpose
@rolldown/pluginutils rolldown/packages/rolldown/node_modules/@rolldown/pluginutils Rolldown plugin utilities
rolldown rolldown/packages/rolldown Rolldown bundler
vite vite/packages/vite Vite v8 beta
tsdown node_modules/tsdown TypeScript build tool

This approach enables users to access Vite, Rolldown, and related tools through a single package with consistent module specifier rewrites.


Build Steps

Vite Source Preparation

Before core bundling, brand-vite.ts applies branding and the patch-vite-config.ts resolver patch to the vendored Vite source. sync-remote runs this preparation. CI also applies it after checking out upstream sources.

Regular pnpm build runs use the prepared sources. If the patch code changes after synchronization, run pnpm exec tool brand-vite once, then pnpm build to regenerate Vite types and rebuild the packages.

The resolver patch adds an optional internal eighth argument to resolveConfig. The resolveConfigFromFile(configFile, options?) helper exported by vite-plus passes a base directory through a private type bridge. By default, this base is the config file's parent directory. With an absolute configFile, default resolution of the initial root from the config file is independent of process.cwd(). Callers can pass { rootBase: projectRoot } to use a different project directory, including when the config is in a subdirectory. Relative configFile and explicit rootBase paths resolve from process.cwd(); the helper does not change the process cwd.

After a config file loads, an unset or relative root resolves from the selected base, before plugin apply and config hooks. Absolute roots are preserved, and an inline root retains priority. Plugin hooks can later change root using Vite's normal semantics. For example, a relative root returned by a config hook resolves from process.cwd(). Vite still handles config loading, environment initialization, configuration metadata, and plugin hooks.

The helper's default does not change ordinary resolveConfig calls, which retain Vite's cwd-based root resolution. Existing CLI callers keep their inline root: cwd, including when vp pack finds a parent config. Adopting the new helper is a separate integration choice for callers such as Oxlint and Oxfmt; it is not restricted to LSP.

build.ts calls assertViteConfigPatched() before any bundling starts. It rejects missing, changed, duplicate, or partially applied patch anchors. When the Vite pin changes, review the patch against the new source. The guard validates src/node/config.ts; it does not check whether generated type declarations are current.

The build process executes 5 steps in sequence:

Step 1: Bundle Rolldown Pluginutils (bundleRolldownPluginutils)

Action: Copies pre-built dist directory.

await cp(join(rolldownPluginUtilsDir, 'dist'), join(projectDir, 'dist', 'pluginutils'), {
  recursive: true,
});

Input: rolldown/packages/rolldown/node_modules/@rolldown/pluginutils/dist/ Output: dist/pluginutils/

Step 2: Bundle Rolldown (bundleRolldown)

Action: Copies dist directory and rewrites module specifiers.

Transformations:

  • @rolldown/pluginutils → @voidzero-dev/vite-plus-core/rolldown/pluginutils
  • rolldown/* → @voidzero-dev/vite-plus-core/rolldown/*
  • Replace the WebContainer fallback's rolldown/package.json lookup with the bundled Rolldown version. The WASM download must use that version, not the core package version.
  • In release builds: supported @rolldown/binding-* → @voidzero-dev/vite-plus-*

Input: rolldown/packages/rolldown/dist/ Output: dist/rolldown/

Step 3: Build Vite (buildVite)

Action: Full Rolldown build with custom transforms.

This is the most complex step, using the upstream vite-rolldown.config with modifications:

  1. Filter externals - Bundles picomatch, tinyglobby, fdir, rolldown, yaml instead of keeping them external
  2. Add RewriteImportsPlugin - Rewrites vite/rolldown imports at build time
  3. Rewrite static paths - Fixes VITE_PACKAGE_DIR, CLIENT_ENTRY, BUNDLED_DEV_CLIENT_ENTRY, ENV_ENTRY constants
  4. Copy additional files - misc/, .d.ts files, types/, client.d.ts
  5. Copy the bin script - bin/vite.js, with its CLI import pointed at ../node/cli.js. vp dev, vp build, and vp preview start through it, as vite does, so the startup time (ready in N ms), --debug, --filter, --profile, and Node's compile cache work

Input: vite/packages/vite/ Output: dist/vite/

Step 4: Bundle Tsdown (bundleTsdown)

Action: Re-bundles tsdown with CJS dependency handling.

Process:

  1. Bundle tsdown/dist/run.mjs and tsdown/dist/index.mjs using Rolldown
  2. Detect third-party CJS modules using find-create-require.ts
  3. Bundle detected CJS dependencies using build-cjs-deps.ts
  4. Bundle type declarations using rolldown-plugin-dts

Input: node_modules/tsdown/dist/ Output: dist/tsdown/

Step 5: Merge Package.json (mergePackageJson)

Action: Merges metadata from upstream packages and records bundled versions.

Updates:

  • peerDependencies - Merged from rolldown-plugin-dts, tsdown and vite (minus bundled packages)
  • peerDependenciesMeta - Merged from rolldown-plugin-dts, tsdown and vite (minus bundled packages)
  • bundledVersions - Records vite, rolldown, and tsdown versions

Module Specifier Rewriting System

The build uses two complementary rewriting mechanisms:

Build-Time Rewriting (RewriteImportsPlugin)

Located in build-support/rewrite-imports.ts, this Rolldown plugin rewrites imports during bundling:

export const RewriteImportsPlugin: Plugin = {
  name: 'rewrite-imports-for-vite-plus',
  resolveId: {
    order: 'pre',
    handler(id: string) {
      if (id.startsWith('vite/')) {
        return { id: id.replace(/^vite\//, `${pkgJson.name}/`), external: true };
      }
      if (id === 'rolldown') {
        return { id: `${pkgJson.name}/rolldown`, external: true };
      }
      if (id.startsWith('rolldown/')) {
        return { id: id.replace(/^rolldown\//, `${pkgJson.name}/rolldown/`), external: true };
      }
    },
  },
};

Post-Build Rewriting (AST-grep)

Located in build-support/rewrite-module-specifiers.ts, this utility rewrites specifiers in already-built files using AST-grep:

Original Import Rewritten Import
vite @voidzero-dev/vite-plus-core
vite/* @voidzero-dev/vite-plus-core/*
rolldown @voidzero-dev/vite-plus-core/rolldown
rolldown/* @voidzero-dev/vite-plus-core/rolldown/*
@rolldown/pluginutils @voidzero-dev/vite-plus-core/rolldown/pluginutils
@rolldown/pluginutils/* @voidzero-dev/vite-plus-core/rolldown/pluginutils/*

Detecting Missed Rewrites

__tests__/build-artifacts.spec.ts snapshots the remaining bare rolldown and @rolldown/pluginutils names in all built JavaScript and declarations. It parses string literals and template literals, then records references to constants and their aliases. This includes package names passed to require.resolve() or import.meta.resolve(), which import-only checks miss.

The snapshot allows CLI branding, embedded package metadata, and the browser runtime import that Vite rewrites before serving. Review new entries when upstream code changes; do not accept unresolved Node package lookups. Dynamically constructed names can escape static checks, so the installed-package bundled dev snapshots also verify runtime resolution without a separate Rolldown installation.

Native @rolldown/binding-* references have separate rewrite checks, described below.

The rolldown_webcontainer_fallback CLI snapshot executes the packed binding loader in a simulated WebContainer. It checks fresh and cached WASM bindings without a standalone rolldown package. The fixture uses real Node metadata resolution and a fake installer, and asserts that both paths use the bundled Rolldown version.

Release Build: Native Binding Rewriting

During release builds (RELEASE_BUILD=1), bundleRolldown() rewrites Rolldown's native binding requires through build-support/rewrite-rolldown-binding.ts. For every platform in the CLI's napi.targets (mapped to napi platform suffixes with parseTriple), the loader's @rolldown/binding-<suffix> requires become @voidzero-dev/vite-plus-<suffix>, and that branch's version guard switches from the Rolldown version to the CLI version, which is what the Vite+ platform packages are published as.

Platform-specific binding rewrites, one per napi.targets entry in packages/cli/package.json (see the target table in CLI Package Bundling), for example:

Original Import Rewritten Import
@rolldown/binding-darwin-arm64 @voidzero-dev/vite-plus-darwin-arm64
@rolldown/binding-linux-x64-musl @voidzero-dev/vite-plus-linux-x64-musl

Specifiers for platforms Vite+ does not ship (android, freebsd, the wasm32-wasi fallback, darwin-universal, ...) stay on @rolldown/binding-* and keep their upstream version guards. The build fails if the rewritten specifier and guard counts diverge from the napi-rs loader shape, so a loader format change cannot ship a partial rewrite.

Why this matters:

  1. Self-contained distribution - Users don't need to install separate @rolldown/binding-* packages
  2. Declared dependency graph - Core resolves the binding through its own optionalDependencies (injected during publish by packages/cli/publish-native-addons.ts), so pnpm's global virtual store and Yarn PnP work without hidden hoisting, and core no longer requires back into vite-plus
  3. Version alignment - Each rewritten branch's guard checks the platform package version against the CLI version, which the platform packages use. The core version differs (see Core Version)

Resolution chain:

User code imports '@voidzero-dev/vite-plus-core/rolldown'
  → dist/rolldown/index.mjs
    → requires '@voidzero-dev/vite-plus-<platform>'
      (rewritten from '@rolldown/binding-<platform>')
      → vite-plus.<platform>.node (contains rolldown_binding)

See CLI Package Bundling for details on how the CLI compiles and publishes the platform packages, and rfcs/core-binding-resolution.md for the design.


CJS Dependency Handling

Tsdown uses createRequire() to load some CommonJS dependencies. These are detected and bundled specially:

Detection (find-create-require.ts)

Uses oxc-parser to find patterns like:

// Pattern 1: Static import
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
require('some-cjs-package');

// Pattern 2: Global module
const require = globalThis.process.getBuiltinModule('module').createRequire(import.meta.url);
require('some-cjs-package');

Bundling (build-cjs-deps.ts)

Creates CJS entry files and bundles them with Rolldown:

// Creates: npm_entry_some_cjs_package.cjs
module.exports = require('some-cjs-package');

The original require("some-cjs-package") calls are rewritten to require("./npm_entry_some_cjs_package.cjs").


Output Structure

dist/
├── pluginutils/           # @rolldown/pluginutils
│   ├── index.js
│   ├── index.d.ts
│   └── filter/
├── rolldown/              # Rolldown bundler
│   ├── index.mjs
│   ├── index.d.mts
│   ├── config.mjs
│   ├── experimental-index.mjs
│   ├── filter-index.mjs
│   ├── parse-ast-index.mjs
│   ├── plugins-index.mjs
│   └── ...
├── vite/                  # Vite
│   ├── bin/
│   │   └── vite.js        # Entry for vp dev/build/preview
│   ├── node/
│   │   ├── index.js
│   │   ├── index.d.ts
│   │   ├── internal.js
│   │   ├── module-runner.js
│   │   └── chunks/
│   ├── client/
│   │   ├── bundledDevClient.mjs
│   │   ├── client.mjs
│   │   └── env.mjs
│   ├── misc/
│   ├── types/
│   └── client.d.ts
└── tsdown/                # TypeScript build tool
    ├── index.js
    ├── index-types.d.ts
    ├── run.js
    └── npm_entry_*.cjs    # Bundled CJS deps

Package Exports

Export Path Points To Description
. ./dist/vite/node/index.js Vite main entry
./client types: ./dist/vite/client.d.ts Client ambient types
./dist/client/* ./dist/vite/client/* Client runtime files
./internal ./dist/vite/node/internal.js Internal Vite APIs
./lib ./dist/tsdown/index.js Tsdown library
./module-runner ./dist/vite/node/module-runner.js Vite module runner
./rolldown ./dist/rolldown/index.mjs Rolldown main entry
./rolldown/config ./dist/rolldown/config.mjs Rolldown config helpers
./rolldown/experimental ./dist/rolldown/experimental-index.mjs Experimental features
./rolldown/filter ./dist/rolldown/filter-index.mjs Filter utilities
./rolldown/parseAst ./dist/rolldown/parse-ast-index.mjs AST parsing
./rolldown/plugins ./dist/rolldown/plugins-index.mjs Built-in plugins
./rolldown/pluginutils ./dist/pluginutils/index.js Plugin utilities
./rolldown/pluginutils/filter ./dist/pluginutils/filter/index.js Filter utilities
./types/* ./dist/vite/types/* Type definitions

Source Directories

Upstream Project Source Location Relation
@rolldown/pluginutils ../../rolldown/packages/rolldown/node_modules/@rolldown/pluginutils npm dependency
rolldown ../../rolldown/packages/rolldown Git submodule
vite ../../vite/packages/vite Git submodule
tsdown node_modules/tsdown npm dependency

Build Dependencies

Package Purpose
rolldown Bundler for building vite and tsdown
rolldown-plugin-dts TypeScript declaration bundling
@ast-grep/napi Post-build module specifier rewriting
oxc-parser CJS require detection in tsdown
oxfmt Code formatting for package.json
tinyglobby File globbing for copying files

Maintenance: Updating Bundled Versions

Updating Vite

  1. Update the Vite pin in packages/tools/.upstream-versions.json and review the resolver patch against the new source
  2. Follow the upstream sync and build instructions to prepare the source, regenerate Vite types, and rebuild the packages
  3. Verify bundledVersions.vite in package.json is updated
  4. Set version in package.json to the encoded version for the new Vite version, for example 8.4.2000 for Vite 8.4.2 (see Core Version). The upgrade-deps workflow does this step automatically
  5. Test with pnpm test

Updating Rolldown

  1. Update the rolldown git submodule to the new version
  2. Run pnpm -C packages/core build
  3. Verify bundledVersions.rolldown in package.json is updated
  4. Test with pnpm test

Updating Tsdown

  1. Update tsdown version in devDependencies
  2. Run pnpm install
  3. Run pnpm -C packages/core build
  4. Check for new CJS dependencies (build will detect them automatically)
  5. Verify bundledVersions.tsdown in package.json is updated
  6. Test with pnpm test

Build Commands

These direct core builds require prepared Vite sources and current Vite types. The standard repository build regenerates Vite types before building core. For a direct core build after source changes, run pnpm --filter vite build-types first.

# Build the core package
pnpm -C packages/core build

# Release build (rewrites supported @rolldown/binding-* to @voidzero-dev/vite-plus-*)
RELEASE_BUILD=1 pnpm -C packages/core build

Technical Reference

Build Flow

   assertViteConfigPatched()      Validate prepared Vite source before bundling
1. bundleRolldownPluginutils()    Copy pre-built dist
2. bundleRolldown()               Copy + rewrite module specifiers
3. buildVite()                    Full Rolldown build with transforms
   ├── Apply RewriteImportsPlugin     Build-time import rewriting
   ├── Apply rewrite-static-paths     Fix VITE_PACKAGE_DIR constants
   ├── Run Rolldown build             Bundle vite source
   └── Copy and rewrite .d.ts files   Post-build specifier rewriting
4. bundleTsdown()                 Re-bundle with CJS handling
   ├── Bundle tsdown with Rolldown    Find CJS modules
   ├── buildCjsDeps()                 Bundle detected CJS deps
   └── Bundle types with dts plugin   Generate declarations
5. mergePackageJson()             Merge metadata + record versions

Key Constants

// Source directories
const rolldownPluginUtilsDir = resolve(
  projectDir,
  '..',
  '..',
  'rolldown',
  'packages',
  'pluginutils',
);
const rolldownSourceDir = resolve(projectDir, '..', '..', 'rolldown', 'packages', 'rolldown');
const rolldownViteSourceDir = resolve(projectDir, '..', '..', 'vite', 'packages', 'vite');
const tsdownSourceDir = resolve(projectDir, 'node_modules/tsdown');

// Package name used for rewrites
const targetPackage = '@voidzero-dev/vite-plus-core';

Bundled Versions Tracking

The bundledVersions field in package.json records the exact versions of bundled upstream projects:

{
  "bundledVersions": {
    "vite": "8.0.0-beta.8",
    "rolldown": "1.0.0-beta.60",
    "tsdown": "0.20.0-beta.4"
  }
}

This is automatically updated by mergePackageJson() during each build.

Core Version

The core version encodes bundledVersions.vite, so it differs from the vite-plus version. Package managers compare the version of the vite alias target with the vite peer ranges of plugins, so the encoded version makes those checks match the bundled Vite. See the RFC for the design.

Release Core version Example
Stable vite-plus <vite major>.<vite minor>.<vite patch * 1000 + n> Vite 8.3.5, n = 1: 8.3.5001
vite-plus prerelease, stable Vite <next stable core version>-vp.<k> 8.4.0-vp.0
vite-plus prerelease, Vite prerelease <vite version>.vp.<k> 9.0.0-beta.3.vp.0
Local and CI builds, stable Vite n = 999 8.3.5999
Local and CI builds, Vite prerelease <vite version>.vp.999 9.0.0-beta.3.vp.999

n counts the stable releases on one Vite version, from 0 to 998. k counts the prereleases on one base, from 0 to 998. This follows the oxlint-tsgolint versioning, where 7.0.2000 is the first release on TypeScript 7.0.2. packages/tools/src/core-version.ts implements the scheme:

  • prepare_release.yml runs core-version.ts prepare to select the next unpublished version from the registry. It writes that version and the vite-plus version (vitePlusVersion) to package.json.
  • release.yml runs core-version.ts check --release. It fails when the registry already holds the core version for a different vite-plus release, or when the version number was unpublished.
  • .github/scripts/upgrade-deps.ts resets version to n = 0 when the bundled Vite changes.
  • __tests__/core-version.spec.ts checks that the committed version encodes bundledVersions.vite.