# Example Snowtype generated code for data structures
> Example configuration files, generated output, and how to use them for each Snowtype-supported tracker and language.
> Source: https://docs.snowplow.io/docs/event-studio/implement-tracking/generate-tracking-code/example-data-structures/
> 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 the [Iglu Central](https://iglucentral.com) schema `web_page` and a custom data structure, `product`. The `tracker` and `language` fields in your configuration determine the language and structure of the output.

These are the example schemas:

### `web_page`

**Type:** Schema

Schema for a web page

**Properties:**

| Property      | Description |
| ------------- | ----------- |
| `id` _string_ | _Required._ |

### `product`

**Type:** Schema

Schema for a product entity

**Properties:**

| Property            | Description                                        |
| ------------------- | -------------------------------------------------- |
| `id` _string_       | _Required._ The product ID (SKU).                  |
| `name` _string_     | _Required._ The product name.                      |
| `currency` _string_ | _Required._ The currency the product is listed in. |
| `price` _number_    | _Required._ The price of the product.              |
| `category` _string_ | _Required._ The product category.                  |

## 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`.

```json
{
  "orgId": "your-org-id",
  "tracker": "@snowplow/browser-tracker",
  "language": "typescript",
  "outpath": "./src/tracking/snowplow",
  "dataProductIds": [],
  "eventSpecificationIds": [],
  "igluCentralSchemas": [
    "iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0"
  ],
  "dataStructures": [
    "iglu:com.example/product/jsonschema/1-0-0"
  ]
}
```

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

/**
 * Schema for a web page
 */
export type WebPage = {
    /**
     * The page view ID.
     */
    id: string;
}

/**
 * Schema for a product entity
 */
export type Product = {
    /**
     * The product category.
     */
    category: string;
    /**
     * The currency the product is listed in.
     */
    currency: string;
    /**
     * The product ID (SKU).
     */
    id: string;
    /**
     * The product name.
     */
    name: string;
    /**
     * The price of the product.
     */
    price: number;
}

type ContextsOrTimestamp<T = any> = Omit<CommonEventProperties<T>, 'context'> & { context?: SelfDescribingJson<T>[] | null | undefined }
/**
 * Track a Snowplow event for WebPage.
 * Schema for a web page
 */
export function trackWebPage<T extends {} = any>(webPage: WebPage & ContextsOrTimestamp<T>, trackers?: string[]){
    const { context, timestamp, ...data } = webPage;
    const event: SelfDescribingJson = {
        schema: 'iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0',
        data
    };

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

/**
 * Creates a Snowplow WebPage entity.
 */
export function createWebPage(webPage: WebPage){
    return {
        schema: 'iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0',
        data: webPage
    }
}
/**
 * Track a Snowplow event for Product.
 * Schema for a product entity
 */
export function trackProduct<T extends {} = any>(product: Product & ContextsOrTimestamp<T>, trackers?: string[]){
    const { context, timestamp, ...data } = product;
    const event: SelfDescribingJson = {
        schema: 'iglu:com.example/product/jsonschema/1-0-0',
        data
    };

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

/**
 * Creates a Snowplow Product entity.
 */
export function createProduct(product: Product){
    return {
        schema: 'iglu:com.example/product/jsonschema/1-0-0',
        data: product
    }
}
```

Here's how you could use the generated code:

```typescript
import {
  trackWebPage,
  createProduct,
  WebPage,
  Product,
  createWebPage,
} from "./src/tracking/snowplow";

/* Track a self-describing event */
trackWebPage({ id: "212a9b63-1af7-4e96-9f35-e2fca110ff43" });

/* Track an event with an entity attached */
const product = createProduct({
  id: "Product id",
  name: "Snowplow product",
  currency: "EUR",
  price: 10,
  category: "Snowplow/Shoes",
});
trackWebPage({
  id: "212a9b63-1af7-4e96-9f35-e2fca110ff43",
  context: [product],
});

/* Enforce specific entity types using type arguments */
const webPage = createWebPage({
  id: "212a9b63-1af7-4e96-9f35-e2fca110ff43",
});
trackWebPage<Product | WebPage>({
  id: "212a9b63-1af7-4e96-9f35-e2fca110ff43",
  context: [product, webPage],
});
```

### Browser (JavaScript)

Generated code for the [Browser tracker](/docs/sources/web-trackers/) in JavaScript. Snowtype produces JSDoc typedefs, with `track` and `create` functions.

```json
{
  "orgId": "your-org-id",
  "tracker": "@snowplow/browser-tracker",
  "language": "javascript",
  "outpath": "./src/tracking/snowplow",
  "dataProductIds": [],
  "eventSpecificationIds": [],
  "igluCentralSchemas": [
    "iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0"
  ],
  "dataStructures": [
    "iglu:com.example/product/jsonschema/1-0-0"
  ]
}
```

```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
 */

/**
 * Schema for a web page
 * @typedef {object} WebPage
 * @property {string} id The page view ID.
 */


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

/**
 * Schema for a product entity
 * @typedef {object} Product
 * @property {string} category The product category.
 * @property {string} currency The currency the product is listed in.
 * @property {string} id The product ID (SKU).
 * @property {string} name The product name.
 * @property {number} price The price of the product.
 */


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

/**
 * Track a Snowplow event for WebPage.
 * Schema for a web page
 * @param { WebPage & Timestamp & Context } webPage - Attributes for WebPage.
 * @param {string[]} [trackers] - Tracker names to send the event to.
 */
export function trackWebPage(webPage, trackers){
    const { context, timestamp, ...data } = webPage;
    const event = {
        schema: 'iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0',
        data
    };

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

/**
 * Creates a Snowplow WebPage entity.
 * @param { WebPage } webPage - Attributes for WebPage.
 */
export function createWebPage(webPage){
    return {
        schema: 'iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0',
        data: webPage
    }
}
/**
 * Track a Snowplow event for Product.
 * Schema for a product entity
 * @param { Product & Timestamp & Context } product - Attributes for Product.
 * @param {string[]} [trackers] - Tracker names to send the event to.
 */
export function trackProduct(product, trackers){
    const { context, timestamp, ...data } = product;
    const event = {
        schema: 'iglu:com.example/product/jsonschema/1-0-0',
        data
    };

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

/**
 * Creates a Snowplow Product entity.
 * @param { Product } product - Attributes for Product.
 */
export function createProduct(product){
    return {
        schema: 'iglu:com.example/product/jsonschema/1-0-0',
        data: product
    }
}
```

Here's how you could use the generated code:

```javascript
import {
  trackWebPage,
  createProduct,
  createWebPage,
} from "./src/tracking/snowplow";

/* Track a self-describing event */
trackWebPage({ id: "212a9b63-1af7-4e96-9f35-e2fca110ff43" });

/* Track an event with an entity attached */
const product = createProduct({
  id: "Product id",
  name: "Snowplow product",
  currency: "EUR",
  price: 10,
  category: "Snowplow/Shoes",
});
trackWebPage({
  id: "212a9b63-1af7-4e96-9f35-e2fca110ff43",
  context: [product],
});
```

### JavaScript tag

Generated code for the [JavaScript tag](/docs/sources/web-trackers/). Snowtype produces functions that call `window.snowplow()` directly, suitable for use with the Snowplow JavaScript tag loaded via a script element.

```json
{
  "orgId": "your-org-id",
  "tracker": "@snowplow/javascript-tracker",
  "language": "javascript",
  "outpath": "./src/tracking/snowplow",
  "dataProductIds": [],
  "eventSpecificationIds": [],
  "igluCentralSchemas": [
    "iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0"
  ],
  "dataStructures": [
    "iglu:com.example/product/jsonschema/1-0-0"
  ]
}
```

```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
 */

/**
 * Schema for a web page
 * @typedef {object} WebPage
 * @property {string} id The page view ID.
 */


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

/**
 * Schema for a product entity
 * @typedef {object} Product
 * @property {string} category The product category.
 * @property {string} currency The currency the product is listed in.
 * @property {string} id The product ID (SKU).
 * @property {string} name The product name.
 * @property {number} price The price of the product.
 */


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

/**
 * Track a Snowplow event for WebPage.
 * Schema for a web page
 * @param { WebPage & Timestamp & Context } webPage - Attributes for WebPage.
 * @param {string[]} [trackers] - Tracker names to send the event to.
 */
function trackWebPage(webPage, trackers){
    const trackerNames = (trackers && trackers.length) ? ':' + trackers.join(';') : '';
    const { context, timestamp, ...data } = webPage;
    window.snowplow('trackSelfDescribingEvent' + trackerNames, {
        event: {
            schema: 'iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0',
            data
        },
        context,
        timestamp,
    });
}

/**
 * Creates a Snowplow WebPage entity.
 * @param { WebPage } webPage - Attributes for WebPage.
 */
function createWebPage(webPage){
    return {
        schema: 'iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0',
        data: webPage
    }
}
/**
 * Track a Snowplow event for Product.
 * Schema for a product entity
 * @param { Product & Timestamp & Context } product - Attributes for Product.
 * @param {string[]} [trackers] - Tracker names to send the event to.
 */
function trackProduct(product, trackers){
    const trackerNames = (trackers && trackers.length) ? ':' + trackers.join(';') : '';
    const { context, timestamp, ...data } = product;
    window.snowplow('trackSelfDescribingEvent' + trackerNames, {
        event: {
            schema: 'iglu:com.example/product/jsonschema/1-0-0',
            data
        },
        context,
        timestamp,
    });
}

/**
 * Creates a Snowplow Product entity.
 * @param { Product } product - Attributes for Product.
 */
function createProduct(product){
    return {
        schema: 'iglu:com.example/product/jsonschema/1-0-0',
        data: product
    }
}
```

Here's how you could use the generated code:

```javascript
/* Track a self-describing event */
trackWebPage({ id: "212a9b63-1af7-4e96-9f35-e2fca110ff43" });

/* Track an event with an entity attached */
const product = createProduct({
  id: "Product id",
  name: "Snowplow product",
  currency: "EUR",
  price: 10,
  category: "Snowplow/Shoes",
});
trackWebPage({
  id: "212a9b63-1af7-4e96-9f35-e2fca110ff43",
  context: [product],
});
```

## iOS (Swift)

Generated code for the [iOS tracker](/docs/sources/mobile-trackers/). Snowtype produces Swift structs with `toEvent()` and `toEntity()` methods.

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": [],
  "igluCentralSchemas": [
    "iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0"
  ],
  "dataStructures": [
    "iglu:com.example/product/jsonschema/1-0-0"
  ],
  // "namespace": "Snowtype"
}
```

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. For example, instead of generating `WebPage` and `Product` structs as in the example, Snowtype would generate `Snowtype.WebPage` and `Snowtype.Product`. This can be helpful for avoiding naming conflicts with other types in your codebase.

````swift
import Foundation
import SnowplowTracker

// MARK: - Encode/decode helpers

final class JSONNull: Codable, Hashable, Sendable {

        public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
                        return true
        }

        public func hash(into hasher: inout Hasher) {}

        public init() {}

        public required init(from decoder: Decoder) throws {
                        let container = try decoder.singleValueContainer()
                        if !container.decodeNil() {
                                        throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
                        }
        }

        public func encode(to encoder: Encoder) throws {
                        var container = encoder.singleValueContainer()
                        try container.encodeNil()
        }
}

final class JSONCodingKey: CodingKey, Sendable {
        let key: String

        required init?(intValue: Int) {
                        return nil
        }

        required init?(stringValue: String) {
                        key = stringValue
        }

        var intValue: Int? {
                        return nil
        }

        var stringValue: String {
                        return key
        }
}

class JSONAny: Codable, @unchecked Sendable {

        let value: Any

        static func decodingError(forCodingPath codingPath: [CodingKey]) -> DecodingError {
                        let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Cannot decode JSONAny")
                        return DecodingError.typeMismatch(JSONAny.self, context)
        }

        static func encodingError(forValue value: Any, codingPath: [CodingKey]) -> EncodingError {
                        let context = EncodingError.Context(codingPath: codingPath, debugDescription: "Cannot encode JSONAny")
                        return EncodingError.invalidValue(value, context)
        }

        static func decode(from container: SingleValueDecodingContainer) throws -> Any {
                        if let value = try? container.decode(Bool.self) {
                                        return value
                        }
                        if let value = try? container.decode(Int64.self) {
                                        return value
                        }
                        if let value = try? container.decode(Double.self) {
                                        return value
                        }
                        if let value = try? container.decode(String.self) {
                                        return value
                        }
                        if container.decodeNil() {
                                        return JSONNull()
                        }
                        throw decodingError(forCodingPath: container.codingPath)
        }

        static func decode(from container: inout UnkeyedDecodingContainer) throws -> Any {
                        if let value = try? container.decode(Bool.self) {
                                        return value
                        }
                        if let value = try? container.decode(Int64.self) {
                                        return value
                        }
                        if let value = try? container.decode(Double.self) {
                                        return value
                        }
                        if let value = try? container.decode(String.self) {
                                        return value
                        }
                        if let value = try? container.decodeNil() {
                                        if value {
                                                        return JSONNull()
                                        }
                        }
                        if var container = try? container.nestedUnkeyedContainer() {
                                        return try decodeArray(from: &container)
                        }
                        if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self) {
                                        return try decodeDictionary(from: &container)
                        }
                        throw decodingError(forCodingPath: container.codingPath)
        }

        static func decode(from container: inout KeyedDecodingContainer<JSONCodingKey>, forKey key: JSONCodingKey) throws -> Any {
                        if let value = try? container.decode(Bool.self, forKey: key) {
                                        return value
                        }
                        if let value = try? container.decode(Int64.self, forKey: key) {
                                        return value
                        }
                        if let value = try? container.decode(Double.self, forKey: key) {
                                        return value
                        }
                        if let value = try? container.decode(String.self, forKey: key) {
                                        return value
                        }
                        if let value = try? container.decodeNil(forKey: key) {
                                        if value {
                                                        return JSONNull()
                                        }
                        }
                        if var container = try? container.nestedUnkeyedContainer(forKey: key) {
                                        return try decodeArray(from: &container)
                        }
                        if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key) {
                                        return try decodeDictionary(from: &container)
                        }
                        throw decodingError(forCodingPath: container.codingPath)
        }

        static func decodeArray(from container: inout UnkeyedDecodingContainer) throws -> [Any] {
                        var arr: [Any] = []
                        while !container.isAtEnd {
                                        let value = try decode(from: &container)
                                        arr.append(value)
                        }
                        return arr
        }

        static func decodeDictionary(from container: inout KeyedDecodingContainer<JSONCodingKey>) throws -> [String: Any] {
                        var dict = [String: Any]()
                        for key in container.allKeys {
                                        let value = try decode(from: &container, forKey: key)
                                        dict[key.stringValue] = value
                        }
                        return dict
        }

        static func encode(to container: inout UnkeyedEncodingContainer, array: [Any]) throws {
                        for value in array {
                                        if let value = value as? Bool {
                                                        try container.encode(value)
                                        } else if let value = value as? Int64 {
                                                        try container.encode(value)
                                        } else if let value = value as? Double {
                                                        try container.encode(value)
                                        } else if let value = value as? String {
                                                        try container.encode(value)
                                        } else if value is JSONNull {
                                                        try container.encodeNil()
                                        } else if let value = value as? [Any] {
                                                        var container = container.nestedUnkeyedContainer()
                                                        try encode(to: &container, array: value)
                                        } else if let value = value as? [String: Any] {
                                                        var container = container.nestedContainer(keyedBy: JSONCodingKey.self)
                                                        try encode(to: &container, dictionary: value)
                                        } else {
                                                        throw encodingError(forValue: value, codingPath: container.codingPath)
                                        }
                        }
        }

        static func encode(to container: inout KeyedEncodingContainer<JSONCodingKey>, dictionary: [String: Any]) throws {
                        for (key, value) in dictionary {
                                        let key = JSONCodingKey(stringValue: key)!
                                        if let value = value as? Bool {
                                                        try container.encode(value, forKey: key)
                                        } else if let value = value as? Int64 {
                                                        try container.encode(value, forKey: key)
                                        } else if let value = value as? Double {
                                                        try container.encode(value, forKey: key)
                                        } else if let value = value as? String {
                                                        try container.encode(value, forKey: key)
                                        } else if value is JSONNull {
                                                        try container.encodeNil(forKey: key)
                                        } else if let value = value as? [Any] {
                                                        var container = container.nestedUnkeyedContainer(forKey: key)
                                                        try encode(to: &container, array: value)
                                        } else if let value = value as? [String: Any] {
                                                        var container = container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key)
                                                        try encode(to: &container, dictionary: value)
                                        } else {
                                                        throw encodingError(forValue: value, codingPath: container.codingPath)
                                        }
                        }
        }

        static func encode(to container: inout SingleValueEncodingContainer, value: Any) throws {
                        if let value = value as? Bool {
                                        try container.encode(value)
                        } else if let value = value as? Int64 {
                                        try container.encode(value)
                        } else if let value = value as? Double {
                                        try container.encode(value)
                        } else if let value = value as? String {
                                        try container.encode(value)
                        } else if value is JSONNull {
                                        try container.encodeNil()
                        } else {
                                        throw encodingError(forValue: value, codingPath: container.codingPath)
                        }
        }

        public required init(from decoder: Decoder) throws {
                        if var arrayContainer = try? decoder.unkeyedContainer() {
                                        self.value = try JSONAny.decodeArray(from: &arrayContainer)
                        } else if var container = try? decoder.container(keyedBy: JSONCodingKey.self) {
                                        self.value = try JSONAny.decodeDictionary(from: &container)
                        } else {
                                        let container = try decoder.singleValueContainer()
                                        self.value = try JSONAny.decode(from: container)
                        }
        }

        public func encode(to encoder: Encoder) throws {
                        if let arr = self.value as? [Any] {
                                        var container = encoder.unkeyedContainer()
                                        try JSONAny.encode(to: &container, array: arr)
                        } else if let dict = self.value as? [String: Any] {
                                        var container = encoder.container(keyedBy: JSONCodingKey.self)
                                        try JSONAny.encode(to: &container, dictionary: dict)
                        } else {
                                        var container = encoder.singleValueContainer()
                                        try JSONAny.encode(to: &container, value: self.value)
                        }
        }
}



// MARK: - WebPage

/// Schema for a web page
/// Schema: `iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0`
///
/// Example:
/// ```swift
/// let data = WebPage(
///     id: id
/// )
/// // 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 WebPage {

        /// The page view ID.
        var id: String

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

        private var payload: [String : Any] {
                var payload: [String : Any] = [:]
                payload["id"] = id
                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: - Product

/// Schema for a product entity
/// Schema: `iglu:com.example/product/jsonschema/1-0-0`
///
/// Example:
/// ```swift
/// let data = Product(
///     category: category,
///     currency: currency,
///     id: id,
///     name: name,
///     price: price
/// )
/// // 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 Product {

        /// The product category.
        var category: String
        /// The currency the product is listed in.
        var currency: String
        /// The product ID (SKU).
        var id: String
        /// The product name.
        var name: String
        /// The price of the product.
        var price: Double

        private var schema: String {
                return "iglu:com.example/product/jsonschema/1-0-0"
        }

        private var payload: [String : Any] {
                var payload: [String : Any] = [:]
                payload["category"] = category
                payload["currency"] = currency
                payload["id"] = id
                payload["name"] = name
                payload["price"] = price
                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)
        }

}
````

