relapsesdk 0.0.0-stage → 0.1.0
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.
- package/LICENSE +232 -0
- package/README.md +150 -2
- package/dist/channel.d.ts +33 -0
- package/dist/channel.js +40 -0
- package/dist/client.d.ts +28 -0
- package/dist/client.js +58 -0
- package/dist/discovery.d.ts +12 -0
- package/dist/discovery.js +80 -0
- package/dist/errors.d.ts +5 -0
- package/dist/errors.js +10 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +10 -0
- package/dist/internal/json.d.ts +5 -0
- package/dist/internal/json.js +16 -0
- package/dist/internal/operation.d.ts +13 -0
- package/dist/internal/operation.js +53 -0
- package/dist/internal/transport.d.ts +25 -0
- package/dist/internal/transport.js +204 -0
- package/dist/internal/wait-for.d.ts +3 -0
- package/dist/internal/wait-for.js +36 -0
- package/dist/launcher.d.ts +12 -0
- package/dist/launcher.js +35 -0
- package/dist/main-channel.d.ts +74 -0
- package/dist/main-channel.js +234 -0
- package/dist/profiles.d.ts +20 -0
- package/dist/profiles.js +56 -0
- package/examples/channel.mjs +21 -0
- package/examples/consumer.ts +135 -0
- package/examples/execute.mjs +23 -0
- package/package.json +58 -4
- package/src/channel.ts +72 -0
- package/src/client.ts +77 -0
- package/src/discovery.ts +81 -0
- package/src/errors.ts +26 -0
- package/src/index.ts +22 -0
- package/src/internal/json.ts +26 -0
- package/src/internal/operation.ts +70 -0
- package/src/internal/transport.ts +214 -0
- package/src/internal/wait-for.ts +41 -0
- package/src/launcher.ts +44 -0
- package/src/main-channel.ts +296 -0
- package/src/profiles.ts +75 -0
- package/tsconfig.json +20 -0
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
// Copyright (C) 2026 vpu007
|
|
2
|
+
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
import { EventEmitter } from "node:events";
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { basename } from "node:path";
|
|
7
|
+
import type { ChannelConnection } from "./channel.js";
|
|
8
|
+
import { RelapseError } from "./errors.js";
|
|
9
|
+
import { isRecord } from "./internal/json.js";
|
|
10
|
+
import { operation, type Operation, type WaitOptions } from "./internal/operation.js";
|
|
11
|
+
import { Transport, type CloseInfo } from "./internal/transport.js";
|
|
12
|
+
import { waitForEvent } from "./internal/wait-for.js";
|
|
13
|
+
|
|
14
|
+
export interface MainChannelOptions extends WaitOptions {
|
|
15
|
+
socketPath: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface ExecuteOptions extends WaitOptions {
|
|
19
|
+
name?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type MainRequest = {
|
|
23
|
+
op: "execute";
|
|
24
|
+
script_id: number;
|
|
25
|
+
session: number;
|
|
26
|
+
source: string;
|
|
27
|
+
name?: string;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export interface MainHello {
|
|
31
|
+
type: "hello";
|
|
32
|
+
pid: number;
|
|
33
|
+
profile: string;
|
|
34
|
+
ready: boolean;
|
|
35
|
+
session: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface MainStatus {
|
|
39
|
+
type: "status";
|
|
40
|
+
ready: boolean;
|
|
41
|
+
session: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface ExecutionResult {
|
|
45
|
+
type: "exec_result";
|
|
46
|
+
script_id: number;
|
|
47
|
+
phase: "submitted" | "error";
|
|
48
|
+
detail?: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface LogEntry {
|
|
52
|
+
type: "log";
|
|
53
|
+
level: string;
|
|
54
|
+
text: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface MainError {
|
|
58
|
+
type: "error";
|
|
59
|
+
detail: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export type MainMessage = MainHello | MainStatus | ExecutionResult | LogEntry | MainError;
|
|
63
|
+
|
|
64
|
+
export interface MainChannelEvents {
|
|
65
|
+
message: [message: MainMessage];
|
|
66
|
+
hello: [message: MainHello];
|
|
67
|
+
status: [message: MainStatus];
|
|
68
|
+
exec_result: [message: ExecutionResult];
|
|
69
|
+
log: [message: LogEntry];
|
|
70
|
+
close: [info: CloseInfo];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export class MainChannel extends EventEmitter<MainChannelEvents> implements ChannelConnection {
|
|
74
|
+
readonly #transport: Transport;
|
|
75
|
+
readonly #opening: Operation<void>;
|
|
76
|
+
readonly #requests = new Map<number, Operation<void>>();
|
|
77
|
+
readonly #pending = new Set<number>();
|
|
78
|
+
#hello: Readonly<MainHello> | undefined;
|
|
79
|
+
#ready = false;
|
|
80
|
+
#session = 0;
|
|
81
|
+
#nextId = 1;
|
|
82
|
+
|
|
83
|
+
private constructor(options: MainChannelOptions, opening: Operation<void>) {
|
|
84
|
+
super();
|
|
85
|
+
this.#opening = opening;
|
|
86
|
+
this.#transport = new Transport(options.socketPath, "@main", {
|
|
87
|
+
message: message => this.#receive(message),
|
|
88
|
+
close: info => this.#closed(info),
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Connects to @main and receives its initial hello, which may report ready: false. */
|
|
93
|
+
static async connect(options: MainChannelOptions): Promise<MainChannel> {
|
|
94
|
+
const opening = operation<void>(options, 5000);
|
|
95
|
+
let channel: MainChannel;
|
|
96
|
+
try {
|
|
97
|
+
channel = new MainChannel(options, opening);
|
|
98
|
+
} catch (error) {
|
|
99
|
+
opening.resolve();
|
|
100
|
+
await opening.promise.catch(() => {});
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
try {
|
|
104
|
+
await Promise.all([
|
|
105
|
+
channel.#transport.open(options).then(() => channel.#transport.resume()),
|
|
106
|
+
opening.promise,
|
|
107
|
+
]);
|
|
108
|
+
setImmediate(() => channel.#transport.resume());
|
|
109
|
+
return channel;
|
|
110
|
+
} catch (error) {
|
|
111
|
+
channel.close();
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
get socketPath(): string { return this.#transport.socketPath; }
|
|
117
|
+
get name(): "@main" { return "@main"; }
|
|
118
|
+
get connected(): boolean { return this.#transport.connected; }
|
|
119
|
+
get maxMessageBytes(): number { return this.#transport.maxMessageBytes; }
|
|
120
|
+
get hello(): Readonly<MainHello> { return this.#hello!; }
|
|
121
|
+
get ready(): boolean { return this.connected && this.#ready; }
|
|
122
|
+
get session(): number { return this.#session; }
|
|
123
|
+
|
|
124
|
+
/** Validates and writes a request. Execution acknowledgements arrive as exec_result events. */
|
|
125
|
+
async send(value: MainRequest): Promise<void> {
|
|
126
|
+
const request = validateRequest(value);
|
|
127
|
+
if (!this.connected) throw new RelapseError("disconnected", "Main channel is closed.");
|
|
128
|
+
if (!this.ready) throw new RelapseError("not_ready", "Executor is not ready.");
|
|
129
|
+
if (request.session !== this.#session) throw new RelapseError("session_changed", "Request targets a different executor session.");
|
|
130
|
+
if (this.#pending.has(request.script_id)) throw new TypeError("This execution request ID is already pending.");
|
|
131
|
+
if (this.#pending.size >= 16) throw new RelapseError("backpressure", "Too many pending executions.");
|
|
132
|
+
|
|
133
|
+
this.#pending.add(request.script_id);
|
|
134
|
+
this.#nextId = Math.max(this.#nextId, request.script_id + 1);
|
|
135
|
+
try {
|
|
136
|
+
await this.#transport.send(request);
|
|
137
|
+
} catch (error) {
|
|
138
|
+
this.#pending.delete(request.script_id);
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Waits for a future matching event. Check ready before waiting for a readiness transition. */
|
|
144
|
+
waitFor<K extends keyof MainChannelEvents>(
|
|
145
|
+
event: K,
|
|
146
|
+
predicate?: (value: MainChannelEvents[K][0]) => boolean,
|
|
147
|
+
options: WaitOptions = {},
|
|
148
|
+
): Promise<MainChannelEvents[K][0]> {
|
|
149
|
+
return waitForEvent(this, event, this.connected, predicate, options);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Resolves on submission, not script completion. Timeout/abort cannot undo submission. */
|
|
153
|
+
async execute(source: string, options: ExecuteOptions = {}): Promise<void> {
|
|
154
|
+
if (this.#nextId > Number.MAX_SAFE_INTEGER) throw new RangeError("Execution request IDs exhausted.");
|
|
155
|
+
const request = operation<void>(options, 10_000);
|
|
156
|
+
const id = this.#nextId++;
|
|
157
|
+
if (!request.settled) {
|
|
158
|
+
this.#requests.set(id, request);
|
|
159
|
+
this.send({
|
|
160
|
+
op: "execute", script_id: id, session: this.#session,
|
|
161
|
+
source, name: options.name ?? "relapse",
|
|
162
|
+
}).catch(error => request.reject(error));
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
await request.promise;
|
|
166
|
+
} finally {
|
|
167
|
+
this.#requests.delete(id);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async executeFile(path: string, options: ExecuteOptions = {}): Promise<void> {
|
|
172
|
+
const source = await readFile(path, {
|
|
173
|
+
encoding: "utf8",
|
|
174
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
175
|
+
});
|
|
176
|
+
await this.execute(source, { ...options, name: options.name ?? basename(path) });
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
close(): void {
|
|
180
|
+
this.#transport.close();
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
#receive(value: unknown): void {
|
|
184
|
+
let message: MainMessage;
|
|
185
|
+
try {
|
|
186
|
+
message = parseMessage(value);
|
|
187
|
+
if ((!this.#hello && message.type !== "hello") || (this.#hello && message.type === "hello")) {
|
|
188
|
+
throw new TypeError("Expected one initial hello message.");
|
|
189
|
+
}
|
|
190
|
+
} catch (error) {
|
|
191
|
+
this.#transport.close(new RelapseError("protocol_error", "Invalid @main message.", { cause: error }));
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
switch (message.type) {
|
|
196
|
+
case "hello":
|
|
197
|
+
this.#hello = Object.freeze(message);
|
|
198
|
+
this.#ready = message.ready;
|
|
199
|
+
this.#session = message.session;
|
|
200
|
+
this.#transport.pause();
|
|
201
|
+
this.#opening.resolve();
|
|
202
|
+
this.emit("hello", message);
|
|
203
|
+
break;
|
|
204
|
+
case "status":
|
|
205
|
+
if (!message.ready || message.session !== this.#session) {
|
|
206
|
+
for (const pending of this.#requests.values()) {
|
|
207
|
+
pending.reject(new RelapseError("session_changed", "Executor session changed before acknowledgement."));
|
|
208
|
+
}
|
|
209
|
+
this.#requests.clear();
|
|
210
|
+
this.#pending.clear();
|
|
211
|
+
}
|
|
212
|
+
this.#ready = message.ready;
|
|
213
|
+
this.#session = message.session;
|
|
214
|
+
this.emit("status", message);
|
|
215
|
+
break;
|
|
216
|
+
case "exec_result": {
|
|
217
|
+
this.#pending.delete(message.script_id);
|
|
218
|
+
const pending = this.#requests.get(message.script_id);
|
|
219
|
+
this.#requests.delete(message.script_id);
|
|
220
|
+
if (message.phase === "submitted") pending?.resolve();
|
|
221
|
+
else pending?.reject(new RelapseError("execution_failed", message.detail ?? "Execution rejected."));
|
|
222
|
+
this.emit("exec_result", message);
|
|
223
|
+
break;
|
|
224
|
+
}
|
|
225
|
+
case "log":
|
|
226
|
+
this.emit("log", message);
|
|
227
|
+
break;
|
|
228
|
+
case "error":
|
|
229
|
+
this.emit("message", message);
|
|
230
|
+
this.#transport.close(new RelapseError("protocol_error", message.detail));
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
this.emit("message", message);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
#closed(info: CloseInfo): void {
|
|
237
|
+
const error = info.error ?? new RelapseError("disconnected", "Main channel closed.");
|
|
238
|
+
this.#opening.reject(error);
|
|
239
|
+
for (const request of this.#requests.values()) request.reject(error);
|
|
240
|
+
this.#requests.clear();
|
|
241
|
+
this.#pending.clear();
|
|
242
|
+
this.#ready = false;
|
|
243
|
+
this.emit("close", info);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function integer(value: unknown, minimum: number): value is number {
|
|
248
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= minimum;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function validateRequest(value: unknown): MainRequest {
|
|
252
|
+
if (!isRecord(value) || Object.keys(value).some(key =>
|
|
253
|
+
!["op", "script_id", "session", "source", "name"].includes(key))) {
|
|
254
|
+
throw new TypeError("Expected a main-channel execution request with only defined fields.");
|
|
255
|
+
}
|
|
256
|
+
const { op, script_id, session, source, name } = value;
|
|
257
|
+
if (op !== "execute" || !integer(script_id, 1) || !integer(session, 0) || typeof source !== "string" ||
|
|
258
|
+
(name !== undefined && (typeof name !== "string" || Buffer.byteLength(name) > 255))) {
|
|
259
|
+
throw new TypeError("Expected execute, a positive script_id, a session, source text, and an optional name of at most 255 bytes.");
|
|
260
|
+
}
|
|
261
|
+
if (Buffer.from(source).toString("utf8") !== source ||
|
|
262
|
+
(name !== undefined && Buffer.from(name).toString("utf8") !== name)) {
|
|
263
|
+
throw new TypeError("Script source and name must contain valid Unicode.");
|
|
264
|
+
}
|
|
265
|
+
// Copy validated fields so serialization cannot use a caller's toJSON implementation.
|
|
266
|
+
return { op, script_id, session, source, ...(name === undefined ? {} : { name }) };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function parseMessage(value: unknown): MainMessage {
|
|
270
|
+
if (!isRecord(value)) throw new TypeError("Expected an object.");
|
|
271
|
+
switch (value.type) {
|
|
272
|
+
case "hello":
|
|
273
|
+
case "status": {
|
|
274
|
+
const { ready, session } = value;
|
|
275
|
+
if (typeof ready !== "boolean" || !integer(session, ready ? 1 : 0)) break;
|
|
276
|
+
if (value.type === "status") return { type: "status", ready, session };
|
|
277
|
+
if (!integer(value.pid, 1) || typeof value.profile !== "string") break;
|
|
278
|
+
return { type: "hello", ready, session, pid: value.pid, profile: value.profile };
|
|
279
|
+
}
|
|
280
|
+
case "exec_result": {
|
|
281
|
+
const { script_id, phase, detail } = value;
|
|
282
|
+
if (!integer(script_id, 1) || (phase !== "submitted" && phase !== "error") ||
|
|
283
|
+
(detail !== undefined && typeof detail !== "string")) break;
|
|
284
|
+
return { type: "exec_result", script_id, phase, ...(detail === undefined ? {} : { detail }) };
|
|
285
|
+
}
|
|
286
|
+
case "log":
|
|
287
|
+
if (typeof value.level === "string" && typeof value.text === "string") {
|
|
288
|
+
return { type: "log", level: value.level, text: value.text };
|
|
289
|
+
}
|
|
290
|
+
break;
|
|
291
|
+
case "error":
|
|
292
|
+
if (typeof value.detail === "string") return { type: "error", detail: value.detail };
|
|
293
|
+
break;
|
|
294
|
+
}
|
|
295
|
+
throw new TypeError("Invalid main-channel message.");
|
|
296
|
+
}
|
package/src/profiles.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Copyright (C) 2026 vpu007
|
|
2
|
+
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
3
|
+
|
|
4
|
+
import { lstat, mkdir, readdir } from "node:fs/promises";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { isAbsolute, join } from "node:path";
|
|
7
|
+
|
|
8
|
+
export interface ProfileOptions {
|
|
9
|
+
homeDirectory?: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface ProfileInfo {
|
|
13
|
+
name: string;
|
|
14
|
+
directory: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface ProfilePaths {
|
|
18
|
+
directory: string;
|
|
19
|
+
state: string;
|
|
20
|
+
cookies: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function isValidName(name: string): boolean {
|
|
24
|
+
return typeof name === "string" && /^[a-zA-Z0-9._-]{1,64}$/u.test(name) && name !== "." && name !== "..";
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function directory(options: ProfileOptions = {}): string {
|
|
28
|
+
const home = options.homeDirectory ?? homedir();
|
|
29
|
+
if (!isAbsolute(home)) throw new TypeError("homeDirectory must be an absolute path.");
|
|
30
|
+
return join(home, ".local", "share", "relapse", "profiles");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function path(name: string, options: ProfileOptions = {}): string {
|
|
34
|
+
if (!isValidName(name)) {
|
|
35
|
+
throw new TypeError("Profile names must contain 1–64 letters, digits, dots, underscores or hyphens, excluding . and ..");
|
|
36
|
+
}
|
|
37
|
+
return join(directory(options), name);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function paths(name: string, options: ProfileOptions = {}): ProfilePaths {
|
|
41
|
+
const profile = path(name, options);
|
|
42
|
+
return {
|
|
43
|
+
directory: profile,
|
|
44
|
+
state: join(profile, "state"),
|
|
45
|
+
cookies: join(profile, "state", "app", "data", "sober", "cookies"),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function get(name: string, options: ProfileOptions = {}): Promise<ProfileInfo> {
|
|
50
|
+
const profile = path(name, options);
|
|
51
|
+
const stat = await lstat(profile);
|
|
52
|
+
if (!stat.isDirectory()) throw new Error("Profile must be a directory, not a symlink or other file.");
|
|
53
|
+
return { name, directory: profile };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function list(options: ProfileOptions = {}): Promise<ProfileInfo[]> {
|
|
57
|
+
const root = directory(options);
|
|
58
|
+
const entries = await readdir(root, { withFileTypes: true }).catch((error: NodeJS.ErrnoException) => {
|
|
59
|
+
if (error.code === "ENOENT") return [];
|
|
60
|
+
throw error;
|
|
61
|
+
});
|
|
62
|
+
return entries.filter(entry => entry.isDirectory() && isValidName(entry.name))
|
|
63
|
+
.map(entry => ({ name: entry.name, directory: join(root, entry.name) }))
|
|
64
|
+
.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Creates a fresh profile directory. The launcher initializes its state on first use. */
|
|
68
|
+
export async function create(name: string, options: ProfileOptions = {}): Promise<ProfileInfo> {
|
|
69
|
+
const profile = path(name, options);
|
|
70
|
+
const root = directory(options);
|
|
71
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
72
|
+
if (!(await lstat(root)).isDirectory()) throw new Error("Profiles directory must not be a symlink.");
|
|
73
|
+
await mkdir(profile, { mode: 0o700 });
|
|
74
|
+
return { name, directory: profile };
|
|
75
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2022",
|
|
4
|
+
"module": "NodeNext",
|
|
5
|
+
"moduleResolution": "NodeNext",
|
|
6
|
+
"lib": ["ES2022"],
|
|
7
|
+
"types": ["node"],
|
|
8
|
+
"rootDir": "src",
|
|
9
|
+
"outDir": "dist",
|
|
10
|
+
"declaration": true,
|
|
11
|
+
"strict": true,
|
|
12
|
+
"noUncheckedIndexedAccess": true,
|
|
13
|
+
"exactOptionalPropertyTypes": true,
|
|
14
|
+
"verbatimModuleSyntax": true,
|
|
15
|
+
"forceConsistentCasingInFileNames": true,
|
|
16
|
+
"noUnusedLocals": true,
|
|
17
|
+
"noUnusedParameters": true
|
|
18
|
+
},
|
|
19
|
+
"include": ["src/**/*.ts"]
|
|
20
|
+
}
|