npm.io
0.3.1 • Published 17h ago

@tktchurch/convoy

Licence
MIT
Version
0.3.1
Deps
0
Size
186 kB
Vulns
0
Weekly
0

@tktchurch/convoy

Runtime-neutral TypeScript client for Convoy campaigns and registration flows. It uses web-standard fetch, Headers, AbortController, and URL APIs and has no runtime dependencies, so the same package works in browsers and Deno.

Install

npm install @tktchurch/convoy

Deno can import the npm package directly:

import { createConvoyClient } from "npm:@tktchurch/convoy@0.1.0";

Create a client

import { createConvoyClient } from "@tktchurch/convoy";

const convoy = createConvoyClient({
  baseUrl: "https://convoy.tktchurch.com",
  timeout: 30_000,
  defaultHeaders: {
    // Add Authorization here only in a trusted request-scoped client.
    authorization: `Bearer ${accessToken}`,
  },
});

fetch may be injected for testing or runtimes that do not expose globalThis.fetch. Request headers override defaultHeaders.

Campaigns

const campaign = await convoy.campaigns.get("faith-gathering");
const status = await convoy.campaigns.status("faith-gathering");

Campaign status includes currently relevant announcements. The pure selector applies the shared display order: global before campaign, newest startsAt, then announcement ID.

import {
  announcementDismissalKey,
  selectActiveAnnouncement,
} from "@tktchurch/convoy";

const announcement = selectActiveAnnouncement(
  status.announcements,
  campaign.campaign.campaignId,
);

if (announcement) {
  const key = announcementDismissalKey(
    announcement,
    announcement.presentation,
  );
  // Persist `key` after the user dismisses this presentation.
}

Modal and banner keys are intentionally separate and include announcementId:revision; publishing a revision shows it again without making a modal dismissal suppress the banner. selectAnnouncement is also available when a consumer needs to pre-filter one presentation and a set of dismissal keys.

Registration flow

const touch = captureAttributionTouch({
  url: window.location.href,
  referrer: document.referrer,
});
const attribution = mergeAttribution(
  previouslyStoredAttribution,
  touch,
  `acq_${crypto.randomUUID().replaceAll("-", "")}`,
);

let session = await convoy.registration.startSession({
  campaignId: "faith-gathering",
  attribution: attributionToRecord(attribution),
});

// Keep ownerSecret in memory or an HttpOnly server session. It is a capability.
const ownerSecret = session.ownerSecret;

session = await convoy.registration.submitStep(
  session.sessionId,
  session.currentStep!.id,
  { accepted: "true" },
  ownerSecret,
);

// Calling the OTP step without a code asks Convoy to send another code.
session = await convoy.registration.resendOtp(
  session.sessionId,
  session.currentStep!.id,
  { phoneCountryCode: "+91", phone: "9000025521" },
  ownerSecret,
);

Resume an in-flight registration with registration.getSession(sessionId, ownerSecret). expiresAt and ownerSecret are typed for the owner-secret API rollout while remaining optional against the current API response.

registration.redeemRecovery(campaignId, token) calls POST /convoy/register/recovery/redeem. The opaque token is sent in the JSON body with its campaign binding, never in the URL.

Recovery-route contract

Convoy-generated links use /registration/recover#campaignId=<encoded>&token=<encoded>. Both Fresh microsites must implement this as a client-only route: read the fragment, immediately call history.replaceState(null, "", "/registration/recover"), then pass both values to registration.redeemRecovery. Store the returned ownerSecret as the registration-only capability and resume with getSession.

The route must not server-render, persist, log, or copy the fragment into a query string. Fragments are not sent in HTTP requests or Referer headers; clearing it before further navigation keeps the bearer out of browser history.

Current registration

The current API requires eventId; the SDK keeps it optional so the planned server-side default remains source-compatible.

const mine = await convoy.registrations.me({ eventId: "evt_123" });

await convoy.registrations.updateFormFields({
  eventId: "evt_123",
  fields: { ATTENDS_TKT_CHURCH: "yes" },
});

These endpoints require an OAuth Bearer token, normally supplied through a request-scoped client's defaultHeaders.

Typed errors

All failures derive from ConvoyError:

  • SessionExpiredError
  • OtpSessionExpiredError
  • OtpRateLimitedError (retryAfter)
  • MaintenanceError (mode, endsAt)
  • OwnershipRequiredError
import { MaintenanceError, SessionExpiredError } from "@tktchurch/convoy";

try {
  await convoy.registration.getSession(sessionId, ownerSecret);
} catch (error) {
  if (error instanceof SessionExpiredError) {
    // Offer recovery or begin a new session.
  } else if (error instanceof MaintenanceError) {
    // Keep local form state and retry after maintenance.
  }
}

The SDK parses structured code, message, error, error_description, and reason fields. It never logs requests, owner secrets, recovery tokens, or Bearer tokens. Callers must apply the same rule to their own telemetry.

Caching

Session, status, recovery, mutation, and self-service requests use cache: "no-store". Campaign metadata may use the runtime's default caching policy.

Keywords