Here's how you could use the generated code:

```swift
import SnowplowTracker

/* Track a self-describing event */
_ = tracker.track(WebPage(id: "212a9b63-1af7-4e96-9f35-e2fca110ff43").toEvent())

/* Track an event with an entity attached */
let product = Product(
    category: "Snowplow/Shoes",
    currency: "EUR",
    id: "Product id",
    name: "Snowplow product",
    price: 10
)
let event = WebPage(id: "212a9b63-1af7-4e96-9f35-e2fca110ff43").toEvent()
event.entities.append(product.toEntity())
_ = tracker.track(event)
```

## Android (Kotlin)

Generated code for the [Android tracker](/docs/sources/mobile-trackers/). Snowtype produces Kotlin data classes with `toEvent()` and `toEntity()` methods.

```json
{
  "orgId": "your-org-id",
  "tracker": "snowplow-android-tracker",
  "language": "kotlin",
  "outpath": "./app/src/main/java/snowtype",
  "dataProductIds": [],
  "eventSpecificationIds": [],
  "igluCentralSchemas": [
    "iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0"
  ],
  "dataStructures": [
    "iglu:com.example/product/jsonschema/1-0-0"
  ]
}
```

````kotlin
// Automatically generated by Snowtype

package Snowtype

import com.snowplowanalytics.snowplow.event.SelfDescribing
import com.snowplowanalytics.snowplow.payload.SelfDescribingJson

