# Example Snowtype generated code for an event specification
> Example configuration files and generated output for each Snowtype-supported tracker and language.
> Source: https://docs.snowplow.io/docs/event-studio/implement-tracking/generate-tracking-code/example-event-specs/
> Documentation index: https://docs.snowplow.io/llms.txt

The following examples show the Snowtype [configuration file](/docs/event-studio/implement-tracking/snowtype-config/), generated output, and how to use them, for a `User Log In` event specification. The event specification has a `login` event data structure, plus two entities: `user` and `user_authentication`.

The `tracker` and `language` fields in your configuration determine the language and structure of the output.

These are the example schemas:

### `login`

**Type:** Schema

Captured when a user attempts to log in to their account. Tracks the method and outcome of the authentication attempt.

**Properties:**

| Property               | Description                                                                                                     |
| ---------------------- | --------------------------------------------------------------------------------------------------------------- |
| `method` _string_      | _Required._ The method used to authenticate, such as 'email', 'google', 'apple', or 'saml'.                     |
| `error_code` _string_  | _Optional._ An optional error code if the login attempt failed (e.g., 'invalid\_password', 'user\_not\_found'). |
| `is_success` _boolean_ | _Required._ Whether the login attempt was successful.                                                           |

### `user`

**Type:** Schema

A subset of the user fields from the users-service

**Properties:**

| Property                  | Description                                                                   |
| ------------------------- | ----------------------------------------------------------------------------- |
| `userId` _string_         | _Required._ The users UUID.                                                   |
| `firstName` _string_      | _Required._ The users first name.                                             |
| `lastName` _string_       | _Required._ The users last name.                                              |
| `organizationId` _string_ | _Required._ The organization's UUID that the user belongs to.                 |
| `email` _string_          | _Optional._ The users email address.                                          |
| `jobTitle` _string_       | _Optional._ The users job title.                                              |
| `accessLevel` _string_    | _Optional._ The users access level. Must be one of: `Admin`, `User`, `Custom` |

### `user_authentication`

**Type:** Schema

Data structure that defines how the user logged in

**Properties:**

| Property             | Description                                                                            |
| -------------------- | -------------------------------------------------------------------------------------- |
| `auth_type` _string_ | _Required._ Type of authentication used Must be one of: `google`, `facebook`, `manual` |

![Console screenshot showing the example event specification](/assets/images/example_event_spec_full-4de68d5b0428c3d71783b23c4c74d006.png)

## Web trackers

Snowtype can generate code in TypeScript or JavaScript, depending which version of the [web trackers](/docs/sources/web-trackers/) you're using.

### Browser (TypeScript)

Generated code for the [Browser tracker](/docs/sources/web-trackers/). Snowtype produces TypeScript type definitions with `track` and `create` functions that wrap `trackSelfDescribingEvent`, plus a `trackXSpec` function, in this case `trackUserLogInSpec`. This function automatically includes the required entities along with the event specification entity.

```json
{
  "orgId": "your-org-id",
  "tracker": "@snowplow/browser-tracker",
  "language": "typescript",
  "outpath": "./src/tracking/snowplow",
  "dataProductIds": [],
  "eventSpecificationIds": ["a965caf1-88a6-4a89-9aea-cc92516a9d56"],
  "dataStructures": [],
  "igluCentralSchemas": []
}
```

```typescript
import { trackSelfDescribingEvent, CommonEventProperties, SelfDescribingJson } from '@snowplow/browser-tracker';
// Automatically generated by Snowtype

/**
 * Captured when a user attempts to log in to their account. Tracks the method and outcome
 * of the authentication attempt.
 */
export type Login = {
    /**
     * An optional error code if the login attempt failed (e.g., 'invalid_password',
     * 'user_not_found').
     */
    error_code?: null | string;
    /**
     * Whether the login attempt was successful.
     */
    is_success: boolean;
    /**
     * The method used to authenticate, such as 'email', 'google', 'apple', or 'saml'.
     */
    method: string;
}

/**
 * A subset of the user fields from the users-service
 */
export type User = {
    /**
     * The users access level.
     */
    accessLevel?: AccessLevel;
    /**
     * The users email address.
     */
    email?: null | string;
    /**
     * The users first name.
     */
    firstName: string;
    /**
     * The users job title.
     */
    jobTitle?: null | string;
    /**
     * The users last name.
     */
    lastName: string;
    /**
     * The organization's UUID that the user belongs to.
     */
    organizationId: string;
    /**
     * The users UUID.
     */
    userId: string;
}

/**
 * The users access level.
 */
export type AccessLevel = "Admin" | "User" | "Custom";

/**
 * Data structure that defines how the user logged in
 */
export type UserAuthentication = {
    /**
     * Type of authentication used
     */
    auth_type: AuthType;
}

/**
 * Type of authentication used
 */
export type AuthType = "google" | "facebook" | "manual";

/**
 * Creates a Snowplow Event Specification entity.
 */
export function createEventSpecification(eventSpecification: Omit<EventSpecification, 'data_product_domain'> & Partial<Pick<EventSpecification, 'data_product_domain'>>){
    return {
        schema:
            'iglu:com.snowplowanalytics.snowplow/event_specification/jsonschema/1-0-4',
        data: eventSpecification,
    }
}

/**
 * Automatically attached context for event specifications
 */
interface EventSpecification {
    id: string;
    version: number;
    name: string;
    data_product_id: string;
    data_product_name: string;
    data_product_domain?: string;
}

type ContextsOrTimestamp<T = any> = Omit<CommonEventProperties<T>, 'context'> & { context?: SelfDescribingJson<T>[] | null | undefined }
/**
 * Track a Snowplow event for Login.
 * Captured when a user attempts to log in to their account. Tracks the method and outcome of the authentication attempt.
 */
export function trackLogin<T extends {} = any>(login: Login & ContextsOrTimestamp<T>, trackers?: string[]){
    const { context, timestamp, ...data } = login;
    const event: SelfDescribingJson = {
        schema: 'iglu:com.snplow.msc.aws/login/jsonschema/1-0-0',
        data
    };

    trackSelfDescribingEvent({
        event,
        context,
        timestamp,
    }, trackers);
}

/**
 * Creates a Snowplow Login entity.
 */
export function createLogin(login: Login){
    return {
        schema: 'iglu:com.snplow.msc.aws/login/jsonschema/1-0-0',
        data: login
    }
}
/**
 * Track a Snowplow event for User.
 * A subset of the user fields from the users-service
 */
export function trackUser<T extends {} = any>(user: User & ContextsOrTimestamp<T>, trackers?: string[]){
    const { context, timestamp, ...data } = user;
    const event: SelfDescribingJson = {
        schema: 'iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1',
        data
    };

    trackSelfDescribingEvent({
        event,
        context,
        timestamp,
    }, trackers);
}

/**
 * Creates a Snowplow User entity.
 */
export function createUser(user: User){
    return {
        schema: 'iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1',
        data: user
    }
}
/**
 * Track a Snowplow event for UserAuthentication.
 * Data structure that defines how the user logged in
 */
export function trackUserAuthentication<T extends {} = any>(userAuthentication: UserAuthentication & ContextsOrTimestamp<T>, trackers?: string[]){
    const { context, timestamp, ...data } = userAuthentication;
    const event: SelfDescribingJson = {
        schema: 'iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0',
        data
    };

    trackSelfDescribingEvent({
        event,
        context,
        timestamp,
    }, trackers);
}

/**
 * Creates a Snowplow UserAuthentication entity.
 */
export function createUserAuthentication(userAuthentication: UserAuthentication){
    return {
        schema: 'iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0',
        data: userAuthentication
    }
}

/**
 * Tracks a UserLogIn event specification.
 * ID: a965caf1-88a6-4a89-9aea-cc92516a9d56
 */
export function trackUserLogInSpec(userLogIn: Login & ContextsOrTimestamp<User | UserAuthentication>, trackers?: string[]){
    const eventSpecificationContext = createEventSpecification({
        id: 'a965caf1-88a6-4a89-9aea-cc92516a9d56',
        version: 8,
        name: 'User Log In',
        data_product_id: '57471841-aa79-445d-b4f7-1cbd073a3188',
        data_product_name: 'Checkout Flow',
        data_product_domain: 'Marketing'
    });

    const context = Array.isArray(userLogIn.context)
        ? [...userLogIn.context, eventSpecificationContext]
        : [eventSpecificationContext];

    const modifiedUserLogIn = {
        ...userLogIn,
        context,
    };

    trackLogin<User | UserAuthentication | EventSpecification>(modifiedUserLogIn, trackers);
}
```

Here's how you could use the generated code:

```typescript
import {
  trackUserLogInSpec,
  createUser,
  createUserAuthentication,
} from "./src/tracking/snowplow";

const user = createUser({
  userId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  firstName: "Ada",
  lastName: "Lovelace",
  organizationId: "57471841-aa79-445d-b4f7-1cbd073a3188",
  email: "ada@example.com",
  accessLevel: "Admin",
});

const userAuth = createUserAuthentication({ auth_type: "google" });

trackUserLogInSpec({
  method: "google",
  is_success: true,
  context: [user, userAuth],
});
```

### Browser (JavaScript)

Generated code for the [Browser tracker](/docs/sources/web-trackers/) in JavaScript. Snowtype produces JSDoc typedefs, with `track` and `create` functions, plus a `trackXSpec` function, in this case `trackUserLogInSpec`. This function automatically includes the required entities along with the event specification entity.

```json
{
  "orgId": "your-org-id",
  "tracker": "@snowplow/browser-tracker",
  "language": "javascript",
  "outpath": "./src/tracking/snowplow",
  "dataProductIds": [],
  "eventSpecificationIds": ["a965caf1-88a6-4a89-9aea-cc92516a9d56"],
  "dataStructures": [],
  "igluCentralSchemas": []
}
```

