pledgepack
v0.1.8
Published
A Rust+Zig bundler with incremental computation, JS plugins, and Rollup-quality output
Downloads
2,046
Maintainers
Readme
Pledgepack
A Rust native alternative to Vite, webpack and Rollup. Built with Rust + Zig for raw speed, with real framework compilation, a built in test runner, HMR with live error overlay, and a clean programmatic API. No stubs, no JavaScript overhead, just raw speed.
npm package:
pledgepack· CLI command:pledge· Rust crates:pledgepack-*
Architecture
┌─────────────────────────────────────────────────────┐
│ pledge CLI │
│ (dev / build / serve / bench) │
├─────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌──────────────────────┐ │
│ │ RUST │ │ ZIG │ │
│ │ (Orchestrator)│ │ (Hot Paths) │ │
│ │ │ │ │ │
│ │ • Engine │ │ • File I/O (io_uring)│ │
│ │ • Resolver │ │ • Module graph (arena)│ │
│ │ • Cache │ │ • SIMD scanning │ │
│ │ • Dev server │ │ • Hashing │ │
│ │ • Optimizer │ │ • Memory-mapped I/O │ │
│ │ • JS plugin │ │ │ │
│ │ host │ │ │ │
│ │ • Oxc transform│ │ │ │
│ └──────┬───────┘ └──────────┬───────────┘ │
│ │ C ABI (zero-cost) │ │
│ └──────────┬─────────────┘ │
│ │ │
└─────────────────────────────────────────────────────┘What Makes This Different
| Feature | Vite | Turbopack | Pledge | |---------|------|-----------|--------| | Core language | JS + Rust | Rust | Rust + Zig | | Graph memory | Standard | Rc (48B/node) | Arena (0B/node) | | File I/O | epoll | epoll | io_uring | | HMR at scale | 300-400ms | ~50ms | ~50ms (target) | | Plugin system | JS (V8) | None | JS (Boa engine) | | Framework | Any | Next.js only | Any | | Bundle size | Smallest | +72% bloat | Small (target) | | Incremental | Module-level | Function-level | Function-level | | Transform | SWC/esbuild | SWC | Oxc |
Project Structure
pledge-dev/
├── Cargo.toml # Rust workspace (oxc, axum, tower-http, notify)
├── build.zig # Zig build script
├── build.zig.zon # Zig config
├── build.ps1 # Build script (Zig + Rust)
├── src/ # User app source code (TypeScript/TSX)
│ ├── index.tsx # Entry point
│ └── utils.ts # Utility module
├── dist/ # Production build output (generated by `pledge build`)
│ ├── index.html # Generated HTML shell
│ └── src/ # Transformed JS files (types stripped, JSX → JS)
├── native-sys/ # Rust FFI bindings to Zig
│ ├── src/lib.rs # C ABI bindings (Graph, read_file, find_imports, chkstk_ms)
│ └── zig/ # Zig native library (moved from src/)
│ ├── lib.zig # C ABI exports
│ ├── io.zig # File I/O (io_uring, mmap, thread pool)
│ ├── graph.zig # Arena-allocated module graph
│ ├── simd.zig # SIMD source scanning
│ └── bench.zig # Benchmarks
├── crates/
│ ├── cli/ # CLI entry point (pledgepack-cli, binary: pledge)
│ ├── core/ # pledgepack-core: engine + config + transform + env + html + compression + analyzer + edge + dep_bundler
│ ├── cache/ # pledgepack-cache: function-level incremental cache (memory + disk/bincode)
│ ├── resolver/ # pledgepack-resolver: module resolution (node_modules, tsconfig, exports)
│ ├── dev-server/ # pledgepack-dev-server: dev server + HMR + CSS HMR + error overlay + proxy
│ ├── optimizer/ # pledgepack-optimizer: tree shaking, code splitting, vendor/shared chunks
│ ├── js-plugin-host/ # pledgepack-js-plugin-host: Vite-compatible JS plugin API (Boa engine)
│ ├── adapter-react/ # pledgepack-adapter-react: React JSX + Fast Refresh adapter (Oxc-based)
│ ├── adapter-solid/ # pledgepack-adapter-solid: Solid.js JSX adapter (Oxc-based, solid-js runtime)
│ ├── adapter-next/ # pledgepack-adapter-next: Next.js adapter (App/Pages Router, SSR, API routes)
│ ├── adapter-tanstack/ # pledgepack-adapter-tanstack: TanStack Router adapter (file-based routing)
│ └── adapter-pledgestack/ # pledgepack-adapter-pledgestack: PledgeStack adapter (React + Rust backend, .rs/.psx)
├── package.json # npm scripts (dev, build, preview, serve, bench)
└── docs/ # Documentation
├── ARCHITECTURE.md # System architecture deep dive
├── BUILD_SYSTEM.md # Build pipeline, Oxc transform, caching, compression, edge
├── DEV_SERVER.md # Dev server, HMR, CSS HMR, error overlay, proxy, HTTPS, WS proxy
└── CHANGELOG.md # Development historysrc/ vs dist/
| | src/ | dist/ |
|---|---|---|
| Purpose | Source code you edit | Build output browser runs |
| Languages | TypeScript, TSX, JSX | JavaScript only |
| JSX | Raw JSX syntax | React.createElement() calls |
| Types | Full type annotations | Types stripped |
| Extensions | .ts, .tsx | .js |
| Imports | import { foo } from "./utils" | import { foo } from "./utils" (paths preserved) |
| Served by | pledge dev (port 3000, on-demand transform) | pledge serve (port 4000, static files) |
Installation
Via npm (recommended)
# Global install for CLI usage
npm install -g pledgepack
# Or as a dev dependency in your project
npm install --save-dev pledgepackThe postinstall script automatically downloads the prebuilt native binary for your platform (Linux x64/arm64, macOS x64/arm64, Windows x64/arm64) from GitHub Releases. If no prebuilt binary is available, it falls back to building from source.
From source
git clone https://github.com/pledgeandgrow/pledgerepo
cd pledgerepo
cargo build --releaseRequires Rust (stable, edition 2024) and Zig (0.14.0+).
Building
Prerequisites
Build
# Debug build
.\build.ps1
# Release build
.\build.ps1 release
# Run tests
.\build.ps1 test
# Run benchmarks
.\build.ps1 benchManual build
# Build Zig native library
zig build -Doptimize=ReleaseFast
# Build Rust
cargo build --releaseUsage
# Using npm scripts
npm run dev # Start dev server (port 3000, HMR, on-demand transforms)
npm run build # Production build (transform + optimize + emit to dist/)
npm run preview # Preview production build
npm run serve # Serve production build (static files, port 4000)
npm run bench # Benchmark build performance (5 runs)
npm run cache:clear # Clear disk cache
# Using pledge CLI directly
pledge dev # Start dev server
pledge build # Production build
pledge build --watch # Watch mode build
pledge build --profile # Profile build performance
pledge serve # Serve dist/ on port 4000
pledge bench # Benchmark (5 runs, min/max/avg/median)
pledge cache clear # Clear disk cache
pledge cache stats # Show cache statistics
pledge create react my-app # Scaffold a new React project
pledge create vue my-app # Scaffold a new Vue project
pledge create svelte my-app # Scaffold a new Svelte project
pledge create solid my-app # Scaffold a new Solid project
pledge create next my-app # Scaffold a new Next.js project
pledge create tanstack my-app # Scaffold a new TanStack Router project
pledge create vanilla my-app # Scaffold a new vanilla TS project
pledge analyze # Analyze bundle size with interactive treemap
pledge analyze --port 4200 # Serve analysis on custom port
pledge analyze --graph # Generate interactive dependency graph
pledge test # Run tests (Vitest-compatible API)
pledge test --watch # Watch mode tests
pledge test --ui # Browser UI test mode
pledge dashboard # Build telemetry dashboard (localhost:4300)
pledge schema # Generate JSON Schema for pledge.config.ts
pledge generate-env-types # Generate pledge-env.d.ts for import.meta.envConfiguration
pledge.config.ts (TypeScript Config with Autocompletion)
Pledge supports TypeScript config files with full autocompletion via defineConfig:
import { defineConfig } from 'pledge';
export default defineConfig({
entry: ['src/index.tsx'],
framework: 'react',
source_maps: true,
env_prefix: 'PLEDGE_',
env_dts: true,
html_entry: 'index.html',
compress_gzip: true,
compress_brotli: true,
edge_target: 'cloudflare', // 'cloudflare' | 'vercel' | 'deno'
plugins: ['./plugins/my-plugin.ts'],
image: {
quality: 80,
webp: true,
avif: false,
max_width: 1920,
max_height: 1080,
},
// Library mode build
library: {
entry: 'src/index.ts',
formats: ['esm', 'cjs'],
name: 'MyLib',
external: ['react'],
declarations: true,
},
// HTTPS dev server
https: {
cert: './cert.pem',
key: './key.pem',
},
// Server entry point for SSR/API routes (enables server-only code hot reload)
server_entry: 'server/index.ts',
// Node.js polyfills for browser builds
node_polyfills: true,
// Compile-time constant replacement
define: {
'process.env.NODE_ID': '"production"',
'__VERSION__': '"1.0.0"',
},
// Watch mode for production builds
watch: {
enabled: false,
debounce_ms: 300,
},
dev_server: {
port: 3000,
host: 'localhost',
hmr: true,
open: false, // Set to true to auto-open browser on dev server start
proxy: [
{ path: '/api', target: 'http://localhost:8080', rewrite: true, ws: true }
],
},
// Test configuration (pledge test)
test: {
include: ['**/*.{test,spec}.{ts,tsx,js,jsx}'],
exclude: ['node_modules', '.pledge', 'dist'],
environment: 'node', // 'node' | 'jsdom' | 'happy-dom'
globals: false, // Set to true for global describe/it/expect without imports
setup_files: [], // e.g. ['./test/setup.ts'] — run before each test file
isolation: 'file', // 'file' | 'pool' | 'none'
coverage: false, // Enable code coverage collection
coverage_reporter: 'text', // 'text' | 'json' | 'html' | 'lcov'
snapshot: true, // Enable snapshot testing
snapshot_dir: '__snapshots__', // Directory for .snap files
update_snapshots: false, // Set to true to update snapshots (-u flag)
},
});Config file resolution order: pledge.config.ts → pledge.config.js → pledge.config.mjs → pledge.json → defaults.
.env Files
Pledge loads environment variables from .env files with the following precedence (highest first):
.env.[mode].local(e.g.,.env.development.local).env.[mode](e.g.,.env.development).env.local.env
Variables are injected into code via import.meta.env.*:
// Any PLEDGE_-prefixed variable is available
const apiUrl = import.meta.env.PLEDGE_API_URL;
const isDev = import.meta.env.PLEDGE_DEV;Built-in variables: PLEDGE_DEV, PLEDGE_PROD, PLEDGE_MODE, MODE, DEV, PROD, SSR.
Generate TypeScript declarations:
pledge generate-env-types # Creates pledge-env.d.tsImplemented Features
Oxc Transform Pipeline (crates/core/src/transform.rs)
- JSX → JS: Framework-aware JSX runtime (React classic, Solid automatic, Vue automatic)
- TypeScript type stripping: Full type annotation removal via Oxc parser + transformer
- Semantic analysis: Oxc SemanticBuilder for symbol table and scope tree
- Codegen: Oxc Codegen with optional minification for production builds
- Source types:
.tsx,.ts,.jsx,.js,.mjs,.vue,.svelte,.astroall supported - Production minification: Dead code elimination, variable mangling, constant folding (Oxc Minifier)
- import.meta.glob: Glob-based file imports for dynamic route/component discovery —
import.meta.glob('./pages/*.tsx')expanded at transform time with lazy and eager modes,?rawquery support,importfilter, and**recursive wildcard
Framework Adapters
React (crates/adapter-react/)
- JSX transform: Oxc-based automatic runtime JSX transformation (
react/jsx-runtime) - TypeScript stripping: Full type annotation removal via Oxc transformer
- Fast Refresh: AST-based component detection +
import.meta.hot.accept()injection for HMR state preservation - Component detection: Function declarations, arrow functions with capitalized names via Oxc AST visitor
- Production minification: Oxc Codegen with minify option for production builds
Vue (crates/core/src/transform.rs:transform_vue)
- SFC parsing:
<template>,<script setup>,<style scoped>block extraction - TypeScript transform:
<script lang="ts">blocks transformed with Oxc (type stripping) - Render functions: Template compiled to render function
- Scoped CSS:
[data-v-pledge]attribute selectors for scoped styles - HMR boundary:
import.meta.hot.accept()injected in dev mode
Svelte (crates/core/src/transform.rs:transform_svelte)
- SFC parsing:
<script>,<style>, markup extraction - TypeScript transform:
<script lang="ts">blocks transformed with Oxc (type stripping) - Render functions: Markup compiled to DOM render function with mount/unmount
- Scoped CSS:
[svelte-pledge]attribute selectors for scoped styles - HMR boundary:
import.meta.hot.accept()injected in dev mode
Solid (crates/adapter-solid/)
- JSX transform: Oxc-based automatic runtime with
solid-js/jsx-runtimeimport source - TypeScript stripping: Full type annotation removal via Oxc transformer
- Development mode:
development: truein dev for better error messages - Production minification: Oxc Codegen with minify option for production builds
Astro (crates/core/src/transform.rs:transform_astro)
- Frontmatter parsing:
---delimited code blocks extracted as module-level JS - TypeScript transform: Frontmatter TS transformed with Oxc (type stripping)
- Template compilation: HTML template compiled to async render function
- Style extraction:
<style>blocks extracted as CSS - HMR boundary:
import.meta.hot.accept()injected in dev mode - Islands ready: Component-level hydration support
Next.js (crates/adapter-next/)
- App Router:
app/directory route discovery (page.tsx, layout.tsx, loading.tsx, error.tsx) - Pages Router:
pages/directory route discovery (index.tsx, [param].tsx) - Dynamic routes:
[param]→:paramURL parameter mapping - API routes:
app/api/orpages/api/detection - Layout nesting: Layout routes tracked for component nesting
- SSR manifest: JSON manifest of all routes for server-side rendering
- Client router: Auto-generated route map with lazy imports
TanStack (crates/adapter-tanstack/)
- File-based routing:
src/routes/directory scanning - Dynamic params:
$paramfiles →:paramroute segments - Layout routes:
layout.tsx/__root.tsxdetection - Route tree: Auto-generated route tree with lazy imports
- Route manifest: JSON manifest with parent/child relationships
PledgeStack (crates/adapter-pledgestack/)
- React frontend + Rust backend: Next.js-like full-stack framework with Rust backend instead of Node.js
- Frontend routes: Scans
app/for.tsxpages (file-based routing, dynamic[slug]segments) - Backend routes: Scans
server/api/for.rsand.psxfiles with#[route(GET, "/api/users")]macros - Middleware: Scans
server/middleware/for.rsor.psxmiddleware files - Server entry: Detects
server/lib.rs,server/lib.psx,server/main.rs, orserver/main.psx - Route macro formats: Simple (
GET, "/path"), qualified (pledge::route(...)), key-value (method = "GET", path = "/path") .psxextension: PledgeStack eXtension — brands backend files, parallel to.tsxfor frontend.psx→.rscopy: Copies.psxfiles to.rsduring build forcargo buildcompatibility- Route manifest: JSON manifest with all frontend + backend routes + middleware
- SSR/SSG detection: Detects
getServerSideProps/getStaticProps/revalidateexports
CSS Processing
Lightning CSS (crates/core/src/transform.rs:transform_css)
- Minification: Production-mode CSS minification via Lightning CSS
- Nesting: CSS nesting transpilation
- Autoprefixing: Browser target autoprefixing
- CSS Modules:
*.module.cssscoped class names with blake3 content hashing (generate_css_module_map)
PostCSS / Tailwind (crates/core/src/transform.rs:process_postcss)
- @tailwind directives:
@tailwind base/components/utilitiesexpanded to generated CSS - @apply expansion: 80+ utility class mappings (flex, p-4, text-center, rounded-lg, etc.)
- Base reset: Tailwind-compatible CSS reset injected for
@tailwind base - Container component: Responsive
.containerclass with breakpoint max-widths - Utility classes: Full subset of Tailwind utilities (display, flex, spacing, typography, etc.)
Advanced CSS (crates/core/src/css_advanced.rs)
- CSS Modules composes: Parse and resolve
composes: button from './buttons.css'cross-file compositions; strip after resolution - Dark mode generation: Auto-generate dark mode variants from
prefers-color-scheme: darkor CSS custom property inversion; config:css.dark_mode - Custom property optimization: Inline single-use variables, remove unused
:rootvars, minify property names in production - Scoped CSS for React:
data-v-xxxxxattribute-based scoping (like Vue); config:css.scoped: "attribute" - Nesting polyfill: Native CSS nesting (
& > .child) transpiled by lightningcss for older browser targets
Security (crates/core/src/security.rs)
- SRI hashes: Generate
integrityattributes for<script>and<link>tags; config:security.sri: true - CSP generation: Auto-generate Content Security Policy from build output; config:
security.csp: "auto" - Vulnerability scanning: Scan
package.jsondependencies for known CVEs; integrated inpledge doctor - License compliance: Scan
node_modulesfor license compatibility; blacklist copyleft licenses; integrated inpledge doctor
Performance (crates/core/src/performance.rs)
- Route-based chunk splitting: Detect routes from app/pages directories, split per-route with shared chunk extraction
- Module prefetch directives: Generate
<link rel="modulepreload">and<link rel="prefetch">based on route chunks - CSS-in-JS runtime tree shaking: Strip styled-components/emotion/vanilla-extract runtime imports after static extraction
- WASM streaming compilation:
WebAssembly.instantiateStreaming()with fallback and SIMD auto-detection - Precompute module hash: Content hash computed at transform time, not during emit
Asset Handling
Static Assets (crates/core/src/transform.rs:transform_asset)
- URL imports:
import logo from './logo.png'→export default "/src/logo.png" - Inline imports:
import logo from './logo.png?inline'→ base64 data URI - MIME detection: Automatic MIME type from file extension (png, jpg, svg, woff2, etc.)
JSON (crates/core/src/transform.rs:transform_json)
- Named exports: Top-level object keys exported as
export const - Default export:
export default <json>
WASM (crates/core/src/transform.rs:transform_wasm)
- Async instantiation:
import wasm from './module.wasm'→WebAssembly.instantiateStreaming - Export exports:
instance.exportsreturned from default export function
Web Workers (crates/core/src/transform.rs:transform_worker_imports)
- Worker pattern:
new Worker(new URL('./worker.ts', import.meta.url))→new Worker('/src/worker.js') - SharedWorker:
new SharedWorker(new URL(...))patterns also supported - Worker modules:
.worker.js/.worker.tsextensions detected as worker kind
Code Splitting
Dynamic Imports (crates/core/src/transform.rs:detect_dynamic_imports)
- AST-based detection: Oxc
ImportExpressionvisitor for accurate dynamic import detection - String fallback: Falls back to string-based scanning if parsing fails
- Relative only: Only relative specifiers (
./,../) tracked for chunk splitting - Async chunks: Dynamic imports marked for separate chunk emission
Production Output (crates/core/src/engine.rs:emit())
- Writes each transformed module to
dist/preserving directory structure - Changes extensions to
.js - Generates
index.htmlwith<script type="module">entry point - Asset hashing: Content-hashed filenames for cache busting
- manifest.json: Generated manifest mapping source files to output files
- Single-file bundle:
emit_single_file()concatenates all modules into one ESM file - Logs each emitted file
Programmatic API (crates/core/src/api.rs)
createServer(options): Create a dev server instance with configurable port, host, HMR, HTTPSbuild(options): Run a production build programmatically with full config controltransform(code, id, config): Transform a single module (JSX, TS, CSS, Vue, Svelte) and return code + source map + depsresolve(specifier, importer, root): Resolve module specifiers to file paths (relative, absolute, bare, node_modules with package.json)
Dev Server (crates/dev-server/src/lib.rs)
- On-demand transforms: Each request triggers Oxc transform (parse → semantic → transform → codegen)
- AST-based import rewriting: Oxc parser rewrites imports with string fallback (
./utils→./utils.js) - Alias rewriting: Resolve aliases (e.g.,
@/components→/src/components) rewritten in dev - Extension fallback:
/src/utils.jsresolves toutils.tson disk automatically - Import map injection: Bare specifiers in
node_modulesresolved via import map in HTML - Inline React shim: Minimal
React.createElementimplementation injected in HTML - Content-Type:
application/javascript; charset=utf-8withno-cacheheaders - Error overlay: Full-screen in-browser error overlay with source context, stack traces, line/column display, auto-dismiss on HMR success
- Runtime error overlay: Catches
window.errorevents and unhandled promise rejections (unhandledrejection), displaying runtime errors in the overlay with stack traces - Auto-open browser:
open: trueconfig (or--openCLI flag) auto-opens the default browser on dev server start viaopenercrate (cross-platform) - Network URL display: Shows local network IP alongside localhost URL via
local-ip-addresscrate (e.g.,→ Network: http://192.168.x.x:3000) - CSS HMR:
<style>tags injected/updated without page reload on CSS file changes - HTTPS support: TLS via rustls + tokio-rustls (config:
https: { cert, key }) - Dev server proxy: All HTTP methods (GET, POST, PUT, DELETE, PATCH) proxied via reqwest
- WebSocket proxy:
ws: trueon proxy config enables bidirectional WS proxying - Source maps:
sourceMappingURLcomments appended to dev server responses
HMR (crates/dev-server/src/lib.rs)
- File watcher:
notifycrate with recursive watch on project root - Debounce: 200ms debounce to batch rapid file changes, filters out
node_modules,.pledge,target,.git - WebSocket:
/__pledge_hmrendpoint for real-time push - Client-side: Auto-reload changed modules via timestamp query params
- HMR boundary:
import.meta.hot.accept()injected in TS/TSX/JS modules - React Fast Refresh: Component state preservation via
window.__pledge_fast_refreshregistry - CSS HMR: CSS file changes send content via WebSocket,
<style>tags updated in-place - Error reporting: Transform errors sent via WebSocket to all connected clients with source context and stack traces
- Server-only hot reload:
server_entryconfig enables detection of server-only file changes viacompute_server_dirs()andis_server_file(). Sendsserver-reload→server-reload-completeHMR updates, preserving WebSocket connections. Client-side banner UI shows reload status.
Watch Mode (crates/cli/src/main.rs)
- Debounced rebuild: 200ms debounce on file changes, only rebuilds when source files change
- Smart filtering: Ignores
node_modules,.pledge,target,.gitdirectories - Colored output: Shows changed files and rebuild timing
- Source file detection: Only watches
.ts,.tsx,.js,.jsx,.css,.scss,.less,.vue,.svelte,.html,.jsonfiles - Test watch mode:
pledge test --watchre-runs tests on file change with 300ms debounce
Optimizer (crates/optimizer/src/lib.rs)
- Tree shaking: Reachability analysis from entry points, removes dead modules
- Side-effect detection: Heuristic-based marking of modules with top-level side effects
- Vendor splitting:
node_modulesmodules → separate vendor chunk - Shared splitting: Modules used by 2+ entries → shared chunk
- Entry chunks: Entry module + exclusive dependencies grouped together
- Scope hoisting: ESM imports preserved (no wrapper functions), modules share scope
Disk Cache (crates/cache/src/lib.rs + crates/core/src/engine.rs)
- Two-tier: In-memory
DashMap(fast) + diskbincode(persistent) - Cache key: Content hash + function ID + params hash (via
blake3) - Build integration: Memory cache checked first, then disk, then transform
- Automatic persistence: Transform results written to
node_modules/.pledge-cache/ - Cache invalidation: By content hash (file change → new hash → cache miss)
Resolver (crates/resolver/src/lib.rs)
- Relative paths:
./foo,../barresolved from importer directory - Bare specifiers:
react,lodash→ recursivenode_moduleslookup - tsconfig paths:
from_tsconfig()readstsconfig.jsoncompilerOptions.paths - Package exports: Full
exportsfield support with conditions (import,require,browser,default) - Subpath exports:
react/jsx-runtime→ correct subpath resolution - Pattern matching:
./utils/*→./utils/*.jswildcard expansion - Scoped packages:
@scope/name/subpathhandled correctly - Extension resolution:
.tsx→.ts→.jsx→.js→index.* - Module/Main/Browser: Fallback to
module,main,browserfields inpackage.json - DashMap cache: Per-(importer, specifier) result caching
JS Plugin Host (crates/js-plugin-host/src/lib.rs)
- Vite-compatible API: JS plugins with
resolveId,load,transform,transformIndexHtml,configureServer,buildStart,buildEnd,generateBundlehooks - Embedded JS runtime:
boa_engineevaluates plugin source and executes hooks in-process - Console support:
console.log()injected for plugin debugging - Plugin loading: Scans plugin files for hook definitions, evaluates source in JS context
- Hook execution:
transform()hook actually calls JS function and parses JSON result - Build integration: Plugins loaded in build command,
buildStart/buildEndlifecycle hooks called
Environment Variables (crates/core/src/env.rs)
.envfile loading:.env,.env.local,.env.[mode],.env.[mode].localwith precedence- Variable expansion:
${VAR}syntax for referencing other env vars import.meta.envinjection:PLEDGE_*-prefixed variables replaced in code during transform- Built-in vars:
PLEDGE_DEV,PLEDGE_PROD,PLEDGE_MODE,MODE,DEV,PROD,SSR - Type declarations:
generate_dts()producespledge-env.d.tswith typedImportMetaEnvinterface
HTML Processing (crates/core/src/html.rs)
- Entry point parsing: Extracts
<script type="module">src,<link rel="stylesheet">,<link rel="modulepreload">,<title>,<meta>tags - Production HTML: Replaces script src with hashed filenames, injects CSS
<link>tags, adds meta tags - HTML minification:
minify_html()removes comments, collapses whitespace, strips redundant spaces between tags - Default HTML generation:
generate_default_html()createsindex.htmlwith entry script and title
Source Maps (crates/core/src/transform.rs)
- V3 source maps: Generated with
sourcesContentfor debugging - Dev server:
sourceMappingURLcomments appended to transformed modules - Production: Source maps emitted alongside production output
Dependency Pre-Bundling (crates/core/src/dep_bundler.rs)
- Bare import scanning: Recursively scans source files for non-relative imports
- CJS → ESM conversion: Generates ESM interop wrappers for CommonJS modules
- Package resolution: Reads
package.jsonmodule/mainfields, prefers ESM - Output: Pre-bundled deps written to
node_modules/.pledge-deps/
Parallel Transforms (crates/core/src/engine.rs)
- Rayon parallelism:
transform_modules_parallel()usesrayon::par_iterfor multi-core processing - Batch processing: All modules transformed in parallel, errors propagated
Compression Output (crates/core/src/compression.rs)
- Gzip: Real gzip compression via
flate2—.gzfiles for all compressible output (JS, CSS, HTML, JSON, SVG, WASM) - Brotli: Real Brotli compression via
brotlicrate —.brfiles generated alongside gzip - Statistics: Reports file count, original/compressed sizes, compression ratios
Edge-Ready Output (crates/core/src/edge.rs)
- Cloudflare Workers: Service Worker format with
fetchhandler andwrangler.toml - Vercel Edge Functions: Edge function format with
config.runtime = 'edge'andvercel.json - Deno Deploy:
Deno.serve()format withdeno.jsonconfig
Build Analyzer (crates/core/src/analyzer.rs)
- Per-module analysis: Original + transformed sizes, dependencies, module kind
- Chunk breakdown: Modules grouped by directory with size summaries
- Duplicate detection: Same module name in different paths flagged
- Largest modules: Top 20 modules by size
- Interactive HTML:
pledge analyzeserves a styled HTML report with stats and module table
Build Profiling (crates/core/src/pipeline.rs)
- Per-phase timing: Parse + Transform, Optimize, Emit phases timed individually
- Total build time: End-to-end build duration reported
- Enable:
pledge build --profileorprofile: truein config
Node.js Polyfills (crates/core/src/polyfills.rs)
- 20 built-in modules: buffer, process, path, crypto, stream, util, events, url, os, fs, http, https, net, tls, zlib, querystring, string_decoder, timers, assert, child_process
- Browser-safe: Minimal ESM-compatible polyfills using Web APIs (Web Crypto, TextEncoder, fetch, etc.)
- node: prefix: Supports both
import 'path'andimport 'node:path'specifiers - Enable:
node_polyfills: truein config
Define / Compile-Time Constants (crates/core/src/transform.rs:apply_define)
- Constant replacement: Replace identifiers with literal values at build time
- Type inference: Automatically wraps strings, preserves numbers/booleans
- Enable:
define: { 'process.env.NODE_ID': '"production"' }in config
Library Mode (crates/core/src/config.rs:LibraryConfig)
- Multiple formats: ESM, CJS, UMD, IIFE output formats
- External dependencies: Mark packages as external (not bundled)
- Type declarations: Optional
.d.tsgeneration - Enable:
library: { entry, formats, name, external, declarations }in config
pledge bench (crates/cli/src/main.rs)
- 5-run benchmark with fresh engine per run (disk cache stays warm)
- Reports min, max, avg, median build times
- Measures both cold and incremental (cached) performance
pledge create — Project Scaffolding
- Templates:
react,vue,svelte,solid,next,tanstack,vanilla - Generated files:
package.json,pledge.config.ts,index.html,.env,.env.local,.gitignore,src/index.tsx,src/utils.ts - Framework-aware: Each template configures the correct framework in
pledge.config.ts
pledge analyze — Bundle Analyzer
- Serves interactive HTML report at
http://localhost:4200 - Shows total size, module count, chunk count, duplicate count
- Lists top 20 largest modules with size and percentage
pledge test — Built-in Testing
- Vitest-compatible API:
describe,it,test,expectwith matchers (toBe,toEqual,toBeTruthy,toContain,toHaveLength,toThrow,notinverse matchers, etc.) - Lifecycle hooks:
beforeEach,afterEach,beforeAll,afterAll - Real JS execution: Tests run in
boa_engineembedded JS runtime withconsole.logandrequire()shim - TypeScript stripping: TS syntax automatically stripped for Boa compatibility
- Pattern matching:
--patternflag for glob-style file filtering - Watch mode:
--watchflag with debounced file watching, re-runs tests on change - UI mode:
--uiflag generates HTML report and serves it atlocalhost:5174with pass/fail/skip summary, per-test status, error details, and auto-opens browser - Snapshot testing:
toMatchSnapshot()andtoMatchInlineSnapshot()with.snapfile persistence, auto-update mode (test.update_snapshots), and mismatch error reporting - Coverage reporting: Code coverage collection with text, JSON, HTML, and LCOV output formats; enabled via
test.coverageconfig - Test setup files:
test.setup_filesconfig array for running setup code before each test file - Test environments:
test.environmentconfig supportingnode(default),jsdom, andhappy-domwith DOM shims - Globals mode:
test.globals: trueto run tests with globaldescribe,it,test,expectwithout imports - Test isolation:
test.isolationconfig withfile(default),pool, andnonemodes - Mock support:
vi.fn(),vi.mock(),vi.spyOn(),vi.stubGlobal()for Vitest-compatible mocking
pledge generate-env-types — Type-Safe Env
- Generates
pledge-env.d.tswith typedImportMetaEnvinterface - Reads all
PLEDGE_*-prefixed variables from.envfiles - Provides autocompletion for
import.meta.env.*in TypeScript
pledge schema — JSON Schema Generation
- Generates JSON Schema for
pledge.config.tsconfiguration viaschemarscrate pledge schemaoutputs to stdout,pledge schema --output schema.jsonwrites to file- Covers all config fields: build, dev_server, cache, plugins, image, i18n, a11y, encrypt, etc.
- Enables IDE autocompletion and validation for pledge config files
pledge dashboard — Build Telemetry
- Serves interactive web UI at
localhost:4300showing build history and metrics - SVG chart with build duration trends and cache hit rates
- Build records persisted to
.pledge/history.json(max 100 entries) - Shows recent build summary table with status, duration, module counts
Crate Integrations
similar— HMR line-level diff via Myers algorithm (replaces hand-rolled LCS, no line limit)opener— Cross-platform browser opening (replaces platform-specific commands, handles WSL)local-ip-address— Network URL display alongside localhost for device testingschemars— JSON Schema generation forPledgeConfig(all 18 sub-structs/enums)miette— Graphical error diagnostics with source spans (enabledfancyfeature)clap_mangen— Auto-generates roff man pages for CLI commandshumansize— Unified file size formatting across CLI output, cache stats, build analysisserde_yaml— YAML config parsing (replaces hand-rolled line-based parser)
npm Scripts (package.json)
{
"scripts": {
"dev": "pledge dev",
"build": "pledge build",
"build:profile": "pledge build --profile",
"build:watch": "pledge build --watch",
"preview": "pledge preview",
"serve": "pledge serve",
"cache:clear": "pledge cache clear",
"bench": "pledge bench",
"analyze": "pledge analyze",
"test": "pledge test",
"test:watch": "pledge test --watch",
"dashboard": "pledge dashboard",
"schema": "pledge schema",
"gen:env": "pledge generate-env-types"
}
}Supported Project Types
| Framework | Status | File Types |
|-----------|--------|------------|
| React | ✅ Full | .tsx, .jsx, Fast Refresh, classic JSX |
| Solid | ✅ Full | .tsx, .jsx, automatic JSX with solid-js (dedicated adapter crate) |
| Vue | ✅ Full | .vue (SFC), scoped CSS, script setup |
| Svelte | ✅ Full | .svelte (SFC), scoped CSS, render functions |
| Astro | ✅ Full | .astro, frontmatter, islands-ready |
| Next.js | ✅ Adapter | App Router, Pages Router, API routes, SSR |
| TanStack | ✅ Adapter | File-based routing, route tree generation |
| PledgeStack | ✅ Adapter | React frontend + Rust backend, .rs/.psx, route macros |
| Vanilla TS/JS | ✅ Full | .ts, .js, .mjs |
License
MIT License (LICENSE).
Roadmap: 50 Future Features and Improvements
Build Performance
- ~~Incremental rebuild graph~~ ✅ — Only rebuild changed modules and their dependents, skip untouched subtrees entirely instead of full rebuilds. Implemented in
module_graph.rswith content-hash-based change detection and transitive dependent computation. - ~~Persistent module graph~~ ✅ — Serialize the module graph to disk between builds for faster cold starts and incremental detection.
SerializableModuleGraphsaves/loads via bincode tomodule_graph.binin the cache directory. - ~~Parallel dependency optimization~~ ✅ — Multi-threaded tree shaking and chunk splitting using rayon for large dependency graphs.
mark_side_effectsandsplit_chunksparallelized withpar_iter()andpartition_map(). - ~~Lazy dependency scanning~~ ✅ — Scan only entry-point imports on first build, expand graph lazily as imports are discovered. BFS queue processes modules on-demand, resolving dependencies only when encountered.
- ~~Build cache sharing~~ ✅ — Share transform cache across CI runs via content-addressable storage backed by S3/GCS.
RemoteCacheinremote.rssupports HTTP, S3, and GCS backends with automatic fallback. - ~~Git-based cache invalidation~~ ✅ — Use git tree hashes for cache keys instead of file content hashes for faster invalidation on large repos.
GitCacheInvalidatoringit_cache.rsusesgit ls-filesandgit rev-parse HEAD^{tree}. - ~~Remote cache~~ ✅ — Network-based cache for team/CI builds, sharing transform results across machines. Integrated in
BuildEnginewith 3-tier fallback: memory → disk → remote. - ~~Memory-mapped output writing~~ ✅ — Use mmap for writing large build output files instead of buffered I/O.
write_output_file()uses mmap for files >64KB on Unix, buffered write for smaller files and Windows.
Dev Server
- ~~File system watcher optimizations~~ ✅ — Use
inotify/FSEvents/ReadDirectoryChangesWnatively instead ofnotifycrate abstraction for lower latency. Implemented inwatcher.rswith platform-specific native watchers and fallback. - ~~HMR partial updates~~ ✅ — Send only the changed function/module diff via WebSocket instead of full module replacement. Implemented in
hmr_diff.rswithsimilarcrate (Myers algorithm) for line-level diff computation andis_small()heuristic. - ~~Dev server cold boot optimization~~ ✅ — Lazy-load transform pipeline, only initialize Oxc/Lightning CSS on first request. Implemented in
lazy_pipeline.rswith deferred initialization and dirty dependency tracking. - ~~WebSocket compression~~ ✅ — Per-message deflate for HMR WebSocket to reduce bandwidth on large module updates. Applied via
tower-httpCompressionLayerwith gzip andFastestquality level. - ~~Multi-entry dev server~~ ✅ — Support multiple HTML entry points with independent HMR contexts in a single dev server.
detect_entries()auto-detects HTML files and registers per-entry routes. - ~~Dev server middleware chain~~ ✅ — Configurable middleware pipeline for request processing (auth, logging, headers) before module serving. Implemented in
middleware.rswithMiddlewareFnparsing from config and CORS/rewrite helpers. - ~~On-demand dependency optimization~~ ✅ — Re-optimize dependencies only when import patterns change, not on every server start. Import patterns tracked per-module in
DevServerStateand compared on each transform.
Transform & Compilation
- ~~WASM target compilation~~ ✅ — Compile select modules to WASM for compute-heavy workloads with
?wasmimport suffix.transform_optimizations.rsdetects?wasmimports and generates JS glue code for loading WASM modules. - ~~Tree shaking with side-effects detection~~ ✅ — Heuristic-based side-effect detection for tree shaking unused exports.
analyze_side_effects()checks for global writes, DOM access, andconsolecalls;tree_shake_module()removes unused exports. - ~~Cross-chunk variable hoisting~~ ✅ — Hoist shared variables across chunks to avoid duplicate declarations in split bundles.
analyze_cross_chunk_hoisting()tracks which chunks import variables from other chunks. - ~~CSS tree shaking~~ ✅ — Remove unused CSS selectors by analyzing class names in JS/JSX/TSX source code.
extract_used_class_names()findsclassName,class,:classattributes including template literals;shake_css()filters CSS rules. - ~~Dead code elimination at expression level~~ ✅ — Remove unreachable branches inside functions.
eliminate_dead_code()handlesif (false),if (true), strict comparison replacements, andtypeofchecks. - ~~Constant folding with type info~~ ✅ — Fold expressions like
1 + 2→3and"a" + "b"→"ab".fold_constants()handles numeric, string, boolean, andtypeofexpression folding. - ~~Optional chaining nullish short-circuit~~ ✅ — Optimize
a?.b?.cchains to avoid redundant null checks.optimize_optional_chaining()simplifies redundant null checks in optional chaining. - ~~Module-level memoization~~ ✅ — Cache transform results keyed by source hash + transform config hash.
ModuleTransformCacheuses blake3 hashes for cache keys with LRU eviction and path-based invalidation.
CSS & Styling
- ~~Tailwind v4 Oxide engine~~ ✅ — Native Tailwind v4 engine integration with CSS-first config and Lightning CSS.
tailwind_v4.rsparses@theme,@utility,@variantdirectives, generates utility classes from theme tokens, and includes v4 preflight (reset). - ~~CSS-in-JS compile-time extraction~~ ✅ — Built-in support for styled-components, emotion, and vanilla-extract compile-time transforms.
css_in_js.rsextracts CSS from template literals and style objects at build time, replacing runtime CSS-in-JS with static CSS + class names. - ~~CSS layer support~~ ✅ —
@layercascade layer management and automatic layer ordering in output.css_features.rsparses@layerdeclarations and reorders layer blocks according to@layer name1, name2;order statements. - ~~Container queries polyfill~~ ✅ — Built-in container query transform for older browser targets.
polyfill_container_queries()incss_features.rsgenerates class-based fallbacks alongside native@containerrules. - ~~Critical CSS extraction~~ ✅ — Extract above-the-fold CSS and inline it in HTML
<head>for faster FCP.extract_critical_css()analyzes HTML class/id/tag usage and filters CSS rules;inline_critical_css()injects the result into<head>. - ~~CSS source maps in dev~~ ✅ — Accurate CSS source maps pointing to original
.scss,.less, or.cssfiles.generate_css_source_map()incss_features.rsproduces v3 source maps with VLQ-encoded line mappings and original source content. - ~~PostCSS plugin caching~~ ✅ — Cache PostCSS plugin results to avoid re-running expensive plugins on unchanged CSS.
PostCssCacheincss_features.rsuses blake3 content hashing to key and cache plugin output.
Asset Pipeline
- ~~MDX compilation~~ ✅ —
.mdxfile compilation (Markdown + JSX) with frontmatter extraction and component imports.compile_mdx()inasset_pipeline.rsparses frontmatter, converts markdown to JSX (headings, lists, code blocks, links, bold/italic), and exports aMDXContentcomponent. - ~~GraphQL file loading~~ ✅ —
.graphql/.gqlfile loading with automatic TypeScript type generation.parse_graphql()extracts queries, mutations, subscriptions, and fragments;graphql_to_module()generates named exports with PascalCase type declarations. - ~~YAML/CSV/TSV imports~~ ✅ — Data file imports with typed named exports.
transform_yaml()parses key-value pairs into named exports;transform_csv()/transform_tsv()exportcolumns,rowCount, androwsas array of objects. - ~~Image format auto-selection~~ ✅ — Automatically convert images to WebP/AVIF based on browser support and size savings.
select_image_format()inasset_pipeline.rspicks AVIF for large images with support, WebP for medium, original for small;generate_picture_element()produces<picture>with multiple<source>tags. - ~~Audio/video asset handling~~ ✅ — Import audio (
.mp3,.wav,.ogg) and video (.mp4,.webm) files with URL exports.transform_audio_asset()/transform_video_asset()inasset_pipeline.rsproduce URL or base64 data URI exports based on inline threshold. - ~~PDF asset handling~~ ✅ — Import
.pdffiles with URL exports and optional inline base64 for small documents.transform_pdf_asset()inasset_pipeline.rshandles both URL anddata:application/pdf;base64,...inline exports. - ~~Asset manifest generation~~ ✅ — JSON manifest mapping all asset imports to their hashed output paths for backend integration.
AssetManifestinasset_pipeline.rstracks source→output mappings with content hashes, file sizes, and MIME types;hashed_output_path()generatesassets/{name}-{hash}.{ext}paths.
Plugin System
- ~~Plugin hot reload~~ ✅ — Reload JS plugins without restarting dev server when plugin source changes.
PluginHotReloaderinplugin_system.rswatches plugin source files via blake3 content hashing and triggers reload callbacks on change. - ~~Plugin sandboxing improvements~~ ✅ — JS plugin sandboxing with configurable limits.
SandboxLimitsconfigures max memory, CPU time, FS reads/writes, allowed paths, network access, and stack depth;SandboxedFsenforces path access and read/write limits. - ~~Plugin dependency resolution~~ ✅ — Allow plugins to import npm packages within the WASM sandbox via pre-bundled imports.
PluginDependencyResolverpre-bundles dependencies and generates import maps for WASM plugins. - ~~Plugin lifecycle hooks~~ ✅ — Add
watchStart,watchChange,watchEndhooks for file-watcher-aware plugins.LifecycleHookRegistrysupports 9 hook types with per-plugin registration and invocation. - ~~Plugin parallel execution~~ ✅ — Run independent plugin transforms in parallel using rayon for multi-plugin pipelines.
execute_parallel_transforms()uses rayon'spar_iter;group_independent_tasks()groups tasks by file independence.
Output & Distribution
- ~~Service worker generation~~ ✅ — Automatic service worker with precaching, runtime caching, and offline fallback for production builds.
service_worker.rsgenerates SW code with configurable caching strategies (network-first, cache-first, stale-while-revalidate). - ~~Web App Manifest generation~~ ✅ — Automatic
manifest.jsongeneration from config with icons, themes, and display modes.generate_manifest()inservice_worker.rsproduces a complete Web App Manifest fromWebAppManifestconfig. - ~~Performance budget enforcement~~ ✅ — Fail build if bundle exceeds configured size limits with per-entry and per-chunk budgets.
check_budget()inoutput_distribution.rsvalidates total, entry, chunk, initial load, and per-asset-type sizes againstPerformanceBudget. - ~~Bundle size diff~~ ✅ — Compare bundle sizes between builds and fail CI on regressions.
diff_snapshots()comparesBundleSizeSnapshotobjects;format_diff_report()generates markdown reports with regression detection. - ~~Source map explorer~~ ✅ — Interactive treemap showing which modules contribute to source map size.
build_source_map_tree()constructs a module contribution tree from source maps;generate_explorer_html()produces an interactive HTML treemap visualization. - ~~Multi-format output~~ ✅ — Generate ESM, CJS, and IIFE outputs simultaneously from a single build for library mode.
generate_multi_format()inoutput_distribution.rsconverts ESM source to CJS, IIFE, and UMD formats with proper export handling.
DX & Tooling
- ~~LSP server~~ ✅ — Language Server Protocol implementation for import resolution, go-to-definition, and diagnostics in any editor.
lsp_server.rsprovidesLspServerStatewith go-to-definition, completion, diagnostics, hover, and document symbols; supports path aliases and node_modules resolution. - ~~Migration tooling~~ ✅ — Automatic migration from Vite/Webpack/Turbopack configs to
pledge.config.tswithpledge migrate.migrate_config()inmigrate.rsdetects and converts Vite, Webpack, and Turbopack configurations to Pledge format.
Roadmap v2: 70 Goals (55 Completed ✅)
Build Output & Optimization
~~Build-time environment variable injection~~ ✅ — Replace static env vars at transform time.
process.env.NODE_ENV→"production"inlined. Tree-shake unreachable env branches (if (DEV)blocks eliminated).defineconfig andimport.meta.envinjection inenv.rs.~~Module preloading strategy~~ ✅ — Configurable preloading for critical path chunks.
performance.rsgenerates<link rel="modulepreload">and<link rel="prefetch">based on route chunks.Build output verification — Post-build integrity check: verify all chunks exist, no broken import references, all assets resolved.
pledge build --verifyflag. Fails build on missing output files.~~Incremental output diff~~ ✅ — Only write changed chunks to disk between watch-mode rebuilds. Compare content hashes, skip unchanged files. Integrated with function-level incremental cache in watch mode.
~~WASM SIMD auto-detection~~ ✅ — Detect WASM SIMD support in build target and generate SIMD-optimized WASM modules when available.
performance.rsincludes WASM streaming compilation with SIMD auto-detection.
TypeScript & Type Safety
Type checking during build — Integrated
tsctype checking inpledge buildwithout separatetsc --noEmitstep.typeCheck: trueconfig. Fail build on type errors with formatted output.Type-aware tree shaking — Use TypeScript type info to safely remove unused exports. Detect when exports are only used in type positions (
import type) and exclude them from runtime bundle.~~Path mapping auto-resolution~~ ✅ — Read
tsconfig.jsonpaths/bases and auto-configureresolve.alias.resolver.rsreadstsconfig.jsoncompilerOptions.pathsviafrom_tsconfig()..d.tsbundling for library mode — Bundle TypeScript declarations into a single.d.tsfile for library output. Tree-shake unused type declarations.library: { declarations: 'bundled' }config.Type-safe plugin API — TypeScript types for pledgepack plugins with
Plugininterface, hook signatures, and return types. Published aspledgepack/pluginsentry point.
Testing & Quality
~~Browser-based test runner~~ ✅ —
pledge test --uigenerates HTML report and serves it atlocalhost:5174with pass/fail/skip summary, per-test status, error details, and auto-opens browser.Visual regression testing — Screenshot comparison between builds.
pledge test --visualflag. Pixel diff with threshold config. Baseline storage in.pledge/visual-baselines/.Dependency-graph-aware test re-run —
pledge test --watchonly re-runs tests affected by changed files, not all tests. Uses module graph to determine test impact set. Faster watch-mode feedback.Test parallelization across cores — Run test files in parallel using rayon thread pool.
test: { parallel: true, max_workers: 4 }config. Shared state isolation per worker.Mutation testing —
pledge test --mutateinjects code mutations to measure test effectiveness. Reports mutation score per file. Stryker-compatible output format.
CSS & Styling
~~CSS Modules with composes — Full CSS Modules
composesdirective support.composes: button from './buttons.css'. Scoped class name resolution across files.~~ ✅~~Dark mode CSS generation — Auto-generate dark mode variants from
prefers-color-schemequeries.css: { dark_mode: 'auto' }config. CSS custom property-based theme switching.~~ ✅~~CSS custom properties optimization — Detect and inline static CSS custom properties. Remove unused
:rootvariables. Minify variable names in production.~~ ✅~~Scoped CSS for React — CSS scoping without CSS Modules using automatic attribute selectors.
css: { scope: 'attribute' }config.data-v-xxxxxattribute-based scoping like Vue.~~ ✅~~CSS nesting polyfill — Native CSS nesting (
& > .child) polyfill for older browsers. Lightning CSS-based transformation with browser target config.~~ ✅
Performance & Optimization
~~Automatic route-based chunk splitting — Analyze route imports and split chunks per-route. Common shared chunks extracted automatically.
splitChunks: { strategy: 'route-aware' }config.~~ ✅~~Module prefetch directives — Auto-generate
<link rel="modulepreload">for route dependencies.<link rel="prefetch">for likely-next routes.prefetch: { strategy: 'hover' | 'viewport' | 'load' }config.~~ ✅~~Tree shaking of CSS-in-JS runtime — Remove styled-components/emotion runtime when all styles are extracted at build time. Zero runtime CSS-in-JS in production.~~ ✅
~~WASM module streaming compilation — Compile WASM modules with
WebAssembly.streaming()instead of buffer-based instantiation. Faster WASM load times.~~ ✅~~Precompute module hash at transform time — Compute content hash during transform pass, not as a separate emit pass. Eliminates redundant file reads in the emit phase.~~ ✅
Assets & Media
~~Font subsetting — Subset fonts to only include characters used in the project.
assets: { font_subset: true }config. Reduces font file size by 60-90%.~~ ✅~~SVG sprite generation — Combine SVG files into a single sprite sheet with
<symbol>elements.import logo from './logo.svg?sprite'syntax. Reduces HTTP requests.~~ ✅~~Video poster frame extraction — Auto-extract poster frame from video files.
import { src, poster } from './video.mp4'exports both URL and poster image.~~ ✅~~Responsive image srcset generation — Auto-generate
srcsetwith multiple resolutions.assets: { responsive: { widths: [400, 800, 1200] } }config.<img srcset="...">output.~~ ✅~~Asset inlining threshold — Configurable threshold for inlining assets as base64 data URIs.
assets: { inline_threshold: '4kb' }config. Assets below threshold inlined automatically.~~ ✅
Security & Integrity
~~Subresource Integrity (SRI) hashes — Generate
integrityattributes for<script>and<link>tags.security: { sri: true }config. SHA-384 hash output.~~ ✅~~Content Security Policy generation — Auto-generate CSP headers from build output. Hash-based CSP for inline scripts.
security: { csp: 'auto' }config. Output as_headersfile.~~ ✅~~Dependency vulnerability scanning — Scan
node_modulesfor known vulnerabilities during build.pledge doctorincludes security audit. CVE database lookup.~~ ✅~~License compliance checking — Scan dependencies for license compatibility.
pledge doctor --licensesflag. Whitelist/blacklist license types in config.~~ ✅
Dev Experience
~~Error overlay with source maps~~ ✅ — Interactive error overlay in dev server showing original source code with error location. Stack trace mapping to original files. Auto-dismiss on HMR success. Runtime error catching via
window.errorandunhandledrejection.Build progress streaming — Real-time build progress over WebSocket in dev mode. Per-module transform status.
pledge devshows which modules are transforming.Config file hot reload — Reload
pledge.config.tschanges without restarting dev server. Watch config file and re-initialize engine on change.Friendly error messages with suggestions — Enhanced error messages with "Did you mean...?" for import paths, config fields, and CLI commands. Color-coded severity levels.
pledge whycommand — Analyze why a module is included in the bundle. Shows import chain from entry to target module.pledge why lodashoutput shows full dependency path.
Deployment & Output
~~Build output manifest~~ ✅ —
manifest.jsongenerated during build, mapping source files to output files with content-hashed filenames for cache busting.Docker image generation — Generate Dockerfile + .dockerignore for production deployment. Multi-stage build with minimal final image.
pledge build --dockerflag.Base path configuration —
base: '/my-app/'config for deploying under a subpath. All asset URLs and import paths adjusted automatically.~~CSS critical path extraction~~ ✅ —
extract_critical_css()analyzes HTML class/id/tag usage and filters CSS rules;inline_critical_css()injects the result into<head>.
Ecosystem & Extensibility
~~Plugin preset system —
presets: ['react', 'tailwind']config applies a bundle of plugins with sensible defaults. Community presets installable via npm.pledgepack-preset-*naming convention.~~ ✅~~Vite plugin compatibility layer — Run existing Vite plugins unmodified in pledgepack.
plugins: [{ vite: 'vite-plugin-svg' }]config. Automatic API translation.~~ ✅~~Rollup plugin adapter — Run Rollup plugins in pledgepack via compatibility shim.
plugins: [{ rollup: '@rollup/plugin-json' }]config. Widens plugin ecosystem instantly.~~ ✅~~Custom transformer pipeline —
transform: { pipeline: ['oxc', 'custom-transform', 'minify'] }config. Insert custom transform steps at any point in the pipeline. WASM or JS transformers.~~ ✅
Monorepo & Workspaces
~~Workspace-aware resolution — Auto-detect npm/pnpm/yarn workspaces. Resolve
@myorg/uito local workspace package, not npm registry.workspaces: trueconfig.~~ ✅~~Cross-package HMR — Hot reload changes in workspace packages and propagate to consuming app. No manual rebuild of dependent packages needed.~~ ✅
~~Shared build cache across workspace — Cache transform results in a shared
.pledge/at workspace root. All packages share the same cache directory. Faster incremental builds across packages.~~ ✅
Observability & Monitoring
~~Build telemetry dashboard~~ ✅ —
pledge dashboardserves a web UI showing build history, cache hit rates, module counts, and build times over time. Data persisted in.pledge/history.json.~~Bundle size budget CI integration~~ ✅ —
pledge build --check-budgetsexits non-zero on budget violations. GitHub Actions annotation format output. PR comment generation with size diff.~~Performance regression detection~~ ✅ — Compare build times across commits.
pledge bench --baseline <ref>flag. Warns when build time increases by more than configured threshold.~~Module dependency graph visualization~~ ✅ —
pledge analyze --graphgenerates interactive force-directed graph of module dependencies. Circular dependency detection highlighted in red.~~Build event webhooks~~ ✅ —
webhooks: { on_build: 'https://api.example.com/build-done' }config. POST build results to external service on completion. Slack/Discord notification support.
Internationalization & Accessibility
~~i18n-aware bundling~~ ✅ — Split bundles by locale.
i18n: { locales: ['en', 'fr', 'ja'], defaultLocale: 'en' }config. Only load current locale's strings.import messages from './messages.${locale}.json'pattern.~~RTL CSS auto-generation~~ ✅ — Auto-generate RTL CSS from LTR stylesheets using logical properties.
css: { rtl: 'auto' }config.direction: rtlsupport without manual CSS duplication.~~a11y linting during build~~ ✅ — Check for common accessibility issues in HTML output. Missing
altattributes, insufficient color contrast, missing ARIA labels.a11y: { enabled: true }config.~~Build-time string encryption~~ ✅ — Encrypt sensitive strings in source at build time, decrypt at runtime via injected shim.
encrypt: { keys: ['API_KEY'] }config. Prevents plain-text secrets in bundles.
Advanced Features
~~Web Components compilation~~ ✅ — Compile Custom Elements with Shadow DOM from
.wc.tsxfiles. AutomaticcustomElements.define()registration. Shadow DOM CSS scoping.~~Web Worker bundling~~ ✅ —
import worker from './worker.ts?worker'syntax. Bundle web workers as separate chunks with proper import URL generation.new Worker(new URL('./worker.ts', import.meta.url))pattern.~~Shared worker bundling~~ ✅ —
import worker from './worker.ts?sharedworker'syntax. Bundle shared workers accessible across multiple browser tabs. ProperSharedWorkerconstructor output.~~Service worker caching strategies~~ ✅ — Configurable caching per route pattern: cache-first, network-first, stale-while-revalidate.
sw: { caching: [{ pattern: '/api/*', strategy: 'network-first' }] }config. Extends existing SW generation.~~Import glob expansion~~ ✅ —
import.meta.glob('./pages/*.tsx')syntax. Expands to a map of file paths to lazy import functions at build time.glob: { eager: false }config for preloading all or lazy loading.~~Module federation support~~ ✅ — Share modules across independently deployed apps.
federation: { name: 'host', remotes: { app1: 'http://cdn/app1.js' } }config. Webpack Module Federation-compatible.~~GraphQL code generation~~ ✅ —
pledge build --codegengenerates TypeScript types from.graphqlfiles. Schema-first development with type-safe queries.graphql: { schema: 'schema.graphql' }config.~~Environment-specific builds~~ ✅ —
pledge build --env stagingloads.env.stagingand setsprocess.env.NODE_ENV = 'staging'. Multiple environment configs without code changes.~~Post-build optimization hooks~~ ✅ —
plugins: [{ name: 'seo', postBuild: true }]API. Plugins run after build to optimize HTML meta tags, generate sitemaps, or submit to search engines.~~Conditional exports resolution~~ ✅ — Read
package.jsonexportsfield with conditions.exports: { conditions: ['production', 'browser'] }config. Correct entry point per environment.~~Build concurrency control~~ ✅ —
build: { parallel: 4 }config limits concurrent module transforms. Prevents OOM on large projects. Auto-detects optimal concurrency based on CPU cores.
