create-nolly-template 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTRIBUTING.md +142 -0
- package/LICENSE +21 -0
- package/README.md +32 -0
- package/dist/builder.js +83 -0
- package/dist/index.js +123 -0
- package/dist/paths.js +5 -0
- package/dist/registry/index.js +4 -0
- package/dist/registry/types.js +1 -0
- package/dist/registry/web/backend/fastify/base.js +17 -0
- package/dist/registry/web/backend/fastify/features/mongodb.js +10 -0
- package/dist/registry/web/backend/fastify/features/swagger.js +26 -0
- package/dist/registry/web/backend/fastify/features/websocket.js +31 -0
- package/dist/registry/web/backend/index.js +7 -0
- package/dist/registry/web/index.js +7 -0
- package/package.json +54 -0
- package/templates/web/backend/fastify/base/package.json +26 -0
- package/templates/web/backend/fastify/base/pnpm-workspace.yaml +2 -0
- package/templates/web/backend/fastify/base/src/app.ts +53 -0
- package/templates/web/backend/fastify/base/src/controllers/user.controller.ts +12 -0
- package/templates/web/backend/fastify/base/src/index.ts +25 -0
- package/templates/web/backend/fastify/base/src/plugins/health.plugin.ts +6 -0
- package/templates/web/backend/fastify/base/src/routes/user.routes.ts +6 -0
- package/templates/web/backend/fastify/base/src/utils/env.ts +17 -0
- package/templates/web/backend/fastify/base/src/utils/response.ts +5 -0
- package/templates/web/backend/fastify/base/tsconfig.json +20 -0
- package/templates/web/backend/fastify/mongodb/.env +2 -0
- package/templates/web/backend/fastify/mongodb/src/plugins/mongo.plugin.ts +53 -0
- package/templates/web/backend/fastify/websocket/src/routes/chat.ws.ts +23 -0
- package/templates/web/backend/fastify/websocket/src/utils/websocket.ts +177 -0
package/CONTRIBUTING.md
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# Contributing to create-nolly-template
|
|
2
|
+
|
|
3
|
+
Thank you for your interest in contributing to `create-nolly-template`! This project is a CLI tool that provides opinionated templates for various tech stacks, making it easier to bootstrap new projects. We welcome contributions from everyone, whether it's bug fixes, new features, documentation improvements, or adding new templates.
|
|
4
|
+
|
|
5
|
+
## Table of Contents
|
|
6
|
+
|
|
7
|
+
- [Contributing to create-nolly-template](#contributing-to-create-nolly-template)
|
|
8
|
+
- [Table of Contents](#table-of-contents)
|
|
9
|
+
- [Getting Started](#getting-started)
|
|
10
|
+
- [Development Setup](#development-setup)
|
|
11
|
+
- [Project Structure](#project-structure)
|
|
12
|
+
- [Adding New Templates](#adding-new-templates)
|
|
13
|
+
- [Coding Guidelines](#coding-guidelines)
|
|
14
|
+
- [Testing](#testing)
|
|
15
|
+
- [Submitting Changes](#submitting-changes)
|
|
16
|
+
- [Reporting Issues](#reporting-issues)
|
|
17
|
+
- [Code of Conduct](#code-of-conduct)
|
|
18
|
+
- [License](#license)
|
|
19
|
+
|
|
20
|
+
## Getting Started
|
|
21
|
+
|
|
22
|
+
Before you start contributing, please familiarize yourself with the project by reading the [README.md](README.md). It provides an overview of what the tool does, how to install it, and its usage.
|
|
23
|
+
|
|
24
|
+
## Development Setup
|
|
25
|
+
|
|
26
|
+
To set up the development environment:
|
|
27
|
+
|
|
28
|
+
1. **Clone the repository:**
|
|
29
|
+
```bash
|
|
30
|
+
git clone https://github.com/thenolle/create-nolly-template.git
|
|
31
|
+
cd create-nolly-template
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
2. **Install dependencies:**
|
|
35
|
+
This project uses [pnpm](https://pnpm.io/) for package management. If you don't have pnpm installed, install it first:
|
|
36
|
+
```bash
|
|
37
|
+
npm install -g pnpm
|
|
38
|
+
```
|
|
39
|
+
Then install the dependencies:
|
|
40
|
+
```bash
|
|
41
|
+
pnpm install
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
3. **Run in development mode:**
|
|
45
|
+
Use the dev script to run the CLI tool directly from source:
|
|
46
|
+
```bash
|
|
47
|
+
pnpm dev
|
|
48
|
+
```
|
|
49
|
+
This uses `tsx` to run TypeScript files without building.
|
|
50
|
+
|
|
51
|
+
4. **Build the project:**
|
|
52
|
+
To build the distributable version:
|
|
53
|
+
```bash
|
|
54
|
+
pnpm build
|
|
55
|
+
```
|
|
56
|
+
This compiles TypeScript to JavaScript in the `dist/` folder.
|
|
57
|
+
|
|
58
|
+
5. **Test the built version:**
|
|
59
|
+
After building, you can test the CLI:
|
|
60
|
+
```bash
|
|
61
|
+
pnpm start
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Ensure you have Node.js version 20 or higher installed, as specified in the `engines` field of `package.json`.
|
|
65
|
+
|
|
66
|
+
## Project Structure
|
|
67
|
+
|
|
68
|
+
- `src/`: Source code for the CLI tool
|
|
69
|
+
- `index.ts`: Main entry point
|
|
70
|
+
- `builder.ts`: Logic for building projects from templates
|
|
71
|
+
- `paths.ts`: Path utilities
|
|
72
|
+
- `registry/`: Template registry and types
|
|
73
|
+
- `templates/`: Template directories
|
|
74
|
+
- `web/backend/fastify/`: Fastify-based backend templates
|
|
75
|
+
- `dist/`: Built JavaScript files (generated)
|
|
76
|
+
- `package.json`: Project configuration
|
|
77
|
+
- `tsconfig.json`: TypeScript configuration
|
|
78
|
+
|
|
79
|
+
## Adding New Templates
|
|
80
|
+
|
|
81
|
+
To add a new template:
|
|
82
|
+
|
|
83
|
+
1. Create a new directory under `templates/` following the structure (e.g., `templates/web/frontend/react/`).
|
|
84
|
+
2. Add the necessary files for the template (e.g., `package.json`, source files).
|
|
85
|
+
3. Update the registry in `src/registry/` to include the new template.
|
|
86
|
+
4. Test the template by running the CLI and selecting it.
|
|
87
|
+
|
|
88
|
+
Ensure templates are opinionated and follow best practices for the respective tech stack.
|
|
89
|
+
|
|
90
|
+
## Coding Guidelines
|
|
91
|
+
|
|
92
|
+
- **TypeScript:** All code is written in TypeScript. Use strict type checking.
|
|
93
|
+
- **Style:** Follow consistent naming conventions and formatting. Use Prettier if available (though not currently configured).
|
|
94
|
+
- **Commits:** Write clear, concise commit messages. Use conventional commits if possible (e.g., `feat: add new template`).
|
|
95
|
+
- **Imports:** Use ES modules (`import/export`) as the project is configured with `"type": "module"`.
|
|
96
|
+
|
|
97
|
+
## Testing
|
|
98
|
+
|
|
99
|
+
Currently, there are no automated tests set up. Contributions that add tests (e.g., using Jest or Vitest) are highly encouraged. For now, manually test your changes by:
|
|
100
|
+
|
|
101
|
+
- Running the CLI in dev mode
|
|
102
|
+
- Building and testing the built version
|
|
103
|
+
- Ensuring templates generate correctly
|
|
104
|
+
|
|
105
|
+
## Submitting Changes
|
|
106
|
+
|
|
107
|
+
1. **Fork the repository** on GitHub.
|
|
108
|
+
2. **Create a feature branch** from `main`:
|
|
109
|
+
```bash
|
|
110
|
+
git checkout -b feature/your-feature-name
|
|
111
|
+
```
|
|
112
|
+
3. **Make your changes** and commit them:
|
|
113
|
+
```bash
|
|
114
|
+
git commit -m "feat: description of your changes"
|
|
115
|
+
```
|
|
116
|
+
4. **Push to your fork:**
|
|
117
|
+
```bash
|
|
118
|
+
git push origin feature/your-feature-name
|
|
119
|
+
```
|
|
120
|
+
5. **Open a Pull Request** on GitHub. Provide a clear description of what your changes do and why they're needed.
|
|
121
|
+
|
|
122
|
+
## Reporting Issues
|
|
123
|
+
|
|
124
|
+
If you find a bug or have a feature request:
|
|
125
|
+
|
|
126
|
+
1. Check the [existing issues](https://github.com/thenolle/create-nolly-template/issues) to see if it's already reported.
|
|
127
|
+
2. If not, open a new issue with:
|
|
128
|
+
- A clear title
|
|
129
|
+
- Detailed description
|
|
130
|
+
- Steps to reproduce (for bugs)
|
|
131
|
+
- Expected vs. actual behavior
|
|
132
|
+
- Your environment (Node.js version, OS, etc.)
|
|
133
|
+
|
|
134
|
+
## Code of Conduct
|
|
135
|
+
|
|
136
|
+
This project follows a code of conduct to ensure a welcoming environment for all contributors. Be respectful, inclusive, and constructive in all interactions.
|
|
137
|
+
|
|
138
|
+
## License
|
|
139
|
+
|
|
140
|
+
By contributing to this project, you agree that your contributions will be licensed under the same MIT License as the project. See [LICENSE](LICENSE) for details.
|
|
141
|
+
|
|
142
|
+
Thank you for contributing! 🚀
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nolly
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# 🚀 create-nolly-template
|
|
2
|
+
|
|
3
|
+
All of my opiniated templates in one place. This is a CLI tool to create a new project based on one of my templates.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
```bash
|
|
7
|
+
npm i -g create-nolly-template
|
|
8
|
+
# or pnpm i -g create-nolly-template
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
```bash
|
|
13
|
+
create-nolly-template
|
|
14
|
+
# or npx create-nolly-template
|
|
15
|
+
# or pnpx create-nolly-template
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Templates
|
|
19
|
+
You can see the full list of available templates by running `create-nolly-template --list` or `create-nolly-template -l`.
|
|
20
|
+
|
|
21
|
+
## Commands
|
|
22
|
+
- `create-nolly-template` - Create a new project based on one of the templates.
|
|
23
|
+
- `create-nolly-template --list` or `create-nolly-template -l` - List all available templates.
|
|
24
|
+
- `create-nolly-template --help` or `create-nolly-template -h` - Show help message.
|
|
25
|
+
- `create-nolly-template --about` or `create-nolly-template -a` - Show information about the project.
|
|
26
|
+
|
|
27
|
+
## Contributing
|
|
28
|
+
If you want to contribute to this project, feel free to open a pull request or an issue. I would love to see your contributions!
|
|
29
|
+
See the [CONTRIBUTING](CONTRIBUTING.md) guide for more details.
|
|
30
|
+
|
|
31
|
+
## License
|
|
32
|
+
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details.
|
package/dist/builder.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import fs from 'fs-extra';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { TEMPLATES_ROOT } from './paths.js';
|
|
4
|
+
function mergeIntoPackageJson(pkg, dependencies, devDependencies) {
|
|
5
|
+
if (dependencies)
|
|
6
|
+
pkg.dependencies = { ...pkg.dependencies, ...dependencies };
|
|
7
|
+
if (devDependencies)
|
|
8
|
+
pkg.devDependencies = { ...pkg.devDependencies, ...devDependencies };
|
|
9
|
+
}
|
|
10
|
+
function applyReplacements(content, answers) {
|
|
11
|
+
let result = content;
|
|
12
|
+
for (const [key, value] of Object.entries(answers))
|
|
13
|
+
result = result.replace(new RegExp(`{{${key}}}`, 'g'), value);
|
|
14
|
+
return result;
|
|
15
|
+
}
|
|
16
|
+
function toRegExp(pattern) {
|
|
17
|
+
return typeof pattern === 'string' ? new RegExp(pattern, 'g') : pattern;
|
|
18
|
+
}
|
|
19
|
+
function applyPatchOperations(content, operations) {
|
|
20
|
+
let result = content;
|
|
21
|
+
for (const op of operations) {
|
|
22
|
+
const regex = 'pattern' in op ? toRegExp(op.pattern) : undefined;
|
|
23
|
+
if (op.type === 'replace' && regex) {
|
|
24
|
+
result = result.replace(regex, op.replacement);
|
|
25
|
+
}
|
|
26
|
+
else if (op.type === 'remove' && regex) {
|
|
27
|
+
result = result.replace(regex, '');
|
|
28
|
+
}
|
|
29
|
+
else if (op.type === 'insertBefore' && regex) {
|
|
30
|
+
result = result.replace(regex, match => `${op.insert}\n${match}`);
|
|
31
|
+
}
|
|
32
|
+
else if (op.type === 'insertAfter' && regex) {
|
|
33
|
+
result = result.replace(regex, match => `${match}\n${op.insert}`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return result;
|
|
37
|
+
}
|
|
38
|
+
function applyPatches(fileMap, patches) {
|
|
39
|
+
for (const patch of patches) {
|
|
40
|
+
const current = fileMap.get(patch.targetPath);
|
|
41
|
+
if (!current)
|
|
42
|
+
continue;
|
|
43
|
+
const next = applyPatchOperations(current, patch.operations);
|
|
44
|
+
fileMap.set(patch.targetPath, next);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
async function loadDirectoryIntoMap(root, baseDir, fileMap) {
|
|
48
|
+
const entries = await fs.readdir(root, { withFileTypes: true });
|
|
49
|
+
for (const entry of entries) {
|
|
50
|
+
const absolute = path.join(root, entry.name);
|
|
51
|
+
const relative = path.relative(baseDir, absolute).replace(/\\/g, '/');
|
|
52
|
+
if (entry.isDirectory()) {
|
|
53
|
+
await loadDirectoryIntoMap(absolute, baseDir, fileMap);
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
const content = await fs.readFile(absolute, 'utf-8');
|
|
57
|
+
fileMap.set(relative, content);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
export async function buildProject(template, selectedFeatures, answers, outputDir) {
|
|
62
|
+
const fileMap = new Map();
|
|
63
|
+
const baseRoot = path.join(TEMPLATES_ROOT, template.templateRoot);
|
|
64
|
+
await loadDirectoryIntoMap(baseRoot, baseRoot, fileMap);
|
|
65
|
+
const pkgRaw = fileMap.get('package.json');
|
|
66
|
+
const pkg = pkgRaw ? JSON.parse(pkgRaw) : {};
|
|
67
|
+
mergeIntoPackageJson(pkg, template.dependencies, template.devDependencies);
|
|
68
|
+
for (const feature of selectedFeatures) {
|
|
69
|
+
if (feature.templateRoot) {
|
|
70
|
+
const featureRoot = path.join(TEMPLATES_ROOT, feature.templateRoot);
|
|
71
|
+
await loadDirectoryIntoMap(featureRoot, featureRoot, fileMap);
|
|
72
|
+
}
|
|
73
|
+
mergeIntoPackageJson(pkg, feature.dependencies, feature.devDependencies);
|
|
74
|
+
}
|
|
75
|
+
const allPatches = selectedFeatures.flatMap(f => f.patches ?? []);
|
|
76
|
+
applyPatches(fileMap, allPatches);
|
|
77
|
+
fileMap.set('package.json', JSON.stringify(pkg, null, 2));
|
|
78
|
+
await fs.ensureDir(outputDir);
|
|
79
|
+
for (const [filePath, content] of fileMap.entries()) {
|
|
80
|
+
const fullPath = path.join(outputDir, filePath);
|
|
81
|
+
await fs.outputFile(fullPath, applyReplacements(content, answers));
|
|
82
|
+
}
|
|
83
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import prompts from 'prompts';
|
|
3
|
+
import { registry } from './registry/index.js';
|
|
4
|
+
import { buildProject } from './builder.js';
|
|
5
|
+
async function printHelp() {
|
|
6
|
+
console.log(`
|
|
7
|
+
🚀 create-nolly-template v1.0.0
|
|
8
|
+
|
|
9
|
+
Usage:
|
|
10
|
+
create-nolly-template Interactive wizard
|
|
11
|
+
create-nolly-template --help This help
|
|
12
|
+
create-nolly-template --about About & credits
|
|
13
|
+
create-nolly-template --list List all templates
|
|
14
|
+
|
|
15
|
+
Examples:
|
|
16
|
+
pnpx create-nolly-template
|
|
17
|
+
create-nolly-template -l
|
|
18
|
+
`);
|
|
19
|
+
process.exit(0);
|
|
20
|
+
}
|
|
21
|
+
async function printAbout() {
|
|
22
|
+
console.log(`
|
|
23
|
+
🚀 create-nolly-template
|
|
24
|
+
|
|
25
|
+
Nolly's templates. Zero-config, TypeScript-first.
|
|
26
|
+
|
|
27
|
+
Templates: Fastify, WebSocket, Swagger, MongoDB, Prisma, and even more !
|
|
28
|
+
Built with: TypeScript, ESM, fs-extra, prompts, and a lot of ❤️
|
|
29
|
+
|
|
30
|
+
Made by Nolly, a passionate full-stack developer and open-source enthusiast.
|
|
31
|
+
GitHub: thenolle/create-nolly-template
|
|
32
|
+
License: MIT
|
|
33
|
+
`);
|
|
34
|
+
process.exit(0);
|
|
35
|
+
}
|
|
36
|
+
async function printList() {
|
|
37
|
+
console.log('\n📋 Available Templates & Features\n');
|
|
38
|
+
for (const category of registry) {
|
|
39
|
+
console.log(`┌─ ${category.name} (${category.key})`);
|
|
40
|
+
console.log('│');
|
|
41
|
+
for (const sub of category.subCategories) {
|
|
42
|
+
console.log(`│ ├─ ${sub.name} (${sub.key})`);
|
|
43
|
+
console.log('│ │');
|
|
44
|
+
for (const template of sub.templates) {
|
|
45
|
+
console.log(`│ │ ├─ ${template.name} (${template.key})`);
|
|
46
|
+
if (template.features?.length) {
|
|
47
|
+
console.log(`│ │ │ Features:`);
|
|
48
|
+
template.features.forEach(feat => console.log(`│ │ │ • ${feat.name} - ${feat.description}`));
|
|
49
|
+
}
|
|
50
|
+
console.log('│ │');
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
console.log('│');
|
|
54
|
+
}
|
|
55
|
+
console.log('Run without args for interactive mode.\n');
|
|
56
|
+
process.exit(0);
|
|
57
|
+
}
|
|
58
|
+
async function main() {
|
|
59
|
+
const args = process.argv.slice(2);
|
|
60
|
+
if (args.includes('--help') || args.includes('-h'))
|
|
61
|
+
return printHelp();
|
|
62
|
+
if (args.includes('--about') || args.includes('-a'))
|
|
63
|
+
return printAbout();
|
|
64
|
+
if (args.includes('--list') || args.includes('-l'))
|
|
65
|
+
return printList();
|
|
66
|
+
console.log('\n🚀 Welcome to create-nolly-template!\n');
|
|
67
|
+
const { category } = await prompts({
|
|
68
|
+
type: 'select',
|
|
69
|
+
name: 'category',
|
|
70
|
+
message: 'Main category',
|
|
71
|
+
choices: registry.map(category => ({ title: category.name, value: category }))
|
|
72
|
+
});
|
|
73
|
+
const { subCategory } = await prompts({
|
|
74
|
+
type: 'select',
|
|
75
|
+
name: 'subCategory',
|
|
76
|
+
message: 'Sub category',
|
|
77
|
+
choices: category.subCategories.map(subCategory => ({ title: subCategory.name, value: subCategory }))
|
|
78
|
+
});
|
|
79
|
+
if (!subCategory)
|
|
80
|
+
process.exit(0);
|
|
81
|
+
const { template } = await prompts({
|
|
82
|
+
type: 'select',
|
|
83
|
+
name: 'template',
|
|
84
|
+
message: 'Base template',
|
|
85
|
+
choices: subCategory.templates.map(template => ({ title: template.name, value: template }))
|
|
86
|
+
});
|
|
87
|
+
if (!template)
|
|
88
|
+
process.exit(0);
|
|
89
|
+
let selectedFeatures = [];
|
|
90
|
+
if (template.features && template.features.length > 0) {
|
|
91
|
+
const { features } = await prompts({
|
|
92
|
+
type: 'multiselect',
|
|
93
|
+
name: 'features',
|
|
94
|
+
message: 'Optional features (space to toggle)',
|
|
95
|
+
choices: template.features.map((feature) => ({
|
|
96
|
+
title: feature.name,
|
|
97
|
+
value: feature,
|
|
98
|
+
description: feature.description
|
|
99
|
+
})),
|
|
100
|
+
hint: '- Space to select. Return to submit'
|
|
101
|
+
});
|
|
102
|
+
selectedFeatures = features ?? [];
|
|
103
|
+
}
|
|
104
|
+
const answers = await prompts(template.prompts);
|
|
105
|
+
const { outputDir } = await prompts({
|
|
106
|
+
type: 'text',
|
|
107
|
+
name: 'outputDir',
|
|
108
|
+
message: 'Output directory',
|
|
109
|
+
initial: `./${answers.name || template.key}`
|
|
110
|
+
});
|
|
111
|
+
if (!outputDir)
|
|
112
|
+
process.exit(0);
|
|
113
|
+
await buildProject(template, selectedFeatures, answers, outputDir);
|
|
114
|
+
console.log('\n✅ Project created at', outputDir);
|
|
115
|
+
console.log(' Base:', template.name);
|
|
116
|
+
if (selectedFeatures.length > 0)
|
|
117
|
+
console.log(' Features:', selectedFeatures.map((feature) => feature.name).join(', '));
|
|
118
|
+
console.log('\n cd', outputDir, '&& pnpm install\n');
|
|
119
|
+
}
|
|
120
|
+
main().catch(error => {
|
|
121
|
+
console.error('Error:', error);
|
|
122
|
+
process.exit(1);
|
|
123
|
+
});
|
package/dist/paths.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { swaggerFeature } from './features/swagger.js';
|
|
2
|
+
import { websocketFeature } from './features/websocket.js';
|
|
3
|
+
import { mongodbFeature } from './features/mongodb.js';
|
|
4
|
+
export const fastifyBase = {
|
|
5
|
+
key: 'fastify',
|
|
6
|
+
name: 'Fastify TypeScript',
|
|
7
|
+
description: 'Fastify with TypeScript, auto-registration, health check',
|
|
8
|
+
prompts: [
|
|
9
|
+
{ type: 'text', name: 'name', message: 'Project name', initial: 'my-fastify-app' }
|
|
10
|
+
],
|
|
11
|
+
templateRoot: 'web/backend/fastify/base',
|
|
12
|
+
features: [
|
|
13
|
+
swaggerFeature,
|
|
14
|
+
websocketFeature,
|
|
15
|
+
mongodbFeature
|
|
16
|
+
]
|
|
17
|
+
};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export const swaggerFeature = {
|
|
2
|
+
key: 'swagger',
|
|
3
|
+
name: 'Swagger / OpenAPI docs',
|
|
4
|
+
description: 'Adds automatic API documentation with Swagger / OpenAPI',
|
|
5
|
+
dependencies: {
|
|
6
|
+
'@fastify/swagger': '^9.7.0',
|
|
7
|
+
'@fastify/swagger-ui': '^5.2.5'
|
|
8
|
+
},
|
|
9
|
+
patches: [
|
|
10
|
+
{
|
|
11
|
+
targetPath: 'src/app.ts',
|
|
12
|
+
operations: [
|
|
13
|
+
{
|
|
14
|
+
type: 'insertBefore',
|
|
15
|
+
pattern: "import path from 'path'",
|
|
16
|
+
insert: "import swagger from '@fastify/swagger'\nimport swaggerUi from '@fastify/swagger-ui'"
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
type: 'insertAfter',
|
|
20
|
+
pattern: "app\\.register\\(helmet\\)",
|
|
21
|
+
insert: "\tapp.register(swagger, { openapi: { info: { title: '{{name}} API', version: '1.0.0' } } })\n\tawait app.register(swaggerUi, { routePrefix: '/docs' })"
|
|
22
|
+
}
|
|
23
|
+
]
|
|
24
|
+
}
|
|
25
|
+
]
|
|
26
|
+
};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export const websocketFeature = {
|
|
2
|
+
key: 'websocket',
|
|
3
|
+
name: 'WebSocket support',
|
|
4
|
+
description: 'Adds WebSocket support',
|
|
5
|
+
templateRoot: 'web/backend/fastify/websocket',
|
|
6
|
+
dependencies: {
|
|
7
|
+
'@fastify/websocket': '^11.2.0',
|
|
8
|
+
},
|
|
9
|
+
patches: [
|
|
10
|
+
{
|
|
11
|
+
targetPath: 'src/app.ts',
|
|
12
|
+
operations: [
|
|
13
|
+
{
|
|
14
|
+
type: 'insertBefore',
|
|
15
|
+
pattern: "import path from 'path'",
|
|
16
|
+
insert: "import websocket from '@fastify/websocket'"
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
type: 'insertAfter',
|
|
20
|
+
pattern: `app\\.register\\(helmet\\)`,
|
|
21
|
+
insert: ` app.register(websocket)`
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
type: 'insertAfter',
|
|
25
|
+
pattern: `await autoRegister\\(app, 'routes/\\*\\*/\\.routes\\.{ts,js}\\)`,
|
|
26
|
+
insert: ` await autoRegister(app, 'routes/**/*.ws.{ts,js}', '/ws')`
|
|
27
|
+
}
|
|
28
|
+
]
|
|
29
|
+
}
|
|
30
|
+
]
|
|
31
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "create-nolly-template",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "All of my opiniated templates in one place. This is a CLI tool to create a new project based on one of my templates.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"template",
|
|
7
|
+
"fastify",
|
|
8
|
+
"react",
|
|
9
|
+
"next.js",
|
|
10
|
+
"fullstack",
|
|
11
|
+
"vite",
|
|
12
|
+
"swagger",
|
|
13
|
+
"prisma",
|
|
14
|
+
"typescript",
|
|
15
|
+
"cli",
|
|
16
|
+
"boilerplate"
|
|
17
|
+
],
|
|
18
|
+
"author": "Nolly",
|
|
19
|
+
"license": "MIT",
|
|
20
|
+
"bin": {
|
|
21
|
+
"create-nolly-template": "dist/index.js"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"templates",
|
|
26
|
+
"package.json",
|
|
27
|
+
"README.md",
|
|
28
|
+
"LICENSE",
|
|
29
|
+
"CONTRIBUTING.md"
|
|
30
|
+
],
|
|
31
|
+
"engines": {
|
|
32
|
+
"node": ">=20"
|
|
33
|
+
},
|
|
34
|
+
"publishConfig": {
|
|
35
|
+
"registry": "https://registry.npmjs.org/"
|
|
36
|
+
},
|
|
37
|
+
"type": "module",
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"fs-extra": "^11.3.4",
|
|
40
|
+
"prompts": "^2.4.2"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@types/fs-extra": "^11.0.4",
|
|
44
|
+
"@types/node": "^25.5.0",
|
|
45
|
+
"@types/prompts": "^2.4.9",
|
|
46
|
+
"tsx": "^4.21.0",
|
|
47
|
+
"typescript": "^5.9.3"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {
|
|
50
|
+
"build": "rm -rf dist && tsc --build tsconfig.cli.json",
|
|
51
|
+
"start": "node dist/index.js",
|
|
52
|
+
"dev": "tsx src/index.ts"
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "{{name}}",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"private": true,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"dev": "tsx src/index.ts",
|
|
8
|
+
"build": "tsc",
|
|
9
|
+
"start": "node dist/index.js"
|
|
10
|
+
},
|
|
11
|
+
"dependencies": {
|
|
12
|
+
"@fastify/cors": "^11.2.0",
|
|
13
|
+
"@fastify/env": "^5.0.3",
|
|
14
|
+
"@fastify/helmet": "^13.0.2",
|
|
15
|
+
"dotenv": "^17.3.1",
|
|
16
|
+
"fast-glob": "^3.3.3",
|
|
17
|
+
"fastify": "^5.8.2",
|
|
18
|
+
"zod": "^4.3.6"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"@types/node": "^25.5.0",
|
|
22
|
+
"pino-pretty": "^13.1.3",
|
|
23
|
+
"tsx": "^4.21.0",
|
|
24
|
+
"typescript": "^5.9.3"
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import fastify from 'fastify'
|
|
2
|
+
import cors from '@fastify/cors'
|
|
3
|
+
import helmet from '@fastify/helmet'
|
|
4
|
+
import path from 'path'
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from 'url'
|
|
6
|
+
import fg from 'fast-glob'
|
|
7
|
+
import { env } from './utils/env'
|
|
8
|
+
import { sendResponse } from './utils/response'
|
|
9
|
+
|
|
10
|
+
const __filename = fileURLToPath(import.meta.url)
|
|
11
|
+
const __dirname = path.dirname(__filename)
|
|
12
|
+
|
|
13
|
+
async function autoRegister(app: ReturnType<typeof fastify>, pattern: string, prefix: string = '') {
|
|
14
|
+
const joined = path.join(__dirname, pattern).replace(/\\/g, '/')
|
|
15
|
+
const files = fg.sync(joined)
|
|
16
|
+
await Promise.all(files.map(async (file) => {
|
|
17
|
+
const module = await import(pathToFileURL(file).href)
|
|
18
|
+
const fn = module.default || module[Object.keys(module)[0]]
|
|
19
|
+
if (typeof fn === 'function') void app.register(fn, { prefix })
|
|
20
|
+
}))
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function buildApp() {
|
|
24
|
+
const isDev = env.NODE_ENV === 'development'
|
|
25
|
+
const app = fastify({
|
|
26
|
+
logger: {
|
|
27
|
+
level: 'info',
|
|
28
|
+
transport: isDev ? {
|
|
29
|
+
target: 'pino-pretty',
|
|
30
|
+
options: {
|
|
31
|
+
colorize: true,
|
|
32
|
+
translateTime: 'HH:MM:ss',
|
|
33
|
+
ignore: 'pid,hostname',
|
|
34
|
+
},
|
|
35
|
+
} : undefined,
|
|
36
|
+
},
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
app.register(cors, { origin: true })
|
|
40
|
+
app.register(helmet)
|
|
41
|
+
|
|
42
|
+
await autoRegister(app, 'plugins/**/*.plugin.{ts,js}')
|
|
43
|
+
await autoRegister(app, 'routes/**/*.routes.{ts,js}')
|
|
44
|
+
|
|
45
|
+
app.setNotFoundHandler((_request, reply) => sendResponse(reply, 404, { error: 'Route not found' }))
|
|
46
|
+
app.setErrorHandler((error: any, _request, reply) => {
|
|
47
|
+
const statusCode = error?.statusCode ?? 500
|
|
48
|
+
app.log.error(error)
|
|
49
|
+
return sendResponse(reply, statusCode, { error: statusCode >= 500 ? 'Internal Server Error' : error.message })
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
return app
|
|
53
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { FastifyRequest, FastifyReply } from 'fastify'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
import { sendResponse } from '../utils/response'
|
|
4
|
+
|
|
5
|
+
const userSchema = z.object({ id: z.uuid() })
|
|
6
|
+
|
|
7
|
+
export async function getUserHandler(request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) {
|
|
8
|
+
const parseResult = userSchema.safeParse(request.params)
|
|
9
|
+
if (!parseResult.success) return sendResponse(reply, 400, { error: 'Invalid user ID' })
|
|
10
|
+
const user = { id: parseResult.data.id, name: 'Nolly Example' }
|
|
11
|
+
return sendResponse(reply, 200, user)
|
|
12
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import 'dotenv/config'
|
|
2
|
+
import { buildApp } from './app'
|
|
3
|
+
import { env } from './utils/env'
|
|
4
|
+
|
|
5
|
+
const PORT = parseInt(env.PORT, 10)
|
|
6
|
+
const HOST = env.HOST
|
|
7
|
+
|
|
8
|
+
buildApp()
|
|
9
|
+
.then((app) => {
|
|
10
|
+
const shutdown = async (signal: string) => {
|
|
11
|
+
app.log.info(`Received ${signal}, shutting down...`)
|
|
12
|
+
await app.close()
|
|
13
|
+
process.exit(0)
|
|
14
|
+
}
|
|
15
|
+
process.on('SIGINT', () => shutdown('SIGINT'))
|
|
16
|
+
process.on('SIGTERM', () => shutdown('SIGTERM'))
|
|
17
|
+
app.listen({ port: PORT, host: HOST }).catch((error) => {
|
|
18
|
+
app.log.error('Error starting server:', error)
|
|
19
|
+
process.exit(1)
|
|
20
|
+
})
|
|
21
|
+
})
|
|
22
|
+
.catch((error) => {
|
|
23
|
+
console.error('Error building app:', error)
|
|
24
|
+
process.exit(1)
|
|
25
|
+
})
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { FastifyInstance } from 'fastify'
|
|
2
|
+
import { sendResponse } from '../utils/response'
|
|
3
|
+
|
|
4
|
+
export default async function healthPlugin(app: FastifyInstance) {
|
|
5
|
+
app.get('/health', async (_request, reply) => sendResponse(reply, 200, { status: 'ok', uptime: process.uptime() }))
|
|
6
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import 'dotenv/config'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
|
|
4
|
+
const envSchema = z.object({
|
|
5
|
+
PORT: z.string().optional().default('4000'),
|
|
6
|
+
HOST: z.string().optional().default('0.0.0.0'),
|
|
7
|
+
NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
|
|
8
|
+
})
|
|
9
|
+
|
|
10
|
+
const result = envSchema.safeParse(process.env)
|
|
11
|
+
if (!result.success) {
|
|
12
|
+
console.error('❌ Invalid environment variables:')
|
|
13
|
+
const flattened = z.treeifyError(result.error)
|
|
14
|
+
console.error(flattened.errors)
|
|
15
|
+
process.exit(1)
|
|
16
|
+
}
|
|
17
|
+
export const env = result.data
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2022",
|
|
4
|
+
"useDefineForClassFields": true,
|
|
5
|
+
"lib": [ "ES2022" ],
|
|
6
|
+
"module": "ESNext",
|
|
7
|
+
"moduleResolution": "bundler",
|
|
8
|
+
"allowImportingTsExtensions": true,
|
|
9
|
+
"isolatedModules": true,
|
|
10
|
+
"moduleDetection": "force",
|
|
11
|
+
"noEmit": true,
|
|
12
|
+
"strict": true,
|
|
13
|
+
"noUnusedLocals": true,
|
|
14
|
+
"noUnusedParameters": true,
|
|
15
|
+
"noFallthroughCasesInSwitch": true,
|
|
16
|
+
"noUncheckedSideEffectImports": true,
|
|
17
|
+
"skipLibCheck": true
|
|
18
|
+
},
|
|
19
|
+
"include": [ "src" ]
|
|
20
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import fastifyPlugin from 'fastify-plugin'
|
|
2
|
+
import { MongoClient, Db } from 'mongodb'
|
|
3
|
+
import { FastifyInstance } from 'fastify'
|
|
4
|
+
import path from 'path'
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from 'url'
|
|
6
|
+
import fastGlob from 'fast-glob'
|
|
7
|
+
import { env } from '../utils/env'
|
|
8
|
+
|
|
9
|
+
const __filename = fileURLToPath(import.meta.url)
|
|
10
|
+
const __dirname = path.dirname(__filename)
|
|
11
|
+
|
|
12
|
+
export type ModelFactory = (db: Db, app: FastifyInstance) => any
|
|
13
|
+
|
|
14
|
+
declare module 'fastify' {
|
|
15
|
+
interface FastifyInstance {
|
|
16
|
+
mongo: {
|
|
17
|
+
client: MongoClient
|
|
18
|
+
db: Db
|
|
19
|
+
}
|
|
20
|
+
models: Record<string, any>
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function autoLoadModels(app: FastifyInstance, db: Db) {
|
|
25
|
+
const pattern = path.join(__dirname, '../models/**/*.model.{ts,js}').replace(/\\/g, '/')
|
|
26
|
+
const files = fastGlob.sync(pattern)
|
|
27
|
+
const models: Record<string, any> = {}
|
|
28
|
+
for (const file of files) {
|
|
29
|
+
const module = await import(pathToFileURL(file).href)
|
|
30
|
+
const factory: ModelFactory = module.default || module[Object.keys(module)[0]]
|
|
31
|
+
if (typeof factory !== 'function') continue
|
|
32
|
+
const model = factory(db, app)
|
|
33
|
+
if (!model?.name) throw new Error(`Model in ${file} must return { name: string }`)
|
|
34
|
+
models[model.name] = model
|
|
35
|
+
}
|
|
36
|
+
return models
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export default fastifyPlugin(async function mongoPlugin(app) {
|
|
40
|
+
const client = new MongoClient(env.MONGO_URI, { serverSelectionTimeoutMS: 5000 })
|
|
41
|
+
try {
|
|
42
|
+
await client.connect()
|
|
43
|
+
} catch (error: any) {
|
|
44
|
+
app.log.error('Mongo connection failed:', error)
|
|
45
|
+
throw error
|
|
46
|
+
}
|
|
47
|
+
const db = client.db(env.MONGO_DB)
|
|
48
|
+
app.decorate('mongo', { client, db })
|
|
49
|
+
const models = await autoLoadModels(app, db)
|
|
50
|
+
app.decorate('models', models)
|
|
51
|
+
app.addHook('onClose', async () => { await client.close() })
|
|
52
|
+
app.log.info(`📦 Mongo connected: ${env.MONGO_DB}`)
|
|
53
|
+
}, { name: 'mongoPlugin' })
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { FastifyInstance } from 'fastify'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
import { createWebSocketContext, registerConnection } from '../utils/websocket'
|
|
4
|
+
|
|
5
|
+
export default async function chat(app: FastifyInstance) {
|
|
6
|
+
app.get('/chat', { websocket: true }, async (socket, request) => {
|
|
7
|
+
const options = { auth: false, jwtSecret: 'dev-secret', rateLimit: { max: 10, windowMs: 1000 } }
|
|
8
|
+
const client = await registerConnection(socket, request, options)
|
|
9
|
+
const context = createWebSocketContext(client, options)
|
|
10
|
+
app.log.info(`WS connected: ${context.id} user=${JSON.stringify(context.user)}`)
|
|
11
|
+
context.on('join', z.object({ room: z.string().min(1) }), ({ room }, context) => {
|
|
12
|
+
context.join(room)
|
|
13
|
+
context.send('joined', { room })
|
|
14
|
+
})
|
|
15
|
+
context.on('leave', z.object({ room: z.string().min(1) }), ({ room }, context) => {
|
|
16
|
+
context.leave(room)
|
|
17
|
+
context.send('left', { room })
|
|
18
|
+
})
|
|
19
|
+
context.on('message', z.object({ room: z.string().min(1), message: z.string().min(1) }), ({ room, message }, context) => context.broadcast('message', { from: context.user ?? context.id, message }, room))
|
|
20
|
+
context.on('broadcast', z.object({ message: z.string().min(1) }), ({ message }, context) => context.broadcast('broadcast', { from: context.user ?? context.id, message }))
|
|
21
|
+
socket.on('close', () => app.log.info(`WebSocket disconnected: ${context.id}`))
|
|
22
|
+
})
|
|
23
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { WebSocket } from '@fastify/websocket'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
import { createHmac, randomUUID } from 'crypto'
|
|
4
|
+
|
|
5
|
+
// ----- Protocol -----
|
|
6
|
+
|
|
7
|
+
const baseSchema = z.object({
|
|
8
|
+
event: z.string().min(1),
|
|
9
|
+
data: z.unknown().optional()
|
|
10
|
+
})
|
|
11
|
+
type BaseMessage = z.infer<typeof baseSchema>
|
|
12
|
+
|
|
13
|
+
// ----- Types -----
|
|
14
|
+
|
|
15
|
+
export type WebSocketUser = Record<string, any>
|
|
16
|
+
type Client = {
|
|
17
|
+
id: string
|
|
18
|
+
socket: WebSocket
|
|
19
|
+
rooms: Set<string>
|
|
20
|
+
handlers: Map<string, (data: unknown, context: WebSocketContext) => void>
|
|
21
|
+
user?: WebSocketUser
|
|
22
|
+
rate?: {
|
|
23
|
+
tokens: number
|
|
24
|
+
last: number
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const clients = new Map<string, Client>()
|
|
28
|
+
const rooms = new Map<string, Set<string>>()
|
|
29
|
+
|
|
30
|
+
// ----- Options -----
|
|
31
|
+
|
|
32
|
+
type WebSocketOptions = {
|
|
33
|
+
auth?: boolean | ((request: any) => Promise<WebSocketUser | null> | WebSocketUser | null)
|
|
34
|
+
jwtSecret?: string
|
|
35
|
+
rateLimit?: {
|
|
36
|
+
max: number
|
|
37
|
+
windowMs: number
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// ----- JsonWebSocket -----
|
|
42
|
+
|
|
43
|
+
function verifyJWT(token: string, secret: string): WebSocketUser | null {
|
|
44
|
+
try {
|
|
45
|
+
const [header, payload, signature] = token.split('.')
|
|
46
|
+
if (!header || !payload || !signature) return null
|
|
47
|
+
const expected = createHmac('sha256', secret).update(`${header}.${payload}`).digest('base64url')
|
|
48
|
+
if (expected !== signature) return null
|
|
49
|
+
const decoded = JSON.parse(Buffer.from(payload, 'base64url').toString())
|
|
50
|
+
return decoded
|
|
51
|
+
} catch {
|
|
52
|
+
return null
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// ----- Core -----
|
|
57
|
+
|
|
58
|
+
export async function registerConnection(socket: WebSocket, request?: any, options?: WebSocketOptions): Promise<Client> {
|
|
59
|
+
const id = randomUUID()
|
|
60
|
+
const client: Client = { id, socket, rooms: new Set(), handlers: new Map() }
|
|
61
|
+
if (options?.auth) {
|
|
62
|
+
let user: WebSocketUser | null = null
|
|
63
|
+
if (typeof options.auth === 'function') {
|
|
64
|
+
user = await options.auth(request)
|
|
65
|
+
} else if (options.auth === true) {
|
|
66
|
+
const header = request?.headers?.authorization
|
|
67
|
+
const token = header?.replace('Bearer ', '')
|
|
68
|
+
if (token && options.jwtSecret) user = verifyJWT(token, options.jwtSecret)
|
|
69
|
+
}
|
|
70
|
+
if (!user) {
|
|
71
|
+
socket.send(JSON.stringify({ event: 'error', data: { message: 'Unauthorized' } }))
|
|
72
|
+
socket.close()
|
|
73
|
+
throw new Error('Unauthorized WS connection')
|
|
74
|
+
}
|
|
75
|
+
client.user = user
|
|
76
|
+
}
|
|
77
|
+
if (options?.rateLimit) {
|
|
78
|
+
client.rate = {
|
|
79
|
+
tokens: options.rateLimit.max,
|
|
80
|
+
last: Date.now()
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
clients.set(id, client)
|
|
84
|
+
socket.on('close', () => {
|
|
85
|
+
for (const room of client.rooms) leaveRoom(id, room)
|
|
86
|
+
clients.delete(id)
|
|
87
|
+
})
|
|
88
|
+
return client
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ----- Rooms -----
|
|
92
|
+
|
|
93
|
+
function joinRoom(clientId: string, room: string) {
|
|
94
|
+
const client = clients.get(clientId)
|
|
95
|
+
if (!client) return
|
|
96
|
+
if (!rooms.has(room)) rooms.set(room, new Set())
|
|
97
|
+
rooms.get(room)!.add(clientId)
|
|
98
|
+
client.rooms.add(room)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function leaveRoom(clientId: string, room: string) {
|
|
102
|
+
const client = clients.get(clientId)
|
|
103
|
+
if (!client) return
|
|
104
|
+
rooms.get(room)?.delete(clientId)
|
|
105
|
+
client.rooms.delete(room)
|
|
106
|
+
if (rooms.get(room)?.size === 0) rooms.delete(room)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// ----- Broadcasting -----
|
|
110
|
+
|
|
111
|
+
function sendRaw(socket: WebSocket, payload: unknown) {
|
|
112
|
+
socket.send(JSON.stringify(payload))
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function broadcast(message: BaseMessage, room?: string) {
|
|
116
|
+
const payload = JSON.stringify(message)
|
|
117
|
+
if (room) {
|
|
118
|
+
const ids = rooms.get(room)
|
|
119
|
+
if (!ids) return
|
|
120
|
+
for (const id of ids) clients.get(id)?.socket.send(payload)
|
|
121
|
+
return
|
|
122
|
+
}
|
|
123
|
+
for (const client of clients.values()) client.socket.send(payload)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// ----- Rate Limiting -----
|
|
127
|
+
|
|
128
|
+
function checkRate(client: Client, options?: WebSocketOptions): boolean {
|
|
129
|
+
if (!options?.rateLimit || !client.rate) return true
|
|
130
|
+
const now = Date.now()
|
|
131
|
+
const elapsed = now - client.rate.last
|
|
132
|
+
const refill = (elapsed / options.rateLimit.windowMs) * options.rateLimit.max
|
|
133
|
+
client.rate.tokens = Math.min(options.rateLimit.max, client.rate.tokens + refill)
|
|
134
|
+
client.rate.last = now
|
|
135
|
+
if (client.rate.tokens < 1) return false
|
|
136
|
+
client.rate.tokens -= 1
|
|
137
|
+
return true
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// ----- Context -----
|
|
141
|
+
|
|
142
|
+
export type WebSocketContext = {
|
|
143
|
+
id: string
|
|
144
|
+
user?: WebSocketUser
|
|
145
|
+
send: (event: string, data?: unknown) => void
|
|
146
|
+
join: (room: string) => void
|
|
147
|
+
leave: (room: string) => void
|
|
148
|
+
broadcast: (event: string, data?: unknown, room?: string) => void
|
|
149
|
+
on: <T>(event: string, schema: z.ZodType<T>, handler: (data: T, context: WebSocketContext) => void) => void
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function createWebSocketContext(client: Client, options?: WebSocketOptions): WebSocketContext {
|
|
153
|
+
const context: WebSocketContext = {
|
|
154
|
+
id: client.id,
|
|
155
|
+
user: client.user,
|
|
156
|
+
send: (event, data) => sendRaw(client.socket, { event, data }),
|
|
157
|
+
join: (room) => joinRoom(client.id, room),
|
|
158
|
+
leave: (room) => leaveRoom(client.id, room),
|
|
159
|
+
broadcast: (event, data, room) => broadcast({ event, data }, room),
|
|
160
|
+
on: (event, schema, handler) => {
|
|
161
|
+
client.handlers.set(event, (raw, context) => {
|
|
162
|
+
if (!checkRate(client, options)) return context.send('error', { message: 'Rate limit exceeded' })
|
|
163
|
+
const parsed = schema.safeParse(raw)
|
|
164
|
+
if (!parsed.success) return context.send('error', { message: `Invalid payload for ${event}` })
|
|
165
|
+
handler(parsed.data, context)
|
|
166
|
+
})
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
client.socket.on('message', (raw: any) => {
|
|
170
|
+
let message: BaseMessage
|
|
171
|
+
try { message = baseSchema.parse(JSON.parse(raw.toString())) } catch { return context.send('error', { message: 'Invalid message format' }) }
|
|
172
|
+
const handler = client.handlers.get(message.event)
|
|
173
|
+
if (!handler) return context.send('error', { message: `Unhandled event: ${message.event}` })
|
|
174
|
+
handler(message.data, context)
|
|
175
|
+
})
|
|
176
|
+
return context
|
|
177
|
+
}
|