swc4j

repository·main·Indexed 41 days ago

https://github.com/caoccao/swc4j

An ultra-fast JavaScript and TypeScript compilation, bundling, and sanitization tool for the JVM. Part of the Javet portfolio, it provides capabilities for AST manipulation, source map support, and code transpilation. It includes a ByteCodeCompiler to compile TypeScript directly to JVM bytecode and a sanitizer to enforce security restrictions on identifiers, built-in objects, and keywords.

Tokens
182.4K
Snippets
367
Records
624
Agent score
52%

What's inside swc4j

  1. Class implementation capabilities overview

    main

    The swc4j class implementation supports a wide range of TypeScript-to-JVM features:

    • Inheritance: Supports extends (superclass resolution, super.method() calls, and constructor chaining) and implements (multiple interface implementation).
    • Abstract Classes: Supports the ACC_ABSTRACT flag and abstract method declarations.
    • Access Modifiers: Supports public, private (TypeScript keyword), protected, and ES2022 private fields/methods (#field, #method).
    • Constructors: Supports parameter handling, field initialization, overloading, and constructor chaining (this() and super()).
    • Members: Supports instance fields, static fields, static methods, and explicit static blocks.
    • Generics: Implements type erasure to Object or constraint types.

    Note: Decorators are currently NOT supported as the compiler targets a subset of TypeScript without decorator metaprogramming.

  2. Supported Class Features and Limitations

    main

    swc4j supports a wide range of TypeScript and ECMAScript class features when transpiling to JVM bytecode.

    Supported Features

    • Inheritance: Single class inheritance (extends) and interface implementation (implements).
    • Abstract Classes: Support for abstract classes and abstract methods.
    • Constructors: Explicit constructors, constructor overloading, and constructor chaining using this() or super().
    • Fields: Instance fields, static fields, and explicit static blocks (static { ... }).
    • Access Modifiers: TypeScript private/protected keywords and ES2022 private members (#field, #method).
    • Generics: Supported via type erasure.

    Known Limitations

    • Decorators: Intentionally not supported.
    • Multiple Inheritance: Limited to single class inheritance due to JVM constraints.
    • Nested Classes: Support for inner classes may be limited.
    • Dynamic Class Loading: Not supported at compile time.
    • Generic Constraints: Supports simple constraints (e.g., T extends SomeType), but complex constraints may require fully qualified names.
  3. Explore swc4j Core Features

    main

    swc4j provides several core capabilities for working with JavaScript/TypeScript code:

    • AST (Abstract Syntax Tree) Manipulation: Inspect, navigate, and transform code using AST structures and visitor patterns.
    • Source Map Support: Parse and work with source maps to map generated code positions back to original source locations, including VLQ decoding and error location tracking.
    • Library Loading: Customize how native libraries are deployed and loaded, allowing for custom locations, skipping deployment for system libraries, and configuring via system properties.
  4. Explore swc4j features

    main

    swc4j includes advanced capabilities categorized into four main areas:

    Code Analysis & AST

    • AST: Understand the structure of the Abstract Syntax Tree.
    • AST Visitor: Implement custom code analysis or transformations using the visitor pattern.
    • Plugin: Create reusable plugins for code processing.

    Security & Sanitization

    Provides mechanisms to create safe JavaScript execution environments, including:

    • Built-in Object Protection: Prevent access to dangerous built-in objects.
    • Identifier Restriction/Freeze/Deletion: Control variable/function names and immutability.
    • Function/Keyword Restriction: Limit which functions can be called or which keywords are used.
    • Naming Convention: Enforce specific identifier naming rules.

    TypeScript to JVM Bytecode

    • Bytecode Compiler: Compiles TypeScript directly to JVM bytecode, bypassing the need for a JavaScript runtime. It supports classes, inheritance, interfaces, control flow, constructors, generics, and Java interop.

    Configuration & Deployment

    • Custom Library Loading: Control how native libraries are deployed, including custom paths, system library integration, and support for Docker/Kubernetes.
  5. Use Javet Sanitizer for JavaScript and TypeScript validation

    main
    Javet Sanitizer is a framework for parsing and validating JavaScript and TypeScript code on the JVM. It is built on top of swc4j and provides AST-level checkers to identify and eliminate potential security threats before code execution in Javet. It supports multiple formats including .js, .ts, .jsx, .tsx, .cjs, .mjs, .mts, .cts, .d.ts, .d.mts, .d.cts, .json, .tsbuildinfo, wasm, and source maps.
  6. Summary of TypeScript to JVM Bytecode capabilities

    main

    The TypeScript to JVM Bytecode compiler allows TypeScript code to be executed on the JVM by bridging TypeScript syntax to JVM bytecode.

    Supported Features:

    • Classes and Constructors
    • Inheritance and Interfaces
    • Control Flow
    • Fields
    • Generics
    • Enums
    • Interoperability with Java standard library classes
  7. What is a plugin host and how to use it

    main

    A plugin host is an interface that receives the AST program as input. When a plugin host is configured in Swc4jTranspileOptions or Swc4jTransformOptions, the corresponding parse(), transform(), or transpile() methods will invoke the host to modify the AST before generating output.

    Use the ISwc4jPluginHost interface to define custom logic. There is a built-in Swc4jPluginHost that manages a list of ISwc4jPlugin instances.

    public interface ISwc4jPluginHost {
        boolean process(ISwc4jAstProgram<?> program);
    }
  8. What is Javet Sanitizer?

    main
    Javet Sanitizer is a sanitizer framework designed for parsing and validating JavaScript and TypeScript code on the JVM. It is built on top of swc4j and provides a set of rich checkers at the AST (Abstract Syntax Tree) level for Javet. Its primary purpose is to allow applications to identify and eliminate potential security threats or policy violations before the JavaScript code is executed.
  9. What is a visitor plugin and how to implement one

    main

    A visitor plugin uses the ISwc4jAstVisitor interface to manipulate the AST at specific node levels. This provides a developer experience similar to Babel, where you can target specific node types (like assignment expressions or if statements) without managing the entire tree traversal manually.

    Use Swc4jPluginVisitors to hold and manage a list of these visitors.

  10. Edge cases for For Statement test conditions

    main

    The test condition (the middle expression) can involve complex logic:

    • No Test Condition: Results in an infinite loop (for (let i = 0; ; i++)).
    • Complex Boolean Logic: Using &&, ||, and ! operators.
    • Side Effects in Test: Expressions that modify state during the test evaluation (for (let i = 0; (x++) < 10; i++)).
    • Short-Circuiting: Ensuring that subsequent parts of a boolean expression are not evaluated if the first part fails.
    • Method Calls: Evaluating properties or methods (e.g., arr.length) on every iteration.
    for (let i = 0; i < 10 && check(i); i++) { }
  11. How String Switch Compilation Works

    main

    To support string-based switches, swc4j implements a three-phase approach similar to the JDK 17 compiler to handle hash collisions and maintain performance.

    The Three Phases:

    1. Phase 1 (Data Structure Building): Maps string case labels to their positions and groups strings by their hashCode() to handle potential collisions.
    2. Phase 2 (Hash Switch): Generates a lookupswitch based on the hashCode() of the input string. Inside each hash block, it performs an equals() check to verify the actual string value and assigns a sequential position index.
    3. Phase 3 (Position Switch): Generates a tableswitch using the sequential position indices to jump to the actual case bodies.

    This ensures that hash collisions are safely handled via .equals() and that the final jump is an $O(1)$ operation.

  12. Differences between while and for loop generation

    main

    When working with or extending the compiler, note these key differences between while and for loop implementations:

    FeatureWhile LoopFor Loop
    InitializationHandled externally (before the loop)Handled in an initialization section
    Update SectionHandled inside the bodyHandled in a dedicated update section
    StructureSimpler: only test and bodyMore complex: init, test, update, body
    Continue TargetJumps to the test labelJumps to the update label
    ScopeDoes not introduce new scopeCan introduce scope for loop variables