JavaScript and TypeScript SDK
The JavaScript SDK connects your application to the ExecKernel HTTP API. The API executes the graph and keeps the session; the SDK exposes asynchronous operations and a Session object containing the last state and payload it received. Your application turns that payload into controls, messages and the next screen.
This guide develops that connection: where the client belongs, how a choice changes the view, and what to do when the API rejects it. It assumes an existing application, an installed SDK and a reachable API. The JavaScript and TypeScript Quick Start covers the first connection.
Place API access in your application
Section titled “Place API access in your application”For a web application with a service Bearer token, create the SDK client in your Node.js backend. The browser sends the person’s choice to your application; your backend checks which session belongs to that person, obtains the context needed by the graph and calls ExecKernel. It can return a view model containing only the data the interface needs.
This keeps the service credential in server configuration. Using JavaScript does not require placing that credential in a browser bundle. The SDK is an HTTP client: it does not run the PHP engine locally in the browser or in Node.js.
A graph can describe any supported process. To make the integration concrete, we reuse learning-path from Anatomy of a graph. Node 10 offers a guide through edge 101 and browser practice through edge 102. The guide ends at terminal 20; practice ends at terminal 30 and requires practiceEnabled: true in the context. The API must already publish that graph; HTTP API integration explains the API side.
const { ExecKernelClient } = require('@execkernel/sdk');
const client = new ExecKernelClient({ baseUrl: process.env.EXECKERNEL_BASE_URL, apiKey: process.env.EXECKERNEL_API_TOKEN, flowId: 'learning-path', lang: 'en',});baseUrl is the service root; the SDK appends its endpoint paths. apiKey supplies the Bearer token. flowId is the graph identifier, while lang selects the graph’s presentation language. Creating the client does not create a session. The complete program below checks the required environment variables before constructing it.
Start a session and prepare the choices
Section titled “Start a session and prepare the choices”Starting returns a Session after the API has answered. Here, your application has established that practice is unavailable:
const session = await client.startSession({ practiceEnabled: false });const sessionId = session.sessionId;if (!sessionId) throw new Error('Missing session identifier.');Save sessionId with the application record that owns this execution. It identifies the remote session in later requests. The Session object is the SDK’s current local representation of that execution.
Its currentPayload contains the presentation data. For an ordinary node, the SDK exposes type: 'node', a nodeId and an edges array. The following projection creates application data for a selection screen:
const { isNodePayload } = require('@execkernel/sdk');
const payload = session.currentPayload;if (!isNodePayload(payload)) throw new Error('Expected choices.');
const view = { kind: 'choices', heading: payload.title ?? '', choices: payload.edges.map(edge => ({ edgeId: edge.id, label: edge.label ?? String(edge.id), enabled: edge.enabled !== false, availability: edge.availability ?? null, reason: edge.disabledReason ?? null, })),};isNodePayload() checks that the value has a node payload’s shape. The SDK has already normalized the HTTP presentation fields: edge.label is the selected label and disabledReason uses the JavaScript field name. Your application creates its own objects instead of modifying the session’s read-only data.
With this graph and context, the heading is “How would you like to learn?”. “Read the guide” is available; “Practise in the browser” is disabled with availability: 'blocked' and reason context_value_failed. Your interface can disable the second control and translate the reason into suitable wording.
Availability describes the presented choice. Under policies that expose pending, an enabled control can still await validation when selected. Keep that distinction in your view model when it matters; the API makes the decision when it receives the choice.
Await a choice, then replace the view
Section titled “Await a choice, then replace the view”The interface submits an edge’s integer ID. In a backend request, obtain that ID from the selected control, check the request and use the session associated with the authenticated application record. Selecting the guide looks like this:
const result = await session.selectEdge(101);The method sends the selection to the API. After a successful, valid response, it replaces the session’s local state and payload and returns the new payload. result and session.currentPayload now describe the same result.
The optional second argument supplies context updates. Those values should come from facts your backend has checked. For example, sending { practiceEnabled: true } changes a condition’s input; it is not a permission that an unchecked browser field should grant itself. Builders, payloads and session snapshots explains the accepted input shapes.
While the promise is pending, your interface should show that the choice is being submitted and prevent another submission for that session. Await operations in order. The SDK rejects overlapping operations on the same session through its client; that guard does not coordinate separate clients or application processes.
The guide response is terminal. A terminal payload contains outputs rather than further edges:
const { isTerminalPayload } = require('@execkernel/sdk');
if (isTerminalPayload(result)) { const view = { kind: 'result', heading: result.title ?? '', messages: result.outputs.flatMap(output => output.type === 'content' && typeof output.content === 'string' ? [output.content] : []), links: result.outputs.flatMap(output => (output.type === 'url' || output.type === 'redirect') && typeof output.url === 'string' ? [{ kind: output.type, label: output.label ?? output.url, url: output.url }] : []), };}Your application can replace the selection form with “Guide selected”, the message “Read the guide at your own pace.” and an “Open the guide” link. Returning a redirect output also gives your application data to act on; the SDK does not navigate the browser. Apply your application’s destination rules when presenting links or navigating. The graph’s example.org URLs are illustrative destinations.
Keep a rejected choice understandable
Section titled “Keep a rejected choice understandable”The API can reject a submitted choice even if the request reached it correctly. In the standalone API, submitting the blocked practice edge in this example returns HTTP 403 with code EK-RULE-403. The SDK rejects the promise with an ExecKernelError.
The application service in the complete example handles that known case by retrieving the current payload and returning a rejected result with the refreshed view. This is its choose() method; this.session and this.client are application-owned fields:
async choose(edgeId, context = {}) { if (!this.session || !this.sessionId) throw new Error('Start or resume first.'); try { await this.session.selectEdge(edgeId, context); return { accepted: true, view: this.view }; } catch (error) { if (!(error instanceof ExecKernelError) || error.ekCode !== 'EK-RULE-403') { throw error; } const view = await this.resume(this.sessionId); return { accepted: false, code: error.ekCode, view }; }}The interface can explain that the choice is unavailable while continuing to display the options at node 10. It should use its own user-facing wording for the returned code. The service does not repeat the rejected selection.
This handling is specific to a known API rejection. A lost connection or an invalid response leaves a different question: did the API apply the operation? The SDK keeps the last accepted local representation, but that does not establish the backend’s position. Use client.status(sessionId) to inspect it and retrieve its payload when appropriate before deciding on another write. Client errors, transport and diagnostics develops that recovery. The JavaScript transport has no built-in retry loop or request deadline.
This is an illustration of views your application can build from the returned data, not a built-in SDK interface. Rejection and success are alternative outcomes of a submission.
Resume in a later request
Section titled “Resume in a later request”A later backend request can construct a client with the same API configuration and pass the saved session ID to restoreSession():
const resumed = await client.restoreSession(sessionId);const currentView = toView(resumed.currentPayload);toView() is the application’s projection function in the complete example below. After choosing the guide, currentView describes terminal 20. The API must still retain the session and allow it to resume.
Passing an ID makes a request to the API. Passing a saved snapshot containing state or payload instead hydrates a local representation without that request. These are different uses of the same method; session snapshots explains when each is useful.
The complete SessionService class below holds one local Session. Create an instance for each application-owned session; do not share that mutable holder among different people. To survive process restarts or move between workers, save the ID with your application record and resume it in the appropriate request. Keeping a JavaScript object alive is not the API’s persistence mechanism.
Use types and events without changing the operations
Section titled “Use types and events without changing the operations”The package includes the SDK’s TypeScript declarations. Payload is the union of node and terminal payloads; DeepReadonly describes the data a session exposes. Type guards narrow that union while checking the value:
import { isNodePayload, type DeepReadonly, type Payload } from '@execkernel/sdk';
function choiceLabels(payload: DeepReadonly<Payload> | null): string[] { if (!isNodePayload(payload)) return []; return payload.edges.map(edge => edge.label ?? String(edge.id));}Within the guarded branch, TypeScript permits edges. For a terminal branch, use isTerminalPayload() or the type discriminator to access outputs. Build a mutable view model of your own when a framework needs one. A type assertion does not make an arbitrary response into a valid SDK payload.
The complete TypeScript version also declares a View union for the application’s choices and result screens, and a ChoiceResult union for accepted and rejected selections. It compiles with --strict against the package’s declarations, using the same operations as the JavaScript version. Type checking verifies the SDK contract; it does not prove that a graph allows a choice or that the API accepts a context value.
You can observe node and terminal payloads through session:node and session:terminal events. For example:
const stopObserving = client.on('session:terminal', payload => { if (isTerminalPayload(payload)) { console.info('Terminal reached:', payload.nodeId); }});
// When the part of your application that registered the observer is disposed:stopObserving();on() returns the unsubscribe function. Restoring a snapshot locally can also emit a payload event, so an event alone does not establish that the API was contacted. These observers are best-effort: their exceptions or rejected promises do not change the operation’s outcome. Keep essential view updates and error handling on the awaited operation; use observers for secondary reactions. Diagnostic events and their data are covered in Client errors, transport and diagnostics.
Complete application service
Section titled “Complete application service”The JavaScript service and demonstration contains toView() and SessionService as application code. You can import them into your backend. Its executable demonstration starts with practice unavailable, deliberately submits that disabled choice to show recovery, selects the guide, resumes the session and finally deletes its own demonstration session.
With the SDK and API connection variables already configured, run:
node js-session-service.cjsThe output’s initial and rejected.view contain the choices at node 10. rejected.accepted is false with EK-RULE-403. Both selected.view and resumed show the guide result at node 20. A real request obtains the edge ID from the person’s selection instead of following the demonstration’s fixed sequence.
Complete JavaScript service and demonstration
'use strict';
const { ExecKernelClient, ExecKernelError, isNodePayload, isTerminalPayload,} = require('@execkernel/sdk');
function toView(payload) { if (isNodePayload(payload)) { return { kind: 'choices', nodeId: payload.nodeId, heading: payload.title ?? '', description: payload.description ?? '', choices: payload.edges.map(edge => ({ edgeId: edge.id, label: edge.label ?? String(edge.id), enabled: edge.enabled !== false, availability: edge.availability ?? null, reason: edge.disabledReason ?? null, })), }; } if (isTerminalPayload(payload)) { return { kind: 'result', nodeId: payload.nodeId, heading: payload.title ?? '', messages: payload.outputs.flatMap(output => output.type === 'content' && typeof output.content === 'string' ? [output.content] : []), links: payload.outputs.flatMap(output => (output.type === 'url' || output.type === 'redirect') && typeof output.url === 'string' ? [{ kind: output.type, label: output.label ?? output.url, url: output.url }] : []), }; } throw new Error('No displayable session payload.');}
// Application code: create one instance for one application-owned session.class SessionService { constructor(client) { this.client = client; this.session = null; }
get sessionId() { return this.session?.sessionId ?? null; }
get view() { return toView(this.session?.currentPayload ?? null); }
async start(context) { this.session = await this.client.startSession(context); return this.view; }
async resume(sessionId) { this.session = await this.client.restoreSession(sessionId); return this.view; }
async choose(edgeId, context = {}) { if (!this.session || !this.sessionId) throw new Error('Start or resume first.'); try { await this.session.selectEdge(edgeId, context); return { accepted: true, view: this.view }; } catch (error) { if (!(error instanceof ExecKernelError) || error.ekCode !== 'EK-RULE-403') { throw error; } // A known rejection: refresh the view; do not repeat the rejected choice. const view = await this.resume(this.sessionId); return { accepted: false, code: error.ekCode, view }; } }}
async function main() { const baseUrl = process.env.EXECKERNEL_BASE_URL; const apiKey = process.env.EXECKERNEL_API_TOKEN; if (!baseUrl || !apiKey) { throw new Error('Set EXECKERNEL_BASE_URL and EXECKERNEL_API_TOKEN.'); } const client = new ExecKernelClient({ baseUrl, apiKey, flowId: process.env.EXECKERNEL_GRAPH_CODE || 'learning-path', lang: process.env.EXECKERNEL_LANG || 'en', }); const service = new SessionService(client); try { const initial = await service.start({ practiceEnabled: false }); // Deliberately submit a disabled choice to demonstrate rejection recovery. const rejected = await service.choose(102); const selected = await service.choose(101); const sessionId = service.sessionId; if (!sessionId) throw new Error('Missing session identifier.'); const resumed = await service.resume(sessionId); console.log(JSON.stringify({ initial, rejected, selected, resumed }, null, 2)); } finally { // Cleanup belongs to this demonstration, not to the reusable service. if (service.sessionId) await client.destroy(service.sessionId); }}
module.exports = { toView, SessionService };
if (require.main === module) { main().catch(error => { console.error(error instanceof ExecKernelError ? error.ekCode : error instanceof Error ? error.message : 'Unexpected failure.'); process.exitCode = 1; });}The complete TypeScript version adds application view types without replacing the SDK’s declarations. In a project with TypeScript and Node.js declarations already configured, this standalone compilation uses the .cts file’s CommonJS format:
npx tsc js-session-service.cts --strict --target ES2022 --module NodeNext --moduleResolution NodeNext --lib ES2022,DOM --outDir buildnode build/js-session-service.cjsIn an existing application, use your project’s module settings and build process. The service’s public operations stay the same: start a session, resume its current payload, or submit a choice and use the returned view.