PeaBox Lab › PeaLang › Learn › Chapter 15 › Lesson 4

Part III — Advanced Systems · Chapter 15 · Lesson 4 of 7 · 7 min read

Lesson 4: TypeScript Client and React Integration

Lesson level: Advanced

Purpose: Call PeaLang rules from TypeScript with types derived from the contract, and present rule results in React without trusting the browser for final decisions.

Learning objectives

By the end of this lesson you will be able to:

4.1 Where TypeScript runs

TypeScript appears in two very different places. On a Node.js server, it is a trusted host that can call the sidecar with a secret token. In the browser, it is untrusted: anything it receives can be read, and anything it sends can be forged. Keep this distinction in every design decision in this lesson.

The rule of thumb is simple: the browser calls your API, your API calls the sidecar, and only your server decides prices.

4.2 Types from the contract

Generate types and validators from the contract file with a schema library such as Zod. The type describes the shape at compile time; the schema checks the shape at run time.

// src/pricing/contract.ts  (generated from pricing.contract.toml)
import { z } from "zod";

export const LineItem = z.object({
  sku: z.string().max(32),
  qty: z.number().int().min(1).max(999),
  price: z.number().min(0),
});

export const QuoteInput = z.object({
  customer_id: z.string().regex(/^C[0-9]{6}$/),
  currency: z.enum(["EUR", "GBP", "USD"]),
  items: z.array(LineItem).min(1).max(200),
});

export const QuoteOutput = z.object({
  subtotal: z.number().min(0),
  discount_pct: z.number().min(0).max(30),
  reason: z.enum(["NONE", "GOLD_100", "BULK_250"]),
});

export type QuoteInput = z.infer<typeof QuoteInput>;
export type QuoteOutput = z.infer<typeof QuoteOutput>;

Because the type is inferred from the schema, the two cannot disagree. A TypeScript type alone would compile happily against a response that does not match it at run time.

4.3 A server-side client

// src/pricing/client.ts  (Node.js only)
import { QuoteInput, QuoteOutput } from "./contract";

export class PricingError extends Error {
  constructor(public code: string, public retryable: boolean) { super(code); }
}

const BASE = process.env.PEA_SIDECAR_URL ?? "http://127.0.0.1:7071";
const TOKEN = process.env.PEA_SIDECAR_TOKEN ?? "";

