UNPKG

lxrbckl

Version:

CRUD functionality to enhance readability and abstraction in projects, for both local and remote file management.

442 lines (433 loc) 12.7 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { step(generator.next(value)); } catch (e) { reject(e); } }; var rejected = (value) => { try { step(generator.throw(value)); } catch (e) { reject(e); } }; var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); step((generator = generator.apply(__this, __arguments)).next()); }); }; // index.ts var lxRbckl_exports = {}; __export(lxRbckl_exports, { axiosGet: () => axiosGet, dirDel: () => dirDel, dirGet: () => dirGet, dirSet: () => dirSet, discord: () => discord, fileDel: () => fileDel, fileGet: () => fileGet, fileSet: () => fileSet, getProjectPath: () => getProjectPath, octokit: () => octokit, openai: () => openai }); module.exports = __toCommonJS(lxRbckl_exports); // src/services/axios.ts var axios = require("axios"); function axiosGet(url) { return __async(this, null, function* () { try { const response = yield axios.get(url); return response.data; } catch (error) { console.log("Error: ", error, "\nUrl: ", url); } }); } // src/services/local.ts var import_path = __toESM(require("path")); var import_promises = require("fs/promises"); function getProjectPath(file = "", delimeter = "/") { const dir = import_path.default.dirname(__filename).split(/[]/); const base = dir.includes("node_modules") ? -4 : -1; return [...dir.slice(0, base), file.split(/[/\\]/)].join(delimeter); } function fileSet(_0, _1) { return __async(this, arguments, function* (data, file, indent = 3, path2 = getProjectPath()) { try { yield (0, import_promises.writeFile)( path2 + file, file.endsWith(".json") ? JSON.stringify(data, null, indent) : data ); } catch (error) { console.log(`Error: ${error} Path: ${path2 + file}`); } }); } function fileGet(_0) { return __async(this, arguments, function* (file, path2 = getProjectPath(), encoding = "utf8") { try { const fin = yield (0, import_promises.readFile)(path2 + file, encoding); return file.endsWith(".json") ? JSON.parse(fin.toString()) : fin; } catch (error) { console.log(`Error: ${error} Path: ${path2 + file}`); } }); } function fileDel(_0) { return __async(this, arguments, function* (file, path2 = getProjectPath()) { try { yield (0, import_promises.unlink)(path2 + file); } catch (error) { console.log(`Error: ${error} Path: ${path2 + file}`); } }); } function dirSet(_0) { return __async(this, arguments, function* (dir, path2 = getProjectPath()) { try { yield (0, import_promises.mkdir)(path2 + dir); } catch (error) { console.log(`Error: ${error} Path: ${path2 + dir}`); } }); } function dirGet(_0) { return __async(this, arguments, function* (dir, path2 = getProjectPath()) { try { return yield (0, import_promises.readdir)(path2 + dir); } catch (error) { console.log(`Error: ${error} Path: ${path2 + dir}`); } }); } function dirDel(_0) { return __async(this, arguments, function* (dir, path2 = getProjectPath()) { try { yield (0, import_promises.rmdir)(path2 + dir); } catch (error) { console.log(`Error: ${error} Path: ${path2 + dir}`); } }); } // src/services/openai.ts var import_util = require("util"); var import_child_process = require("child_process"); var openai = class { constructor({ token, model = "gpt-4o", temperature = 1.5 }) { this._token = token; this._model = model; this._temperature = temperature; } query(prompt) { return __async(this, null, function* () { const query = ` curl -X POST https://api.openai.com/v1/chat/completions -H "Content-Type: application/json" -H "Authorization: Bearer ${this._token}" -d '{ "model" : "${this._model}", "temperature" : ${this._temperature}, "messages" : [ { "role" : "system", "content" : "You are a helpful assistant." }, { "role" : "user", "content" : "${prompt}" } ] }' `; const execPromise = (0, import_util.promisify)(import_child_process.exec); const { stdout, stderr } = yield execPromise(query); return JSON.parse(stdout).choices[0].message.content; }); } }; // src/services/octokit.ts var import_rest = require("@octokit/rest"); var octokit = class { constructor({ token, owner, indent = 3, stringEncoding = "utf8", bufferEncoding = "base64" }) { this._token = token; this._owner = owner; this._indent = indent; this._stringEncoding = stringEncoding; this._bufferEncoding = bufferEncoding; this._octokit = new import_rest.Octokit({ auth: this._token }); } set owner(newOwner) { this._owner = newOwner; } request(_0) { return __async(this, arguments, function* ({ endpoint, parameters = {}, elementFromProperty = "", propertyFromResult = "data" }) { let response = yield this._octokit.request(endpoint, parameters); switch (elementFromProperty == "") { case true: return response[propertyFromResult]; case false: return response[propertyFromResult].map((i) => i[elementFromProperty]); } }); } endpointFile({ file, method, repository, branch = void 0 }) { let endpoint = ""; endpoint += `${method} /repos/${this._owner}/${repository}/contents/${file}`; endpoint += branch ? `?ref=${branch}` : ""; return endpoint; } repositoryGet(_0) { return __async(this, arguments, function* ({ file, branch, repository, displayError = false, propertyFromResult = "content" }) { let endpoint = this.endpointFile({ file, method: "GET", branch, repository }); try { let data = yield this.request({ endpoint, parameters: { ref: branch } }); switch (propertyFromResult == "content") { case false: return data[propertyFromResult]; case true: let encoding = data.encoding; let buffer = Buffer.from(data.content, encoding); let fileEnding = file.split(".").splice(-1)[0]; let result = buffer.toString(this._stringEncoding); switch (fileEnding) { case "json": return JSON.parse(result); default: return result; } } } catch (error) { displayError ? console.log("Error: ", error) : void 0; return false; } }); } respositorySet(_0) { return __async(this, arguments, function* ({ data, file, branch, repository, retryOnError = 0, displayError = false, commitMessage = "Automated Action" }) { let fileEnding = file.split(".").splice(-1)[0]; switch (fileEnding) { case "json": data = JSON.stringify(data, null, this._indent); break; } let endpoint = this.endpointFile({ file, method: "PUT", branch, repository }); try { yield this._octokit.request(endpoint, { branch, owner: this._owner, message: commitMessage, content: Buffer.from(data).toString(this._bufferEncoding), sha: yield this.repositoryGet({ file, branch, repository, propertyFromResult: "sha", displayError }) }); return true; } catch (error) { displayError ? console.log("Error: ", error) : void 0; if (retryOnError == 0) { return false; } else { return yield this.respositorySet({ data, file, branch, repository, displayError, commitMessage, retryOnError: retryOnError - 1 }); } } }); } }; // src/services/discord.ts var import_discord = require("discord.js"); var discord = class { constructor({ guildId, channelId, applicationId, commands = {}, version = "10", intents = [ import_discord.IntentsBitField.Flags.Guilds, import_discord.IntentsBitField.Flags.GuildMembers, import_discord.IntentsBitField.Flags.GuildMessages, import_discord.IntentsBitField.Flags.MessageContent ] }) { this._version = version; this._intents = intents; this._guildId = guildId; this.commands = commands; this._channelId = channelId; this._applicationId = applicationId; this._client = new import_discord.Client({ intents: this._intents, rest: { version: this._version } }); } // required // login({ token }) { this._client.login(token); } // required // registerCommands() { this._client.rest.put( import_discord.Routes.applicationGuildCommands( this._applicationId, this._guildId ), { body: Object.values(this.commands).map((c) => c.context()) } ); } // suggested // registerOnReady(callback) { return __async(this, null, function* () { this._client.on("ready", () => __async(this, null, function* () { yield callback(); })); }); } // suggested // registerInteractionCreate(callback) { return __async(this, null, function* () { this._client.on("interactionCreate", (interaction) => __async(this, null, function* () { yield callback(interaction); })); }); } // optional // registerCommandChoices() { return __async(this, null, function* () { yield Promise.all( Object.values(this.commands).filter((c) => c.registerChoices).map((c) => c.registerChoices()) ); }); } // optional // messageChannel({ content, codeBlock = "", isInline = false, isSpoiler = false }) { try { if (content.length > 0) { let channel = this._client.channels.cache.get(this._channelId); if (channel instanceof import_discord.TextChannel) { content = isInline ? `\` ${content} \`` : content; content = isSpoiler ? `|| ${content} ||` : content; content = codeBlock ? `\`\`\`${codeBlock} ${content}\`\`\`` : content; channel.send(content); } } else { console.log("There is no content."); } } catch (error) { console.log("Error: ", error, "\nChannelId: ", this._channelId); } } // optional // terminate() { this._client.destroy(); } }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { axiosGet, dirDel, dirGet, dirSet, discord, fileDel, fileGet, fileSet, getProjectPath, octokit, openai });