```javascript
import { trackSelfDescribingEvent } from '@snowplow/browser-tracker';
// Automatically generated by Snowtype

/**
 * Typedef for a DeviceTimestamp
 * @typedef {object} DeviceTimestamp
 * @property {'dtm'} type The value of 'dtm'
 * @property {number} value The value of the device timestamp
 */

/**
 * Typedef for a TrueTimestamp
 * @typedef {object} TrueTimestamp
 * @property {'ttm'} type The value of 'ttm'
 * @property {number} value The value of the true timestamp
 */

/**
 * Typedef for a Timestamp
 * @typedef {object} Timestamp
 * @property {number|TrueTimestamp|DeviceTimestamp} [timestamp] The value of the timestamp
 */

/**
 * Typedef for a SelfDescribingJson
 * @typedef {object} SelfDescribingJson
 * @property {string} schema The schema of the context
 * @property {object} data The data to send for the context
 */

/**
 * Typedef for a Context
 * @typedef {object} Context
 * @property {SelfDescribingJson[]} [context] Contexts to include in the event
 */

/**
 * Captured when a user attempts to log in to their account. Tracks the method and outcome of the authentication attempt.
 * @typedef {object} Login
 * @property {string} method The method used to authenticate, such as 'email', 'google', 'apple', or 'saml'.
 * @property {?string} [error_code] An optional error code if the login attempt failed (e.g., 'invalid_password', 'user_not_found').
 * @property {boolean} is_success Whether the login attempt was successful.
 */


/**
 * Typedef for a Login entity context.
 * @typedef {object} LoginContext
 * @property {string} schema The schema of the context.
 * @property { Login } data The data to send for the context.
 */

/**
 * A subset of the user fields from the users-service
 * @typedef {object} User
 * @property {string} userId The users UUID.
 * @property {string} firstName The users first name.
 * @property {string} lastName The users last name.
 * @property {string} organizationId The organization's UUID that the user belongs to.
 * @property {?string} [email] The users email address.
 * @property {?string} [jobTitle] The users job title.
 * @property {"Admin"|"User"|"Custom"|null} [accessLevel] The users access level.
 */


/**
 * Typedef for a User entity context.
 * @typedef {object} UserContext
 * @property {string} schema The schema of the context.
 * @property { User } data The data to send for the context.
 */

/**
 * Data structure that defines how the user logged in
 * @typedef {object} UserAuthentication
 * @property {"google"|"facebook"|"manual"} auth_type Type of authentication used
 */


/**
 * Typedef for a UserAuthentication entity context.
 * @typedef {object} UserAuthenticationContext
 * @property {string} schema The schema of the context.
 * @property { UserAuthentication } data The data to send for the context.
 */

/**
 * Creates a Snowplow Event Specification entity.
 */
export function createEventSpecification(eventSpecification){
    return {
        schema:
            'iglu:com.snowplowanalytics.snowplow/event_specification/jsonschema/1-0-4',
        data: eventSpecification,
    }
}


/**
 * Track a Snowplow event for Login.
 * Captured when a user attempts to log in to their account. Tracks the method and outcome of the authentication attempt.
 * @param { Login & Timestamp & Context } login - Attributes for Login.
 * @param {string[]} [trackers] - Tracker names to send the event to.
 */
export function trackLogin(login, trackers){
    const { context, timestamp, ...data } = login;
    const event = {
        schema: 'iglu:com.snplow.msc.aws/login/jsonschema/1-0-0',
        data
    };

    trackSelfDescribingEvent({
        event,
        context,
        timestamp,
    }, trackers);
}

/**
 * Creates a Snowplow Login entity.
 * @param { Login } login - Attributes for Login.
 */
export function createLogin(login){
    return {
        schema: 'iglu:com.snplow.msc.aws/login/jsonschema/1-0-0',
        data: login
    }
}
/**
 * Track a Snowplow event for User.
 * A subset of the user fields from the users-service
 * @param { User & Timestamp & Context } user - Attributes for User.
 * @param {string[]} [trackers] - Tracker names to send the event to.
 */
export function trackUser(user, trackers){
    const { context, timestamp, ...data } = user;
    const event = {
        schema: 'iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1',
        data
    };

    trackSelfDescribingEvent({
        event,
        context,
        timestamp,
    }, trackers);
}

/**
 * Creates a Snowplow User entity.
 * @param { User } user - Attributes for User.
 */
export function createUser(user){
    return {
        schema: 'iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1',
        data: user
    }
}
/**
 * Track a Snowplow event for UserAuthentication.
 * Data structure that defines how the user logged in
 * @param { UserAuthentication & Timestamp & Context } userAuthentication - Attributes for UserAuthentication.
 * @param {string[]} [trackers] - Tracker names to send the event to.
 */
export function trackUserAuthentication(userAuthentication, trackers){
    const { context, timestamp, ...data } = userAuthentication;
    const event = {
        schema: 'iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0',
        data
    };

    trackSelfDescribingEvent({
        event,
        context,
        timestamp,
    }, trackers);
}

/**
 * Creates a Snowplow UserAuthentication entity.
 * @param { UserAuthentication } userAuthentication - Attributes for UserAuthentication.
 */
export function createUserAuthentication(userAuthentication){
    return {
        schema: 'iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0',
        data: userAuthentication
    }
}

/**
 * Typedef for UserLogIn event specification contexts.
 * @typedef {object} UserLogInContexts
 * @property {(UserContext | UserAuthenticationContext)[]} [context] Contexts to include in the UserLogIn event specification.
 */

/**
 * Tracks a UserLogIn event specification.
 * ID: a965caf1-88a6-4a89-9aea-cc92516a9d56
 * @param { Login & Timestamp & UserLogInContexts } userLogIn - Attributes for UserLogIn event specification.
 * @param {string[]} [trackers] - Tracker names to send the event specification to.
 */
export function trackUserLogInSpec(userLogIn, trackers){
    const eventSpecificationContext = createEventSpecification({
        id: 'a965caf1-88a6-4a89-9aea-cc92516a9d56',
        version: 8,
        name: 'User Log In',
        data_product_id: '57471841-aa79-445d-b4f7-1cbd073a3188',
        data_product_name: 'Checkout Flow',
        data_product_domain: 'Marketing'
    });

    const context = Array.isArray(userLogIn.context)
        ? [...userLogIn.context, eventSpecificationContext]
        : [eventSpecificationContext];

    const modifiedUserLogIn = {
        ...userLogIn,
        context,
    };

    trackLogin(modifiedUserLogIn, trackers);
}
```

Here's how you could use the generated code:

```javascript
import {
  trackUserLogInSpec,
  createUser,
  createUserAuthentication,
} from "./src/tracking/snowplow";

const user = createUser({
  userId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  firstName: "Ada",
  lastName: "Lovelace",
  organizationId: "57471841-aa79-445d-b4f7-1cbd073a3188",
  email: "ada@example.com",
  accessLevel: "Admin",
});

const userAuth = createUserAuthentication({ auth_type: "google" });

trackUserLogInSpec({
  method: "google",
  is_success: true,
  context: [user, userAuth],
});
```

### JavaScript tag

Generated code for the [JavaScript tag](/docs/sources/web-trackers/). Snowtype produces functions that call `window.snowplow()` directly, including a `trackXSpec` function, in this case `trackUserLogInSpec`. This function automatically includes the required entities along with the event specification entity.

```json
{
  "orgId": "your-org-id",
  "tracker": "@snowplow/javascript-tracker",
  "language": "javascript",
  "outpath": "./src/tracking/snowplow",
  "dataProductIds": [],
  "eventSpecificationIds": ["a965caf1-88a6-4a89-9aea-cc92516a9d56"],
  "dataStructures": [],
  "igluCentralSchemas": []
}
```

```javascript
// Automatically generated by Snowtype

/**
 * Typedef for a DeviceTimestamp
 * @typedef {object} DeviceTimestamp
 * @property {'dtm'} type The value of 'dtm'
 * @property {number} value The value of the device timestamp
 */

/**
 * Typedef for a TrueTimestamp
 * @typedef {object} TrueTimestamp
 * @property {'ttm'} type The value of 'ttm'
 * @property {number} value The value of the true timestamp
 */

/**
 * Typedef for a Timestamp
 * @typedef {object} Timestamp
 * @property {number|TrueTimestamp|DeviceTimestamp} [timestamp] The value of the timestamp
 */

/**
 * Typedef for a SelfDescribingJson
 * @typedef {object} SelfDescribingJson
 * @property {string} schema The schema of the context
 * @property {object} data The data to send for the context
 */

/**
 * Typedef for a Context
 * @typedef {object} Context
 * @property {SelfDescribingJson[]} [context] Contexts to include in the event
 */

/**
 * Captured when a user attempts to log in to their account. Tracks the method and outcome of the authentication attempt.
 * @typedef {object} Login
 * @property {string} method The method used to authenticate, such as 'email', 'google', 'apple', or 'saml'.
 * @property {?string} [error_code] An optional error code if the login attempt failed (e.g., 'invalid_password', 'user_not_found').
 * @property {boolean} is_success Whether the login attempt was successful.
 */


/**
 * Typedef for a Login entity context.
 * @typedef {object} LoginContext
 * @property {string} schema The schema of the context.
 * @property { Login } data The data to send for the context.
 */

/**
 * A subset of the user fields from the users-service
 * @typedef {object} User
 * @property {string} userId The users UUID.
 * @property {string} firstName The users first name.
 * @property {string} lastName The users last name.
 * @property {string} organizationId The organization's UUID that the user belongs to.
 * @property {?string} [email] The users email address.
 * @property {?string} [jobTitle] The users job title.
 * @property {"Admin"|"User"|"Custom"|null} [accessLevel] The users access level.
 */


/**
 * Typedef for a User entity context.
 * @typedef {object} UserContext
 * @property {string} schema The schema of the context.
 * @property { User } data The data to send for the context.
 */

/**
 * Data structure that defines how the user logged in
 * @typedef {object} UserAuthentication
 * @property {"google"|"facebook"|"manual"} auth_type Type of authentication used
 */


/**
 * Typedef for a UserAuthentication entity context.
 * @typedef {object} UserAuthenticationContext
 * @property {string} schema The schema of the context.
 * @property { UserAuthentication } data The data to send for the context.
 */

/**
 * Track a Snowplow event for Login.
 * Captured when a user attempts to log in to their account. Tracks the method and outcome of the authentication attempt.
 * @param { Login & Timestamp & Context } login - Attributes for Login.
 * @param {string[]} [trackers] - Tracker names to send the event to.
 */
function trackLogin(login, trackers){
    const trackerNames = (trackers && trackers.length) ? ':' + trackers.join(';') : '';
    const { context, timestamp, ...data } = login;
    window.snowplow('trackSelfDescribingEvent' + trackerNames, {
        event: {
            schema: 'iglu:com.snplow.msc.aws/login/jsonschema/1-0-0',
            data
        },
        context,
        timestamp,
    });
}

/**
 * Creates a Snowplow Login entity.
 * @param { Login } login - Attributes for Login.
 */
function createLogin(login){
    return {
        schema: 'iglu:com.snplow.msc.aws/login/jsonschema/1-0-0',
        data: login
    }
}
/**
 * Track a Snowplow event for User.
 * A subset of the user fields from the users-service
 * @param { User & Timestamp & Context } user - Attributes for User.
 * @param {string[]} [trackers] - Tracker names to send the event to.
 */
function trackUser(user, trackers){
    const trackerNames = (trackers && trackers.length) ? ':' + trackers.join(';') : '';
    const { context, timestamp, ...data } = user;
    window.snowplow('trackSelfDescribingEvent' + trackerNames, {
        event: {
            schema: 'iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1',
            data
        },
        context,
        timestamp,
    });
}

/**
 * Creates a Snowplow User entity.
 * @param { User } user - Attributes for User.
 */
function createUser(user){
    return {
        schema: 'iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1',
        data: user
    }
}
/**
 * Track a Snowplow event for UserAuthentication.
 * Data structure that defines how the user logged in
 * @param { UserAuthentication & Timestamp & Context } userAuthentication - Attributes for UserAuthentication.
 * @param {string[]} [trackers] - Tracker names to send the event to.
 */
function trackUserAuthentication(userAuthentication, trackers){
    const trackerNames = (trackers && trackers.length) ? ':' + trackers.join(';') : '';
    const { context, timestamp, ...data } = userAuthentication;
    window.snowplow('trackSelfDescribingEvent' + trackerNames, {
        event: {
            schema: 'iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0',
            data
        },
        context,
        timestamp,
    });
}

/**
 * Creates a Snowplow UserAuthentication entity.
 * @param { UserAuthentication } userAuthentication - Attributes for UserAuthentication.
 */
function createUserAuthentication(userAuthentication){
    return {
        schema: 'iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0',
        data: userAuthentication
    }
}

/**
 * Creates a Snowplow Event Specification entity.
 */
export function createEventSpecification(eventSpecification){
    return {
        schema:
            'iglu:com.snowplowanalytics.snowplow/event_specification/jsonschema/1-0-4',
        data: eventSpecification,
    }
}

/**
 * Typedef for UserLogIn event specification contexts.
 * @typedef {object} UserLogInContexts
 * @property {(UserContext | UserAuthenticationContext)[]} [context] Contexts to include in the UserLogIn event specification.
 */

/**
 * Tracks a UserLogIn event specification.
 * ID: a965caf1-88a6-4a89-9aea-cc92516a9d56
 * @param { Login & Timestamp & UserLogInContexts } userLogIn - Attributes for UserLogIn event specification.
 * @param {string[]} [trackers] - Tracker names to send the event specification to.
 */
function trackUserLogInSpec(userLogIn, trackers){
    const eventSpecificationContext = createEventSpecification({
        id: 'a965caf1-88a6-4a89-9aea-cc92516a9d56',
        version: 8,
        name: 'User Log In',
        data_product_id: '57471841-aa79-445d-b4f7-1cbd073a3188',
        data_product_name: 'Checkout Flow',
        data_product_domain: 'Marketing'
    });

    const context = Array.isArray(userLogIn.context)
        ? [...userLogIn.context, eventSpecificationContext]
        : [eventSpecificationContext];

    const modifiedUserLogIn = {
        ...userLogIn,
        context,
    };

    trackLogin(modifiedUserLogIn, trackers);
}
```

Here's how you could use the generated code:

```javascript
const user = createUser({
  userId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  firstName: "Ada",
  lastName: "Lovelace",
  organizationId: "57471841-aa79-445d-b4f7-1cbd073a3188",
  email: "ada@example.com",
  accessLevel: "Admin",
});

const userAuth = createUserAuthentication({ auth_type: "google" });

trackUserLogInSpec({
  method: "google",
  is_success: true,
  context: [user, userAuth],
});
```

## iOS (Swift)

Generated code for the [iOS tracker](/docs/sources/mobile-trackers/). Snowtype produces Swift structs with `toEvent()` and `toEntity()` methods, plus a `toXSpec()` extension on the event struct that bundles it with its required entities and attaches the event specification entity. In this case, a `toUserLogInSpec()` extension on the `Login` struct.

The generated code is compatible with both Swift 5.5+ and 6.

```json
{
  "orgId": "your-org-id",
  "tracker": "snowplow-ios-tracker",
  "language": "swift",
  "outpath": "./Sources/Tracking/Snowtype",
  "dataProductIds": [],
  "eventSpecificationIds": ["a965caf1-88a6-4a89-9aea-cc92516a9d56"],
  "dataStructures": [],
  "igluCentralSchemas": [],
  // "namespace": "SnowplowTracking"
}
```

When generating tracking code for the iOS tracker, you can set the optional `namespace` option in your Snowtype configuration. All classes generated will be included in this namespace. This can be helpful for avoiding naming conflicts with other types in your codebase.

