From f1b9b3901e4854b886e19094a35c8276c82d254a Mon Sep 17 00:00:00 2001 From: = <=> Date: Sat, 11 Mar 2023 03:02:39 -0500 Subject: [PATCH] Imported to Git --- .eslintrc.js | 41 ++++++++++++++++++ .gitignore | 4 ++ package.json | 20 +++++++++ repl.js | 9 ++++ src/ClientContainer.ts | 31 ++++++++++++++ src/Kettle.ts | 48 ++++++++++++++++++++++ src/Models/Repository.ts | 89 ++++++++++++++++++++++++++++++++++++++++ src/Models/User.ts | 42 +++++++++++++++++++ todo.md | 66 +++++++++++++++++++++++++++++ tsconfig.json | 71 ++++++++++++++++++++++++++++++++ 10 files changed, 421 insertions(+) create mode 100644 .eslintrc.js create mode 100644 .gitignore create mode 100644 package.json create mode 100644 repl.js create mode 100644 src/ClientContainer.ts create mode 100644 src/Kettle.ts create mode 100644 src/Models/Repository.ts create mode 100644 src/Models/User.ts create mode 100644 todo.md create mode 100644 tsconfig.json diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..f28bf55 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,41 @@ +module.exports = { + "env": { + "es6": true, + "node": true + }, + "extends": [ + "eslint:recommended", + "plugin:@typescript-eslint/eslint-recommended", + "plugin:@typescript-eslint/recommended" + ], + "globals": { + "Atomics": "readonly", + "SharedArrayBuffer": "readonly" + }, + "parser": "@typescript-eslint/parser", + "parserOptions": { + "ecmaVersion": 11, + "sourceType": "module" + }, + "plugins": [ + "@typescript-eslint" + ], + "rules": { + "indent": [ + "error", + 4 + ], + "linebreak-style": [ + "error", + "unix" + ], + "quotes": [ + "error", + "single" + ], + "semi": [ + "error", + "always" + ] + } +}; diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f9e84f4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +apikey +node_modules/ +out/ +package-lock.json \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..1d06fcf --- /dev/null +++ b/package.json @@ -0,0 +1,20 @@ +{ + "name": "kettle", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "repl": "tsc && node ./repl.js", + "run": "tsc " + }, + "author": "Xetanai", + "license": "MIT", + "devDependencies": { + "@typescript-eslint/eslint-plugin": "^4.22.0", + "typescript": "^4.2.4" + }, + "dependencies": { + "axios": "^0.21.1" + } +} diff --git a/repl.js b/repl.js new file mode 100644 index 0000000..0ff7124 --- /dev/null +++ b/repl.js @@ -0,0 +1,9 @@ +const repl = require("repl"); +const { default: Kettle } = require("./out/Kettle"); +const { default: User } = require("./out/Models/User"); +const { default: Repository } = require("./out/Models/Repository"); + +AdminClient = new Kettle("http://localhost:3000","409d7b787cadcb281ed38ce4385dd8a40ce72578"); +UserClient = new Kettle("http://localhost:3000", "5e0ef8de53839d3807cc04d12fc6f21732f46d9d"); + +repl.start("> "); \ No newline at end of file diff --git a/src/ClientContainer.ts b/src/ClientContainer.ts new file mode 100644 index 0000000..2603fc5 --- /dev/null +++ b/src/ClientContainer.ts @@ -0,0 +1,31 @@ +import axios from "axios"; + +class ClientContainer { + host: string; + token: string; + + constructor(host: string, token: string) { + this.token = token; + this.host = host; + + // TODO: Consider doing nothing to the host + // Alternatively, make an attempt raw, then make + // an attempt after appending during validation + // This way, weird server configs will work. + if(!host.endsWith("/api/v1")) { + this.host += "/api/v1"; + } + } + + public async _get(endpoint: string) { + const response = await axios.get( + this.host+endpoint, + { + headers: {'Authorization': 'token '+ this.token} + } + ); + return response.data; + } +} + +export default ClientContainer; \ No newline at end of file diff --git a/src/Kettle.ts b/src/Kettle.ts new file mode 100644 index 0000000..711634a --- /dev/null +++ b/src/Kettle.ts @@ -0,0 +1,48 @@ +import ClientContainer from "./ClientContainer"; +import Repository from "./Models/Repository"; +import User from "./Models/User"; + +class Kettle extends ClientContainer { + // TODO: Make custom errors that are easier to catch and handle + // than the axios ones currently forwarded + + constructor(host: string, token: string) { + super(host, token); + // TODO: Test the credentials. + // We can do this by checking version with the server + // Or, fetch our SelfUser to go ahead and cache it + // TODO: Also confirm both above endpoints error on incorrect creds + // TODO: Also also, see if unauthenticated Clients are possible + } + + // TODO: Cache + /** + * @returns The User this object makes requests as + */ + public getSelfUser(): Promise { + return User._get(this); + } + + /** + * + * @param username The username of the target, or null for self + * @returns The User, if they exist + */ + public getUser(username?: string): Promise { + return User._get(this, username); + } + + public getRepository(ownerOrOwnRepositoryName: string, repositoryName?: string): Promise { + return Repository._get(this, ownerOrOwnRepositoryName, repositoryName); + } + + public _getClientContainer() { + return new ClientContainer(this.host, this.token); + } + + public static getClientUser(client: ClientContainer): Promise { + return User._get(client); + } +} + +export default Kettle; \ No newline at end of file diff --git a/src/Models/Repository.ts b/src/Models/Repository.ts new file mode 100644 index 0000000..63758bf --- /dev/null +++ b/src/Models/Repository.ts @@ -0,0 +1,89 @@ +import ClientContainer from "../ClientContainer"; +import Kettle from "../Kettle"; +import User from "./User"; + +class Repository { + readonly api: ClientContainer; + + // TODO: Implement outcommented properties + allow_merge_commits!: boolean; + allow_rebase!: boolean; + allow_rebase_explicit!: boolean; + allow_squash_merge!: boolean; + archived!: boolean; + avatar_url!: string; + clone_url!: string; + created_at!: string; // Date-time + default_branch!: string; + description!: string; + empty!: boolean; + // external_tracker: ExternalTracker; + // external_wiki: ExternalWiki; + fork!: boolean; + forks_count!: number; + full_name!: string; + has_issues!: boolean; + has_projects!: boolean; + has_pull_requests!: boolean; + has_wiki!: boolean; + html_url!: string; + id!: number; + ignore_whitespace_conflicts!: boolean; + internal!: boolean; + // internal_tracker: InternalTracker; + mirror!: boolean; + mirror_interval!: string; + name!: string; + open_issues_count!: number; + open_pr_counter!: number; + original_url!: string; + owner: User; + // TODO: Research this. Swagger says it's an empty, typeless object. + // Interestingly enough, in practice it sometimes doesn't exist at all. + // Current theory is a shallow copy of a fork's source. + parent: unknown; + // permissions: Permission; + private!: boolean; + release_counter!: number; + size!: number; + ssh_url!: string; + stars_count!: number; + template!: boolean; + updated_at!: string; //Date-time + watchers_count!: number; + website!: string; + + constructor(client: ClientContainer, data: any) { + Object.assign(this, data); + + this.owner = new User(client, data.owner); + this.api = client; + } + + public equals(repo: Repository) + { + return this.id === repo.id; + } + + public static async _get(client: ClientContainer, ownerOrOwnRepositoryName: string, repositoryName?: string) { + // In most cases, both parameters are filled + let owner = ownerOrOwnRepositoryName; + let repository = repositoryName; + + if (repositoryName == undefined) { + // No owner was given, we can assume we want our client's own repository + // ownerOrOwnRepositoryName is assumed to be the repository name + + // TODO: Cache our selfuser and get this from cache + owner = (await User._get(client)).login; + repository = ownerOrOwnRepositoryName; + } + + const res = await client._get(`/repos/${owner}/${repository}`); + + return new Repository(client, res); + } + +} + +export default Repository; \ No newline at end of file diff --git a/src/Models/User.ts b/src/Models/User.ts new file mode 100644 index 0000000..8bdfe9d --- /dev/null +++ b/src/Models/User.ts @@ -0,0 +1,42 @@ +import axios from "axios"; +import ClientContainer from "../ClientContainer"; +import Kettle from "../Kettle"; +import Repository from "./Repository"; + +class User { + readonly api: ClientContainer; + + readonly avatar_url!: string; + readonly created!: string; // Date-time + readonly email!: string; // Email + readonly full_name!: string; + readonly id!: number; + readonly is_admin!: boolean; + readonly language!: string; + readonly last_login!: string; // Date-time + readonly login!: string; + readonly restricted!: boolean; + + constructor(client: ClientContainer, data: any) { + Object.assign(this, data); + this.api = client; + } + + public equals(user: User) { + return this.id === user.id; + } + + public static async _get(client: ClientContainer, username?: string) { + let res = null; + if(username === undefined) { + res = await client._get('/user'); + } else { + res = await client._get('/users/'+ username); + } + + return new User(client, res); + } + +} + +export default User; \ No newline at end of file diff --git a/todo.md b/todo.md new file mode 100644 index 0000000..c64ed09 --- /dev/null +++ b/todo.md @@ -0,0 +1,66 @@ +# Endpoint coverage todo list + +**In order of appearance on `/api/swagger`** + +--- + +## Admin +Methods | Endpoint +------- | -------- +`get` | `/admin/cron` +`post` | `/admin/cron/{task}` +`get` | `/admin/orgs` +`get` | `/admin/unadopted` +`post, delete` | `/admin/unadopted/{owner}/{repo}` +`get, post` | `/admin/users` +`delete, patch` | `/admin/users/{username}` +`post` | `/admin/users/{username}/keys` +`delete` | `/admin/users/{username}/keys/{id}` +`post` | `/admin/users/{username}/orgs` +`post` | `/admin/users/{username}/repos` +--- +## Miscellaneous +Methods | Endpoint +------- | -------- +`post` | `/markdown` +`post` | `/markdown/raw` +`get` | `/signing-key.gpg` +`get` | `/version` +--- +## Notifications +Methods | Endpoint +------- | -------- +`get, put` | `/notifications` +`get` | `/notifications/new` +`get, patch` | `/notifications/threads/{id}` +`get, put` | `/repos/{owner}/{repo}/notifications` +## Organizations +Methods | Endpoint +------- | -------- +`get, post` | `/orgs` +`get, delete, patch` | `/orgs/{org}` +`get, post` | `/orgs/{org}/hooks` +`get, delete, patch` | `/orgs/{org}/hooks/{id}` +`get, post` | `/orgs/{org}/labels` +`get, delete, patch` | `/orgs/{org}/labels/{id}` +`get` | `/orgs/{org}/members` +`get, delete` | `/orgs/{org}/members/{username}` +`get` | `/orgs/{org}/public_members` +`get, put, delete` | `/orgs/{org}/public_members/{username}` +`get, post` | `/orgs/{org}/repos` +`get, post` | `/orgs/{org}/teams` +`get` | `/orgs/{org}/teams/search` +`get, delete, patch` | `/teams/{id}` +`get` | `/teams/{id}/members` +`get, put, delete` | `/teams/{id}/members/{username}` +`get` | `/teams/{id}/repos` +`put, delete` | `/teams/{id}/repos/{org}/{repo}` +`get` | `/user/orgs` +`get` | `/users/{username}/orgs` +## Issues +Methods | Endpoint +------- | -------- + +**Holy shit there's a lot here. I'm just gonna not right now.** + +**Completed**: /user, /users/{username} \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..0b84fba --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,71 @@ +{ + "include": ["src/**/*", "tests/**/*"], + + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Basic Options */ + // "incremental": true, /* Enable incremental compilation */ + "target": "es2015", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ + "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ + // "lib": [], /* Specify library files to be included in the compilation. */ + // "allowJs": true, /* Allow javascript files to be compiled. */ + // "checkJs": true, /* Report errors in .js files. */ + // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ + // "declaration": true, /* Generates corresponding '.d.ts' file. */ + // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ + // "sourceMap": true, /* Generates corresponding '.map' file. */ + // "outFile": "./", /* Concatenate and emit output to single file. */ + "outDir": "./out/", /* Redirect output structure to the directory. */ + // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ + // "composite": true, /* Enable project compilation */ + // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ + // "removeComments": true, /* Do not emit comments to output. */ + // "noEmit": true, /* Do not emit outputs. */ + // "importHelpers": true, /* Import emit helpers from 'tslib'. */ + // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ + // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ + + /* Strict Type-Checking Options */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* Enable strict null checks. */ + // "strictFunctionTypes": true, /* Enable strict checking of function types. */ + // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ + // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ + // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ + "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ + + /* Additional Checks */ + // "noUnusedLocals": true, /* Report errors on unused locals. */ + // "noUnusedParameters": true, /* Report errors on unused parameters. */ + // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + + /* Module Resolution Options */ + // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ + // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ + // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ + // "typeRoots": [], /* List of folders to include type definitions from. */ + // "types": [], /* Type declaration files to be included in compilation. */ + // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + + /* Source Map Options */ + // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ + + /* Experimental Options */ + // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ + // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + + /* Advanced Options */ + "skipLibCheck": true, /* Skip type checking of declaration files. */ + "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ + } +}