Skip to content
Longplay
Docs
Browse docs / JavaScript / TypeScript

JavaScript / TypeScript

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

Markdown
API v1Updated

Install#

terminalShell
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.

Related: Install SDKs and CLI

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.

terminalShell
SDK_MODULE_URL="$(curl -fsS https://cdn.longplayai.com/sdk/module)" &&printf 'export * from "%s";\n' "$SDK_MODULE_URL" > longplay-sdk.js
index.htmlHTML
<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.htmlHTML
<link rel="preconnect" href="https://api.longplayai.com" crossorigin><link rel="preconnect" href="https://cdn.longplayai.com" crossorigin>

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.

Related: Complete IAM integration guide

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.tsTypeScript
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
AreaMethods
Customer messaging and installationssendMessage, readMessage
Customers, Guests and SessionsgetOrCreateCustomer, getCustomer, listCustomers, updateCustomer, createCustomerSession, revokeCustomerSessions, createGuestCustomer, resumeGuestSession, claimGuestCustomer
Entitlements and product presentationcheckEntitlement, resolveOffering, resolvePaywall, readHoldings
Balances, usage and ledgerreadBalanceSource, adjustBalance, readUsage, setUsage, manageBalanceGrant, listBalanceGrants, manageUsageEntity, readUsageAnalytics, readCreditAnalytics, submitUsageBatch, readUsageBatch, readLedger, readCreditStatement, quoteBalance, trackUsage, mutateBalance
SeatsreadSeats, manageSeat
Subscriptions and paymentssetupPayment, readPaymentSetup, verifySubscriptions, previewAttach, attach, readSubscriptionOperation, previewUpdate, update, readSubscriptionUpdate, listSubscriptions, listPurchases, listSubscriptionConflicts, retrySubscriptionConflict, manageSubscriptionTrial, readSubscriptionTrial, previewSubscriptionBatch, confirmSubscriptionBatch, readSubscriptionBatch, abandonSubscriptionBatch, recordMerchantEvent
Invoices, refunds and billinglistInvoiceTemplates, previewInvoice, createInvoice, manageInvoice, readInvoiceOperation, listInvoices, getInvoice, previewRefund, refund, readRefund, manageBillingLimits, readBillingInvoice, prepareBillingAdjustment
Coupons, rewards and referralsgrantOffer, grantModelBenefit, readModelBenefit
Feature flags, evaluation and eventsgetFeatures, evaluateFeatures, trackEvents
Native purchasesrestoreNativePurchase
AI pricingreadAiPricing
CLI and CIresolveContent

Server methods by area

  • Customer messaging and installations

    Methods
    sendMessage, readMessage
  • Customers, Guests and Sessions

    Methods
    getOrCreateCustomer, getCustomer, listCustomers, updateCustomer, createCustomerSession, revokeCustomerSessions, createGuestCustomer, resumeGuestSession, claimGuestCustomer
  • Entitlements and product presentation

    Methods
    checkEntitlement, resolveOffering, resolvePaywall, readHoldings
  • Balances, usage and ledger

    Methods
    readBalanceSource, adjustBalance, readUsage, setUsage, manageBalanceGrant, listBalanceGrants, manageUsageEntity, readUsageAnalytics, readCreditAnalytics, submitUsageBatch, readUsageBatch, readLedger, readCreditStatement, quoteBalance, trackUsage, mutateBalance
  • Seats

    Methods
    readSeats, manageSeat
  • Subscriptions and payments

    Methods
    setupPayment, readPaymentSetup, verifySubscriptions, previewAttach, attach, readSubscriptionOperation, previewUpdate, update, readSubscriptionUpdate, listSubscriptions, listPurchases, listSubscriptionConflicts, retrySubscriptionConflict, manageSubscriptionTrial, readSubscriptionTrial, previewSubscriptionBatch, confirmSubscriptionBatch, readSubscriptionBatch, abandonSubscriptionBatch, recordMerchantEvent
  • Invoices, refunds and billing

    Methods
    listInvoiceTemplates, previewInvoice, createInvoice, manageInvoice, readInvoiceOperation, listInvoices, getInvoice, previewRefund, refund, readRefund, manageBillingLimits, readBillingInvoice, prepareBillingAdjustment
  • Coupons, rewards and referrals

    Methods
    grantOffer, grantModelBenefit, readModelBenefit
  • Feature flags, evaluation and events

    Methods
    getFeatures, evaluateFeatures, trackEvents
  • Native purchases

    Methods
    restoreNativePurchase
  • AI pricing

    Methods
    readAiPricing
  • CLI and CI

    Methods
    resolveContent
Client options
OptionDescription
apiKeyServer Key (gg_sk_) from your backend secret store.
scope{ projectId, environment }: the App UUID and sandbox or live, matching the Key.
baseUrlAPI origin; default https://api.longplayai.com. Set https://api.longplayai.com for these examples, without /api/v1.
timeoutMsPer-request timeout, default 10000, maximum 120000.
fetchInject a custom fetch for proxies or offline tests.

Client options

  • apiKey

    Description
    Server Key (gg_sk_) from your backend secret store.
  • scope

    Description
    { projectId, environment }: the App UUID and sandbox or live, matching the Key.
  • baseUrl

    Description
    API origin; default https://api.longplayai.com. Set https://api.longplayai.com for these examples, without /api/v1.
  • timeoutMs

    Description
    Per-request timeout, default 10000, maximum 120000.
  • fetch

    Description
    Inject a custom fetch for proxies or offline tests.

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.