Snowtype generates `JSONNull`, `JSONCodingKey`, and `JSONAny` helper classes for encoding and decoding JSON values. These are omitted here for brevity.

````swift
import Foundation
import SnowplowTracker

// MARK: - Encode/decode helpers

// Helper classes JSONNull, JSONCodingKey, and JSONAny not shown

// MARK: - Login

/// Captured when a user attempts to log in to their account. Tracks the method and outcome
/// of the authentication attempt.
/// Schema: `iglu:com.snplow.msc.aws/login/jsonschema/1-0-0`
///
/// Example:
/// ```swift
/// let data = Login(
///     isSuccess: isSuccess,
///     method: method,
///     errorCode: errorCode
/// )
/// // Track as an event
/// Snowplow.defaultTracker()?.track(data.toEvent())
/// // Add as an entity to another event
/// let event = ScreenView(name: "Product")
/// event.entities.append(data.toEntity())
/// Snowplow.defaultTracker()?.track(event)
/// ```
struct Login {

        /// Whether the login attempt was successful.
        var isSuccess: Bool
        /// The method used to authenticate, such as 'email', 'google', 'apple', or 'saml'.
        var method: String
        /// An optional error code if the login attempt failed (e.g., 'invalid_password',
        /// 'user_not_found').
        var errorCode: String?

        private var schema: String {
                return "iglu:com.snplow.msc.aws/login/jsonschema/1-0-0"
        }

        private var payload: [String : Any] {
                var payload: [String : Any] = [:]
                if let errorCode = errorCode {
                        payload["error_code"] = errorCode
                }
                payload["is_success"] = isSuccess
                payload["method"] = method
                return payload
        }

        /// Creates an event instance to be tracked by the tracker.
        func toEvent() -> SelfDescribing {
                return SelfDescribing(schema: schema, payload: payload)
        }

        /// Creates an entity that can be added to events.
        func toEntity() -> SelfDescribingJson {
                return SelfDescribingJson(schema: schema, andData: payload)
        }

}

// MARK: - User

/// A subset of the user fields from the users-service
/// Schema: `iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1`
///
/// Example:
/// ```swift
/// let data = User(
///     firstName: firstName,
///     lastName: lastName,
///     organizationID: organizationID,
///     userID: userID,
///     accessLevel: accessLevel,
///     email: email,
///     jobTitle: jobTitle
/// )
/// // Track as an event
/// Snowplow.defaultTracker()?.track(data.toEvent())
/// // Add as an entity to another event
/// let event = ScreenView(name: "Product")
/// event.entities.append(data.toEntity())
/// Snowplow.defaultTracker()?.track(event)
/// ```
struct User {

        /// The users first name.
        var firstName: String
        /// The users last name.
        var lastName: String
        /// The organization's UUID that the user belongs to.
        var organizationID: String
        /// The users UUID.
        var userID: String
        /// The users access level.
        var accessLevel: AccessLevel?
        /// The users email address.
        var email: String?
        /// The users job title.
        var jobTitle: String?

        private var schema: String {
                return "iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1"
        }

        private var payload: [String : Any] {
                var payload: [String : Any] = [:]
                if let accessLevel = accessLevel {
                        payload["accessLevel"] = accessLevel.rawValue
                }
                if let email = email {
                        payload["email"] = email
                }
                payload["firstName"] = firstName
                if let jobTitle = jobTitle {
                        payload["jobTitle"] = jobTitle
                }
                payload["lastName"] = lastName
                payload["organizationId"] = organizationID
                payload["userId"] = userID
                return payload
        }

        /// Creates an event instance to be tracked by the tracker.
        func toEvent() -> SelfDescribing {
                return SelfDescribing(schema: schema, payload: payload)
        }

        /// Creates an entity that can be added to events.
        func toEntity() -> SelfDescribingJson {
                return SelfDescribingJson(schema: schema, andData: payload)
        }

}

// MARK: - UserAuthentication

/// Data structure that defines how the user logged in
/// Schema: `iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0`
///
/// Example:
/// ```swift
/// let data = UserAuthentication(
///     authType: authType
/// )
/// // Track as an event
/// Snowplow.defaultTracker()?.track(data.toEvent())
/// // Add as an entity to another event
/// let event = ScreenView(name: "Product")
/// event.entities.append(data.toEntity())
/// Snowplow.defaultTracker()?.track(event)
/// ```
struct UserAuthentication {

        /// Type of authentication used
        var authType: AuthType

        private var schema: String {
                return "iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0"
        }

        private var payload: [String : Any] {
                var payload: [String : Any] = [:]
                payload["auth_type"] = authType.rawValue
                return payload
        }

        /// Creates an event instance to be tracked by the tracker.
        func toEvent() -> SelfDescribing {
                return SelfDescribing(schema: schema, payload: payload)
        }

        /// Creates an entity that can be added to events.
        func toEntity() -> SelfDescribingJson {
                return SelfDescribingJson(schema: schema, andData: payload)
        }

}

// MARK: - EventSpecification

/// Entity schema for referencing an event specification
/// Schema: `iglu:com.snowplowanalytics.snowplow/event_specification/jsonschema/1-0-4`
///
/// Example:
/// ```swift
/// let data = EventSpecification(
///     id: id,
///     version: version,
///     name: name,
///     dataProductId: dataProductId,
///     dataProductName: dataProductName,
///     dataProductDomain: dataProductDomain
/// )
/// // Track as an event
/// Snowplow.defaultTracker()?.track(data.toEvent())
/// // Add as an entity to another event
/// let event = ScreenView(name: "Product")
/// event.entities.append(data.toEntity())
/// Snowplow.defaultTracker()?.track(event)
/// ```
struct EventSpecification {

        /// Identifier for the event specification that the event adheres
        var id: String
        /// Version of the event specification that the event adheres to
        var version: Int
        /// Name for the event specification that the event adheres to
        var name: String
        /// Identifier for the data product that the event specification belongs to
        var dataProductId: String
        /// Name for the data product that the event specification belongs to
        var dataProductName: String
        /// Domain for the data product that the event specification belongs to
        var dataProductDomain: String?

        private var schema: String {
                return "iglu:com.snowplowanalytics.snowplow/event_specification/jsonschema/1-0-4"
        }

        private var payload: [String : Any] {
                var payload: [String : Any] = [:]
                payload["id"] = id
                payload["version"] = version
                payload["name"] = name
                payload["data_product_id"] = dataProductId
                payload["data_product_name"] = dataProductName
                if let dataProductDomain = dataProductDomain {
                        payload["data_product_domain"] = dataProductDomain
                }
                return payload
        }

        /// Creates an event instance to be tracked by the tracker.
        func toEvent() -> SelfDescribing {
                return SelfDescribing(schema: schema, payload: payload)
        }

        /// Creates an entity that can be added to events.
        func toEntity() -> SelfDescribingJson {
                return SelfDescribingJson(schema: schema, andData: payload)
        }

}

// MARK: - AccessLevel

/// The users access level.
enum AccessLevel: String {
        case admin = "Admin"
        case custom = "Custom"
        case user = "User"
}

// MARK: - AuthType

/// Type of authentication used
enum AuthType: String {
        case facebook = "facebook"
        case google = "google"
        case manual = "manual"
}

extension Login {
        /// Creates an event with entities for a UserLogIn event specification.
        /// ID: a965caf1-88a6-4a89-9aea-cc92516a9d56
        /// Example:
        /// ```swift
        /// let data = Login(...)
        /// let dataUser = User(...)
        /// let dataUserAuthentication = UserAuthentication(...)
        /// let event = data.toUserLogInSpec(dataUser, dataUserAuthentication)
        /// // Track as an event
        /// Snowplow.defaultTracker()?.track(event)
        /// ```
        func toUserLogInSpec(_ entityUser: User, _ entityUserAuthentication: UserAuthentication) -> SelfDescribing {
                let event = toEvent()
                let eventSpec = EventSpecification(
                        id: "a965caf1-88a6-4a89-9aea-cc92516a9d56",
                        version: 8,
                        name: "User Log In",
                        dataProductId: "57471841-aa79-445d-b4f7-1cbd073a3188",
                        dataProductName: "Checkout Flow",
                        dataProductDomain: "Marketing"
                )
                event.entities.append(entityUser.toEntity())
                event.entities.append(entityUserAuthentication.toEntity())
                event.entities.append(eventSpec.toEntity())
                return event
        }
}
````

Here's how you could use the generated code:

```swift
import SnowplowTracker

let user = User(
    firstName: "Ada",
    lastName: "Lovelace",
    organizationID: "57471841-aa79-445d-b4f7-1cbd073a3188",
    userID: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    email: "ada@example.com",
    accessLevel: .admin
)

let userAuth = UserAuthentication(authType: .google)

let login = Login(
    isSuccess: true,
    method: "google"
)

let event = login.toUserLogInSpec(user, userAuth)
Snowplow.defaultTracker()?.track(event)
```

## Android (Kotlin)

Generated code for the [Android tracker](/docs/sources/mobile-trackers/). Snowtype produces Kotlin data classes with `toEvent()` and `toEntity()` methods, plus a `toXSpec()` extension function for the event that bundles it with its required entities and attaches the event specification entity. In this case, a `toUserLogInSpec()` extension on `Login`.

```json
{
  "orgId": "your-org-id",
  "tracker": "snowplow-android-tracker",
  "language": "kotlin",
  "outpath": "./app/src/main/java/snowtype",
  "dataProductIds": [],
  "eventSpecificationIds": ["a965caf1-88a6-4a89-9aea-cc92516a9d56"],
  "dataStructures": [],
  "igluCentralSchemas": []
}
```

````kotlin
// Automatically generated by Snowtype

package Snowtype

import com.snowplowanalytics.snowplow.event.SelfDescribing
import com.snowplowanalytics.snowplow.payload.SelfDescribingJson
import kotlinx.serialization.json.*

/**
 * Captured when a user attempts to log in to their account. Tracks the method and outcome
 * of the authentication attempt.
 * Schema: `iglu:com.snplow.msc.aws/login/jsonschema/1-0-0`
 *
 * Example:
 * ```kotlin
 * val data = Login(
 *     isSuccess = isSuccess,
 *     method = method,
 *     errorCode = errorCode
 * )
 * // Track as an event
 * Snowplow.defaultTracker?.track(data.toEvent())
 * // Add as an entity to another event
 * val event = ScreenView(name = "Product")
 * event.entities.add(data.toEntity())
 * Snowplow.defaultTracker?.track(event)
 * ```
*/
data class Login(

        /** Whether the login attempt was successful. */
        var isSuccess: Boolean,

        /** The method used to authenticate, such as 'email', 'google', 'apple', or 'saml'. */
        var method: String,

        /**
         * An optional error code if the login attempt failed (e.g., 'invalid_password',
         * 'user_not_found').
         */
        var errorCode: String? = null
) {
        private val schema = "iglu:com.snplow.msc.aws/login/jsonschema/1-0-0"

        private val payload: Map<String, Any?>
                get() {
                        val payload = HashMap<String, Any?>()
                        errorCode?.let { payload["error_code"] = it }
                        payload["is_success"] = isSuccess
                        payload["method"] = method
                        return payload
                }

        /** Creates an event instance to be tracked by the tracker. */
        fun toEvent() : SelfDescribing {
                return SelfDescribing(schema, payload)
        }

        /** Creates an entity that can be added to events. */
        fun toEntity() : SelfDescribingJson {
                return SelfDescribingJson(schema, payload)
        }
}

/**
 * A subset of the user fields from the users-service
 * Schema: `iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1`
 *
 * Example:
 * ```kotlin
 * val data = User(
 *     firstName = firstName,
 *     lastName = lastName,
 *     organizationID = organizationID,
 *     userID = userID,
 *     accessLevel = accessLevel,
 *     email = email,
 *     jobTitle = jobTitle
 * )
 * // Track as an event
 * Snowplow.defaultTracker?.track(data.toEvent())
 * // Add as an entity to another event
 * val event = ScreenView(name = "Product")
 * event.entities.add(data.toEntity())
 * Snowplow.defaultTracker?.track(event)
 * ```
*/
data class User(

        /** The users first name. */
        var firstName: String,

        /** The users last name. */
        var lastName: String,

        /** The organization's UUID that the user belongs to. */
        var organizationID: String,

        /** The users UUID. */
        var userID: String,

        /** The users access level. */
        var accessLevel: AccessLevel? = null,

        /** The users email address. */
        var email: String? = null,

        /** The users job title. */
        var jobTitle: String? = null
) {
        private val schema = "iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1"

        private val payload: Map<String, Any?>
                get() {
                        val payload = HashMap<String, Any?>()
                        accessLevel?.let { payload["accessLevel"] = it.string }
                        email?.let { payload["email"] = it }
                        payload["firstName"] = firstName
                        jobTitle?.let { payload["jobTitle"] = it }
                        payload["lastName"] = lastName
                        payload["organizationId"] = organizationID
                        payload["userId"] = userID
                        return payload
                }

        /** Creates an event instance to be tracked by the tracker. */
        fun toEvent() : SelfDescribing {
                return SelfDescribing(schema, payload)
        }

        /** Creates an entity that can be added to events. */
        fun toEntity() : SelfDescribingJson {
                return SelfDescribingJson(schema, payload)
        }
}

