New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

revolt-api

Package Overview
Dependencies
Maintainers
1
Versions
99
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

revolt-api - npm Package Compare versions

Comparing version 0.5.3-alpha.8-patch.0 to 0.5.3-patch.1

dist/baseURL.d.ts

183

dist/index.js

@@ -1,41 +0,152 @@

import { writeFile } from 'fs/promises';
import info from './openapi/info.js';
import definitions from './openapi/definitions.js';
import paths, { group, tags } from './openapi/paths.js';
import './routes/index.js';
async function generate() {
return {
['__comment']: "THIS FILE WAS AUTO-GENERATED USING https://github.com/revoltchat/api. DO NOT EDIT.",
openapi: "3.0.0",
info: await info(),
tags,
// Redoc tag groups
['x-tagGroups']: group(),
paths: await paths(),
definitions: await definitions(),
servers: [
{
"url": "https://api.revolt.chat",
"description": "Production instance of the Revolt API"
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.API = exports.getPathName = void 0;
// This file was auto-generated by @insertish/oapi!
const axios_1 = __importDefault(require("axios"));
const lodash_defaultsdeep_1 = __importDefault(require("lodash.defaultsdeep"));
__exportStar(require("./types"), exports);
const baseURL_1 = require("./baseURL");
const params_1 = require("./params");
/**
* Get the specific path name of any given path.
* @param anyPath Any path
* @returns Specific path
*/
function getPathName(anyPath) {
var _a;
const segments = anyPath.split('/');
const list = (_a = params_1.pathResolve[(segments.length - 1).toString()]) !== null && _a !== void 0 ? _a : [];
for (const entry of list) {
let i = 1;
let copy = [...segments];
for (i; i < segments.length; i++) {
if (Array.isArray(entry[i - 1])) {
copy[i] = entry[i - 1];
continue;
}
],
components: {
securitySchemes: {
'Session Token': {
type: "apiKey",
in: "header",
name: "x-session-token",
description: "Session is created by calling `/session/login`.\n"
},
'Bot Token': {
type: "apiKey",
in: "header",
name: "x-bot-token",
description: "Generate a bot token in-app by going to [\"My Bots\"](https://app.revolt.chat/settings/bots) in user settings.\n"
else if (entry[i - 1] !== segments[i])
break;
}
if (i === segments.length)
return copy.join('/');
}
}
exports.getPathName = getPathName;
/**
* API Client
*/
class API {
constructor({ baseURL, authentication } = {}) {
this.baseURL = baseURL !== null && baseURL !== void 0 ? baseURL : baseURL_1.defaultBaseURL;
this.authentication = authentication !== null && authentication !== void 0 ? authentication : {};
}
/**
* Generate authentication options.
*/
get auth() {
if (this.authentication.rauth) {
if (typeof this.authentication.rauth === 'string') {
return {
headers: {
'X-Session-Token': this.authentication.rauth
}
};
}
}
else if (this.authentication.revolt) {
switch (typeof this.authentication.revolt) {
case 'string': {
return {
headers: {
'X-Bot-Token': this.authentication.revolt
}
};
}
case 'object': {
return {
headers: {
'X-Session-Token': this.authentication.revolt.token
}
};
}
}
}
};
return {};
}
/**
* Generate config to pass through to API.
*/
get config() {
return Object.assign({ baseURL: this.baseURL }, this.auth);
}
/**
* Send any arbitrary request.
* @param method HTTP Method
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
req(method, path, params, config) {
let query, body;
let named = getPathName(path);
// If we are aware of this route, then match the parameters given.
if (named && typeof params === 'object') {
const route = params_1.queryParams[named];
const allowed_query = route[method];
// Map each parameter to the correct object.
for (const parameter of Object.keys(params)) {
if (allowed_query === null || allowed_query === void 0 ? void 0 : allowed_query.includes(parameter)) {
query = Object.assign(Object.assign({}, (query !== null && query !== void 0 ? query : {})), { [parameter]: params[parameter] });
}
else {
body = Object.assign(Object.assign({}, (body !== null && body !== void 0 ? body : {})), { [parameter]: params[parameter] });
}
}
}
return (0, axios_1.default)(path, (0, lodash_defaultsdeep_1.default)({
method,
params: query,
data: body
}, (0, lodash_defaultsdeep_1.default)(config, this.config)))
.then(res => res.data);
}
get(path, params, config) {
// @ts-ignore-next-line
return this.req('get', path, params, config);
}
patch(path, params, config) {
// @ts-ignore-next-line
return this.req('patch', path, params, config);
}
put(path, params, config) {
// @ts-ignore-next-line
return this.req('put', path, params, config);
}
delete(path, config) {
// @ts-ignore-next-line
return this.req('delete', path, undefined, config);
}
post(path, params, config) {
// @ts-ignore-next-line
return this.req('post', path, params, config);
}
}
generate()
.then(v => writeFile('OpenAPI.json', JSON.stringify(v, undefined, 2)));
exports.API = API;

43

package.json
{
"name": "revolt-api",
"version": "0.5.3-alpha.8-patch.0",
"description": "Revolt API typings",
"version": "0.5.3-patch.1",
"description": "Revolt API Library",
"main": "dist/index.js",
"type": "module",
"module": "esm/index.js",
"homepage": "https://developers.revolt.chat",

@@ -12,21 +12,24 @@ "repository": "https://gitlab.insrt.uk/revolt/api.git",

"scripts": {
"build:generator": "tsc",
"start:generator": "node .",
"watch:generator": "tsc-watch",
"redoc": "docker run --network host -e SPEC_URL=http://localhost:5500/OpenAPI.json redocly/redoc",
"preview": "sirv . --port 5500 --host",
"dev": "concurrently \"yarn redoc\" \"nodemon --exec \\\"yarn build:generator && yarn start:generator && yarn preview\\\"\"",
"open": "concurrently \"yarn redoc\" \"yarn preview\" \"open-cli http://localhost:80\""
"build": "REWRITE_ANYOF=1 oapilib && tsc && tsc -p tsconfig.esm.json",
"prepublish": "in-publish && yarn build || echo Skipping build."
},
"devDependencies": {
"@openapi-contrib/json-schema-to-openapi-schema": "^2.0.0",
"concurrently": "^6.2.0",
"nodemon": "^2.0.12",
"open-cli": "^7.0.0",
"openapi-types": "^9.1.0",
"sirv-cli": "^1.0.12",
"tsc-watch": "^4.4.0",
"typescript": "^4.3.5",
"typescript-json-schema": "^0.50.1"
}
"@types/lodash.defaultsdeep": "^4.6.6",
"in-publish": "^2.0.1",
"openapi-typescript": "^5.2.0",
"typescript": "^4.6.2"
},
"dependencies": {
"@insertish/oapi": "0.1.15",
"axios": "^0.26.1",
"lodash.defaultsdeep": "^4.6.1"
},
"files": [
"src",
"dist",
"esm",
"OpenAPI.json",
"LICENSE",
"README.md"
]
}

@@ -5,51 +5,36 @@ # Revolt API

This package contains typings for objects in the [Revolt API](https://developers.revolt.chat/api/) and code for generating the OpenAPI specification.
This package contains typings for objects in the [Revolt API](https://developers.revolt.chat/api/) and a fully typed API request builder.
For most cases, if not all, you should only be concerned with `revolt-api/types`.
### Example Usage
If you just need access to types:
```typescript
import type { User } from 'revolt-api/types/Users';
import type { User } from 'revolt-api';
```
### Commit Style
If you want to send requests:
If publishing a new version of the spec, the first line should always be the API version.
```typescript
import { API } from 'revolt-api';
```
0.5.0-alpha.0
Commit description.
Line 2.
```
// Initialise a new API client:
const client = new API();
If you are creating new changes for a PR, don't include any version!
// or with authentication:
const client = new API({ authentication: { revolt: 'bot-token' } });
For any subsequent lines, prepend the relevant text:
// Make requests with ease:
client.get('/users/@me')
// Fully typed responses!
.then(user => user.username);
Prefix | Description
--------|-------------
`Structure` | Added a new data structure to the API.
`Route` | Added a new route to the API.
`Change` | Changed an existing route or data structure.
`Fix` | Fixes to structures / routes.
`Deprecation` | Use when deprecating a structure or route.
`Library` | Changes to this repo unrelated to the API.
// No need to worry about the details:
let channel_id = "some channel id";
client.post(`/channels/${channel_id}/messages`, {
// Parameters given are fully typed as well!
content: "some content"
});
```
Add new prefixes to this list as necessary.
### Tip
For faster compile times when working on API routes, comment out the categories you don't care about.
```ts
/// src/routes/index.ts
export async function load() {
// await import('./core.js');
// await import('./users.js');
// await import('./channels.js');
await import('./servers.js');
}
await load();
```
For more details on how this works, see the [README of @insertish/oapi](https://github.com/insertish/oapi#example).

@@ -1,52 +0,270 @@

import { writeFile } from 'fs/promises';
import type { OpenAPIV3 } from "openapi-types";
import type * as TJS from "typescript-json-schema";
// This file was auto-generated by @insertish/oapi!
import Axios from 'axios';
import type { AxiosRequestConfig } from 'axios';
type Document = OpenAPIV3.Document & { definitions?: TJS.Definition };
import defaultsDeep from 'lodash.defaultsdeep';
import info from './openapi/info.js';
import definitions from './openapi/definitions.js';
import paths, { group, tags } from './openapi/paths.js';
export * from './types';
import type { APIRoutes } from './routes';
import './routes/index.js';
import { defaultBaseURL } from './baseURL';
import { pathResolve, queryParams } from './params';
async function generate(): Promise<Document> {
return {
['__comment' as any]: "THIS FILE WAS AUTO-GENERATED USING https://github.com/revoltchat/api. DO NOT EDIT.",
openapi: "3.0.0",
info: await info(),
tags,
// Redoc tag groups
['x-tagGroups' as any]: group(),
paths: await paths(),
definitions: await definitions(),
servers: [
{
"url": "https://api.revolt.chat",
"description": "Production instance of the Revolt API"
type Methods = APIRoutes['method'];
type PickRoutes<Method extends Methods> = APIRoutes & { method: Method };
type GetRoutes = PickRoutes<'get'>;
type PatchRoutes = PickRoutes<'patch'>;
type PutRoutes = PickRoutes<'put'>;
type DeleteRoutes = PickRoutes<'delete'>;
type PostRoutes = PickRoutes<'post'>;
type Count<Str extends string, SubStr extends string, Matches extends null[] = []> =
Str extends `${infer _}${SubStr}${infer After}` ? Count<After, SubStr, [...Matches, null]> : Matches['length'];
/**
* Get the specific path name of any given path.
* @param anyPath Any path
* @returns Specific path
*/
export function getPathName(anyPath: string) {
const segments = anyPath.split('/');
const list = (pathResolve as unknown as Record<string, (string | [string])[]>)[(segments.length - 1).toString()] ?? [];
for (const entry of list) {
let i = 1;
let copy = [...segments];
for (i;i<segments.length;i++) {
if (Array.isArray(entry[i - 1])) {
copy[i] = entry[i - 1];
continue;
}
],
components: {
securitySchemes: {
'Session Token': {
type: "apiKey",
in: "header",
name: "x-session-token",
description: "Session is created by calling `/session/login`.\n"
},
'Bot Token': {
type: "apiKey",
in: "header",
name: "x-bot-token",
description: "Generate a bot token in-app by going to [\"My Bots\"](https://app.revolt.chat/settings/bots) in user settings.\n"
else if (entry[i - 1] !== segments[i]) break;
}
if (i === segments.length) return copy.join('/');
}
}
/**
* Client configuration options
*/
export interface Options {
/**
* Base URL of the Revolt node
*/
baseURL: string;
/**
* Authentication used for requests
*/
authentication: {
rauth?: string | undefined;
revolt?: { token: string } | string | undefined;
};
}
/**
* API Client
*/
export class API {
private baseURL: Options['baseURL'];
private authentication: Options['authentication'];
constructor({ baseURL, authentication }: Partial<Options> = { }) {
this.baseURL = baseURL ?? defaultBaseURL;
this.authentication = authentication ?? { };
}
/**
* Generate authentication options.
*/
get auth(): AxiosRequestConfig {
if (this.authentication.rauth) {
if (typeof this.authentication.rauth === 'string') {
return {
headers: {
'X-Session-Token': this.authentication.rauth
}
}
}
} else if (this.authentication.revolt) {
switch (typeof this.authentication.revolt) {
case 'string': {
return {
headers: {
'X-Bot-Token': this.authentication.revolt
}
}
}
case 'object': {
return {
headers: {
'X-Session-Token': this.authentication.revolt.token
}
}
}
}
}
return { };
}
/**
* Generate config to pass through to API.
*/
get config(): AxiosRequestConfig {
return {
baseURL: this.baseURL,
...this.auth,
};
}
/**
* Send any arbitrary request.
* @param method HTTP Method
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
req<Method extends Methods, Routes extends PickRoutes<Method>, Path extends Routes['path'], Route extends Routes & { path: Path, parts: Count<Path, '/'> }>(method: Method, path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']> {
let query, body;
let named = getPathName(path);
// If we are aware of this route, then match the parameters given.
if (named && typeof params === 'object') {
const route = queryParams[named as keyof typeof queryParams];
const allowed_query = (route as unknown as Record<Method, string[]>)[method];
// Map each parameter to the correct object.
for (const parameter of Object.keys(params)) {
if (allowed_query?.includes(parameter)) {
query = {
...(query ?? {}),
[parameter]: (params as Record<any, any>)[parameter]
};
} else {
body = {
...(body ?? {}),
[parameter]: (params as Record<any, any>)[parameter]
};
}
}
}
return Axios(path, defaultsDeep({
method,
params: query,
data: body
}, defaultsDeep(
config,
this.config
)))
.then(res => res.data);
}
/**
* Send HTTP GET request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
get<Path extends GetRoutes['path'], Route extends GetRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP GET request.
* @param path Path
* @returns Typed Response Data
*/
get<Path extends (GetRoutes & { params: undefined })['path'], Route extends GetRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path): Promise<Route['response']>;
get(path: any, params?: any, config?: AxiosRequestConfig): Promise<any> {
// @ts-ignore-next-line
return this.req('get', path, params, config);
}
/**
* Send HTTP PATCH request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
patch<Path extends PatchRoutes['path'], Route extends PatchRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP PATCH request.
* @param path Path
* @returns Typed Response Data
*/
patch<Path extends (PatchRoutes & { params: undefined })['path'], Route extends PatchRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path): Promise<Route['response']>;
patch(path: any, params?: any, config?: AxiosRequestConfig): Promise<any> {
// @ts-ignore-next-line
return this.req('patch', path, params, config);
}
/**
* Send HTTP PUT request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
put<Path extends PutRoutes['path'], Route extends PutRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP PUT request.
* @param path Path
* @returns Typed Response Data
*/
put<Path extends (PutRoutes & { params: undefined })['path'], Route extends PutRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path): Promise<Route['response']>;
put(path: any, params?: any, config?: AxiosRequestConfig): Promise<any> {
// @ts-ignore-next-line
return this.req('put', path, params, config);
}
/**
* Send HTTP DELETE request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
delete<Path extends DeleteRoutes['path'], Route extends DeleteRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path, config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP DELETE request.
* @param path Path
* @returns Typed Response Data
*/
delete<Path extends (DeleteRoutes & { params: undefined })['path'], Route extends DeleteRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path): Promise<Route['response']>;
delete(path: any, config?: AxiosRequestConfig): Promise<any> {
// @ts-ignore-next-line
return this.req('delete', path, undefined, config);
}
/**
* Send HTTP POST request.
* @param path Path
* @param params Body or Query Parameters
* @param config Axios configuration
* @returns Typed Response Data
*/
post<Path extends PostRoutes['path'], Route extends PostRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path, params: Route['params'], config?: AxiosRequestConfig): Promise<Route['response']>;
/**
* Send HTTP POST request.
* @param path Path
* @returns Typed Response Data
*/
post<Path extends (PostRoutes & { params: undefined })['path'], Route extends PostRoutes & { path: Path, parts: Count<Path, '/'> }>(path: Path): Promise<Route['response']>;
post(path: any, params?: any, config?: AxiosRequestConfig): Promise<any> {
// @ts-ignore-next-line
return this.req('post', path, params, config);
}
}
generate()
.then(v =>
writeFile('OpenAPI.json', JSON.stringify(v, undefined, 2))
);

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc