@soft-boy/agentschema 0.3.12 → 0.5.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 (94) hide show
  1. package/README.md +13 -9
  2. package/dist/bin/agentschema.d.ts +2 -0
  3. package/dist/bin/agentschema.js +333 -0
  4. package/dist/lib/channels.d.ts +65 -0
  5. package/dist/lib/channels.js +339 -0
  6. package/dist/lib/check.d.ts +10 -0
  7. package/dist/lib/check.js +411 -0
  8. package/dist/lib/files.d.ts +7 -0
  9. package/{lib → dist/lib}/files.js +10 -14
  10. package/dist/lib/index.d.ts +24 -0
  11. package/{lib → dist/lib}/index.js +3 -10
  12. package/dist/lib/instance.d.ts +41 -0
  13. package/dist/lib/instance.js +74 -0
  14. package/dist/lib/markdown.d.ts +11 -0
  15. package/dist/lib/markdown.js +38 -0
  16. package/dist/lib/scaffold.d.ts +15 -0
  17. package/dist/lib/scaffold.js +46 -0
  18. package/dist/lib/scheduled.d.ts +56 -0
  19. package/dist/lib/scheduled.js +185 -0
  20. package/dist/lib/skills.d.ts +28 -0
  21. package/dist/lib/skills.js +55 -0
  22. package/dist/lib/stream.d.ts +30 -0
  23. package/dist/lib/stream.js +56 -0
  24. package/dist/lib/system-prompt.d.ts +16 -0
  25. package/{lib → dist/lib}/system-prompt.js +14 -15
  26. package/dist/lib/tools.d.ts +105 -0
  27. package/dist/lib/tools.js +353 -0
  28. package/dist/lib/vaults.d.ts +55 -0
  29. package/dist/lib/vaults.js +143 -0
  30. package/dist/src/chat.d.ts +15 -0
  31. package/dist/src/chat.js +159 -0
  32. package/dist/src/check.d.ts +2 -0
  33. package/dist/src/check.js +14 -0
  34. package/dist/src/cred-menu.d.ts +17 -0
  35. package/dist/src/cred-menu.js +193 -0
  36. package/dist/src/cred.d.ts +54 -0
  37. package/dist/src/cred.js +252 -0
  38. package/dist/src/custom-tools.d.ts +3 -0
  39. package/dist/src/custom-tools.js +18 -0
  40. package/dist/src/delete.d.ts +9 -0
  41. package/dist/src/delete.js +27 -0
  42. package/dist/src/deploy.d.ts +62 -0
  43. package/dist/src/deploy.js +442 -0
  44. package/dist/src/dotenv.d.ts +7 -0
  45. package/dist/src/dotenv.js +54 -0
  46. package/dist/src/folder.d.ts +5 -0
  47. package/dist/src/folder.js +57 -0
  48. package/dist/src/init.d.ts +11 -0
  49. package/dist/src/init.js +51 -0
  50. package/dist/src/list.d.ts +3 -0
  51. package/dist/src/list.js +46 -0
  52. package/dist/src/lock.d.ts +10 -0
  53. package/dist/src/lock.js +37 -0
  54. package/dist/src/mcp.d.ts +11 -0
  55. package/dist/src/mcp.js +79 -0
  56. package/dist/src/node.d.ts +14 -0
  57. package/dist/src/oauth.d.ts +64 -0
  58. package/dist/src/oauth.js +208 -0
  59. package/dist/src/prompts.d.ts +18 -0
  60. package/dist/src/prompts.js +166 -0
  61. package/dist/src/session.d.ts +58 -0
  62. package/dist/src/session.js +200 -0
  63. package/dist/src/tools-menu.d.ts +8 -0
  64. package/dist/src/tools-menu.js +173 -0
  65. package/package.json +21 -9
  66. package/bin/agentschema.js +0 -326
  67. package/lib/channels.js +0 -338
  68. package/lib/check.js +0 -388
  69. package/lib/instance.js +0 -48
  70. package/lib/markdown.js +0 -42
  71. package/lib/scaffold.js +0 -51
  72. package/lib/scheduled.js +0 -175
  73. package/lib/skills.js +0 -58
  74. package/lib/stream.js +0 -50
  75. package/lib/tools.js +0 -327
  76. package/lib/vaults.js +0 -142
  77. package/src/chat.js +0 -156
  78. package/src/check.js +0 -14
  79. package/src/cred-menu.js +0 -197
  80. package/src/cred.js +0 -263
  81. package/src/custom-tools.js +0 -17
  82. package/src/delete.js +0 -25
  83. package/src/deploy.js +0 -441
  84. package/src/dotenv.js +0 -50
  85. package/src/folder.js +0 -55
  86. package/src/init.js +0 -54
  87. package/src/list.js +0 -49
  88. package/src/lock.js +0 -40
  89. package/src/mcp.js +0 -76
  90. package/src/oauth.js +0 -215
  91. package/src/prompts.js +0 -159
  92. package/src/session.js +0 -194
  93. package/src/tools-menu.js +0 -163
  94. /package/{src → dist/src}/node.js +0 -0