/**
 * Data structure that defines how the user logged in
 * Schema: `iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0`
 *
 * Example:
 * ```kotlin
 * val data = UserAuthentication(
 *     authType = authType
 * )
 * // Track as an event
 * Snowplow.defaultTracker?.track(data.toEvent())
 * // Add as an entity to another event
 * val event = ScreenView(name = "Product")
 * event.entities.add(data.toEntity())
 * Snowplow.defaultTracker?.track(event)
 * ```
*/
data class UserAuthentication(

        /** Type of authentication used */
        var authType: AuthType
) {
        private val schema = "iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0"

        private val payload: Map<String, Any?>
                get() {
                        val payload = HashMap<String, Any?>()
                        payload["auth_type"] = authType.string
                        return payload
                }

        /** Creates an event instance to be tracked by the tracker. */
        fun toEvent() : SelfDescribing {
                return SelfDescribing(schema, payload)
        }

        /** Creates an entity that can be added to events. */
        fun toEntity() : SelfDescribingJson {
                return SelfDescribingJson(schema, payload)
        }
}

/**
 * Entity schema for referencing an event specification
 * Schema: `iglu:com.snowplowanalytics.snowplow/event_specification/jsonschema/1-0-4`
 *
 * Example:
 * ```kotlin
 * val data = EventSpecification(
 *     id = id,
 *     version = version,
 *     name = name,
 *     dataProductId = dataProductId,
 *     dataProductName = dataProductName,
 *     dataProductDomain = dataProductDomain
 * )
 * // Track as an event
 * Snowplow.defaultTracker?.track(data.toEvent())
 * // Add as an entity to another event
 * val event = ScreenView(name = "Product")
 * event.entities.add(data.toEntity())
 * Snowplow.defaultTracker?.track(event)
 * ```
*/
data class EventSpecification(

        /** Identifier for the event specification that the event adheres */
        var id: String,

        /** Version of the event specification that the event adheres to*/
        var version: Int,

        /** Name for the event specification that the event adheres to */
        var name: String,

        /** Identifier for the data product that the event specification belongs to */
        var dataProductId: String,

        /** Name for the data product that the event specification belongs to */
        var dataProductName: String,

        /** Domain for the data product that the event specification belongs to */
        var dataProductDomain: String? = null
) {
        private val schema = "iglu:com.snowplowanalytics.snowplow/event_specification/jsonschema/1-0-4"

        private val payload: Map<String, Any?>
                get() {
                        val payload = HashMap<String, Any?>()
                        payload["id"] = id
                        payload["version"] = version
                        payload["name"] = name
                        payload["data_product_id"] = dataProductId
                        payload["data_product_name"] = dataProductName
                        dataProductDomain?.let { payload["data_product_domain"] = it }
                        return payload
                }

        /** Creates an event instance to be tracked by the tracker. */
        fun toEvent() : SelfDescribing {
                return SelfDescribing(schema, payload)
        }

        /** Creates an entity that can be added to events. */
        fun toEntity() : SelfDescribingJson {
                return SelfDescribingJson(schema, payload)
        }
}

/**
 * The users access level.
*/
enum class AccessLevel(val string: String) {
        Admin("Admin"),
        Custom("Custom"),
        User("User")
}

/**
 * Type of authentication used
*/
enum class AuthType(val string: String) {
        Facebook("facebook"),
        Google("google"),
        Manual("manual")
}

/**
 * Creates an event with entities for a UserLogIn event specification.
 * ID: a965caf1-88a6-4a89-9aea-cc92516a9d56
 * Example:
 * ```kotlin
 * val data = Login(...)
 * val dataUser = User(...)
 * val dataUserAuthentication = UserAuthentication(...)
 * val event = data.toUserLogInSpec(dataUser, dataUserAuthentication)
 * // Track as an event
 * Snowplow.defaultTracker?.track(event)
 * ```
*/
fun Login.toUserLogInSpec(entityUser: User, entityUserAuthentication: UserAuthentication) : SelfDescribing {
        val event = toEvent()
        val eventSpec = EventSpecification(
                "a965caf1-88a6-4a89-9aea-cc92516a9d56",
                8,
                "User Log In",
                "57471841-aa79-445d-b4f7-1cbd073a3188",
                "Checkout Flow",
                "Marketing"
        )
        event.entities.add(entityUser.toEntity())
        event.entities.add(entityUserAuthentication.toEntity())
        event.entities.add(eventSpec.toEntity())
        return event
}
````

Here's how you could use the generated code:

```kotlin
import Snowtype.Login
import Snowtype.User
import Snowtype.UserAuthentication
import Snowtype.toUserLogInSpec

val user = User(
    userID = "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    firstName = "Ada",
    lastName = "Lovelace",
    organizationID = "57471841-aa79-445d-b4f7-1cbd073a3188",
    email = "ada@example.com",
    accessLevel = AccessLevel.Admin
)

val userAuth = UserAuthentication(authType = AuthType.Google)

val login = Login(
    method = "google",
    isSuccess = true
)

val event = login.toUserLogInSpec(user, userAuth)
Snowplow.defaultTracker?.track(event)
```

## React Native (TypeScript)

Generated code for the [React Native tracker](/docs/sources/react-native-tracker/). Snowtype produces TypeScript types with `track` and `create` functions, plus a `trackXSpec` function, in this case `trackUserLogInSpec`. This function automatically includes the required entities along with the event specification entity.

```json
{
  "orgId": "your-org-id",
  "tracker": "@snowplow/react-native-tracker",
  "language": "typescript",
  "outpath": "./src/tracking/snowplow",
  "dataProductIds": [],
  "eventSpecificationIds": ["a965caf1-88a6-4a89-9aea-cc92516a9d56"],
  "dataStructures": [],
  "igluCentralSchemas": []
}
```

```typescript
import { ReactNativeTracker } from '@snowplow/react-native-tracker';
// Automatically generated by Snowtype

/**
 * Captured when a user attempts to log in to their account. Tracks the method and outcome
 * of the authentication attempt.
 */
export type Login = {
    /**
     * An optional error code if the login attempt failed (e.g., 'invalid_password',
     * 'user_not_found').
     */
    error_code?: null | string;
    /**
     * Whether the login attempt was successful.
     */
    is_success: boolean;
    /**
     * The method used to authenticate, such as 'email', 'google', 'apple', or 'saml'.
     */
    method: string;
}

/**
 * A subset of the user fields from the users-service
 */
export type User = {
    /**
     * The users access level.
     */
    accessLevel?: AccessLevel;
    /**
     * The users email address.
     */
    email?: null | string;
    /**
     * The users first name.
     */
    firstName: string;
    /**
     * The users job title.
     */
    jobTitle?: null | string;
    /**
     * The users last name.
     */
    lastName: string;
    /**
     * The organization's UUID that the user belongs to.
     */
    organizationId: string;
    /**
     * The users UUID.
     */
    userId: string;
}

/**
 * The users access level.
 */
export type AccessLevel = "Admin" | "User" | "Custom";

/**
 * Data structure that defines how the user logged in
 */
export type UserAuthentication = {
    /**
     * Type of authentication used
     */
    auth_type: AuthType;
}

/**
 * Type of authentication used
 */
export type AuthType = "google" | "facebook" | "manual";

interface CommonEventProperties<T = Record<string, unknown>> {
    /** Add context to an event by setting an Array of Self Describing JSON */
    contexts?: Array<SelfDescribing<T>>;
}

type Contexts<T = any> = Omit<CommonEventProperties<T>, 'context'> & { context?: SelfDescribing<T>[] }

/**
 * SelfDescribing type
 */
export type SelfDescribing<T extends Record<keyof T, unknown> = Record<string, unknown>> = {
        /**
         * The schema string
         * @example 'iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0'
         */
        schema: string;
        /**
         * The data object which should conform to the supplied schema
         */
        data: T;
};


/**
 * Creates a Snowplow Event Specification entity.
 */
export function createEventSpecification(eventSpecification: Omit<EventSpecification, 'data_product_domain'> & Partial<Pick<EventSpecification, 'data_product_domain'>>){
    return {
        schema:
            'iglu:com.snowplowanalytics.snowplow/event_specification/jsonschema/1-0-4',
        data: eventSpecification,
    }
}

/**
 * Automatically attached context for event specifications
 */
interface EventSpecification {
    id: string;
    version: number;
    name: string;
    data_product_id: string;
    data_product_name: string;
    data_product_domain?: string;
}

/**
 * Track a Snowplow event for Login.
 * Captured when a user attempts to log in to their account. Tracks the method and outcome of the authentication attempt.
 */
export function trackLogin<T extends {} = any>(tracker: ReactNativeTracker, login: Login & Contexts<T>){
    const { contexts, ...data } = login;
    tracker.trackSelfDescribingEvent({
        schema: 'iglu:com.snplow.msc.aws/login/jsonschema/1-0-0',
        data
    }, contexts);
}

/**
 * Creates a Snowplow Login entity.
 */
export function createLogin(login: Login){
    return {
        schema: 'iglu:com.snplow.msc.aws/login/jsonschema/1-0-0',
        data: login
    }
}
/**
 * Track a Snowplow event for User.
 * A subset of the user fields from the users-service
 */
export function trackUser<T extends {} = any>(tracker: ReactNativeTracker, user: User & Contexts<T>){
    const { contexts, ...data } = user;
    tracker.trackSelfDescribingEvent({
        schema: 'iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1',
        data
    }, contexts);
}

/**
 * Creates a Snowplow User entity.
 */
export function createUser(user: User){
    return {
        schema: 'iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1',
        data: user
    }
}
/**
 * Track a Snowplow event for UserAuthentication.
 * Data structure that defines how the user logged in
 */
export function trackUserAuthentication<T extends {} = any>(tracker: ReactNativeTracker, userAuthentication: UserAuthentication & Contexts<T>){
    const { contexts, ...data } = userAuthentication;
    tracker.trackSelfDescribingEvent({
        schema: 'iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0',
        data
    }, contexts);
}

/**
 * Creates a Snowplow UserAuthentication entity.
 */
export function createUserAuthentication(userAuthentication: UserAuthentication){
    return {
        schema: 'iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0',
        data: userAuthentication
    }
}

/**
 * Tracks a UserLogIn event specification.
 */
export function trackUserLogInSpec(tracker: ReactNativeTracker, userLogIn: Login & Contexts<User | UserAuthentication>){
    const eventSpecificationContext = createEventSpecification({
        id: 'a965caf1-88a6-4a89-9aea-cc92516a9d56',
        version: 8,
        name: 'User Log In',
        data_product_id: '57471841-aa79-445d-b4f7-1cbd073a3188',
        data_product_name: 'Checkout Flow',
        data_product_domain: 'Marketing'
    });

    const contexts = Array.isArray(userLogIn.contexts)
        ? [...userLogIn.contexts, eventSpecificationContext]
        : [eventSpecificationContext];

    const modifiedUserLogIn = {
        ...userLogIn,
        contexts,
    } as Login & Contexts<User | UserAuthentication>;

    trackLogin<User | UserAuthentication>(tracker, modifiedUserLogIn);
}
```

Here's how you could use the generated code:

```tsx
import {
  trackUserLogInSpec,
  createUser,
  createUserAuthentication,
} from "./src/tracking/snowplow";

/*
 * `t` is the tracker instance created by the
 * `createTracker` function of @snowplow/react-native-tracker.
 */

const user = createUser({
  userId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  firstName: "Ada",
  lastName: "Lovelace",
  organizationId: "57471841-aa79-445d-b4f7-1cbd073a3188",
  email: "ada@example.com",
  accessLevel: "Admin",
});

const userAuth = createUserAuthentication({ auth_type: "google" });

trackUserLogInSpec(t, {
  method: "google",
  is_success: true,
  contexts: [user, userAuth],
});
```

## Flutter (Dart)

Generated code for the [Flutter tracker](/docs/sources/flutter-tracker/). Snowtype produces immutable Dart classes that implement `SelfDescribing`, with `schema`, `data`, and `toMap()` accessors, plus a `toXSpec()` extension function for the event that bundles it with its required entities and attaches the event specification entity. In this case, a `toUserLogInSpec()` extension on `Login`.

