@sesamy/sdk
v1.40.0
Published
Pure TypeScript SDK for Sesamy API Proxy
Readme
@sesamy/sdk
A pure TypeScript SDK for the Sesamy API Proxy, designed for tree-shaking with separate client and management exports.
Installation
npm install @sesamy/sdk
# or
pnpm add @sesamy/sdkUsage
The SDK is auth-agnostic and accepts a tokenProvider function that returns a complete Authorization header value (e.g., "Bearer token" or "Basic credentials"). This allows integration with any authentication library or method, supporting both Bearer token and Basic authentication schemes.
Importing Types
import { client, management } from '@sesamy/sdk';
import type { User, Profile, Subscription, Entitlement } from '@sesamy/types';Client SDK (End-user operations)
import { client } from '@sesamy/sdk';
// Example with auth0-spa-js
import { Auth0Client } from '@auth0/auth0-spa-js';
const auth0Client = new Auth0Client({
domain: 'your-domain.auth0.com',
client_id: 'your-client-id',
});
const sdkClient = client({
baseUrl: 'https://api-proxy.example.com',
tokenProvider: async () => {
const token = await auth0Client.getTokenSilently();
return `Bearer ${token}`; // Return the full Authorization header
},
vendorId: 'your-vendor-id', // Optional, for multi-tenancy
});
// Use client methods
const profile: Profile = await sdkClient.getProfile('user-id');
const updatedProfile: Profile = await sdkClient.updateProfile('user-id', { name: 'New Name' });
// Generate checkout link
const checkoutUrl = sdkClient.checkouts.generateLink(
{ apiUrl: 'https://api-proxy.example.com' },
{
items: [{ sku: 'premium-monthly' }],
email: '[email protected]',
language: 'en',
redirectUrl: 'https://example.com/success',
}
);
// Generate other links
const accountUrl = sdkClient.links.generateAccountLink(
{ baseUrl: 'https://app.example.com', clientId: 'your-client-id' },
{ language: 'en' }
);
const changePaymentUrl = sdkClient.links.generateChangePaymentLink(
{ baseUrl: 'https://app.example.com', clientId: 'your-client-id' },
{ contractId: 'contract-123', language: 'en' }
);Management SDK (Admin operations)
import { management } from '@sesamy/sdk';
// Example with server-side auth (e.g., auth0-next or next-auth)
const sdkManagement = management({
baseUrl: 'https://api-proxy.example.com',
tokenProvider: async () => {
// Your token retrieval logic here
// e.g., from session, auth0-next, next-auth, etc.
const token = await getTokenFromSession();
return `Bearer ${token}`; // Return the full Authorization header
},
vendorId: 'your-vendor-id',
});
// Use management methods
const users: User[] = await sdkManagement.getUsers({ limit: 10 });
const newUser: User = await sdkManagement.createUser({ email: '[email protected]' });
await sdkManagement.setPassword('user-id', 'new-password');Tree Shaking
Import only what you need to reduce bundle size:
// Only client
import { client } from '@sesamy/sdk';
// Only management
import { management } from '@sesamy/sdk';
// Only specific parts
import client from '@sesamy/sdk/client';
import management from '@sesamy/sdk/management';API Reference
Types
The SDK re-exports TypeScript type definitions from the shared @sesamy/types package:
import type {
User,
Profile,
Address,
Subscription,
Entitlement,
EntitlementType,
Product,
Contract,
Checkout,
Bill,
Transaction,
Fulfillment,
Vendor,
Amendment,
Tally,
PaymentIssue,
UserMetadata,
} from '@sesamy/types';
// SDK-specific types
import type { SDKConfig, ClientSDK, ManagementSDK } from '@sesamy/sdk';Client Methods
getProfile(userId: string): Promise<Profile>- Get user profileupdateProfile(userId: string, data: Partial<Profile>): Promise<Profile>- Update user profile
Checkout Methods
checkouts.generateLink(config, params): string- Generate a checkout link URLcheckouts.create(data): Promise<Checkout>- Create a checkout sessioncheckouts.get(id): Promise<Checkout>- Get checkout session by IDcheckouts.update(id, data): Promise<Checkout>- Update a checkout session
Link Generation Methods
links.generateCheckoutLink(config, params): string- Generate a checkout link URLlinks.generateAccountLink(config, params): string- Generate an account management linklinks.generateChangePaymentLink(config, params): string- Generate a change payment method linklinks.generateChangePlanLink(config, params): string- Generate a change subscription plan linklinks.generateConsumeLink(config, params): string- Generate a content consumption link
Management Methods
getUsers(query?: any): Promise<User[]>- List users with optional filteringcreateUser(data: Partial<User>): Promise<User>- Create a new usergetUser(userId: string): Promise<User>- Get a user by IDupdateUser(userId: string, data: Partial<User>): Promise<User>- Update a userdeleteUser(userId: string): Promise<void>- Delete a usersetPassword(userId: string, password: string): Promise<void>- Set user passwordchangeLoginIdentifier(userId: string, email: string): Promise<void>- Change user login emailsetUserMetadata(userId: string, key: string, value: string): Promise<void>- Set user metadatadeleteUserMetadata(userId: string, key: string): Promise<void>- Delete user metadata
Configuration
baseUrl(required): Base URL for the API proxytokenProvider(required): Async function that returns the full Authorization header value (e.g., "Bearer token", "Basic credentials")vendorId(optional): Vendor ID for multi-tenant setupsonRequestError(optional): Called when a request never completes or ends in a 5xx response, with the URL, method, and either the status or the error fetch threw. Meant for telemetry: the request still rejects with anAPIError, and anything the callback throws is ignored.
Error Handling
The SDK throws errors for API failures. Handle token expiration by refreshing tokens in your tokenProvider:
const sdk = client({
baseUrl: 'https://api-proxy.example.com',
tokenProvider: async () => {
try {
const token = await auth0Client.getTokenSilently();
return `Bearer ${token}`; // Return the full Authorization header
} catch (error) {
// Handle token refresh failure
throw new Error('Authentication failed');
}
},
});Development
Using pnpm filters
From the monorepo root, you can use the sdk filter to run commands specifically for this package:
# Build the SDK
pnpm sdk build
# Production build (includes type definitions)
pnpm sdk build:prod
# Type checking
pnpm sdk type-check
# Development server
pnpm sdk devDirect commands
You can also run commands directly in the package directory:
cd packages/sdk
pnpm build
pnpm build:prod
pnpm type-checkLicense
MIT
