slice-cas: Zero-Stat Content-Addressed Storage, Oxc Compiler & AST Tree-Shaker
crates/slice-cas shifts all module resolution, TypeScript/JSX compilation, hygienic ESM/CJS linking, dead-export elimination, and cold-method require deferring from runtime to build/pack time (slice pack / slice compile).
1. Production Rust TypeScript & JSX/TSX Compilation via Oxc (v0.160.0)
Section titled “1. Production Rust TypeScript & JSX/TSX Compilation via Oxc (v0.160.0)”- Implemented in
strip_typescript_raw(compiler/mod.rs,compiler/ts_helpers.rs,compiler/comments.rs) usingoxc::parser::Parser,oxc::semantic::SemanticBuilder,oxc::transformer::Transformer, andoxc::codegen::Codegen. - Arena-Allocated Single-Pass Parsing, Zero-Codegen Pure-JS Fast Path, & Transformation: Oxc parses ASTs in a bump-allocated memory arena (
oxc::allocator::Allocator) and strips TypeScript interfaces, type aliases, generics, parameter properties (including barereadonly), abstract classes/members, legacy@decoratormetadata (HelperLoaderMode::External), Stage-3accessorauto-accessors (lower_auto_accessors_in_js), ES2026using/await usingresource blocks, and TypeScriptimport x = require(...)/export = ...(Module::CommonJS) at native Rust speeds (3x-5x faster than SWC, 40x+ faster thantsc). Identifier-boundary pre-checks (may_contain_ts_or_jsx) andprogram_has_ts_or_jsxensure pure JavaScript returnsCow::Borrowed(source)directly (0allocations,0OxcCodegen,0line-map passes) whilestrip_typescript_checked_for_bundlerfuses syntax validation and TypeScript stripping into a single Oxc parse per user module insidebundle_entrypoint_with_deps(-33%Oxc parses). - Native
.tsx/.jsxCompilation:strip_typescript_and_normalize_with_extselectsSourceType::tsx()directly on.tsx/.jsxspecifiers withtransform_options.jsx.jsx_plugin = true, compiling JSX elements into zero-dependencyslice:jsx(jsx,jsxs,Fragment,renderToString) calls on the first parse pass. - Plain
.jsDependency Compaction & Unmodified[email protected]Intrinsic Acceleration: Duringbundle_entrypoint_with_deps, third-party.jsfiles insidenode_modules/are passed through Oxc’s parser + minifying codegen (CodegenOptions::minify()), stripping all JSDoc blocks, license banners, and whitespace before bundling, whilemaybe_rewrite_unmodified_npm_cjs_moduleroutes unmodified upstream[email protected](node_modules/ms/index.js) through Slice’s zero-regex__slice_fast_msnative intrinsic (preserving custom or patchedmsmodules verbatim).
2. Type-Directed Oxc Semantic Lowering & AST Array Pipeline Fusion
Section titled “2. Type-Directed Oxc Semantic Lowering & AST Array Pipeline Fusion”2.1 Type-Directed Oxc Semantic Lowering (analyze_typescript_semantics)
Section titled “2.1 Type-Directed Oxc Semantic Lowering (analyze_typescript_semantics)”- Before Oxc strips TypeScript types,
slice-caswalksoxc::parser::ParserAST nodes (TSInterfaceDeclaration,TSTypeAnnotation,BindingPattern) andoxc::semantic::SemanticBuildersymbol tables, performing 100% AST-driven lowering:- Extracts exact
string/number/booleanproperty schemas fromTSInterfaceDeclarationAST nodes and variable/parameterTSTypeAnnotationbindings without fragile line/colon text heuristics. - Lowers unshadowed global
Buffer.from(<arg>, <enc>?).toString("base64" | "base64url" | "utf8")andBuffer.byteLength(<arg>)via OxcSemanticBuilderscope verification + ASTCallExpressionspan replacement (rewrite_buffer_fast_paths_ast) directly to__slice_base64_encode,__slice_base64_decode,__slice_buf_to_utf8, and__slice_utf8_byte_lennative Rust intrinsics without touching local/shadowedBufferbindings, string literals, or comments. - Collects all unshadowed
require("<spec>")CallExpressionstring literal spans in a single Oxc AST +SemanticBuilderpass per module (collect_require_edits_from_program+slice_with_edits), eliminating per-statement Oxc parser re-invocations and duplicate CJS parses while preserving user-definedrequireparameters or bindings.
- Extracts exact
2.2 Opt-In Hygienic Oxc AST Array Pipeline Fusion (fuse_array_pipelines_ast)
Section titled “2.2 Opt-In Hygienic Oxc AST Array Pipeline Fusion (fuse_array_pipelines_ast)”- Standard TypeScript and JavaScript compilation delegates higher-order array and iterator operations (
map,filter,reduce,some,every) directly toboa_engine’s ECMAScript-compliant intrinsics, guaranteeing exact sparse-array hole skipping, initial.lengthcapture, custom receiver method dispatch, and multi-stage callback ordering. - For explicit source-to-source optimization workflows,
slice-casprovidesfuse_array_pipelines_ast, which selects collision-free temporary prefixes (choose_hygienic_fusion_prefix), rejects default parameter initializers and side-effecting multi-stage callbacks, guardsArray.isArray+ standardArray.prototypemethod identity at runtime, snapshots.length >>> 0, and skips sparse array holes (!(i in arr)).
3. ESM-First Conditional "exports" & General-Purpose Oxc Semantic/AST Tree-Shaker
Section titled “3. ESM-First Conditional "exports" & General-Purpose Oxc Semantic/AST Tree-Shaker”Implemented across crates/slice-cas/src/bundler/resolver.rs and crates/slice-cas/src/linker/mod.rs with zero package-specific or framework-specific rules:
- ESM-First
package.jsonConditional"exports", Subpath"imports"(#*), &tsconfig.json"paths"Resolution (resolve_module_specifier):- Resolves Node.js
package.jsonSubpath"imports"(#internal/*,#config) with exact, wildcard (*), and conditional target support (resolve_package_imports). - Resolves JSONC-comment-tolerant
tsconfig.json/jsconfig.json"compilerOptions.paths"and"compilerOptions.baseUrl"aliases (@/*,~/*, including"extends"base config inheritance) (resolve_tsconfig_paths). - Prioritizes
"workerd","worker","edge-light","import","module","browser","require","node", and"default"inpackage.json"exports"and top-level"module"before"main". - Selecting ESM entrypoints (
dist/index.mjs,esm/index.js) exposes staticimport/exportdeclarations to Oxc’s AST linker across all modern npm packages (hono,itty-router,ufo,radix3,destr,ohash,cookie,flatted,zod, etc.). - Lowers
import.meta(url,dirname,filename,env), dynamicimport("<spec>")(ImportExpression), top-levelawait(has_top_level_await), and__dirname/__filenamebindings in a single Oxc AST pass.
- Resolves Node.js
- Oxc AST Cold-Method
requireInliner (inline_cold_method_requires_ast):- Parses each CommonJS module with
oxc::parser::Parserand inspects top-levelvar/const/let X = require("...")bindings. - If
Xis referenced exclusively inside cold class method bodies (never at top level, never inconstructor, and never in hot dispatch methodsfetch,route,dispatch,match,handle,run,exec), inlinesrequire("...")directly into those cold method bodies and removes the top-levelrequiredeclaration (while protecting non-computed class method/property keys vianon_computed_key_spans). - Example impact: In
hono’sHonoRequestclass (request.js),body.js(parseBody) andurl.js(tryDecodeURIComponent) are only used inside.parseBody(),.param(), and.query(), so they are never eagerly evaluated during basic request routing.
- Parses each CommonJS module with
- Reverse-Topological Oxc Semantic Scope-Resolved Dead-Export Tree-Shaker (
analyze_module_used_exports&prune_and_minify_cjs_module_ast):- Computes used export sets (
UsedExports::Named(FxHashSet<String>)vsUsedExports::All) in reverse topological order from the entrypoint down to leafnode_modulesdependencies:- Tracks
const { a, b: alias } = require("mod")(ObjectPattern) andconst ns = require("mod"); ns.foo()(StaticMemberExpressionproperty accesses).
- Tracks
- Inside
prune_and_minify_cjs_module_ast:- Removes unused
exports.<Unused> = ...assignments and unusedObject.defineProperty(exports, "<Unused>", ...)live-getter exports while preserving non-enumerableObject.defineProperty(exports, "__esModule", { value: true })namespace metadata (ESM lowering binds default exports onexports.defaultwithout ever aliasing or mutating user objects viamodule.exports). - Runs an iterative fixed-point pass using
oxc::semantic::SemanticBuilder(scoping.get_resolved_reference_ids(sym_id).is_empty()), which uses Oxc’s full ECMAScript lexical scope resolver so shadowed single-letter local variables (e,t,s,n,r) inside live functions never false-keep dead top-level declarators, functions, classes, or destructuredrequire(...)properties. - Emits the pruned AST with
oxc::codegen::Codegen::new().with_options(CodegenOptions::minify()).
- Removes unused
- Computes used export sets (
- Eager-Edge BFS Lazy Module Stringifier (
collect_eager_module_indices):- Performs a breadth-first traversal of top-level eager
require(id)calls starting from the entrypoint. - Modules on the eager startup path are emitted as direct function expressions (
__slice_modules[id] = function(module,exports,require){...}), while cold modules are emitted as JSON string literals (__slice_modules[id] = "...") that are only compiled vianew Functionif dynamically required at runtime, skippingBoalexing and AST construction for all cold transitive modules on startup.
- Performs a breadth-first traversal of top-level eager
4. 64-Byte Cache-Line Aligned SLICE_CAS v1 Binary Format, Default SLICEBC\x01 Precompiled CodeBlock, & SLICEEXE
Section titled “4. 64-Byte Cache-Line Aligned SLICE_CAS v1 Binary Format, Default SLICEBC\x01 Precompiled CodeBlock, & SLICEEXE”- Every module blob in a
.casarchive is hashed with SIMD-accelerated BLAKE3-256 (blake3::hash) and padded to a strict 64-byte boundary (CACHE_LINE_ALIGN = 64):+-----------------------------------------------------------------------+| 0..8 : Magic Bytes b"SLICECAS" || 8..16 : Version (u32 = 1) + Reserved Flags (u32 = 0) || 16..24 : JSON Radix Header Length (u64 LE) || 24..32 : 64-Byte Aligned Data Payload Start Offset (u64 LE) || 32..N : CasIndexHeader (Radix Map: Specifier -> BLAKE3 -> Offsets) || [Padding to 64-byte CPU cache-line boundary] || Data : [64B-aligned Source/Bytecode Slice] ... |+-----------------------------------------------------------------------+ - Default
SLICEBC\x01Precompiled BoaCodeBlockCAS (boacas = true) & Single-Copy CAS Deduplication (CasBuilder::add_module):- By default (
boacas = true),compile_source_to_bytecodepacks bundled JavaScript into a 32-byteBoaCasHeader(SLICEBC\x01) +SLCB\x01recursiveCodeBlockbinary image (crates/slice-engine/src/vm/boacas.rs,vendor/boa_engine/SLICE_PATCH.md) with pre-fused runtime prelude shards andnode:*built-in scripts. - When a code module’s (
!is_static && !is_manifest) compiled bytecode isSLICEBC\x01orSLICEBOA,CasBuilder::write_to_filewrites only the 64B-alignedbytecode_bytesintodata_payloadand aliasessource_offsetdirectly into the embedded fallback UTF-8 slice insidebytecode_bytes(static:/assets preserve their exact MIME string even if asset bytes start withSLICEBC\x01/SLICEBOA, andingest_directoryskips.d.ts/.d.mts/.d.ctsdeclarations while protecting exact entrypoint stems across sibling extensions).
- By default (
- Pre-Indexed
O(1)Blob Table, Relative Specifier Resolution, &open_detached(MappedCasArchive): At archive open time,MappedCasArchive::from_mmap_regionvalidates all checkedusizeoffsets/lengths, pre-faults bytecodemmappages, and constructs a contiguousblobs_vec: Vec<CasBlobEntry>+specifier_index: FxHashMap<String, u32>soresolve_specifierandresolve_specifier_from(./,../,.js->.ts,/index, rejecting..above root andstatic://manifest:/non-code blobs) execute in a single hash lookup with0stat()orread()syscalls. For--tenant-dirhot-swap on Windows,MappedCasArchive::open_detachedmaps into an anonymous read-onlyMmapand closes the OS file handle immediately so in-place<tenant>.casoverwrites never triggerERROR_USER_MAPPED_FILE(1224). - Self-Contained Executables (
SLICEEXE):embed_cas_into_executableinspectsinspect_sliceexe_trailer(cas_end <= file_len - 24) to strip any prior embedded.caspayload on re-pack before streaming the baseslicebinary and.casarchive through bounded256 KBBufReader/BufWriterbuffers into an atomic staging executable followed by a 24-byte trailer ([u64 cas_offset][u64 cas_len][b"SLICEEXE"]). On startup,MappedCasArchive::open_embedded_selfseeks and validates only the 24-byte EOF trailer first and memory-mapsstd::env::current_exe()only whenb"SLICEEXE"is valid. - Per-Blob Source-Line Table (
CasIndexHeader.blob_source_map_markers& Linearcompute_source_line_map):compute_source_line_mapbuilds bounded<= 256-byte prefix and 2/3-tokenFxHashMapanchor indices in strictly linearO(|raw_src| + |cjs_body|)time.CasBuilder::write_to_filescopes source-map markers per blob hash (blob_source_map_markers) soMappedCasArchive::reconstruct_annotated_sourceandmap_bundled_error_locationmap uncaught exceptions back to their exact 1-based TypeScriptfile.ts:lineacross both single-blob and multi-blob.cas/SLICEEXEarchives. - Zero-Stat Static Asset Table (
StaticAssetTable): Pre-computesBLAKE3ETagheaders and MIME classifications at pack time for instant304 Not Modifiededge asset serving.