relapsesdk 0.0.0-stage → 0.2.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.
Files changed (49) hide show
  1. package/LICENSE +232 -0
  2. package/README.md +2 -2
  3. package/dist/channel.d.ts +33 -0
  4. package/dist/channel.js +39 -0
  5. package/dist/client.d.ts +28 -0
  6. package/dist/client.js +57 -0
  7. package/dist/configuration.d.ts +38 -0
  8. package/dist/configuration.js +251 -0
  9. package/dist/discovery.d.ts +12 -0
  10. package/dist/discovery.js +79 -0
  11. package/dist/errors.d.ts +5 -0
  12. package/dist/errors.js +9 -0
  13. package/dist/index.d.ts +14 -0
  14. package/dist/index.js +10 -0
  15. package/dist/internal/json.d.ts +5 -0
  16. package/dist/internal/json.js +15 -0
  17. package/dist/internal/operation.d.ts +13 -0
  18. package/dist/internal/operation.js +52 -0
  19. package/dist/internal/profile-name.d.ts +1 -0
  20. package/dist/internal/profile-name.js +4 -0
  21. package/dist/internal/transport.d.ts +25 -0
  22. package/dist/internal/transport.js +203 -0
  23. package/dist/internal/wait-for.d.ts +3 -0
  24. package/dist/internal/wait-for.js +35 -0
  25. package/dist/launcher.d.ts +12 -0
  26. package/dist/launcher.js +34 -0
  27. package/dist/main-channel.d.ts +74 -0
  28. package/dist/main-channel.js +233 -0
  29. package/dist/profiles.d.ts +18 -0
  30. package/dist/profiles.js +65 -0
  31. package/examples/channel.mjs +20 -0
  32. package/examples/consumer.ts +134 -0
  33. package/examples/execute.mjs +22 -0
  34. package/package.json +61 -4
  35. package/src/channel.ts +71 -0
  36. package/src/client.ts +76 -0
  37. package/src/configuration.ts +273 -0
  38. package/src/discovery.ts +80 -0
  39. package/src/errors.ts +25 -0
  40. package/src/index.ts +26 -0
  41. package/src/internal/json.ts +25 -0
  42. package/src/internal/operation.ts +69 -0
  43. package/src/internal/profile-name.ts +5 -0
  44. package/src/internal/transport.ts +213 -0
  45. package/src/internal/wait-for.ts +40 -0
  46. package/src/launcher.ts +43 -0
  47. package/src/main-channel.ts +295 -0
  48. package/src/profiles.ts +83 -0
  49. package/tsconfig.json +20 -0