```json
{
  "orgId": "your-org-id",
  "tracker": "snowplow-flutter-tracker",
  "language": "dart",
  "outpath": "./lib/tracking/snowplow",
  "dataProductIds": [],
  "eventSpecificationIds": ["a965caf1-88a6-4a89-9aea-cc92516a9d56"],
  "dataStructures": [],
  "igluCentralSchemas": []
}
```

````dart
import 'package:flutter/foundation.dart';
import 'package:snowplow_tracker/events/self_describing.dart';

/// Captured when a user attempts to log in to their account. Tracks the method and outcome of the authentication attempt.
/// Schema: `iglu:com.snplow.msc.aws/login/jsonschema/1-0-0`
@immutable
class Login implements SelfDescribing {

    /// An optional error code if the login attempt failed (e.g., 'invalid_password',,'user_not_found').
    final String? errorCode;

    /// Whether the login attempt was successful.
    final bool isSuccess;

    /// The method used to authenticate, such as 'email', 'google', 'apple', or 'saml'.
    final String method;

    const Login({
        this.errorCode,
        required this.isSuccess,
        required this.method
    });

    @override
    String endpoint() {
        return 'trackSelfDescribing';
    }

    @override
    Map<String, Object?> get data {
        return {
            if (errorCode != null) 'error_code': errorCode,
            'is_success': isSuccess,
            'method': method,
        };
    }

    @override
    String get schema => 'iglu:com.snplow.msc.aws/login/jsonschema/1-0-0';

    @override
    Map<String, Object?> toMap() {
        return {
            'schema': schema,
            'data': data,
        };
    }
}
/// A subset of the user fields from the users-service
/// Schema: `iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1`
@immutable
class User implements SelfDescribing {

    /// The users access level.
    final AccessLevel? accessLevel;

    /// The users email address.
    final String? email;

    /// The users first name.
    final String firstName;

    /// The users job title.
    final String? jobTitle;

    /// The users last name.
    final String lastName;

    /// The organization's UUID that the user belongs to.
    final String organizationId;

    /// The users UUID.
    final String userId;

    const User({
        this.accessLevel,
        this.email,
        required this.firstName,
        this.jobTitle,
        required this.lastName,
        required this.organizationId,
        required this.userId
    });

    @override
    String endpoint() {
        return 'trackSelfDescribing';
    }

    @override
    Map<String, Object?> get data {
        return {
            if (accessLevel != null) 'accessLevel': accessLevel?.value,
            if (email != null) 'email': email,
            'firstName': firstName,
            if (jobTitle != null) 'jobTitle': jobTitle,
            'lastName': lastName,
            'organizationId': organizationId,
            'userId': userId,
        };
    }

    @override
    String get schema => 'iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1';

    @override
    Map<String, Object?> toMap() {
        return {
            'schema': schema,
            'data': data,
        };
    }
}
/// Data structure that defines how the user logged in
/// Schema: `iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0`
@immutable
class UserAuthentication implements SelfDescribing {

    /// Type of authentication used
    final AuthType authType;

    const UserAuthentication({
        required this.authType
    });

    @override
    String endpoint() {
        return 'trackSelfDescribing';
    }

    @override
    Map<String, Object?> get data {
        return {
            'auth_type': authType.value,
        };
    }

    @override
    String get schema => 'iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0';

    @override
    Map<String, Object?> toMap() {
        return {
            'schema': schema,
            'data': data,
        };
    }
}

/// The users access level.
enum AccessLevel {
    admin("Admin"),
    custom("Custom"),
    user("User");

    const AccessLevel(this.value);
    final String value;
}

/// Type of authentication used
enum AuthType {
    facebook("facebook"),
    google("google"),
    manual("manual");

    const AuthType(this.value);
    final String value;
}

/// For internal use.
@immutable
class EventSpecification {
    final SelfDescribing event;
    final List<SelfDescribing> contexts;

    const EventSpecification({
        required this.event,
        required this.contexts
    });
}

/// For internal use.
@immutable
class EventSpecEntity implements SelfDescribing {
    /// Identifier for the data product that the event specification belongs to
    final String? dataProductId;
    /// Name for the data product that the event specification belongs to
    final String? dataProductName;
    /// Domain of the data product that the event specification belongs to
    final String? dataProductDomain;
    /// Identifier for the event specification that the event adheres to
    final String id;
    /// Version of the event specification that the event adheres to
    final int version;
    /// Name for the event specification that the event adheres to
    final String? name;
    const EventSpecEntity({
        this.dataProductId,
        this.dataProductName,
        this.dataProductDomain,
        required this.id,
        required this.version,
        this.name
    });

    @override
    String endpoint() {
            return 'trackSelfDescribing';
    }

    @override
    Map<String, Object?> get data {
        return {
            if (dataProductId != null) 'data_product_id': dataProductId,
            if (dataProductName != null) 'data_product_name': dataProductName,
            if (dataProductDomain != null) 'data_product_domain': dataProductDomain,
            'id': id,
            'version': version,
            if (name != null) 'name': name,
        };
    }

    @override
    String get schema => 'iglu:com.snowplowanalytics.snowplow/event_specification/jsonschema/1-0-4';

    @override
    Map<String, Object?> toMap() {
        return {
            'schema': schema,
            'data': data,
        };
    }
}

/// Creates an event with entities for a UserLogIn event specification.
/// ID: a965caf1-88a6-4a89-9aea-cc92516a9d56
/// Example:
/// ```dart
/// const baseEvent = Login(...);
/// final eventSpec = baseEvent.toUserLogInSpec(
///   dataUser: User(...), dataUserAuthentication: UserAuthentication(...)
/// );
/// /// Track as an event and list of context entities
/// tracker.track(eventSpec.event, contexts: eventSpec.contexts);
/// ```
extension UserLogInEventSpec on Login {
    EventSpecification toUserLogInSpec({ required User dataUser, required UserAuthentication dataUserAuthentication }) {
        final entities = <SelfDescribing>[];
        const eventSpecEntity = EventSpecEntity(
            id: "a965caf1-88a6-4a89-9aea-cc92516a9d56",
            version: 8,
            name: "User Log In",
            dataProductId: "57471841-aa79-445d-b4f7-1cbd073a3188",
            dataProductName: "Checkout Flow",
            dataProductDomain: 'Marketing'
        );
        entities.add(eventSpecEntity);
        entities.add(dataUser);
        entities.add(dataUserAuthentication);
        return EventSpecification(
            event: this,
            contexts: entities
        );
    }
}
````

Here's how you could use the generated code:

```dart
import './lib/tracking/snowplow/snowtype.dart';

const login = Login(method: "google", isSuccess: true);
final eventSpec = login.toUserLogInSpec(
  dataUser: User(
    userId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    firstName: "Ada",
    lastName: "Lovelace",
    organizationId: "57471841-aa79-445d-b4f7-1cbd073a3188",
    email: "ada@example.com",
    accessLevel: AccessLevel.admin,
  ),
  dataUserAuthentication: UserAuthentication(authType: AuthType.google),
);
await tracker.track(eventSpec.event, contexts: eventSpec.contexts);
```

## Node.js

Snowtype can generate code in TypeScript or JavaScript for the [Node.js tracker](/docs/sources/node-js-tracker/).

### TypeScript

Snowtype generates TypeScript type definitions and typed `track` and `create` functions that import directly from `@snowplow/node-tracker`, plus a `trackXSpec` function, in this case `trackUserLogInSpec`. This function automatically includes the required entities along with the event specification entity.

```json
{
  "orgId": "your-org-id",
  "tracker": "@snowplow/node-tracker",
  "language": "typescript",
  "outpath": "./src/tracking/snowplow",
  "dataProductIds": [],
  "eventSpecificationIds": ["a965caf1-88a6-4a89-9aea-cc92516a9d56"],
  "dataStructures": [],
  "igluCentralSchemas": []
}
```

```typescript
import { buildSelfDescribingEvent, SelfDescribingJson, Timestamp, Tracker } from '@snowplow/node-tracker';
// Automatically generated by Snowtype

/**
 * Captured when a user attempts to log in to their account. Tracks the method and outcome
 * of the authentication attempt.
 */
export type Login = {
    /**
     * An optional error code if the login attempt failed (e.g., 'invalid_password',
     * 'user_not_found').
     */
    error_code?: null | string;
    /**
     * Whether the login attempt was successful.
     */
    is_success: boolean;
    /**
     * The method used to authenticate, such as 'email', 'google', 'apple', or 'saml'.
     */
    method: string;
}

/**
 * A subset of the user fields from the users-service
 */
export type User = {
    /**
     * The users access level.
     */
    accessLevel?: AccessLevel;
    /**
     * The users email address.
     */
    email?: null | string;
    /**
     * The users first name.
     */
    firstName: string;
    /**
     * The users job title.
     */
    jobTitle?: null | string;
    /**
     * The users last name.
     */
    lastName: string;
    /**
     * The organization's UUID that the user belongs to.
     */
    organizationId: string;
    /**
     * The users UUID.
     */
    userId: string;
}

/**
 * The users access level.
 */
export type AccessLevel = "Admin" | "User" | "Custom";

/**
 * Data structure that defines how the user logged in
 */
export type UserAuthentication = {
    /**
     * Type of authentication used
     */
    auth_type: AuthType;
}

/**
 * Type of authentication used
 */
export type AuthType = "google" | "facebook" | "manual";

interface CommonEventProperties<T = Record<string, unknown>> {
    /** Add context to an event by setting an Array of Self Describing JSON */
    context?: Array<SelfDescribingJson<T>> | null;
    /** Set the true timestamp or overwrite the device sent timestamp on an event */
    timestamp?: Timestamp | null;
}

/**
 * Creates a Snowplow Event Specification entity.
 */
export function createEventSpecification(eventSpecification: Omit<EventSpecification, 'data_product_domain'> & Partial<Pick<EventSpecification, 'data_product_domain'>>){
    return {
        schema:
            'iglu:com.snowplowanalytics.snowplow/event_specification/jsonschema/1-0-4',
        data: eventSpecification,
    }
}

/**
 * Automatically attached context for event specifications
 */
interface EventSpecification {
    id: string;
    version: number;
    name: string;
    data_product_id: string;
    data_product_name: string;
    data_product_domain?: string;
}

type ContextsOrTimestamp<T = any> = Omit<CommonEventProperties<T>, 'context'> & { context?: SelfDescribingJson<T>[] | null | undefined }

/**
 * Track a Snowplow event for Login.
 * Captured when a user attempts to log in to their account. Tracks the method and outcome of the authentication attempt.
 */
export function trackLogin<T extends {} = any>(tracker: Tracker, login: Login & ContextsOrTimestamp<T>){
    const { context, timestamp, ...data } = login;
    tracker.track(buildSelfDescribingEvent({
        event: {
            schema: 'iglu:com.snplow.msc.aws/login/jsonschema/1-0-0',
            data
        }
    }), context, timestamp);
}

/**
 * Creates a Snowplow Login entity.
 */
export function createLogin(login: Login){
    return {
        schema: 'iglu:com.snplow.msc.aws/login/jsonschema/1-0-0',
        data: login
    }
}
/**
 * Track a Snowplow event for User.
 * A subset of the user fields from the users-service
 */
export function trackUser<T extends {} = any>(tracker: Tracker, user: User & ContextsOrTimestamp<T>){
    const { context, timestamp, ...data } = user;
    tracker.track(buildSelfDescribingEvent({
        event: {
            schema: 'iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1',
            data
        }
    }), context, timestamp);
}

/**
 * Creates a Snowplow User entity.
 */
export function createUser(user: User){
    return {
        schema: 'iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1',
        data: user
    }
}
/**
 * Track a Snowplow event for UserAuthentication.
 * Data structure that defines how the user logged in
 */
export function trackUserAuthentication<T extends {} = any>(tracker: Tracker, userAuthentication: UserAuthentication & ContextsOrTimestamp<T>){
    const { context, timestamp, ...data } = userAuthentication;
    tracker.track(buildSelfDescribingEvent({
        event: {
            schema: 'iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0',
            data
        }
    }), context, timestamp);
}

/**
 * Creates a Snowplow UserAuthentication entity.
 */
export function createUserAuthentication(userAuthentication: UserAuthentication){
    return {
        schema: 'iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0',
        data: userAuthentication
    }
}

/**
 * Tracks a UserLogIn event specification.
 * ID: a965caf1-88a6-4a89-9aea-cc92516a9d56
 */
export function trackUserLogInSpec(tracker: Tracker, userLogIn: Login & ContextsOrTimestamp<User | UserAuthentication>){
    const eventSpecificationContext = createEventSpecification({
        id: 'a965caf1-88a6-4a89-9aea-cc92516a9d56',
        version: 8,
        name: 'User Log In',
        data_product_id: '57471841-aa79-445d-b4f7-1cbd073a3188',
        data_product_name: 'Checkout Flow',
        data_product_domain: 'Marketing'
    });

    const context = Array.isArray(userLogIn.context)
        ? [...userLogIn.context, eventSpecificationContext]
        : [eventSpecificationContext];

    const modifiedUserLogIn: Login & ContextsOrTimestamp<User | UserAuthentication | EventSpecification> = {
        ...userLogIn,
        context,
    };

    trackLogin(tracker, modifiedUserLogIn);
}
```

