# JavaScript / TypeScript

Server and browser clients, every method, Funnel/Paywall/experiment entry points and error handling.

Last updated: 2026-11-06

[Web version](https://www.longplayai.com/docs/sdk/javascript)

<a id="install"></a>

## Install

**terminal**

```bash
npm install --save-exact @tinkerlandai/longplay-sdk@latest
```

One package serves Node.js 22+ backends and browsers and ships TypeScript types. These examples use production API https://api.longplayai.com with that deployment's Sandbox credentials. See the install page for entry points and environment requirements.

- [Install SDKs and CLI](https://www.longplayai.com/docs/install.md#javascript)

<a id="script"></a>

## Script installation

Plain HTML sites need no npm or bundler. Resolve the latest published Web module once, save longplay-sdk.js and commit it, then import from that file. Resolve again explicitly to upgrade. This example uses Sandbox credentials from the production API deployment.

**terminal**

```bash
SDK_MODULE_URL="$(curl -fsS https://cdn.longplayai.com/sdk/module)" &&
printf 'export * from "%s";\n' "$SDK_MODULE_URL" > longplay-sdk.js
```

**index.html**

```html
<script type="module">
  import { createLongplay } from "./longplay-sdk.js";
  // This endpoint must verify your existing signed-in user before issuing credentials.
  const response = await fetch("/api/longplay-session", {
    credentials: "same-origin", cache: "no-store",
  });
  if (!response.ok) throw new Error("Customer session unavailable");
  const session = await response.json();
  const client = createLongplay({
    baseUrl: "https://api.longplayai.com",
    scope: { projectId: "<APP_UUID>", environment: "sandbox" },
  });
  client.identify(session);
  console.log(await client.readHoldings());
  client.track("page_viewed", { page: location.pathname });
  await client.flush();
  // Call client.reset() on logout/account change, and destroy any open UI hosts.
</script>
```

longplay-sdk.js re-exports every npm root browser API plus `createPageExperiments` / `createVisualExperiments`. Replace npm imports in the guides with imports of the same names from longplay-sdk.js: use `createLongplay` for entitlements/events, `createPaywallSession` / `showPaywall` for Paywalls, `createFunnelRunController` / `showFunnelRun` for Funnels, and `mountContent` for independent content.

Loading does not create sessions, send events or start experiments. Your authenticated backend issues Customer Tokens and retains Server Keys. Funnels retain backend start and Run recovery. Loading failures reject the module import. UI loads on demand, with archived modules retained. CSP must allow the script origin and target API. The existing classic /sdk.js loader still provides Longplay.ready and follows Web releases. Page experiments also use the unified entry; explicitly create their clients and call `start()`.

Pages that show a Funnel or Paywall can open their connections early. Put these two lines in the page head. `crossorigin` is required: the SDK sends requests without credentials, so a preconnect without it opens a connection the SDK cannot use.

**index.html**

```html
<link rel="preconnect" href="https://api.longplayai.com" crossorigin>
<link rel="preconnect" href="https://cdn.longplayai.com" crossorigin>
```

<a id="iam"></a>

## IAM and visual experiment binding

The independent IAM build package generates the page map. Pass the descriptor's digest as appManifestRelease to createVisualExperiments and explicitly call start. Building, uploading and experiment publication are separate steps.

- [Complete IAM integration guide](https://www.longplayai.com/docs/iam.md)

<a id="server"></a>

## Server client

`createLongplayServer` uses a Server Key and can only be created on a trusted backend; calling it in a browser throws `SERVER_ONLY`. Each method maps to one HTTP operation, and requests and responses are validated against the public contract.

**longplay.server.ts**

```ts
import { createLongplayServer, LongplayError } from "@tinkerlandai/longplay-sdk/server";

const longplay = createLongplayServer({
  baseUrl: process.env.LONGPLAY_API_URL!,
  apiKey: process.env.LONGPLAY_SERVER_KEY!,
  scope: { projectId: process.env.LONGPLAY_PROJECT_ID!, environment: "sandbox" },
});

export async function generateImage(verifiedUserId: string, eventId: string) {
  const { customer } = await longplay.getOrCreateCustomer({
    externalUserId: verifiedUserId,
  });
  const { check } = await longplay.checkEntitlement({
    customerId: customer.id,
    requirement: {
      internal_feature_id: process.env.LONGPLAY_FEATURE_ID!,
      quantity: "1",
      properties: {},
    },
  });
  if (!check.allowed) return { allowed: false as const };

  try {
    const { receipts } = await longplay.trackUsage({
      customerId: customer.id,
      // eventId is persisted before the call and reused on every retry.
      command: { eventName: "image_generated", quantity: "1", idempotencyKey: eventId },
    });
    for (const receipt of receipts)
      if (!receipt.accepted) console.warn("usage refused", receipt.reason);
    return { allowed: true as const, receipts };
  } catch (error) {
    if (error instanceof LongplayError) console.error(error.code, error.recovery, error.requestId);
    throw error;
  }
}
```

**Server methods by area**

| Area | Methods |
| --- | --- |
| Customer messaging and installations | `sendMessage`, `readMessage` |
| Customers, Guests and Sessions | `getOrCreateCustomer`, `getCustomer`, `listCustomers`, `updateCustomer`, `createCustomerSession`, `revokeCustomerSessions`, `createGuestCustomer`, `resumeGuestSession`, `claimGuestCustomer` |
| Entitlements and product presentation | `checkEntitlement`, `resolveOffering`, `resolvePaywall`, `readHoldings` |
| Balances, usage and ledger | `readBalanceSource`, `adjustBalance`, `readUsage`, `setUsage`, `manageBalanceGrant`, `listBalanceGrants`, `manageUsageEntity`, `readUsageAnalytics`, `readCreditAnalytics`, `submitUsageBatch`, `readUsageBatch`, `readLedger`, `readCreditStatement`, `quoteBalance`, `trackUsage`, `mutateBalance` |
| Seats | `readSeats`, `manageSeat` |
| Subscriptions and payments | `setupPayment`, `readPaymentSetup`, `verifySubscriptions`, `previewAttach`, `attach`, `readSubscriptionOperation`, `previewUpdate`, `update`, `readSubscriptionUpdate`, `listSubscriptions`, `listPurchases`, `listSubscriptionConflicts`, `retrySubscriptionConflict`, `manageSubscriptionTrial`, `readSubscriptionTrial`, `previewSubscriptionBatch`, `confirmSubscriptionBatch`, `readSubscriptionBatch`, `abandonSubscriptionBatch`, `recordMerchantEvent` |
| Invoices, refunds and billing | `listInvoiceTemplates`, `previewInvoice`, `createInvoice`, `manageInvoice`, `readInvoiceOperation`, `listInvoices`, `getInvoice`, `previewRefund`, `refund`, `readRefund`, `manageBillingLimits`, `readBillingInvoice`, `prepareBillingAdjustment` |
| Coupons, rewards and referrals | `grantOffer`, `grantModelBenefit`, `readModelBenefit` |
| Feature flags, evaluation and events | `getFeatures`, `evaluateFeatures`, `trackEvents` |
| Native purchases | `restoreNativePurchase` |
| AI pricing | `readAiPricing` |
| CLI and CI | `resolveContent` |

**Client options**

| Option | Description |
| --- | --- |
| `apiKey` | Server Key (`gg_sk_`) from your backend secret store. |
| `scope` | `{ projectId, environment }`: the App UUID and `sandbox` or `live`, matching the Key. |
| `baseUrl` | API origin; default https://api.longplayai.com. Set https://api.longplayai.com for these examples, without /api/v1. |
| `timeoutMs` | Per-request timeout, default 10000, maximum 120000. |
| `fetch` | Inject a custom fetch for proxies or offline tests. |

<a id="browser"></a>

## Browser client

Browsers never hold a Server Key. After your backend verifies the login it issues a Customer Token, and the browser calls `identify(token)`. The token determines the Customer; a browser cannot select another customerId. Call `reset()` on sign-out or account switch.

**Backend: server/session.ts**

```ts
import { createLongplayServer } from "@tinkerlandai/longplay-sdk/server";

const longplay = createLongplayServer({
  baseUrl: process.env.LONGPLAY_API_URL!,
  apiKey: process.env.LONGPLAY_SERVER_KEY!,
  scope: { projectId: process.env.LONGPLAY_PROJECT_ID!, environment: "sandbox" },
});

// Call only after your own login check succeeds.
export async function issueCustomerSession(verifiedUserId: string) {
  const { customer } = await longplay.getOrCreateCustomer({
    externalUserId: verifiedUserId,
  });
  return longplay.createCustomerSession(customer.id);
}
```

**Browser: app/longplay.ts**

```ts
import { createLongplay, type CustomerSession } from "@tinkerlandai/longplay-sdk";

const longplay = createLongplay({
  baseUrl: "https://api.longplayai.com",
  scope: { projectId: "<APP_UUID>", environment: "sandbox" },
});

export async function signIn(session: CustomerSession) {
  longplay.identify(session);
  const { holdings } = await longplay.readHoldings();
  return holdings;
}

export function signOut() {
  longplay.reset();
}
```

**Browser methods by area**

| Area | Methods |
| --- | --- |
| Customer messaging and installations | `push.sync`, `push.read`, `messaging.preference`, `messaging.setPreference` |
| Customers, Guests and Sessions | `session.refresh` |
| Entitlements and product presentation | `checkEntitlement`, `resolveOffering`, `resolvePaywall`, `readHoldings` |
| Balances, usage and ledger | `readLedger`, `readCreditStatement`, `quoteBalance` |
| Subscriptions and payments | `setupPayment`, `readPaymentSetup`, `previewAttach`, `attach`, `readSubscriptionOperation`, `previewUpdate`, `update`, `readSubscriptionUpdate` |
| Invoices, refunds and billing | `readBillingControls`, `prepareBillingAuthorization`, `confirmBillingAuthorization`, `setBillingCoupons`, `revokeBillingAuthorization`, `listBillingInvoices`, `readBillingInvoice`, `confirmBillingAdjustment` |
| Coupons, rewards and referrals | `redeemCoupon`, `listOffers`, `claimCoupon`, `redeemReward`, `createReferralCode`, `claimRewardProduct` |
| Feature flags, evaluation and events | `features`, `track`, `flush` |
| Native purchases | `restoreNativePurchase` |
| CLI and CI | `resolveContent` |

- Register website origins in Console under Integrations → Website origins (one complete origin per line, at most 20). Sandbox also allows HTTP development on localhost, 127.0.0.1 and [::1]; Live accepts HTTPS only.
- The Key that issues sessions needs `sessions:create` plus the scopes the browser will use, such as `entitlements:read`, `billing:write` or `offers:resolve`.
- `longplay.forFunnel({ funnelId, versionId })` returns a resource client bound to that Funnel for coupon claims, Offering/Paywall resolution and purchase quotes.

<a id="content"></a>

## Standalone Pages, Popups and Banners

Publish a Banner with no required inputs and a declared continue action. The Customer Token needs content:read. resolveContent reads a published version and mountContent explicitly mounts it; use the matching kind for a Page or Popup.

**content.ts**

```ts
import {
  createLongplay,
  mountContent,
  type ContentActionIntent,
} from "@tinkerlandai/longplay-sdk";

export async function showBanner(
  container: HTMLElement,
  customerToken: string,
  contentId: string,
  onContinue: (intent: ContentActionIntent) => Promise<void>,
) {
  const longplay = createLongplay({
    baseUrl: "https://api.longplayai.com",
    scope: { projectId: "<TEST_APP_UUID>", environment: "sandbox" },
  });
  longplay.identify(customerToken);
  const { content } = await longplay.resolveContent({
    kind: "banner",
    selector: { type: "resource", id: contentId },
  });
  const host = await mountContent(container, {
    content,
    actions: { continue: onContinue },
    onError: console.error,
  });
  return {
    retryAction: host.retryAction,
    destroy() {
      host.destroy();
      longplay.reset();
    },
  };
}
```

Supply a handler for every declared action. Use intent.requestId as the backend operation's idempotency key. retryAction preserves the original intent after failure; call destroy on unmount, sign-out or account switch. Display and clicks grant no commercial authority; your backend still authorizes and executes business actions.

<a id="helpers"></a>

## Funnels, Paywalls and experiments

**Other exports**

| Function | Entry | Purpose |
| --- | --- | --- |
| `createFunnelStartClient` | `/server` | Start a Funnel Run from your backend and receive a Run Token |
| `createFunnelRunController`, `showFunnelRun` | main | Display and advance a Run in the browser |
| `createFunnelClient` | main | Start a Run from a client that holds a Customer Token |
| `createLocalFunnelClient`, `createConfigurationSync` | main / `/server` | Local-mode Funnels and shared public configuration |
| `createFunnelDecisionClient`, `createFunnelCampaignClient` | `/server` | Server decisions, Campaign starts and adoption reports |
| `createFunnelOrchestrationClient`, `renewFunnelRun` | `/server` | Signal a Run, read its results and rotate its Run Token |
| `createPaywallStartClient`, `createPaywallSession`, `showPaywall` | `/server` / main | Standalone Paywall sessions and display |
| `createFeatureClient`, `longplay.features()` | main | Feature evaluation and subscriptions |
| `createPageExperiments` | `/page` | URL redirect experiments |
| `createVisualExperiments` | `/visual` | Visual experiments |
| `createNativeReceiptClient` | `/server` | Submit native store proofs from your backend |
| `createAiUsageMiddleware`, `createAiPricing` | `/server` | AI SDK usage-billing middleware and pricing |
| `createOpenRouterUsageClient`, `trackOpenRouterUsage` | `/openrouter` | OpenRouter usage billing |

- [Run Funnels](https://www.longplayai.com/docs/guides/funnels.md)
- [Payments, subscriptions and billing](https://www.longplayai.com/docs/guides/commerce.md)
- [Features, experiments and events](https://www.longplayai.com/docs/guides/features.md)

<a id="errors"></a>

## Errors and retries

A failed request throws `LongplayError` with `code`, `status`, `requestId`, `retryable`, `recovery`, and optional `reason` and `retryAfterSeconds`. The SDK never retries writes automatically: persist the requestId, eventId or idempotencyKey before sending, and after an unknown result replay the same value and input or read the original operation.

> When input doesn't match the operation's format, the SDK throws before sending anything. A few methods, such as `getOrCreateCustomer` and `grantOffer`, throw `LongplayError` (`INVALID_REQUEST`); most throw a ZodError (`error.name === "ZodError"`), which is not a `LongplayError`. Validate input before calling, or handle both.

- [Error codes and recovery](https://www.longplayai.com/docs/api/errors.md)
