# WRNexus JavaScript/TypeScript SDK

## Forms respondent client (0.3.6)

Version 0.3.6 includes `@wrnexus/sdk/forms`. It calls the Forms application's public respondent endpoints, not the business API gateway. Forms must be enabled on the target installation. Install using `npm install @wrnexus/sdk@0.3.6 --registry https://registry.workroot.in/repository/npm/`.

```ts
import { FormsRespondentClient } from "@wrnexus/sdk/forms";

const form = new FormsRespondentClient({ formId: "your-form-id" });
// Persist this key until you know whether this exact response was accepted.
const idempotencyKey = crypto.randomUUID();
const response = await form.submit({
  version: 1,
  answers: { name: "Respondent" },
  idempotencyKey,
});
if (response.booking) {
  const { booking } = await form.booking(response.booking).status();
  console.log(booking.status);
}
```

- `saveDraft` accepts the published version, answers and optional invitation/resume token. Later saves also send the returned `draftRevision`. Store the returned resume link privately.
- `slots` reads available booking choices for a published version. Availability is checked again when submitting or applying an approved time change.
- `booking(capability)` provides `status`, `slots`, `reschedule`, `withdrawChange` and `cancel`. Rescheduling needs a stable idempotency key. A pending review keeps the original booking confirmed; withdrawing is available only before approval.
- `payment(capability)` provides `initialize`, `verify`, `status` and `refresh`. Open the provider checkout with `initialize().checkout`, then pass its order ID, payment ID and signature to `verify`. A browser callback alone does not prove payment. The server verifies and reconciles it.
- `applicant(capability)` provides `read` and revision-checked `edit`. The form's current editing policy and approval state still apply.

Use the capability objects returned by submission; never embed an organization API key. Capability tokens are transmitted in Authorization headers, while invitation/resume tokens remain in request bodies. The SDK never retries changes automatically. After an uncertain result, use the same submission/change key or refresh the existing booking/payment instead of creating another operation.

The client accepts HTTPS origins and localhost HTTP for development. Redirects are refused, responses and requests are bounded, and transport errors do not echo tokens or private answers. Pass an AbortSignal as the final request option to cancel a request.

Browser usage requires the Forms origin or an approved same-origin integration. This client does not bypass CSRF, enable cross-origin embedding, add authenticated-respondent access, or expose staff management APIs. Upload helpers and business Forms/Calendar SDK operations remain separate release work.

Server SDK for SMS, WhatsApp, email, shared Service Balance and signed webhooks, with Notifications and recipient inbox preview clients. Requires Node.js 22+ or Bun 1.3+. Uses ES modules and includes TypeScript declarations.

```sh
npm install @wrnexus/sdk@0.3.0 --registry=https://registry.workroot.in/repository/npm/
```

Publishing requires registry authentication; installation is public. Set `WRNEXUS_API_KEY` in the server environment. Never expose a business API key in a browser or mobile application. `WRNEXUS_API_ENDPOINT` defaults to `https://api.wrnexus.com`; explicit constructor options take precedence over environment values.

```ts
import WRNexus, { type SmsSendResponse, type BalanceResponse } from "@wrnexus/sdk";
const wrnexus = new WRNexus();
const wallet: BalanceResponse = await wrnexus.sms.balance();
console.log(wallet.balance.availableMinor, wallet.balance.currency);
const sent: SmsSendResponse = await wrnexus.sms.send({
  destination: "+919000000000",
  templateName: "your-approved-template",
  senderName: "your-verified-sender",
  variables: { order: "123" },
  idempotencyKey: "order-123",
});
const status = await wrnexus.sms.checkStatus(sent.messageId);
console.log(status.status, status.message.error_code);
```

## Available operations and response types

Each channel supports `send`, `checkStatus`, `details`, `list({limit,status})`, `templates` and `balance`. SMS also supports `senders`. There are 19 gateway operations. Lists have a limit/status filter, without a pagination cursor. Method return types are inferred automatically; exported models include `SmsSendResponse`, `WhatsAppSendResponse`, `EmailSendResponse`, `SmsStatusMessage`, `SmsMessageDetails`, `SmsListMessage`, `WhatsAppMessage`, `WhatsAppMessageDetails`, `EmailMessage`, channel template types, `SmsSender`, `StatusResponse<T>`, `MessagesResponse<T>`, `TemplatesResponse<T>` and `BalanceResponse`.