Here's how you could use the generated code in a Node.js project:

```tsx
import {
  trackUserLogInSpec,
  createUser,
  createUserAuthentication,
} from "./src/tracking/snowplow";

/*
 * `t` is the tracker instance created by the
 * `tracker` function of @snowplow/node-tracker.
 */

const user = createUser({
  userId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  firstName: "Ada",
  lastName: "Lovelace",
  organizationId: "57471841-aa79-445d-b4f7-1cbd073a3188",
  email: "ada@example.com",
  accessLevel: "Admin",
});

const userAuth = createUserAuthentication({ auth_type: "google" });

trackUserLogInSpec(t, {
  method: "google",
  is_success: true,
  context: [user, userAuth],
});
```

### JavaScript

Snowtype generates JSDoc typedefs and untyped `track` and `create` functions, with a `@typedef {object} Tracker` for the tracker instance parameter, plus a `trackXSpec` function, in this case `trackUserLogInSpec`. This function automatically includes the required entities along with the event specification entity.

```json
{
  "orgId": "your-org-id",
  "tracker": "@snowplow/node-tracker",
  "language": "javascript",
  "outpath": "./src/tracking/snowplow",
  "dataProductIds": [],
  "eventSpecificationIds": ["a965caf1-88a6-4a89-9aea-cc92516a9d56"],
  "dataStructures": [],
  "igluCentralSchemas": []
}
```

```javascript
import { buildSelfDescribingEvent } from '@snowplow/node-tracker';
// Automatically generated by Snowtype

/**
 * Typedef for a DeviceTimestamp
 * @typedef {object} DeviceTimestamp
 * @property {'dtm'} type The value of 'dtm'
 * @property {number} value The value of the device timestamp
 */

/**
 * Typedef for a TrueTimestamp
 * @typedef {object} TrueTimestamp
 * @property {'ttm'} type The value of 'ttm'
 * @property {number} value The value of the true timestamp
 */

/**
 * Typedef for a Timestamp
 * @typedef {object} Timestamp
 * @property {number|TrueTimestamp|DeviceTimestamp} [timestamp] The value of the timestamp
 */

/**
 * Typedef for a SelfDescribingJson
 * @typedef {object} SelfDescribingJson
 * @property {string} schema The schema of the context
 * @property {object} data The data to send for the context
 */

/**
 * Typedef for a Context
 * @typedef {object} Context
 * @property {SelfDescribingJson[]} [context] Contexts to include in the event
 */

/**
 * Captured when a user attempts to log in to their account. Tracks the method and outcome of the authentication attempt.
 * @typedef {object} Login
 * @property {string} method The method used to authenticate, such as 'email', 'google', 'apple', or 'saml'.
 * @property {?string} [error_code] An optional error code if the login attempt failed (e.g., 'invalid_password', 'user_not_found').
 * @property {boolean} is_success Whether the login attempt was successful.
 */


/**
 * Typedef for a Login entity context.
 * @typedef {object} LoginContext
 * @property {string} schema The schema of the context.
 * @property { Login } data The data to send for the context.
 */

/**
 * A subset of the user fields from the users-service
 * @typedef {object} User
 * @property {string} userId The users UUID.
 * @property {string} firstName The users first name.
 * @property {string} lastName The users last name.
 * @property {string} organizationId The organization's UUID that the user belongs to.
 * @property {?string} [email] The users email address.
 * @property {?string} [jobTitle] The users job title.
 * @property {"Admin"|"User"|"Custom"|null} [accessLevel] The users access level.
 */


/**
 * Typedef for a User entity context.
 * @typedef {object} UserContext
 * @property {string} schema The schema of the context.
 * @property { User } data The data to send for the context.
 */

/**
 * Data structure that defines how the user logged in
 * @typedef {object} UserAuthentication
 * @property {"google"|"facebook"|"manual"} auth_type Type of authentication used
 */


/**
 * Typedef for a UserAuthentication entity context.
 * @typedef {object} UserAuthenticationContext
 * @property {string} schema The schema of the context.
 * @property { UserAuthentication } data The data to send for the context.
 */

/**
 * Creates a Snowplow Event Specification entity.
 */
export function createEventSpecification(eventSpecification){
    return {
        schema:
            'iglu:com.snowplowanalytics.snowplow/event_specification/jsonschema/1-0-4',
        data: eventSpecification,
    }
}

/**
 * Typedef for a Node.js tracker object.
 * @typedef {object} Tracker
 */

/**
 * Track a Snowplow event for Login.
 * Captured when a user attempts to log in to their account. Tracks the method and outcome of the authentication attempt.
 * @param {Tracker} tracker - Tracker to send the event to.
 * @param { Login & Timestamp & Context } login - Attributes for Login.
 */
export function trackLogin(tracker, login){
    const { context, timestamp, ...data } = login;

    tracker.track(buildSelfDescribingEvent({
        event: {
            schema: 'iglu:com.snplow.msc.aws/login/jsonschema/1-0-0',
            data
        }
    }), context, timestamp);
}

/**
 * Creates a Snowplow Login entity.
 * @param { Login } login - Attributes for Login.
 */
export function createLogin(login){
    return {
        schema: 'iglu:com.snplow.msc.aws/login/jsonschema/1-0-0',
        data: login
    }
}
/**
 * Track a Snowplow event for User.
 * A subset of the user fields from the users-service
 * @param {Tracker} tracker - Tracker to send the event to.
 * @param { User & Timestamp & Context } user - Attributes for User.
 */
export function trackUser(tracker, user){
    const { context, timestamp, ...data } = user;

    tracker.track(buildSelfDescribingEvent({
        event: {
            schema: 'iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1',
            data
        }
    }), context, timestamp);
}

/**
 * Creates a Snowplow User entity.
 * @param { User } user - Attributes for User.
 */
export function createUser(user){
    return {
        schema: 'iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1',
        data: user
    }
}
/**
 * Track a Snowplow event for UserAuthentication.
 * Data structure that defines how the user logged in
 * @param {Tracker} tracker - Tracker to send the event to.
 * @param { UserAuthentication & Timestamp & Context } userAuthentication - Attributes for UserAuthentication.
 */
export function trackUserAuthentication(tracker, userAuthentication){
    const { context, timestamp, ...data } = userAuthentication;

    tracker.track(buildSelfDescribingEvent({
        event: {
            schema: 'iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0',
            data
        }
    }), context, timestamp);
}

/**
 * Creates a Snowplow UserAuthentication entity.
 * @param { UserAuthentication } userAuthentication - Attributes for UserAuthentication.
 */
export function createUserAuthentication(userAuthentication){
    return {
        schema: 'iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0',
        data: userAuthentication
    }
}

/**
 * Typedef for UserLogIn event specification contexts.
 * @typedef {object} LoginContexts
 * @property {(UserContext | UserAuthenticationContext)[]} [context] Contexts to include in the UserLogIn event specification.
 */

/**
 * Tracks a UserLogIn event specification.
 * ID: a965caf1-88a6-4a89-9aea-cc92516a9d56
 * @param {Tracker} tracker - Tracker to send the tracking event specification to.
 * @param { Login & Timestamp & LoginContexts } userLogIn - Attributes for UserLogIn event specification.
 */
export function trackUserLogInSpec(tracker, userLogIn){
    const eventSpecificationContext = createEventSpecification({
        id: 'a965caf1-88a6-4a89-9aea-cc92516a9d56',
        version: 8,
        name: 'User Log In',
        data_product_id: '57471841-aa79-445d-b4f7-1cbd073a3188',
        data_product_name: 'Checkout Flow',
        data_product_domain: 'Marketing'
    });

 const context = Array.isArray(userLogIn.context)
        ? [...userLogIn.context, eventSpecificationContext]
        : [eventSpecificationContext];

    const modifiedUserLogIn = {
        ...userLogIn,
        context,
    };

    trackLogin(tracker, modifiedUserLogIn);
}
```

Here's how you could use the generated code in a Node.js project:

```javascript
import {
  trackUserLogInSpec,
  createUser,
  createUserAuthentication,
} from "./src/tracking/snowplow";

/*
 * `t` is the tracker instance created by the
 * `tracker` function of @snowplow/node-tracker.
 */

const user = createUser({
  userId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  firstName: "Ada",
  lastName: "Lovelace",
  organizationId: "57471841-aa79-445d-b4f7-1cbd073a3188",
  email: "ada@example.com",
  accessLevel: "Admin",
});

const userAuth = createUserAuthentication({ auth_type: "google" });

trackUserLogInSpec(t, {
  method: "google",
  is_success: true,
  context: [user, userAuth],
});
```

## Golang

Generated code for the [Golang tracker](/docs/sources/golang-tracker/). Snowtype produces Go structs with `mapstructure` tags and `SnowplowFormat()` methods that implement the `SnowplowApplicable` interface, plus a `TrackXSpec` function, in this case `TrackUserLogInSpec`. This function automatically includes the required entities along with the event specification entity.

```json
{
  "orgId": "your-org-id",
  "tracker": "snowplow-golang-tracker",
  "language": "go",
  "outpath": "./tracking/snowtype",
  "dataProductIds": [],
  "eventSpecificationIds": ["a965caf1-88a6-4a89-9aea-cc92516a9d56"],
  "dataStructures": [],
  "igluCentralSchemas": []
}
```