/**
 * Schema for a web page
 * Schema: `iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0`
 *
 * Example:
 * ```kotlin
 * val data = WebPage(
 *     id = id
 * )
 * // 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 WebPage(

        /** The page view ID. */
        var id: String
) {
        private val schema = "iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0"

        private val payload: Map<String, Any?>
                get() {
                        val payload = HashMap<String, Any?>()
                        payload["id"] = id
                        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)
        }
}

/**
 * Schema for a product entity
 * Schema: `iglu:com.example/product/jsonschema/1-0-0`
 *
 * Example:
 * ```kotlin
 * val data = Product(
 *     category = category,
 *     currency = currency,
 *     id = id,
 *     name = name,
 *     price = price
 * )
 * // 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 Product(

        /** The product category. */
        var category: String,

        /** The currency the product is listed in. */
        var currency: String,

        /** The product ID (SKU). */
        var id: String,

        /** The product name. */
        var name: String,

        /** The price of the product. */
        var price: Double
) {
        private val schema = "iglu:com.example/product/jsonschema/1-0-0"

        private val payload: Map<String, Any?>
                get() {
                        val payload = HashMap<String, Any?>()
                        payload["category"] = category
                        payload["currency"] = currency
                        payload["id"] = id
                        payload["name"] = name
                        payload["price"] = price
                        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)
        }
}
````

