@nomux-sh/extension 0.0.0-stage → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,183 @@
1
+ import { CallError, RunError, describe } from "./error.js";
2
+ import { FrameError, FrameReader } from "./frame.js";
3
+ import { answerHello } from "./handshake.js";
4
+ import { Host } from "./host.js";
5
+ import { Outbound } from "./outbound.js";
6
+ import { PendingCalls } from "./pending-calls.js";
7
+ /**
8
+ * One connection to the host, from `Hello` to the end.
9
+ *
10
+ * The connection reads the frames as they arrive. It answers health
11
+ * requests, records cancellations and gives the responses of host services
12
+ * to the calls that wait for them at once. The work of the other requests
13
+ * runs in a queue, one request at a time, in the sequence of arrival.
14
+ */
15
+ export class Connection {
16
+ input;
17
+ identity;
18
+ answer;
19
+ reader = new FrameReader();
20
+ outbound;
21
+ pending = new PendingCalls();
22
+ cancellations = new Map();
23
+ queue = [];
24
+ host;
25
+ isWorking = false;
26
+ isStopped = false;
27
+ resolve = () => { };
28
+ reject = () => { };
29
+ onData = (chunk) => this.receive(chunk);
30
+ onEnd = () => this.receiveEnd();
31
+ onError = (error) => this.stop(new RunError("frame", `the stream failed: ${error.message}`, { cause: error }));
32
+ constructor(input, output, identity, answer) {
33
+ this.input = input;
34
+ this.identity = identity;
35
+ this.answer = answer;
36
+ this.outbound = new Outbound(output);
37
+ output.on("error", this.onError);
38
+ }
39
+ /** Serves the host until a shutdown request or a failure. */
40
+ run() {
41
+ const done = new Promise((resolve, reject) => {
42
+ this.resolve = resolve;
43
+ this.reject = reject;
44
+ });
45
+ this.input.on("data", this.onData);
46
+ this.input.on("end", this.onEnd);
47
+ this.input.on("error", this.onError);
48
+ return done;
49
+ }
50
+ receive(chunk) {
51
+ try {
52
+ for (const envelope of this.reader.read(chunk)) {
53
+ if (this.isStopped) {
54
+ return;
55
+ }
56
+ this.route(envelope);
57
+ }
58
+ }
59
+ catch (error) {
60
+ if (!(error instanceof FrameError)) {
61
+ throw error;
62
+ }
63
+ this.stop(new RunError("frame", error.message, { cause: error }));
64
+ }
65
+ }
66
+ receiveEnd() {
67
+ const error = this.reader.isBetweenFrames
68
+ ? new RunError("disconnected", "the host closed the stream and did not send a shutdown request")
69
+ : new RunError("frame", "the stream ended in the middle of a frame");
70
+ this.stop(error);
71
+ }
72
+ route(envelope) {
73
+ if (this.host === undefined) {
74
+ this.handshake(envelope);
75
+ return;
76
+ }
77
+ switch (envelope.kind?.$case) {
78
+ case "request":
79
+ this.routeRequest(envelope.kind.value);
80
+ break;
81
+ case "response":
82
+ this.pending.resolve(envelope.kind.value);
83
+ break;
84
+ case "cancel":
85
+ this.cancellations.get(envelope.kind.value.id)?.abort();
86
+ break;
87
+ // The host sends no events. A kind that this version does not know
88
+ // comes from a newer host and is not an error.
89
+ default:
90
+ break;
91
+ }
92
+ }
93
+ handshake(envelope) {
94
+ const { response, outcome } = answerHello(envelope, this.identity);
95
+ if (response !== undefined) {
96
+ this.outbound.send({ $case: "response", value: response });
97
+ }
98
+ if (outcome instanceof RunError) {
99
+ this.stop(outcome);
100
+ return;
101
+ }
102
+ this.host = new Host(this.outbound, this.pending, outcome);
103
+ }
104
+ routeRequest(request) {
105
+ const { id, body } = request;
106
+ switch (body?.$case) {
107
+ case "health":
108
+ this.respond(id, { $case: "health", value: {} });
109
+ return;
110
+ case "hello":
111
+ this.respond(id, failure("the handshake is already complete"));
112
+ return;
113
+ case "initialize":
114
+ case "shutdown":
115
+ this.enqueue(id, { $case: body.$case });
116
+ return;
117
+ case "call":
118
+ this.enqueue(id, body);
119
+ return;
120
+ default:
121
+ this.respond(id, failure("the extension does not know this request"));
122
+ }
123
+ }
124
+ enqueue(id, work) {
125
+ const controller = new AbortController();
126
+ this.cancellations.set(id, controller);
127
+ this.queue.push({ id, work, controller });
128
+ void this.work();
129
+ }
130
+ async work() {
131
+ if (this.isWorking || this.host === undefined) {
132
+ return;
133
+ }
134
+ this.isWorking = true;
135
+ const host = this.host;
136
+ let next = this.queue.shift();
137
+ while (next !== undefined && !this.isStopped) {
138
+ const result = await this.answer(next.work, { host, signal: next.controller.signal });
139
+ this.cancellations.delete(next.id);
140
+ if (this.isStopped) {
141
+ break;
142
+ }
143
+ this.respond(next.id, result);
144
+ if (next.work.$case === "shutdown") {
145
+ this.stop(undefined);
146
+ break;
147
+ }
148
+ next = this.queue.shift();
149
+ }
150
+ this.isWorking = false;
151
+ }
152
+ respond(id, result) {
153
+ try {
154
+ this.outbound.send({ $case: "response", value: { id, result } });
155
+ }
156
+ catch (error) {
157
+ // A result that is too large is the failure of one call. The
158
+ // connection stays open.
159
+ if (!(error instanceof FrameError) || !error.isTooLarge) {
160
+ throw error;
161
+ }
162
+ this.outbound.send({ $case: "response", value: { id, result: failure(describe(error)) } });
163
+ }
164
+ }
165
+ /** Stops the connection. `error` is `undefined` after a shutdown request. */
166
+ stop(error) {
167
+ if (this.isStopped) {
168
+ return;
169
+ }
170
+ this.isStopped = true;
171
+ this.input.off("data", this.onData);
172
+ this.input.off("end", this.onEnd);
173
+ this.input.destroy();
174
+ this.pending.close();
175
+ for (const controller of this.cancellations.values()) {
176
+ controller.abort();
177
+ }
178
+ this.outbound.flush().then(() => (error === undefined ? this.resolve() : this.reject(error)), (cause) => this.reject(new RunError("frame", `the stream failed: ${describe(cause)}`, { cause })));
179
+ }
180
+ }
181
+ function failure(message) {
182
+ return { $case: "error", value: CallError.failed(message).toWire() };
183
+ }
@@ -0,0 +1,41 @@
1
+ import { ErrorCode } from "./generated/nomux/extension/v1/envelope.js";
2
+ import type { Error as WireError } from "./generated/nomux/extension/v1/envelope.js";
3
+ export { ErrorCode };
4
+ /**
5
+ * The failure of one call.
6
+ *
7
+ * A method of an extension throws it, and the host gets the code and the
8
+ * message. A call of a host service throws it when the host refuses or fails
9
+ * the call.
10
+ */
11
+ export declare class CallError extends Error {
12
+ /** The reason for the failure. */
13
+ readonly code: ErrorCode;
14
+ /** Makes an error with a code and a message in English for the user. */
15
+ constructor(code: ErrorCode, message: string);
16
+ /** Makes an error with the code {@link ErrorCode.FAILED}. */
17
+ static failed(message: string): CallError;
18
+ /**
19
+ * Makes the error that a method throws when it stops because its
20
+ * `signal` is aborted.
21
+ */
22
+ static cancelled(): CallError;
23
+ /** Makes the error of a wire message. A code that is not known fails. */
24
+ static fromWire(error: WireError): CallError;
25
+ /** The wire message of the error. */
26
+ toWire(): WireError;
27
+ }
28
+ /** The reason why {@link RunError} stopped the extension. */
29
+ export type RunErrorKind = "frame" | "no-hello" | "incompatible-api" | "disconnected";
30
+ /**
31
+ * The reason why `Extension.run` stopped before the host sent a shutdown
32
+ * request.
33
+ */
34
+ export declare class RunError extends Error {
35
+ /** The kind of the failure. */
36
+ readonly kind: RunErrorKind;
37
+ /** Makes an error of a kind with a message. */
38
+ constructor(kind: RunErrorKind, message: string, options?: ErrorOptions);
39
+ }
40
+ /** The message of a thrown value. */
41
+ export declare function describe(error: unknown): string;
package/dist/error.js ADDED
@@ -0,0 +1,61 @@
1
+ import { ErrorCode } from "./generated/nomux/extension/v1/envelope.js";
2
+ export { ErrorCode };
3
+ /**
4
+ * The failure of one call.
5
+ *
6
+ * A method of an extension throws it, and the host gets the code and the
7
+ * message. A call of a host service throws it when the host refuses or fails
8
+ * the call.
9
+ */
10
+ export class CallError extends Error {
11
+ /** The reason for the failure. */
12
+ code;
13
+ /** Makes an error with a code and a message in English for the user. */
14
+ constructor(code, message) {
15
+ super(message);
16
+ this.name = "CallError";
17
+ this.code = code;
18
+ }
19
+ /** Makes an error with the code {@link ErrorCode.FAILED}. */
20
+ static failed(message) {
21
+ return new CallError(ErrorCode.FAILED, message);
22
+ }
23
+ /**
24
+ * Makes the error that a method throws when it stops because its
25
+ * `signal` is aborted.
26
+ */
27
+ static cancelled() {
28
+ return new CallError(ErrorCode.CANCELLED, "the call was cancelled");
29
+ }
30
+ /** Makes the error of a wire message. A code that is not known fails. */
31
+ static fromWire(error) {
32
+ return new CallError(knownCode(error.code), error.message);
33
+ }
34
+ /** The wire message of the error. */
35
+ toWire() {
36
+ return { code: this.code, message: this.message };
37
+ }
38
+ }
39
+ /** A code that is not set or not known is a failure with no other reason. */
40
+ function knownCode(code) {
41
+ const isKnown = Number.isInteger(code) && code > ErrorCode.UNSPECIFIED && code <= ErrorCode.CANCELLED;
42
+ return isKnown ? code : ErrorCode.FAILED;
43
+ }
44
+ /**
45
+ * The reason why `Extension.run` stopped before the host sent a shutdown
46
+ * request.
47
+ */
48
+ export class RunError extends Error {
49
+ /** The kind of the failure. */
50
+ kind;
51
+ /** Makes an error of a kind with a message. */
52
+ constructor(kind, message, options) {
53
+ super(message, options);
54
+ this.name = "RunError";
55
+ this.kind = kind;
56
+ }
57
+ }
58
+ /** The message of a thrown value. */
59
+ export function describe(error) {
60
+ return error instanceof Error ? error.message : String(error);
61
+ }
@@ -0,0 +1,90 @@
1
+ import type { Readable, Writable } from "node:stream";
2
+ import type { ApiVersion } from "./api-version.js";
3
+ import type { Call } from "./call.js";
4
+ import type { MethodCodecs } from "./codec.js";
5
+ import type { Host } from "./host.js";
6
+ /**
7
+ * A method that the host can call. It gets the decoded argument and the
8
+ * context of the call, and returns the result. It throws a
9
+ * {@link CallError} to fail the call with a code.
10
+ */
11
+ export type Method<Input, Output> = (input: Input, call: Call) => Output | Promise<Output>;
12
+ type Initialize = (host: Host) => void | Promise<void>;
13
+ /**
14
+ * The daemon part of an extension.
15
+ *
16
+ * Add the methods, then call {@link Extension.run}:
17
+ *
18
+ * ```ts
19
+ * await new Extension("nomux.echo", "0.1.0")
20
+ * .method("echo", { input: Text, output: Text }, (text) => text)
21
+ * .run();
22
+ * ```
23
+ */
24
+ export declare class Extension {
25
+ private readonly id;
26
+ private readonly version;
27
+ private api;
28
+ private readonly methods;
29
+ private initializer;
30
+ private isInitialized;
31
+ /**
32
+ * Starts the definition of an extension.
33
+ *
34
+ * `id` and `version` are the values of `id` and `version` in
35
+ * `extension.toml`. The host stops an extension whose `id` is different
36
+ * from its manifest.
37
+ */
38
+ constructor(id: string, version: string);
39
+ /**
40
+ * States the lowest extension API version that the extension needs. The
41
+ * default is {@link MINIMUM_API_VERSION}. State a later version only if the
42
+ * extension uses a feature of that version, and give `api` in
43
+ * `extension.toml` the same minimum: version 0.1.1 and `api = "^0.1.1"`.
44
+ *
45
+ * The extension refuses a host whose version does not match the caret
46
+ * requirement of `version`.
47
+ *
48
+ * Throws if the SDK does not implement `version`: if the caret requirement
49
+ * of `version` does not match {@link API_VERSION}.
50
+ */
51
+ requiresApi(version: ApiVersion): this;
52
+ /**
53
+ * Adds a method that the host can call.
54
+ *
55
+ * If the payload of a call is not a valid argument, the host gets
56
+ * {@link ErrorCode.INVALID_ARGUMENT} and the method does not run.
57
+ *
58
+ * The methods run one at a time, in the sequence in which the calls
59
+ * arrive. While a method waits, the extension answers health requests and
60
+ * records cancellations.
61
+ *
62
+ * Throws if the extension already has a method with this name.
63
+ */
64
+ method<Input, Output>(name: string, codecs: MethodCodecs<Input, Output>, method: Method<Input, Output>): this;
65
+ /**
66
+ * Sets a function that runs one time, after the handshake and before the
67
+ * first call. If the function throws, the host gets the error and no
68
+ * method runs.
69
+ */
70
+ onInitialize(initialize: Initialize): this;
71
+ /**
72
+ * Serves the host on the standard input and the standard output of the
73
+ * process, until the host sends a shutdown request. Then the promise
74
+ * resolves and the process can exit. The promise rejects with a
75
+ * {@link RunError} when the extension must stop for a different reason.
76
+ *
77
+ * The standard output carries the protocol. Write logs to the standard
78
+ * error.
79
+ */
80
+ run(): Promise<void>;
81
+ /**
82
+ * Serves a host on the given streams, until the host sends a shutdown
83
+ * request. Use it to test an extension in the process of the test.
84
+ */
85
+ serve(input: Readable, output: Writable): Promise<void>;
86
+ private answer;
87
+ private initialize;
88
+ private call;
89
+ }
90
+ export {};
@@ -0,0 +1,153 @@
1
+ import process from "node:process";
2
+ import { API_VERSION, MINIMUM_API_VERSION, formatVersion, isCompatible } from "./api-version.js";
3
+ import { Connection } from "./connection.js";
4
+ import { CallError, ErrorCode } from "./error.js";
5
+ import { decode } from "./host.js";
6
+ /**
7
+ * The daemon part of an extension.
8
+ *
9
+ * Add the methods, then call {@link Extension.run}:
10
+ *
11
+ * ```ts
12
+ * await new Extension("nomux.echo", "0.1.0")
13
+ * .method("echo", { input: Text, output: Text }, (text) => text)
14
+ * .run();
15
+ * ```
16
+ */
17
+ export class Extension {
18
+ id;
19
+ version;
20
+ api = MINIMUM_API_VERSION;
21
+ methods = new Map();
22
+ initializer;
23
+ isInitialized = false;
24
+ /**
25
+ * Starts the definition of an extension.
26
+ *
27
+ * `id` and `version` are the values of `id` and `version` in
28
+ * `extension.toml`. The host stops an extension whose `id` is different
29
+ * from its manifest.
30
+ */
31
+ constructor(id, version) {
32
+ this.id = id;
33
+ this.version = version;
34
+ }
35
+ /**
36
+ * States the lowest extension API version that the extension needs. The
37
+ * default is {@link MINIMUM_API_VERSION}. State a later version only if the
38
+ * extension uses a feature of that version, and give `api` in
39
+ * `extension.toml` the same minimum: version 0.1.1 and `api = "^0.1.1"`.
40
+ *
41
+ * The extension refuses a host whose version does not match the caret
42
+ * requirement of `version`.
43
+ *
44
+ * Throws if the SDK does not implement `version`: if the caret requirement
45
+ * of `version` does not match {@link API_VERSION}.
46
+ */
47
+ requiresApi(version) {
48
+ if (!isCompatible(version, API_VERSION)) {
49
+ throw new Error(`the SDK implements the extension API version ${formatVersion(API_VERSION)}, not ${formatVersion(version)}`);
50
+ }
51
+ this.api = { ...version };
52
+ return this;
53
+ }
54
+ /**
55
+ * Adds a method that the host can call.
56
+ *
57
+ * If the payload of a call is not a valid argument, the host gets
58
+ * {@link ErrorCode.INVALID_ARGUMENT} and the method does not run.
59
+ *
60
+ * The methods run one at a time, in the sequence in which the calls
61
+ * arrive. While a method waits, the extension answers health requests and
62
+ * records cancellations.
63
+ *
64
+ * Throws if the extension already has a method with this name.
65
+ */
66
+ method(name, codecs, method) {
67
+ if (this.methods.has(name)) {
68
+ throw new Error(`the method \`${name}\` is added twice`);
69
+ }
70
+ this.methods.set(name, async (payload, call) => {
71
+ const input = decode(codecs.input, payload, "the payload");
72
+ return codecs.output.encode(await method(input, call));
73
+ });
74
+ return this;
75
+ }
76
+ /**
77
+ * Sets a function that runs one time, after the handshake and before the
78
+ * first call. If the function throws, the host gets the error and no
79
+ * method runs.
80
+ */
81
+ onInitialize(initialize) {
82
+ this.initializer = initialize;
83
+ return this;
84
+ }
85
+ /**
86
+ * Serves the host on the standard input and the standard output of the
87
+ * process, until the host sends a shutdown request. Then the promise
88
+ * resolves and the process can exit. The promise rejects with a
89
+ * {@link RunError} when the extension must stop for a different reason.
90
+ *
91
+ * The standard output carries the protocol. Write logs to the standard
92
+ * error.
93
+ */
94
+ run() {
95
+ return this.serve(process.stdin, process.stdout);
96
+ }
97
+ /**
98
+ * Serves a host on the given streams, until the host sends a shutdown
99
+ * request. Use it to test an extension in the process of the test.
100
+ */
101
+ serve(input, output) {
102
+ const identity = { id: this.id, version: this.version, api: this.api };
103
+ return new Connection(input, output, identity, (work, call) => this.answer(work, call)).run();
104
+ }
105
+ async answer(work, call) {
106
+ try {
107
+ switch (work.$case) {
108
+ case "initialize":
109
+ await this.initialize(call.host);
110
+ return { $case: "initialize", value: {} };
111
+ case "shutdown":
112
+ return { $case: "shutdown", value: {} };
113
+ case "call":
114
+ return { $case: "call", value: { payload: await this.call(work.value, call) } };
115
+ }
116
+ }
117
+ catch (error) {
118
+ return { $case: "error", value: callError(error, call.signal).toWire() };
119
+ }
120
+ }
121
+ async initialize(host) {
122
+ if (this.isInitialized) {
123
+ throw CallError.failed("the extension is already initialized");
124
+ }
125
+ const initialize = this.initializer;
126
+ this.initializer = undefined;
127
+ await initialize?.(host);
128
+ this.isInitialized = true;
129
+ }
130
+ async call(request, call) {
131
+ if (!this.isInitialized) {
132
+ throw CallError.failed("the extension is not initialized");
133
+ }
134
+ if (call.signal.aborted) {
135
+ throw CallError.cancelled();
136
+ }
137
+ const method = this.methods.get(request.method);
138
+ if (method === undefined) {
139
+ throw new CallError(ErrorCode.NOT_FOUND, `the extension has no method \`${request.method}\``);
140
+ }
141
+ return method(request.payload, call);
142
+ }
143
+ }
144
+ /** The error that the host gets for a value that a method threw. */
145
+ function callError(error, signal) {
146
+ if (error instanceof CallError) {
147
+ return error;
148
+ }
149
+ if (signal.aborted) {
150
+ return CallError.cancelled();
151
+ }
152
+ return CallError.failed(error instanceof Error ? error.message : String(error));
153
+ }
@@ -0,0 +1,32 @@
1
+ import { Envelope } from "./generated/nomux/extension/v1/envelope.js";
2
+ /**
3
+ * The largest number of bytes of one encoded {@link Envelope}. A peer that
4
+ * reads a larger length stops: it cannot find the start of the subsequent
5
+ * frame.
6
+ */
7
+ export declare const MAX_ENVELOPE_LENGTH: number;
8
+ /** The reason why a frame was not read or written. */
9
+ export declare class FrameError extends Error {
10
+ /** `true` if the envelope is larger than {@link MAX_ENVELOPE_LENGTH}. */
11
+ readonly isTooLarge: boolean;
12
+ constructor(message: string, isTooLarge?: boolean, options?: ErrorOptions);
13
+ }
14
+ /** Encodes one envelope as a frame: the varint length, then the envelope. */
15
+ export declare function encodeFrame(envelope: Envelope): Uint8Array;
16
+ /**
17
+ * Takes the bytes of a stream in chunks of any size and gives the envelopes
18
+ * in them.
19
+ */
20
+ export declare class FrameReader {
21
+ private length;
22
+ private lengthBytes;
23
+ private body;
24
+ private filled;
25
+ /** `true` if the bytes so far end between two frames. */
26
+ get isBetweenFrames(): boolean;
27
+ /** Reads a chunk. Throws {@link FrameError} if a frame is not valid. */
28
+ read(chunk: Uint8Array): Generator<Envelope>;
29
+ private readLength;
30
+ private startBody;
31
+ private takeEnvelope;
32
+ }
package/dist/frame.js ADDED
@@ -0,0 +1,99 @@
1
+ import { BinaryWriter } from "@bufbuild/protobuf/wire";
2
+ import { describe } from "./error.js";
3
+ import { Envelope } from "./generated/nomux/extension/v1/envelope.js";
4
+ /**
5
+ * The largest number of bytes of one encoded {@link Envelope}. A peer that
6
+ * reads a larger length stops: it cannot find the start of the subsequent
7
+ * frame.
8
+ */
9
+ export const MAX_ENVELOPE_LENGTH = 4 * 1024 * 1024;
10
+ /** The largest number of bytes of the length of a frame. */
11
+ const MAX_LENGTH_BYTES = 5;
12
+ /** The reason why a frame was not read or written. */
13
+ export class FrameError extends Error {
14
+ /** `true` if the envelope is larger than {@link MAX_ENVELOPE_LENGTH}. */
15
+ isTooLarge;
16
+ constructor(message, isTooLarge = false, options) {
17
+ super(message, options);
18
+ this.name = "FrameError";
19
+ this.isTooLarge = isTooLarge;
20
+ }
21
+ }
22
+ /** Encodes one envelope as a frame: the varint length, then the envelope. */
23
+ export function encodeFrame(envelope) {
24
+ const body = Envelope.encode(envelope).finish();
25
+ if (body.length > MAX_ENVELOPE_LENGTH) {
26
+ throw new FrameError(`the envelope has ${body.length} bytes, but the limit is ${MAX_ENVELOPE_LENGTH} bytes`, true);
27
+ }
28
+ return new BinaryWriter().bytes(body).finish();
29
+ }
30
+ /**
31
+ * Takes the bytes of a stream in chunks of any size and gives the envelopes
32
+ * in them.
33
+ */
34
+ export class FrameReader {
35
+ length = 0;
36
+ lengthBytes = 0;
37
+ body;
38
+ filled = 0;
39
+ /** `true` if the bytes so far end between two frames. */
40
+ get isBetweenFrames() {
41
+ return this.lengthBytes === 0 && this.body === undefined;
42
+ }
43
+ /** Reads a chunk. Throws {@link FrameError} if a frame is not valid. */
44
+ *read(chunk) {
45
+ let offset = 0;
46
+ while (offset < chunk.length) {
47
+ if (this.body === undefined) {
48
+ offset = this.readLength(chunk, offset);
49
+ if (this.body === undefined) {
50
+ continue;
51
+ }
52
+ }
53
+ const count = Math.min(this.body.length - this.filled, chunk.length - offset);
54
+ this.body.set(chunk.subarray(offset, offset + count), this.filled);
55
+ this.filled += count;
56
+ offset += count;
57
+ if (this.filled === this.body.length) {
58
+ yield this.takeEnvelope(this.body);
59
+ }
60
+ }
61
+ }
62
+ readLength(chunk, start) {
63
+ let offset = start;
64
+ while (offset < chunk.length) {
65
+ const byte = chunk[offset] ?? 0;
66
+ offset += 1;
67
+ this.length += (byte & 0x7f) * 2 ** (7 * this.lengthBytes);
68
+ this.lengthBytes += 1;
69
+ if ((byte & 0x80) === 0) {
70
+ this.startBody();
71
+ return offset;
72
+ }
73
+ if (this.lengthBytes === MAX_LENGTH_BYTES) {
74
+ throw new FrameError("the length of the frame is not valid");
75
+ }
76
+ }
77
+ return offset;
78
+ }
79
+ startBody() {
80
+ if (this.length > MAX_ENVELOPE_LENGTH) {
81
+ throw new FrameError(`the envelope has ${this.length} bytes, but the limit is ${MAX_ENVELOPE_LENGTH} bytes`, true);
82
+ }
83
+ this.body = new Uint8Array(this.length);
84
+ this.filled = 0;
85
+ }
86
+ takeEnvelope(body) {
87
+ this.length = 0;
88
+ this.lengthBytes = 0;
89
+ this.body = undefined;
90
+ try {
91
+ return Envelope.decode(body);
92
+ }
93
+ catch (error) {
94
+ throw new FrameError(`the frame is not an envelope: ${describe(error)}`, false, {
95
+ cause: error,
96
+ });
97
+ }
98
+ }
99
+ }
@@ -0,0 +1,29 @@
1
+ import { BinaryReader, BinaryWriter } from "@bufbuild/protobuf/wire";
2
+ /** Calls one method. */
3
+ export interface CallRequest {
4
+ /**
5
+ * The name of the method.
6
+ *
7
+ * From the host: a method that the extension supplies, for example `echo`.
8
+ * From the extension: a method of a host service in the form
9
+ * `<service>.<method>`, for example `sessions.list`.
10
+ */
11
+ method: string;
12
+ /**
13
+ * The argument of the method. The method specifies the encoding. The Rust
14
+ * SDK uses an encoded protobuf message.
15
+ */
16
+ payload: Uint8Array;
17
+ }
18
+ /** The reply to `CallRequest`. */
19
+ export interface CallResponse {
20
+ /** The result of the method. The method specifies the encoding. */
21
+ payload: Uint8Array;
22
+ }
23
+ export declare const CallRequest: MessageFns<CallRequest>;
24
+ export declare const CallResponse: MessageFns<CallResponse>;
25
+ interface MessageFns<T> {
26
+ encode(message: T, writer?: BinaryWriter): BinaryWriter;
27
+ decode(input: BinaryReader | Uint8Array, length?: number): T;
28
+ }
29
+ export {};