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,251 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+ import { readFile, mkdir, rename, unlink, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { dirname, isAbsolute, join } from "node:path";
5
+ import { isValidName } from "./internal/profile-name.js";
6
+ import { isRecord } from "./internal/json.js";
7
+ export function configDirectory(options = {}) {
8
+ const home = options.homeDirectory ?? process.env.HOME ?? homedir();
9
+ if (!isAbsolute(home))
10
+ throw new TypeError("homeDirectory must be an absolute path.");
11
+ const configured = options.configHome ?? process.env.XDG_CONFIG_HOME;
12
+ const root = configured ? configured : join(home, ".config");
13
+ if (!isAbsolute(root))
14
+ throw new TypeError("configHome must be an absolute path.");
15
+ return join(root, "relapse");
16
+ }
17
+ export function dataDirectory(options = {}) {
18
+ const home = options.homeDirectory ?? process.env.HOME ?? homedir();
19
+ if (!isAbsolute(home))
20
+ throw new TypeError("homeDirectory must be an absolute path.");
21
+ const configured = options.dataHome ?? process.env.XDG_DATA_HOME;
22
+ const root = configured ? configured : join(home, ".local", "share");
23
+ if (!isAbsolute(root))
24
+ throw new TypeError("dataHome must be an absolute path.");
25
+ return join(root, "relapse");
26
+ }
27
+ export function globalPath(options = {}) {
28
+ return join(configDirectory(options), "config.json");
29
+ }
30
+ export function profilePath(name, options = {}) {
31
+ if (!isValidName(name))
32
+ throw new TypeError("Invalid profile name.");
33
+ return join(configDirectory(options), "profiles", name, "config.json");
34
+ }
35
+ function stripComments(text) {
36
+ let result = "";
37
+ let quoted = false;
38
+ let escaped = false;
39
+ let lineComment = false;
40
+ let blockComment = false;
41
+ for (let index = 0; index < text.length; index++) {
42
+ const character = text[index];
43
+ const next = text[index + 1];
44
+ if (lineComment) {
45
+ if (character === "\n") {
46
+ result += character;
47
+ lineComment = false;
48
+ }
49
+ else
50
+ result += " ";
51
+ }
52
+ else if (blockComment) {
53
+ if (character === "*" && next === "/") {
54
+ result += " ";
55
+ index++;
56
+ blockComment = false;
57
+ }
58
+ else
59
+ result += character === "\n" ? "\n" : " ";
60
+ }
61
+ else if (quoted) {
62
+ result += character;
63
+ if (escaped)
64
+ escaped = false;
65
+ else if (character === "\\")
66
+ escaped = true;
67
+ else if (character === '"')
68
+ quoted = false;
69
+ }
70
+ else if (character === '"') {
71
+ result += character;
72
+ quoted = true;
73
+ }
74
+ else if (character === "/" && next === "/") {
75
+ result += " ";
76
+ index++;
77
+ lineComment = true;
78
+ }
79
+ else if (character === "/" && next === "*") {
80
+ result += " ";
81
+ index++;
82
+ blockComment = true;
83
+ }
84
+ else
85
+ result += character;
86
+ }
87
+ return result;
88
+ }
89
+ async function readObject(path) {
90
+ const text = await readFile(path, "utf8").catch((error) => {
91
+ if (error.code === "ENOENT")
92
+ return undefined;
93
+ throw error;
94
+ });
95
+ if (text === undefined)
96
+ return {};
97
+ if (Buffer.byteLength(text) > 1024 * 1024 || text.includes("\0")) {
98
+ throw new Error("Configuration must be UTF-8 JSON smaller than 1 MiB.");
99
+ }
100
+ const value = JSON.parse(stripComments(text));
101
+ if (!isRecord(value))
102
+ throw new TypeError("Relapse configuration must be a JSON object.");
103
+ return value;
104
+ }
105
+ async function writeObject(path, value) {
106
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
107
+ const temporary = `${path}.tmp.${process.pid}.${Date.now()}`;
108
+ try {
109
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, {
110
+ encoding: "utf8", flag: "wx", mode: 0o600,
111
+ });
112
+ await rename(temporary, path);
113
+ }
114
+ finally {
115
+ await unlink(temporary).catch((error) => {
116
+ if (error.code !== "ENOENT")
117
+ throw error;
118
+ });
119
+ }
120
+ }
121
+ function validatePath(value, key) {
122
+ if (value !== undefined && (typeof value !== "string" || !value || !isAbsolute(value))) {
123
+ throw new TypeError(`${key} must be an absolute path.`);
124
+ }
125
+ }
126
+ function validateAutolaunch(value) {
127
+ if (value === undefined || value === null)
128
+ return;
129
+ if (!Array.isArray(value) || !value.length || value.some(argument => typeof argument !== "string") || !value[0]) {
130
+ throw new TypeError("autolaunch must be null or a nonempty string array.");
131
+ }
132
+ }
133
+ function validateGlobal(configuration) {
134
+ if (configuration.defaultProfile !== undefined && !isValidName(configuration.defaultProfile)) {
135
+ throw new TypeError("defaultProfile must be a valid profile name.");
136
+ }
137
+ validatePath(configuration.workspace, "workspace");
138
+ validatePath(configuration.autoexec, "autoexec");
139
+ validateAutolaunch(configuration.autolaunch);
140
+ }
141
+ function validateProfile(configuration) {
142
+ validatePath(configuration.dataDir, "dataDir");
143
+ if (configuration.override !== undefined) {
144
+ if (!isRecord(configuration.override))
145
+ throw new TypeError("Profile override must be an object.");
146
+ validatePath(configuration.override.workspace, "override.workspace");
147
+ validatePath(configuration.override.autoexec, "override.autoexec");
148
+ validateAutolaunch(configuration.override.autolaunch);
149
+ }
150
+ }
151
+ export async function readGlobal(options = {}) {
152
+ return await readObject(globalPath(options));
153
+ }
154
+ export async function readProfile(name, options = {}) {
155
+ return await readObject(profilePath(name, options));
156
+ }
157
+ export async function writeGlobal(configuration, options = {}) {
158
+ if (!isRecord(configuration))
159
+ throw new TypeError("Global configuration must be an object.");
160
+ validateGlobal(configuration);
161
+ await writeObject(globalPath(options), configuration);
162
+ }
163
+ export async function writeProfile(name, configuration, options = {}) {
164
+ if (!isValidName(name))
165
+ throw new TypeError("Invalid profile name.");
166
+ if (!isRecord(configuration))
167
+ throw new TypeError("Profile configuration must be an object.");
168
+ validateProfile(configuration);
169
+ await writeObject(profilePath(name, options), configuration);
170
+ }
171
+ function merge(target, overrides) {
172
+ for (const [key, value] of Object.entries(overrides)) {
173
+ const current = target[key];
174
+ target[key] = isRecord(current) && isRecord(value)
175
+ ? merge({ ...current }, value)
176
+ : value;
177
+ }
178
+ return target;
179
+ }
180
+ function resolvedPath(object, key, fallback) {
181
+ const value = object[key];
182
+ if (value === undefined)
183
+ return fallback;
184
+ validatePath(value, key);
185
+ return value;
186
+ }
187
+ function environmentName(path) {
188
+ let name = "RELAPSE_";
189
+ for (const character of path) {
190
+ if (character === "." || character === "-")
191
+ name += "_";
192
+ else if (/[a-zA-Z0-9_]/u.test(character))
193
+ name += character.toUpperCase();
194
+ else
195
+ throw new TypeError(`Executor configuration key has unsupported characters: ${path}`);
196
+ }
197
+ return name;
198
+ }
199
+ function flatten(object, prefix, environment) {
200
+ for (const [key, value] of Object.entries(object)) {
201
+ const path = prefix ? `${prefix}.${key}` : key;
202
+ if (isRecord(value)) {
203
+ flatten(value, path, environment);
204
+ continue;
205
+ }
206
+ let encoded;
207
+ if (typeof value === "boolean")
208
+ encoded = value ? "1" : "0";
209
+ else if (typeof value === "string")
210
+ encoded = value;
211
+ else if (typeof value === "number" && Number.isFinite(value))
212
+ encoded = JSON.stringify(value);
213
+ else
214
+ throw new TypeError(`Executor configuration values must be scalar: ${path}`);
215
+ environment[environmentName(path)] = encoded;
216
+ }
217
+ }
218
+ export async function resolve(requestedProfile, options = {}) {
219
+ const [global, profileConfiguration] = await Promise.all([readGlobal(options),
220
+ requestedProfile ? readProfile(requestedProfile, options) : undefined]);
221
+ let profile = requestedProfile;
222
+ if (!profile) {
223
+ const selected = global.defaultProfile === undefined ? "Default" : global.defaultProfile;
224
+ if (typeof selected !== "string")
225
+ throw new TypeError("defaultProfile must be a string.");
226
+ profile = selected;
227
+ }
228
+ if (!isValidName(profile))
229
+ throw new TypeError("Invalid profile name.");
230
+ const selectedConfiguration = requestedProfile ? profileConfiguration : await readProfile(profile, options);
231
+ const overrides = selectedConfiguration.override === undefined ? {} : selectedConfiguration.override;
232
+ if (!isRecord(overrides))
233
+ throw new TypeError("Profile override must be an object.");
234
+ const defaultDataDir = join(dataDirectory(options), "profiles", profile);
235
+ const dataDir = selectedConfiguration.dataDir === undefined ? defaultDataDir : selectedConfiguration.dataDir;
236
+ validatePath(dataDir, "dataDir");
237
+ const merged = merge({ ...global }, overrides);
238
+ delete merged.defaultProfile;
239
+ const workspace = resolvedPath(merged, "workspace", join(dataDirectory(options), "workspace"));
240
+ const autoexec = resolvedPath(merged, "autoexec", join(configDirectory(options), "autoexec"));
241
+ const command = merged.autolaunch;
242
+ validateAutolaunch(command);
243
+ const autolaunch = command ? Array.from(command) : null;
244
+ delete merged.workspace;
245
+ delete merged.autoexec;
246
+ delete merged.dataDir;
247
+ delete merged.autolaunch;
248
+ const environment = {};
249
+ flatten(merged, "", environment);
250
+ return { profile, dataDir: dataDir, workspace, autoexec, autolaunch, environment };
251
+ }
@@ -0,0 +1,12 @@
1
+ import { type ClientInfo } from "./client.js";
2
+ import { type WaitOptions } from "./internal/operation.js";
3
+ export interface DiscoveryOptions extends WaitOptions {
4
+ directory?: string;
5
+ }
6
+ export interface WatchOptions extends DiscoveryOptions {
7
+ intervalMs?: number;
8
+ }
9
+ /** Finds responsive @main endpoints belonging to the current user. */
10
+ export declare function listClients(options?: DiscoveryOptions): Promise<ClientInfo[]>;
11
+ /** Yields an initial snapshot, then changed snapshots. Abort or break to stop polling. */
12
+ export declare function watchClients(options?: WatchOptions): AsyncGenerator<ClientInfo[]>;
@@ -0,0 +1,79 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+ import { lstat, readdir } from "node:fs/promises";
3
+ import { isAbsolute, join } from "node:path";
4
+ import { setTimeout as sleep } from "node:timers/promises";
5
+ import { Client } from "./client.js";
6
+ import { RelapseError } from "./errors.js";
7
+ import { isValidName } from "./profiles.js";
8
+ import { resolveTimeout } from "./internal/operation.js";
9
+ /** Finds responsive @main endpoints belonging to the current user. */
10
+ export async function listClients(options = {}) {
11
+ if (options.signal?.aborted)
12
+ throw new RelapseError("aborted", "Discovery aborted.");
13
+ const directory = options.directory ?? "/tmp";
14
+ if (!isAbsolute(directory))
15
+ throw new TypeError("Discovery directory must be an absolute path.");
16
+ const timeoutMs = resolveTimeout(options.timeoutMs, 1000);
17
+ const entries = await readdir(directory, { withFileTypes: true }).catch((error) => {
18
+ if (error.code === "ENOENT")
19
+ return [];
20
+ throw error;
21
+ });
22
+ const paths = entries.filter(entry => {
23
+ const match = /^relapse-(.+)\.sock$/u.exec(entry.name);
24
+ return entry.isSocket() && (entry.name === "relapse.sock" || (match?.[1] && isValidName(match[1])));
25
+ }).map(entry => join(directory, entry.name)).sort();
26
+ const result = [];
27
+ for (let offset = 0; offset < paths.length; offset += 4) {
28
+ const batch = await Promise.all(paths.slice(offset, offset + 4).map(async (socketPath) => {
29
+ let client;
30
+ try {
31
+ const stat = await lstat(socketPath);
32
+ if (!stat.isSocket() || stat.uid !== process.getuid?.())
33
+ return undefined;
34
+ client = await Client.connect({
35
+ socketPath,
36
+ timeoutMs,
37
+ ...(options.signal ? { signal: options.signal } : {}),
38
+ });
39
+ return client.info;
40
+ }
41
+ catch (error) {
42
+ if (options.signal?.aborted)
43
+ throw new RelapseError("aborted", "Discovery aborted.", { cause: error });
44
+ return undefined;
45
+ }
46
+ finally {
47
+ client?.close();
48
+ }
49
+ }));
50
+ for (const client of batch)
51
+ if (client)
52
+ result.push(client);
53
+ }
54
+ return result;
55
+ }
56
+ /** Yields an initial snapshot, then changed snapshots. Abort or break to stop polling. */
57
+ export async function* watchClients(options = {}) {
58
+ const interval = options.intervalMs ?? 1000;
59
+ if (!Number.isInteger(interval) || interval < 1 || interval > 2_147_483_647) {
60
+ throw new RangeError("intervalMs must be an integer between 1 and 2147483647.");
61
+ }
62
+ let previous;
63
+ while (!options.signal?.aborted) {
64
+ try {
65
+ const clients = await listClients(options);
66
+ const snapshot = JSON.stringify(clients);
67
+ if (snapshot !== previous) {
68
+ previous = snapshot;
69
+ yield clients;
70
+ }
71
+ await sleep(interval, undefined, options.signal ? { signal: options.signal } : {});
72
+ }
73
+ catch (error) {
74
+ if (options.signal?.aborted)
75
+ return;
76
+ throw error;
77
+ }
78
+ }
79
+ }
@@ -0,0 +1,5 @@
1
+ export type ErrorCode = "connection_failed" | "disconnected" | "protocol_error" | "channel_rejected" | "message_too_large" | "backpressure" | "not_ready" | "execution_failed" | "session_changed" | "timeout" | "aborted";
2
+ export declare class RelapseError extends Error {
3
+ readonly code: ErrorCode;
4
+ constructor(code: ErrorCode, message: string, options?: ErrorOptions);
5
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,9 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+ export class RelapseError extends Error {
3
+ code;
4
+ constructor(code, message, options) {
5
+ super(message, options);
6
+ this.code = code;
7
+ this.name = "RelapseError";
8
+ }
9
+ }
@@ -0,0 +1,14 @@
1
+ /// <reference types="node" preserve="true" />
2
+ export { Channel, type ChannelOptions, type ChannelEvents, type ChannelConnection } from "./channel.js";
3
+ export { Client, type ClientOptions, type ClientInfo, } from "./client.js";
4
+ export { MainChannel, type MainChannelOptions, type MainChannelEvents, type MainRequest, type MainMessage, type MainHello, type MainStatus, type MainError, type ExecuteOptions, type ExecutionResult, type LogEntry, } from "./main-channel.js";
5
+ export { listClients, watchClients, type DiscoveryOptions, type WatchOptions } from "./discovery.js";
6
+ export { launch, type LaunchOptions } from "./launcher.js";
7
+ export { RelapseError, type ErrorCode } from "./errors.js";
8
+ export * as configuration from "./configuration.js";
9
+ export type { ConfigurationOptions, ConfigurationObject, GlobalConfiguration, ConfigurationOverrides, ProfileConfiguration, ResolvedConfiguration, } from "./configuration.js";
10
+ export * as profiles from "./profiles.js";
11
+ export type { ProfileInfo, ProfileOptions, ProfilePaths } from "./profiles.js";
12
+ export type { JsonValue } from "./internal/json.js";
13
+ export type { WaitOptions } from "./internal/operation.js";
14
+ export type { CloseInfo } from "./internal/transport.js";
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+ /// <reference types="node" preserve="true" />
3
+ export { Channel } from "./channel.js";
4
+ export { Client, } from "./client.js";
5
+ export { MainChannel, } from "./main-channel.js";
6
+ export { listClients, watchClients } from "./discovery.js";
7
+ export { launch } from "./launcher.js";
8
+ export { RelapseError } from "./errors.js";
9
+ export * as configuration from "./configuration.js";
10
+ export * as profiles from "./profiles.js";
@@ -0,0 +1,5 @@
1
+ export type JsonValue = null | boolean | number | string | readonly JsonValue[] | {
2
+ readonly [key: string]: JsonValue;
3
+ };
4
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
5
+ export declare function encodeJson(value: JsonValue): Buffer;
@@ -0,0 +1,15 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+ export function isRecord(value) {
3
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4
+ }
5
+ export function encodeJson(value) {
6
+ const text = JSON.stringify(value, (_key, item) => {
7
+ if (typeof item === "undefined" || typeof item === "function" ||
8
+ typeof item === "symbol" || typeof item === "bigint" ||
9
+ (typeof item === "number" && !Number.isFinite(item))) {
10
+ throw new TypeError("Messages must contain only JSON-compatible values.");
11
+ }
12
+ return item;
13
+ });
14
+ return Buffer.from(text, "utf8");
15
+ }
@@ -0,0 +1,13 @@
1
+ export interface WaitOptions {
2
+ /** Milliseconds to wait. Zero disables the timeout. */
3
+ timeoutMs?: number;
4
+ signal?: AbortSignal;
5
+ }
6
+ export interface Operation<T> {
7
+ promise: Promise<T>;
8
+ readonly settled: boolean;
9
+ resolve(value: T): void;
10
+ reject(error: unknown): void;
11
+ }
12
+ export declare function resolveTimeout(timeout: number | undefined, fallback: number): number;
13
+ export declare function operation<T>(options: WaitOptions, defaultTimeout: number): Operation<T>;
@@ -0,0 +1,52 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+ import { RelapseError } from "../errors.js";
3
+ export function resolveTimeout(timeout, fallback) {
4
+ const value = timeout ?? fallback;
5
+ if (!Number.isInteger(value) || value < 0 || value > 2_147_483_647) {
6
+ throw new RangeError("timeoutMs must be an integer between 0 and 2147483647.");
7
+ }
8
+ return value;
9
+ }
10
+ export function operation(options, defaultTimeout) {
11
+ const timeout = resolveTimeout(options.timeoutMs, defaultTimeout);
12
+ const signal = options.signal;
13
+ let settled = false;
14
+ let timer;
15
+ let resolve;
16
+ let reject;
17
+ const promise = new Promise((accept, fail) => {
18
+ resolve = accept;
19
+ reject = fail;
20
+ });
21
+ const cleanup = () => {
22
+ settled = true;
23
+ clearTimeout(timer);
24
+ signal?.removeEventListener("abort", abort);
25
+ };
26
+ const result = {
27
+ promise,
28
+ get settled() { return settled; },
29
+ resolve(value) {
30
+ if (settled)
31
+ return;
32
+ cleanup();
33
+ resolve(value);
34
+ },
35
+ reject(error) {
36
+ if (settled)
37
+ return;
38
+ cleanup();
39
+ reject(error);
40
+ },
41
+ };
42
+ const abort = () => result.reject(new RelapseError("aborted", "Operation aborted.", {
43
+ cause: signal?.reason,
44
+ }));
45
+ signal?.addEventListener("abort", abort, { once: true });
46
+ if (signal?.aborted)
47
+ abort();
48
+ if (!settled && timeout > 0) {
49
+ timer = setTimeout(() => result.reject(new RelapseError("timeout", "Operation timed out.")), timeout);
50
+ }
51
+ return result;
52
+ }
@@ -0,0 +1 @@
1
+ export declare function isValidName(name: string): boolean;
@@ -0,0 +1,4 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+ export function isValidName(name) {
3
+ return typeof name === "string" && /^[a-zA-Z0-9._-]{1,64}$/u.test(name) && name !== "." && name !== "..";
4
+ }
@@ -0,0 +1,25 @@
1
+ import { RelapseError } from "../errors.js";
2
+ import { type JsonValue } from "./json.js";
3
+ import { type WaitOptions } from "./operation.js";
4
+ export interface CloseInfo {
5
+ reason: "local" | "peer" | "error";
6
+ error?: RelapseError;
7
+ }
8
+ interface Handlers {
9
+ message(value: unknown): void;
10
+ close(info: CloseInfo): void;
11
+ }
12
+ export declare class Transport {
13
+ #private;
14
+ readonly socketPath: string;
15
+ readonly name: string;
16
+ constructor(socketPath: string, name: string, handlers: Handlers);
17
+ get connected(): boolean;
18
+ get maxMessageBytes(): number;
19
+ open(options: WaitOptions): Promise<void>;
20
+ pause(): void;
21
+ resume(): void;
22
+ send(value: JsonValue): Promise<void>;
23
+ close(error?: RelapseError): void;
24
+ }
25
+ export {};