server/session.tsTypeScript
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 methods by area
AreaMethods
Customer messaging and installationspush.sync, push.read, messaging.preference, messaging.setPreference
Customers, Guests and Sessionssession.refresh
Entitlements and product presentationcheckEntitlement, resolveOffering, resolvePaywall, readHoldings
Balances, usage and ledgerreadLedger, readCreditStatement, quoteBalance
Subscriptions and paymentssetupPayment, readPaymentSetup, previewAttach, attach, readSubscriptionOperation, previewUpdate, update, readSubscriptionUpdate
Invoices, refunds and billingreadBillingControls, prepareBillingAuthorization, confirmBillingAuthorization, setBillingCoupons, revokeBillingAuthorization, listBillingInvoices, readBillingInvoice, confirmBillingAdjustment
Coupons, rewards and referralsredeemCoupon, listOffers, claimCoupon, redeemReward, createReferralCode, claimRewardProduct
Feature flags, evaluation and eventsfeatures, track, flush
Native purchasesrestoreNativePurchase
CLI and CIresolveContent

Browser methods by area

  • Customer messaging and installations

    Methods
    push.sync, push.read, messaging.preference, messaging.setPreference
  • Customers, Guests and Sessions

    Methods
    session.refresh
  • Entitlements and product presentation

    Methods
    checkEntitlement, resolveOffering, resolvePaywall, readHoldings
  • Balances, usage and ledger

    Methods
    readLedger, readCreditStatement, quoteBalance
  • Subscriptions and payments

    Methods
    setupPayment, readPaymentSetup, previewAttach, attach, readSubscriptionOperation, previewUpdate, update, readSubscriptionUpdate
  • Invoices, refunds and billing

    Methods
    readBillingControls, prepareBillingAuthorization, confirmBillingAuthorization, setBillingCoupons, revokeBillingAuthorization, listBillingInvoices, readBillingInvoice, confirmBillingAdjustment
  • Coupons, rewards and referrals

    Methods
    redeemCoupon, listOffers, claimCoupon, redeemReward, createReferralCode, claimRewardProduct
  • Feature flags, evaluation and events

    Methods
    features, track, flush
  • Native purchases

    Methods
    restoreNativePurchase
  • CLI and CI

    Methods
    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.

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.tsTypeScript
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.

Funnels, Paywalls and experiments#

Other exports
FunctionEntryPurpose
createFunnelStartClient/serverStart a Funnel Run from your backend and receive a Run Token
createFunnelRunController, showFunnelRunmainDisplay and advance a Run in the browser
createFunnelClientmainStart a Run from a client that holds a Customer Token
createLocalFunnelClient, createConfigurationSyncmain / /serverLocal-mode Funnels and shared public configuration
createFunnelDecisionClient, createFunnelCampaignClient/serverServer decisions, Campaign starts and adoption reports
createFunnelOrchestrationClient, renewFunnelRun/serverSignal a Run, read its results and rotate its Run Token
createPaywallStartClient, createPaywallSession, showPaywall/server / mainStandalone Paywall sessions and display
createFeatureClient, longplay.features()mainFeature evaluation and subscriptions
createPageExperiments/pageURL redirect experiments
createVisualExperiments/visualVisual experiments
createNativeReceiptClient/serverSubmit native store proofs from your backend
createAiUsageMiddleware, createAiPricing/serverAI SDK usage-billing middleware and pricing
createOpenRouterUsageClient, trackOpenRouterUsage/openrouterOpenRouter usage billing

Other exports

  • createFunnelStartClient

    Entry
    /server
    Purpose
    Start a Funnel Run from your backend and receive a Run Token
  • createFunnelRunController, showFunnelRun

    Entry
    main
    Purpose
    Display and advance a Run in the browser
  • createFunnelClient

    Entry
    main
    Purpose
    Start a Run from a client that holds a Customer Token
  • createLocalFunnelClient, createConfigurationSync

    Entry
    main / /server
    Purpose
    Local-mode Funnels and shared public configuration
  • createFunnelDecisionClient, createFunnelCampaignClient

    Entry
    /server
    Purpose
    Server decisions, Campaign starts and adoption reports
  • createFunnelOrchestrationClient, renewFunnelRun

    Entry
    /server
    Purpose
    Signal a Run, read its results and rotate its Run Token
  • createPaywallStartClient, createPaywallSession, showPaywall

    Entry
    /server / main
    Purpose
    Standalone Paywall sessions and display
  • createFeatureClient, longplay.features()

    Entry
    main
    Purpose
    Feature evaluation and subscriptions
  • createPageExperiments

    Entry
    /page
    Purpose
    URL redirect experiments
  • createVisualExperiments

    Entry
    /visual
    Purpose
    Visual experiments
  • createNativeReceiptClient

    Entry
    /server
    Purpose
    Submit native store proofs from your backend
  • createAiUsageMiddleware, createAiPricing

    Entry
    /server
    Purpose
    AI SDK usage-billing middleware and pricing
  • createOpenRouterUsageClient, trackOpenRouterUsage

    Entry
    /openrouter
    Purpose
    OpenRouter usage billing

Related: Run Funnels·Payments, subscriptions and billing·Features, experiments and events

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.

Related: Error codes and recovery