Transform Function Contract
Every jssg codemod must export a default function with this exact signature:Transform Options
Theoptions
object provides execution context:
options.language: string
— language of the current file (e.g.,ts
,tsx
). Use it to branch logic or choose language‑sensitive patterns.options.params?: Record<string, string>
— user parameters defined in the workflow. Drive behavior switches, defaults, and environment‑specific choices.options.matches?: any[]
— pre‑filtered nodes from the exported selector (if any). Use to skip broad queries inside the transform.options.matrixValues?: Record<string, unknown>
— values from matrix strategy execution. Use for sharding, multi‑variant runs, or team‑scoped processing.
options.matches
contains nodes that matched your selector (when getSelector
is exported). Use them to short‑circuit or to avoid recomputing broad queries.Dynamic Parsing
Dynamic parsing allows you to parse and analyze different types of code within a single transform. This is particularly powerful when working with embedded languages like CSS-in-JS, HTML templates, or SQL queries within JavaScript code. Use dynamic parsing when your codemod needs to analyze multiple languages or when you’re working with template literals containing different syntax.Return Semantics
string
: Modified code (if identical to input, treated as unmodified)null
: No changes neededundefined
: Same as null- Other types: Runtime error
Parameters and Configuration
Parameters make your codemods flexible and reusable by allowing you to pass configuration values at runtime. This enables you to create codemods that adapt their behavior based on user input or different execution contexts.Enterprise Features: In the Codemod app, parameters are configured through a visual UI. The Codemod app provides centralized state management for large-scale refactoring across many repos.
options.params
.
How to pass params when executing your workflow:
Passing parameters (—param).
Matrix Strategy Integration
Matrix strategies enable you to run the same codemod with different configurations or to split large codebases into manageable chunks for parallel processing. Matrix values are particularly useful for:- Sharding: Distributing work across multiple processes or machines
- Multi-variant transforms: Running the same logic with different parameters
- Team-based processing: Applying different rules based on team ownership
Accessing Matrix Values
Access matrix values viaoptions.matrixValues
:
options.matrixValues
is only defined when your workflow uses a matrix strategy. Otherwise it is undefined
.Prefer checking sharding against a project-relative path (e.g.,
path.relative(process.cwd(), root.filename())
) to avoid mismatches across environments.Matrix Strategy Configuration
Matrix strategy is defined in your workflow:workflow.yaml
Parameters vs Matrix Values:
options.params
contains user-configured workflow settings, while options.matrixValues
contains values from matrix strategy (e.g., team
, shard
, shardId
from the shards
state array). See Matrix Strategy for details.Selectors (getSelector)
By default, jssg processes every file in your project, which can be inefficient for large codebases. When a selector is exported, you can pre-filter files based on specific patterns, so that the engine only calls your transform for files that match it.- jssg scans files using the selector before calling your transform
- Files without matches are skipped, reducing work
- Matched nodes are available via
options.matches
If the selector finds no matches in a file, your transform is not invoked for that file. This reduces both file processing and runtime initialization overhead. Prefer selectors for broad filtering; use
find
/findAll
inside the transform for precise node selection.State Management
State conveys execution context and progress signals across runs (e.g., total files, current progress) to coordinate large migrations.Persistent State Across Runs
jssg codemods can leverage persistent state for large-scale migrations:Common State Use Cases
- Sharding: Distribute files across multiple workers
- Progress tracking: Monitor migration progress
- Coordination: Coordinate between parallel tasks
- Resume capability: Resume interrupted migrations
Multi-Repo Orchestration
Use multi-repo orchestration when your codemod must coordinate changes across multiple repositories—such as updating shared libraries, enforcing consistency, or applying repo-specific logic. This approach streamlines large-scale migrations and ensures changes are applied uniformly.Advanced Pattern Composition
Rule References with Utils
Reference named sub‑rules inutils
and attach them via matches
to keep complex patterns DRY and composable.
Constraint System
Define reusable named fragments inconstraints
and reuse them across rules to centralize pattern logic.
Traversal Control
UsestopBy
to bound relational searches (e.g., to immediate neighbors or the end of a parent) for correctness and performance.
Best Practices
Consistent Patterns
- Use
const transform: Transform<TSX> = async (root, options) => {}
withexport default transform
- Import proper types - use
Transform
,GetSelector
, and language-specific types fromcodemod:ast-grep
- Handle edge cases - always check for null/undefined values and use try-catch for async operations
- Use early returns - skip processing when possible, especially for sharding
- Batch operations - collect edits before committing
- Export getSelector - provide a selector function for performance optimization
- Optimization strategies - prefer early returns, single traversals, and batching edits; use specific patterns to reduce backtracking and false positives
Enterprise Considerations
- Idempotent transforms: Ensure transforms can be run multiple times safely
- Progress reporting: Log progress for long-running migrations
- Error handling: Gracefully handle unexpected input
- Performance: Optimize for large codebases
- Coordination: Use state for multi-repo coordination
If you’re working on a large-scale enterprise migration, feel free to reach out to us to learn more about pro and enterprise plans and features.