export async function quote(input: QuoteInput, requestId: string): Promise<QuoteOutput & { version: string }> {
  const args = QuoteInput.parse(input);
  const ctrl = new AbortController();
  const timer = setTimeout(() => ctrl.abort(), 150);
  try {
    const res = await fetch(`${BASE}/v1/modules/pricing/exports/quote`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${TOKEN}`,
        "Content-Type": "application/json",
        "X-Request-Id": requestId,
      },
      body: JSON.stringify({ args: [args] }),
      signal: ctrl.signal,
    });
    const body = await res.json();
    if (!res.ok) {
      throw new PricingError(body?.error?.code ?? "UNKNOWN", res.status === 503);
    }
    const result = QuoteOutput.safeParse(body.result);
    if (!result.success) throw new PricingError("INVALID_DECISION", false);
    return { ...result.data, version: String(body.module_version) };
  } catch (e) {
    if (e instanceof PricingError) throw e;
    throw new PricingError("SIDECAR_UNAVAILABLE", true);
  } finally {
    clearTimeout(timer);
  }
}

The token is read from the server environment and never appears in code that ships to a browser. Note that QuoteInput.parse throws a validation error for bad input; catch it in the route below and return 400 so caller mistakes are not mistaken for an unavailable sidecar.

4.4 Your API route

// src/routes/quote.ts  (Express)
import { Router } from "express";
import { randomUUID } from "node:crypto";
import { ZodError } from "zod";
import { quote, PricingError } from "../pricing/client";
import { cartFromSession } from "../cart";

export const router = Router();

router.post("/api/quote", async (req, res) => {
  const requestId = randomUUID();
  try {
    const cart = await cartFromSession(req);          // server-side cart, not req.body
    const q = await quote(cart, requestId);
    res.json({ subtotal: q.subtotal, discountPct: q.discount_pct,
               reason: q.reason, requestId });
  } catch (e) {
    if (e instanceof ZodError) return res.status(400).json({ code: "INVALID_CART", requestId });
    if (e instanceof PricingError && e.retryable)
      return res.status(503).json({ code: "PRICING_UNAVAILABLE", requestId });
    req.log?.error({ requestId, code: (e as PricingError).code });
    res.status(502).json({ code: "PRICING_ERROR", requestId });
  }
});

The route builds the cart from server-side session state, not from the request body. A browser can send any prices it likes; it cannot change what the server already knows about the cart. The response omits module_version and usage data: they help operators, not shoppers.

4.5 A React hook for quotes

// web/src/useQuote.ts
import { useEffect, useRef, useState } from "react";

type Quote = { subtotal: number; discountPct: number; reason: string };
type State =
  | { status: "loading" }
  | { status: "ready"; quote: Quote }
  | { status: "unavailable" }
  | { status: "error"; requestId?: string };

export function useQuote(cartVersion: number): State {
  const [state, setState] = useState<State>({ status: "loading" });
  const latest = useRef(0);

  useEffect(() => {
    const call = ++latest.current;
    setState({ status: "loading" });
    fetch("/api/quote", { method: "POST", credentials: "same-origin" })
      .then(async (res) => {
        const body = await res.json();
        if (call !== latest.current) return;          // ignore stale responses
        if (res.ok) setState({ status: "ready", quote: body });
        else if (res.status === 503) setState({ status: "unavailable" });
        else setState({ status: "error", requestId: body.requestId });
      })
      .catch(() => call === latest.current && setState({ status: "unavailable" }));
  }, [cartVersion]);

  return state;
}

The latest counter prevents a slow response for an old cart from overwriting the quote for the current cart, a common bug when shoppers change quantities quickly.

// web/src/QuoteSummary.tsx
export function QuoteSummary({ cartVersion }: { cartVersion: number }) {
  const q = useQuote(cartVersion);
  if (q.status === "loading") return <p aria-busy="true">Calculating your price…</p>;
  if (q.status === "unavailable") return <p>Prices are being updated. Please try again shortly.</p>;
  if (q.status === "error") return <p>We couldn't price your cart (ref {q.requestId}).</p>;
  const { subtotal, discountPct, reason } = q.quote;
  return (
    <dl>
      <dt>Subtotal</dt><dd>{subtotal.toFixed(2)}</dd>
      {discountPct > 0 && (<><dt>Discount</dt><dd>{discountPct}% ({REASON_TEXT[reason]})</dd></>)}
    </dl>
  );
}

const REASON_TEXT: Record<string, string> = {
  NONE: "", GOLD_100: "Gold member offer", BULK_250: "Bulk order saving",
};

Reason codes are mapped to shopper-friendly text in the front end. Codes stay stable for tests and audits; wording can change without touching the rule.

4.6 What the browser must never decide

ConcernBrowserServer
Show an estimated discountYesYes
Decide the charged priceNoYes, at checkout, re-evaluated
Hold the sidecar tokenNeverYes, in environment or secret store
See module version and usageNoYes, in logs
Retry on 503Yes, with back-offNarrowly, in the client

At checkout, the server evaluates the rule again with the final cart. If the result differs from what the shopper saw, show the new price and ask for confirmation instead of silently charging a different amount.

4.7 Common mistakes

MistakeConsequenceFix
Calling the sidecar from the browserToken exposed; rules callable by anyoneBrowser calls your API; server calls the sidecar
TypeScript types without runtime checksBad responses pass silentlyInfer types from Zod or similar schemas
Taking prices from the request bodyShoppers set their own pricesBuild the cart from server-side state
Showing reason codes to usersConfusing, brittle wordingMap codes to text in the front end
Ignoring stale responsesOld quotes overwrite new onesTrack the latest request and drop older results
Trusting the estimate at checkoutCharged price differs from rule resultRe-evaluate on the server and confirm changes

Guided practice

Hands-on lab

Build a small checkout page that shows a live quote as quantities change. Implement the server client, API route, hook, and summary component. Add a checkout endpoint that re-evaluates the rule and returns a PRICE_CHANGED response when the final result differs from the last quote the shopper saw.

Deliverable: the server and web source, tests for forged input and stale responses, and a short screen recording or screenshots of the loading, ready, unavailable, and price-changed states.

Review questions

Applied challenge

Add an offline preview of the pricing rule using the browser execution model from Chapter 23. Show the preview instantly, replace it with the server quote when it arrives, and display a clear notice whenever the two differ. Explain why the preview can never be used to charge a customer.

Lesson summary

TypeScript hosts derive types and validators from the shared contract. Server-side clients hold secrets, validate both directions, and map errors to stable codes. React components call your own API, handle loading, error, unavailable, and stale states, and translate reason codes for people. The browser may display estimates, but only the server decides what a customer pays.

Transition to Lesson 5

Lesson 5 returns to Python with FastAPI integration patterns: dependency injection for runtimes, request-scoped limits, and the standard exception handlers.

Lesson status: Ready for review.

← Previous Next →