```go
package snowtypegenerated

import "github.com/mitchellh/mapstructure"
import sp "github.com/snowplow/snowplow-golang-tracker/v3/tracker"

// Captured when a user attempts to log in to their account. Tracks the method and outcome
// of the authentication attempt.
type Login struct {
	// An optional error code if the login attempt failed (e.g., 'invalid_password',
	// 'user_not_found').
	ErrorCode                                                                         *string `mapstructure:"error_code"`
	// Whether the login attempt was successful.
	IsSuccess                                                                         bool    `mapstructure:"is_success"`
	// The method used to authenticate, such as 'email', 'google', 'apple', or 'saml'.
	Method                                                                            string  `mapstructure:"method"`
}

// A subset of the user fields from the users-service
type User struct {
	// The users access level.
	AccessLevel                                         *AccessLevel `mapstructure:"accessLevel,omitempty"`
	// The users email address.
	Email                                               *string      `mapstructure:"email"`
	// The users first name.
	FirstName                                           string       `mapstructure:"firstName"`
	// The users job title.
	JobTitle                                            *string      `mapstructure:"jobTitle"`
	// The users last name.
	LastName                                            string       `mapstructure:"lastName"`
	// The organization's UUID that the user belongs to.
	OrganizationID                                      string       `mapstructure:"organizationId"`
	// The users UUID.
	UserID                                              string       `mapstructure:"userId"`
}

// Data structure that defines how the user logged in
type UserAuthentication struct {
	// Type of authentication used
	AuthType                      AuthType `mapstructure:"auth_type"`
}

// The users access level.
type AccessLevel string

const (
	AccessLevelUser AccessLevel = "User"
	Admin           AccessLevel = "Admin"
	Custom          AccessLevel = "Custom"
)

// Type of authentication used
type AuthType string

const (
	Facebook AuthType = "facebook"
	Google   AuthType = "google"
	Manual   AuthType = "manual"
)

// SnowplowApplicable signifies ability to be formatted as self-describing json
type SnowplowApplicable interface {
	// SnowplowFormat constructs a Snowplow SelfDescribingJson
	SnowplowFormat() (*sp.SelfDescribingJson, error)
}

// internal type to provide functional options for the API
type option func(*sp.SelfDescribingEvent) error

// WithTimestamp returns an option to set the device timestamp
func WithTimestamp(tstamp int64) option {
	return func(sde *sp.SelfDescribingEvent) error {
		sde.Timestamp = &tstamp
		return nil
	}
}

// WithEventID returns an option to set the event_id
func WithEventID(id string) option {
	return func(sde *sp.SelfDescribingEvent) error {
		sde.EventId = &id
		return nil
	}
}

// WithTrueTimestamp returns an option to set the true timestamp
func WithTrueTimestamp(tstamp int64) option {
	return func(sde *sp.SelfDescribingEvent) error {
		sde.TrueTimestamp = &tstamp
		return nil
	}
}

// WithContexts returns an option to set the contexts of an event
func WithContexts(ctx ...SnowplowApplicable) option {
	return func(sde *sp.SelfDescribingEvent) error {
		finalCtx := make([]sp.SelfDescribingJson, len(ctx))
		var ctxErr error
		for i, val := range ctx {
			ctxSdj, ctxErr := val.SnowplowFormat()
			if ctxErr != nil {
				break
			}
			finalCtx[i] = *ctxSdj
		}
		if ctxErr != nil {
			return ctxErr
		}
		sde.Contexts = finalCtx
		return nil
	}
}

// WithSubject returns an option to set the Subject
func WithSubject(subject *sp.Subject) option {
	return func(sde *sp.SelfDescribingEvent) error {
		sde.Subject = subject
		return nil
	}
}

// Entity schema for referencing an event specification
type EventSpecification struct {
	// Identifier for the event specification that the event adheres to
	Id string `mapstructure:"id"`
	Version uint32 `mapstructure:"version"`
	Name string `mapstructure:"name"`
	DataProductId string `mapstructure:"data_product_id"`
	DataProductName string `mapstructure:"data_product_name"`
	DataProductDomain string `mapstructure:"data_product_domain,omitempty"`
}

// SnowplowFormat implements SnowplowApplicable
func (eventSpecification EventSpecification) SnowplowFormat() (*sp.SelfDescribingJson, error) {
	var decodedMap map[string]interface{}
	err := mapstructure.Decode(eventSpecification, &decodedMap)
	if err != nil {
		return nil, err
	}

	sdj := sp.InitSelfDescribingJson("iglu:com.snowplowanalytics.snowplow/event_specification/jsonschema/1-0-4", decodedMap)
	return sdj, nil
}


// SnowplowFormat implements SnowplowApplicable
func (login Login) SnowplowFormat() (*sp.SelfDescribingJson, error) {
	var decodedMap map[string]interface{}
	err := mapstructure.Decode(login, &decodedMap)
	if err != nil {
		return nil, err
	}

	sdj := sp.InitSelfDescribingJson("iglu:com.snplow.msc.aws/login/jsonschema/1-0-0", decodedMap)
	return sdj, nil
}

// TrackLogin tracks a Login
func TrackLogin(tracker *sp.Tracker, login Login, opts ...option) error {
	sdj, err := login.SnowplowFormat()
	if err != nil {
		return err
	}

	sde := &sp.SelfDescribingEvent{Event: sdj}
	for _, opt := range opts {
		opt(sde)
	}

	tracker.TrackSelfDescribingEvent(*sde)
	return nil
}


// SnowplowFormat implements SnowplowApplicable
func (user User) SnowplowFormat() (*sp.SelfDescribingJson, error) {
	var decodedMap map[string]interface{}
	err := mapstructure.Decode(user, &decodedMap)
	if err != nil {
		return nil, err
	}

	sdj := sp.InitSelfDescribingJson("iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1", decodedMap)
	return sdj, nil
}

// TrackUser tracks a User
func TrackUser(tracker *sp.Tracker, user User, opts ...option) error {
	sdj, err := user.SnowplowFormat()
	if err != nil {
		return err
	}

	sde := &sp.SelfDescribingEvent{Event: sdj}
	for _, opt := range opts {
		opt(sde)
	}

	tracker.TrackSelfDescribingEvent(*sde)
	return nil
}


// SnowplowFormat implements SnowplowApplicable
func (userAuthentication UserAuthentication) SnowplowFormat() (*sp.SelfDescribingJson, error) {
	var decodedMap map[string]interface{}
	err := mapstructure.Decode(userAuthentication, &decodedMap)
	if err != nil {
		return nil, err
	}

	sdj := sp.InitSelfDescribingJson("iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0", decodedMap)
	return sdj, nil
}

// TrackUserAuthentication tracks a UserAuthentication
func TrackUserAuthentication(tracker *sp.Tracker, userAuthentication UserAuthentication, opts ...option) error {
	sdj, err := userAuthentication.SnowplowFormat()
	if err != nil {
		return err
	}

	sde := &sp.SelfDescribingEvent{Event: sdj}
	for _, opt := range opts {
		opt(sde)
	}

	tracker.TrackSelfDescribingEvent(*sde)
	return nil
}



// UserLogInApplicable represents a context applicable to UserLogIn event specification
type UserLogInApplicable interface {
	UserLogInFormat() (*sp.SelfDescribingJson, error)
}


// UserLogInFormat implements UserLogInApplicable
func (user User) UserLogInFormat() (*sp.SelfDescribingJson, error) {
	return user.SnowplowFormat()
}


// UserLogInFormat implements UserLogInApplicable
func (userAuthentication UserAuthentication) UserLogInFormat() (*sp.SelfDescribingJson, error) {
	return userAuthentication.SnowplowFormat()
}


// UserLogIn Event Specification
type UserLogIn struct {
	Event    Login
	Contexts []UserLogInApplicable
}


// TrackUserLogInSpec tracks UserLogIn event specification
// ID: a965caf1-88a6-4a89-9aea-cc92516a9d56
func TrackUserLogInSpec(tracker *sp.Tracker, userLogIn UserLogIn, opts ...option) error {
	event := userLogIn.Event
	sdj, err := event.SnowplowFormat()
	if err != nil {
		return err
	}

	sde := &sp.SelfDescribingEvent{Event: sdj}
	var optErr error
	for _, opt := range opts {
		optErr = opt(sde)
		if optErr != nil {
			break
		}
	}
	if optErr != nil {
		return optErr
	}

	eventSpecificationCtx := make([]sp.SelfDescribingJson, len(userLogIn.Contexts))
	var ctxErr error
	for i, val := range userLogIn.Contexts {
		ctxSdj, ctxErr := val.UserLogInFormat()
		if ctxErr != nil {
			break
		}
		eventSpecificationCtx[i] = *ctxSdj
	}
	if ctxErr != nil {
		return ctxErr
	}

	eventSpec := EventSpecification{
		Id: "a965caf1-88a6-4a89-9aea-cc92516a9d56",
		Version: 8,
		Name: "User Log In",
		DataProductId : "57471841-aa79-445d-b4f7-1cbd073a3188",
		DataProductName: "Checkout Flow",
		DataProductDomain: "Marketing",
	}
	eventSpecSdj, err := eventSpec.SnowplowFormat()
	if err != nil {
		return err
	}
	eventSpecificationCtx = append(eventSpecificationCtx, *eventSpecSdj)

	sde.Contexts = append(sde.Contexts, eventSpecificationCtx...)
	tracker.TrackSelfDescribingEvent(*sde)
	return nil
}
```

Here's how you could use the generated code in a Go project:

```go
email := "ada@example.com"
accessLevel := Admin

err := TrackUserLogInSpec(tracker, UserLogIn{
	Event: Login{
		Method:    "google",
		IsSuccess: true,
	},
	Contexts: []UserLogInApplicable{
		User{
			UserID:         "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
			FirstName:      "Ada",
			LastName:       "Lovelace",
			OrganizationID: "57471841-aa79-445d-b4f7-1cbd073a3188",
			Email:          &email,
			AccessLevel:    &accessLevel,
		},
		UserAuthentication{AuthType: Google},
	},
})
```

## Java

Generated code for the [Java tracker](/docs/sources/java-tracker/). Snowtype produces Java classes with a Builder pattern, `toSelfDescribingJson()` methods, and Javadoc comments. Each class is generated as a separate file.

Enums and the `EventSpecification` class are also generated separately, along with a `Snowtype` class containing a static `xSpec()` method, in this case `userLogInSpec()`. This method automatically includes the required entities along with the event specification entity.

```json
{
  "orgId": "your-org-id",
  "tracker": "snowplow-java-tracker",
  "language": "java",
  "outpath": "./src/main/java/snowtype",
  "dataProductIds": [],
  "eventSpecificationIds": ["a965caf1-88a6-4a89-9aea-cc92516a9d56"],
  "dataStructures": [],
  "igluCentralSchemas": []
}
```

```java
package com.snowplowanalytics.snowplow.snowtype;
import com.snowplowanalytics.snowplow.tracker.payload.SelfDescribingJson;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


public class Login {
        /** An optional error code if the login attempt failed (e.g., 'invalid_password',
        'user_not_found'). */
        private final String errorCode;
        /** Whether the login attempt was successful. */
        private final boolean isSuccess;
        /** The method used to authenticate, such as 'email', 'google', 'apple', or 'saml'. */
        private final String method;
        private static final String SCHEMA = "iglu:com.snplow.msc.aws/login/jsonschema/1-0-0";

        private Login(Builder builder) {
                this.errorCode = builder.errorCode;
                this.isSuccess = Objects.requireNonNull(builder.isSuccess, "isSuccess is required");
                this.method = Objects.requireNonNull(builder.method, "method is required");
        }

        private Map<String, Object> getPayload() {
                Map<String, Object> payload = new HashMap<>();
                if (errorCode != null) payload.put("error_code", errorCode);
                payload.put("is_success", isSuccess);
                payload.put("method", method);
                return payload;
        }

        /** Creates a self describing json. */
        public SelfDescribingJson toSelfDescribingJson() {
                return new SelfDescribingJson(SCHEMA, getPayload());
        }

        public static class Builder {
                private String errorCode;
                private boolean isSuccess;
                private String method;

                public Builder setErrorCode(String errorCode) {
                        this.errorCode = errorCode;
                        return this;
                }

                public Builder setIsSuccess(boolean isSuccess) {
                        this.isSuccess = isSuccess;
                        return this;
                }

                public Builder setMethod(String method) {
                        this.method = method;
                        return this;
                }

                public Login build() {
                        return new Login(this);
                }
        }
}
```

```java
package com.snowplowanalytics.snowplow.snowtype;
import com.snowplowanalytics.snowplow.tracker.payload.SelfDescribingJson;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


public class User {
        /** The users access level. */
        private final AccessLevel accessLevel;
        /** The users email address. */
        private final String email;
        /** The users first name. */
        private final String firstName;
        /** The users job title. */
        private final String jobTitle;
        /** The users last name. */
        private final String lastName;
        /** The organization's UUID that the user belongs to. */
        private final UUID organizationID;
        /** The users UUID. */
        private final UUID userID;
        private static final String SCHEMA = "iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1";

        private User(Builder builder) {
                this.accessLevel = builder.accessLevel;
                this.email = builder.email;
                this.firstName = Objects.requireNonNull(builder.firstName, "firstName is required");
                this.jobTitle = builder.jobTitle;
                this.lastName = Objects.requireNonNull(builder.lastName, "lastName is required");
                this.organizationID = Objects.requireNonNull(builder.organizationID, "organizationID is required");
                this.userID = Objects.requireNonNull(builder.userID, "userID is required");
        }

        private Map<String, Object> getPayload() {
                Map<String, Object> payload = new HashMap<>();
                if (accessLevel != null) payload.put("accessLevel", accessLevel);
                if (email != null) payload.put("email", email);
                payload.put("firstName", firstName);
                if (jobTitle != null) payload.put("jobTitle", jobTitle);
                payload.put("lastName", lastName);
                payload.put("organizationId", organizationID);
                payload.put("userId", userID);
                return payload;
        }

        /** Creates a self describing json. */
        public SelfDescribingJson toSelfDescribingJson() {
                return new SelfDescribingJson(SCHEMA, getPayload());
        }

        public static class Builder {
                private AccessLevel accessLevel;
                private String email;
                private String firstName;
                private String jobTitle;
                private String lastName;
                private UUID organizationID;
                private UUID userID;

                public Builder setAccessLevel(AccessLevel accessLevel) {
                        this.accessLevel = accessLevel;
                        return this;
                }

                public Builder setEmail(String email) {
                        this.email = email;
                        return this;
                }

                public Builder setFirstName(String firstName) {
                        this.firstName = firstName;
                        return this;
                }

                public Builder setJobTitle(String jobTitle) {
                        this.jobTitle = jobTitle;
                        return this;
                }

                public Builder setLastName(String lastName) {
                        this.lastName = lastName;
                        return this;
                }

                public Builder setOrganizationID(UUID organizationID) {
                        this.organizationID = organizationID;
                        return this;
                }

                public Builder setUserID(UUID userID) {
                        this.userID = userID;
                        return this;
                }

                public User build() {
                        return new User(this);
                }
        }
}
```

```java
package com.snowplowanalytics.snowplow.snowtype;
import com.snowplowanalytics.snowplow.tracker.payload.SelfDescribingJson;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


public class UserAuthentication {
        /** Type of authentication used */
        private final AuthType authType;
        private static final String SCHEMA = "iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0";

        private UserAuthentication(Builder builder) {
                this.authType = Objects.requireNonNull(builder.authType, "authType is required");
        }

        private Map<String, Object> getPayload() {
                Map<String, Object> payload = new HashMap<>();
                payload.put("auth_type", authType.getString());
                return payload;
        }

        /** Creates a self describing json. */
        public SelfDescribingJson toSelfDescribingJson() {
                return new SelfDescribingJson(SCHEMA, getPayload());
        }

        public static class Builder {
                private AuthType authType;

                public Builder setAuthType(AuthType authType) {
                        this.authType = authType;
                        return this;
                }

                public UserAuthentication build() {
                        return new UserAuthentication(this);
                }
        }
}
```

