Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

Tutela is an Effect-native TypeScript SDK for the Guardian Connect insurance APIs.

Tutela — Latin for guardianship and protection. The name nods both to the domain (life & group insurance) and to the SDK’s aim: to guard the boundary between your code and a remote API with types you can trust.

import { Effect } from "effect"
import { Tutela } from "@tutela/sdk"

const program = Tutela.eoi
  .submit()
  .policy(Tutela.Brand.GroupPolicyId("GP-00420"))
  .nonce(Tutela.Brand.Nonce("nonce-abc-123"))
  .body(form)
  .send() // only callable once policy + nonce + body are all set
  .pipe(
    Effect.catchTag("PaymentRequired", recover), // Guardian's 402 business error
  )

await Tutela.run(program, {
  baseUrl: "https://api.guardianlife.com",
  tokenUrl: "https://api.guardianlife.com/oauth/client_credential/accesstoken",
  clientId, clientSecret, apiKey,
})

What you get

  • All 11 Guardian Connect APIs, each with a named resource on Tutela.
  • Compile-time safety: branded ids, type-state request builders, and an exhaustive tagged error channel.
  • Runtime safety where it matters: responses decoded through effect/Schema, so contract drift surfaces as a typed error rather than a silent any.
  • Batteries-included transport: an auto-refreshing OAuth client-credentials token provider, secrets kept in Redacted, and a transparent 401 retry.

Read on for Getting Started, or jump to the Design & Philosophy behind it.

This is an unofficial client built from publicly published OpenAPI documentation. See the Disclaimer.

Getting Started

Install

pnpm add @tutela/sdk effect @effect/platform

effect and @effect/platform are peer dependencies — you bring your own (shared) copy so the SDK composes with the rest of your Effect application.

Requires Node ≥ 18 and an ESM project ("type": "module").

A first call

Every resource method returns an Effect. Provide the runtime once — with your base URL, token URL, and partner credentials — and run it:

import { Effect } from "effect"
import { Tutela } from "@tutela/sdk"

const verify = Tutela.vob.verify({
  member: { member_id: "M-001", first_name: "Ada", last_name: "Lovelace" },
})

const result = await Tutela.run(verify, {
  baseUrl: "https://api.guardianlife.com",
  tokenUrl: "https://api.guardianlife.com/oauth/client_credential/accesstoken",
  clientId: process.env.GUARDIAN_CLIENT_ID!,
  clientSecret: process.env.GUARDIAN_CLIENT_SECRET!,
  apiKey: process.env.GUARDIAN_API_KEY!,
})

Composing with your own Effect app

Tutela.run is a convenience. In a larger Effect application, provide the layer yourself and keep the program as a value:

import { Effect } from "effect"
import { Tutela } from "@tutela/sdk"

const layer = Tutela.layer({ baseUrl, tokenUrl, clientId, clientSecret, apiKey })

const program = Effect.gen(function* () {
  const policy = yield* Tutela.policy.specs(mag)
  const vob = yield* Tutela.vob.verify({ member })
  return { policy, vob }
})

await Effect.runPromise(Effect.provide(program, layer))

You can also build the config from the environment with Tutela.Config.fromEnv (reads TUTELA_BASE_URL, TUTELA_TOKEN_URL, TUTELA_CLIENT_ID, TUTELA_CLIENT_SECRET, TUTELA_API_KEY).

What you must supply

The published OpenAPI specs do not include two things you’ll need:

  1. The real OAuth token URL (the specs ship a placeholder).
  2. Your partner-issued client credentials and API key.

Base URLs are inferred from the specs where present; otherwise pass baseUrl explicitly per the environment you’re targeting.

Authentication

Guardian fronts every API with an Apigee gateway using the OAuth 2.0 client-credentials grant. Tutela handles the whole token lifecycle for you.

How it works

  1. On the first call, the SDK requests a token from tokenUrl using HTTP Basic auth (clientId:clientSecret) and grant_type=client_credentials.
  2. The returned JWT is cached in a Ref together with its expiry (minus a small skew, so it refreshes shortly before it actually expires).
  3. Every request carries Authorization: Bearer <token> and your x-api-key.
  4. If a request comes back 401, the SDK invalidates the cached token, fetches a fresh one, and retries the request once.

You never write any of this — it lives in the TokenProvider layer.

Secrets stay redacted

clientSecret and apiKey are stored as Effect Redacted values. They are used when building requests but never appear in logs or stack traces — printing a Redacted yields <redacted>.

Configuration

FieldMeaning
baseUrlApigee gateway origin, e.g. https://api.guardianlife.com
tokenUrlOAuth client-credentials token endpoint
clientId / clientSecretPartner-issued credentials
apiKeyPer-app API key sent on every request

Provide them once via Tutela.layer(...), Tutela.run(program, ...), or Tutela.Config.fromEnv. Swapping between production, UAT, and internal hosts is a change of configuration, not a change of code.

Failure mode: if the token endpoint itself fails, calls fail with a typed AuthError — see Error Handling.

Resources & API Coverage

