Skip to main content

TypeScript

View as Markdown

RocketRide TypeScript SDK

Build, run, and manage AI pipelines from Node.js or the browser.

npm GitHub Discord MIT License

Quick Start

# NPM
npm install rocketride
# Yarn
yarn add rocketride
# PNPM
pnpm add rocketride
import { RocketRideClient } from 'rocketride';

const client = new RocketRideClient({
auth: process.env.ROCKETRIDE_APIKEY!,
uri: 'https://cloud.rocketride.ai',
});
await client.connect();
const { token } = await client.use({ filepath: './pipeline.pipe' });
const result = await client.send(token, 'Hello, pipeline!', { name: 'input.txt' }, 'text/plain');
console.log(result);
await client.terminate(token);
await client.disconnect();

Don't have a pipeline yet? Visit RocketRide on GitHub or download the extension directly in your IDE.

Install RocketRide extension

What is RocketRide?

RocketRide is an open-source, developer-native AI pipeline platform. It lets you build, debug, and deploy production AI workflows without leaving your IDE - using a visual drag-and-drop canvas or code-first with TypeScript and Python SDKs.

  • 50+ ready-to-use nodes - 13 LLM providers, 8 vector databases, OCR, NER, PII anonymization, and more
  • High-performance C++ engine - production-grade speed and reliability
  • Deploy anywhere - locally, on-premises, or self-hosted with Docker
  • MIT licensed - fully open source, OSI-compliant

You build your .pipe - and you run it against the fastest AI runtime available.

RocketRide visual canvas builder

Features

  • Pipeline execution - Start with use(), send data via send(), sendFiles(), or pipe()
  • Chat - Conversational AI via chat() and Question
  • Event streaming - Real-time events via onEvent and setEvents()
  • File upload - sendFiles() with progress; streaming with pipe()
  • Connection lifecycle - Optional persist mode, reconnection, and callbacks (onConnected, onDisconnected, onConnectError)
  • Full TypeScript support - Complete type definitions
  • Telemetry reporting - The shared loose report() core via rocketride/analytics; each app owns its own event taxonomy (Analytics / Telemetry Reporting)

RocketRideClientConfig

Configuration object passed to new RocketRideClient(config).

Why it matters: The config controls not only where you connect and how you authenticate, but also how the client behaves when the connection drops or when the server is slow to start. Getting persist and the callbacks right avoids confusing "connection lost" vs "never connected" UX.

