Skip to content

Commit

Permalink
chore: fix eslint errors
Browse files Browse the repository at this point in the history
  • Loading branch information
waylaidwanderer committed Mar 8, 2023
1 parent ec84815 commit c927593
Show file tree
Hide file tree
Showing 11 changed files with 178 additions and 154 deletions.
7 changes: 7 additions & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,12 @@ module.exports = {
'no-plusplus': ['error', { 'allowForLoopAfterthoughts': true }],
'no-console': 'off',
'import/extensions': 'off',
'no-use-before-define': ['error', {
'functions': false,
}],
'no-promise-executor-return': 'off',
'no-param-reassign': 'off',
'no-continue': 'off',
'no-restricted-syntax': 'off',
},
};
55 changes: 32 additions & 23 deletions bin/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,16 @@
import fs from 'fs';
import { pathToFileURL } from 'url';
import { KeyvFile } from 'keyv-file';
import ChatGPTClient from '../src/ChatGPTClient.js';
import boxen from 'boxen';
import ora from 'ora';
import clipboard from 'clipboardy';
import inquirer from 'inquirer';
import inquirerAutocompletePrompt from 'inquirer-autocomplete-prompt';
import ChatGPTClient from '../src/ChatGPTClient.js';
import BingAIClient from '../src/BingAIClient.js';

const arg = process.argv.find((arg) => arg.startsWith('--settings'));
let path;
if (arg) {
path = arg.split('=')[1];
} else {
path = './settings.js';
}
const arg = process.argv.find(_arg => _arg.startsWith('--settings'));
const path = arg?.split('=')[1] ?? './settings.js';