Response models preserve current backend names, nullable fields and fields that differ between status, details and list operations. `requestId` is available on all successful responses and on errors when supplied by the server. PostgreSQL bigint row columns use `DatabaseInteger` (`number | string`); convert intentionally before calculations. These static models describe the current contract; they do not validate arbitrary replacement transports at runtime.

### Service Balance

```ts
await wrnexus.sms.balance();
await wrnexus.whatsapp.balance();
await wrnexus.email.balance();
await wrnexus.balance("whatsapp"); // convenience method; defaults to SMS
```

All four examples read the **same organization wallet**. They are not separate balances and must not be summed. Choose a channel permitted by your key. The matching API-key permission is `sms.balance`, `whatsapp.balance` or `email.balance`; existing keys do not automatically gain new permissions. IP restrictions, membership checks and rate limits still apply.

The typed response is `{ok:true,requestId?,balance:{availableMinor,reservedMinor,currency,updatedAt}}`. Amounts are integers in the currency's minor units (for INR, 5021 means ₹50.21). Missing wallets return `balance-not-found`; a missing wallet is never represented as a fabricated zero balance. Balance calls are read-only and do not create, fund or charge a wallet.

### Requests and errors

Errors expose `code`, `status`, and `requestId`. Server messages and transport errors are sanitized to avoid credential leakage, including problem+json errors. Send inputs keep backend field names. SMS/WhatsApp support the shown idempotency keys; email has no guaranteed idempotency support. Sends are never automatically retried. Reads optionally retry up to three transient HTTP responses (`readRetries`); the default is zero. Default timeout is 30 seconds, overridden with `timeoutMs`. Every API call accepts `{signal}` for cancellation. Redirects are rejected. Endpoints require HTTPS except loopback HTTP for isolated tests. Current keys are live keys; changing an endpoint does not create a sandbox account.

WhatsApp inputs include text, approved templates, hosted media, location, contacts, reaction and interactive messages. Hosted media uses `media_kind` and `media_url` or `media_id`; multipart upload is not exposed by this JSON gateway. Interactive fields keep current backend names, including `interactive_type`, `body`, `buttons`, `rows`, `product_id`, `flow_id` and `cta`. Provider prerequisites still apply.

## Notifications (preview)

`@wrnexus/sdk/notifications` is the server client for the Notifications API. It covers recipients, groups, segments, templates, every send channel (in-app, Email, SMS, WhatsApp, web push, mobile push), campaigns, workflows and events. It also covers provider connections, branding, custom domains, Test recipients, exports and units. The API key decides the organisation, the Test or Live environment, and the permissions. Contract `sdk/notifications-contract.json` lists all 94 operations, and its status is `preview` until Notifications launches.

```ts
import WRNexusNotifications, { NotificationEvent } from "@wrnexus/sdk/notifications";
const wrnexus = new WRNexusNotifications();
const recipient = await wrnexus.notifications.recipientUpsert({
  customerId: "customer-42",
  name: "Asha",
});
await wrnexus.notifications.send({
  recipientId: recipient.recipient.id,
  title: "Order ready",
  body: "Your order is ready for collection.",
  purpose: "transactional",
  category: "orders",
  idempotencyKey: "order-42-ready",
});
// Issue a short-lived recipient token for the recipient's browser or app.
const { token } = await wrnexus.notifications.recipientToken({
  recipientId: recipient.recipient.id,
});
```

Sends never retry automatically; resend with the same `idempotencyKey` to replay safely. Test-environment keys simulate delivery except for recipients an owner approved for real Test delivery.

## Recipient inbox client

`@wrnexus/sdk/inbox` runs in browsers, React Native and server runtimes. It uses only `fetch` and has no Node.js imports. It authenticates with a recipient token that your server issues, never with an API key.

```ts
import WRNexusInbox from "@wrnexus/sdk/inbox";
const inbox = new WRNexusInbox({
  // Called before each request, so an expiring token can be refreshed from your server.
  token: async () => (await fetch("/my-app/notifications-token")).text(),
});
const { messages, unreadCount } = await inbox.messages({ limit: 20 });
await inbox.markRead(messages[0].id);
const stop = new AbortController();
void inbox.subscribe((snapshot) => render(snapshot), { signal: stop.signal });
await inbox.savePreferences({ category: "offers", inAppEnabled: true, marketingEnabled: false });
```

