# RudderTyper v1


[RudderTyper](https://github.com/rudderlabs/rudder-typer) is a tool that lets you generate strongly-typed RudderStack analytics library wrappers based on your [Tracking Plan]({{< ref "data-governance/tracking-plans/" >}}). It uses an event from your specified Tracking Plan and generates an analytics call in the supported languages.

{{< warning >}}
RudderTyper v1 (npm) is in maintenance mode and will not receive new features. 

For Kotlin (Android/JVM) and Swift (iOS) support and the actively maintained version, see [RudderTyper v2]({{< ref "dev-tools/rudder-cli/ruddertyper-v2.md" >}}).
{{< /warning >}}

{{< version-badge registry="npm" package="rudder-typer" fallback="1.7.5" href="https://www.npmjs.com/package/rudder-typer/" >}}

{{<badge label="Node.js" message="v20.x" color="7447fc" link="https://github.com/rudderlabs/rudder-typer/" target="_blank">}}

<br /><br />

{{< image src="images/readme-example.gif" alt="RudderTyper in action" >}}

## Overview

The following steps give a high-level overview of how RudderTyper works:

1. RudderTyper generates type-safe SDK code from a Tracking Plan by parsing it to understand the events and data types. 
2. It then creates platform-specific classes and methods that match the Tracking Plan, ensuring that only valid events and properties are used.
3. Finally, it integrates this code into the SDKs and provides compile-time checks to catch any errors and ensure consistency in the tracking implementation.

{{< info >}}
RudderTyper currently generates native clients for the following SDKs:

- [JavaScript]({{< ref "sources/event-streams/sdks/rudderstack-javascript-sdk/_index.md" >}})
- [Android (Java)]({{< ref "sources/event-streams/sdks/rudderstack-android-sdk/_index.md" >}})
- [iOS (Obj-C)]({{< ref "sources/event-streams/sdks/rudderstack-ios-sdk/_index.md" >}})
- [Node.js]({{< ref "sources/event-streams/sdks/rudderstack-node-sdk.md" >}})
{{< /info >}}

### CLI integration

RudderStack also offers type-safe code generation through the [Rudder CLI tool]({{< ref "dev-tools/rudder-cli/ruddertyper-v2.md" >}}):

```bash
rudder-cli typer generate --tracking-plan-id <ID> --platform kotlin -o ./generated
```

The CLI-based typer currently supports **Kotlin** for Android. For JavaScript, TypeScript, Java, and Objective-C, use the npm-based RudderTyper documented below.

See [RudderTyper v2]({{< ref "dev-tools/rudder-cli/ruddertyper-v2.md" >}}) for details.

## Key features

- Displays compile-time errors and warns you about any missing required properties, data mismatch, and any issues in the JSON schema configured in your Tracking Plan.
- Lets you contextualize your analytics instrumentation and validate it with your event spec before deploying it to production.
- Lets you access and validate your event names, properties, types, etc.

## Get started

The following sections will help you set up and use RudderTyper to generate your first client.

### Prerequisites

- Make sure your [Node version](https://nodejs.org/en/about/previous-releases) is v20.x or above
- Clone the [RudderTyper repository](https://github.com/rudderlabs/rudder-typer) in your preferred location
- Generate a [workspace-level Service Access Token]({{< ref "access-management/service-access-tokens.md#workspace-sat" >}}) in your RudderStack workspace

{{< info >}}
The workspace-level Service Access Token has **Read** permissions by default. You do not need to assign any [resource permissions]({{< ref "access-management/policies-overview.md#resource-permissions" >}}) while generating the token.
{{< /info >}}

#### Token permissions for legacy RBAC system

If you are on the [legacy Permissions Management (RBAC) system]({{< ref "archive/dashboard-guides/user-management.md" >}}), your workspace-level Service Access Token should have **Viewer** permission.

See [this documentation]({{< ref "archive/dashboard-guides/service-access-tokens.md#generate-service-access-token" >}}) for more information on generating the token.

{{< image src="images/access-management/permissions/legacy/viewer.webp" alt="workspace-level Service Access Token with Viewer permission" >}}

### Quickstart

The following steps highlight the process of creating a `ruddertyper.yml` file and generate your first RudderTyper client with the specified configuration details:

1. Run the following command to initialize RudderTyper:

```bash
$ npx rudder-typer init  # Or initialize or quickstart
```

2. Choose the SDK type for your RudderTyper client - you can use the up/down arrow key to navigate through the options.

{{< image src="images/dev-tools/ruddertyper/choose-sdk.webp" alt="Choose SDK for RudderTyper client" >}}

3. Choose the appropriate language and continue. The following image shows the language options for the Web SDK:

{{< image src="images/dev-tools/ruddertyper/choose-language.webp" alt="Choose language option" >}}

4. Enter the [workspace-level Service Access Token](#prerequisites) generated above. RudderTyper uses this token to fetch all the Tracking Plans present in your workspace.

5. Choose the Tracking Plan for which RudderTyper generates the client - this plan is automatically saved locally in a `plan.json` file.

{{< image src="images/dev-tools/ruddertyper/tracking-plan.webp" alt="Choose Tracking Plan" >}}

6. Choose the RudderTyper mode. You will see two options - `Production` or `Development`.  See [RudderTyper modes](#ruddertyper-modes) for more information on each mode.

7. Specify the directory to store the generated RudderTyper client. You can choose an existing directory or create a new one, depending on your requirement.

{{< image src="images/dev-tools/ruddertyper/specify-directory.webp" alt="Choose directory to store the client" >}}

8. Review the settings and select **Looks good!** to complete the process. You can select **Edit** to make any changes to the above steps.

{{< image src="images/dev-tools/ruddertyper/review.webp" alt="Review settings" >}}

RudderTyper then generates the client based on your configuration settings and stores it in the specified directory. See [Configuration reference](#configuration-reference) for more information on the `ruddertyper.yml` file structure.

{{< image src="images/dev-tools/ruddertyper/client-generate.webp" alt="Generated RudderTyper client" >}}

#### Troubleshooting

- If you get an error during the setup process, run the following commands to clear your cache and local storage:

```bash
npm cache clean --force
rm -r ~/.ruddertyper
```

- If you get a "Your workspace does not have any Tracking Plans" error during the setup, verify that your RudderTyper client is on a stable version (v1.x).

## Commands

<table>
    <thead>
        <tr>
            <th>Command</th>
            <th><div style="width:250px">Description</div></th>
        </tr>
    </thead>
    <tbody>
    <tr>
            <td>Initialize<br /><br /><pre>$ npx rudder-typer init</pre></td>
            <td>Initializes RudderTyper with a quickstart guide to generate your RudderTyper client .</td>
        </tr>
    <tr>
            <td>Help<br /><br /><pre>$ npx rudder-typer help</pre></td>
            <td>Prints the help message describing different commands available with RudderTyper.</td>
        </tr>
        <tr>
            <td>Update plan<br /><br /><pre>$ npx rudder-typer update | u | *   (default)</pre></td>
            <td>Syncs <code class="inline-code">plan.json</code> with RudderStack to pull the latest changes from your Tracking Plan and generates an updated development client.</td>
        </tr>
        <tr>
            <td>Build development client<br /><br /><pre>$ npx rudder-typer build | b | d | dev | development</pre></td>
            <td>Generates a development client from <code class="inline-code">plan.json</code> with runtime validation.</td>
        </tr>
        <tr>
            <td>Build production client<br /><br /><pre>$ npx rudder-typer prod | p | production</pre></td>
            <td>Generates a production client from <code class="inline-code">plan.json</code> without runtime validation .</td>
        </tr>
        <tr>
            <td>Print token configuration<br /><br /><pre>$ npx rudder-typer token | tokens | t</pre></td>
            <td>Prints the local RudderStack API token configuration.</td>
        </tr>
        <tr>
            <td>Print RudderTyper version<br /><br /><pre>$ npx rudder-typer version</pre></td>
            <td>Prints the RudderTyper CLI version.</td>
        </tr>
    </tbody>
</table>


## CLI arguments

Run the help command (`npx rudder-typer help`) to get the below list of CLI arguments that you can use with RudderTyper:

| Argument  | Description |
| :-------- | :-------- | 
| `config`  | Optional path to a `ruddertyper.yml` \(or a directory with `ruddertyper.yml`\). |
| `debug`   | Optional \(hidden\) flag to turn on/off debug mode. |
| `version` / `v` | Prints the RudderTyper CLI version.  |
| `help` / `h` | Prints help on a command. |

## RudderTyper modes

RudderTyper operates in two distinct modes: **Development** and **Production** mode. Each mode serves a specific purpose in the analytics implementation workflow. By utilizing the required mode, you can streamline the process of implementing and managing analytics with RudderTyper.

#### Development mode

This mode is designed to facilitate testing and validating your changes before the events go live.

This mode is suitable for local development and debugging and helps you:

- Validate the JSON schema to ensure correctness.
- Verify the tracking events against the defined Tracking Plan.
- Include additional validation logic to catch potential errors early.

#### Production mode

This mode is optimized for deployment and ensures seamless event tracking in live environments.

This mode is suitable for staging and production environments and helps you:

- Generate production-ready, optimized code.
- Adhere strictly to the validated schema to maintain consistency.
- Remove unnecessary validation and debugging logic for efficiency.

## Configuration reference

RudderTyper stores its configuration in a `ruddertyper.yml` file in the root of your repository.

A sample configuration looks like the following:

```yaml
# RudderStack RudderTyper configuration reference (https://github.com/rudderlabs/rudder-typer)
# Run `npx rudder-typer` to regenerate a client with the latest versions of these events.

scripts:
  # You can supply a RudderStack service access token using a `scripts.token` command. The output of `script.token` command should be a valid RudderStack API token.
  token: source .env; echo $RUDDERTYPER_TOKEN

  # You can supply the email address linked to your workspace using a `scripts.email` command.The output of `script.email` command should be an email address registered with your workspace.
  email: source .env; echo $EMAIL

  # You can format any of RudderTyper's auto-generated files using a `scripts.after` command.
  # See `Formatting Generated Files` below.
  after: ./node_modules/.bin/prettier --write analytics/plan.json

client:
  # The RudderStack SDK you are generating the client for
  # Valid values: analytics.js, analytics-node, analytics-ios, analytics-android.
  sdk: analytics.js

  # The target language for your RudderTyper client.
  # Valid values: javascript, typescript, objective-c, swift, java.
  language: typescript

  # JavaScript Transpilation Settings
  # Valid values: 'ES3','ES5','ES2015','ES2016','ES2017','ES2018','ES2019','ESNext','Latest'
  scriptTarget: "ES5"

  # Valid values: 'CommonJS','AMD','UMD','System','ES2015','ESNext'
  moduleTarget: "ESNext"

trackingPlans:
  # The RudderStack Tracking Plan that you are generating a client for.
  # Provide your workspace slug and Tracking Plan id
  # You also need to supply a path to a directory to save your RudderTyper client.
  - id: <TRACKING_PLAN_ID>
    workspaceSlug: rudderstack-demo
    path: ./analytics

    # Valid values: v1 (old Tracking Plan), v2 (new Tracking Plan format)
    APIVersion: v2
```

Note the following:

- Store `token` and `email`  in a `.env` file created in the same directory as `ruddertyper.yml` to ensure the scripts automatically use these values. A sample `.env` file is shown below:

```txt
RUDDERTYPER_TOKEN=<SERVICE_ACCESS_TOKEN>
EMAIL=<EMAIL_ADDRESS>
```

- You can get the `id` field by going to the Tracking Plan in the RudderStack dashboard. For example, `https://app.rudderstack.com/trackingPlans/<TRACKING_PLAN_ID>`.

## Integrate RudderTyper client with SDK

This section includes the steps to integrate your RudderTyper-generated client with your app across different RudderStack SDKs.

{{< tabs tabTotal="4" >}}
{{% tab tabName="Android (Java) — Legacy" %}}
1. Import all files in the client generated by RudderTyper as a package in your project.
2. Make the calls using the RudderTyper client, as shown:

```java
// Import your auto-generated RudderTyper client:
import com.rudderstack.generated.*

  // Issue your first RudderTyper track call
  RudderTyperAnalytics.with(this).orderCompleted(
    OrderCompleted.Builder()
    .orderID("ck-f306fe0e-cc21-445a-9caa-08245a9aa52c")
    .total(39.99)
    .build()
  );
```
{{% /tab %}}
{{% tab tabName="iOS (Obj-C) — Legacy" %}}
1. Import your RudderTyper client into your project using XCode.

{{< warning >}}
If you place the generated files into a folder within your
project, import the project as a group, **not** as a folder reference.
{{< /warning >}}

2. Make the calls using the RudderTyper client, as shown:

```objectivec
// Import your auto-generated RudderTyper client:
#import "RSRudderTyperAnalytics.h"

// Issue your first RudderTyper track call
[RSRudderTyperAnalytics orderCompletedWithOrderID: "ck-f306fe0e-cc21-445a-9caa-08245a9aa52c" total: @39.99];
```
{{% /tab %}}
{{% tab tabName="JavaScript" %}}

There are two ways to get started with RudderTyper in your browser:

### Using JavaScript SDK snippet

1. Paste the [JavaScript SDK snippet]({{< ref "sources/event-streams/sdks/rudderstack-javascript-sdk/quickstart.md#using-cdn" >}}) from the RudderStack dashboard in your HTML file.
2. If you use TypeScript, add `@rudderstack/analytics-js` as a dev dependency:

```bash
npm install --save-dev  @rudderstack/analytics-js
```

3. Run the below command to generate a bundle from the RudderTyper client:

```bash
npx browserify analytics/index.js --standalone rudderTyper >  rudderTyperBundle.js
```

4. For the TypeScript analytics client, add the npm package `tsify` as a dependency and run the below command to generate the bundle:

```bash
npx browserify analytics/index.ts -p [ tsify ] --standalone rudderTyper >  rudderTyperBundle.js
```

5. Import your RudderTyper client and send events.

```html
<script>
  // Add the JavaScript SDK snippet from https://www.rudderstack.com/docs/sources/event-streams/sdks/rudderstack-javascript-sdk/quickstart/#using-cdn
</script>
<script src="./rudderTyperBundle.js"></script>
<script>
  rudderTyper.setRudderTyperOptions({
    analytics: rudderanalytics,
  });
  rudderTyper.orderCompleted({
    orderID: 'ck-f306fe0e-cc21-445a-9caa-08245a9aa52c',
    total: 39.99,
  });
</script>
```

See the [sample application](https://github.com/rudderlabs/rudder-typer/tree/develop/examples/js-cdn-typescript) for more information.

### Using NPM

Import the RudderTyper-generated client and make the calls if your framework supports them.

```javascript
// Import RudderStack JS SDK and initialize it
import { RudderAnalytics } from '@rudderstack/analytics-js';
// Import your auto-generated RudderTyper client:
import { RudderTyperAnalytics } from './analytics/index';

const rudderAnalytics = new RudderAnalytics();
rudderAnalytics.load(WRITE_KEY, DATA_PLANE_URL, {});

// Pass in your @rudderstack/analytics-js instance to RudderTyper client
RudderTyperAnalytics.setRudderTyperOptions({
  analytics: rudderAnalytics,
});

// Issue your first RudderTyper track call
RudderTyperAnalytics.orderCompleted({
  orderID: 'ck-f306fe0e-cc21-445a-9caa-08245a9aa52c',
  total: 39.99,
});
```

Note that:

- Replace `WRITE_KEY` and `DATA_PLANE_URL` in the above snippet with your source write key and [data plane URL]({{< ref "dashboard-guides/_index.md#connections" >}}) respectively.
- Make sure to run `npx rudder-typer` to regenerate your RudderTyper client every time you update the Tracking Plan.

See the [sample application](https://github.com/rudderlabs/rudder-typer/tree/develop/examples/js-npm-typescript) for more information.

{{% /tab %}}
{{% tab tabName="Node.js" %}}
Import the RudderTyper-generated client and start making calls, as shown:

```javascript
// Import RudderStack Node.js SDK and initialize it
const RudderAnalytics = require('@rudderstack/rudder-sdk-node');

const client = new RudderAnalytics(WRITE_KEY, {
  dataPlaneUrl: DATA_PLANE_URL,
  // Other initialization options
});

const RudderTyperAnalytics = require('./analytics/index');
// Pass in your @rudderstack/rudder-sdk-node instance to RudderTyper.
RudderTyperAnalytics.setRudderTyperOptions({
  analytics: client,
});

// Issue your first RudderTyper track call
RudderTyperAnalytics.orderCompleted({
  orderID: 'ck-f306fe0e-cc21-445a-9caa-08245a9aa52c',
  total: 39.99,
});
```
{{% /tab %}}
{{< /tabs >}}

## How RudderTyper validates events based on Tracking Plan

**Case 1: Source is connected to a Tracking Plan**

| Scenario | Behavior |
| :---| :----|
| RudderTyper configured with the same [Tracking Plan ID](#configuration-reference) and version | RudderStack validates the events with the specified Tracking Plan and shows the violations accordingly.  |
| RudderTyper configured with the same Tracking Plan ID but different version | RudderTyper validates the events and shows the violations based on the Tracking Plan version used to generate it, **even if** the Tracking Plan has undergone revisions since then.<br /><br />For example, if you generate RudderTyper with Tracking Plan version v5 and then revise the Tracking Plan version to v6, then RudderTyper validates events and shows violations based on Tracking Plan v5, not v6.  |
| RudderTyper configured with a different Tracking Plan ID | RudderStack validates the events with the Tracking Plan connected to the source in the dashboard and shows the violations accordingly. |

**Case 2: Source is not connected to a Tracking Plan**

In this case, RudderStack does not proceed to the Tracking Plan validation stage. As a result, no violations are shown.

## Contribute

- To submit a bug report or feature request, file an issue [here](https://github.com/rudderlabs/rudder-typer/issues).
- To build on a RudderTyper feature or propose support for a new language, see the [contributor's documentation](https://github.com/rudderlabs/rudder-typer/blob/master/.github/CONTRIBUTING.md).

## References

- [Download Node](https://nodejs.org/en/download/package-manager). You will also get the necessary commands to set up Node.js and verify your installation.
- [Commands to build and run the RudderTyper client](https://github.com/rudderlabs/rudder-typer/blob/master/.github/CONTRIBUTING.md#developing-on-ruddertyper)
- [Yarn reference](https://classic.yarnpkg.com/lang/en/docs/install/#mac-stable)

## FAQ 

#### Can I use a different Service Access Token for authenticating RudderTyper?

Yes, you can. 

1. Follow steps 1 to 3 from the [Quickstart](#quickstart) section.
2. In the **Enter Rudder API token** window, choose **No, provide a different token**.

{{< image src="images/dev-tools/ruddertyper/sat.webp" alt="Choose different SAT option" >}}

#### Why am I seeing events validated against different Tracking Plan versions in the live events viewer?

Different events may be validated against different Tracking Plan versions because RudderStack validates each event against the **specific version** that was used to instrument it.

This behavior ensures that each event is validated against the exact rules it was designed to follow, and prevents false validation errors when Tracking Plans evolve over time.

See [Tracking Plan observability]({{< ref "data-governance/tracking-plans/observability.md#how-validation-works" >}}) for more details.

<br />
