JavaScript Client Design#
The internal design of the JavaScript client. This page builds on the shared client design and the client specification. Usage is in
the JavaScript guide. Paths are relative to client/js/.
Services and Declarations#
Every service is built at connect from GetServices. The client then has the members of the
server it connects to.
A connect registers the types of every service, then the members of every class, then the services. A member of a class can belong to another service.
Each member is a property set with
defineProperty. A member naming a type the client does not know is left out. An internal procedure is left out too.A kRPC property is a
getXand asetXmethod. A JavaScript setter cannot return aPromise, sovessel.name = "x"would drop the server’s error.A procedure returning an event resolves with an
Event. One returning a stream, such asKRPC.AddStream, rejects with aTypeErrorwhen called, asaddStreammakes that call itself.clientgenandjs.tmplinkrpctoolsgenerate a TypeScript module per service, insrc/services/. Its classes and service are declarations. Its enumerations, structures and exceptions are values, made bydeclareEnumeration,declareStructanddeclareExceptionindeclarations.ts.Each of those calls registers its type in
registry.ts, by service and name.connectuses the registered type where the server’s definition matches, by the rule of the Python client. An enumeration matches on its flags, names and numbers, a structure on its field names in order, and an exception on the JavaScript error it extends. A matched type is also the service’s member, soconn.spaceCenter.SASMode === SpaceCenter.SASMode.The package’s own modules import
declarations.jsby its path, through clientgen’s--client-module. The package’s name resolves toindex.ts, which imports the modules, andtscleaves the import path as written.Connectionmerges with the interfaceConnection extends Services, which holds the services a release ships. A mod’s module adds its service toServiceswith module augmentation.DynamicConnectiontypes any other service asany.RemoteObject,RemoteEnumandRemoteStructtake the type’s name as a type parameter. A property keyed by a symbol that exists in types only holds it, so two classes with the same members do not mix.A procedure with default arguments has two overloads: the positional one, and the required arguments followed by an options object.
The library’s tsconfig.json leaves out the Node.js types. A Node.js built-in used by mistake
then fails the type check, as it would in a browser.
Values#
JavaScript has no operator overloading, so === is identity. The client interns the values a
program compares:
ObjectCacheholds one object per id per connection, as aWeakRef. AFinalizationRegistryremoves the entry of a collected object. An object then works as aMapkey or aSetelement.An
Enumerationholds oneRemoteEnumper number. A flags enumeration also holds each combination it has made, so combinations compare with===too.A structure value is a new object for each result.
equalscompares structures field by field.A structure’s
StructDeclarationholds its field names and the class of its values, and is shared by the connections that match a generated module. TheStructof a connection adds the field types from the server’s definition.An enumeration value of another
Enumerationwith the same service and name passes as an argument by its number.equalscompares two such values by number, as their===is false.
Structures are classes, so a plain object is never a value. A trailing plain object, with the
prototype Object.prototype or null, then holds arguments by name. A protobuf message, such
as a ProcedureCall, is a plain object too, and isMessage tells it apart.
codec.ts encodes values with the BinaryReader and BinaryWriter of
@bufbuild/protobuf. Its 64-bit integers are bigint, so a uint64 above 2^53 round
trips.
Errors#
Each connection builds a class for each exception a service lists, or uses the generated module’s
class where it matches. KRPC.StreamRemovedException is StreamError, in the connection and
the generated module, as the server ends a stream with it. One the server maps to a .NET
exception extends the matching JavaScript error, such as TypeError, and the others extend
ServerError.
A class that extends a JavaScript error also has the service, exception, description
and stackTrace of a ServerError. Its declaration narrows instanceof to the JavaScript
error and ServerErrorDetails.
Deprecated Members#
inheritDeprecation applies the shared rule to the service definitions at connect. The client
warns at the use of a member:
A procedure, method or static method warns when it is called.
A deprecated service, class, enumeration, structure, exception or enumeration value is a getter, which warns when it is read.
A deprecated structure field is a getter on the value. The codec and
equalsread fields throughRemoteStruct.fieldOf, so a value from the server, or one passed to a call, gives no warning.
Deprecations records the warnings a connection has given, so a loop does not repeat one. It
calls process.emitWarning when the runtime has it, and console.warn otherwise. It finds
process through globalThis, as the library has no Node.js types.
The generated modules mark each deprecated member with @deprecated, for editors. Their
deprecated enumeration values and structure fields warn when read too, once per process, as
those values belong to no connection.
Ownership#
connect returns a Connection. Services and objects hold the connection’s state, and none of
them owns it:
const conn = await connect();
const vessel = await conn.spaceCenter.getActiveVessel();
await conn.close();
await vessel.getName(); // Rejects with a ConnectionError
References#
The Connection holds its Session, and a WeakMap in connection.ts maps it to its
Context. The context holds the session, the Types and the service definitions. The session
holds the WebSocket.
The objects the program keeps also hold the context. Each connection builds its own classes, whose methods are closures over the context. A service holds those closures too. Enumeration and structure values hold no connection.
The open socket holds the session through its event listeners. An unclosed connection is therefore never collected.
Lifetime#
The connection closes on
close(), when the server closes the socket or sends adisconnect, or when a message breaks the protocol.close()sends adisconnectand a close frame, then waits up to a second for the server to close the socket. A secondclose()sends nothing.After a close or a failure,
Session.endedholds theConnectionError. Each call waiting for a response rejects with it, and so does each later call. Each stream ends with it, or for a failure with aConnectionErrorwhose cause is that error.Connectionand objects have no finalizer. An object is an id and its connection’s classes, and sends no release to the server.
Event Loop#
The client runs on one thread, like the single-threaded clients, but no call
reads the socket. The socket’s message event reads each message, so several calls can wait at
once, and stream updates arrive between calls:
A call adds its pending slot, keyed by request id, then sends its request.
WebSocket.sendqueues the whole message, so requests never interleave.The message handler holds no
await. No other code runs while it handles a message, and it settles thePromiseof the call the response is for.A response with an unknown id is a protocol error, as no call can abandon its slot. JavaScript has no way to interrupt a call.
The handler passes a
stream_updateto theStreamManager, and skips any message case it does not know. Aconnection_request,connection_responseorrequestis a protocol error.A WebSocket message arrives whole, so a message never stalls and the client has no stall timeout.
setTimeoutbounds the upgrade and the handshake together.
Streams and Events#
streams.ts holds the streams. A StreamState is the state the handles of one stream share,
and the StreamManager holds a connection’s states by id. Stream and Event are the
handles. A copy of a handle is a reference to the same object.
Adding a Stream#
addStream takes a function that returns one call, as C#’s AddStream takes a lambda:
const altitude = await conn.addStream(() => flight.getMeanAltitude());
The client runs the function in a capture mode. A member called then builds its
ProcedureCall, records it and returns aPromisethat never settles, in place of sending the call.addStreamchecks that the function returned thatPromise, from one call.The member warns of its deprecation as it would for a call, so a stream of a deprecated member warns too.
The stream’s value type is the call’s result type, so TypeScript infers
Stream<number>from the function’sPromise<number>.A stream is added on the connection
addStreamis called on, whichever connection the object came from.
A stream’s first update can follow the response to AddStream in the same read. The session’s
call takes a function to run on the result in the message handler, before the next message.
It registers the stream there. A call of a procedure returning an event registers the event’s
stream the same way.
Values and Waits#
The message handler stores each value and wakes the waits, with no await, so a call that
returns sees each value sent before its response. get waits for the first value, and the
value getter reads the latest one at once. wait resolves on the next value after it
starts.
An event counts the true values of its stream as its firings. Each Event keeps the count its
last wait returned for, and a wait returns at once for a later firing. A remove or a close discards
an unseen firing, and an end by the server keeps it.
The client has no conditions profile. A condition holds a stream’s value still while a thread
reads it and waits. A run of reads with no await between them already sees one state, and no
other code runs during it.
Callbacks#
A microtask after the message handler runs the callbacks of the update’s values, then the update callbacks. A callback added in between gets the value through its first call.
A callback runs one call at a time. A callback that returns a
Promiseis busy until it settles. A value that arrives meanwhile waits, and a newer one replaces it.The first call is made before
addCallbackreturns, with the value the stream has. Noawaitlies between reading the value and the call, so no update passes a newer one first.End callbacks of a server ending wait for the value callbacks. A value that arrived before the ending reaches the callbacks first. A remove or a close drops the waiting values, and calls the end callbacks at once.
A remove or a close calls the end callbacks itself. A failure of the connection calls them in a microtask, so the message handler runs no program code.
An error a callback throws is reported, through
reportErrorwhere the runtime has it andconsole.errorotherwise. JavaScript has no kind of error apart from its ordinary ones, so none propagates.
Lifetime of a Stream#
A stream runs until it is removed, or its connection closes. A collected handle leaves its stream on the server, as in the other clients. A collection happens at no predictable time, so a stream kept only for its callbacks would stop at random.
Stream and Event have Symbol.asyncDispose, so an await using declaration removes the
stream at the end of its block. Removing a stream ends it before the RemoveStream call, so a
value that arrives during the call is dropped.
Server Side Functions#
functions.ts adds the server side functions built with the expression API, and
compiler/ compiles a JavaScript function into one.
getCalltakes a function returning one call, asaddStreamdoes, and returns theProcedureCallit captures. It is synchronous, as the capture sends nothing.getCallTemplatetakes a member function itself, such asEngine.prototype.getHasFuel. AWeakMapholds the procedure of each member function the connection builds. A capture would need an object to call the member on, and arguments it cannot encode. The declarations give each class value itsprototype, so TypeScript checks the member’s name.addStreamtakes aKRPC.Expressionin place of a function, andaddEventtakes one too. They callKRPC.AddFunctionStreamandKRPC.AddEvent, which the services leave out as internal. The stream is registered in the message handler, as forAddStream.The function supplies its types.
runandaddStreamread the types of the parameters and the value from theKRPC.Expression, as in the Lua client. They read them once per function, cached in aWeakMapkeyed by the object. TypeScript erases a type argument, sorun<T>andaddStream<T>name a type the client cannot check.A function with parameters has no stream or event, as nothing passes its arguments. The client rejects one with a
TypeErrorbefore calling the server.
Function Compiler#
compile, run, addStream and addEvent take a JavaScript function. The compiler reads
its source with Function.prototype.toString and parses it with acorn.
Captures are an object pattern. JavaScript gives no access to a closure, and a minifier renames local names, so every name a function reads is a capture, a parameter or a builtin global. A minifier keeps the keys of the pattern
({ vessel, limit }), and renames each binding with its uses. Positional captures were ruled out, as a wrong order goes unnoticed.The body is written as it runs on the server. A property is read as a property, and a method returns its value. Calls with
awaitwould also run on the client, but are unreadable at any size.Two stages. The compiler builds a typed tree on the client with no calls, so every
CompilationErroris thrown before anything reaches the server. It then builds the nodes, the children of a node concurrently, so a compile takes about one round trip per level of the tree.The compiler gives the function’s types, so
runreads none from the server. The native tests check them against the server’s.A number is a double, and a
biginta 64-bit integer, so arithmetic gives JavaScript’s results. A server integer is anumberin the client, so keeping integer arithmetic would make7 / 2differ from JavaScript.Type values are values. A parameter type is
types.doubleor a service’s class, checked when the program is written. A type string would be checked only when compiling.Each call compiles again. The captures can differ per call. The parse is cached per function object, in a
WeakMap.The compiler is loaded with
import(). acorn is larger than the rest of the client, and a bundler splits the compiler into its own chunk.A first parameter that is a name the body does not read, such as
_, takes no captures, as Biome’s recommended rules reject the empty pattern{}.A later use types a value with none. An empty array,
SetorMap, anull, and the parameters of a local function take their type from a later use or call. The use notes the type, and the function is compiled again with it, as in Python. A read of a variable holdingnullcompiles asnulluntil then.Numbers in variables are doubles, so a variable assigned an integer and then a fraction keeps JavaScript’s value.
A local function is one Lambda, built at its first call and called with
Invoke. It checks at each call that every path assigns the variables it reads.A for loop with a continue runs its update at the start of the body, on every pass but the first, as the server’s
Continuejumps there. A do…while runs its test there the same way.A catch records which branch matched. Each
e instanceof Xbranch catches its exceptions by name, innermost first, and the branches run after the catches, so an exception from one branch is not caught by the next, as in Python.The body is typed by server forms. Each generated module declares a
Servernamespace, with a synchronous form of the service and each class, and adds them to the package’sServerTypesandClientTypesinterfaces by declaration merging, so mods’ modules join in.OnServermaps a captured value to its server form through the brands ofRemoteObjectandRemoteService, andOnClientmaps a result back.ServerFunction<P, R>carries a compiled function’s types, sorunchecks its arguments.Parameter types are inferred from the tuple of type values, mapped to value types by
ValuesOf. A union of the forms of a type value would also infer from the static methods of a class.Strict comparison with null is an error. The server has one null, and the codec gives it as
null, so=== undefinedwould differ from the client.== nullmatches both.Sets and maps are the server’s, with .NET’s order. Insertion order after a delete would need ordered collections on the server.
A construct the server cannot match is an error, such as a
replaceAllpattern, aMath.log2of a server value or abigintcomparator. A result that differs from JavaScript goes unnoticed.State is a property of a captured object that the function assigns or changes, in place of Python’s
nonlocal, as JavaScript has no access to a closure.
Transports#
WebSockets is the only transport, through the global WebSocket, which Node.js 22 and browsers
both have. Its binaryType is arraybuffer, and a text message ends the connection as
malformed.
Mapping the Spec to JavaScript#
Spec |
JavaScript |
|---|---|
Calls |
A |
Streams, events |
|
Stream error |
|
Callbacks |
Functions called in a microtask after the message handler, one call at a time each |
Scoping construct |
|
Closing a connection |
|
Remote error, and the connection and encoding errors |
|
Server error with no mapped type |
|
Server exception with a mapped type |
A class on the service, extending only |
Argument error |
|
Null object, nullable value |
|
Member names |
lowerCamel, as in |
Named arguments |
A plain object after the positional arguments |
64-bit integers |
|
List, tuple, set, dictionary |
|
Timeouts |
Milliseconds, with |
Static method |
A function on the class, reached through the service of a connection |
Interrupting a call or a wait, hashes |
Unsupported, as JavaScript has neither |
Fatal errors from callbacks |
Unsupported, as JavaScript has no kind of error apart from its ordinary ones |
Conditions |
None. See Values and Waits |
Getting a call as a value |
|
Value type of a server side function |
The function’s own type, read from the server. A null value is |
Flags enumeration |
A |