Skip to content

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) using oxc::parser::Parser, oxc::semantic::SemanticBuilder, oxc::transformer::Transformer, and oxc::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 bare readonly), abstract classes/members, legacy @decorator metadata (HelperLoaderMode::External), Stage-3 accessor auto-accessors (lower_auto_accessors_in_js), ES2026 using / await using resource blocks, and TypeScript import x = require(...) / export = ... (Module::CommonJS) at native Rust speeds (3x-5x faster than SWC, 40x+ faster than tsc). Identifier-boundary pre-checks (may_contain_ts_or_jsx) and program_has_ts_or_jsx ensure pure JavaScript returns Cow::Borrowed(source) directly (0 allocations, 0 Oxc Codegen, 0 line-map passes) while strip_typescript_checked_for_bundler fuses syntax validation and TypeScript stripping into a single Oxc parse per user module inside bundle_entrypoint_with_deps (-33% Oxc parses).
  • Native .tsx / .jsx Compilation: strip_typescript_and_normalize_with_ext selects SourceType::tsx() directly on .tsx/.jsx specifiers with transform_options.jsx.jsx_plugin = true, compiling JSX elements into zero-dependency slice:jsx (jsx, jsxs, Fragment, renderToString) calls on the first parse pass.
  • Plain .js Dependency Compaction & Unmodified [email protected] Intrinsic Acceleration: During bundle_entrypoint_with_deps, third-party .js files inside node_modules/ are passed through Oxc’s parser + minifying codegen (CodegenOptions::minify()), stripping all JSDoc blocks, license banners, and whitespace before bundling, while maybe_rewrite_unmodified_npm_cjs_module routes unmodified upstream [email protected] (node_modules/ms/index.js) through Slice’s zero-regex __slice_fast_ms native intrinsic (preserving custom or patched ms modules verbatim).

2. Type-Directed Oxc Semantic Lowering & AST Array Pipeline Fusion