Here's how you could use the generated code:

```kotlin
import {{ specified package }}.Product
import {{ specified package }}.WebPage

/* Track a self-describing event */
tracker.track(WebPage(id = "212a9b63-1af7-4e96-9f35-e2fca110ff43").toEvent())

/* Track an event with an entity attached */
val product = Product(
    id = "Product id",
    name = "Snowplow product",
    currency = "EUR",
    price = 10.0,
    category = "Snowplow/Shoes",
)
val event = WebPage(id = "212a9b63-1af7-4e96-9f35-e2fca110ff43").toEvent()
event.entities.add(product.toEntity())
tracker.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.

```json
{
  "orgId": "your-org-id",
  "tracker": "@snowplow/react-native-tracker",
  "language": "typescript",
  "outpath": "./src/tracking/snowplow",
  "dataProductIds": [],
  "eventSpecificationIds": [],
  "igluCentralSchemas": [
    "iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0"
  ],
  "dataStructures": [
    "iglu:com.example/product/jsonschema/1-0-0"
  ]
}
```

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

/**
 * Schema for a web page
 */
export type WebPage = {
    /**
     * The page view ID.
     */
    id: string;
}

/**
 * Schema for a product entity
 */
export type Product = {
    /**
     * The product category.
     */
    category: string;
    /**
     * The currency the product is listed in.
     */
    currency: string;
    /**
     * The product ID (SKU).
     */
    id: string;
    /**
     * The product name.
     */
    name: string;
    /**
     * The price of the product.
     */
    price: number;
}

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;
};

/**
 * Track a Snowplow event for WebPage.
 * Schema for a web page
 */
export function trackWebPage<T extends {} = any>(tracker: ReactNativeTracker, webPage: WebPage & Contexts<T>){
    const { contexts, ...data } = webPage;
    tracker.trackSelfDescribingEvent({
        schema: 'iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0',
        data
    }, contexts);
}

/**
 * Creates a Snowplow WebPage entity.
 */
export function createWebPage(webPage: WebPage){
    return {
        schema: 'iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0',
        data: webPage
    }
}
/**
 * Track a Snowplow event for Product.
 * Schema for a product entity
 */
export function trackProduct<T extends {} = any>(tracker: ReactNativeTracker, product: Product & Contexts<T>){
    const { contexts, ...data } = product;
    tracker.trackSelfDescribingEvent({
        schema: 'iglu:com.example/product/jsonschema/1-0-0',
        data
    }, contexts);
}

/**
 * Creates a Snowplow Product entity.
 */
export function createProduct(product: Product){
    return {
        schema: 'iglu:com.example/product/jsonschema/1-0-0',
        data: product
    }
}
```

