@sublang/spex 4.1.0 → 5.0.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/README.md +438 -54
- package/dist/cli.js +81 -31
- package/dist/commands/add.d.ts +12 -0
- package/dist/commands/add.js +138 -0
- package/dist/commands/auth-target.d.ts +11 -0
- package/dist/commands/auth-target.js +50 -0
- package/dist/commands/environment.d.ts +123 -0
- package/dist/commands/environment.js +411 -0
- package/dist/commands/export.d.ts +21 -0
- package/dist/commands/export.js +663 -0
- package/dist/commands/home.d.ts +56 -0
- package/dist/commands/home.js +215 -0
- package/dist/commands/install.d.ts +2 -0
- package/dist/commands/install.js +48 -0
- package/dist/commands/list.d.ts +2 -0
- package/dist/commands/list.js +87 -0
- package/dist/commands/login.d.ts +2 -0
- package/dist/commands/login.js +211 -0
- package/dist/commands/logout.d.ts +2 -0
- package/dist/commands/logout.js +74 -0
- package/dist/commands/publish.d.ts +2 -0
- package/dist/commands/publish.js +120 -0
- package/dist/commands/remove.d.ts +2 -0
- package/dist/commands/remove.js +34 -0
- package/dist/commands/run.d.ts +50 -0
- package/dist/commands/run.js +309 -0
- package/dist/commands/search.d.ts +2 -0
- package/dist/commands/search.js +34 -0
- package/dist/commands/settle.d.ts +124 -0
- package/dist/commands/settle.js +475 -0
- package/dist/commands/update.d.ts +2 -0
- package/dist/commands/update.js +37 -0
- package/dist/commands/whoami.d.ts +2 -0
- package/dist/commands/whoami.js +75 -0
- package/dist/lib/environment/agent-folders.d.ts +14 -0
- package/dist/lib/environment/agent-folders.js +11 -0
- package/dist/lib/environment/archive.d.ts +26 -0
- package/dist/lib/environment/archive.js +91 -0
- package/dist/lib/environment/builtins.d.ts +112 -0
- package/dist/lib/environment/builtins.js +539 -0
- package/dist/lib/environment/citations.d.ts +75 -0
- package/dist/lib/environment/citations.js +267 -0
- package/dist/lib/environment/exports.d.ts +190 -0
- package/dist/lib/environment/exports.js +1029 -0
- package/dist/lib/environment/format.d.ts +133 -0
- package/dist/lib/environment/format.js +651 -0
- package/dist/lib/environment/git-source.d.ts +41 -0
- package/dist/lib/environment/git-source.js +159 -0
- package/dist/lib/environment/index.d.ts +20 -0
- package/dist/lib/environment/index.js +27 -0
- package/dist/lib/environment/install.d.ts +140 -0
- package/dist/lib/environment/install.js +694 -0
- package/dist/lib/environment/layout.d.ts +15 -0
- package/dist/lib/environment/layout.js +50 -0
- package/dist/lib/environment/lock.d.ts +87 -0
- package/dist/lib/environment/lock.js +305 -0
- package/dist/lib/environment/marker.d.ts +15 -0
- package/dist/lib/environment/marker.js +31 -0
- package/dist/lib/environment/own-paths.d.ts +59 -0
- package/dist/lib/environment/own-paths.js +174 -0
- package/dist/lib/environment/placed-record.d.ts +32 -0
- package/dist/lib/environment/placed-record.js +72 -0
- package/dist/lib/environment/registries.d.ts +25 -0
- package/dist/lib/environment/registries.js +75 -0
- package/dist/lib/environment/registry.d.ts +173 -0
- package/dist/lib/environment/registry.js +390 -0
- package/dist/lib/environment/requests.d.ts +108 -0
- package/dist/lib/environment/requests.js +403 -0
- package/dist/lib/environment/resolve.d.ts +70 -0
- package/dist/lib/environment/resolve.js +451 -0
- package/dist/lib/environment/semver.d.ts +30 -0
- package/dist/lib/environment/semver.js +130 -0
- package/dist/lib/environment/store.d.ts +23 -0
- package/dist/lib/environment/store.js +123 -0
- package/dist/lib/environment/tar.d.ts +27 -0
- package/dist/lib/environment/tar.js +219 -0
- package/dist/lib/files.d.ts +66 -0
- package/dist/lib/files.js +233 -0
- package/dist/lib/git-host.d.ts +579 -0
- package/dist/lib/git-host.js +1363 -0
- package/dist/lib/home-file.d.ts +124 -0
- package/dist/lib/home-file.js +288 -0
- package/dist/lib/instance.d.ts +63 -0
- package/dist/lib/instance.js +130 -0
- package/dist/lib/words.d.ts +32 -0
- package/dist/lib/words.js +27 -0
- package/dist/lint.js +8 -0
- package/dist/testing/index.d.ts +1 -0
- package/dist/testing/index.js +7 -0
- package/dist/testing/standin-registry.d.ts +94 -0
- package/dist/testing/standin-registry.js +449 -0
- package/package.json +37 -3
- package/dist/attached-cli.d.ts +0 -13
- package/dist/attached-cli.js +0 -247
- package/dist/attached-client.d.ts +0 -36
- package/dist/attached-client.js +0 -189
- package/dist/generated-protocol.d.ts +0 -2
- package/dist/generated-protocol.js +0 -6
package/dist/attached-cli.js
DELETED
|
@@ -1,247 +0,0 @@
|
|
|
1
|
-
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
-
// SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
|
|
3
|
-
import { resolve, isAbsolute, win32 } from "node:path";
|
|
4
|
-
import { AttachedClient, accessEndpoint, CliFailure } from "./attached-client.js";
|
|
5
|
-
const NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
6
|
-
const VALUES = new Set(["server", "timeout", "project", "instance", "version", "path"]);
|
|
7
|
-
export const ATTACHED_USAGE = `Attached commands (an already-running local Spex server is required):
|
|
8
|
-
auth login --instance <origin> Sign in through the browser/device instructions
|
|
9
|
-
auth status Show instance sign-in standing
|
|
10
|
-
project list List registered projects
|
|
11
|
-
project add <folder> Register a project working folder
|
|
12
|
-
package search <query> Search the selected project's registry
|
|
13
|
-
package status Show its requests and installed packages
|
|
14
|
-
package add <org/name> --version <requirement>
|
|
15
|
-
package add <org/name> --path <relative-folder>
|
|
16
|
-
package remove <org/name>
|
|
17
|
-
package install Install the locked selections
|
|
18
|
-
package resolve Resolve requests and install
|
|
19
|
-
package publish <relative-folder> [--dry-run]
|
|
20
|
-
|
|
21
|
-
Connection: --server <access-url> or SPEX_SERVER_URL (literal loopback only).
|
|
22
|
-
Observation: --timeout <positive seconds> (default 600); no reconnect or replay.
|
|
23
|
-
Packages: --project <registered-folder>, otherwise the exact current directory.
|
|
24
|
-
Publishing is explicit; --dry-run checks without uploading.`;
|
|
25
|
-
function usageError(message) { throw new CliFailure(1, message); }
|
|
26
|
-
function relativeFolder(value) {
|
|
27
|
-
if (!value || /[\x00-\x1f\x7f]/.test(value) || isAbsolute(value) || win32.isAbsolute(value) || value.split(/[\\/]/).includes(".."))
|
|
28
|
-
usageError("Package folder must be a relative folder inside the selected project.");
|
|
29
|
-
return value;
|
|
30
|
-
}
|
|
31
|
-
/** Parse the whole invocation before opening a connection or sending a command. */
|
|
32
|
-
export function parseAttached(args) {
|
|
33
|
-
const flags = {};
|
|
34
|
-
const words = [];
|
|
35
|
-
for (let i = 0; i < args.length; i++) {
|
|
36
|
-
const arg = args[i];
|
|
37
|
-
if (!arg.startsWith("-")) {
|
|
38
|
-
words.push(arg);
|
|
39
|
-
continue;
|
|
40
|
-
}
|
|
41
|
-
const match = /^--([a-z-]+)(?:=(.*))?$/.exec(arg);
|
|
42
|
-
const key = match?.[1];
|
|
43
|
-
if (!key || (!VALUES.has(key) && key !== "dry-run"))
|
|
44
|
-
usageError("Unknown option. Use spex --help for supported flags.");
|
|
45
|
-
if (Object.hasOwn(flags, key))
|
|
46
|
-
usageError(`Option --${key} was repeated.`);
|
|
47
|
-
if (key === "dry-run") {
|
|
48
|
-
if (match[2] !== undefined)
|
|
49
|
-
usageError("--dry-run takes no value.");
|
|
50
|
-
flags[key] = true;
|
|
51
|
-
}
|
|
52
|
-
else {
|
|
53
|
-
const value = match[2] ?? args[++i];
|
|
54
|
-
if (!value || value.startsWith("-"))
|
|
55
|
-
usageError(`--${key} requires a value.`);
|
|
56
|
-
flags[key] = value;
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
const [group, action, ...positional] = words;
|
|
60
|
-
const allowed = {
|
|
61
|
-
"auth login": ["instance"], "auth status": [], "project list": [], "project add": [],
|
|
62
|
-
"package search": ["project"], "package status": ["project"],
|
|
63
|
-
"package add": ["project", "version", "path"], "package remove": ["project"],
|
|
64
|
-
"package install": ["project"], "package resolve": ["project"], "package publish": ["project", "dry-run"],
|
|
65
|
-
};
|
|
66
|
-
const entry = allowed[`${group} ${action}`];
|
|
67
|
-
if (!entry)
|
|
68
|
-
usageError("Unknown attached command. Use spex --help.");
|
|
69
|
-
for (const key of Object.keys(flags))
|
|
70
|
-
if (!["server", "timeout", ...entry].includes(key))
|
|
71
|
-
usageError(`--${key} is not valid for this command.`);
|
|
72
|
-
const needsArgument = action === "add" || action === "remove" || action === "search" || action === "publish";
|
|
73
|
-
if (positional.length !== (needsArgument ? 1 : 0))
|
|
74
|
-
usageError(needsArgument ? "This command requires exactly one argument." : "This command takes no positional arguments.");
|
|
75
|
-
if (group === "auth" && action === "login") {
|
|
76
|
-
if (typeof flags.instance !== "string")
|
|
77
|
-
usageError("auth login requires --instance <origin>.");
|
|
78
|
-
try {
|
|
79
|
-
const origin = new URL(flags.instance);
|
|
80
|
-
if (!["http:", "https:"].includes(origin.protocol) || origin.username || origin.password || origin.pathname !== "/" || origin.search || flags.instance.includes("#"))
|
|
81
|
-
throw new Error();
|
|
82
|
-
flags.instance = origin.origin;
|
|
83
|
-
}
|
|
84
|
-
catch {
|
|
85
|
-
usageError("--instance must name an HTTP(S) Space origin, without credentials, path, query or fragment.");
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
if (group === "package") {
|
|
89
|
-
if (["add", "remove"].includes(action) && !NAME.test(positional[0]))
|
|
90
|
-
usageError("Package name must be org/name using lowercase letters, digits and hyphens.");
|
|
91
|
-
if (action === "search" && positional[0].length > 200)
|
|
92
|
-
usageError("Search query must be at most 200 characters.");
|
|
93
|
-
if (action === "add" && (typeof flags.version === "string") === (typeof flags.path === "string"))
|
|
94
|
-
usageError("package add requires exactly one of --version or --path.");
|
|
95
|
-
if (typeof flags.path === "string")
|
|
96
|
-
relativeFolder(flags.path);
|
|
97
|
-
if (action === "publish")
|
|
98
|
-
relativeFolder(positional[0]);
|
|
99
|
-
}
|
|
100
|
-
let seconds = 600;
|
|
101
|
-
if (flags.timeout !== undefined) {
|
|
102
|
-
if (typeof flags.timeout !== "string" || !/^(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)$/.test(flags.timeout))
|
|
103
|
-
usageError("--timeout must be positive seconds.");
|
|
104
|
-
seconds = Number(flags.timeout);
|
|
105
|
-
if (!Number.isFinite(seconds) || seconds <= 0 || seconds * 1000 > 2_147_483_647)
|
|
106
|
-
usageError("--timeout must be positive seconds within the supported timer range.");
|
|
107
|
-
}
|
|
108
|
-
if (typeof flags.project === "string")
|
|
109
|
-
flags.project = resolve(flags.project);
|
|
110
|
-
if (group === "project" && action === "add")
|
|
111
|
-
positional[0] = resolve(positional[0]);
|
|
112
|
-
return { group: group, action: action, positional, flags, timeoutMs: Math.max(1, Math.ceil(seconds * 1000)) };
|
|
113
|
-
}
|
|
114
|
-
function object(value) { return value !== null && typeof value === "object" && !Array.isArray(value); }
|
|
115
|
-
function malformed() { throw new CliFailure(2, "The server returned an incomplete result. Outcome is unknown; inspect its state before retrying. Nothing was resent."); }
|
|
116
|
-
export async function runAttached(args, env = process.env) {
|
|
117
|
-
if (args.includes("--help") || args.includes("-h")) {
|
|
118
|
-
process.stdout.write(ATTACHED_USAGE + "\n");
|
|
119
|
-
return 0;
|
|
120
|
-
}
|
|
121
|
-
let client;
|
|
122
|
-
let token = "";
|
|
123
|
-
let endpoint = "";
|
|
124
|
-
const clean = (value) => {
|
|
125
|
-
let text = String(value);
|
|
126
|
-
if (endpoint)
|
|
127
|
-
text = text.split(endpoint).join("[server access URL redacted]");
|
|
128
|
-
if (token) {
|
|
129
|
-
text = text.split(token).join("[redacted]").split(encodeURIComponent(token)).join("[redacted]");
|
|
130
|
-
}
|
|
131
|
-
return text;
|
|
132
|
-
};
|
|
133
|
-
const print = (value) => process.stdout.write(clean(value) + "\n");
|
|
134
|
-
const interrupt = () => client?.interrupt();
|
|
135
|
-
try {
|
|
136
|
-
const invocation = parseAttached(args);
|
|
137
|
-
const { group, action, positional, flags } = invocation;
|
|
138
|
-
const access = accessEndpoint(typeof flags.server === "string" ? flags.server : env.SPEX_SERVER_URL);
|
|
139
|
-
token = access.token;
|
|
140
|
-
endpoint = access.url;
|
|
141
|
-
client = new AttachedClient(access.url, invocation.timeoutMs);
|
|
142
|
-
process.on("SIGINT", interrupt);
|
|
143
|
-
await client.connect();
|
|
144
|
-
if (group === "project") {
|
|
145
|
-
const result = await client.command(action === "list" ? "project.list" : "project.register", action === "add" ? { path: positional[0] } : {});
|
|
146
|
-
const projects = action === "list" ? result : [result];
|
|
147
|
-
if (!Array.isArray(projects) || projects.some((p) => !object(p) || typeof p.name !== "string" || typeof p.path !== "string"))
|
|
148
|
-
malformed();
|
|
149
|
-
print(projects.length ? projects.map((p) => `${p.name}\t${p.path}`).join("\n") : "No registered projects.");
|
|
150
|
-
}
|
|
151
|
-
else if (group === "auth") {
|
|
152
|
-
if (action === "status") {
|
|
153
|
-
const result = await client.command("space.get");
|
|
154
|
-
if (!Array.isArray(result?.instances) || result.instances.some((i) => !object(i) || typeof i.origin !== "string" || typeof i.signedIn !== "boolean" || (i.signedIn && typeof i.account?.login !== "string")))
|
|
155
|
-
malformed();
|
|
156
|
-
print(result.instances.length ? result.instances.map((i) => `${i.displayName ?? i.host ?? i.origin}\t${i.signedIn ? `Signed in${i.account?.login ? ` as @${i.account.login}` : ""}` : "Signed out"}`).join("\n") : "No instances. Sign in with spex auth login --instance <origin>.");
|
|
157
|
-
}
|
|
158
|
-
else {
|
|
159
|
-
const result = await client.signIn(String(flags.instance), (instruction) => {
|
|
160
|
-
if (instruction?.flow === "device" && typeof instruction.verificationUri === "string" && typeof instruction.userCode === "string")
|
|
161
|
-
print(`Open ${instruction.verificationUri}\nEnter code: ${instruction.userCode}\nWaiting for this sign-in to complete…`);
|
|
162
|
-
else if (instruction?.flow === "browser" && typeof instruction.url === "string")
|
|
163
|
-
print(`Open ${instruction.url}\nWaiting for this sign-in to complete…`);
|
|
164
|
-
else
|
|
165
|
-
malformed();
|
|
166
|
-
});
|
|
167
|
-
print(`Signed in as @${result.account.login}. Catalog reading and Sync are separate operations.`);
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
else {
|
|
171
|
-
const listed = await client.command("project.list");
|
|
172
|
-
if (!Array.isArray(listed))
|
|
173
|
-
malformed();
|
|
174
|
-
const target = typeof flags.project === "string" ? flags.project : process.cwd();
|
|
175
|
-
const matching = listed.filter((p) => p?.path === target);
|
|
176
|
-
if (matching.length !== 1 || typeof matching[0]?.repository?.key !== "string")
|
|
177
|
-
usageError("No unique registered project matches this folder. Use spex project add <folder>, then run from its root or pass --project <folder>.");
|
|
178
|
-
const project = matching[0];
|
|
179
|
-
const repository = project.repository.key;
|
|
180
|
-
if (action === "search") {
|
|
181
|
-
const result = await client.command("environment.search", { repository, query: positional[0] });
|
|
182
|
-
if (!Array.isArray(result?.packages) || result.packages.some((p) => !object(p) || typeof p.name !== "string" || !Array.isArray(p.versions) || p.versions.some((v) => typeof v !== "string")))
|
|
183
|
-
malformed();
|
|
184
|
-
print(result.packages.length ? result.packages.map((p) => `${p.name}\t${p.versions?.join(", ") ?? ""}\t${p.description ?? ""}`).join("\n") : "No packages found.");
|
|
185
|
-
}
|
|
186
|
-
else if (action === "status") {
|
|
187
|
-
const result = await client.command("environment.get", { repository });
|
|
188
|
-
if (!object(result?.requests) || Object.values(result.requests).some((r) => !object(r) || typeof r.kind !== "string") || !Array.isArray(result?.packages) || result.packages.some((p) => !object(p) || typeof p.name !== "string" || typeof p.installed !== "boolean"))
|
|
189
|
-
malformed();
|
|
190
|
-
print(`Project: ${project.name}\nRequests:`);
|
|
191
|
-
for (const [name, request] of Object.entries(result.requests))
|
|
192
|
-
print(` ${name}\t${request.kind}\t${request.version ?? request.path ?? request.repository ?? ""}`);
|
|
193
|
-
print("Packages:");
|
|
194
|
-
for (const p of result.packages)
|
|
195
|
-
print(` ${p.name}\t${p.version ?? "unresolved"}\t${p.installed ? "installed" : "not installed"}`);
|
|
196
|
-
if (result.stale?.length)
|
|
197
|
-
print(`Stale: ${result.stale.join("; ")}`);
|
|
198
|
-
if (result.error)
|
|
199
|
-
print(`Last environment error: ${result.error}`);
|
|
200
|
-
}
|
|
201
|
-
else if (action === "publish") {
|
|
202
|
-
const dryRun = flags["dry-run"] === true;
|
|
203
|
-
const result = await client.command("environment.publish", { repository, path: positional[0], ...(dryRun ? { dryRun: true } : { wait: true }) });
|
|
204
|
-
const receipt = dryRun ? result?.preview : result?.published;
|
|
205
|
-
if ((dryRun ? result?.accepted !== true : result?.completed !== true) || !object(receipt?.instance) || typeof receipt.name !== "string" || typeof receipt.version !== "string" || typeof receipt.instance.origin !== "string")
|
|
206
|
-
malformed();
|
|
207
|
-
if (dryRun ? !Array.isArray(receipt.files) || receipt.files.some((f) => typeof f !== "string" && (!object(f) || typeof f.path !== "string")) : typeof receipt.url !== "string")
|
|
208
|
-
malformed();
|
|
209
|
-
print(`${dryRun ? "Would publish" : "Published"} ${receipt.name}@${receipt.version}\nDestination: ${receipt.instance.name ?? receipt.instance.origin} (${receipt.instance.origin})`);
|
|
210
|
-
if (dryRun) {
|
|
211
|
-
if (!Array.isArray(receipt.files))
|
|
212
|
-
malformed();
|
|
213
|
-
for (const file of receipt.files)
|
|
214
|
-
print(` ${typeof file === "string" ? file : file.path}`);
|
|
215
|
-
}
|
|
216
|
-
else if (typeof receipt.url === "string")
|
|
217
|
-
print(receipt.url);
|
|
218
|
-
}
|
|
219
|
-
else {
|
|
220
|
-
let type = `environment.${action}`;
|
|
221
|
-
const fields = { repository, wait: true };
|
|
222
|
-
if (action === "add") {
|
|
223
|
-
type = "environment.request";
|
|
224
|
-
fields.name = positional[0];
|
|
225
|
-
fields.request = typeof flags.path === "string" ? { kind: "path", path: flags.path } : { kind: "registry", version: flags.version };
|
|
226
|
-
}
|
|
227
|
-
else if (action === "remove")
|
|
228
|
-
fields.name = positional[0];
|
|
229
|
-
const result = await client.command(type, fields);
|
|
230
|
-
if (result?.completed !== true)
|
|
231
|
-
malformed();
|
|
232
|
-
print(`Package ${action} completed for ${project.name}.`);
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
return 0;
|
|
236
|
-
}
|
|
237
|
-
catch (error) {
|
|
238
|
-
const failure = error instanceof CliFailure ? error : new CliFailure(1, "Command failed. Check the running server and command arguments.");
|
|
239
|
-
process.stderr.write(clean(failure.message) + "\n");
|
|
240
|
-
return failure.exitCode;
|
|
241
|
-
}
|
|
242
|
-
finally {
|
|
243
|
-
process.off("SIGINT", interrupt);
|
|
244
|
-
client?.close();
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
//# sourceMappingURL=attached-cli.js.map
|
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
export declare class CliFailure extends Error {
|
|
2
|
-
readonly exitCode: number;
|
|
3
|
-
constructor(exitCode: number, message: string);
|
|
4
|
-
}
|
|
5
|
-
type Message = Record<string, any>;
|
|
6
|
-
/** Validate before opening a socket; WHATWG normalization must not admit
|
|
7
|
-
* numeric aliases, wildcard addresses or DNS names other than localhost. */
|
|
8
|
-
export declare function accessEndpoint(input: string | undefined): {
|
|
9
|
-
url: string;
|
|
10
|
-
token: string;
|
|
11
|
-
};
|
|
12
|
-
/** One invocation, one connection. Core owns validation and operation state. */
|
|
13
|
-
export declare class AttachedClient {
|
|
14
|
-
private readonly endpoint;
|
|
15
|
-
private readonly timeoutMs;
|
|
16
|
-
private socket?;
|
|
17
|
-
private ready?;
|
|
18
|
-
private pending;
|
|
19
|
-
private completion;
|
|
20
|
-
private earlyCompletion;
|
|
21
|
-
private sent;
|
|
22
|
-
private stopped;
|
|
23
|
-
private failure?;
|
|
24
|
-
private timer?;
|
|
25
|
-
signInId?: string;
|
|
26
|
-
constructor(endpoint: string, timeoutMs: number);
|
|
27
|
-
connect(): Promise<void>;
|
|
28
|
-
private observationFailure;
|
|
29
|
-
private message;
|
|
30
|
-
command(type: string, fields?: Message, id?: `${string}-${string}-${string}-${string}-${string}`): Promise<any>;
|
|
31
|
-
signIn(instance: string, instructions: (result: any) => void): Promise<Message>;
|
|
32
|
-
interrupt(): void;
|
|
33
|
-
private fail;
|
|
34
|
-
close(): void;
|
|
35
|
-
}
|
|
36
|
-
export {};
|
package/dist/attached-client.js
DELETED
|
@@ -1,189 +0,0 @@
|
|
|
1
|
-
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
-
// SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
|
|
3
|
-
import { randomUUID } from "node:crypto";
|
|
4
|
-
import { PROTOCOL_VERSION, ATTACHED_CLI_VERSION } from "./generated-protocol.js";
|
|
5
|
-
export class CliFailure extends Error {
|
|
6
|
-
exitCode;
|
|
7
|
-
constructor(exitCode, message) {
|
|
8
|
-
super(message);
|
|
9
|
-
this.exitCode = exitCode;
|
|
10
|
-
}
|
|
11
|
-
}
|
|
12
|
-
/** Validate before opening a socket; WHATWG normalization must not admit
|
|
13
|
-
* numeric aliases, wildcard addresses or DNS names other than localhost. */
|
|
14
|
-
export function accessEndpoint(input) {
|
|
15
|
-
const guidance = "Use --server <loopback access-url> or SPEX_SERVER_URL from the running local Spex server.";
|
|
16
|
-
if (!input)
|
|
17
|
-
throw new CliFailure(1, guidance);
|
|
18
|
-
try {
|
|
19
|
-
const rawHost = /^[a-z]+:\/\/(\[[^\]]+\]|[^/:?#]+)(?::[0-9]+)?(?:[/?#]|$)/i.exec(input)?.[1]?.toLowerCase();
|
|
20
|
-
const url = new URL(input);
|
|
21
|
-
if (!rawHost || !["localhost", "127.0.0.1", "[::1]"].includes(rawHost) ||
|
|
22
|
-
!["http:", "https:", "ws:", "wss:"].includes(url.protocol) || url.username || url.password ||
|
|
23
|
-
input.includes("#") || url.pathname !== "/" || [...url.searchParams.keys()].some((k) => k !== "token") ||
|
|
24
|
-
url.searchParams.getAll("token").length !== 1 || !url.searchParams.get("token"))
|
|
25
|
-
throw new Error();
|
|
26
|
-
const token = url.searchParams.get("token");
|
|
27
|
-
url.protocol = url.protocol === "http:" ? "ws:" : url.protocol === "https:" ? "wss:" : url.protocol;
|
|
28
|
-
return { url: url.href, token };
|
|
29
|
-
}
|
|
30
|
-
catch {
|
|
31
|
-
throw new CliFailure(1, `Invalid server access URL. ${guidance}`);
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
/** One invocation, one connection. Core owns validation and operation state. */
|
|
35
|
-
export class AttachedClient {
|
|
36
|
-
endpoint;
|
|
37
|
-
timeoutMs;
|
|
38
|
-
socket;
|
|
39
|
-
ready;
|
|
40
|
-
pending = new Map();
|
|
41
|
-
completion = new Map();
|
|
42
|
-
earlyCompletion = new Map();
|
|
43
|
-
sent = false;
|
|
44
|
-
stopped = false;
|
|
45
|
-
failure;
|
|
46
|
-
timer;
|
|
47
|
-
signInId;
|
|
48
|
-
constructor(endpoint, timeoutMs) {
|
|
49
|
-
this.endpoint = endpoint;
|
|
50
|
-
this.timeoutMs = timeoutMs;
|
|
51
|
-
}
|
|
52
|
-
async connect() {
|
|
53
|
-
if (typeof globalThis.WebSocket !== "function")
|
|
54
|
-
throw new CliFailure(1, "This Node.js runtime needs WebSocket support. Use Node.js 22 or later without disabling WebSocket.");
|
|
55
|
-
this.timer = setTimeout(() => this.fail(this.observationFailure("Observation timed out")), this.timeoutMs);
|
|
56
|
-
await new Promise((resolve, reject) => {
|
|
57
|
-
this.ready = { resolve, reject };
|
|
58
|
-
try {
|
|
59
|
-
this.socket = new WebSocket(this.endpoint);
|
|
60
|
-
}
|
|
61
|
-
catch {
|
|
62
|
-
this.fail(new CliFailure(1, "Could not connect. Check the running server and its access URL."));
|
|
63
|
-
return;
|
|
64
|
-
}
|
|
65
|
-
this.socket.addEventListener("message", (event) => this.message(event.data));
|
|
66
|
-
this.socket.addEventListener("error", () => this.fail(this.observationFailure("Connection failed; check the running server and its access URL")));
|
|
67
|
-
this.socket.addEventListener("close", () => {
|
|
68
|
-
if (!this.stopped)
|
|
69
|
-
this.fail(this.observationFailure("Connection closed"));
|
|
70
|
-
});
|
|
71
|
-
});
|
|
72
|
-
}
|
|
73
|
-
observationFailure(reason) {
|
|
74
|
-
return new CliFailure(this.sent ? 2 : 1, this.sent
|
|
75
|
-
? `${reason}. The result is unknown; the operation may still complete. Inspect its state before retrying; nothing was resent.`
|
|
76
|
-
: `${reason}. No command was sent.`);
|
|
77
|
-
}
|
|
78
|
-
message(data) {
|
|
79
|
-
if (this.stopped)
|
|
80
|
-
return;
|
|
81
|
-
let message;
|
|
82
|
-
try {
|
|
83
|
-
message = JSON.parse(String(data));
|
|
84
|
-
if (!message || typeof message !== "object" || Array.isArray(message))
|
|
85
|
-
throw new Error();
|
|
86
|
-
}
|
|
87
|
-
catch {
|
|
88
|
-
this.fail(this.observationFailure("Invalid server message"));
|
|
89
|
-
return;
|
|
90
|
-
}
|
|
91
|
-
if (this.ready) {
|
|
92
|
-
if (message.type !== "hello" || message.protocolVersion !== PROTOCOL_VERSION || message.attachedCliVersion !== ATTACHED_CLI_VERSION) {
|
|
93
|
-
this.fail(new CliFailure(1, "Incompatible server. Update the CLI and running Spex server together; no command was sent."));
|
|
94
|
-
return;
|
|
95
|
-
}
|
|
96
|
-
const ready = this.ready;
|
|
97
|
-
this.ready = undefined;
|
|
98
|
-
ready.resolve(undefined);
|
|
99
|
-
return;
|
|
100
|
-
}
|
|
101
|
-
if (message.type === "reply" && typeof message.id === "string") {
|
|
102
|
-
const pending = this.pending.get(message.id);
|
|
103
|
-
if (!pending)
|
|
104
|
-
return;
|
|
105
|
-
this.pending.delete(message.id);
|
|
106
|
-
if (message.ok === true && Object.hasOwn(message, "result"))
|
|
107
|
-
pending.resolve(message.result);
|
|
108
|
-
else if (message.ok === false && typeof message.error?.code === "string" && typeof message.error?.message === "string")
|
|
109
|
-
pending.reject(new CliFailure(1, `${message.error.code}: ${message.error.message}${message.error.details ? `\n${JSON.stringify(message.error.details)}` : ""}`));
|
|
110
|
-
else
|
|
111
|
-
pending.reject(this.observationFailure("Invalid terminal reply"));
|
|
112
|
-
}
|
|
113
|
-
else if (message.type === "space.signin.completed" && typeof message.id === "string" && message.id === this.signInId) {
|
|
114
|
-
const pending = this.completion.get(message.id);
|
|
115
|
-
if (pending) {
|
|
116
|
-
this.completion.delete(message.id);
|
|
117
|
-
pending.resolve(message);
|
|
118
|
-
}
|
|
119
|
-
else
|
|
120
|
-
this.earlyCompletion.set(message.id, message);
|
|
121
|
-
}
|
|
122
|
-
// Aggregate state is deliberately ignored: it cannot complete a request.
|
|
123
|
-
}
|
|
124
|
-
command(type, fields = {}, id = randomUUID()) {
|
|
125
|
-
if (this.failure)
|
|
126
|
-
return Promise.reject(this.failure);
|
|
127
|
-
if (!this.socket || this.socket.readyState !== WebSocket.OPEN || this.ready)
|
|
128
|
-
return Promise.reject(this.observationFailure("Server is not connected"));
|
|
129
|
-
return new Promise((resolve, reject) => {
|
|
130
|
-
this.pending.set(id, { resolve, reject });
|
|
131
|
-
try {
|
|
132
|
-
this.socket.send(JSON.stringify({ type, id, ...fields }));
|
|
133
|
-
this.sent = true;
|
|
134
|
-
}
|
|
135
|
-
catch {
|
|
136
|
-
this.fail(this.observationFailure("Could not send command"));
|
|
137
|
-
}
|
|
138
|
-
});
|
|
139
|
-
}
|
|
140
|
-
async signIn(instance, instructions) {
|
|
141
|
-
const id = randomUUID();
|
|
142
|
-
this.signInId = id;
|
|
143
|
-
const result = await this.command("space.signin.start", { url: instance, reportCompletion: true }, id);
|
|
144
|
-
instructions(result);
|
|
145
|
-
if (this.failure)
|
|
146
|
-
throw this.failure;
|
|
147
|
-
const early = this.earlyCompletion.get(id);
|
|
148
|
-
const terminal = early ?? await new Promise((resolve, reject) => this.completion.set(id, { resolve, reject }));
|
|
149
|
-
this.signInId = undefined;
|
|
150
|
-
if (terminal.instance !== instance)
|
|
151
|
-
throw this.observationFailure("Sign-in completion named another instance");
|
|
152
|
-
if (terminal.ok === true && typeof terminal.account?.login === "string")
|
|
153
|
-
return terminal;
|
|
154
|
-
if (terminal.ok === false && typeof terminal.error?.code === "string" && typeof terminal.error?.message === "string")
|
|
155
|
-
throw new CliFailure(1, `${terminal.error.code}: ${terminal.error.message}`);
|
|
156
|
-
throw this.observationFailure("Invalid sign-in completion");
|
|
157
|
-
}
|
|
158
|
-
interrupt() {
|
|
159
|
-
const signingIn = this.signInId;
|
|
160
|
-
if (signingIn && this.socket?.readyState === WebSocket.OPEN) {
|
|
161
|
-
// Ordered before close on the same connection; never cancels another start.
|
|
162
|
-
try {
|
|
163
|
-
this.socket.send(JSON.stringify({ type: "space.signin.cancel", id: randomUUID(), startId: signingIn }));
|
|
164
|
-
}
|
|
165
|
-
catch { /* connection already lost */ }
|
|
166
|
-
}
|
|
167
|
-
this.fail(new CliFailure(130, signingIn
|
|
168
|
-
? "Interrupted. Requested cancellation of this sign-in where connected; no rollback is promised."
|
|
169
|
-
: "Interrupted observation. Work may still complete; inspect its state before retrying. No rollback is promised."));
|
|
170
|
-
}
|
|
171
|
-
fail(error) {
|
|
172
|
-
if (this.stopped)
|
|
173
|
-
return;
|
|
174
|
-
this.failure = error;
|
|
175
|
-
this.ready?.reject(error);
|
|
176
|
-
this.ready = undefined;
|
|
177
|
-
for (const waiter of [...this.pending.values(), ...this.completion.values()])
|
|
178
|
-
waiter.reject(error);
|
|
179
|
-
this.pending.clear();
|
|
180
|
-
this.completion.clear();
|
|
181
|
-
this.close();
|
|
182
|
-
}
|
|
183
|
-
close() {
|
|
184
|
-
this.stopped = true;
|
|
185
|
-
clearTimeout(this.timer);
|
|
186
|
-
this.socket?.close();
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
//# sourceMappingURL=attached-client.js.map
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
-
// SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
|
|
3
|
-
// Generated from core/src/protocol.ts; do not edit.
|
|
4
|
-
export const PROTOCOL_VERSION = 28;
|
|
5
|
-
export const ATTACHED_CLI_VERSION = 1;
|
|
6
|
-
//# sourceMappingURL=generated-protocol.js.map
|