lokalise-sdk-patterns
Apply production-ready Lokalise SDK patterns for TypeScript and Node.js. Use when implementing Lokalise integrations, refactoring SDK usage, or establishing team coding standards for Lokalise. Trigger with phrases like "lokalise SDK patterns", "lokalise best practices", "lokalise code patterns", "idiomatic lokalise".
What this skill does
# Lokalise SDK Patterns
## Overview
Production-grade patterns for `@lokalise/node-api`: client singleton, cursor pagination, typed error handling, batch operations, upload monitoring, and retry with rate limiting.
## Prerequisites
- `@lokalise/node-api` v12+ installed
- TypeScript 5+ with `strict` mode
## Instructions
1. Create a client singleton to centralize configuration and support branch-based project IDs.
```typescript
// src/lib/lokalise-client.ts
import { LokaliseApi } from "@lokalise/node-api";
let instance: LokaliseApi | null = null;
export function getClient(apiKey?: string): LokaliseApi {
if (instance) return instance;
const key = apiKey ?? process.env.LOKALISE_API_TOKEN;
if (!key) throw new Error("Set LOKALISE_API_TOKEN or pass apiKey");
instance = new LokaliseApi({ apiKey: key, enableCompression: true });
return instance;
}
export function resetClient(): void { instance = null; }
/** Lokalise branch syntax: "projectId:branchName" */
export function projectId(id: string, branch?: string): string {
return branch ? `${id}:${branch}` : id;
}
```
1. Build a cursor-based pagination helper that works with any paginated endpoint.
```typescript
// src/lib/paginate.ts
interface PaginatedResult<T> {
items: T[];
hasNextCursor(): boolean;
nextCursor(): string;
}
type Fetcher<T> = (params: Record<string, unknown>) => Promise<PaginatedResult<T>>;
/** Async generator yielding all items across pages with rate-limit spacing. */
export async function* paginate<T>(
fetcher: Fetcher<T>,
baseParams: Record<string, unknown>,
pageSize = 500
): AsyncGenerator<T, void, undefined> {
let cursor: string | undefined;
let n = 0;
do {
const params = { ...baseParams, limit: pageSize, ...(cursor ? { cursor } : {}) };
if (n++ > 0) await new Promise((r) => setTimeout(r, 170)); // 6 req/sec
const page = await fetcher(params);
for (const item of page.items) yield item;
cursor = page.hasNextCursor() ? page.nextCursor() : undefined;
} while (cursor);
}
/** Collect all pages into an array (use only when dataset fits in memory). */
export async function paginateAll<T>(fetcher: Fetcher<T>, params: Record<string, unknown>): Promise<T[]> {
const out: T[] = [];
for await (const item of paginate(fetcher, params)) out.push(item);
return out;
}
```
Usage:
```typescript
const allKeys = await paginateAll(
(p) => client.keys().list(p),
{ project_id: "123456.abcdef", include_translations: 1 }
);
```
1. Wrap API calls with structured error handling that classifies retryable errors.
```typescript
// src/lib/lokalise-api.ts
export class LokaliseError extends Error {
constructor(
message: string,
public readonly statusCode: number,
public readonly isRetryable: boolean
) {
super(message);
this.name = "LokaliseError";
}
}
export async function apiCall<T>(fn: () => Promise<T>): Promise<T> {
try {
return await fn();
} catch (err: unknown) {
if (err && typeof err === "object" && "code" in err) {
const e = err as { code: number; message: string };
throw new LokaliseError(e.message, e.code, e.code === 429 || e.code >= 500);
}
throw err;
}
}
// Usage
try {
const keys = await apiCall(() => client.keys().list({ project_id: pid, limit: 500 }));
} catch (err) {
if (err instanceof LokaliseError && err.isRetryable) {
console.log("Transient failure, safe to retry");
}
}
```
1. Batch key operations that chunk requests to respect the 500-key-per-request limit.
```typescript
// src/lib/batch.ts
function chunk<T>(arr: T[], size: number): T[][] {
const out: T[][] = [];
for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
return out;
}
/** Create keys in batches of 500 with rate-limit spacing. */
export async function batchCreateKeys(
client: LokaliseApi, projectId: string,
keys: Array<{ key_name: { web: string }; platforms: string[]; tags?: string[];
translations?: Array<{ language_iso: string; translation: string }> }>
): Promise<{ created: number; errors: Error[] }> {
const batches = chunk(keys, 500);
let created = 0;
const errors: Error[] = [];
for (let i = 0; i < batches.length; i++) {
try {
const r = await client.keys().create({ project_id: projectId, keys: batches[i] });
created += r.items.length;
} catch (err) { errors.push(err as Error); }
if (i < batches.length - 1) await new Promise((r) => setTimeout(r, 500));
}
return { created, errors };
}
/** Delete keys in batches of 500. */
export async function batchDeleteKeys(
client: LokaliseApi, projectId: string, keyIds: number[]
): Promise<number> {
const batches = chunk(keyIds, 500);
let deleted = 0;
for (let i = 0; i < batches.length; i++) {
const r = await client.keys().bulk_delete(batches[i], { project_id: projectId });
deleted += r.keys_removed;
if (i < batches.length - 1) await new Promise((r) => setTimeout(r, 500));
}
return deleted;
}
```
1. Upload files with async process monitoring and progress callbacks.
```typescript
// src/lib/upload.ts
import { readFileSync } from "node:fs";
export async function uploadWithProgress(
client: LokaliseApi, projectId: string,
opts: { filePath: string; langIso: string; tags?: string[];
replaceModified?: boolean; cleanupMode?: boolean },
onProgress?: (status: string, elapsedMs: number) => void
): Promise<{ processId: string; status: string; durationMs: number }> {
const data = readFileSync(opts.filePath).toString("base64");
const start = Date.now();
const proc = await client.files().upload(projectId, {
data,
filename: opts.filePath.split("/").pop()!,
lang_iso: opts.langIso,
replace_modified: opts.replaceModified ?? true,
cleanup_mode: opts.cleanupMode ?? false,
detect_icu_plurals: true,
tags: opts.tags,
});
onProgress?.("queued", Date.now() - start);
// Poll process status until terminal state
const maxWait = 120_000; // 2 minutes
let last = proc.status;
while (Date.now() - start < maxWait) {
await new Promise((r) => setTimeout(r, 1500));
const check = await client.queuedProcesses().get(proc.process_id, { project_id: projectId });
if (check.status !== last) { last = check.status; onProgress?.(last, Date.now() - start); }
if (check.status === "finished") return { processId: proc.process_id, status: "finished", durationMs: Date.now() - start };
if (check.status === "cancelled" || check.status === "failed") throw new Error(`Upload ${check.status}: ${JSON.stringify(check.details)}`);
}
throw new Error(`Upload timed out after ${maxWait}ms`);
}
```
Usage:
```typescript
await uploadWithProgress(client, "123456.abcdef", {
filePath: "./src/locales/en.json",
langIso: "en",
tags: ["ci"],
replaceModified: true,
}, (status, ms) => console.log(`[${(ms / 1000).toFixed(1)}s] ${status}`));
```
1. Add a retry decorator with exponential backoff and a rate limiter for sequential calls.
```typescript
// src/lib/retry.ts
/** Retry on 429 and 5xx with exponential backoff + jitter. */
export async function withRetry<T>(
fn: () => Promise<T>,
opts: { maxRetries?: number; baseDelayMs?: number; maxDelayMs?: number;
onRetry?: (attempt: number, err: Error, delayMs: number) => void } = {}
): Promise<T> {
const { maxRetries = 3, baseDelayMs = 1000, maxDelayMs = 10_000, onRetry } = opts;
let lastErr: Error | undefined;
for (let i = 0; i <= maxRetries; i++) {
try { return await fn(); }
catch (err: unknown) {
lastErr = err as Error;
const code = (err as { code?: number })?.code;
if (!(code === 429 || (code && code >= 500)) || i === maxRetries) throw err;
const delay = Math.min(baseDelayMs * 2 ** i + Math.random() * 200, maxDelayMs);
onRetry?.(i + 1, lastErr, delay);
await new Promise((r) => setTimeout(r, delay));
}
}
throw lastErr;
}
/** Enforce minimum spacing between calls (default: 170ms = 6 req/sec). */
export function rateLimited<ARelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.