15 Commits

Author SHA1 Message Date
Mavis fc766357dc chore: remove stray commit msg scratch file 2026-06-03 10:52:07 +00:00
Mavis 1d5b6a9f93 fix: use sub-message decoding for Error fields (not raw bytes)
The kRPC proto defines error on Response and ProcedureResult as
type Error (a sub-message), not raw bytes. The schema already
declared it that way, so protobufjs was decoding the error as
a nested Error object automatically.

But our client code was treating response.error as if it were
a Uint8Array of raw bytes (matching the wrong type annotation
we had earlier), and we were trying to decode those bytes as
a second Error message. That double-decode was the source of
the "RPC error: .:" with stray substitute character and the
"index out of range" errors when the bytes happened to look
like other protobuf structures.

Fix: use the auto-decoded error object directly. response.error
is now { service, name, description, stackTrace } when set,
and we just read those fields.

This should also let the actual response values decode correctly,
since we were previously mangling the error path.
2026-06-03 10:51:58 +00:00
Mavis 273dcd1408 debug: log raw response bytes for failed RPC calls 2026-06-03 10:23:02 +00:00
Mavis 639d265278 fix: decode error bytes as Error protobuf (not as a pre-decoded object)
The kRPC Response and ProcedureResult messages use `bytes` for
their `error` fields — a serialized Error sub-message, not a
pre-decoded object. We were treating them as already-decoded,
which produced 'RPC error: .:`\u2426' (empty service.name.description
with a stray substitute character) and triggered 'invalid wire
type 4 / 7' errors when the bytes happened to look like other
protobuf structures.

Same bug existed in three places:
1. invoke() - top-level Response.error and per-call results[i].error
2. addStream() - results[i].error
3. readStreamLoop() - StreamResult.result.error

Fix: when an error field is set and non-empty, decode the bytes
as a kRPC.Error message to get service/name/description/stackTrace.
If the inner decode fails, fall back to a hex dump so we still
see something useful in the logs.