@@ -0,0 +1,203 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+ import { Socket } from "node:net";
3
+ import { isAbsolute } from "node:path";
4
+ import { RelapseError } from "../errors.js";
5
+ import { encodeJson, isRecord } from "./json.js";
6
+ import { operation } from "./operation.js";
7
+ const MAX_MESSAGE_BYTES = 8 * 1024 * 1024;
8
+ const MAX_QUEUED_BYTES = 16 * 1024 * 1024;
9
+ const MAX_QUEUED_MESSAGES = 256;
10
+ const MAX_OPENING_BYTES = 4096;
11
+ export class Transport {
12
+ socketPath;
13
+ name;
14
+ #socket = new Socket();
15
+ #handlers;
16
+ #header = Buffer.alloc(4);
17
+ #writes = new Set();
18
+ #opening;
19
+ #opened = false;
20
+ #closed = false;
21
+ #paused = false;
22
+ #headerUsed = 0;
23
+ #body;
24
+ #bodyUsed = 0;
25
+ #rest;
26
+ #queuedBytes = 0;
27
+ #maxMessageBytes = MAX_OPENING_BYTES;
28
+ constructor(socketPath, name, handlers) {
29
+ this.socketPath = socketPath;
30
+ this.name = name;
31
+ if (!isAbsolute(socketPath) || socketPath.includes("\0") || Buffer.byteLength(socketPath) >= 108) {
32
+ throw new TypeError("Expected an absolute Unix socket path shorter than 108 bytes.");
33
+ }
34
+ if (!name || Buffer.byteLength(name) > 255 || /[\x00-\x1f\x7f]/u.test(name) ||
35
+ Buffer.from(name).toString("utf8") !== name) {
36
+ throw new TypeError("Channel names must contain 1–255 UTF-8 bytes without control characters.");
37
+ }
38
+ this.#handlers = handlers;
39
+ this.#socket.on("data", (data) => this.#receive(data));
40
+ this.#socket.on("error", error => {
41
+ this.#finish({ reason: "error", error: new RelapseError(this.#opened ? "disconnected" : "connection_failed", error.message, { cause: error }) });
42
+ });
43
+ this.#socket.on("end", () => {
44
+ if (this.#headerUsed || this.#body)
45
+ this.#invalid("Connection ended in the middle of a frame.");
46
+ else
47
+ this.#finish({ reason: "peer" });
48
+ });
49
+ this.#socket.on("close", () => this.#finish({ reason: "peer" }));
50
+ }
51
+ get connected() { return this.#opened && !this.#closed; }
52
+ get maxMessageBytes() { return this.#maxMessageBytes; }
53
+ async open(options) {
54
+ this.#opening = operation(options, 5000);
55
+ try {
56
+ if (!this.#opening.settled) {
57
+ this.#socket.connect(this.socketPath, () => {
58
+ const body = encodeJson({ version: 1, channel: this.name });
59
+ this.#socket.write(this.#frame(body));
60
+ });
61
+ }
62
+ await this.#opening.promise;
63
+ }
64
+ catch (error) {
65
+ this.#finish({ reason: "error", error: error instanceof RelapseError ? error :
66
+ new RelapseError("connection_failed", "Could not connect to Relapse.", { cause: error }) });
67
+ throw error;
68
+ }
69
+ }
70
+ pause() {
71
+ this.#paused = true;
72
+ this.#socket.pause();
73
+ }
74
+ resume() {
75
+ if (this.#closed)
76
+ return;
77
+ this.#paused = false;
78
+ const rest = this.#rest;
79
+ this.#rest = undefined;
80
+ if (rest)
81
+ this.#receive(rest);
82
+ if (!this.#paused && !this.#closed)
83
+ this.#socket.resume();
84
+ }
85
+ async send(value) {
86
+ if (!this.connected)
87
+ throw new RelapseError("disconnected", "Channel is closed.");
88
+ const body = encodeJson(value);
89
+ if (body.length > this.#maxMessageBytes) {
90
+ throw new RelapseError("message_too_large", `Message exceeds ${this.#maxMessageBytes} bytes.`);
91
+ }
92
+ const size = body.length + 4;
93
+ if (this.#writes.size >= MAX_QUEUED_MESSAGES || this.#queuedBytes + size > MAX_QUEUED_BYTES) {
94
+ throw new RelapseError("backpressure", "Channel send queue is full.");
95
+ }
96
+ await new Promise((resolve, reject) => {
97
+ const fail = (error) => reject(error);
98
+ this.#writes.add(fail);
99
+ this.#queuedBytes += size;
100
+ this.#socket.write(this.#frame(body), error => {
101
+ this.#writes.delete(fail);
102
+ this.#queuedBytes -= size;
103
+ if (error)
104
+ reject(new RelapseError("disconnected", error.message, { cause: error }));
105
+ else
106
+ resolve();
107
+ });
108
+ });
109
+ }
110
+ close(error) {
111
+ this.#finish(error ? { reason: "error", error } : { reason: "local" });
112
+ }
113
+ #frame(body) {
114
+ const frame = Buffer.allocUnsafe(body.length + 4);
115
+ frame.writeUInt32BE(body.length);
116
+ body.copy(frame, 4);
117
+ return frame;
118
+ }
119
+ #receive(data) {
120
+ let offset = 0;
121
+ while (offset < data.length && !this.#closed) {
122
+ if (this.#paused) {
123
+ this.#rest = data.subarray(offset);
124
+ return;
125
+ }
126
+ if (this.#headerUsed < 4) {
127
+ const amount = Math.min(4 - this.#headerUsed, data.length - offset);
128
+ data.copy(this.#header, this.#headerUsed, offset, offset + amount);
129
+ offset += amount;
130
+ this.#headerUsed += amount;
131
+ if (this.#headerUsed < 4)
132
+ return;
133
+ const size = this.#header.readUInt32BE();
134
+ if (size === 0 || size > this.#maxMessageBytes) {
135
+ this.#invalid("Invalid channel frame length.");
136
+ return;
137
+ }
138
+ this.#body = Buffer.allocUnsafe(size);
139
+ }
140
+ const body = this.#body;
141
+ const amount = Math.min(body.length - this.#bodyUsed, data.length - offset);
142
+ data.copy(body, this.#bodyUsed, offset, offset + amount);
143
+ offset += amount;
144
+ this.#bodyUsed += amount;
145
+ if (this.#bodyUsed < body.length)
146
+ return;
147
+ this.#headerUsed = this.#bodyUsed = 0;
148
+ this.#body = undefined;
149
+ let message;
150
+ try {
151
+ message = JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(body));
152
+ }
153
+ catch {
154
+ this.#invalid("Expected a UTF-8 JSON message.");
155
+ return;
156
+ }
157
+ if (!this.#opened)
158
+ this.#handshake(message);
159
+ else
160
+ this.#handlers.message(message);
161
+ }
162
+ }
163
+ #handshake(message) {
164
+ if (!isRecord(message) || typeof message.ok !== "boolean") {
165
+ this.#invalid("Expected a channel handshake response.");
166
+ return;
167
+ }
168
+ if (!message.ok) {
169
+ if (typeof message.error !== "string")
170
+ this.#invalid("Invalid channel rejection.");
171
+ else
172
+ this.close(new RelapseError("channel_rejected", message.error));
173
+ return;
174
+ }
175
+ if (message.version !== 1 || typeof message.max_message_bytes !== "number" ||
176
+ !Number.isInteger(message.max_message_bytes) || message.max_message_bytes <= 0 ||
177
+ message.max_message_bytes > 0xffff_ffff) {
178
+ this.#invalid("Unsupported channel version or invalid message limit.");
179
+ return;
180
+ }
181
+ this.#maxMessageBytes = Math.min(message.max_message_bytes, MAX_MESSAGE_BYTES);
182
+ this.#opened = true;
183
+ // Let connect() callers attach listeners before delivering coalesced frames.
184
+ this.pause();
185
+ this.#opening?.resolve();
186
+ }
187
+ #invalid(message) {
188
+ this.close(new RelapseError("protocol_error", message));
189
+ }
190
+ #finish(info) {
191
+ if (this.#closed)
192
+ return;
193
+ this.#closed = true;
194
+ const error = info.error ?? new RelapseError("disconnected", "Channel closed.");
195
+ this.#opening?.reject(error);
196
+ for (const fail of this.#writes)
197
+ fail(error);
198
+ this.#writes.clear();
199
+ this.#body = this.#rest = undefined;
200
+ this.#socket.destroy();
201
+ this.#handlers.close(info);
202
+ }
203
+ }
@@ -0,0 +1,3 @@
1
+ import type { EventEmitter } from "node:events";
2
+ import { type WaitOptions } from "./operation.js";
3
+ export declare function waitForEvent<T>(source: EventEmitter, event: string, connected: boolean, predicate: ((value: T) => boolean) | undefined, options: WaitOptions): Promise<T>;
@@ -0,0 +1,35 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+ import { RelapseError } from "../errors.js";
3
+ import { operation } from "./operation.js";
4
+ export async function waitForEvent(source, event, connected, predicate, options) {
5
+ const wait = operation(options, 30_000);
6
+ const receive = (value) => {
7
+ if (wait.settled)
8
+ return;
9
+ try {
10
+ if (!predicate || predicate(value))
11
+ wait.resolve(value);
12
+ }
13
+ catch (error) {
14
+ wait.reject(error);
15
+ }
16
+ };
17
+ const closed = (info) => {
18
+ wait.reject(info.error ?? new RelapseError("disconnected", "Channel closed before the event arrived."));
19
+ };
20
+ if (!wait.settled) {
21
+ if (!connected)
22
+ wait.reject(new RelapseError("disconnected", "Channel is closed."));
23
+ else {
24
+ source.on(event, receive);
25
+ source.on("close", closed);
26
+ }
27
+ }
28
+ try {
29
+ return await wait.promise;
30
+ }
31
+ finally {
32
+ source.off(event, receive);
33
+ source.off("close", closed);
34
+ }
35
+ }
@@ -0,0 +1,12 @@
1
+ import { type ChildProcess } from "node:child_process";
2
+ export interface LaunchOptions {
3
+ profile: string;
4
+ launcherPath?: string;
5
+ placeId?: string;
6
+ jobId?: string;
7
+ env?: NodeJS.ProcessEnv;
8
+ /** Defaults to ignore. Use pipe to consume the launcher's stdout and stderr. */
9
+ stdio?: "ignore" | "inherit" | "pipe";
10
+ }
11
+ /** Resolves when the launcher process starts, before a client or executor is necessarily ready. */
12
+ export declare function launch(options: LaunchOptions): Promise<ChildProcess>;
@@ -0,0 +1,34 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+ import { spawn } from "node:child_process";
3
+ import { once } from "node:events";
4
+ import { isValidName } from "./profiles.js";
5
+ /** Resolves when the launcher process starts, before a client or executor is necessarily ready. */
6
+ export async function launch(options) {
7
+ if (!isValidName(options.profile))
8
+ throw new TypeError("Invalid profile name.");
9
+ const launcher = options.launcherPath ?? "relapse-launcher";
10
+ if (!launcher || launcher.includes("\0"))
11
+ throw new TypeError("Invalid launcher executable.");
12
+ const args = ["--profile", options.profile, "--no-launch-ui"];
13
+ const place = options.placeId?.trim() ?? "";
14
+ const job = options.jobId?.trim() ?? "";
15
+ if (!place && job)
16
+ throw new TypeError("A Job ID requires a Place ID.");
17
+ if (place) {
18
+ if (!/^[0-9]+$/u.test(place) || BigInt(place) < 1n || BigInt(place) > 0x7fffffffffffffffn) {
19
+ throw new TypeError("Place ID must be a positive 64-bit integer string.");
20
+ }
21
+ if (job && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(job)) {
22
+ throw new TypeError("Job ID must be a UUID.");
23
+ }
24
+ const uri = `roblox://placeId=${BigInt(place)}${job ? `&gameInstanceId=${job}` : ""}`;
25
+ args.push("--", uri);
26
+ }
27
+ const env = { ...(options.env ?? process.env) };
28
+ delete env.LD_PRELOAD;
29
+ delete env.LD_AUDIT;
30
+ delete env.LD_LIBRARY_PATH;
31
+ const child = spawn(launcher, args, { env, stdio: options.stdio ?? "ignore" });
32
+ await once(child, "spawn");
33
+ return child;
34
+ }
@@ -0,0 +1,74 @@
1
+ import { EventEmitter } from "node:events";
2
+ import type { ChannelConnection } from "./channel.js";
3
+ import { type WaitOptions } from "./internal/operation.js";
4
+ import { type CloseInfo } from "./internal/transport.js";
5
+ export interface MainChannelOptions extends WaitOptions {
6
+ socketPath: string;
7
+ }
8
+ export interface ExecuteOptions extends WaitOptions {
9
+ name?: string;
10
+ }
11
+ export type MainRequest = {
12
+ op: "execute";
13
+ script_id: number;
14
+ session: number;
15
+ source: string;
16
+ name?: string;
17
+ };
18
+ export interface MainHello {
19
+ type: "hello";
20
+ pid: number;
21
+ profile: string;
22
+ ready: boolean;
23
+ session: number;
24
+ }
25
+ export interface MainStatus {
26
+ type: "status";
27
+ ready: boolean;
28
+ session: number;
29
+ }
30
+ export interface ExecutionResult {
31
+ type: "exec_result";
32
+ script_id: number;
33
+ phase: "submitted" | "error";
34
+ detail?: string;
35
+ }
36
+ export interface LogEntry {
37
+ type: "log";
38
+ level: string;
39
+ text: string;
40
+ }
41
+ export interface MainError {
42
+ type: "error";
43
+ detail: string;
44
+ }
45
+ export type MainMessage = MainHello | MainStatus | ExecutionResult | LogEntry | MainError;
46
+ export interface MainChannelEvents {
47
+ message: [message: MainMessage];
48
+ hello: [message: MainHello];
49
+ status: [message: MainStatus];
50
+ exec_result: [message: ExecutionResult];
51
+ log: [message: LogEntry];
52
+ close: [info: CloseInfo];
53
+ }
54
+ export declare class MainChannel extends EventEmitter<MainChannelEvents> implements ChannelConnection {
55
+ #private;
56
+ private constructor();
57
+ /** Connects to @main and receives its initial hello, which may report ready: false. */
58
+ static connect(options: MainChannelOptions): Promise<MainChannel>;
59
+ get socketPath(): string;
60
+ get name(): "@main";
61
+ get connected(): boolean;
62
+ get maxMessageBytes(): number;
63
+ get hello(): Readonly<MainHello>;
64
+ get ready(): boolean;
65
+ get session(): number;
66
+ /** Validates and writes a request. Execution acknowledgements arrive as exec_result events. */
67
+ send(value: MainRequest): Promise<void>;
68
+ /** Waits for a future matching event. Check ready before waiting for a readiness transition. */
69
+ waitFor<K extends keyof MainChannelEvents>(event: K, predicate?: (value: MainChannelEvents[K][0]) => boolean, options?: WaitOptions): Promise<MainChannelEvents[K][0]>;
70
+ /** Resolves on submission, not script completion. Timeout/abort cannot undo submission. */
71
+ execute(source: string, options?: ExecuteOptions): Promise<void>;
72
+ executeFile(path: string, options?: ExecuteOptions): Promise<void>;
73
+ close(): void;
74
+ }
@@ -0,0 +1,233 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+ import { EventEmitter } from "node:events";
3
+ import { readFile } from "node:fs/promises";
4
+ import { basename } from "node:path";
5
+ import { RelapseError } from "./errors.js";
6
+ import { isRecord } from "./internal/json.js";
7
+ import { operation } from "./internal/operation.js";
8
+ import { Transport } from "./internal/transport.js";
9
+ import { waitForEvent } from "./internal/wait-for.js";
10
+ export class MainChannel extends EventEmitter {
11
+ #transport;
12
+ #opening;
13
+ #requests = new Map();
14
+ #pending = new Set();
15
+ #hello;
16
+ #ready = false;
17
+ #session = 0;
18
+ #nextId = 1;
19
+ constructor(options, opening) {
20
+ super();
21
+ this.#opening = opening;
22
+ this.#transport = new Transport(options.socketPath, "@main", {
23
+ message: message => this.#receive(message),
24
+ close: info => this.#closed(info),
25
+ });
26
+ }
27
+ /** Connects to @main and receives its initial hello, which may report ready: false. */
28
+ static async connect(options) {
29
+ const opening = operation(options, 5000);
30
+ let channel;
31
+ try {
32
+ channel = new MainChannel(options, opening);
33
+ }
34
+ catch (error) {
35
+ opening.resolve();
36
+ await opening.promise.catch(() => { });
37
+ throw error;
38
+ }
39
+ try {
40
+ await Promise.all([
41
+ channel.#transport.open(options).then(() => channel.#transport.resume()),
42
+ opening.promise,
43
+ ]);
44
+ setImmediate(() => channel.#transport.resume());
45
+ return channel;
46
+ }
47
+ catch (error) {
48
+ channel.close();
49
+ throw error;
50
+ }
51
+ }
52
+ get socketPath() { return this.#transport.socketPath; }
53
+ get name() { return "@main"; }
54
+ get connected() { return this.#transport.connected; }
55
+ get maxMessageBytes() { return this.#transport.maxMessageBytes; }
56
+ get hello() { return this.#hello; }
57
+ get ready() { return this.connected && this.#ready; }
58
+ get session() { return this.#session; }
59
+ /** Validates and writes a request. Execution acknowledgements arrive as exec_result events. */
60
+ async send(value) {
61
+ const request = validateRequest(value);
62
+ if (!this.connected)
63
+ throw new RelapseError("disconnected", "Main channel is closed.");
64
+ if (!this.ready)
65
+ throw new RelapseError("not_ready", "Executor is not ready.");
66
+ if (request.session !== this.#session)
67
+ throw new RelapseError("session_changed", "Request targets a different executor session.");
68
+ if (this.#pending.has(request.script_id))
69
+ throw new TypeError("This execution request ID is already pending.");
70
+ if (this.#pending.size >= 16)
71
+ throw new RelapseError("backpressure", "Too many pending executions.");
72
+ this.#pending.add(request.script_id);
73
+ this.#nextId = Math.max(this.#nextId, request.script_id + 1);
74
+ try {
75
+ await this.#transport.send(request);
76
+ }
77
+ catch (error) {
78
+ this.#pending.delete(request.script_id);
79
+ throw error;
80
+ }
81
+ }
82
+ /** Waits for a future matching event. Check ready before waiting for a readiness transition. */
83
+ waitFor(event, predicate, options = {}) {
84
+ return waitForEvent(this, event, this.connected, predicate, options);
85
+ }
86
+ /** Resolves on submission, not script completion. Timeout/abort cannot undo submission. */
87
+ async execute(source, options = {}) {
88
+ if (this.#nextId > Number.MAX_SAFE_INTEGER)
89
+ throw new RangeError("Execution request IDs exhausted.");
90
+ const request = operation(options, 10_000);
91
+ const id = this.#nextId++;
92
+ if (!request.settled) {
93
+ this.#requests.set(id, request);
94
+ this.send({
95
+ op: "execute", script_id: id, session: this.#session,
96
+ source, name: options.name ?? "relapse",
97
+ }).catch(error => request.reject(error));
98
+ }
99
+ try {
100
+ await request.promise;
101
+ }
102
+ finally {
103
+ this.#requests.delete(id);
104
+ }
105
+ }
106
+ async executeFile(path, options = {}) {
107
+ const source = await readFile(path, {
108
+ encoding: "utf8",
109
+ ...(options.signal ? { signal: options.signal } : {}),
110
+ });
111
+ await this.execute(source, { ...options, name: options.name ?? basename(path) });
112
+ }
113
+ close() {
114
+ this.#transport.close();
115
+ }
116
+ #receive(value) {
117
+ let message;
118
+ try {
119
+ message = parseMessage(value);
120
+ if ((!this.#hello && message.type !== "hello") || (this.#hello && message.type === "hello")) {
121
+ throw new TypeError("Expected one initial hello message.");
122
+ }
123
+ }
124
+ catch (error) {
125
+ this.#transport.close(new RelapseError("protocol_error", "Invalid @main message.", { cause: error }));
126
+ return;
127
+ }
128
+ switch (message.type) {
129
+ case "hello":
130
+ this.#hello = Object.freeze(message);
131
+ this.#ready = message.ready;
132
+ this.#session = message.session;
133
+ this.#transport.pause();
134
+ this.#opening.resolve();
135
+ this.emit("hello", message);
136
+ break;
137
+ case "status":
138
+ if (!message.ready || message.session !== this.#session) {
139
+ for (const pending of this.#requests.values()) {
140
+ pending.reject(new RelapseError("session_changed", "Executor session changed before acknowledgement."));
141
+ }
142
+ this.#requests.clear();
143
+ this.#pending.clear();
144
+ }
145
+ this.#ready = message.ready;
146
+ this.#session = message.session;
147
+ this.emit("status", message);
148
+ break;
149
+ case "exec_result": {
150
+ this.#pending.delete(message.script_id);
151
+ const pending = this.#requests.get(message.script_id);
152
+ this.#requests.delete(message.script_id);
153
+ if (message.phase === "submitted")
154
+ pending?.resolve();
155
+ else
156
+ pending?.reject(new RelapseError("execution_failed", message.detail ?? "Execution rejected."));
157
+ this.emit("exec_result", message);
158
+ break;
159
+ }
160
+ case "log":
161
+ this.emit("log", message);
162
+ break;
163
+ case "error":
164
+ this.emit("message", message);
165
+ this.#transport.close(new RelapseError("protocol_error", message.detail));
166
+ return;
167
+ }
168
+ this.emit("message", message);
169
+ }
170
+ #closed(info) {
171
+ const error = info.error ?? new RelapseError("disconnected", "Main channel closed.");
172
+ this.#opening.reject(error);
173
+ for (const request of this.#requests.values())
174
+ request.reject(error);
175
+ this.#requests.clear();
176
+ this.#pending.clear();
177
+ this.#ready = false;
178
+ this.emit("close", info);
179
+ }
180
+ }
181
+ function integer(value, minimum) {
182
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= minimum;
183
+ }
184
+ function validateRequest(value) {
185
+ if (!isRecord(value) || Object.keys(value).some(key => !["op", "script_id", "session", "source", "name"].includes(key))) {
186
+ throw new TypeError("Expected a main-channel execution request with only defined fields.");
187
+ }
188
+ const { op, script_id, session, source, name } = value;
189
+ if (op !== "execute" || !integer(script_id, 1) || !integer(session, 0) || typeof source !== "string" ||
190
+ (name !== undefined && (typeof name !== "string" || Buffer.byteLength(name) > 255))) {
191
+ throw new TypeError("Expected execute, a positive script_id, a session, source text, and an optional name of at most 255 bytes.");
192
+ }
193
+ if (Buffer.from(source).toString("utf8") !== source ||
194
+ (name !== undefined && Buffer.from(name).toString("utf8") !== name)) {
195
+ throw new TypeError("Script source and name must contain valid Unicode.");
196
+ }
197
+ // Copy validated fields so serialization cannot use a caller's toJSON implementation.
198
+ return { op, script_id, session, source, ...(name === undefined ? {} : { name }) };
199
+ }
200
+ function parseMessage(value) {
201
+ if (!isRecord(value))
202
+ throw new TypeError("Expected an object.");
203
+ switch (value.type) {
204
+ case "hello":
205
+ case "status": {
206
+ const { ready, session } = value;
207
+ if (typeof ready !== "boolean" || !integer(session, ready ? 1 : 0))
208
+ break;
209
+ if (value.type === "status")
210
+ return { type: "status", ready, session };
211
+ if (!integer(value.pid, 1) || typeof value.profile !== "string")
212
+ break;
213
+ return { type: "hello", ready, session, pid: value.pid, profile: value.profile };
214
+ }
215
+ case "exec_result": {
216
+ const { script_id, phase, detail } = value;
217
+ if (!integer(script_id, 1) || (phase !== "submitted" && phase !== "error") ||
218
+ (detail !== undefined && typeof detail !== "string"))
219
+ break;
220
+ return { type: "exec_result", script_id, phase, ...(detail === undefined ? {} : { detail }) };
221
+ }
222
+ case "log":
223
+ if (typeof value.level === "string" && typeof value.text === "string") {
224
+ return { type: "log", level: value.level, text: value.text };
225
+ }
226
+ break;
227
+ case "error":
228
+ if (typeof value.detail === "string")
229
+ return { type: "error", detail: value.detail };
230
+ break;
231
+ }
232
+ throw new TypeError("Invalid main-channel message.");
233
+ }
@@ -0,0 +1,18 @@
1
+ import { type ConfigurationOptions } from "./configuration.js";
2
+ export { isValidName } from "./internal/profile-name.js";
3
+ export type ProfileOptions = ConfigurationOptions;
4
+ export interface ProfileInfo {
5
+ name: string;
6
+ dataDir: string;
7
+ configFile: string;
8
+ }
9
+ export interface ProfilePaths {
10
+ dataDir: string;
11
+ state: string;
12
+ cookies: string;
13
+ configFile: string;
14
+ }
15
+ export declare function paths(name: string, options?: ProfileOptions): Promise<ProfilePaths>;
16
+ export declare function get(name: string, options?: ProfileOptions): Promise<ProfileInfo>;
17
+ export declare function list(options?: ProfileOptions): Promise<ProfileInfo[]>;
18
+ export declare function create(name: string, options?: ProfileOptions): Promise<ProfileInfo>;
@@ -0,0 +1,65 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+ import { lstat, mkdir, readdir } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { configDirectory, dataDirectory, profilePath as configurationPath, resolve as resolveConfiguration, writeProfile, } from "./configuration.js";
5
+ import { isValidName } from "./internal/profile-name.js";
6
+ export { isValidName } from "./internal/profile-name.js";
7
+ function info(name, dataDir, options) {
8
+ return { name, dataDir, configFile: configurationPath(name, options) };
9
+ }
10
+ export async function paths(name, options = {}) {
11
+ const configuration = await resolveConfiguration(name, options);
12
+ return {
13
+ dataDir: configuration.dataDir,
14
+ state: join(configuration.dataDir, "state"),
15
+ cookies: join(configuration.dataDir, "state", "app", "data", "sober", "cookies"),
16
+ configFile: configurationPath(name, options),
17
+ };
18
+ }
19
+ export async function get(name, options = {}) {
20
+ const configFile = configurationPath(name, options);
21
+ const configured = await lstat(configFile);
22
+ if (!configured.isFile())
23
+ throw new Error("Profile configuration must be a regular file.");
24
+ const configuration = await resolveConfiguration(name, options);
25
+ return info(name, configuration.dataDir, options);
26
+ }
27
+ export async function list(options = {}) {
28
+ const root = join(configDirectory(options), "profiles");
29
+ const entries = await readdir(root, { withFileTypes: true }).catch((error) => {
30
+ if (error.code === "ENOENT")
31
+ return [];
32
+ throw error;
33
+ });
34
+ const names = entries.filter(entry => entry.isDirectory() && isValidName(entry.name))
35
+ .map(entry => entry.name).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
36
+ const result = [];
37
+ for (const name of names) {
38
+ try {
39
+ result.push(await get(name, options));
40
+ }
41
+ catch (error) {
42
+ if (error.code !== "ENOENT")
43
+ throw error;
44
+ }
45
+ }
46
+ return result;
47
+ }
48
+ export async function create(name, options = {}) {
49
+ const configFile = configurationPath(name, options);
50
+ const root = join(dataDirectory(options), "profiles");
51
+ const dataDir = join(root, name);
52
+ const configured = await lstat(configFile).catch((error) => {
53
+ if (error.code === "ENOENT")
54
+ return undefined;
55
+ throw error;
56
+ });
57
+ if (configured)
58
+ throw new Error("Profile already exists.");
59
+ await mkdir(root, { recursive: true, mode: 0o700 });
60
+ if (!(await lstat(root)).isDirectory())
61
+ throw new Error("Profiles directory must not be a symlink.");
62
+ await mkdir(dataDir, { mode: 0o700 });
63
+ await writeProfile(name, { dataDir, override: {} }, options);
64
+ return info(name, dataDir, options);
65
+ }