It also covers `archive`, `preferences`, `devices`, `registerWebPush` (pass `PushSubscription.toJSON()`; the matching connection's `publicKey` is the VAPID `applicationServerKey`), `unregisterWebPush`, `registerMobilePush` (an FCM or APNs token) and `unregisterMobilePush`. Errors are `WRNexusInboxError` with `code` and `status`. The endpoint defaults to `https://notifications.wrnexus.com`; pass your verified custom domain instead when you use one. The inbox API allows cross-site browser calls without cookies.

## Branded inbox component (0.3.2 preview)

```ts
import { mountInbox } from "@wrnexus/sdk/inbox-view";
const view = mountInbox(document.getElementById("notifications")!, {
  client: inbox,
  onAction(message, action, url) {
    // Route the HTTPS URL, or handle the custom action.id in your application.
  },
});
// On logout, destroy before mounting a new recipient client.
view.destroy();
```

Use an empty host element. The component loads organization name, brand color and content-addressed logo from the recipient API, then renders messages, unread count, read/archive controls, custom actions and saved notification preferences. It uses the host's WRNexus theme variables, shadow-root style isolation, real buttons, keyboard focus and text-only message rendering. Unsafe action URLs are refused. Destroy clears recipient content and cancels the stream; the same host can then mount a new recipient client. A visible component refreshes after the page resumes. Loading, empty and retry states contain no invented messages.

## Webhook callbacks

```ts
import WRNexus, { WRNexusEvent } from "@wrnexus/sdk";
import express from "express"; // installed separately by your application

const wrnexus = new WRNexus();
const webhook = wrnexus.webhook({
  url: "https://your-domain.com/webhooks/wrnexus",
  secret: process.env.WRNEXUS_WEBHOOK_SECRET!,
});
webhook.on(WRNexusEvent.SMS_DELIVERED, async (data, event) => {
  // Update business records idempotently; event.id identifies repeat deliveries.
});
webhook.onAny(async (type, data, event) => {
  // Central callback for subscribed SMS, WhatsApp and email events.
});
const app = express();
app.post(
  "/webhooks/wrnexus",
  express.raw({ type: "application/json", limit: "1mb" }),
  webhook.expressHandler(),
);
app.use(express.json()); // raw webhook route must come first
app.listen(3000);
```

Register `webhook.url` and the matching secret in Account → Webhooks and deploy the route behind your public domain. SDK initialization does not start a server, expose the domain or register the endpoint. `handler()` accepts Fetch requests (for example `Bun.serve({fetch:webhook.handler()})`); `expressHandler()` accepts Express requests. `dispatch(rawBytes,headers)` supports other adapters. Standalone `WRNexusWebhook` and `verifyWebhook` are exported too.

The 20 event constants match the platform catalogue. `on`, `off`, `onAny` and `offAny` support multiple callbacks. The SDK verifies untouched body bytes with the locally configured secret, HMAC-SHA256 and signing timestamp before invoking callbacks. Default timestamp tolerance is 300 seconds; default body limit is 1 MiB. It never trusts an incoming secret header. Handlers accept POST only; successful callbacks return HTTP 200, invalid signatures 401, oversized payloads 413 and callback failures a sanitized 500 so delivery can retry. Callbacks run sequentially and are awaited.

Deliveries may repeat. Persist `event.id` with your business transaction or make the action idempotent. Earlier callbacks may execute again if a later callback fails. The SDK does not hide retries with a process-local cache. Webhook data keeps its event-specific backend shape as `Record<string,unknown>`; narrow fields before using them.

## Verification

Published packages are installed into a separate consumer project at `sdk/integration/javascript`; consumer tests never import SDK source. Evidence includes authenticated live reads, existing SMS/WhatsApp/email delivery checks, public package installation, TypeScript declaration compilation, signature/tampering tests and an actual platform webhook callback over HTTPS. Provider delivery timing remains outside the SDK; email submitted means mail-server acceptance, not proof of inbox receipt.

Version 0.3.0 publishes the Notifications and inbox entry points under the npm `preview` tag. The existing messaging entry point retains its 19 operations and 20 event constants; Notifications adds 94 operations and 41 separate `NotificationEvent` constants. Java, Python, Go and Rust 0.2.0 provide the same Notifications server operation catalogue. Native-device and production delivery verification remain separate rollout requirements.

## Forms respondent recovery and validation (0.3.6)

Forms source also accepts an optional `applicantRecoveryToken` on submission: generate 32 cryptographically random bytes encoded as unpadded base64url and retain the token with the original answers, coupon and idempotency key. An explicit retry must reuse that request. Eligible forms can recover the same private application link after a lost response; revoked or expired grants are not renewed. Treat this token as a secret capability and never log it. Available in version 0.3.6.

The optional draft `presentationSeed` is 32 lowercase hexadecimal characters and preserves shuffled choice presentation. It is presentation data, not an access token.

`FormRequestError` exposes the server's machine-readable `code`, optional `field`, `answerPath` and `requestId`. For a repeating group, `answerPath` contains alternating field IDs and zero-based entry indexes, ending with the invalid field ID (for example, `['attendees', 1, 'email']`). Use it to focus the corresponding control and translate the error code in your application. The SDK keeps the error message generic and does not attach raw responses or answers. Unknown or malformed metadata is omitted. Available in version 0.3.6.

## Calendar participant client (0.3.6)

Forms waitlist source methods are also available: `joinWaitlist({ version, start, quantity, accessToken, idempotencyKey, token })`, then `waitlist({ id, token }).read()` or `.cancel(revision)`. Use a cryptographically random 32-byte base64url token and retain the complete original enrollment request for explicit retries. Joining is separate from submitting the form and does not reserve a slot. The form must enable waitlists. The participant UI and API are implemented in source, but offer-to-submission completion is still in progress; join and cancel methods are available in version 0.3.6.

Version 0.3.6 includes the `@wrnexus/sdk/calendar` participant entry point for invitations, offers and calendar downloads.

```ts
import { CalendarParticipantClient } from "@wrnexus/sdk/calendar";

const calendar = new CalendarParticipantClient();
const offer = calendar.offer(privateOfferToken);
const current = await offer.read();
// Call only after the participant chooses Accept.
await offer.respond({ action: "accept", revision: current.revision });

const invitation = calendar.invitation(privateInvitationToken);
const details = await invitation.read();
// Call only after the attendee chooses their response.
await invitation.respond({ response: "accepted", revision: details.revision });
// Returns iCalendar text; save it using your application's download mechanism.
const calendarFile = await invitation.downloadCalendar();
```

Tokens come from the private RSVP or booking-offer link. They authorize only that invitation or offer; never put them in logs, analytics, public source code or shared configuration. Reads and mutations use bounded responses, deadlines, no cookies, no redirects and no automatic retries. After a transport failure, read current state before deciding whether another mutation is needed. Offer expiry and payment/approval requirements remain server-enforced.

Use this from a server or the Calendar origin. The application does not enable cross-origin browser requests. No business API key is required or accepted. Invitation responses apply to the series when `recurrenceRule` is present. This API does not grant staff event editing or booking administration.

Calendar downloads are snapshots, not subscriptions. Recurring invitations include the next 90 days by default, with current overrides and cancellations. Pass `{ start, end }` as ISO date strings for a different window of at most one year. Single-event invitations contain their event regardless of the requested window. Later changes require another download. The client bounds downloads to 1 MiB; use a narrower recurring window if necessary.

### Private Forms access (source implementation; not yet released)

`FormsRespondentClient.openPrivateForm(token)` loads the pinned definition, saved answers, page, draft revision and presentation seed for an invitation or resume capability. The token travels in the POST body, never the request URL. The hosted renderer now issues `/f/<id>/access#token=<token>` links. Treat these links and returned data as private; do not log them. Authenticated forms still require the respondent's authorized Forms session. Cross-origin browser access is not enabled by this method.

```ts
const presentation = await forms.openPrivateForm(privateToken);
// Render presentation.definition using presentation.values and preserve
// presentation.presentationSeed and presentation.draftRevision on later saves.
```