Here's how you could use the generated code:

```tsx
import {
  trackWebPage,
  createProduct,
  WebPage,
  Product,
  createWebPage,
} from "./src/tracking/snowplow";

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

/* Track a self-describing event */
trackWebPage(t, { id: "212a9b63-1af7-4e96-9f35-e2fca110ff43" });

/* Track an event with an entity attached */
const product = createProduct({
  id: "Product id",
  name: "Snowplow product",
  currency: "EUR",
  price: 10,
  category: "Snowplow/Shoes",
});
trackWebPage(t, {
  id: "212a9b63-1af7-4e96-9f35-e2fca110ff43",
  context: [product],
});

/* Enforce specific entity types using type arguments */
const webPage = createWebPage({
  id: "212a9b63-1af7-4e96-9f35-e2fca110ff43",
});
trackWebPage<Product | WebPage>(t, {
  id: "212a9b63-1af7-4e96-9f35-e2fca110ff43",
  context: [product, webPage],
});
```

## 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.

```json
{
  "orgId": "your-org-id",
  "tracker": "snowplow-flutter-tracker",
  "language": "dart",
  "outpath": "./lib/tracking/snowplow",
  "dataProductIds": [],
  "eventSpecificationIds": [],
  "igluCentralSchemas": [
    "iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0"
  ],
  "dataStructures": [
    "iglu:com.example/product/jsonschema/1-0-0"
  ]
}
```

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

