# JavaScript and TypeScript

> A typed, dependency-free OTP.ps client for any server-side TypeScript (Node.js, Bun, Deno, Next.js).

A small client with typed answers, a typed error, a 15-second timeout and the same phone rules as the API. It is **server-side only** (`import "server-only"` makes Next.js refuse to bundle it for the browser; remove that line outside Next.js).

```ts title="examples/nextjs/lib/otp.ts"
// OTP.ps client in TypeScript (server-side only: Next.js route handlers, server
// actions, or any Node/Bun/Deno backend). Never import this from a client component.
import "server-only";

export type OtpErrorCode =
  | "unauthorized" | "invalid_request" | "invalid_phone" | "unsupported_network" | "idempotency_conflict"
  | "account_pending" | "account_suspended" | "insufficient_balance" | "rate_limited" | "sms_failed" | "not_found";

export interface Verification {
  id: string;
  status: "pending" | "approved" | "expired" | "failed" | "canceled";
  to: string; // masked, e.g. "0599 ••• 456"
  network: "jawwal" | "ooredoo";
  purpose: "verify" | "login" | "signup" | "order" | "appointment";
  locale: "ar" | "en";
  segments: number;
  attempts: number;
  test: boolean;
  created_at: string;
  expires_at: string;
  verified_at: string | null;
}

export class OtpError extends Error {
  constructor(
    readonly status: number,
    readonly code: OtpErrorCode | "network_error",
    message: string,
    readonly retryAfter?: number,
  ) {
    super(message);
    this.name = "OtpError";
  }
}

const BASE = (process.env.OTP_PS_BASE_URL ?? "https://otp.ps").replace(/\/$/, "");

async function call<T>(method: "GET" | "POST", path: string, body?: unknown, headers: Record<string, string> = {}): Promise<T> {
  const key = process.env.OTP_PS_API_KEY;
  if (!key) throw new Error("OTP_PS_API_KEY is not set");
  let res: Response;
  try {
    res = await fetch(`${BASE}/api/v1${path}`, {
      method,
      headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json", ...headers },
      body: body === undefined ? undefined : JSON.stringify(body),
      signal: AbortSignal.timeout(15_000),
      cache: "no-store",
    });
  } catch {
    throw new OtpError(0, "network_error", "OTP.ps could not be reached");
  }
  const data = (await res.json().catch(() => null)) as { error?: OtpErrorCode; message?: string; retry_after?: number } | null;
  if (!res.ok) throw new OtpError(res.status, data?.error ?? "invalid_request", data?.message ?? `HTTP ${res.status}`, data?.retry_after);
  return data as T;
}

export function sendCode(
  phone: string,
  opts: { purpose?: Verification["purpose"]; locale?: "ar" | "en"; idempotencyKey?: string } = {},
) {
  return call<Verification & { test_code?: string }>(
    "POST",
    "/verify/send",
    { phone, purpose: opts.purpose ?? "verify", ...(opts.locale ? { locale: opts.locale } : {}) },
    opts.idempotencyKey ? { "Idempotency-Key": opts.idempotencyKey } : {},
  );
}

/** Trust only `valid === true`. */
export function checkCode(id: string, code: string) {
  return call<Verification & { valid: boolean; attempts_left: number }>("POST", "/verify/check", { id, code });
}

export function getBalance() {
  return call<{ credits: number; status: "pending" | "active" | "suspended"; mode: "live" | "test" }>("GET", "/balance");
}

/** Normalizes a Palestinian mobile number to +9705XXXXXXXX, or null. Same rules as the API. */
export function normalizePhone(raw: string): string | null {
  let d = raw
    .replace(/[٠-٩]/g, (c) => String(c.charCodeAt(0) - 0x0660))
    .replace(/[۰-۹]/g, (c) => String(c.charCodeAt(0) - 0x06f0))
    .replace(/\D/g, "");
  if (d.startsWith("00")) d = d.slice(2);
  if (d.length === 12 && (d.startsWith("970") || d.startsWith("972"))) d = d.slice(3);
  if (d.length === 10 && d.startsWith("0")) d = d.slice(1);
  return /^5[96]\d{7}$/.test(d) ? `+970${d}` : null;
}
```

Usage:

```ts
import { checkCode, OtpError, sendCode } from "./lib/otp";

try {
  const v = await sendCode("0599123456", { purpose: "order", locale: "ar", idempotencyKey: `order-${orderId}-otp-1` });
  // store v.id with the order / session
} catch (e) {
  if (e instanceof OtpError && e.code === "rate_limited") {
    // tell the customer to wait e.retryAfter seconds
  }
}

const r = await checkCode(storedId, codeFromCustomer);
if (r.valid) {
  // the number is verified
}
```

An official `@otp-ps/sdk` package is planned; until then, copy this file.