All 11 Guardian Connect APIs have a named resource on the Tutela object. They come in two styles.

Curated resources

eoi, vob, benefits, retail.

Curated resources add branded ids and decode responses through effect/Schema at runtime, so a malformed or drifted response surfaces as a typed DecodeError instead of propagating as any. EOI additionally exposes a type-state builder (see Design).

// runtime-validated response; branded path id
const status = yield* Tutela.benefits.transactionStatus(
  Tutela.Brand.MasterAgreementNumber("00000420"),
  transmissionGuid,
)
status.TransmissionStatusCode // "Success" | "Failure" | "Partial" | "In Progress"

Generic resources

policy, underwriting, groupRatingQuoting, dentalProvider, gpsIllustration, prefill, hmb.

Generic resources expose typed named methods built over a single generic combinator that infers path params, query, body, and the success response from the generated OpenAPI types. Each also carries a fully-typed .call escape hatch for any operation not surfaced as a named method.

// named method
yield* Tutela.underwriting.mvrInquiry(body)

// escape hatch — any of the 26 UW operations, fully typed
yield* Tutela.underwriting.call("/v1/uwdata/{uwDataId}", "get", {
  path: { uwDataId: 42 },
})

The catalog

APIResourceStyle
Evidence of Insurabilityeoicurated (type-state builder)
Verification of Benefitsvobcurated
Benefits (LDEx)benefitscurated
Retail Individual Productsretailcurated
Policypolicygeneric
Underwriting Data Serviceunderwritinggeneric (26 ops)
Group Rating & QuotinggroupRatingQuotinggeneric
Group Dental ProviderdentalProvidergeneric
GPS IllustrationgpsIllustrationgeneric
eSuite Prefillprefillgeneric
HMB Membershiphmbgeneric

The split — and why it exists — is covered in How It’s Built.

Error Handling

Every Tutela call resolves into one closed, tagged union — TutelaError. There are no thrown exceptions to catch; failures are values in the Effect error channel, handled with Effect.catchTag and checked exhaustively by the compiler.

The error union

TagWhen
BadRequestHTTP 400 — malformed request
UnauthorizedHTTP 401 — invalid/expired token or API key
PaymentRequiredHTTP 402 — Guardian business failure (EOI/Benefits)
NotFoundHTTP 404
UnprocessableHTTP 422 — Retail validation failure
RateLimitedHTTP 429 — carries retryAfterSeconds
ServerErrorHTTP 5xx — carries status
TransportErrornetwork failure before a response
DecodeErrora 2xx body that didn’t match the schema (contract drift)
AuthErrorfailure obtaining a client-credentials token

Two of these encode Guardian-specific quirks: 402 is a business failure (not “payment required” in the literal sense), and 422 is the Retail validation path. Both carry a normalized list of field-level errors.

Handling them

program.pipe(
  Effect.catchTag("PaymentRequired", (e) => {
    // e.errors: ReadonlyArray<{ code?, field?, value?, message }>
    return recover(e)
  }),
  Effect.catchTag("Unauthorized", () => Effect.die("check credentials")),
  Effect.catchTag("RateLimited", (e) => retryAfter(e.retryAfterSeconds)),
)

Because the union is closed, the compiler knows exactly which tags remain after each catchTag — you can’t forget one, and you can’t catch one that can’t occur.

Contract drift is a typed failure

Curated resources decode responses through effect/Schema. If the server returns a value outside the agreed contract — say a status enum that isn’t one of the documented values — the call fails with a DecodeError rather than handing you a plausible-but-wrong object. This turns silent integration breakage into a loud, typed signal.

Design & Philosophy

Tutela is built on a few convictions about how an API client should behave.

Make illegal states unrepresentable

Ids are branded — GroupPolicyId, PolicyNumber, Nonce, … — so a policy number can’t be passed where an agreement number belongs, even though both are string at runtime.

Request builders use type-state: a call’s .send() does not exist as a callable method until every required field has been supplied. The proof is in the compiler error you get if you try too early:

Tutela: cannot send — missing required field(s): nonce | body

Parse, don’t validate

Responses cross the boundary through effect/Schema. Data is decoded into known shapes once, at the edge; contract drift surfaces as a typed DecodeError instead of an any that fails three layers deep.

Errors are values, not exceptions

Every call resolves into one closed, tagged union (TutelaError). Handling is catchTag, checked exhaustively by the compiler — including the API’s own quirks (402 as a business failure, 422 for validation). See Error Handling.

Dependencies are explicit

Configuration, credentials, and the HTTP client are provided as Effect Layers. Moving between production, UAT, and internal hosts is a change of layer, not a change of code. Secrets stay Redacted and never log.

Generate the boring, hand-craft the meaningful

Type definitions for all 11 APIs are generated from the OpenAPI specs; the ergonomic surface and runtime validation are hand-written where they earn their cost. The mechanics are in How It’s Built.

Honest metrics over vanity numbers

The test and mutation suites verify real behavior. Where a mutation is mathematically equivalent and unkillable, it is documented as such rather than papered over. See Testing & Mutation Score.