/// Schema for a web page
/// Schema: `iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0`
@immutable
class WebPage implements SelfDescribing {

    /// The page view ID.
    final String id;

    const WebPage({
        required this.id
    });

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

    @override
    Map<String, Object?> get data {
        return {
            'id': id,
        };
    }

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

    @override
    Map<String, Object?> toMap() {
        return {
            'schema': schema,
            'data': data,
        };
    }
}
/// Schema for a product entity
/// Schema: `iglu:com.example/product/jsonschema/1-0-0`
@immutable
class Product implements SelfDescribing {

    /// The product category.
    final String category;

    /// The currency the product is listed in.
    final String currency;

    /// The product ID (SKU).
    final String id;

    /// The product name.
    final String name;

    /// The price of the product.
    final double price;

    const Product({
        required this.category,
        required this.currency,
        required this.id,
        required this.name,
        required this.price
    });

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

    @override
    Map<String, Object?> get data {
        return {
            'category': category,
            'currency': currency,
            'id': id,
            'name': name,
            'price': price,
        };
    }

    @override
    String get schema => 'iglu:com.example/product/jsonschema/1-0-0';

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

Here's how you could use the generated code:

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

/* Track a self-describing event */
await tracker.track(const WebPage(id: "212a9b63-1af7-4e96-9f35-e2fca110ff43"));

/* Track an event with an entity attached */
const product = Product(
  category: "Snowplow/Shoes",
  currency: "EUR",
  id: "Product id",
  price: 10.0,
  name: "Snowplow product"
);
const event = WebPage(id: "212a9b63-1af7-4e96-9f35-e2fca110ff43");
await tracker.track(event, contexts: [product]);
```

## 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`.

```json
{
  "orgId": "your-org-id",
  "tracker": "@snowplow/node-tracker",
  "language": "typescript",
  "outpath": "./src/tracking/snowplow",
  "dataProductIds": [],
  "eventSpecificationIds": [],
  "igluCentralSchemas": [
    "iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0"
  ],
  "dataStructures": [
    "iglu:com.example/product/jsonschema/1-0-0"
  ]
}
```

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

/**
 * Schema for a web page
 */
export type WebPage = {
    /**
     * The page view ID.
     */
    id: string;
}

/**
 * Schema for a product entity
 */
export type Product = {
    /**
     * The product category.
     */
    category: string;
    /**
     * The currency the product is listed in.
     */
    currency: string;
    /**
     * The product ID (SKU).
     */
    id: string;
    /**
     * The product name.
     */
    name: string;
    /**
     * The price of the product.
     */
    price: number;
}

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;
}

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

/**
 * Track a Snowplow event for WebPage.
 * Schema for a web page
 */
export function trackWebPage<T extends {} = any>(tracker: Tracker, webPage: WebPage & ContextsOrTimestamp<T>){
    const { context, timestamp, ...data } = webPage;
    tracker.track(buildSelfDescribingEvent({
        event: {
            schema: 'iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0',
            data
        }
    }), context, timestamp);
}

/**
 * Creates a Snowplow WebPage entity.
 */
export function createWebPage(webPage: WebPage){
    return {
        schema: 'iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0',
        data: webPage
    }
}
/**
 * Track a Snowplow event for Product.
 * Schema for a product entity
 */
export function trackProduct<T extends {} = any>(tracker: Tracker, product: Product & ContextsOrTimestamp<T>){
    const { context, timestamp, ...data } = product;
    tracker.track(buildSelfDescribingEvent({
        event: {
            schema: 'iglu:com.example/product/jsonschema/1-0-0',
            data
        }
    }), context, timestamp);
}

/**
 * Creates a Snowplow Product entity.
 */
export function createProduct(product: Product){
    return {
        schema: 'iglu:com.example/product/jsonschema/1-0-0',
        data: product
    }
}
```

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

```tsx
import {
  trackWebPage,
  createProduct,
  WebPage,
  Product,
  createWebPage,
} from "./src/tracking/snowplow";

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

/* Track a self-describing event */
trackWebPage(t, { id: "212a9b63-1af7-4e96-9f35-e2fca110ff43" });