```java
package com.snowplowanalytics.snowplow.snowtype;

/**
 * The users access level.
*/
public enum AccessLevel{
        ADMIN("Admin"),
        CUSTOM("Custom"),
        USER("User");

        private final String value;

        AccessLevel(String value) {
                this.value = value;
        }

        public String getString() {
                return value;
        }
}
```

```java
package com.snowplowanalytics.snowplow.snowtype;

/**
 * Type of authentication used
*/
public enum AuthType{
        FACEBOOK("facebook"),
        GOOGLE("google"),
        MANUAL("manual");

        private final String value;

        AuthType(String value) {
                this.value = value;
        }

        public String getString() {
                return value;
        }
}
```

```java
package com.snowplowanalytics.snowplow.snowtype;
import com.snowplowanalytics.snowplow.tracker.payload.SelfDescribingJson;

import java.util.HashMap;
import java.util.Map;


public class EventSpecification {
        private final String id;
        private final String name;
        private final int version;
        private final String dataProductId;
        private final String dataProductName;
        private final String dataProductDomain;
        private static final String SCHEMA =
                "iglu:com.snowplowanalytics.snowplow/event_specification/jsonschema/1-0-4";

        public EventSpecification(String id, int version, String name,
                        String dataProductId, String dataProductName, String dataProductDomain) {
                this.id = id;
                this.version = version;
                this.name = name;
                this.dataProductId = dataProductId;
                this.dataProductName = dataProductName;
                this.dataProductDomain = dataProductDomain;
        }

        public EventSpecification(String id, int version, String name,
                        String dataProductId, String dataProductName) {
                this(id, version, name, dataProductId, dataProductName, null);
        }

        private Map<String, Object> getPayload() {
                Map<String, Object> payload = new HashMap<>();
                payload.put("id", id);
                payload.put("version", version);
                payload.put("name", name);
                payload.put("data_product_id", dataProductId);
                payload.put("data_product_name", dataProductName);
                if (dataProductDomain != null) {
                        payload.put("data_product_domain", dataProductDomain);
                }
                return payload;
        }

        /** Creates an entity that can be added to events. */
        public SelfDescribingJson toSelfDescribingJson() {
                return new SelfDescribingJson(SCHEMA, getPayload());
        }
}
```

```java
package com.snowplowanalytics.snowplow.snowtype;
import com.snowplowanalytics.snowplow.tracker.payload.SelfDescribingJson;
import com.snowplowanalytics.snowplow.tracker.events.SelfDescribing;

import java.util.Arrays;

public class Snowtype {

        public static SelfDescribing userLogInSpec(Login login,
                        User entityUser, UserAuthentication entityUserAuthentication) {
                SelfDescribingJson event = login.toSelfDescribingJson();
                EventSpecification eventSpec = new EventSpecification(
                        "a965caf1-88a6-4a89-9aea-cc92516a9d56",
                        8,
                        "User Log In",
                        "57471841-aa79-445d-b4f7-1cbd073a3188",
                        "Checkout Flow",
                        "Marketing"
                );
                return SelfDescribing
                        .builder()
                        .eventData(event)
                        .customContext(Arrays.asList(
                                entityUser.toSelfDescribingJson(),
                                entityUserAuthentication.toSelfDescribingJson(),
                                eventSpec.toSelfDescribingJson()))
                        .build();
        }
}
```

Here's how you could use the generated code:

```java
import com.snowplowanalytics.snowplow.snowtype.*;

Login login = new Login.Builder()
    .setIsSuccess(true)
    .setMethod("google")
    .build();

User user = new User.Builder()
    .setFirstName("Ada")
    .setLastName("Lovelace")
    .setOrganizationID(UUID.fromString("57471841-aa79-445d-b4f7-1cbd073a3188"))
    .setUserID(UUID.fromString("a1b2c3d4-e5f6-7890-abcd-ef1234567890"))
    .setEmail("ada@example.com")
    .setAccessLevel(AccessLevel.ADMIN)
    .build();

UserAuthentication userAuth = new UserAuthentication.Builder()
    .setAuthType(AuthType.GOOGLE)
    .build();

tracker.track(Snowtype.userLogInSpec(login, user, userAuth));
```

## Google Tag Manager (JavaScript)

Generated code for [Google Tag Manager](/docs/sources/google-tag-manager/). Snowtype produces a single function that assigns tracking methods to `window.__snowtype`, including `trackXSpec`, designed to be used in a GTM [Custom JavaScript Variable](/docs/event-studio/implement-tracking/working-with-gtm/).

Snowtype will also generate a minified version.

```json
{
  "orgId": "your-org-id",
  "tracker": "google-tag-manager",
  "language": "javascript-gtm",
  "outpath": "./gtm",
  "dataProductIds": [],
  "eventSpecificationIds": ["a965caf1-88a6-4a89-9aea-cc92516a9d56"],
  "dataStructures": [],
  "igluCentralSchemas": []
}
```

```javascript
// Automatically generated by Snowtype
// This code should be copied and pasted in a Google Tag Manager Custom JavaScript Variable

function snowtypeInit() {
    function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], t.indexOf(o) >= 0 || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
    function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.indexOf(n) >= 0) continue; t[n] = r[n]; } return t; }

    /**
    * Creates a Snowplow Event Specification entity.
    */
    function createEventSpecification(eventSpecification){
        return {
            schema: 'iglu:com.snowplowanalytics.snowplow/event_specification/jsonschema/1-0-4',
            data: eventSpecification,
        }
    }

    window.__snowtype = {
        /**
        * Track a Snowplow event for Login.
        * Captured when a user attempts to log in to their account. Tracks the method and outcome of the authentication attempt.
        * @param { Login & Timestamp & Context } login - Attributes for Login.
        * @param {string[]} [trackers] - Tracker names to send the event to.
        */
        trackLogin: function(login, trackers){
                var trackerNames = (trackers && trackers.length) ? ':' + trackers.join(';') : '';
                var context = login.context;
                var timestamp = login.timestamp;
                var data = _objectWithoutProperties(login, ["context", "timestamp"]);
                window.snowplow('trackSelfDescribingEvent' + trackerNames, {
                        event: {
                                schema: 'iglu:com.snplow.msc.aws/login/jsonschema/1-0-0',
                                data: data
                        },
                        context: context,
                        timestamp: timestamp,
                });
        },
        /**
        * Creates a Snowplow Login entity.
        * @param { Login } login - Attributes for Login.
        */
        createLogin: function(login){
                return {
                        schema: 'iglu:com.snplow.msc.aws/login/jsonschema/1-0-0',
                        data: login
                };
        },
        /**
        * Track a Snowplow event for User.
        * A subset of the user fields from the users-service
        * @param { User & Timestamp & Context } user - Attributes for User.
        * @param {string[]} [trackers] - Tracker names to send the event to.
        */
        trackUser: function(user, trackers){
                var trackerNames = (trackers && trackers.length) ? ':' + trackers.join(';') : '';
                var context = user.context;
                var timestamp = user.timestamp;
                var data = _objectWithoutProperties(user, ["context", "timestamp"]);
                window.snowplow('trackSelfDescribingEvent' + trackerNames, {
                        event: {
                                schema: 'iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1',
                                data: data
                        },
                        context: context,
                        timestamp: timestamp,
                });
        },
        /**
        * Creates a Snowplow User entity.
        * @param { User } user - Attributes for User.
        */
        createUser: function(user){
                return {
                        schema: 'iglu:com.snowplowanalytics.console/user/jsonschema/1-0-1',
                        data: user
                };
        },
        /**
        * Track a Snowplow event for UserAuthentication.
        * Data structure that defines how the user logged in
        * @param { UserAuthentication & Timestamp & Context } userAuthentication - Attributes for UserAuthentication.
        * @param {string[]} [trackers] - Tracker names to send the event to.
        */
        trackUserAuthentication: function(userAuthentication, trackers){
                var trackerNames = (trackers && trackers.length) ? ':' + trackers.join(';') : '';
                var context = userAuthentication.context;
                var timestamp = userAuthentication.timestamp;
                var data = _objectWithoutProperties(userAuthentication, ["context", "timestamp"]);
                window.snowplow('trackSelfDescribingEvent' + trackerNames, {
                        event: {
                                schema: 'iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0',
                                data: data
                        },
                        context: context,
                        timestamp: timestamp,
                });
        },
        /**
        * Creates a Snowplow UserAuthentication entity.
        * @param { UserAuthentication } userAuthentication - Attributes for UserAuthentication.
        */
        createUserAuthentication: function(userAuthentication){
                return {
                        schema: 'iglu:com.snplow.msc.aws/user_authentication/jsonschema/1-0-0',
                        data: userAuthentication
                };
        },
        /**
        * Tracks a UserLogIn event specification.
        * ID: a965caf1-88a6-4a89-9aea-cc92516a9d56
        * @param { Login & Timestamp & UserLogInContexts } userLogIn - Attributes for UserLogIn event specification.
        * @param {string[]} [trackers] - Tracker names to send the event specification to.
        */
        trackUserLogInSpec: function(userLogIn, trackers){
                var eventSpecificationContext = createEventSpecification({
                        id: 'a965caf1-88a6-4a89-9aea-cc92516a9d56',
                        version: 8,
                        name: 'User Log In',
                        data_product_id: '57471841-aa79-445d-b4f7-1cbd073a3188',
                        data_product_name: 'Checkout Flow',
                        data_product_domain: 'Marketing'
                });

                var context = Array.isArray(userLogIn.context)
                        ? userLogIn.context.concat(eventSpecificationContext)
                        : [eventSpecificationContext];

                var modifiedUserLogIn = Object.assign(
                        userLogIn,
                        { context: context }
                );

                this.trackLogin(modifiedUserLogIn, trackers);
        },
     };
     return undefined;
 }

/**
 * Typedef for a UserLogInContexts
 * @typedef {object} UserLogInContexts
 * @property {(UserContext | UserAuthenticationContext)[]} [context] Contexts to include in the UserLogIn event specification.
 */


/**
 * Typedef for a DeviceTimestamp
 * @typedef {object} DeviceTimestamp
 * @property {'dtm'} type The value of 'dtm'
 * @property {number} value The value of the device timestamp
 */

/**
 * Typedef for a TrueTimestamp
 * @typedef {object} TrueTimestamp
 * @property {'ttm'} type The value of 'ttm'
 * @property {number} value The value of the true timestamp
 */

/**
 * Typedef for a Timestamp
 * @typedef {object} Timestamp
 * @property {number|TrueTimestamp|DeviceTimestamp} [timestamp] The value of the timestamp
 */

/**
 * Typedef for a SelfDescribingJson
 * @typedef {object} SelfDescribingJson
 * @property {string} schema The schema of the context
 * @property {object} data The data to send for the context
 */

/**
 * Typedef for a Context
 * @typedef {object} Context
 * @property {SelfDescribingJson[]} [context] Contexts to include in the event
 */

/**
 * Captured when a user attempts to log in to their account. Tracks the method and outcome of the authentication attempt.
 * @typedef {object} Login
 * @property {string} method The method used to authenticate, such as 'email', 'google', 'apple', or 'saml'.
 * @property {?string} [error_code] An optional error code if the login attempt failed (e.g., 'invalid_password', 'user_not_found').
 * @property {boolean} is_success Whether the login attempt was successful.
 */


/**
 * Typedef for a Login entity context.
 * @typedef {object} LoginContext
 * @property {string} schema The schema of the context.
 * @property { Login } data The data to send for the context.
 */

/**
 * A subset of the user fields from the users-service
 * @typedef {object} User
 * @property {string} userId The users UUID.
 * @property {string} firstName The users first name.
 * @property {string} lastName The users last name.
 * @property {string} organizationId The organization's UUID that the user belongs to.
 * @property {?string} [email] The users email address.
 * @property {?string} [jobTitle] The users job title.
 * @property {"Admin"|"User"|"Custom"|null} [accessLevel] The users access level.
 */


/**
 * Typedef for a User entity context.
 * @typedef {object} UserContext
 * @property {string} schema The schema of the context.
 * @property { User } data The data to send for the context.
 */

/**
 * Data structure that defines how the user logged in
 * @typedef {object} UserAuthentication
 * @property {"google"|"facebook"|"manual"} auth_type Type of authentication used
 */


/**
 * Typedef for a UserAuthentication entity context.
 * @typedef {object} UserAuthenticationContext
 * @property {string} schema The schema of the context.
 * @property { UserAuthentication } data The data to send for the context.
 */
```
