-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.ts
51 lines (41 loc) · 1.41 KB
/
config.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { readFileSync, writeFileSync, existsSync } from "fs";
import { homedir } from "os";
import enquirer from "enquirer";
import { ClientConfig, refreshAccessToken } from "./client.js";
// Thanks to https://github.com/RomanHotsiy/commitgpt for the foundation of this
const CONFIG_FILE_NAME = `${homedir()}/.textadventure-gpt.json`;
export async function ensureSessionToken(): Promise<string> {
let config: Partial<ClientConfig> = {};
if (existsSync(CONFIG_FILE_NAME)) {
config = JSON.parse(readFileSync(CONFIG_FILE_NAME, "utf-8"));
}
if (!config.sessionToken) {
config.sessionToken = await promptToken();
}
while (true) {
try {
await refreshAccessToken(config.sessionToken);
writeFileSync(CONFIG_FILE_NAME, JSON.stringify(config, null, 2));
return config.sessionToken;
} catch (e) {
console.log("Invalid token. Please try again.");
config.sessionToken = await promptToken();
}
}
}
async function promptToken() {
try {
console.log(
"Follow instructions here to get your OpenAI session token: https://github.com/syndimann/textadventuregpt#get-your-session-token"
);
const answer = await enquirer.prompt<{ sessionToken: string }>({
type: "password",
name: "sessionToken",
message: "Paste your session token here:",
});
return answer.sessionToken;
} catch (e) {
console.log("Aborted.");
process.exit(1);
}
}