/* Track an event with an entity attached */
const product = createProduct({
  id: "Product id",
  name: "Snowplow product",
  currency: "EUR",
  price: 10,
  category: "Snowplow/Shoes",
});
trackWebPage(t, {
  id: "212a9b63-1af7-4e96-9f35-e2fca110ff43",
  context: [product],
});

/* Enforce specific entity types using type arguments */
const webPage = createWebPage({
  id: "212a9b63-1af7-4e96-9f35-e2fca110ff43",
});
trackWebPage<Product | WebPage>(t, {
  id: "212a9b63-1af7-4e96-9f35-e2fca110ff43",
  context: [product, webPage],
});
```

### JavaScript

Snowtype generates JSDoc typedefs and untyped `track` and `create` functions, with a `@typedef {object} Tracker` for the tracker instance parameter.

```json
{
  "orgId": "your-org-id",
  "tracker": "@snowplow/node-tracker",
  "language": "javascript",
  "outpath": "./src/tracking/snowplow",
  "dataProductIds": [],
  "eventSpecificationIds": [],
  "igluCentralSchemas": [
    "iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0"
  ],
  "dataStructures": [
    "iglu:com.example/product/jsonschema/1-0-0"
  ]
}
```

```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
 */

/**
 * Schema for a web page
 * @typedef {object} WebPage
 * @property {string} id The page view ID.
 */


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

/**
 * Schema for a product entity
 * @typedef {object} Product
 * @property {string} category The product category.
 * @property {string} currency The currency the product is listed in.
 * @property {string} id The product ID (SKU).
 * @property {string} name The product name.
 * @property {number} price The price of the product.
 */


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

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

/**
 * Track a Snowplow event for WebPage.
 * Schema for a web page
 * @param {Tracker} tracker - Tracker to send the event to.
 * @param { WebPage & Timestamp & Context } webPage - Attributes for WebPage.
 */
export function trackWebPage(tracker, webPage){
    const { context, timestamp, ...data } = webPage;

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

/**
 * Creates a Snowplow WebPage entity.
 * @param { WebPage } webPage - Attributes for WebPage.
 */
export function createWebPage(webPage){
    return {
        schema: 'iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0',
        data: webPage
    }
}
/**
 * Track a Snowplow event for Product.
 * Schema for a product entity
 * @param {Tracker} tracker - Tracker to send the event to.
 * @param { Product & Timestamp & Context } product - Attributes for Product.
 */
export function trackProduct(tracker, product){
    const { context, timestamp, ...data } = product;

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

/**
 * Creates a Snowplow Product entity.
 * @param { Product } product - Attributes for Product.
 */
export function createProduct(product){
    return {
        schema: 'iglu:com.example/product/jsonschema/1-0-0',
        data: product
    }
}
```

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

```javascript
import {
  trackWebPage,
  createProduct,
  createWebPage,
} from "./src/tracking/snowplow";

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

/* Track a self-describing event */
trackWebPage(t, { id: "212a9b63-1af7-4e96-9f35-e2fca110ff43" });

/* Track an event with an entity attached */
const product = createProduct({
  id: "Product id",
  name: "Snowplow product",
  currency: "EUR",
  price: 10,
  category: "Snowplow/Shoes",
});
trackWebPage(t, {
  id: "212a9b63-1af7-4e96-9f35-e2fca110ff43",
  context: [product],
});
```

## 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 `Track` functions that accept a `*sp.Tracker`.

```json
{
  "orgId": "your-org-id",
  "tracker": "snowplow-golang-tracker",
  "language": "go",
  "outpath": "./tracking/snowtype",
  "dataProductIds": [],
  "eventSpecificationIds": [],
  "igluCentralSchemas": [
    "iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0"
  ],
  "dataStructures": [
    "iglu:com.example/product/jsonschema/1-0-0"
  ]
}
```

```go
package snowtypegenerated

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

// Schema for a web page
type WebPage struct {
	// The page view ID.
	ID string `mapstructure:"id"`
}

// Schema for a product entity
type Product struct {
	// The product category.
	Category string  `mapstructure:"category"`
	// The currency the product is listed in.
	Currency string  `mapstructure:"currency"`
	// The product ID (SKU).
	ID       string  `mapstructure:"id"`
	// The product name.
	Name     string  `mapstructure:"name"`
	// The price of the product.
	Price    float64 `mapstructure:"price"`
}

// 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
	}
}

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

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

