> ## Documentation Index
> Fetch the complete documentation index at: https://docs.codemod.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Upgrade a 1.x package

> Run a workflow.yaml codemod on the 2.0 CLI as it is, then convert it to workflow.ts with codemod workflow upgrade and check that it does the same thing.

You'll take a codemod package made with the 1.x CLI, run it on 2.0 unchanged, convert it to `workflow.ts`, and check that the result and its tests are the same. You need Node.js 22.18 or later and Git.

## 1. The 1.x package

This package is what `codemod init --project-type ast-grep-js` makes on 1.x, shortened: a `workflow.yaml` with one `js-ast-grep` step, a transform that turns `var` into `const`, and a fixture test.

```yaml workflow.yaml theme={null}
version: "1"

nodes:
  - id: apply-transforms
    name: Apply AST Transformations
    type: automatic
    steps:
      - name: "Scan matching typescript files and apply fixes"
        js-ast-grep:
          js_file: scripts/codemod.ts
          base_path: "."
          language: "typescript"
          include:
            - "**/*.{ts,tsx,mts,cts}"
          exclude:
            - "**/node_modules/**"
            - "**/dist/**"
            - "**/build/**"
```

```ts scripts/codemod.ts theme={null}
import type { Codemod } from "codemod:ast-grep";
import type TS from "codemod:ast-grep/langs/typescript";

const codemod: Codemod<TS> = async (root) => {
  const rootNode = root.root();
  const nodes = rootNode.findAll({ rule: { pattern: "var $VAR = $VALUE" } });
  const edits = nodes.map((node) => {
    const varName = node.getMatch("VAR")?.text();
    const value = node.getMatch("VALUE")?.text();
    return node.replace(`const ${varName} = ${value};`);
  });
  if (edits.length === 0) return null;
  return rootNode.commitEdits(edits);
};

export default codemod;
```

`codemod.yaml` points at the workflow with `path: workflow.yaml`, and `tests/fixtures/` holds an `input.js` and an `expected.js`. Put the package in a Git repository, and next to it a small project to run it on:

```ts app/src/index.ts theme={null}
var count = 1;
export var name = "app";
```

```bash theme={null}
(cd my-codemod && git init && git add . && git commit -m "1.x package")
(cd app && git init && git add . && git commit -m "Before the migration")
```

## 2. Run it on 2.0 as it is

```bash theme={null}
npx codemod@next workflow run -w ./my-codemod --target ./app --no-interactive
```

```
▸ Scan matching typescript files and apply fixes
✓ Scan matching typescript files and apply fixes (0.0s)
Done

Tip: to move this codemod to workflow.ts, run `codemod workflow upgrade my-codemod`.
```

```diff theme={null}
-var count = 1;
-export var name = "app";
+const count = 1;
+export const name = "app";
```

The CLI translated `workflow.yaml` to TypeScript in memory and ran that. The package didn't change. Registry packages run the same way: `npx codemod@next @org/my-1x-package`. The compatibility path supports legacy metrics and workflow state without rewriting the source.

Undo the change: `(cd app && git checkout -- .)`.

## 3. Preview the conversion

In the package directory:

```bash theme={null}
cd my-codemod
npx codemod@next workflow upgrade --dry-run
```

It shows every change it would make as a diff, and writes nothing:

```diff theme={null}
--- [before] codemod.yaml
+++ [after]  codemod.yaml
@@ -6,4 +6,4 @@
 workflows:
   - name: main
     default: true
-    path: workflow.yaml
+    path: workflow.ts
--- [before] workflow.ts
+++ [after]  workflow.ts
@@ -0,0 +1,32 @@
+// Generated from workflow.yaml by `codemod workflow upgrade`.
+import { parse } from "codemod/ast-grep";
+import { forEachFile, step } from "codemod/workflow";
+import type { WorkflowContext } from "codemod/workflow";
+import transform from "./scripts/codemod.ts";
+
+type Params = Record<string, string>;
+type JssgResult = string | { edit?: unknown, data?: unknown } | null | void;
+
+export default async function main({ params, target }: WorkflowContext<Params>) {
+  // Apply AST Transformations
+  await step(
+    "Scan matching typescript files and apply fixes",
+    forEachFile(
+      {
+        include: ["**/*.{ts,tsx,mts,cts}"],
+        exclude: ["**/node_modules/**", "**/dist/**", "**/build/**"],
+        language: "typescript",
+      },
+      async (file) => {
+        const result = await transform(parse(file), {
+          params,
+          language: "typescript",
+          targetDir: target,
+        }) as JssgResult;
+        if (typeof result === "string") return file.write(result);
+        if (typeof result?.edit === "string") file.write(result.edit);
+        return result?.data;
+      },
+    ),
+  );
+}
--- [before] workflow.yaml
+++ [after]  workflow.yaml
@@ -1,18 +0,0 @@
-version: "1"
-…
```