let settings;
if (fs.existsSync(path)) {
Expand All @@ -25,9 +20,9 @@ if (fs.existsSync(path)) {
settings = (await import(pathToFileURL(fullPath).toString())).default;
} else {
if (arg) {
console.error(`Error: the file specified by the --settings parameter does not exist.`);
console.error('Error: the file specified by the --settings parameter does not exist.');
} else {
console.error(`Error: the settings.js file does not exist.`);
console.error('Error: the settings.js file does not exist.');
}
process.exit(1);
}
Expand Down Expand Up @@ -95,7 +90,9 @@ switch (clientToUse) {
break;
}

console.log(tryBoxen('ChatGPT CLI', { padding: 0.7, margin: 1, borderStyle: 'double', dimBorder: true }));
console.log(tryBoxen('ChatGPT CLI', {
padding: 0.7, margin: 1, borderStyle: 'double', dimBorder: true,
}));

await conversation();

Expand All @@ -116,13 +113,13 @@ async function conversation() {
prompt.ui.activePrompt.firstRender = false;
// The below is a hack to allow selecting items from the autocomplete menu while also being able to submit messages.
// This basically simulates a hybrid between having `suggestOnly: false` and `suggestOnly: true`.
await new Promise((resolve) => setTimeout(resolve, 0));
await new Promise(resolve => setTimeout(resolve, 0));
prompt.ui.activePrompt.opt.source = (answers, input) => {
if (!input) {
return [];
}
prompt.ui.activePrompt.opt.suggestOnly = !input.startsWith('!');
return availableCommands.filter((command) => command.value.startsWith(input));
return availableCommands.filter(command => command.value.startsWith(input));
};
let { message } = await prompt;
message = message.trim();
Expand All @@ -143,6 +140,8 @@ async function conversation() {
return deleteAllConversations();
case '!exit':
return true;
default:
return conversation();
}
}
return onMessage(message);
Expand Down Expand Up @@ -172,7 +171,9 @@ async function onMessage(message) {
...conversationData,
onProgress: (token) => {
reply += token;
const output = tryBoxen(`${reply.trim()}█`, { title: aiLabel, padding: 0.7, margin: 1, dimBorder: true });
const output = tryBoxen(`${reply.trim()}█`, {
title: aiLabel, padding: 0.7, margin: 1, dimBorder: true,
});
spinner.text = `${spinnerPrefix}\n${output}`;
},
});
Expand All @@ -192,10 +193,10 @@ async function onMessage(message) {
conversationData = {
parentMessageId: response.messageId,
jailbreakConversationId: response.jailbreakConversationId,
//conversationId: response.conversationId,
//conversationSignature: response.conversationSignature,
//clientId: response.clientId,
//invocationId: response.invocationId,
// conversationId: response.conversationId,
// conversationSignature: response.conversationSignature,
// clientId: response.clientId,
// invocationId: response.invocationId,
};
break;
default:
Expand All @@ -206,7 +207,9 @@ async function onMessage(message) {
break;
}
await client.conversationsCache.set('lastConversation', conversationData);
const output = tryBoxen(responseText, { title: aiLabel, padding: 0.7, margin: 1, dimBorder: true });
const output = tryBoxen(responseText, {
title: aiLabel, padding: 0.7, margin: 1, dimBorder: true,
});
console.log(output);
} catch (error) {
spinner.stop();
Expand Down Expand Up @@ -271,7 +274,7 @@ async function copyConversation() {
// get the last message ID
const lastMessageId = messages[messages.length - 1].id;
const orderedMessages = ChatGPTClient.getMessagesForConversation(messages, lastMessageId);
const conversationString = orderedMessages.map((message) => `#### ${message.role}:\n${message.message}`).join('\n\n');
const conversationString = orderedMessages.map(message => `#### ${message.role}:\n${message.message}`).join('\n\n');
try {
await clipboard.write(`${conversationString}\n\n----\nMade with ChatGPT CLI: <https://github.com/waylaidwanderer/node-chatgpt-api>`);
logSuccess('Copied conversation to clipboard.');
Expand All @@ -282,15 +285,21 @@ async function copyConversation() {
}

function logError(message) {
console.log(tryBoxen(message, { title: 'Error', padding: 0.7, margin: 1, borderColor: 'red' }));
console.log(tryBoxen(message, {
title: 'Error', padding: 0.7, margin: 1, borderColor: 'red',
}));
}

function logSuccess(message) {
console.log(tryBoxen(message, { title: 'Success', padding: 0.7, margin: 1, borderColor: 'green' }));
console.log(tryBoxen(message, {
title: 'Success', padding: 0.7, margin: 1, borderColor: 'green',
}));
}

function logWarning(message) {
console.log(tryBoxen(message, { title: 'Warning', padding: 0.7, margin: 1, borderColor: 'yellow' }));
console.log(tryBoxen(message, {
title: 'Warning', padding: 0.7, margin: 1, borderColor: 'yellow',
}));
}

/**
Expand Down
41 changes: 18 additions & 23 deletions bin/server.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,16 @@
#!/usr/bin/env node
import fastify from 'fastify';
import cors from '@fastify/cors';
import { FastifySSEPlugin } from "@waylaidwanderer/fastify-sse-v2";
import { FastifySSEPlugin } from '@waylaidwanderer/fastify-sse-v2';
import fs from 'fs';
import { pathToFileURL } from 'url'
import { pathToFileURL } from 'url';
import { KeyvFile } from 'keyv-file';
import ChatGPTClient from '../src/ChatGPTClient.js';
import ChatGPTBrowserClient from '../src/ChatGPTBrowserClient.js';
import BingAIClient from '../src/BingAIClient.js';
import { KeyvFile } from 'keyv-file';

const arg = process.argv.find((arg) => arg.startsWith('--settings'));
let path;
if (arg) {
path = arg.split('=')[1];
} else {
path = './settings.js';
}
const arg = process.argv.find(_arg => _arg.startsWith('--settings'));
const path = arg?.split('=')[1] ?? './settings.js';

let settings;
if (fs.existsSync(path)) {
Expand All @@ -24,9 +19,9 @@ if (fs.existsSync(path)) {
settings = (await import(pathToFileURL(fullPath).toString())).default;
} else {
if (arg) {
console.error(`Error: the file specified by the --settings parameter does not exist.`);
console.error('Error: the file specified by the --settings parameter does not exist.');
} else {
console.error(`Error: the settings.js file does not exist.`);
console.error('Error: the settings.js file does not exist.');
}
process.exit(1);
}
Expand Down Expand Up @@ -152,7 +147,7 @@ server.post('/conversation', async (request, reply) => {

server.listen({
port: settings.apiOptions?.port || settings.port || 3000,
host: settings.apiOptions?.host || 'localhost'
host: settings.apiOptions?.host || 'localhost',
}, (error) => {
if (error) {
console.error(error);
Expand All @@ -164,8 +159,8 @@ function nextTick() {
return new Promise(resolve => setTimeout(resolve, 0));
}

function getClient(clientToUse) {
switch (clientToUse) {
function getClient(clientToUseForMessage) {
switch (clientToUseForMessage) {
case 'bing':
return new BingAIClient(settings.bingAiClient);
case 'chatgpt-browser':
Expand All @@ -180,7 +175,7 @@ function getClient(clientToUse) {
settings.cacheOptions,
);
default:
throw new Error(`Invalid clientToUse: ${clientToUse}`);
throw new Error(`Invalid clientToUse: ${clientToUseForMessage}`);
}
}

Expand All @@ -189,9 +184,9 @@ function getClient(clientToUse) {
* `settings.js` > `apiOptions.perMessageClientOptionsWhitelist`.
* Returns original object if no whitelist is set.
* @param {*} inputOptions
* @param clientToUse
* @param clientToUseForMessage
*/
function filterClientOptions(inputOptions, clientToUse) {
function filterClientOptions(inputOptions, clientToUseForMessage) {
if (!inputOptions || !perMessageClientOptionsWhitelist) {
return null;
}
Expand All @@ -202,25 +197,25 @@ function filterClientOptions(inputOptions, clientToUse) {
&& inputOptions.clientToUse
&& perMessageClientOptionsWhitelist.validClientsToUse.includes(inputOptions.clientToUse)
) {
clientToUse = inputOptions.clientToUse;
clientToUseForMessage = inputOptions.clientToUse;
} else {
inputOptions.clientToUse = clientToUse;
inputOptions.clientToUse = clientToUseForMessage;
}

const whitelist = perMessageClientOptionsWhitelist[clientToUse];
const whitelist = perMessageClientOptionsWhitelist[clientToUseForMessage];
if (!whitelist) {
// No whitelist, return all options
return inputOptions;
}

const outputOptions = {};

for (let property in inputOptions) {
for (const property of Object.keys(inputOptions)) {
const allowed = whitelist.includes(property);

if (!allowed && typeof inputOptions[property] === 'object') {
// Check for nested properties
for (let nestedProp in inputOptions[property]) {
for (const nestedProp of Object.keys(inputOptions[property])) {
const nestedAllowed = whitelist.includes(`${property}.${nestedProp}`);
if (nestedAllowed) {
outputOptions[property] = outputOptions[property] || {};
Expand Down
2 changes: 1 addition & 1 deletion demos/use-api-server-streaming.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ try {
throw new Error(`Failed to send message. HTTP ${response.status} - ${response.statusText}`);
},
onclose() {
throw new Error(`Failed to send message. Server closed the connection unexpectedly.`);
throw new Error('Failed to send message. Server closed the connection unexpectedly.');
},
onerror(err) {
throw err;
Expand Down
2 changes: 1 addition & 1 deletion demos/use-browser-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const response3 = await chatGptClient.sendMessage('Now write it in French.', {
parentMessageId: response2.messageId,
// If you want streamed responses, you can set the `onProgress` callback to receive the response as it's generated.
// You will receive one token at a time, so you will need to concatenate them yourself.
onProgress: (token) => process.stdout.write(token),
onProgress: token => process.stdout.write(token),
});
console.log();
console.log(response3.response); // Les chats sont les meilleurs animaux de compagnie du monde.
4 changes: 2 additions & 2 deletions demos/use-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ response = await chatGptClient.sendMessage('Now write it in French.', {
parentMessageId: response.messageId,
// If you want streamed responses, you can set the `onProgress` callback to receive the response as it's generated.
// You will receive one token at a time, so you will need to concatenate them yourself.
onProgress: (token) => process.stdout.write(token),
onProgress: token => process.stdout.write(token),
});
console.log();
console.log(response.response); // Doux et élégant, avec des yeux qui brillent,\nLes chats sont des créatures de grâce suprême.\n...
Expand All @@ -62,7 +62,7 @@ response = await chatGptClient.sendMessage('Repeat my 2nd message verbatim.', {
parentMessageId: response.messageId,
// If you want streamed responses, you can set the `onProgress` callback to receive the response as it's generated.
// You will receive one token at a time, so you will need to concatenate them yourself.
onProgress: (token) => process.stdout.write(token),
onProgress: token => process.stdout.write(token),
});
console.log();
console.log(response.response); // "Write a short poem about cats."
2 changes: 1 addition & 1 deletion settings.example.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,4 @@ export default {
// (Optional) Possible options: "chatgpt", "bing".
// clientToUse: 'bing',
},
}
};
Loading

0 comments on commit c927593

Please sign in to comment.