init: monorepo with typescript bot framework

This commit is contained in:
Erica Marigold 2022-11-18 17:26:05 +05:30
parent 482b69758b
commit 17a611b7a0
No known key found for this signature in database
GPG key ID: 23CD97ABBBCC5ED2
40 changed files with 1174 additions and 779 deletions

View file

@ -1,73 +1,3 @@
# Turborepo starter # create-guilded-bot
<div align="center">A CLI to quickly generate guilded bot projects.</div>
This is an official pnpm starter turborepo. <p align="center">
## What's inside?
This turborepo uses [pnpm](https://pnpm.io) as a package manager. It includes the following packages/apps:
### Apps and Packages
- `docs`: a [Next.js](https://nextjs.org/) app
- `web`: another [Next.js](https://nextjs.org/) app
- `ui`: a stub React component library shared by both `web` and `docs` applications
- `eslint-config-custom`: `eslint` configurations (includes `eslint-config-next` and `eslint-config-prettier`)
- `tsconfig`: `tsconfig.json`s used throughout the monorepo
Each package/app is 100% [TypeScript](https://www.typescriptlang.org/).
### Utilities
This turborepo has some additional tools already setup for you:
- [TypeScript](https://www.typescriptlang.org/) for static type checking
- [ESLint](https://eslint.org/) for code linting
- [Prettier](https://prettier.io) for code formatting
### Build
To build all apps and packages, run the following command:
```
cd my-turborepo
pnpm run build
```
### Develop
To develop all apps and packages, run the following command:
```
cd my-turborepo
pnpm run dev
```
### Remote Caching
Turborepo can use a technique known as [Remote Caching](https://turbo.build/repo/docs/core-concepts/remote-caching) to share cache artifacts across machines, enabling you to share build caches with your team and CI/CD pipelines.
By default, Turborepo will cache locally. To enable Remote Caching you will need an account with Vercel. If you don't have an account you can [create one](https://vercel.com/signup), then enter the following commands:
```
cd my-turborepo
pnpm dlx turbo login
```
This will authenticate the Turborepo CLI with your [Vercel account](https://vercel.com/docs/concepts/personal-accounts/overview).
Next, you can link your Turborepo to your Remote Cache by running the following command from the root of your turborepo:
```
pnpm dlx turbo link
```
## Useful Links
Learn more about the power of Turborepo:
- [Pipelines](https://turbo.build/repo/docs/core-concepts/monorepos/running-tasks)
- [Caching](https://turbo.build/repo/docs/core-concepts/caching)
- [Remote Caching](https://turbo.build/repo/docs/core-concepts/remote-caching)
- [Filtering](https://turbo.build/repo/docs/core-concepts/monorepos/filtering)
- [Configuration Options](https://turbo.build/repo/docs/reference/configuration)
- [CLI Usage](https://turbo.build/repo/docs/reference/command-line-reference)

View file

11
apps/bot/package.json Normal file
View file

@ -0,0 +1,11 @@
{
"name": "create-guilded-app-tsconfig",
"version": "0.1.0",
"main": "dist/index.js",
"author": "DevComp <hi@devcomp.xyz>",
"license": "MIT",
"private": true,
"devDependencies": {
"tsconfig": "workspace:*"
}
}

5
apps/bot/tsconfig.json Normal file
View file

@ -0,0 +1,5 @@
{
"extends": "tsconfig/default.json",
"include": ["**/*.ts", "environment.d.ts"],
"exclude": ["node_modules", "**/*.spec.ts"]
}

2
apps/bot/typescript/.env Normal file
View file

@ -0,0 +1,2 @@
botToken=gapi_LwMUinFQKOw4VfHrvBfHFKVP2zIAGp1GxE8P/IwhQrqpcrIXbr3Keq1PbZxnQeABI1qq8RsN4pFcwZ/4RMft+Q==
botPrefix="$"

12
apps/bot/typescript/environment.d.ts vendored Normal file
View file

@ -0,0 +1,12 @@
declare global {
namespace NodeJS {
interface ProcessEnv {
botToken: string;
environment: "dev" | "prod" | "debug";
ownerId: string;
botPrefix: string
}
}
}
export {};

View file

@ -0,0 +1,29 @@
{
"name": "guilded.js-typescript",
"version": "0.1.0",
"main": "dist/index.js",
"author": "DevComp <hi@devcomp.xyz>",
"license": "MIT",
"private": true,
"scripts": {
"build": "tsc",
"dev": "ts-node-dev src/index.ts",
"start": "ts-node src/index.ts"
},
"dependencies": {
"dotenv": "^16.0.3",
"glob": "^7.2.0",
"guilded.js": "^0.13.23"
},
"devDependencies": {
"@types/glob": "^8.0.0",
"@types/node": "^18.11.9",
"ts-node": "^10.9.1",
"eslint-config-custom": "workspace:*",
"eslint": "7.32.0",
"tsconfig": "workspace:*",
"ts-node-dev": "^2.0.0",
"tslib": "^2.4.1",
"typescript": "4.8.4"
}
}

View file

@ -0,0 +1,48 @@
import { Embed } from "guilded.js";
import { client } from "..";
import { Command } from "../structures/Command";
export default new Command({
name: "help",
description: "Get a list of commands.",
run: async ({ interaction }) => {
const options = interaction.ctx.getOptions()
if (!options) {
let fetchedCmds = await client.getCommands()
let stringifiedCommands: string = ""
for (let cmd in fetchedCmds) {
stringifiedCommands += `${fetchedCmds[cmd].name} - ${fetchedCmds[cmd].description}\n`
}
const menu = new Embed({
title: "Available commands",
description: stringifiedCommands,
})
interaction.ctx.reply(menu)
} else if (options && options.length == 1) {
let fetchedCmds = await client.getCommands()
console.log(fetchedCmds)
let stringifiedCommands: string = ""
for (let cmd in fetchedCmds) {
console.log(fetchedCmds[cmd]) // this only includes `help.ts` for some reason
console.log(fetchedCmds[cmd].name, options[0])
if (fetchedCmds[cmd].name == options[0]) {
stringifiedCommands += `${fetchedCmds[cmd].name} - ${fetchedCmds[cmd].description}`
const menu = new Embed({
title: "Available commands",
description: stringifiedCommands,
})
interaction.ctx.reply(menu)
return;
}
}
interaction.ctx.reply("No such command exists.")
}
}
})

View file

@ -0,0 +1,11 @@
import { Embed } from "guilded.js";
import { client } from "..";
import { Command } from "../structures/Command";
export default new Command({
name: "hi",
description: "me when.",
run: async ({ interaction }) => {
interaction.ctx.reply('i say hi')
}
})

View file

@ -0,0 +1,6 @@
import { client } from ".."
import { Event } from "../structures/Event"
export default new Event("ready", () => {
console.log(`${client.user.name} is ready!`)
})

View file

@ -0,0 +1,11 @@
require("dotenv").config();
import { ExtendedClient } from "./structures/Client";
export const client = new ExtendedClient();
client.start();
import { Event } from "./structures/Event";
export default new Event("ready", () => {
console.log("Bot is online");
});

View file

@ -0,0 +1,127 @@
import { Client, ClientEvents } from 'guilded.js'
import { promisify } from 'util'
import glob from 'glob'
import { Event } from './Event'
import { CommandType, ResCtx } from '../typings/command'
const globPromise = promisify(glob)
export class ExtendedClient extends Client {
constructor() {
if (!process.env.botToken) return;
super({ token: process.env.botToken })
}
start() {
this.registerModules()
this.login()
}
// Slash commands would be so cool, guilded!
async importFile(filePath: string) {
return (await import(filePath))?.default;
}
async getCommands() {
const commandFiles = await globPromise(
`${__dirname}/../commands/*{.ts,.js}`
)
const commandsDir: any = new Object()
for (let commandPath of commandFiles) {
const command: CommandType = await this.importFile(commandPath)
const splitted = commandPath.split("/")
const fileName = splitted[splitted.length - 1]
commandsDir[fileName] = { name: command.name, description: command.description }
}
return commandsDir
}
registerModules() {
this.registerCommands()
this.registerEvents()
}
async registerEvents() {
const eventFiles = await globPromise(
`${__dirname}/../events/*{.ts,.js}`
)
eventFiles.forEach(async (filePath) => {
const event: Event<keyof ClientEvents> = await this.importFile(
filePath
);
this.on(event.event, event.run);
});
}
private async validateCommands() {
let commands = await globPromise(
`${__dirname}/../commands/*{.ts,.js}`
)
let findDuplicates = (arr: any[]) => arr.filter((v: any, i: number) => arr.indexOf(v) != i)
let cmds = new Array()
commands.forEach(async (commandPath) => {
let imported = await this.importFile(commandPath)
cmds.push(imported.name)
if (findDuplicates(cmds).length !== 0) {
throw new Error("Command names must be unique.")
}
})
}
async registerCommands() {
this.validateCommands().then(async () => {
let commandFiles = await globPromise(
`${__dirname}/../commands/*{.ts,.js}`
)
this.on("messageCreated", async (message) => {
if (message.content.startsWith(process.env.botPrefix)) {
for (let filepath of commandFiles) {
const command = await this.importFile(filepath)
const parsed = message.content.split(" ")
const args = parsed.filter((_, i) => { return i > 0 })
if (command.name === parsed[0].split(process.env.botPrefix)[1]) {
if (!message.serverId) throw new Error("Failed to fetch message serverId!")
const Context: ResCtx = {
meta:
{
user: await this.members.fetch(message.serverId, message.authorId),
raw: message,
},
ctx:
{
getOptions: () => {
if (args.length != 0) {
return args
} else {
return null
}
},
reply: (content) => { message.reply(content) }
}
}
command.run({ interaction: Context })
return;
}
}
message.reply("Requested command does not exist!")
}
})
})
}
}

View file

@ -0,0 +1,8 @@
import { CommandType, ResCtx } from "../typings/command";
export class Command {
constructor(commandOptions: CommandType) {
Object.assign(this, commandOptions);
}
}

View file

@ -0,0 +1,8 @@
import { ClientEvents } from "guilded.js";
export class Event<Key extends keyof ClientEvents> {
constructor(
public event: Key,
public run: (...args: any) => any
) {}
}

View file

@ -0,0 +1,23 @@
import { Embed, Member, Message, User } from "guilded.js";
import { ExtendedClient } from "../structures/Client";
export type ResCtx = {
meta:
{
user: Member,
raw: Message,
},
ctx:
{
getOptions: () => null|string[],
reply: (content: string|Embed) => void
}
};
export type CommandType = {
name: string,
description: string,
run: (context: { interaction: ResCtx }) => {}
}

View file

@ -0,0 +1,4 @@
import { ClientEvents } from 'guilded.js'
export type extendedEvents = ClientEvents & {
interactionCreate: (...args) => unknown
}

View file

@ -0,0 +1,3 @@
{
"extends": "eslint-config-custom"
}

28
apps/cli/package.json Normal file
View file

@ -0,0 +1,28 @@
{
"name": "create-guilded-app-cli",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "tsc",
"dev": "ts-node-dev src/index.ts",
"start": "ts-node src/index.ts"
},
"type": "module",
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/inquirer": "^9.0.3",
"@types/node": "^18.11.9",
"@types/prompt": "^1.1.4",
"ts-node-dev": "^2.0.0",
"tsconfig": "workspace:*",
"tslib": "^2.4.1",
"typescript": "^4.9.3"
},
"dependencies": {
"inquirer": "^9.1.4",
"kleur": "^4.1.5"
}
}

1
apps/cli/src/index.ts Normal file
View file

@ -0,0 +1 @@
// do this someday

0
apps/cli/tsconfig.json Normal file
View file

View file

@ -1,4 +0,0 @@
module.exports = {
root: true,
extends: ["custom"],
};

View file

@ -1,30 +0,0 @@
## Getting Started
First, run the development server:
```bash
yarn dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `pages/index.js`. The page auto-updates as you edit the file.
[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.js`.
The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn/foundations/about-nextjs) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_source=github.com&utm_medium=referral&utm_campaign=turborepo-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.

View file

@ -1,5 +0,0 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.

View file

@ -1,6 +0,0 @@
module.exports = {
reactStrictMode: true,
experimental: {
transpilePackages: ["ui"],
},
};

View file

@ -1,27 +0,0 @@
{
"name": "docs",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "next dev --port 3001",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "13.0.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"ui": "workspace:*"
},
"devDependencies": {
"@babel/core": "^7.0.0",
"eslint-config-custom": "workspace:*",
"eslint": "7.32.0",
"tsconfig": "workspace:*",
"@types/node": "^17.0.12",
"@types/react": "^18.0.22",
"@types/react-dom": "^18.0.7",
"typescript": "^4.5.3"
}
}

View file

@ -1,10 +0,0 @@
import { Button } from "ui";
export default function Docs() {
return (
<div>
<h1>Docs</h1>
<Button />
</div>
);
}

View file

@ -1,5 +0,0 @@
{
"extends": "tsconfig/nextjs.json",
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}

View file

@ -1,4 +0,0 @@
module.exports = {
root: true,
extends: ["custom"],
};

View file

@ -1,30 +0,0 @@
## Getting Started
First, run the development server:
```bash
yarn dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `pages/index.js`. The page auto-updates as you edit the file.
[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.js`.
The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn/foundations/about-nextjs) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_source=github.com&utm_medium=referral&utm_campaign=turborepo-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.

View file

@ -1,5 +0,0 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.

View file

@ -1,6 +0,0 @@
module.exports = {
reactStrictMode: true,
experimental: {
transpilePackages: ["ui"],
},
};

View file

@ -1,27 +0,0 @@
{
"name": "web",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "13.0.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"ui": "workspace:*"
},
"devDependencies": {
"@babel/core": "^7.0.0",
"eslint-config-custom": "workspace:*",
"eslint": "7.32.0",
"tsconfig": "workspace:*",
"@types/node": "^17.0.12",
"@types/react": "^18.0.22",
"@types/react-dom": "^18.0.7",
"typescript": "^4.5.3"
}
}

View file

@ -1,10 +0,0 @@
import { Button } from "ui";
export default function Web() {
return (
<div>
<h1>Web</h1>
<Button />
</div>
);
}

View file

@ -1,5 +0,0 @@
{
"extends": "tsconfig/nextjs.json",
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}

View file

@ -4,7 +4,8 @@
"private": true, "private": true,
"workspaces": [ "workspaces": [
"apps/*", "apps/*",
"packages/*" "apps/*/*",
"packages/*/*"
], ],
"scripts": { "scripts": {
"build": "turbo run build", "build": "turbo run build",

View file

@ -13,8 +13,7 @@
"noUnusedLocals": false, "noUnusedLocals": false,
"noUnusedParameters": false, "noUnusedParameters": false,
"preserveWatchOutput": true, "preserveWatchOutput": true,
"skipLibCheck": true, "skipLibCheck": true
"strict": true
}, },
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }

View file

@ -0,0 +1,20 @@
{
"extends": "./base.json",
"compilerOptions": {
"lib": ["ESNext"],
"module": "commonjs",
"moduleResolution": "node",
"target": "ESNext",
"outDir": "dist",
"sourceMap": false,
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"allowSyntheticDefaultImports": true,
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"resolveJsonModule": true,
"importHelpers": true,
"rootDirs": ["src", "lib"]
}
}

View file

@ -1,11 +0,0 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"display": "React Library",
"extends": "./base.json",
"compilerOptions": {
"jsx": "react-jsx",
"lib": ["ES2015"],
"module": "ESNext",
"target": "es6"
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,3 +1,4 @@
packages: packages:
- "apps/*" - "apps/*"
- "apps/*/*"
- "packages/*" - "packages/*"