Stream errors are logged as warnings and produce empty values
so the stream loop keeps running for the other streams.
2026-06-03 00:15:00 +00:00
Mavis e9ebbf17d2 fix: translate PascalCase procedure names to .NET getter/setter convention
The kRPC server (a C# application) exposes C# properties using
.NET accessor naming: a property `UT` on the SpaceCenter service
becomes two procedures named `get_UT` and `set_UT`. A class
property `CelestialBody.Name` becomes `CelestialBody.get_Name`
and `CelestialBody.set_Name`.

We had been calling `SpaceCenter.GetUT()` (PascalCase, no
underscore) and looking up the literal key. That key never
matched, so the cache always returned 'procedure not found' —
even though `get_UT` was sitting right there.

The Python client side-steps this by using snake_case for
everything (`SpaceCenter.ut` -> `SpaceCenter.get_UT`), and
the C# client just uses .NET convention directly. Our
TypeScript/extract code uses the more familiar PascalCase
form, so the cache lookup now does the translation.

The translation is purely a fallback path:
- exact match tried first
- if not found and the name starts with Get/Set, the
  .NET-style `get_X`/`set_X` variant is tried
- works for both top-level ("GetUT") and class-prefixed
  ("CelestialBody.GetName") procedure names

This unblocks the real bridge: `SpaceCenter.GetUT`,
`SpaceCenter.GetActiveVessel`, `SpaceCenter.GetBodies`,
`SpaceCenter.GetVessels`, and all the class methods like
`CelestialBody.GetName`, `Vessel.GetType`, `Orbit.GetApoapsis`
should now resolve to actual kRPC procedures.
2026-06-03 00:11:39 +00:00
Mavis ee75d0b6c9 debug: probe specifically for GetUT in SpaceCenter 2026-06-03 00:05:08 +00:00
Mavis 916222f4f4 debug: log SpaceCenter procedure names during ServiceCache build 2026-06-03 00:02:37 +00:00
Mavis 62e7ed0a77 fix: handle null returnType in decodeKrpcType (the actual root cause!)
The stack trace finally showed the truth: the error was in our
own decodeKrpcType, not in protobufjs. The kRPC server omits
the `return_type` field for procedures that have no return value
(e.g. AddStream, RemoveStream, all the setters). protobufjs
decodes missing message fields as null. Our cache then called
`decodeKrpcType(null)`, which did `null.code` and threw.

The null.code error message was a red herring all along — it
looked like protobufjs was looking up an enum descriptor, but it
was actually just our code accessing .code on a null parameter.

The protobufjs fixes (uint32 instead of nested-enum, adding the
game_scenes field) were real and needed — but they weren't the
cause of THIS particular failure mode.

Fix:
- decodeKrpcType accepts null/undefined and returns a NONE type
  (code 0) in that case
- Added a regression test in services.test.ts that builds a fake
  ServiceCache with a procedure whose returnType is null
2026-06-02 23:56:32 +00:00
Mavis 2b0573d328 fix: add missing Procedure.game_scenes field (field 6, repeated GameScene enum)
The kRPC server's GetServices response includes a `game_scenes`
field on every Procedure message — a repeated GameScene enum
describing which KSP scene the procedure is available in
(SPACE_CENTER, FLIGHT, EDITOR_VAB, etc.). My schema was missing
field 6 entirely, and the field type is a nested enum which hits
the same protobufjs bug we've been chasing.

This is the actual cause of the 'Cannot read properties of null
(reading code)' error that has been blocking the bridge. The
decoder was trying to resolve the GameScene nested-enum
descriptor and throwing.

Fix: add field 6 as repeated uint32 (same nested-enum workaround
as Type.code and ConnectionResponse.status), with the enum values
kept as a nested GameScene for documentation/lookup.

After this fix, the GetServices response should decode cleanly
and the bridge should connect to real KSP.
2026-06-02 23:53:16 +00:00
Mavis b1b78a06a3 fix: Type.code nested-enum bug blocks GetServices decode
The real root cause of the 'Cannot read properties of null (reading code)'
error was hiding in two places, not one. The first (ConnectionResponse
status) was fixed in the previous commit. This commit fixes the second:

The KRPC.Type message has a 'code' field of nested-enum type
'Type.TypeCode'. When protobufjs decodes a GetServices response
(which contains MANY Type messages inside Procedure.returnType
fields), it hits the same nested-enum default-value lookup bug
and throws the TypeError.

The fix is identical to the ConnectionResponse.status fix:
change the field type from the nested-enum reference to plain
'uint32'. The wire format is the same (varint), and our code in
services.ts reads raw integers from the typecode field anyway.

This error was happening OUTSIDE my top-level try/catch in
client.connect() — it was in loadServices, called from
adapter.connect(). The bridge's catch caught it, but the error
message was the raw 'Cannot read properties of null (reading code)'
because loadServices didn't wrap the error.

Now:
- The schema fix makes the decode actually succeed
- The adapter wraps any remaining loadServices errors with a
  clear 'kRPC loadServices (GetServices decode) failed:' prefix
  so the next failure mode is immediately actionable
2026-06-02 23:47:13 +00:00
Mavis a6ba6e6583 fix: top-level try/catch around connect() with stack trace
The schema fix to use uint32 for status was the right call, but
the error persists. The fact that the raw bytes are being printed
means the new code IS running, but the error must be coming from
somewhere outside the inline try/catch blocks. Wrapping the whole
connect() in a safety net so we'll see a stack trace on the next
run and can pinpoint the exact line.
2026-06-02 23:38:16 +00:00
Mavis dea84b65bb fix: use uint32 instead of nested-enum type for ConnectionResponse.status
This is the actual root cause of the Windows handshake failure.

The kRPC server sends a minimal ConnectionResponse that omits the
default-value `status` and `message` fields, leaving only the
`clientIdentifier`. Our schema declared the status field as
`type: 'ConnectionResponse.Status'` (a nested enum reference).
When protobufjs decodes the response and the field is absent, it
tries to look up the default value from the nested-enum type
descriptor — but the descriptor resolves to null somewhere in
protobufjs 7.6, and the next thing the code does is
`someDescriptor.code` to look up the default enum value. That
throws the TypeError: 'Cannot read properties of null (reading code)'.

The wire format is identical: status is just a varint. So we model
it as 'uint32' and our code already does `resp.status !== 0`
which works for the happy path (0 = OK). The redundant `!== 'OK'`
check is kept for forward compat — if anyone ever flips the schema
back to nested-enum and protobufjs fixes the bug, the string check
would still work.

Same fix applied to ProcedureResult.error (uses 'Error' which is
the actual top-level Error type, not a nested-enum type).

The raw-bytes diagnostic from the previous commit showed both
handshakes returning 18 bytes:
  1a 10 <16 bytes>
which is just field 3 (clientIdentifier), confirming the server is
sending minimal responses. Decoding those 18 bytes as
ConnectionResponse with the old schema triggered the bug; with
uint32 status, it decodes cleanly to {status: 0, message: "",
clientIdentifier: <16 bytes>}, the handshake succeeds, and the
bridge connects to real KSP.
2026-06-02 23:33:01 +00:00
Mavis 25dd42503b fix: wrap stream handshake decode in try/catch + raw-bytes diagnostic
The original fix only wrapped the RPC handshake decode. The user's
symptom is the same error after the RPC handshake succeeds (the kRPC
server registers the client on the RPC side), so the failure must
be in the stream handshake.

Added:
- try/catch around the stream decode (matching the RPC decode)
- KRPC_DEBUG env var that dumps raw bytes from both handshakes
  to the console. Set it to 1 when running the bridge to see
  exactly what kRPC is sending:

    KRPC_DEBUG=1 pnpm start

  Output will include lines like:
    [krpc-client] rpc handshake raw response (17 bytes): 08001200...
    [krpc-client] stream handshake raw response (4 bytes): 08001200
2026-06-02 23:29:04 +00:00
Mavis 7c46bc0408 fix: remove stray brace in config log 2026-06-02 23:22:29 +00:00
Mavis c4b631c4c4 fix: add BUILD_TAG to bridge so we can verify which code is running
If you see [v2-debug] in the log, you're on the new code. If
you don't, you're still on main and the old error handler is
hiding the real error.

Also hardened the fatal catch handler to never crash on weird
error values.
2026-06-02 23:20:20 +00:00
7 changed files with 312 additions and 25 deletions
+34 -4
View File
@@ -46,8 +46,10 @@ function err(msg: string): void {
console.error(`[ksp-bridge] ${msg}`);
}
const BUILD_TAG = 'v2-debug';
async function main(): Promise<void> {
log(`config: api=${API_URL} host=${HOST}:${RPC_PORT} poll=${POLL_MS}ms`);
log(`config: api=${API_URL} host=${HOST}:${RPC_PORT} poll=${POLL_MS}ms [${BUILD_TAG}]`);
// First, try to connect to a real kRPC server. If it works, run
// the real extract loop. If it fails, fall back to mock mode.
@@ -60,8 +62,28 @@ async function main(): Promise<void> {
await adapter.connect();
log(`connected to kRPC at ${HOST}:${RPC_PORT} — running with real KSP state`);
} catch (e) {
const msg = e === null ? 'null' : e instanceof Error ? e.message : String(e);
log(`no kRPC server at ${HOST}:${RPC_PORT}: ${msg}`);
// Hardened error formatter: handles null, undefined, Error,
// strings, and arbitrary objects. Never crashes the formatter
// itself, so we always see *something*.
let msg: string;
if (e === null) {
msg = 'null';
} else if (e === undefined) {
msg = 'undefined';
} else if (typeof e === 'string') {
msg = e;
} else if (e instanceof Error) {
msg = e.message;
} else if (typeof e === 'object') {
try {
msg = JSON.stringify(e);
} catch {
msg = String(e);
}
} else {
msg = String(e);
}
log(`[${BUILD_TAG}] no kRPC server at ${HOST}:${RPC_PORT}: ${msg}`);
log('Falling back to MOCK mode (synthetic state).');
return runMock();
}
@@ -165,6 +187,14 @@ function mockState(ut: number): ExtractedState {
}
main().catch((e) => {
err(`fatal: ${e}`);
let msg: string;
if (e === null) msg = 'null';
else if (e === undefined) msg = 'undefined';
else if (e instanceof Error) msg = `${e.message} (stack: ${e.stack ?? 'n/a'})`;
else if (typeof e === 'string') msg = e;
else if (typeof e === 'object') {
try { msg = JSON.stringify(e); } catch { msg = String(e); }
} else msg = String(e);
err(`fatal: ${msg}`);
process.exit(1);
});
+14 -2
View File
@@ -64,8 +64,20 @@ export class KRPCAdapter {
return;
}
await this.client.connect();
const loaded = await loadServices(this.client);
this.services = loaded.services;
try {
const loaded = await loadServices(this.client);
this.services = loaded.services;
} catch (e) {
// loadServices calls client.invoke, which decodes the
// KRPC.GetServices response (a HUGE KRPC.Services message).
// If anything goes wrong decoding that, surface a clear
// error instead of the buried protobufjs TypeError.
const msg = e instanceof Error ? e.message : String(e);
const stack = e instanceof Error ? e.stack : '';
// eslint-disable-next-line no-console
console.error('[ksp-bridge] loadServices stack:', stack);
throw new Error(`kRPC loadServices (GetServices decode) failed: ${msg}`);
}
}
async disconnect(): Promise<void> {
+82 -13
View File
@@ -84,6 +84,19 @@ export class KRPCClient {
}
async connect(): Promise<void> {
// Wrap EVERYTHING in a top-level try so we always get a clean
// error message (not a buried TypeError from protobufjs
// nested-enum resolution). The specific sub-step failures are
// caught inline for nicer messages, but this top-level guard
// is the safety net.
try {
return await this._connectImpl();
} catch (e) {
throw new Error(`kRPC connect failed at unknown step: ${formatErr(e)} (stack: ${e instanceof Error ? e.stack : 'n/a'})`);
}
}
private async _connectImpl(): Promise<void> {
// RPC handshake
try {
this.rpcSocket = await tcpConnect(
@@ -106,11 +119,19 @@ export class KRPCClient {
});
let resp: { status: number | string; message: string; clientIdentifier: Uint8Array };
try {
const rpcRaw = await recvRawMessage(this.rpcSocket);
if (process.env.KRPC_DEBUG) {
// eslint-disable-next-line no-console
console.log(
'[krpc-client] rpc handshake raw response (' + rpcRaw.length + ' bytes):',
Buffer.from(rpcRaw).toString('hex'),
);
}
resp = decodeMessage<{
status: number | string;
message: string;
clientIdentifier: Uint8Array;
}>(KRPC.ConnectionResponse, await recvRawMessage(this.rpcSocket));
}>(KRPC.ConnectionResponse, rpcRaw);
} catch (e) {
throw new Error(`kRPC RPC handshake (response decode) failed: ${formatErr(e)}`);
}
@@ -136,10 +157,26 @@ export class KRPCClient {
type: 1, // STREAM
clientIdentifier: this.clientIdentifier,
});
const streamResp = decodeMessage<{ status: number | string; message: string }>(
KRPC.ConnectionResponse,
await recvRawMessage(this.streamSocket),
);
let streamResp: { status: number | string; message: string };
try {
const streamRaw = await recvRawMessage(this.streamSocket);
// Diagnostic: log the raw bytes for the stream handshake response
// so we can see what the kRPC server actually sent. Useful when
// debugging "Cannot read properties of null" type errors.
if (process.env.KRPC_DEBUG) {
// eslint-disable-next-line no-console
console.log(
'[krpc-client] stream handshake raw response (' + streamRaw.length + ' bytes):',
Buffer.from(streamRaw).toString('hex'),
);
}
streamResp = decodeMessage<{ status: number | string; message: string }>(
KRPC.ConnectionResponse,
streamRaw,
);
} catch (e) {
throw new Error(`kRPC Stream handshake (response decode) failed: ${formatErr(e)}`);
}
if (streamResp.status !== 'OK' && streamResp.status !== 0) {
throw new Error(`Stream handshake failed: ${streamResp.status} ${streamResp.message}`);
}
@@ -149,7 +186,7 @@ export class KRPCClient {
// eslint-disable-next-line no-console
console.error('[krpc-client] stream loop error:', err);
});
}
} // end _connectImpl
isConnected(): boolean {
return this.rpcSocket !== null && this.streamSocket !== null && !this.closed;
@@ -188,16 +225,28 @@ export class KRPCClient {
}
sendMessage(this.rpcSocket, KRPC.Request, { calls: [call] });
const raw = await recvRawMessage(this.rpcSocket);
if (process.env.KRPC_DEBUG) {
// eslint-disable-next-line no-console
console.log(
`[krpc-client] ${req.service}.${req.procedure} response (${raw.length} bytes):`,
Buffer.from(raw).toString('hex'),
);
}
// The kRPC schema defines `error` as a sub-message of type Error
// (not raw bytes), so protobufjs decodes it as a nested object
// automatically — service/name/description/stackTrace are already
// populated when the field is set.
const response = decodeMessage<{
error?: { service: string; name: string; description: string };
error?: { service: string; name: string; description: string; stackTrace: string };
results: {
error?: { service: string; name: string; description: string };
error?: { service: string; name: string; description: string; stackTrace: string };
value: Uint8Array;
}[];
}>(KRPC.Response, raw);
if (response.error) {
throw new Error(
`RPC error: ${response.error.service}.${response.error.name}: ${response.error.description}`,
`RPC error: ${response.error.service}.${response.error.name}: ${response.error.description}` +
(response.error.stackTrace ? `\n${response.error.stackTrace}` : ''),
);
}
if (response.results.length === 0) {
@@ -209,7 +258,8 @@ export class KRPCClient {
}
if (r.error) {
throw new Error(
`RPC result error: ${r.error.service}.${r.error.name}: ${r.error.description}`,
`RPC result error: ${r.error.service}.${r.error.name}: ${r.error.description}` +
(r.error.stackTrace ? `\n${r.error.stackTrace}` : ''),
);
}
return r.value;
@@ -239,13 +289,18 @@ export class KRPCClient {
};
sendMessage(this.rpcSocket, KRPC.Request, { calls: [addCall] });
const response = decodeMessage<{
results: { value: Uint8Array; error?: { name: string; description: string } }[];
results: {
value: Uint8Array;
error?: { service: string; name: string; description: string; stackTrace: string };
}[];
}>(KRPC.Response, await recvRawMessage(this.rpcSocket));
if (response.results.length === 0) throw new Error('empty AddStream response');
const r0 = response.results[0];
if (!r0) throw new Error('empty AddStream result');
if (r0.error) {
throw new Error(`AddStream error: ${r0.error.name}: ${r0.error.description}`);
throw new Error(
`AddStream error: ${r0.error.service}.${r0.error.name}: ${r0.error.description}`,
);
}
const stream = decodeMessage<{ id: number }>(KRPC.Stream, r0.value);
return stream.id;
@@ -293,9 +348,23 @@ export class KRPCClient {
try {
const raw = await recvRawMessage(this.streamSocket);
const update = decodeMessage<{
results: { id: number; result: { value: Uint8Array } }[];
results: {
id: number;
result: {
error?: { service: string; name: string; description: string; stackTrace: string };
value: Uint8Array;
};
}[];
}>(KRPC.StreamUpdate, raw);
for (const r of update.results) {
if (r.result.error) {
// eslint-disable-next-line no-console
console.warn(
`[krpc-client] stream ${r.id} error: ${r.result.error.service}.${r.result.error.name}: ${r.result.error.description}`,
);
for (const h of this.streamHandlers) h(r.id, new Uint8Array());
continue;
}
for (const h of this.streamHandlers) h(r.id, r.result.value);
}
} catch (err) {
+48 -2
View File
@@ -36,8 +36,16 @@ const schemaJson = {
},
},
ConnectionResponse: {
// NOTE: status is wire-varint-enum-OK=0, but we model it
// as a plain uint32 to avoid protobufjs nested-enum
// resolution bugs that throw "Cannot read properties of
// null (reading 'code')" when the field is omitted from
// the wire (which the kRPC server does for the happy
// path). Our code already does `resp.status !== 0` /
// `!== 'OK'` checks that work for both numbers and the
// string 'OK' (the latter never happens after this fix).
fields: {
status: { type: 'ConnectionResponse.Status', id: 1 },
status: { type: 'uint32', id: 1 },
message: { type: 'string', id: 2 },
clientIdentifier: { type: 'bytes', id: 3 },
},
@@ -80,6 +88,14 @@ const schemaJson = {
},
ProcedureResult: {
fields: {
// Same nested-enum-as-field-type issue as
// ConnectionResponse.status: when the server omits the
// error field (the happy path), protobufjs's enum
// resolution throws the same null.code TypeError. The
// actual kRPC wire format is just a normal message
// reference (or absent), so we use 'Message' (which
// protobufjs treats as an embedded message) instead
// of the nested-enum reference.
error: { type: 'Error', id: 1 },
value: { type: 'bytes', id: 2 },
},
@@ -145,12 +161,33 @@ const schemaJson = {
},
},
Procedure: {
// The kRPC server sends `game_scenes` (a repeated
// GameScene enum, field 6) on every Procedure. The
// GameScene enum is nested inside Procedure. We model
// it as a repeated uint32 to dodge the protobufjs
// nested-enum default-value bug, same as Type.code and
// ConnectionResponse.status. We don't actually use this
// field on the client side; it's just here so the
// decoder doesn't choke on the wire bytes.
fields: {
name: { type: 'string', id: 1 },
parameters: { rule: 'repeated', type: 'Parameter', id: 2 },
returnType: { type: 'Type', id: 3 },
returnIsNullable: { type: 'bool', id: 4 },
documentation: { type: 'string', id: 5 },
gameScenes: { rule: 'repeated', type: 'uint32', id: 6 },
},
nested: {
GameScene: {
values: {
SPACE_CENTER: 0,
FLIGHT: 1,
TRACKING_STATION: 2,
EDITOR_VAB: 3,
EDITOR_SPH: 4,
MISSION_BUILDER: 5,
},
},
},
},
Parameter: {
@@ -188,8 +225,17 @@ const schemaJson = {
},
},
Type: {
// The `code` field on Type is a wire-varint enum
// (TypeCode = uint32 under the hood). We model it as a
// plain uint32 to dodge the protobufjs nested-enum
// default-value lookup bug that throws
// "Cannot read properties of null (reading 'code')"
// when decoding a Type message whose code field is
// present. Same fix as ConnectionResponse.status.
// The values stay as a nested TypeCode enum for
// documentation / programmatic lookup (in services.ts).
fields: {
code: { type: 'Type.TypeCode', id: 1 },
code: { type: 'uint32', id: 1 },
service: { type: 'string', id: 2 },
name: { type: 'string', id: 3 },
types: { rule: 'repeated', type: 'Type', id: 4 },
+53 -3
View File
@@ -68,6 +68,38 @@ export type ProcedureLookup =
| { found: true; info: ProcedureInfo }
| { found: false };
/**
* Generate the .NET-style variants of a PascalCase procedure name.
* For a top-level procedure like "GetUT" -> ["get_UT"].
* For a class-prefixed one like "CelestialBody.GetName" ->
* ["CelestialBody.get_Name", "get_CelestialBody.Name"].
* (We try the most likely variant first; the second is an extra
* fallback in case the kRPC server ever uses a flat "get_X.Y" form,
* which historical versions have done for some properties.)
*/
function netNameVariants(procedure: string): string[] {
const variants: string[] = [];
const lastDot = procedure.lastIndexOf('.');
if (lastDot < 0) {
// Top-level: "GetUT" -> "get_UT"
if (procedure.startsWith('Get') && procedure.length > 3) {
variants.push(`get_${procedure.slice(3)}`);
} else if (procedure.startsWith('Set') && procedure.length > 3) {
variants.push(`set_${procedure.slice(3)}`);
}
} else {
// Class-prefixed: "CelestialBody.GetName" -> "CelestialBody.get_Name"
const prefix = procedure.slice(0, lastDot);
const method = procedure.slice(lastDot + 1);
if (method.startsWith('Get') && method.length > 3) {
variants.push(`${prefix}.get_${method.slice(3)}`);
} else if (method.startsWith('Set') && method.length > 3) {
variants.push(`${prefix}.set_${method.slice(3)}`);
}
}
return variants;
}
export class ServiceCache {
/** "SpaceCenter.CelestialBody.GetName" -> ProcedureInfo */
private byFullName = new Map<string, ProcedureInfo>();
@@ -135,11 +167,29 @@ export class ServiceCache {
/**
* Look up a procedure by `service.procedure` (e.g. "SpaceCenter.GetUT") or
* by the class-prefixed form ("SpaceCenter.CelestialBody.GetName").
*
* The kRPC server exposes C# properties using .NET naming conventions:
* a property `UT` on the SpaceCenter service becomes two procedures,
* `get_UT` and `set_UT`. Class properties like `CelestialBody.Name`
* become `CelestialBody.get_Name` and `CelestialBody.set_Name`.
* We accept the more familiar PascalCase form as a fallback, both
* for top-level procedures (GetUT -> get_UT) and class-prefixed
* ones (CelestialBody.GetName -> CelestialBody.get_Name).
*/
lookup(service: string, procedure: string): ProcedureLookup {
const info = this.byFullName.get(`${service}.${procedure}`);
if (!info) return { found: false };
return { found: true, info };
const direct = this.byFullName.get(`${service}.${procedure}`);
if (direct) return { found: true, info: direct };
// PascalCase -> .NET-style fallback. We try both the simple form
// (GetUT -> get_UT) and the class-prefixed form
// (CelestialBody.GetName -> CelestialBody.get_Name) so user
// code can use either convention.
for (const variant of netNameVariants(procedure)) {
const hit = this.byFullName.get(`${service}.${variant}`);
if (hit) return { found: true, info: hit };
}
return { found: false };
}
/**
+17 -1
View File
@@ -78,7 +78,23 @@ export interface RawKrpcTypeMessage {
types: RawKrpcTypeMessage[];
}
export function decodeKrpcType(raw: RawKrpcTypeMessage): KrpcType {
/**
* Decode a kRPC Type protobuf message into our plain KrpcType shape.
*
* Returns a NONE-type KrpcType if `raw` is null/undefined or doesn't
* have a `code` field — which happens for procedures with no return
* value (the kRPC server omits the `return_type` field). We treat that
* as the NONE type code (0) rather than throwing.
*/
export function decodeKrpcType(raw: RawKrpcTypeMessage | null | undefined): KrpcType {
if (!raw || typeof raw.code !== 'number') {
return {
code: 0 as TypeCodeValue, // NONE
service: '',
name: '',
types: [],
};
}
return {
code: raw.code as TypeCodeValue,
service: raw.service ?? '',
@@ -196,4 +196,68 @@ describe('ServiceCache', () => {
expect(r.info.returnType.types[0]?.code).toBe(100);
expect(r.info.returnType.types[0]?.name).toBe('CelestialBody');
});
it('handles procedures with no return type (returnType is null)', () => {
// Real kRPC server omits the `return_type` field for void
// procedures (e.g. AddStream, setters). protobufjs decodes
// missing message fields as null. Our cache must not crash.
const raw = {
services: [
{
name: 'KRPC',
procedures: [
{
name: 'AddStream',
parameters: [],
returnType: null, // <-- the trigger
returnIsNullable: false,
},
],
classes: [],
enumerations: [],
},
],
};
const cache = new ServiceCache(raw as unknown as Parameters<typeof ServiceCache>[0]);
const r = cache.lookup('KRPC', 'AddStream');
expect(r.found).toBe(true);
if (!r.found) throw new Error('unreachable');
// Missing return type becomes NONE (code 0).
expect(r.info.returnType.code).toBe(0);
});
it('falls back to .NET-style getter/setter naming for C# properties', () => {
// The kRPC server exposes C# properties using .NET accessor
// conventions: a property `UT` on SpaceCenter becomes two
// procedures named `get_UT` and `set_UT`. User code typically
// writes `SpaceCenter.GetUT()` (PascalCase). The cache must
// transparently translate to the wire-format name.
const raw = {
services: [
{
name: 'SpaceCenter',
procedures: [
{ name: 'get_UT', parameters: [], returnType: null, returnIsNullable: false },
{ name: 'set_UT', parameters: [], returnType: null, returnIsNullable: false },
{ name: 'get_ActiveVessel', parameters: [], returnType: null, returnIsNullable: true },
{ name: 'CelestialBody.get_Name', parameters: [], returnType: null, returnIsNullable: false },
],
classes: [],
enumerations: [],
},
],
};
const cache = new ServiceCache(raw as unknown as Parameters<typeof ServiceCache>[0]);
// Top-level PascalCase -> .NET getter
expect(cache.lookup('SpaceCenter', 'GetUT').found).toBe(true);
// Top-level PascalCase -> .NET setter
expect(cache.lookup('SpaceCenter', 'SetUT').found).toBe(true);
expect(cache.lookup('SpaceCenter', 'GetActiveVessel').found).toBe(true);
// Class-prefixed: "CelestialBody.GetName" -> "CelestialBody.get_Name"
expect(cache.lookup('SpaceCenter', 'CelestialBody.GetName').found).toBe(true);
// Exact match still works
expect(cache.lookup('SpaceCenter', 'get_UT').found).toBe(true);
// And unknown names still return not-found
expect(cache.lookup('SpaceCenter', 'NoSuchProcedure').found).toBe(false);
});
});