// TrackWebPage tracks a WebPage
func TrackWebPage(tracker *sp.Tracker, webPage WebPage, opts ...option) error {
	sdj, err := webPage.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 (product Product) SnowplowFormat() (*sp.SelfDescribingJson, error) {
	var decodedMap map[string]interface{}
	err := mapstructure.Decode(product, &decodedMap)
	if err != nil {
		return nil, err
	}

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

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

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

	tracker.TrackSelfDescribingEvent(*sde)
	return nil
}
```

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

```go
// Track a self-describing event
TrackWebPage(tracker, WebPage{ID: "212a9b63-1af7-4e96-9f35-e2fca110ff43"})

// Track an event with an entity attached
productName := "Snowplow product"
product := Product{
	ID:       "Product_id",
	Currency: "EUR",
	Price:    10,
	Category: "Snowplow/Shoes",
	Name:     &productName,
}

TrackWebPage(
	tracker,
	WebPage{ID: "212a9b63-1af7-4e96-9f35-e2fca110ff43"},
	WithContexts(product),
)
```

## Java

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

```json
{
  "orgId": "your-org-id",
  "tracker": "snowplow-java-tracker",
  "language": "java",
  "outpath": "./src/main/java/snowtype",
  "dataProductIds": [],
  "eventSpecificationIds": [],
  "igluCentralSchemas": [
    "iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0"
  ],
  "dataStructures": [
    "iglu:com.example/product/jsonschema/1-0-0"
  ]
}
```

```java
// WebPage.java

// Automatically generated by Snowtype

/**
 * Schema for a web page
 */
public class WebPage {
    private String id;

    /**
     * The page view ID.
     */
    public String getID() { return id; }
    public void setID(String value) { this.id = value; }
}
```

```java
// Product.java

// Automatically generated by Snowtype

/**
 * Schema for a product entity
 */
public class Product {
    private String category;
    private String currency;
    private String id;
    private String name;
    private double price;

    /**
     * The product category.
     */
    public String getCategory() { return category; }
    public void setCategory(String value) { this.category = value; }

    /**
     * The currency the product is listed in.
     */
    public String getCurrency() { return currency; }
    public void setCurrency(String value) { this.currency = value; }

    /**
     * The product ID (SKU).
     */
    public String getID() { return id; }
    public void setID(String value) { this.id = value; }

    /**
     * The product name.
     */
    public String getName() { return name; }
    public void setName(String value) { this.name = value; }

    /**
     * The price of the product.
     */
    public double getPrice() { return price; }
    public void setPrice(double value) { this.price = value; }
}
```

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

```java
import com.snowplowanalytics.snowplow.tracker.*;
import com.snowplowanalytics.snowplow.snowtype.*;
import com.snowplowanalytics.snowplow.tracker.events.SelfDescribing;

import java.util.Collections;

/* Track a self-describing event */
tracker.track(
    SelfDescribing.builder()
        .eventData(new WebPage.Builder()
            .setId("212a9b63-1af7-4e96-9f35-e2fca110ff43")
            .build()
            .toSelfDescribingJson())
        .build()
);

/* Track an event with an entity attached */
Product product = new Product.Builder()
    .setId("Product id")
    .setName("Snowplow product")
    .setCurrency("EUR")
    .setPrice(10.0)
    .setCategory("Snowplow/Shoes")
    .build();
WebPage webPage = new WebPage.Builder()
    .setId("212a9b63-1af7-4e96-9f35-e2fca110ff43")
    .build();
SelfDescribing event = SelfDescribing.builder()
    .eventData(product.toSelfDescribingJson())
    .customContext(Collections.singletonList(
        webPage.toSelfDescribingJson()))
    .build();
tracker.track(event);
```

## 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`, 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": [],
  "igluCentralSchemas": [
    "iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0"
  ],
  "dataStructures": [
    "iglu:com.example/product/jsonschema/1-0-0"
  ]
}
```

```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; }

    window.__snowtype = {
        /**
        * Track a Snowplow event for WebPage.
        * Schema for a web page
        * @param { WebPage & Timestamp & Context } webPage - Attributes for WebPage.
        * @param {string[]} [trackers] - Tracker names to send the event to.
        */
        trackWebPage: function(webPage, trackers){
                var trackerNames = (trackers && trackers.length) ? ':' + trackers.join(';') : '';
                var context = webPage.context;
                var timestamp = webPage.timestamp;
                var data = _objectWithoutProperties(webPage, ["context", "timestamp"]);
                window.snowplow('trackSelfDescribingEvent' + trackerNames, {
                        event: {
                                schema: 'iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0',
                                data: data
                        },
                        context: context,
                        timestamp: timestamp,
                });
        },
        /**
        * Creates a Snowplow WebPage entity.
        * @param { WebPage } webPage - Attributes for WebPage.
        */
        createWebPage: function(webPage){
                return {
                        schema: 'iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0',
                        data: webPage
                };
        },
        /**
        * Track a Snowplow event for Product.
        * Schema for a product entity
        * @param { Product & Timestamp & Context } product - Attributes for Product.
        * @param {string[]} [trackers] - Tracker names to send the event to.
        */
        trackProduct: function(product, trackers){
                var trackerNames = (trackers && trackers.length) ? ':' + trackers.join(';') : '';
                var context = product.context;
                var timestamp = product.timestamp;
                var data = _objectWithoutProperties(product, ["context", "timestamp"]);
                window.snowplow('trackSelfDescribingEvent' + trackerNames, {
                        event: {
                                schema: 'iglu:com.example/product/jsonschema/1-0-0',
                                data: data
                        },
                        context: context,
                        timestamp: timestamp,
                });
        },
        /**
        * Creates a Snowplow Product entity.
        * @param { Product } product - Attributes for Product.
        */
        createProduct: function(product){
                return {
                        schema: 'iglu:com.example/product/jsonschema/1-0-0',
                        data: product
                };
        },
    };

    return window.__snowtype;
}
```