PropertyTypeRequiredDescription
authstringNoInitial API key. Optional: omit and use env.ROCKETRIDE_APIKEY or pass a credential directly to login() or connect().
uristringNoInitial server URI (e.g. https://cloud.rocketride.ai or ws://localhost:8080). Optional: omit and use env.ROCKETRIDE_URI or the built-in default; attach(), login(), and connect() accept URI overrides.
envRecord<string, string>NoEnvironment override used for ${ROCKETRIDE_*} substitution and credential/URI defaults. If omitted in Node, the SDK copies string values from process.env; it does not load .env files.
persistbooleanNoEnable automatic reconnection with capped linear backoff. Default: false. Retries start at 250ms, increase by 250ms after each failure, and are capped at 15 seconds. An explicit foreground connection action, logout(), or detach() cancels stale scheduled work.
maxRetryTimenumberNoAccepted for backward compatibility but currently ignored. Persistent reconnection has no time limit; stop it explicitly with logout(), detach(), or disconnect().
requestTimeoutnumberNoDefault timeout in ms for each request; overridable per request() call. Prevents a single slow DAP call from hanging indefinitely.
onConnected(info?: string) => Promise<void>NoCalled exactly once for an accepted authenticated connection generation, after authentication and best-effort monitor restoration completes.
onDisconnected(reason?: string, hasError?: boolean) => Promise<void>NoCalled at most once for a generation, and only if that generation previously published onConnected. A failed or cancelled pre-authentication attempt does not call it. Do not call disconnect() here if you want persistent reconnection.
onConnectError(error: ConnectionException) => void | Promise<void>NoCalled for automatic reconnect failures; the next retry waits for this callback. Foreground login() and connect() failures reject their returned promises directly. Authentication failure stops automatic authentication retries.
onEvent(event: DAPMessage) => Promise<void>NoCalled for each server event (e.g. upload progress, task status). Use to drive progress bars or status text; event type is event.event, payload in event.body.
onProtocolMessage(message: string) => voidNoOptional; receives credential-redacted DAP messages for protocol debugging.
onTrace(type: TraceType, message: DAPMessage) => voidNoCalled around high-level SDK requests with a credential-redacted message copy for logging or telemetry.
onDebugMessage(message: string) => voidNoOptional; for debug output.
modulestringNoClient name for logging. Default: CLIENT-0, CLIENT-1, ...

Example - long-lived app with persist and status:

const client = new RocketRideClient({
auth: process.env.ROCKETRIDE_APIKEY!,
uri: 'wss://cloud.rocketride.ai',
persist: true,
requestTimeout: 30000,
onConnected: async () => setStatus('connected'),
onDisconnected: async () => setStatus('disconnected'),
onConnectError: (error) => setStatus('error', error.message),
onEvent: async (e) => handleServerEvent(e),
});

RocketRideClient

Constructor

constructor(config: RocketRideClientConfig = {})

Creates a client instance; it does not open a connection until you call attach(), login(), or connect(). auth and uri are optional at construction; pass per-call overrides to login() or connect(), or a URI override to attach().

Example:

const client = new RocketRideClient({ auth: 'my-key', uri: 'https://cloud.rocketride.ai' });
await client.connect();

Connection

MethodSignatureReturnsDescription
attachattach(uri?: string, options?: { timeout?: number }): Promise<void>Promise<void>Opens an anonymous WebSocket attachment without authenticating. Public rrext_public_* requests are available. A URI override becomes the current endpoint.
detachdetach(): Promise<void>Promise<void>Cancels pending login and reconnect work, closes a CONNECTING or OPEN transport, and leaves the client detached. An in-flight login rejects with cancellation reason detached.
isAttachedisAttached(): booleanbooleanWhether the WebSocket transport is open, regardless of authentication.
loginlogin(credential?: string | { code: string; verifier: string; redirectUri: string }, options?: { uri?: string; timeout?: number }): Promise<ConnectResult>Promise<ConnectResult>Attaches if needed, authenticates, restores monitor subscriptions, and returns account data. The credential and URI may override construction-time values.
logoutlogout(): Promise<void>Promise<void>Clears authentication while retaining an anonymous attachment. During an in-flight login it cancels all joined waiters with reason logout, discards the login transport, and establishes a fresh anonymous attachment instead of depending on deauthentication ordering.
isAuthenticatedisAuthenticated(): booleanbooleanWhether authentication succeeded for the current attachment.
connectconnect(credential?: string | { code: string; verifier: string; redirectUri: string }, options?: { uri?: string; timeout?: number }): Promise<ConnectResult>Promise<ConnectResult>Compatibility method that performs attach and login as one foreground operation.
disconnectdisconnect(): Promise<void>Promise<void>Compatibility method that performs best-effort logout/deauthentication, then cancels pending work and detaches. Call it when the user explicitly disconnects or the app is shutting down.
isConnectedisConnected(): booleanbooleanCompatibility alias for isAttached(); it does not imply authentication.
setEnvsetEnv(env: Record<string, string>): voidvoidReplaces the client's environment map. use()/validate() use it for ROCKETRIDE_* substitution; login() consults ROCKETRIDE_APIKEY when no explicit credential is supplied.

Concurrent foreground login() or connect() calls for the same final WebSocket endpoint and resolved credential join one operation: they share one attachment, one authentication request, and one result. A different foreground login supersedes the earlier operation. A foreground login also supersedes an automatic background reconnect, while background work never supersedes foreground work. Superseded waiters reject with LoginAttemptCancelledError('superseded').

LoginAttemptCancelledError.reason is exactly 'superseded', 'logout', or 'detached'. It is intentionally a plain Error, not a RocketRideException. An unsolicited transport loss during login rejects with ConnectionException instead of a cancellation error. The first terminal cause wins for every caller joined to an operation.

With persist: true, an unexpected loss schedules a generation-owned background reconnect using linear backoff: 250ms, 500ms, 750ms, and so on to a 15-second cap. A successful foreground login resets the delay. Foreground attach(), login(), or connect(), URI changes, logout(), detach(), and disconnect() invalidate stale timers before waiting, so stale callbacks cannot publish state. Authentication failures are not retried automatically. maxRetryTime is accepted for compatibility but ignored.

How to use: For one-off scripts, call connect() once, do your work, then disconnect(). For UIs that need anonymous public calls before sign-in, call attach(), then login(), and use logout() to return to a fresh anonymous attachment. With persist: true, rely on the client to reconnect after unexpected loss; only call detach() or disconnect() when reconnection should stop. The client supports await using (Symbol.asyncDispose) for automatic disconnect when exiting scope.

Low-level DAP

MethodSignatureReturnsDescription
buildRequestbuildRequest(command: string, options?: { token?: string; arguments?: Record<string, unknown>; data?: Uint8Array | string }): DAPMessageDAPMessageBuilds a DAP request message with the next sequence number. Use when you need a custom command not wrapped by use(), send(), etc.
requestrequest(request: DAPMessage, timeout?: number): Promise<DAPMessage>Promise<DAPMessage>Sends the request and returns the response. Pass timeout (ms) to override the config default for this call. Check didFail(response) or response.success before using response.body.
dapRequestdapRequest(command: string, args?: Record<string, unknown>, token?: string, timeout?: number): Promise<DAPMessage>Promise<DAPMessage>Shorthand: builds a request and sends it in one call. Equivalent to buildRequest() + request().
didFaildidFail(response: DAPMessage): booleanbooleanReturns true when the server indicated failure (success === false). Use after request() to decide whether to use body or surface message as an error.

Example - custom DAP command:

const req = client.buildRequest('rrext_monitor', { token, arguments: { types: ['apaevt_status_upload'] } });
const res = await client.request(req, 5000);
if (client.didFail(res)) throw new Error(res.message);

Pipeline execution

MethodSignatureReturnsDescription
useuse(options?: { token?: string; filepath?: string; pipeline?: PipelineConfig; source?: string; threads?: number; useExisting?: boolean; args?: string[]; ttl?: number }): Promise<Record<string, any> & { token: string }>Promise<{ token: string, ... }>Starts a pipeline. You must pass either pipeline (object) or filepath (path to a JSON file; Node only). The client substitutes ${ROCKETRIDE_*} in the config from its configured environment map. Returns at least token; use that token for send(), sendFiles(), pipe(), chat(), getTaskStatus(), and terminate().
validatevalidate(options: { pipeline: PipelineConfig | Record<string, unknown>; source?: string }): Promise<Record<string, unknown>>Promise<Record<string, unknown>>Validates a pipeline configuration without starting it. Returns validation results (e.g. errors, warnings). Use to check pipeline correctness before use().
terminateterminate(token: string): Promise<void>-Stops the pipeline for that token and frees server resources. Call when the user cancels or when you are done sending data.
getTaskStatusgetTaskStatus(token: string, options?: { timeout?: number | false }): Promise<TASK_STATUS>Promise<TASK_STATUS>Returns current task status: e.g. completedCount, totalCount, completed, state, exitCode. Use to poll until completed is true or to show progress.

Why use() returns a token: The server runs each pipeline as a separate task. The token identifies that task so all subsequent operations (sending data, chat, status, terminate) target the right pipeline.

Example - start from file and poll until done:

const { token } = await client.use({ filepath: './pipeline.json', ttl: 3600 });
await client.setEvents(token, ['apaevt_status_processing']);
// ... send data ...
while (true) {
const status = await client.getTaskStatus(token);
if (status.completed) break;
await new Promise((r) => setTimeout(r, 2000));
}
await client.terminate(token);

Data

MethodSignatureReturnsDescription
pipepipe(token: string, objinfo?: Record<string, any>, mimeType?: string, provider?: string): Promise<DataPipe>Promise<DataPipe>Creates a streaming data pipe. Use when you have large payloads or chunks arriving over time; you call open(), then one or more write(), then close(). Default MIME: application/octet-stream.
sendsend(token: string, data: string | Uint8Array, objinfo?: Record<string, any>, mimetype?: string): Promise<PIPELINE_RESULT | undefined>Promise<PIPELINE_RESULT | undefined>Sends data in one shot (internally: open pipe, write once, close). Use for small payloads when you have the full buffer in memory.
sendFilessendFiles(files: Array<{ file: File; objinfo?: Record<string, any>; mimetype?: string }>, token: string): Promise<UPLOAD_RESULT[]>Promise<UPLOAD_RESULT[]>Uploads multiple browser File objects. Results are in the same order as files. Progress is reported via onEvent as apaevt_status_upload events (e.g. body.filepath, body.bytes_sent, body.file_size).

When to use pipe vs send: Use send() when you have a single blob (e.g. a string or one Uint8Array) and don't need to stream. Use pipe() when you are reading a large file in chunks, or when data arrives incrementally (e.g. from a stream or multiple buffers).

Example - send a string:

const result = await client.send(token, 'Hello, pipeline!', { name: 'greeting.txt' }, 'text/plain');

Example - stream chunks with a pipe:

const pipe = await client.pipe(token, { name: 'data.json' }, 'application/json');
await pipe.open();
for (const chunk of chunks) await pipe.write(new TextEncoder().encode(chunk));
const result = await pipe.close();

Store (file access)

Read, write, and manage files in your account's server-side store. All paths are relative to the store root (e.g. 'docs/readme.md'); absolute-like paths (starting with / or \) are rejected. Binary I/O uses an explicit handle lifecycle (fsOpenfsRead / fsWritefsClose, 4 MB chunks); for most cases prefer the string/JSON convenience wrappers.

Handle I/O (low-level binary)

MethodSignatureReturnsDescription
fsOpenfsOpen(path: string, mode?: 'r' | 'w'): Promise<{ handle: string; size?: number }>Promise<{ handle; size? }>Open a handle (mode default 'r'). Read mode also returns size.
fsReadfsRead(handle: string, offset?: number, length?: number): Promise<Uint8Array>Promise<Uint8Array>Read up to length bytes (default 4 MB) from offset. Empty array = EOF.
fsWritefsWrite(handle: string, data: Uint8Array): Promise<number>Promise<number>Write raw bytes to a write handle. Resolves to the number of bytes written.
fsClosefsClose(handle: string, mode: 'r' | 'w'): Promise<void>Promise<void>Close a handle. mode must match the mode passed to fsOpen.

Convenience wrappers (open/read/write/close handled internally)

MethodSignatureReturnsDescription
fsReadStringfsReadString(path: string): Promise<string>Promise<string>Read an entire file as a UTF-8 string.
fsWriteStringfsWriteString(path: string, text: string): Promise<void>Promise<void>Write a UTF-8 string to a file (overwrites).
fsReadJsonfsReadJson<T = any>(path: string): Promise<T>Promise<T>Read and parse a JSON file.
fsWriteJsonfsWriteJson(path: string, obj: any): Promise<void>Promise<void>Serialize an object to JSON and write it.

Directory & metadata

MethodSignatureReturnsDescription
fsListDirfsListDir(path?: string): Promise<{ entries: Array<{ name; type: 'file' | 'dir'; size?; modified? }>; count }>Promise<{ entries; count }>List immediate children (default: store root).
fsStatfsStat(path: string): Promise<{ exists: boolean; type?: 'file' | 'dir'; size?; modified? }>Promise<{ exists; type?; size?; modified? }>File/dir metadata (size/modified for files only).
fsMkdirfsMkdir(path: string): Promise<void>Promise<void>Create a directory.
fsRmdirfsRmdir(path: string, recursive?: boolean): Promise<void>Promise<void>Remove a directory. recursive (default false) deletes contents.
fsRenamefsRename(oldPath: string, newPath: string): Promise<void>Promise<void>Rename or move a file/directory (copy+delete on object stores; recursive for directories).
fsDeletefsDelete(path: string): Promise<void>Promise<void>Delete a file.

Direct URL

MethodSignatureReturnsDescription
fsGetUrlfsGetUrl(path: string, expiresIn?: number, downloadName?: string): Promise<string>Promise<string>Time-limited HTTP(S) URL for direct browser access. Cloud backends (S3/Azure) return a presigned/SAS URL; the local filesystem backend returns a JWT-signed /task/fetch URL. Served inline by default (use as an <img>/<video>/<audio> source). Pass downloadName to force a download with that filename via Content-Disposition: attachment — the only reliable way to set the download filename for cross-origin cloud URLs (where the <a download> attribute is ignored). expiresIn is in seconds (default 3600).
fsReadManyfsReadMany(paths: string[]): Promise<Array<{path, ok, data?, error?}>>Promise<Array>Batch-read many small files in ONE round trip (max 256 paths / 32 MiB total per call) — for many-small-file access patterns where per-file open/read/close is too chatty. Missing/unreadable files are per-entry results (ok: false + error), never a call failure; results come back in request order with data as Uint8Array.

Examples:

// Strings and JSON (wrappers manage the handle for you)
await client.fsWriteString('notes/todo.txt', 'buy milk');
const text = await client.fsReadString('notes/todo.txt');
await client.fsWriteJson('config/app.json', { debug: true });
const cfg = await client.fsReadJson<{ debug: boolean }>('config/app.json');

// Browse and inspect
const { entries } = await client.fsListDir('reports');
for (const e of entries) console.log(e.name, e.type);

// Streaming binary upload via a write handle (4 MB chunks)
const { handle } = await client.fsOpen('uploads/video.mp4', 'w');
try {
const chunkSize = 4 * 1024 * 1024;
for (let offset = 0; offset < file.size; offset += chunkSize) {
const chunk = new Uint8Array(await file.slice(offset, offset + chunkSize).arrayBuffer());
await client.fsWrite(handle, chunk);
}
} finally {
await client.fsClose(handle, 'w');
}

// Inline URL for streaming in a browser (<video>/<img> src)
const streamUrl = await client.fsGetUrl('uploads/video.mp4', 600);

// Force a download with a friendly filename (works cross-origin on S3/Azure too)
const downloadUrl = await client.fsGetUrl('uploads/video.mp4', undefined, 'my video.mp4');

App publish ladder

Typed wrappers over rrext_app_deploy — the publish ladder for RocketRide apps. Publish snapshots an immutable version (never activates anything); Deploy pins a rung (@user, @team/<name>, @org) to a version — first publish, update, promote, and rollback are all this one verb.

MethodSignatureDescription
appPublishappPublish({appId, version, bundle, message?, moduleId?, name?}): Promise<RailEntry>Publish an immutable version to the org registry (single-file remoteEntry.js bundle; commit-style message shows on the version card).
appVersionsappVersions(appId): Promise<RailEntry[]>The version rail, newest first; each entry carries rungs naming the rungs currently pinned to it.
appDeployappDeploy(appId, registryVersion, target): Promise<{deployment, rung}>Pin a rung to a version. Personal deploys resolve into your own manifest immediately.
appWhereappWhere(appId): Promise<Pin[]>The reverse index: {rung, handle, version, appVersion, state, deployedAt} per rung.

Events

MethodSignatureReturnsDescription
setEventssetEvents(token: string, eventTypes: string[], pipeId?: number): Promise<void>-Subscribes this task (or optional pipe) to the given event types (e.g. apaevt_status_upload, apaevt_status_processing). After this, those events are delivered to your onEvent callback. Call after use() and before or while sending data.

Services, validation, and ping

MethodSignatureReturnsDescription
getServicesgetServices(): Promise<Record<string, any>>Promise<Record<string, any>>Returns all service/connector definitions from the server (schemas, UI schemas). Use to discover what pipelines or features the server supports.
getServicegetService(service: string): Promise<Record<string, any> | undefined>Promise<Record<string, any> | undefined>Returns the definition for one service by name. Throws if the request fails.
pingping(token?: string): Promise<void>-Lightweight liveness check. Throws if the server responds with an error. Optional token for task-scoped ping.

Chat

MethodSignatureReturnsDescription
chatchat(options: { token: string; question: Question }): Promise<PIPELINE_RESULT>Promise<PIPELINE_RESULT>Sends the Question to the AI for the given pipeline token and returns the pipeline result. The answer content is in the result body (e.g. fields described by result_types); you can use Answer.parseJson() on raw text if the AI returned JSON.

How it works: The client opens a pipe with MIME type application/rocketride-question, writes the serialized Question, closes the pipe, and returns the server's result. The pipeline must support the chat provider for that token.

Convenience

MethodSignatureReturnsDescription
getConnectionInfogetConnectionInfo(): { connected: boolean; transport: string; uri: string }objectCurrent connection state and URI. Useful for debugging or displaying "Connected to ..." in the UI.
getApiKeygetApiKey(): string | undefinedstring | undefinedThe API key in use (for debugging only; avoid logging in production).

Static

MethodSignatureReturnsDescription
withConnectionRocketRideClient.withConnection<T>(config: RocketRideClientConfig, callback: (client: RocketRideClient) => Promise<T>): Promise<T>Promise<T>Creates a client, calls connect(), runs callback(client), then disconnect() in a finally block. Returns the callback result. Use for one-off scripts so you never forget to disconnect.

DataPipe

Returned by client.pipe(). Represents one streaming upload: open -> one or more write -> close. The server assigns a pipeId when you open; each write() sends a chunk for that pipe, and close() finalizes the stream and returns the pipeline result.

MemberTypeDescription
isOpenedboolean (getter)Whether the pipe has been opened and not yet closed.
pipeIdnumber | undefined (getter)Server-assigned pipe ID; set after open().
MethodSignatureReturnsDescription
openopen(): Promise<DataPipe>Promise<DataPipe>Opens the pipe on the server. Must be called before write().
writewrite(buffer: Uint8Array): Promise<void>-Writes a chunk. Pipe must be open.
closeclose(): Promise<PIPELINE_RESULT | undefined>Promise<PIPELINE_RESULT | undefined>Closes the pipe and returns the processing result. No-op if already closed.

Question

From rocketride. Build a question for client.chat({ token, question }). You can add instructions (how to answer), examples (example input/output), context (background), history (prior messages), and documents (what to reference).

Constructor

constructor(options?: {
type?: QuestionType;
filter?: DocFilter;
expectJson?: boolean;
role?: string;
})

QuestionType: QUESTION, SEMANTIC, KEYWORD, GET, PROMPT. Default type is QUESTION. Default filter and expectJson: false, role: '' if omitted.

Methods

MethodSignatureDescription
addInstructionaddInstruction(title: string, instruction: string): voidAdds an instruction for the AI (e.g. "Answer in bullet points").
addExampleaddExample(given: string, result: string | object | any[]): voidAdds an example input/output so the AI can match format.
addContextaddContext(context: string | object | string[] | object[]): voidAdds context (e.g. "Q4 2024 data").
addHistoryaddHistory(item: QuestionHistory): voidAdds a history item ({ role, content }) for multi-turn chat.
addQuestionaddQuestion(question: string): voidAppends the main question text.
addDocumentsaddDocuments(documents: Doc | Doc[]): voidAdds documents for the AI to reference.
getPromptgetPrompt(hasPreviousJsonFailed?: boolean): stringReturns the full prompt (internal use).

Answer

Used to parse chat response content. The client does not attach an Answer instance to the pipeline result; you read the response body and, if needed, use these static helpers to extract JSON or code from AI text (which often includes markdown or code fences).

MethodSignatureDescription
Answer.parseJsonparseJson(value: string): anyParses JSON from AI text (strips markdown/code blocks).
Answer.parsePythonparsePython(value: string): stringExtracts Python code from a code block in the response.

Types

  • DAPMessage: { type, seq, command?, arguments?, body?, success?, message?, request_seq?, event?, token?, data?, trace? }.
  • TASK_STATUS: Task status with completedCount, totalCount, completed, state, exitCode, and many more fields.
  • PIPELINE_RESULT: { name, path, objectId, result_types?, [key: string]: any }.
  • PipelineConfig: Pipeline definition with name, description, version, components, source, project_id.
  • UPLOAD_RESULT: Per-file result with e.g. action ('complete' | 'error'), filepath, error?, result?, upload_time?.
  • QuestionHistory: { role: string, content: string }.
  • QuestionInstruction: { subtitle: string, instructions: string }.
  • QuestionExample: { given: string, result: string }.

Exceptions

AuthenticationException extends ConnectionException; thrown on DAP auth failure. In persist mode the client calls onConnectError and does not retry authentication so the app can fix credentials and call login() or connect() again.

LoginAttemptCancelledError extends Error directly. Its reason is the LoginAttemptCancellationReason union 'superseded' | 'logout' | 'detached'. Catch it when overlapping lifecycle actions are expected; transport loss and other connection failures remain ConnectionException instances.


Examples (Full API Usage)

1. Minimal: connect, run pipeline from file, send one string, disconnect

import { RocketRideClient } from 'rocketride';

const client = new RocketRideClient({
auth: process.env.ROCKETRIDE_APIKEY!,
uri: 'https://cloud.rocketride.ai',
});
await client.connect();
const { token } = await client.use({ filepath: './pipeline.json' });
const result = await client.send(token, 'Hello, pipeline!', { name: 'input.txt' }, 'text/plain');
console.log(result);
await client.terminate(token);
await client.disconnect();

2. One-off script with automatic disconnect (withConnection)

import { RocketRideClient } from 'rocketride';

const status = await RocketRideClient.withConnection({ auth: 'my-key', uri: 'wss://cloud.rocketride.ai' }, async (client) => {
const { token } = await client.use({ pipeline: { pipeline: myPipelineConfig } });
await client.send(token, JSON.stringify({ data: 1 }));
return await client.getTaskStatus(token);
});
console.log(status);

3. Long-lived app: persist mode, callbacks, and status handling

import { RocketRideClient } from 'rocketride';

const client = new RocketRideClient({
auth: apiKey,
uri: serverUri,
persist: true,
onConnected: async () => updateUI({ state: 'connected' }),
onDisconnected: async (reason, hasError) => updateUI({ state: 'disconnected', reason, hasError }),
onConnectError: (error) => updateUI({ state: 'error', message: error.message }),
onEvent: async (e) => {
if (e.event === 'apaevt_status_upload') updateProgress(e.body);
},
});
await client.connect();
// Later: use(), sendFiles(), etc. If connection drops, client retries; do not call disconnect() in onDisconnected.

4. Upload multiple files and poll until pipeline completes

import { RocketRideClient } from 'rocketride';

const client = new RocketRideClient({ auth, uri, onEvent: async (e) => console.log(e.event, e.body) });
await client.connect();
const { token } = await client.use({ filepath: './vectorize.json' });
await client.setEvents(token, ['apaevt_status_upload', 'apaevt_status_processing']);

const files = [new File([content1], 'a.md'), new File([content2], 'b.md')];
const uploadResults = await client.sendFiles(
files.map((file) => ({ file })),
token
);
console.log('Uploaded:', uploadResults.filter((r) => r.action === 'complete').length);

while (true) {
const status = await client.getTaskStatus(token);
console.log(`Progress: ${status.completedCount}/${status.totalCount}`);
if (status.completed) break;
await new Promise((r) => setTimeout(r, 2000));
}
await client.terminate(token);
await client.disconnect();

5. Streaming large data with a pipe

import { RocketRideClient } from 'rocketride';
import { createReadStream } from 'fs';
import { createInterface } from 'readline';

const client = new RocketRideClient({ auth, uri });
await client.connect();
const { token } = await client.use({ pipeline: { pipeline: config } });

const pipe = await client.pipe(token, { name: 'large.csv' }, 'text/csv');
await pipe.open();
const rl = createInterface({ input: createReadStream('large.csv') });
for await (const line of rl) {
await pipe.write(new TextEncoder().encode(line + '\n'));
}
const result = await pipe.close();
console.log(result);
await client.terminate(token);
await client.disconnect();

6. Chat: question with instructions and examples, parse JSON answer

import { RocketRideClient, Question, Answer } from 'rocketride';

const client = new RocketRideClient({ auth, uri });
await client.connect();
const { token } = await client.use({ pipeline: { pipeline: chatPipelineConfig } });

const question = new Question({ expectJson: true });
question.addInstruction('Format', 'Return a JSON object with keys: summary, keywords.');
question.addExample('Summarize X', { summary: '...', keywords: ['a', 'b'] });
question.addQuestion('Summarize the main points and list keywords.');

const response = await client.chat({ token, question });
const answerText = response?.data?.answer ?? response?.answers?.[0];
const structured = answerText ? Answer.parseJson(answerText) : null;
console.log(structured);

await client.terminate(token);
await client.disconnect();

7. Discover services and send a custom DAP request

import { RocketRideClient } from 'rocketride';

const client = new RocketRideClient({ auth, uri });
await client.connect();

const services = await client.getServices();
console.log('Available:', Object.keys(services));
const ocrSchema = await client.getService('ocr');

const req = client.buildRequest('rrext_ping', { token: myToken });
const res = await client.request(req, 5000);
if (client.didFail(res)) throw new Error(res.message);
await client.disconnect();

License

MIT - see LICENSE.