How It’s Built

Covering 11 APIs — several with hundreds of nested schemas — without drowning in hand-written models comes down to a deliberate two-layer split.

1. Type backbone (all 11 APIs)

openapi-typescript generates a paths/components type module per API into src/generated/. A single generic combinator, api<paths>() (core/typed.ts), turns any of them into typed, Effect-returning calls: path params, query, body, and the success response are all inferred from the generated type. Unknown paths, missing path params, and wrong body types don’t compile.

const call = api<paths>()
call("/v4/policies/{master-agreement-number}/policyspecs", "get", {
  path: { "master-agreement-number": mag },
}) // Effect<Transmission, TutelaError, RequestContext>

Regenerate the backbone whenever the specs change:

pnpm gen   # specs → src/generated/*.ts

2. Curated runtime validation (where it matters)

For the resources worth extra care, a hand-written layer adds effect/Schema response decoding and richer ergonomics (e.g. the EOI type-state builder). Response envelopes are decoded at runtime; the large request bodies are typed via the generated types rather than re-derived by hand.

Why this route

openapi-typescript consumes the OpenAPI 3.0 specs natively and is widely maintained. The alternatives didn’t fit:

  • openapi-to-effect is OpenAPI 3.1-only and targets the deprecated @effect/schema.
  • Hand-writing the 500-schema specs was never an option.

Project layout

src/
├── index.ts              # the Tutela entry point + live Layer wiring
├── core/
│   ├── brand.ts          # branded id constructors
│   ├── errors.ts         # the tagged TutelaError union
│   ├── config.ts         # TutelaConfig service (+ fromEnv)
│   ├── auth.ts           # OAuth2 client-credentials TokenProvider
│   ├── http.ts           # the `request` transport combinator
│   ├── typed.ts          # generic api<paths>() combinator (inference engine)
│   └── request-builder.ts# type-state machinery
├── generated/            # openapi-typescript output, one module per API (11)
├── schema/               # effect/Schema models for curated resources
└── resources/            # the per-API clients

Testing & Mutation Score

Tutela’s correctness is verified two ways: a behavioral test suite, and mutation testing that checks the tests themselves.

Behavioral tests

pnpm test runs 81 assertions against a mock HttpClient layer — no network, fully deterministic. They cover:

  • token fetch, caching, expiry/refresh, and the Basic/Accept/Content-Type headers on the token request;
  • bearer + x-api-key injection on data requests;
  • every status → error mapping (400/401/402/404/422/429/5xx, plus the 300 boundary), with normalized field errors;
  • transparent 401 refresh-and-retry, and the give-up-after-one path;
  • transport errors and malformed-body decode errors;
  • curated effect/Schema decoding, including a contract-drift case (an out-of-enum value becoming a typed DecodeError).

Mutation testing

pnpm mutation runs StrykerJS over src/core/**. It makes thousands of tiny edits (“mutants”) to the code and checks that a test fails for each — a direct measure of whether the suite actually verifies behavior rather than just executing it.

Score: 93.6%, gated at 90 (CI fails below it). brand, errors, and typed are at 100%.

The handful of surviving mutants are equivalent — changes with no observable behavioral difference, which by definition no test can kill (e.g. Context.Tag identity strings, header literals the mock can’t observe, > → >= boundaries). They are catalogued rather than hidden; the full discussion lives in MUTATION.md.

The guiding rule: kill every killable mutant, and document the equivalents. 100% is not a meaningful target — honesty about which mutants are unkillable is.

Contributing

Commands

pnpm install
pnpm gen           # regenerate src/generated/ from the OpenAPI specs
pnpm typecheck     # tsc, no emit
pnpm test          # mock-HttpClient suite (81 assertions)
pnpm mutation      # StrykerJS over src/core/**
pnpm build         # → dist/

Requires Effect ^3.21 and @effect/platform ^0.72 (peer dependencies), and Node ≥ 18.

Adding or updating an API

  1. Drop the OpenAPI spec into the specs directory and run pnpm gen — this regenerates the src/generated/<api>.ts type module.
  2. A generic resource is a thin file over api<paths>() with named methods and a .call escape hatch (see resources/policy.ts).
  3. To make it curated, add an effect/Schema model for the response envelopes under schema/ and decode through the lower-level request combinator (see resources/benefits.ts).

Continuous integration

.github/workflows/ci.yml runs on every push and PR to main:

  • build — typecheck → test → build
  • mutation — StrykerJS, enforcing the 90% break threshold

These docs are built and published to GitHub Pages by .github/workflows/docs.yml on changes under docs/.

Building the docs locally

mdbook serve docs --open   # live-reloading preview
mdbook build docs          # → docs/book/

Disclaimer

Tutela is an unofficial client built from publicly published OpenAPI documentation. It is not affiliated with, endorsed by, or supported by Guardian.

Two things the published specs don’t include and that you must supply yourself:

  • the real OAuth token URL (the specs ship a placeholder), and
  • your partner-issued client credentials and API key.

License

Tutela is released under the MIT License.