Analytics-Swift Typewriter
Typewriter is a tool for generating strongly-typed Segment analytics libraries based on your pre-defined Tracking Plan spec.
At a high-level, Typewriter can take an event from your Tracking Plan like this "Order Completed"
event:
Typewriter uses the event to generate a typed analytics call in different languages:
// Example client in your web app
const typewriter = require('./analytics')
typewriter.orderCompleted({
orderID: 'ck-f306fe0e-cc21-445a-9caa-08245a9aa52c',
total: 39.99
})
// Example client in your iOS app
SEGTypewriterAnalytics.orderCompleted(
orderID: "ck-f306fe0e-cc21-445a-9caa-08245a9aa52c",
total: 39.99
)
These generated clients are embedded with metadata from your Tracking Plan, which contextualizes your analytics instrumentation, and reduces or eliminates incorrect instrumentations in your production environments. In your editor, you can access event names, descriptions, property names, types and more:
You can also configure Typewriter to validate analytic events at runtime, which can alert you to instrumentation errors during development and testing. Typewriter can warn you about missing required properties, invalid enum values, regex mismatches, and any other advanced JSON Schema you configure in your Tracking Plan.
You can use this with a test suite to automatically fail your unit tests if the instrumentation generates any violations:
If you use a statically typed language (such as TypeScript, Java, Objective-C, or Swift), you get access to compile-time warnings about your instrumentation:
Typewriter also helps teams adopt analytics best practices, such as avoiding autogenerated event names, and carefully considering what properties are tracked.
Prerequisites
Typewriter is built using Node.js, and requires node@8.x
or later, and npm@5.2.x
or later to function.
You can check if you have Node and NPM installed by running the following commands in your command-line window:
$ node --version
v10.15.3
$ npm --version
6.9.0
$ npx --version
6.9.0
If you don’t have these, you’ll need to install node
. Installing node
also installs npm
and npx
for you. If you’re on macOS, you can install it with Homebrew:
$ brew install node
Once you’ve installed Node and NPM, run the --version
commands again to verify that they were installed correctly.
Swift Quickstart
For use with the analytics-ios
SDK, use Typewriter v7.
To get started using Typewriter with Swift:
- Make sure you have
node
installed using the instructions in the prerequisites above. - Install
analytics-swift
in your app. Follow the analytics-swift Quickstart Guide. -
Run
npx typewriter init
to use the Typewriter quickstart wizard that generates atypewriter.yml
configuration, along with your first Typewriter client. When you run the command, it creates atypewriter.yml
file in your repository. For more information on the format of this file, see the Typewriter Configuration Reference.
Runnpx typewriter
to regenerate your Typewriter client. You need to do this each time you update your Tracking Plan. -
Import your new Typewriter client into your project using XCode. If you place your generated files into a folder in your project, import the project as a group not a folder reference.
When you add the generated client to your Xcode Project you can use as a Swift extension method on any Analytics client object:Analytics.main.orderCompleted(OrderCompleted( orderID: "ck-f306fe0e-cc21-445a-9caa-08245a9aa52c", total: 39.99 ))
Adding Events
To update or add a new event to a Typewriter client, first apply your changes to your Tracking Plan. Then run the following:
# Run this in the directory with your repo's `typewriter.yml`.
$ npx typewriter
API Token Configuration
Typewriter requires a Segment API token to fetch Tracking Plans from the Segment Public API.
You must be a workspace owner to create Segment API tokens.
To create an API token:
- Click on the Tokens tab on the Access Management page and click Create Token.
- Choose Segment’s Public API.
- Add a description for the token and assign access. If you choose Workspace Member, you only need to select Tracking Plan Read-Only for the Resource Role, as Typewriter only needs the Tracking Plan Read-Only role.
- Click Create.
Typewriter looks for an API token in three ways, in the following order:
- If a token is piped through, it will use that token. For example,
echo $TW_TOKEN | typewriter build
. - Typewriter executes a token script from the
typewriter.yml
. See Token Script for more information. - Typewriter reads the contents of the
~/.typewriter
file.
The quickstart wizard prompts you for an API token and stores it in ~/.typewriter
for you.
Segment recommends you use a Token Script to share an API token with your team. When you use a token script, you can supply your API token as an environment variable (echo $TYPEWRITER_TOKEN
), from an .env.
file (source .env; echo $TYPEWRITER_TOKEN
) or using any other CLI tool for providing secrets.
Segment also recommends you to pipe through your API Token as this will let you keep your token secret, but it also allows you to share it across your team.
Segment is keeping the Token Script execution for compatibility purposes only in v8 of Typewriter. Segment might deprecate this feature in the future, and encourages you to execute your script and pipe in the token. For example, echo $TW_TOKEN | typewriter build
.
Best Practices
Segment strongly recommends that you store your Tracking Plan (plan.json
) in a version control system. This guarantees that Typewriter will generate the same client, regardless of any changes you make to your Tracking Plan in the Segment app. Otherwise, changes to your Tracking Plan could lead to broken builds.
Segment recommends that you only check in the plan.json
, and generate your Typewriter client during the application build step (by calling npx typewriter
). You can do this in git
with the following .gitignore
:
# Make sure to update `analytics` to the full path to your Typewriter client.
analytics/*
!analytics/plan.json
If this isn’t possible you can also check in the full generated client. Segment, however, doesn’t recommend this method.
Configuration Reference
Typewriter stores its configuration in a typewriter.yml
file in the root of your repository. A sample configuration might look like this:
# Segment Typewriter Configuration Reference (https://github.com/segmentio/typewriter)
# Just run `npx typewriter` to re-generate a client with the latest versions of these events.
scripts:
# You can supply a Segment API token using a `script.token` command. See `Token Script` below.
token: source .env; echo $TYPEWRITER_TOKEN
# You can format any of Typewriter's auto-generated files using a `script.after` command.
# See `Formatting Generated Files` below.
after: ./node_modules/.bin/prettier --write analytics/plan.json
client:
# Which Segment SDK you are generating for.
# Valid values: analytics.js, analytics-node, analytics-react-native, swift, kotlin.
sdk: analytics-node
# The target language for your Typewriter client.
# Valid values: javascript, typescript, kotlin, swift.
language: typescript
trackingPlans:
# The Segment Protocols Tracking Plan that you are generating a client for.
# Provide your workspace slug and Tracking Plan id, both of which can be found
# in the URL when viewing the Tracking Plan editor. For example:
# https://app.segment.com/segment-demo/protocols/tracking-plans/rs_QhWHOgp7xg8wkYxilH3scd2uRID
# You also need to supply a path to a directory to save your Typewriter client.
- id: rs_QhWHOgp7xg8wkYxilH3scd2uRID
workspaceSlug: segment-demo
path: ./analytics
At any time, you can regenerate this file by running the Typewriter quickstart wizard:
$ npx typewriter init
Token Script
Segment is keeping the Token Script execution for compatibility purposes only in v8 of Typewriter. Segment might deprecate this feature in the future, and encourages you to execute your script and pipe in the token. For example, echo $TW_TOKEN | typewriter build
.
If your team has a standard way to supply secrets (passwords and tokens) in development environments, whether that’s an .env
file or an AWS-backed secret store, you can configure Typewriter to use it to get a Segment API token.
To configure this, create a token script called scripts.token
in your typewriter.yml
. This script is a string that contains a shell command that, when executed, outputs a valid Segment API token. Here’s an insecure, example:
scripts:
# NOTE: NEVER commit a Segment API token to your version control system.
token: echo "OIEGO$*hf83hfh034fnosnfiOEfowienfownfnoweunfoiwenf..."
To give a real example, Segment stores secrets in segmentio/chamber
which is backed by AWS Parameter Store. Providing access to a token in chamber
looks like this:
scripts:
token: aws-okta exec dev-privileged -- chamber export typewriter | jq -r .typewriter_token
To learn more about the typewriter.yml
configuration format, see the Configuration Reference.
Formatting Generated Files
In your typewriter.yml
, you can configure a script (scripts.after
) that fires after generating a Typewriter client. You can use this to apply your team’s style guide to any of Typewriter’s auto-generated files.
For example, if you want to apply your prettier
formatting to plan.json
(the local snapshot of your Tracking Plan), you can use an after
script like this:
scripts:
after: ./node_modules/.bin/prettier --write ./analytics/plan.json
To learn more about the typewriter.yml
configuration format, see the Configuration Reference.
Connecting to CI
As mentioned in the Best Practices section above, Segment recommends that you only check in the plan.json
, and not the generated clients, into your version control. Instead, Segment recommends building these clients as part of the build step for your application.
In your CI environment, this usually involves a step to build the Typewriter client. Make sure to build the production client before deploying the application, as explained in the Tracking Plan Violation Handling section below.
# An example (simplified) CircleCI configuration:
jobs:
test:
steps:
- npx typewriter development
- yarn run test
deploy:
steps:
- npx typewriter production
- yarn run deploy
Contributing
If you’re interested in contributing, open an issue on GitHub and Segment can help provide you pointers to get started.
Feedback
Segment welcomes feedback you may have on your experience with Typewriter. To contact Segment, open an issue on GitHub.
This page was last modified: 13 Aug 2024
Need support?
Questions? Problems? Need more info? Contact Segment Support for assistance!