package/src/lock.js DELETED
@@ -1,40 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
- import { join } from "node:path";
4
-
5
- export const LOCK_FILE = "claude-lock.json";
6
-
7
- // Same layout as the lock file `ant apply` writes: one entry per file, keyed by "./<file>".
8
- export function readLock(dir) {
9
- const path = join(dir, LOCK_FILE);
10
- if (!existsSync(path)) return null;
11
- try {
12
- return JSON.parse(readFileSync(path, "utf8"));
13
- } catch (err) {
14
- throw new Error(`${LOCK_FILE}: not valid JSON (${err.message})`);
15
- }
16
- }
17
-
18
- export function writeLock(dir, lock) {
19
- writeFileSync(join(dir, LOCK_FILE), JSON.stringify(lock, null, 2) + "\n");
20
- }
21
-
22
- // What's hashed into the lock for a skill: each file's path and contents, so any change makes a
23
- // new version.
24
- export function skillFingerprint(skill) {
25
- return { files: skill.files.map((f) => [f.rel, createHash("sha256").update(f.bytes).digest("hex")]) };
26
- }
27
-
28
- // Hash of a request body with keys sorted, so key order in the YAML doesn't count as a change.
29
- export function hashBody(body) {
30
- return createHash("md5").update(canonicalJSON(body)).digest("hex");
31
- }
32
-
33
- function canonicalJSON(value) {
34
- if (Array.isArray(value)) return `[${value.map(canonicalJSON).join(",")}]`;
35
- if (value && typeof value === "object") {
36
- const keys = Object.keys(value).sort();
37
- return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJSON(value[k])}`).join(",")}}`;
38
- }
39
- return JSON.stringify(value);
40
- }
package/src/mcp.js DELETED
@@ -1,76 +0,0 @@
1
- import { readTools, MCP_TOOLSET, mcpToolsetFile } from "../lib/tools.js";
2
- import { readInstance } from "../lib/instance.js";
3
-
4
- // Just enough of the MCP client protocol (Streamable HTTP) to ask a server for its tools.
5
-
6
- const PROTOCOL_VERSION = "2025-06-18";
7
- const TIMEOUT_MS = 10_000;
8
-
9
- // The names of the tools an MCP server offers, sorted. Returns null when the server won't say, or
10
- // can't be reached. Many only say once you've signed in, so `token` is sent if it's given.
11
- export async function listMcpTools(url, { fetch = globalThis.fetch, token, clientName = "agentschema" } = {}) {
12
- try {
13
- let sessionId = null;
14
- const send = async (message) => {
15
- const headers = { "content-type": "application/json", accept: "application/json, text/event-stream" };
16
- if (sessionId) headers["mcp-session-id"] = sessionId;
17
- if (token) headers.authorization = `Bearer ${token}`;
18
- const res = await fetch(url, { method: "POST", headers, body: JSON.stringify(message), signal: AbortSignal.timeout(TIMEOUT_MS) });
19
- sessionId = res.headers.get("mcp-session-id") ?? sessionId;
20
- if (!res.ok) throw new Error(`status ${res.status}`);
21
- return message.id === undefined ? null : parseResponse(await res.text(), message.id);
22
- };
23
-
24
- await send({
25
- jsonrpc: "2.0",
26
- id: 1,
27
- method: "initialize",
28
- params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: clientName, version: "0" } },
29
- });
30
- await send({ jsonrpc: "2.0", method: "notifications/initialized" });
31
-
32
- const names = [];
33
- let cursor;
34
- let id = 2;
35
- do {
36
- const { result } = await send({ jsonrpc: "2.0", id: id++, method: "tools/list", params: cursor ? { cursor } : {} });
37
- names.push(...result.tools.map((t) => t.name));
38
- cursor = result.nextCursor;
39
- } while (cursor);
40
- return [...new Set(names)].sort();
41
- } catch {
42
- return null;
43
- }
44
- }
45
-
46
- // The tool file for the server at `url`, now listing its tools, once there's a way to ask. Returns
47
- // { path, text }, or null if there's nothing to change: the file has a table already, so it may hold
48
- // choices worth keeping, or the agent has no file for that server, or it won't say what it offers.
49
- export async function listedMcpToolset(files, url, options = {}) {
50
- const servers = readInstance(files).agent?.data.mcp_servers;
51
- const server = Array.isArray(servers) ? servers.find((candidate) => candidate?.url === url) : null;
52
- if (!server) return null;
53
- const tool = readTools(files).tools.find((candidate) => candidate.data.type === MCP_TOOLSET && candidate.data.mcp_server_name === server.name);
54
- if (!tool || tool.rows?.length) return null;
55
-
56
- const names = await listMcpTools(url, options);
57
- if (!names?.length) return null;
58
- return { path: tool.file, text: mcpToolsetFile({ name: server.name, tools: names, permission: tool.data.default_config?.permission_policy?.type ?? "always_ask" }) };
59
- }
60
-
61
- // A response is either plain JSON, or a stream of events with the JSON in a `data:` line.
62
- function parseResponse(text, id) {
63
- const trimmed = text.trim();
64
- if (trimmed.startsWith("{")) return checked(JSON.parse(trimmed));
65
- for (const line of trimmed.split("\n")) {
66
- if (!line.startsWith("data:")) continue;
67
- const message = JSON.parse(line.slice(5));
68
- if (message.id === id) return checked(message);
69
- }
70
- throw new Error("no response");
71
- }
72
-
73
- function checked(message) {
74
- if (message.error) throw new Error(message.error.message);
75
- return message;
76
- }
package/src/oauth.js DELETED
@@ -1,215 +0,0 @@
1
- import { createHash, randomBytes } from "node:crypto";
2
- import { createServer } from "node:http";
3
- import { DeployError } from "./deploy.js";
4
-
5
- // OAuth for MCP servers, as the MCP authorization spec describes it: find the server's
6
- // authorization server from its URL, then sign in through the browser with the authorization
7
- // code flow and PKCE, receiving the code on a local port.
8
-
9
- // A DeployError, so the CLI reports it like any other failure.
10
- export class OAuthError extends DeployError {}
11
-
12
- const GOOGLE = "accounts.google.com";
13
-
14
- // Finds the OAuth endpoints for an MCP server from its URL alone.
15
- // Returns { resource, scopesSupported, issuer, authorizationEndpoint, tokenEndpoint,
16
- // registrationEndpoint, codeChallengeMethods }.
17
- export async function discover(serverUrl, { fetch = globalThis.fetch } = {}) {
18
- const url = new URL(serverUrl);
19
- const path = url.pathname.replace(/\/$/, "");
20
-
21
- // Protected resource metadata (RFC 9728): which authorization server the MCP server trusts. The
22
- // server can say where that is when it turns away a request with no token, and some put it where
23
- // the well-known addresses below wouldn't find it, so its word comes first.
24
- const hinted = await resourceMetadataHint(serverUrl, fetch);
25
- const resourceMeta =
26
- (hinted && (await getJSON(hinted, fetch))) ||
27
- (path && (await getJSON(`${url.origin}/.well-known/oauth-protected-resource${path}`, fetch))) ||
28
- (await getJSON(`${url.origin}/.well-known/oauth-protected-resource`, fetch));
29
- const issuer = resourceMeta?.authorization_servers?.[0] ?? url.origin;
30
-
31
- // Authorization server metadata (RFC 8414), or OpenID Connect discovery, which Google uses.
32
- const as = new URL(issuer);
33
- const asPath = as.pathname.replace(/\/$/, "");
34
- const candidates = [
35
- `${as.origin}/.well-known/oauth-authorization-server${asPath}`,
36
- `${as.origin}/.well-known/openid-configuration${asPath}`,
37
- ...(asPath ? [`${as.origin}${asPath}/.well-known/openid-configuration`] : []),
38
- ];
39
- let meta = null;
40
- for (const candidate of candidates) {
41
- meta = await getJSON(candidate, fetch);
42
- if (meta?.authorization_endpoint && meta?.token_endpoint) break;
43
- meta = null;
44
- }
45
- if (!meta) {
46
- throw new OAuthError(`couldn't find the OAuth sign-in for ${serverUrl}: ${issuer} publishes no authorization server metadata`);
47
- }
48
-
49
- return {
50
- resource: resourceMeta?.resource ?? null,
51
- scopesSupported: resourceMeta?.scopes_supported ?? meta.scopes_supported ?? [],
52
- issuer: meta.issuer ?? issuer,
53
- authorizationEndpoint: meta.authorization_endpoint,
54
- tokenEndpoint: meta.token_endpoint,
55
- registrationEndpoint: meta.registration_endpoint ?? null,
56
- codeChallengeMethods: meta.code_challenge_methods_supported ?? null,
57
- };
58
- }
59
-
60
- // Where the MCP server's 401 says its protected resource metadata is: the resource_metadata
61
- // parameter of its WWW-Authenticate header. Returns null when it doesn't say.
62
- async function resourceMetadataHint(serverUrl, fetch) {
63
- try {
64
- const res = await fetch(serverUrl, {
65
- method: "POST",
66
- headers: { "content-type": "application/json", accept: "application/json, text/event-stream" },
67
- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "agentschema", version: "0" } } }),
68
- signal: AbortSignal.timeout(10_000),
69
- });
70
- if (res.status !== 401) return null;
71
- const match = /\bresource_metadata\s*=\s*(?:"([^"]*)"|([^\s,]+))/i.exec(res.headers.get("www-authenticate") ?? "");
72
- const hint = match?.[1] ?? match?.[2];
73
- return hint && URL.canParse(hint) ? hint : null;
74
- } catch {
75
- return null;
76
- }
77
- }
78
-
79
- async function getJSON(url, fetch) {
80
- try {
81
- const res = await fetch(url, { headers: { accept: "application/json" } });
82
- if (!res.ok) return null;
83
- return await res.json();
84
- } catch {
85
- return null;
86
- }
87
- }
88
-
89
- // Starts the local server the browser is sent back to after signing in.
90
- // Returns { redirectUri, waitForCode(state, timeoutMs), close() }.
91
- export async function startCallbackServer(port = 0) {
92
- let deliver;
93
- const received = new Promise((resolve) => (deliver = resolve));
94
- const server = createServer((req, res) => {
95
- const url = new URL(req.url, "http://127.0.0.1");
96
- if (url.pathname !== "/callback") {
97
- res.writeHead(404).end();
98
- return;
99
- }
100
- const error = url.searchParams.get("error");
101
- res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
102
- res.end(
103
- `<!doctype html><title>agentschema</title><body style="font:16px system-ui;margin:4em auto;max-width:30em">` +
104
- (error ? `<h1>Sign-in failed</h1><p>${escape(error)}. Check the terminal.</p>` : "<h1>Signed in</h1><p>You can close this tab and go back to the terminal.</p>") +
105
- "</body>",
106
- );
107
- deliver(url.searchParams);
108
- });
109
- await new Promise((resolve, reject) => {
110
- server.once("error", (err) => reject(new OAuthError(`couldn't listen on 127.0.0.1:${port}: ${err.message}`)));
111
- server.listen(port, "127.0.0.1", resolve);
112
- });
113
- const redirectUri = `http://127.0.0.1:${server.address().port}/callback`;
114
-
115
- return {
116
- redirectUri,
117
- async waitForCode(state, timeoutMs = 5 * 60_000) {
118
- let timer;
119
- const timeout = new Promise((_, reject) => {
120
- timer = setTimeout(() => reject(new OAuthError("timed out waiting for the browser sign-in")), timeoutMs);
121
- });
122
- try {
123
- const params = await Promise.race([received, timeout]);
124
- const error = params.get("error");
125
- if (error) {
126
- const detail = params.get("error_description");
127
- throw new OAuthError(`sign-in failed: ${error}${detail ? ` (${detail})` : ""}`);
128
- }
129
- if (params.get("state") !== state) throw new OAuthError("sign-in failed: the response's state didn't match");
130
- const code = params.get("code");
131
- if (!code) throw new OAuthError("sign-in failed: no authorization code came back");
132
- return code;
133
- } finally {
134
- clearTimeout(timer);
135
- }
136
- },
137
- close: () => new Promise((resolve) => server.close(resolve)),
138
- };
139
- }
140
-
141
- const escape = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
142
-
143
- // Registers as an OAuth client (RFC 7591), for servers that allow it. `clientName` is what the
144
- // provider shows on its sign-in page. Returns { clientId, clientSecret, authMethod }.
145
- export async function registerClient(registrationEndpoint, redirectUri, { fetch = globalThis.fetch, clientName = "agentschema" } = {}) {
146
- const res = await fetch(registrationEndpoint, {
147
- method: "POST",
148
- headers: { "content-type": "application/json", accept: "application/json" },
149
- body: JSON.stringify({
150
- client_name: clientName,
151
- redirect_uris: [redirectUri],
152
- grant_types: ["authorization_code", "refresh_token"],
153
- response_types: ["code"],
154
- token_endpoint_auth_method: "none",
155
- }),
156
- });
157
- const body = await res.json().catch(() => ({}));
158
- if (!res.ok || !body.client_id) {
159
- throw new OAuthError(`couldn't register a client at ${registrationEndpoint} (${res.status}): ${body.error_description ?? body.error ?? "no client_id in the response"}`);
160
- }
161
- return {
162
- clientId: body.client_id,
163
- clientSecret: body.client_secret ?? null,
164
- authMethod: body.token_endpoint_auth_method ?? (body.client_secret ? "client_secret_post" : "none"),
165
- };
166
- }
167
-
168
- // The URL to send the browser to, and the PKCE verifier and state to finish with.
169
- export function authorizationRequest({ authorizationEndpoint, issuer, clientId, redirectUri, scope, resource }) {
170
- const verifier = base64url(randomBytes(32));
171
- const state = base64url(randomBytes(16));
172
- const url = new URL(authorizationEndpoint);
173
- const params = {
174
- response_type: "code",
175
- client_id: clientId,
176
- redirect_uri: redirectUri,
177
- code_challenge: base64url(createHash("sha256").update(verifier).digest()),
178
- code_challenge_method: "S256",
179
- state,
180
- };
181
- if (scope) params.scope = scope;
182
- if (resource) params.resource = resource;
183
- // Google only issues a refresh token for offline access, and only on a fresh consent.
184
- if (new URL(issuer).host === GOOGLE) Object.assign(params, { access_type: "offline", prompt: "consent" });
185
- for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
186
- return { url: url.toString(), verifier, state };
187
- }
188
-
189
- // Trades the authorization code for tokens.
190
- // Returns { accessToken, refreshToken, expiresAt, scope }.
191
- export async function exchangeCode({ tokenEndpoint, code, verifier, redirectUri, clientId, clientSecret, authMethod, resource }, { fetch = globalThis.fetch } = {}) {
192
- const form = new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: redirectUri, code_verifier: verifier });
193
- if (resource) form.set("resource", resource);
194
- const headers = { "content-type": "application/x-www-form-urlencoded", accept: "application/json" };
195
- if (authMethod === "client_secret_basic") {
196
- headers.authorization = `Basic ${Buffer.from(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`).toString("base64")}`;
197
- } else {
198
- form.set("client_id", clientId);
199
- if (authMethod === "client_secret_post") form.set("client_secret", clientSecret);
200
- }
201
-
202
- const res = await fetch(tokenEndpoint, { method: "POST", headers, body: form });
203
- const body = await res.json().catch(() => ({}));
204
- if (!res.ok || !body.access_token) {
205
- throw new OAuthError(`the token endpoint refused the sign-in (${res.status}): ${body.error_description ?? body.error ?? "no access token in the response"}`);
206
- }
207
- return {
208
- accessToken: body.access_token,
209
- refreshToken: body.refresh_token ?? null,
210
- expiresAt: body.expires_in ? new Date(Date.now() + Number(body.expires_in) * 1000).toISOString() : null,
211
- scope: body.scope ?? null,
212
- };
213
- }
214
-
215
- const base64url = (buf) => buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
package/src/prompts.js DELETED
@@ -1,159 +0,0 @@
1
- import { createInterface, emitKeypressEvents } from "node:readline";
2
-
3
- // Interactive questions, shared by `init` and `cred create`. In a terminal, choices are picked
4
- // with the arrow keys and secrets aren't echoed; with piped input, each answer is a line.
5
- //
6
- // text(question, fallback, { validate }) an empty reply keeps the fallback; validate returns
7
- // an error message, or nothing when the reply is fine
8
- // select(question, choices, fallback) one of `choices` (strings)
9
- // confirm(question, fallback) true or false
10
- // secret(question) a reply that isn't shown
11
- // close()
12
- //
13
- // Ctrl+C rejects with the error `cancelled()` returns.
14
- export function prompts(input, output, { cancelled = () => new Error("cancelled") } = {}) {
15
- const base = input.isTTY ? terminalPrompts(input, output, cancelled) : linePrompts(input, output, cancelled);
16
-
17
- const text = async (question, fallback = "", { validate } = {}) => {
18
- while (true) {
19
- const reply = await base.text(question, fallback);
20
- const problem = validate?.(reply);
21
- if (!problem) return reply;
22
- output.write(`${problem}\n`);
23
- if (base.ended?.()) throw cancelled();
24
- }
25
- };
26
- const confirm = async (question, fallback) => {
27
- while (true) {
28
- const reply = (await base.text(`${question} [y/n]`, fallback ? "y" : "n")).toLowerCase();
29
- if (/^(y|yes)$/.test(reply)) return true;
30
- if (/^(n|no)$/.test(reply)) return false;
31
- output.write("Answer y or n\n");
32
- }
33
- };
34
- return { ...base, text, confirm };
35
- }
36
-
37
- // Prompts for piped input: one answer per line, and choices picked by name or number.
38
- function linePrompts(input, output, cancelled) {
39
- const rl = createInterface({ input, output, terminal: false });
40
- const lines = rl[Symbol.asyncIterator]();
41
- let ended = false;
42
-
43
- const line = async () => {
44
- if (ended) return null;
45
- const { value, done } = await lines.next();
46
- if (done) {
47
- ended = true;
48
- output.write("\n");
49
- return null;
50
- }
51
- return value.trim();
52
- };
53
- const text = async (question, fallback) => {
54
- output.write(fallback ? `${question} (${fallback}) ` : `${question} `);
55
- return (await line()) || fallback;
56
- };
57
- const select = async (question, choices, fallback) => {
58
- const listed = choices.map((c, i) => `${i + 1}) ${c}`).join(" ");
59
- while (true) {
60
- const reply = await text(`${question} ${listed}`, String(choices.indexOf(fallback) + 1 || 1));
61
- const picked = choices[Number(reply) - 1] ?? choices.find((c) => c === reply);
62
- if (picked) return picked;
63
- output.write(`Pick one of: ${choices.join(", ")}\n`);
64
- if (ended) throw cancelled();
65
- }
66
- };
67
- const secret = async (question) => {
68
- output.write(`${question} `);
69
- const reply = await line();
70
- if (reply === null) throw cancelled();
71
- return reply;
72
- };
73
- return { text, select, secret, ended: () => ended, close: () => rl.close() };
74
- }
75
-
76
- const ESC = "\x1b[";
77
- const cyan = (s) => `${ESC}36m${s}${ESC}0m`;
78
- const dim = (s) => `${ESC}2m${s}${ESC}0m`;
79
-
80
- // Prompts for a terminal: choices are picked with the arrow keys and Enter.
81
- function terminalPrompts(input, output, cancelled) {
82
- // A fresh readline per question, so it doesn't fight the raw-mode select for the arrow keys.
83
- const text = (question, fallback) =>
84
- new Promise((resolve, reject) => {
85
- const rl = createInterface({ input, output, terminal: true });
86
- rl.on("SIGINT", () => {
87
- rl.close();
88
- output.write("\n");
89
- reject(cancelled());
90
- });
91
- rl.question(fallback ? `${question} ${dim(`(${fallback})`)} ` : `${question} `, (reply) => {
92
- rl.close();
93
- resolve(reply.trim() || fallback);
94
- });
95
- });
96
-
97
- const select = (question, choices, fallback) =>
98
- new Promise((resolve, reject) => {
99
- let index = Math.max(0, choices.indexOf(fallback));
100
- const render = (first) => {
101
- if (!first) output.write(`${ESC}${choices.length}A`);
102
- for (const [i, choice] of choices.entries()) {
103
- output.write(`${ESC}2K${i === index ? cyan(`❯ ${choice}`) : ` ${choice}`}\n`);
104
- }
105
- };
106
- const finish = (err) => {
107
- input.off("keypress", onKey);
108
- input.setRawMode(false);
109
- input.pause();
110
- // Collapse the list to one line with the answer.
111
- output.write(`${ESC}${choices.length + 1}A${ESC}J${ESC}?25h`);
112
- output.write(`${question} ${err ? dim("cancelled") : cyan(choices[index])}\n`);
113
- err ? reject(err) : resolve(choices[index]);
114
- };
115
- const onKey = (str, key = {}) => {
116
- if (key.ctrl && key.name === "c") return finish(cancelled());
117
- if (key.name === "return" || key.name === "enter") return finish();
118
- if (key.name === "up" || key.name === "k") index = (index - 1 + choices.length) % choices.length;
119
- else if (key.name === "down" || key.name === "j" || key.name === "tab") index = (index + 1) % choices.length;
120
- else if (/^[1-9]$/.test(str ?? "") && Number(str) <= choices.length) index = Number(str) - 1;
121
- else return;
122
- render(false);
123
- };
124
-
125
- emitKeypressEvents(input);
126
- input.setRawMode(true);
127
- input.resume();
128
- output.write(`${question} ${dim("(↑/↓, Enter)")}\n${ESC}?25l`);
129
- render(true);
130
- input.on("keypress", onKey);
131
- });
132
-
133
- // Not echoed, so the secret doesn't end up on screen or in the scrollback; pasting works.
134
- const secret = (question) =>
135
- new Promise((resolve, reject) => {
136
- output.write(`${question} ${dim("(hidden)")} `);
137
- input.setRawMode(true);
138
- input.resume();
139
- let answer = "";
140
- const finish = (err) => {
141
- input.off("data", onData);
142
- input.setRawMode(false);
143
- input.pause();
144
- output.write("\n");
145
- err ? reject(err) : resolve(answer.trim());
146
- };
147
- const onData = (chunk) => {
148
- for (const ch of chunk.toString("utf8")) {
149
- if (ch === "\r" || ch === "\n") return finish();
150
- if (ch === "\u0003") return finish(cancelled());
151
- if (ch === "\u007f" || ch === "\b") answer = answer.slice(0, -1);
152
- else if (ch >= " ") answer += ch;
153
- }
154
- };
155
- input.on("data", onData);
156
- });
157
-
158
- return { text, select, secret, close() {} };
159
- }