The node became a `step`, the `js-ast-grep` step became `forEachFile` with the same files, and the transform is imported and called for each file. Your transform doesn't change.

## 4. Convert

```bash theme={null}
npx codemod@next workflow upgrade
```

```
▸ Plan
✓ Plan (0.0s)
▸ Check
✓ Check (0.0s)
▸ Upgrade
✓ Upgrade (0.0s)
Done
✓ workflow.yaml -> workflow.ts
✓ updated codemod.yaml

Check the result with: codemod workflow validate -w /…/my-codemod
i Add codemod to package.json, so its scripts run that CLI and editors get the workflow types: npm install --save-dev codemod@2.0.0
```

The upgrade checks every package before it writes anything: if one can't be converted, nothing is written. The hint names the CLI version you ran, so the package gets 2.0 and not the `latest` tag, which is 1.x.

`git status` shows what it did: `workflow.ts` added, `workflow.yaml` removed (keep it with `--keep-yaml`), and `codemod.yaml` now says `path: workflow.ts`.

## 5. Check it

```bash theme={null}
npx codemod@next workflow validate -w .
```

```
─── Workflow `main` (./workflow.ts) ───
✅ Workflow builds
✅ forEachFile callbacks: Valid (1 extracted)
✅ Package validation successful
```

Run it on the project again. The diff is the same as in step 2:

```bash theme={null}
cd ..
npx codemod@next workflow run -w ./my-codemod --target ./app --no-interactive
(cd app && git diff --stat)
```

```
 src/index.ts | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
```

The transform's fixture test runs as before:

```bash theme={null}
cd my-codemod
npx codemod@next jssg test -l typescript ./scripts/codemod.ts
```

```
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
```

Commit the conversion. From here you can edit `workflow.ts` like any workflow: add steps, return a report, or [test the whole workflow](https://docs.codemod.com/community/workflows/testing.md).

> [!NOTE]
>
> 1.x's `codemod init` writes `npx codemod@latest jssg test` in `package.json`, and `@latest` is the 1.x CLI. Change it to `codemod jssg test`, and add `codemod` as a dev dependency, so the tests run with the CLI the package uses.

## Transforms that read files

1.x transforms often read the target with `fs`, directly or through a helper library. An upgraded workflow's transforms keep what they had on 1.x, inside the target: `fs` reads files, writes them (replacing a file that is there) and deletes them with `unlinkSync`. The writes and deletes are part of the step's diff. That allowance comes from a line of the generated file:

```ts theme={null}
// Generated from workflow.yaml by `codemod workflow upgrade`.
```

Keep that line among the comments the file starts with while the transforms still use `fs`; a license comment above it is fine. A `workflow.ts` without it, such as one you write yourself, refuses `fs`. Moving the transforms to `codemod/files` is optional; once they no longer import `fs`, you can delete the line.

## What `upgrade` can't convert for you

`upgrade` lists anything it can't translate exactly, and leaves a `// codemod upgrade:` comment where it was. The common ones:

* Transforms that use `codemod:metrics`: return the counts instead. See [Upgrade from 1.x](https://docs.codemod.com/community/workflows/upgrade-from-1x.md#metrics-are-now-return-values).
* Transforms that call `getState` or `setState`: pass values between steps instead.
* `runtime: docker` or `runtime: podman`: 2.0 refuses the workflow before running any steps. Keep running it with 1.x, or explicitly invoke the container from a `shell` step when you port it.
* Transforms that import `child_process`: an upgraded workflow's transforms can't start processes. `upgrade` refuses the package (see below); move the commands to a `shell` step first.

`upgrade` also refuses, and writes nothing, when:

* A workflow file is a symbolic link. Upgrade the file it points to, and point `codemod.yaml` at that file. A transform that is a symbolic link is refused too: put the file itself in its place.
* A transform, or a file of the package it imports, imports `child_process`. Its calls would fail only when they run, after `workflow.yaml` is gone, so the package stays on `workflow.yaml`.
* A file it would change is one its steps don't select, such as a transform a `.gitignore` ignores.
* Two workflows would become the same `.ts` file, or names that differ only in letter case (`Build.yaml` and `build.yaml`), which would overwrite each other on macOS and Windows.
* A support file it would add, such as `__codemod_v1/metrics.ts`, already exists with other contents.
* A transform would not load in 2.0. Before writing, `upgrade` loads every transform the new `workflow.ts` imports, as the workflow's steps will. When one fails, it names the transform and the import that stopped it, for example `scripts/codemod.ts does not load in 2.0: it imports 'node:net', which 2.0 workflows don't provide`, and the package stays on `workflow.yaml`. A transform that imports a package that isn't installed can't be checked: `upgrade` says so and converts the package anyway. Install the package's dependencies first to have it checked.

It lists every package it can't upgrade, not only the first, and exits with code `2`.

See [Migrate from workflow.yaml](https://docs.codemod.com/community/workflows/migrate.md) for how every YAML feature maps to TypeScript.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.