Section titled “2. Type-Directed Oxc Semantic Lowering & AST Array Pipeline Fusion”
  • Before Oxc strips TypeScript types, slice-cas walks oxc::parser::Parser AST nodes (TSInterfaceDeclaration, TSTypeAnnotation, BindingPattern) and oxc::semantic::SemanticBuilder symbol tables, performing 100% AST-driven lowering:
    1. Extracts exact string / number / boolean property schemas from TSInterfaceDeclaration AST nodes and variable/parameter TSTypeAnnotation bindings without fragile line/colon text heuristics.
    2. Lowers unshadowed global Buffer.from(<arg>, <enc>?).toString("base64" | "base64url" | "utf8") and Buffer.byteLength(<arg>) via Oxc SemanticBuilder scope verification + AST CallExpression span replacement (rewrite_buffer_fast_paths_ast) directly to __slice_base64_encode, __slice_base64_decode, __slice_buf_to_utf8, and __slice_utf8_byte_len native Rust intrinsics without touching local/shadowed Buffer bindings, string literals, or comments.
    3. Collects all unshadowed require("<spec>") CallExpression string literal spans in a single Oxc AST + SemanticBuilder pass per module (collect_require_edits_from_program + slice_with_edits), eliminating per-statement Oxc parser re-invocations and duplicate CJS parses while preserving user-defined require parameters or bindings.
  • Standard TypeScript and JavaScript compilation delegates higher-order array and iterator operations (map, filter, reduce, some, every) directly to boa_engine’s ECMAScript-compliant intrinsics, guaranteeing exact sparse-array hole skipping, initial .length capture, custom receiver method dispatch, and multi-stage callback ordering.
  • For explicit source-to-source optimization workflows, slice-cas provides fuse_array_pipelines_ast, which selects collision-free temporary prefixes (choose_hygienic_fusion_prefix), rejects default parameter initializers and side-effecting multi-stage callbacks, guards Array.isArray + standard Array.prototype method 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:

  1. ESM-First package.json Conditional "exports", Subpath "imports" (#*), & tsconfig.json "paths" Resolution (resolve_module_specifier):
    • Resolves Node.js package.json Subpath "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" in package.json "exports" and top-level "module" before "main".
    • Selecting ESM entrypoints (dist/index.mjs, esm/index.js) exposes static import / export declarations 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), dynamic import("<spec>") (ImportExpression), top-level await (has_top_level_await), and __dirname / __filename bindings in a single Oxc AST pass.
  2. Oxc AST Cold-Method require Inliner (inline_cold_method_requires_ast):
    • Parses each CommonJS module with oxc::parser::Parser and inspects top-level var/const/let X = require("...") bindings.
    • If X is referenced exclusively inside cold class method bodies (never at top level, never in constructor, and never in hot dispatch methods fetch, route, dispatch, match, handle, run, exec), inlines require("...") directly into those cold method bodies and removes the top-level require declaration (while protecting non-computed class method/property keys via non_computed_key_spans).
    • Example impact: In hono’s HonoRequest class (request.js), body.js (parseBody) and url.js (tryDecodeURIComponent) are only used inside .parseBody(), .param(), and .query(), so they are never eagerly evaluated during basic request routing.
  3. 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>) vs UsedExports::All) in reverse topological order from the entrypoint down to leaf node_modules dependencies:
      • Tracks const { a, b: alias } = require("mod") (ObjectPattern) and const ns = require("mod"); ns.foo() (StaticMemberExpression property accesses).
    • Inside prune_and_minify_cjs_module_ast:
      • Removes unused exports.<Unused> = ... assignments and unused Object.defineProperty(exports, "<Unused>", ...) live-getter exports while preserving non-enumerable Object.defineProperty(exports, "__esModule", { value: true }) namespace metadata (ESM lowering binds default exports on exports.default without ever aliasing or mutating user objects via module.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 destructured require(...) properties.
      • Emits the pruned AST with oxc::codegen::Codegen::new().with_options(CodegenOptions::minify()).
  4. 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 via new Function if dynamically required at runtime, skipping Boa lexing and AST construction for all cold transitive modules on startup.

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 .cas archive 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\x01 Precompiled Boa CodeBlock CAS (boacas = true) & Single-Copy CAS Deduplication (CasBuilder::add_module):
    • By default (boacas = true), compile_source_to_bytecode packs bundled JavaScript into a 32-byte BoaCasHeader (SLICEBC\x01) + SLCB\x01 recursive CodeBlock binary image (crates/slice-engine/src/vm/boacas.rs, vendor/boa_engine/SLICE_PATCH.md) with pre-fused runtime prelude shards and node:* built-in scripts.
    • When a code module’s (!is_static && !is_manifest) compiled bytecode is SLICEBC\x01 or SLICEBOA, CasBuilder::write_to_file writes only the 64B-aligned bytecode_bytes into data_payload and aliases source_offset directly into the embedded fallback UTF-8 slice inside bytecode_bytes (static:/ assets preserve their exact MIME string even if asset bytes start with SLICEBC\x01/SLICEBOA, and ingest_directory skips .d.ts/.d.mts/.d.cts declarations while protecting exact entrypoint stems across sibling extensions).
  • Pre-Indexed O(1) Blob Table, Relative Specifier Resolution, & open_detached (MappedCasArchive): At archive open time, MappedCasArchive::from_mmap_region validates all checked usize offsets/lengths, pre-faults bytecode mmap pages, and constructs a contiguous blobs_vec: Vec<CasBlobEntry> + specifier_index: FxHashMap<String, u32> so resolve_specifier and resolve_specifier_from (./, ../, .js->.ts, /index, rejecting .. above root and static://manifest:/ non-code blobs) execute in a single hash lookup with 0 stat() or read() syscalls. For --tenant-dir hot-swap on Windows, MappedCasArchive::open_detached maps into an anonymous read-only Mmap and closes the OS file handle immediately so in-place <tenant>.cas overwrites never trigger ERROR_USER_MAPPED_FILE (1224).
  • Self-Contained Executables (SLICEEXE): embed_cas_into_executable inspects inspect_sliceexe_trailer (cas_end <= file_len - 24) to strip any prior embedded .cas payload on re-pack before streaming the base slice binary and .cas archive through bounded 256 KB BufReader/BufWriter buffers into an atomic staging executable followed by a 24-byte trailer ([u64 cas_offset][u64 cas_len][b"SLICEEXE"]). On startup, MappedCasArchive::open_embedded_self seeks and validates only the 24-byte EOF trailer first and memory-maps std::env::current_exe() only when b"SLICEEXE" is valid.
  • Per-Blob Source-Line Table (CasIndexHeader.blob_source_map_markers & Linear compute_source_line_map): compute_source_line_map builds bounded <= 256-byte prefix and 2/3-token FxHashMap anchor indices in strictly linear O(|raw_src| + |cjs_body|) time. CasBuilder::write_to_file scopes source-map markers per blob hash (blob_source_map_markers) so MappedCasArchive::reconstruct_annotated_source and map_bundled_error_location map uncaught exceptions back to their exact 1-based TypeScript file.ts:line across both single-blob and multi-blob .cas / SLICEEXE archives.
  • Zero-Stat Static Asset Table (StaticAssetTable): Pre-computes BLAKE3 ETag headers and MIME classifications at pack time for instant 304 Not Modified edge asset serving.