galbe 0.5.0 → 0.6.1
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/.github/ISSUE_TEMPLATE/bug_report.md +35 -0
- package/.github/ISSUE_TEMPLATE/feature_request.md +23 -0
- package/.github/workflows/deploy_website.yml +1 -1
- package/README.md +6 -1
- package/bin/cli.ts +2 -0
- package/bin/commands/build.ts +3 -0
- package/bin/commands/dev.ts +11 -3
- package/bin/commands/generate/client.ts +16 -8
- package/bin/commands/info.ts +29 -0
- package/bin/res/cli.template.js +1 -1
- package/bin/res/client.template.ts +6 -3
- package/bin/util.ts +20 -1
- package/docs/CONTRIBUTING.md +105 -0
- package/docs/cli.md +340 -0
- package/docs/getting-started.md +61 -46
- package/docs/plugins.md +7 -12
- package/docs/routes.md +1 -12
- package/package.json +1 -1
- package/src/extras/spec/openapi.serializer.ts +4 -1
- package/src/index.ts +18 -7
- package/src/server.ts +14 -12
- package/src/types.ts +5 -3
- package/src/util.ts +6 -5
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: Bug report
|
|
3
|
+
about: Create a report to help us improve
|
|
4
|
+
title: '[bug] '
|
|
5
|
+
labels: bug
|
|
6
|
+
assignees: ''
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
**Describe the bug**
|
|
10
|
+
|
|
11
|
+
<!-- A clear and concise description of what the bug is. -->
|
|
12
|
+
|
|
13
|
+
**Steps To Reproduce**
|
|
14
|
+
|
|
15
|
+
<!-- Steps to reproduce the behavior -->
|
|
16
|
+
|
|
17
|
+
**Expected behavior**
|
|
18
|
+
|
|
19
|
+
<!-- A clear and concise description of what you expected to happen. -->
|
|
20
|
+
|
|
21
|
+
**Screenshots**
|
|
22
|
+
|
|
23
|
+
<!-- If applicable, add screenshots to help explain your problem. -->
|
|
24
|
+
|
|
25
|
+
**Environment (please complete the following information):**
|
|
26
|
+
|
|
27
|
+
<!-- To help us diagnose the issue, please navigate to the root of your project in your terminal and execute "bunx galbe info". Then paste the output bellow -->
|
|
28
|
+
|
|
29
|
+
```txt
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
**Additional context**
|
|
34
|
+
|
|
35
|
+
<!-- Add any other context about the problem here. -->
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: Feature request
|
|
3
|
+
about: Suggest an idea for this project
|
|
4
|
+
title: '[feat] '
|
|
5
|
+
labels: enhancement
|
|
6
|
+
assignees: ''
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
**Is your feature request related to a problem? Please describe.**
|
|
10
|
+
|
|
11
|
+
<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
|
|
12
|
+
|
|
13
|
+
**Describe the solution you'd like**
|
|
14
|
+
|
|
15
|
+
<!-- A clear and concise description of what you want to happen. -->
|
|
16
|
+
|
|
17
|
+
**Describe alternatives you've considered**
|
|
18
|
+
|
|
19
|
+
<!-- A clear and concise description of any alternative solutions or features you've considered. -->
|
|
20
|
+
|
|
21
|
+
**Additional context**
|
|
22
|
+
|
|
23
|
+
<!-- Add any other context or screenshots about the feature request here. -->
|
|
@@ -16,5 +16,5 @@ jobs:
|
|
|
16
16
|
-H "Accept: application/vnd.github+json" \
|
|
17
17
|
-H "Authorization: Bearer ${{ secrets.GH_WEBSITE_TOKEN }}" \
|
|
18
18
|
-H "X-GitHub-Api-Version: 2022-11-28" \
|
|
19
|
-
https://api.github.com/repos/pierre-cm/galbe-website/actions/workflows/
|
|
19
|
+
https://api.github.com/repos/pierre-cm/galbe-website/actions/workflows/static.yml/dispatches \
|
|
20
20
|
-d '{"ref":"main"}'
|
package/README.md
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<a href="https://galbe.dev"><img src="https://galbe.dev/galbe.svg" alt="Logo" height=150></a>
|
|
3
|
+
</p>
|
|
4
|
+
<h1 align="center">Galbe</h1>
|
|
2
5
|
|
|
3
6
|
[](https://github.com/pierre-cm/galbe/actions/workflows/build_test.yml)
|
|
4
7
|
[](https://github.com/pierre-cm/galbe/blob/main/LICENSE)
|
|
@@ -22,3 +25,5 @@ bun install && bun dev
|
|
|
22
25
|
The detailed documentation is available at [galbe.dev](https://galbe.dev).
|
|
23
26
|
|
|
24
27
|
## Contributing
|
|
28
|
+
|
|
29
|
+
Please refer to the [Contributing Guide](https://github.com/pierre-cm/galbe/blob/main/docs/CONTRIBUTING.md) to start contributing to Galbe.
|
package/bin/cli.ts
CHANGED
|
@@ -7,11 +7,13 @@ import { pckg } from './util'
|
|
|
7
7
|
import dev from './commands/dev'
|
|
8
8
|
import build from './commands/build'
|
|
9
9
|
import generate from './commands/generate'
|
|
10
|
+
import info from './commands/info'
|
|
10
11
|
|
|
11
12
|
program.name('galbe').description(pckg.description).version(pckg.version)
|
|
12
13
|
|
|
13
14
|
dev(program.command('dev'))
|
|
14
15
|
build(program.command('build'))
|
|
15
16
|
generate(program.command('generate'))
|
|
17
|
+
info(program.command('info'))
|
|
16
18
|
|
|
17
19
|
program.parse()
|
package/bin/commands/build.ts
CHANGED
|
@@ -79,9 +79,12 @@ export default (cmd: Command) => {
|
|
|
79
79
|
...Object.fromEntries(Object.entries(bunfig).filter(([k, v]) => v)),
|
|
80
80
|
entrypoints: [buildIndex],
|
|
81
81
|
outdir: resolve(CWD, out),
|
|
82
|
+
sourcemap: 'external',
|
|
82
83
|
target: 'bun'
|
|
83
84
|
}
|
|
84
85
|
|
|
86
|
+
await rm(resolve(CWD, out), { recursive: true })
|
|
87
|
+
|
|
85
88
|
let bo = await Bun.build(buildConfig)
|
|
86
89
|
if (bo.success) process.stdout.write(' : \x1b[1;30m\x1b[32mdone\x1b[0m\n')
|
|
87
90
|
else {
|
package/bin/commands/dev.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { $ } from 'bun'
|
|
|
2
2
|
import { Command, Option } from 'commander'
|
|
3
3
|
import { resolve } from 'path'
|
|
4
4
|
|
|
5
|
-
import { CWD, fmtInterval, fmtVal, instanciateRoutes, watchDir } from '../util'
|
|
5
|
+
import { CWD, fmtInterval, fmtVal, instanciateRoutes, killPort, watchDir } from '../util'
|
|
6
6
|
import { Galbe } from '../../src'
|
|
7
7
|
|
|
8
8
|
const defaultPort = 3000
|
|
@@ -22,13 +22,21 @@ export default (cmd: Command) => {
|
|
|
22
22
|
)
|
|
23
23
|
.addOption(new Option('-w, --watch', 'watch file changes').default(false, fmtVal(false)))
|
|
24
24
|
.addOption(new Option('-nc, --noclear', "don't clear on file changes").default(false, fmtVal(false)))
|
|
25
|
+
.addOption(
|
|
26
|
+
new Option('-f, --force', 'kills any process running on defined port before strating the server').default(
|
|
27
|
+
false,
|
|
28
|
+
fmtVal(false)
|
|
29
|
+
)
|
|
30
|
+
)
|
|
25
31
|
.action(async (index, props) => {
|
|
26
|
-
const { port, watch, noclear } = props
|
|
32
|
+
const { port, watch, noclear, force } = props
|
|
27
33
|
const clear = !noclear
|
|
28
34
|
const indexPath = resolve(CWD, index)
|
|
29
35
|
let g: Galbe
|
|
30
36
|
|
|
31
|
-
Bun.env.BUN_ENV = 'development'
|
|
37
|
+
if (!Bun.env.BUN_ENV) Bun.env.BUN_ENV = 'development'
|
|
38
|
+
|
|
39
|
+
if (force) await killPort(port || 3000)
|
|
32
40
|
|
|
33
41
|
if (watch) {
|
|
34
42
|
await watchDir(
|
|
@@ -82,7 +82,14 @@ export default (cmd: Command) => {
|
|
|
82
82
|
[...r.path.matchAll(/:([^\/]+)/g)]?.map(m => [
|
|
83
83
|
m?.[1],
|
|
84
84
|
{
|
|
85
|
-
...(r.schema?.params?.[m?.[1]]
|
|
85
|
+
...(r.schema?.params?.[m?.[1]]
|
|
86
|
+
? {
|
|
87
|
+
type: schemaToTypeStr(r.schema.params[m[1]]),
|
|
88
|
+
...(r.schema.params[m[1]]?.description
|
|
89
|
+
? { description: r.schema.params[m[1]].description as string }
|
|
90
|
+
: {})
|
|
91
|
+
}
|
|
92
|
+
: { type: 'string' })
|
|
86
93
|
}
|
|
87
94
|
])
|
|
88
95
|
) || {},
|
|
@@ -106,14 +113,15 @@ export default (cmd: Command) => {
|
|
|
106
113
|
description: meta.head,
|
|
107
114
|
route,
|
|
108
115
|
arguments:
|
|
109
|
-
Object.entries((
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
116
|
+
Object.entries((route?.params || {}) as Record<string, { type: string; description?: string }>)?.map(
|
|
117
|
+
([k, p]) => {
|
|
118
|
+
return {
|
|
119
|
+
name: k,
|
|
120
|
+
type: p.type === 'boolean' ? '' : `<${p.type}>`,
|
|
121
|
+
description: p?.description || ''
|
|
122
|
+
}
|
|
115
123
|
}
|
|
116
|
-
|
|
124
|
+
) || [],
|
|
117
125
|
options:
|
|
118
126
|
Object.entries((r.schema?.query || {}) as Record<string, STSchema>)?.map(([k, o]) => {
|
|
119
127
|
let type = schemaToTypeStr({ ...o, [Optional]: false })
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import os from 'os'
|
|
2
|
+
import { Command } from 'commander'
|
|
3
|
+
|
|
4
|
+
export default async (cmd: Command) => {
|
|
5
|
+
cmd.description('print informations about the current os, bun and galbe version').action(async () => {
|
|
6
|
+
const osName = os.type()
|
|
7
|
+
const osArch = os.arch()
|
|
8
|
+
const osVersion = os.release()
|
|
9
|
+
|
|
10
|
+
const bunVersion = Bun.version
|
|
11
|
+
const bunRevision = Bun.revision
|
|
12
|
+
|
|
13
|
+
let localPckg: any = {}
|
|
14
|
+
try {
|
|
15
|
+
localPckg = await Bun.file('./node_modules/galbe/package.json').json()
|
|
16
|
+
} catch (err) {}
|
|
17
|
+
const galbeVersion = localPckg?.version || 'not found'
|
|
18
|
+
|
|
19
|
+
console.log('OS')
|
|
20
|
+
console.log(` name: ${osName}`)
|
|
21
|
+
console.log(` arch: ${osArch}`)
|
|
22
|
+
console.log(` version: ${osVersion}`)
|
|
23
|
+
console.log('Bun')
|
|
24
|
+
console.log(` version: ${bunVersion}`)
|
|
25
|
+
console.log(` revision: ${bunRevision}`)
|
|
26
|
+
console.log('Galbe')
|
|
27
|
+
console.log(` version: ${galbeVersion}`)
|
|
28
|
+
})
|
|
29
|
+
}
|
package/bin/res/cli.template.js
CHANGED
|
@@ -100,7 +100,7 @@ const formatDefault = def =>
|
|
|
100
100
|
: def ?? 'undefined';
|
|
101
101
|
|
|
102
102
|
result = commands.map(c=>{
|
|
103
|
-
let args = c.arguments.map(a=>`.argument("${a.
|
|
103
|
+
let args = c.arguments.map(a=>`.argument("${a.name}", "${a.description || a.name+' argument' || ''}")`)
|
|
104
104
|
let optionsBase = [
|
|
105
105
|
{name: '%format', short:'%f', type: '[string]', description: 'response format [\'s\',\'h\',\'b\',\'t\',\'p\']', default:["s","b","p"]},
|
|
106
106
|
{name: '%header', short:'%h', type: '<string...>', description: 'request header formated as headerName=headerValue', default:[]},
|
|
@@ -42,8 +42,9 @@ type PGR<
|
|
|
42
42
|
O extends number = 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 226
|
|
43
43
|
> = Promise<GR<S, B, O>>
|
|
44
44
|
|
|
45
|
-
type RequestOptions<H = any, B = any> = {
|
|
45
|
+
type RequestOptions<H = any, Q = any, B = any> = {
|
|
46
46
|
headers?: H
|
|
47
|
+
query?: Q
|
|
47
48
|
body?: B
|
|
48
49
|
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD'
|
|
49
50
|
}
|
|
@@ -61,7 +62,7 @@ export default class GalbeClient {
|
|
|
61
62
|
return`${method} = {\n${list.map( r => {
|
|
62
63
|
let p = Object.entries(r.params)
|
|
63
64
|
let schemas = Object.keys(r.schemas).length ?
|
|
64
|
-
`<${r.schemas.headers??'any'},${r.schemas.body??'any'}>`:
|
|
65
|
+
`<${r.schemas.headers??'any'},${r.schemas.query??'any'},${r.schemas.body??'any'}>`:
|
|
65
66
|
''
|
|
66
67
|
let oks = Object.keys(r.schemas?.response||{}).filter(s=>s>=200&&s<300)
|
|
67
68
|
let responses = Object.keys(r.schemas?.response||{}).length ?
|
|
@@ -79,6 +80,8 @@ export default class GalbeClient {
|
|
|
79
80
|
|
|
80
81
|
async fetch(path: string, options: RequestOptions) {
|
|
81
82
|
let url = `${this?.config?.server?.url ?? ''}${path}`
|
|
83
|
+
const params = new URLSearchParams(options?.query || {})
|
|
84
|
+
url = `${url}?${params.toString()}`
|
|
82
85
|
let res = await fetch(url, {
|
|
83
86
|
method: options?.method || 'GET',
|
|
84
87
|
headers: { ...DEFAULT_HEADERS, ...(options?.headers || {}) },
|
|
@@ -148,7 +151,7 @@ export default class GalbeClient {
|
|
|
148
151
|
return list.filter(r=>r.alias).map(r => {
|
|
149
152
|
let p = Object.entries(r.params)
|
|
150
153
|
let schemas = Object.keys(r.schemas).length ?
|
|
151
|
-
`<${r.schemas.headers??'any'},${r.schemas.body??'any'}>`:
|
|
154
|
+
`<${r.schemas.headers??'any'},${r.schemas.query??'any'},${r.schemas.body??'any'}>`:
|
|
152
155
|
''
|
|
153
156
|
let oks = Object.keys(r.schemas?.response||{}).filter(s=>s>=200&&s<300)
|
|
154
157
|
let responses = Object.keys(r.schemas?.response||{}).length ?
|
package/bin/util.ts
CHANGED
|
@@ -58,7 +58,7 @@ export const watchDir = async (
|
|
|
58
58
|
})
|
|
59
59
|
}
|
|
60
60
|
export const instanciateRoutes = async (g: Galbe) => {
|
|
61
|
-
console.log('🏗️ \x1b[
|
|
61
|
+
console.log('🏗️ \x1b[1mConstructing routes\x1b[0m\n')
|
|
62
62
|
// Main thread routes definitions
|
|
63
63
|
let hasMainRoutes = false
|
|
64
64
|
walkRoutes(g.router.routes, r => {
|
|
@@ -102,6 +102,25 @@ export const softMerge = (base, override) => {
|
|
|
102
102
|
return base
|
|
103
103
|
}
|
|
104
104
|
|
|
105
|
+
export const killPort = async (port: number) => {
|
|
106
|
+
let getProcCmd: string[], killCmd: (port: string) => string[]
|
|
107
|
+
|
|
108
|
+
if (process.platform === 'win32') {
|
|
109
|
+
getProcCmd = ['cmd', '-c', `netstat -aon | findstr ${port}`]
|
|
110
|
+
killCmd = (pid: string) => ['taskkill', '/pid', pid, '/f']
|
|
111
|
+
} else {
|
|
112
|
+
getProcCmd = ['lsof', '-t', `-i:${port}`, '-sTCP:LISTEN']
|
|
113
|
+
killCmd = (pid: string) => ['kill', '-9', pid]
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
let proc = Bun.spawn(getProcCmd, { stdout: 'pipe' })
|
|
117
|
+
const pid = (await new Response(proc.stdout).text()).trim()
|
|
118
|
+
if (pid) {
|
|
119
|
+
proc = Bun.spawn(killCmd(pid), { stdout: 'pipe' })
|
|
120
|
+
await proc.exited
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
105
124
|
export const HttpStatus = {
|
|
106
125
|
100: 'Continue',
|
|
107
126
|
101: 'Switching Protocols',
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# Contributing to Galbe
|
|
2
|
+
|
|
3
|
+
First off, thank you for considering contributing to our project! We appreciate your time and effort and want to make this as easy and transparent as possible for everyone.
|
|
4
|
+
|
|
5
|
+
## Create an Issue
|
|
6
|
+
|
|
7
|
+
If you encounter a bug, want to propose a new feature, or something that could be improved, please create an issue. Here's how:
|
|
8
|
+
|
|
9
|
+
1. **Check Existing Issues**: Before creating a new issue, please search the [existing issues](https://github.com/pierre-cm/galbe/issues) to see if someone else has already reported the same problem or suggested the same feature.
|
|
10
|
+
|
|
11
|
+
2. **Open a New Issue**: If your issue is new, [open a new issue](https://github.com/pierre-cm/galbe/issues/new/choose) and provide the following details:
|
|
12
|
+
|
|
13
|
+
- **Title**: A concise summary of the issue.
|
|
14
|
+
- **Description**: A detailed description of the problem or suggestion. Include steps to reproduce the issue if applicable.
|
|
15
|
+
- **Screenshots**: If possible, include screenshots or other visual aids that help explain the issue.
|
|
16
|
+
- **Environment**: Mention the environment in which you encountered the issue (e.g., OS, Bun version).
|
|
17
|
+
- **Labels**: Assign appropriate labels (e.g., bug, enhancement) to help categorize your issue.
|
|
18
|
+
|
|
19
|
+
3. **Follow Up**: Once your issue is submitted, be ready to provide additional information if requested. We'll do our best to address the issue promptly.
|
|
20
|
+
|
|
21
|
+
## Create a Pull Request
|
|
22
|
+
|
|
23
|
+
### 1. Fork the Repository
|
|
24
|
+
|
|
25
|
+
If you haven't already, [fork Galbe's repository on GitHub](https://github.com/pierre-cm/galbe/fork). This will create a copy of this repository under your GitHub account.
|
|
26
|
+
|
|
27
|
+
### 2. Clone Your Fork
|
|
28
|
+
|
|
29
|
+
Clone the forked repository to your local machine:
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
git clone https://github.com/<your-username>/galbe.git
|
|
33
|
+
cd galbe
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### 3. Create a New Branch
|
|
37
|
+
|
|
38
|
+
Before making any changes, create a new branch for your work. Branches help keep your changes separate from the main branch and make it easier to review and merge:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
git checkout -b feature/your-feature-name
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Use a descriptive name for your branch to indicate what you are working on.
|
|
45
|
+
|
|
46
|
+
### 4. Make Your Changes
|
|
47
|
+
|
|
48
|
+
Make the necessary changes in your branch. Be sure to follow the project's coding style and best practices.
|
|
49
|
+
|
|
50
|
+
### 5. Commit Your Changes
|
|
51
|
+
|
|
52
|
+
Once you’ve made your changes, commit them with a clear and descriptive message:
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
git add .
|
|
56
|
+
git commit -m "Add feature X to do Y"
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### 6. Push to Your Fork
|
|
60
|
+
|
|
61
|
+
Push your changes to your forked repository on GitHub:
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
git push origin feature/your-feature-name
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### 7. Create a Pull Request
|
|
68
|
+
|
|
69
|
+
Once your changes are pushed to GitHub, you can create a pull request. Go to the [original repository](https://github.com/pierre-cm/galbe) on GitHub, and you should see an option to create a pull request from your branch.
|
|
70
|
+
|
|
71
|
+
- Make sure to provide a detailed description of your changes and why they are necessary.
|
|
72
|
+
- Link any related issues if applicable.
|
|
73
|
+
- If your pull request is still a work in progress, mark it as a draft to let others know that you are not yet ready for a review.
|
|
74
|
+
|
|
75
|
+
### 8. Respond to Feedback
|
|
76
|
+
|
|
77
|
+
Once your pull request is submitted, it will be reviewed by the project maintainers. They may ask for changes or provide feedback. Please be responsive and make the necessary adjustments.
|
|
78
|
+
|
|
79
|
+
### Coding Standards
|
|
80
|
+
|
|
81
|
+
Please follow these coding standards to ensure consistency across the project:
|
|
82
|
+
|
|
83
|
+
- **Code Style**: Follow the [style guide]().
|
|
84
|
+
- **Commit Messages**: Use clear and descriptive commit messages.
|
|
85
|
+
- **Documentation**: Update documentation where applicable. This includes comments in the code and other documentation files under the `docs` directory.
|
|
86
|
+
|
|
87
|
+
## Code of Conduct
|
|
88
|
+
|
|
89
|
+
We are committed to creating a welcoming and inclusive environment for everyone. To ensure this, all contributors are expected to adhere to the following guidelines:
|
|
90
|
+
|
|
91
|
+
1. **Be Respectful**: Treat everyone with respect. Disagreements are inevitable, but it's important to remain courteous and constructive. Personal attacks, harassment, or offensive comments will not be tolerated.
|
|
92
|
+
|
|
93
|
+
2. **Collaborate Openly**: Collaboration is key to the success of the project. Be open to feedback and suggestions from others. Constructive criticism should be welcomed and given in a positive manner.
|
|
94
|
+
|
|
95
|
+
3. **Resolve Disagreements Constructively**: If you find yourself in a disagreement, seek to resolve it in a way that is constructive and respectful. If necessary, involve a project maintainer to help mediate.
|
|
96
|
+
|
|
97
|
+
4. **Report Issues**: If you witness or experience any behavior that violates this Code of Conduct, please report it immediately to the project maintainers. We take all reports seriously and will address them promptly.
|
|
98
|
+
|
|
99
|
+
By participating in this project, you agree to abide by this Code of Conduct.
|
|
100
|
+
|
|
101
|
+
## Getting Help
|
|
102
|
+
|
|
103
|
+
If you have any questions or need help, feel free to open an issue or contact one of the maintainers.
|
|
104
|
+
|
|
105
|
+
Thank you for your contribution!
|
package/docs/cli.md
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
# CLI
|
|
2
|
+
|
|
3
|
+
A Command Line Interface is shipped with Galbe package. You can use it to perform useful tasks around your application.
|
|
4
|
+
|
|
5
|
+
After [Installing Galbe](getting-started.md#automatic-installation), the CLI will be available locally to your project.
|
|
6
|
+
|
|
7
|
+
However, if you want to use it directly from your terminal, you must either:
|
|
8
|
+
|
|
9
|
+
Install it globally using the following command:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
$ bun install -g galbe
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Or run it with `bunx`:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
$ bunx galbe
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## dev
|
|
22
|
+
|
|
23
|
+
Start a dev server running your Galbe application.
|
|
24
|
+
|
|
25
|
+
#### Arguments
|
|
26
|
+
|
|
27
|
+
| Name | Description |
|
|
28
|
+
| ----- | -------------------------------------------------------- |
|
|
29
|
+
| index | The js or ts file that export you Galbe server instance. |
|
|
30
|
+
|
|
31
|
+
#### Options
|
|
32
|
+
|
|
33
|
+
| Short | Long | Descritpion | Default |
|
|
34
|
+
| ----- | --------- | --------------------------- | ------- |
|
|
35
|
+
| -p | --port | port number [1-65535] | 3000 |
|
|
36
|
+
| -w | --watch | watch file changes | false |
|
|
37
|
+
| -nc | --noclear | don't clear on file changes | false |
|
|
38
|
+
|
|
39
|
+
#### Example
|
|
40
|
+
|
|
41
|
+
index.js
|
|
42
|
+
|
|
43
|
+
```js
|
|
44
|
+
import { Galbe } from 'galbe'
|
|
45
|
+
|
|
46
|
+
const g = new Galbe()
|
|
47
|
+
g.get('example', () => '')
|
|
48
|
+
|
|
49
|
+
export default g
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
$ galbe dev index.js -p 7357 -w
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## build
|
|
57
|
+
|
|
58
|
+
Bundle your Galbe application.
|
|
59
|
+
|
|
60
|
+
#### Arguments
|
|
61
|
+
|
|
62
|
+
| Name | Description |
|
|
63
|
+
| ----- | -------------------------------------------------------- |
|
|
64
|
+
| index | The js or ts file that export you Galbe server instance. |
|
|
65
|
+
|
|
66
|
+
#### Options
|
|
67
|
+
|
|
68
|
+
| Short | Long | Descritpion | Default |
|
|
69
|
+
| ----- | --------- | ------------------------------ | -------- |
|
|
70
|
+
| -o | --out | output directory | dist/app |
|
|
71
|
+
| -C | --compile | create a standalone executable | false |
|
|
72
|
+
| -c | --config | bun config (js or ts) | |
|
|
73
|
+
|
|
74
|
+
#### Example
|
|
75
|
+
|
|
76
|
+
index.js
|
|
77
|
+
|
|
78
|
+
```js
|
|
79
|
+
import { Galbe } from 'galbe'
|
|
80
|
+
|
|
81
|
+
export default new Galbe()
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
$ galbe build index.js
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## generate
|
|
89
|
+
|
|
90
|
+
Generate resources arround your Galbe application.
|
|
91
|
+
|
|
92
|
+
### client
|
|
93
|
+
|
|
94
|
+
Generate a client for your Galbe application.
|
|
95
|
+
|
|
96
|
+
#### Arguments
|
|
97
|
+
|
|
98
|
+
| Name | Description |
|
|
99
|
+
| ----- | -------------------------------------------------------- |
|
|
100
|
+
| index | The js or ts file that export you Galbe server instance. |
|
|
101
|
+
|
|
102
|
+
#### Options
|
|
103
|
+
|
|
104
|
+
| Short | Long | Descritpion | Default |
|
|
105
|
+
| ----- | -------- | -------------------------- | ------------------------------------ |
|
|
106
|
+
| -o | --out | output file | dist/(client.ts \| client.js \| cli) |
|
|
107
|
+
| -t | --target | build target [ts, js, cli] | ts |
|
|
108
|
+
|
|
109
|
+
#### Examples
|
|
110
|
+
|
|
111
|
+
Let's first setup a new Galbe project:
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
$ bun create galbe galbe-example -t hello -l ts
|
|
115
|
+
$ cd galbe-example
|
|
116
|
+
$ bun install
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
> [!NOTE]
|
|
120
|
+
> In order for the following examples to work, you must ensure that an instance of you galbe app is running on port 3000.
|
|
121
|
+
> You can do that by running `bun run dev`.
|
|
122
|
+
|
|
123
|
+
##### JS or TS client
|
|
124
|
+
|
|
125
|
+
To generate a JS or TS client of that application, you can run the following command:
|
|
126
|
+
|
|
127
|
+
```bash
|
|
128
|
+
$ galbe generate client index.ts
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
This will generate a `dist/client.ts` client lib by default.
|
|
132
|
+
You can import it and use it like in the following example:
|
|
133
|
+
|
|
134
|
+
client_example.ts
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
import HelloClient from './dist/client'
|
|
138
|
+
|
|
139
|
+
const client = new HelloClient({ server: { url: 'http://localhost:3000' } })
|
|
140
|
+
|
|
141
|
+
const response = await client.hello('Bob', { query: { age: 42 } })
|
|
142
|
+
// This is equivalent as calling
|
|
143
|
+
// const response = await client.get["/hello/:name"]("Bob", { query: { age: 42 } })
|
|
144
|
+
|
|
145
|
+
if (response.ok) console.log(await response.body())
|
|
146
|
+
// Hello Bob! You're 42 y.o.
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
##### CLI client
|
|
150
|
+
|
|
151
|
+
To generate a CLI of that application, you can run the following command:
|
|
152
|
+
|
|
153
|
+
```bash
|
|
154
|
+
$ galbe generate client index.ts -t cli
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
This will generate a `cli` binary file under `dist` directory by default.
|
|
158
|
+
|
|
159
|
+
```bash
|
|
160
|
+
$ ./dist/cli --help
|
|
161
|
+
Usage: galbe-example [options] [command]
|
|
162
|
+
|
|
163
|
+
Options:
|
|
164
|
+
-V, --version output the version number
|
|
165
|
+
-h, --help display help for command
|
|
166
|
+
|
|
167
|
+
Commands:
|
|
168
|
+
hello [options] Greeting endpoint
|
|
169
|
+
help [command] display help for command
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
```bash
|
|
173
|
+
$ ./dist/cli hello --help
|
|
174
|
+
Usage: galbe-example hello [options] <name>
|
|
175
|
+
|
|
176
|
+
Greeting endpoint
|
|
177
|
+
|
|
178
|
+
Arguments:
|
|
179
|
+
name name argument
|
|
180
|
+
|
|
181
|
+
Options:
|
|
182
|
+
-%f, --%format [string] response format ['s','h','b','t','p'] (default: ["s","b","p"])
|
|
183
|
+
-%h, --%header <string...> request header formated as headerName=headerValue (default: [])
|
|
184
|
+
-%q, --%query <string...> query param formated as paramName=paramValue (default: [])
|
|
185
|
+
-%b, --%body <string> request body (default: "")
|
|
186
|
+
-%bf, --%bodyFile <path> request body file (default: "")
|
|
187
|
+
-a, --age <number>
|
|
188
|
+
-h, --help display help for command
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
```bash
|
|
192
|
+
$ ./dist/cli hello Pierre -a 29
|
|
193
|
+
200
|
|
194
|
+
Hello Pierre! You're 29 y.o.
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
> [!IMPORTANT]
|
|
198
|
+
> A `GCLI_SERVER_URL` environment variable must be defined. It should indicates the url of the Galbe server you want to target.
|
|
199
|
+
> In that specific case `http://localhost:3000`.
|
|
200
|
+
|
|
201
|
+
### spec
|
|
202
|
+
|
|
203
|
+
Generate the spec of your Galbe application.
|
|
204
|
+
|
|
205
|
+
#### Arguments
|
|
206
|
+
|
|
207
|
+
| Name | Description |
|
|
208
|
+
| ----- | -------------------------------------------------------- |
|
|
209
|
+
| index | The js or ts file that export you Galbe server instance. |
|
|
210
|
+
|
|
211
|
+
#### Options
|
|
212
|
+
|
|
213
|
+
| Short | Long | Descritpion | Default |
|
|
214
|
+
| ----- | -------- | ------------------------------------------------ | ----------------------- |
|
|
215
|
+
| -t | --target | spec target [openapi:3.0:json, openapi:3.0:yaml] | openapi:3.0:yaml |
|
|
216
|
+
| -b | --base | base spec file | |
|
|
217
|
+
| -o | --out | output file | spec/api.(yaml \| json) |
|
|
218
|
+
|
|
219
|
+
#### Example
|
|
220
|
+
|
|
221
|
+
Let's try to generate the specof the project defined in the previous client section. You can then run:
|
|
222
|
+
|
|
223
|
+
```bash
|
|
224
|
+
$ galbe generate spec index.ts
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
This should generate the following `spec/api.yaml` file:
|
|
228
|
+
|
|
229
|
+
```yaml
|
|
230
|
+
openapi: 3.0.3
|
|
231
|
+
info:
|
|
232
|
+
title: galbe-app
|
|
233
|
+
version: 0.1.0
|
|
234
|
+
paths:
|
|
235
|
+
/hello/{name}:
|
|
236
|
+
get:
|
|
237
|
+
summary: Greeting endpoint
|
|
238
|
+
operationId: hello
|
|
239
|
+
parameters:
|
|
240
|
+
- name: age
|
|
241
|
+
in: query
|
|
242
|
+
required: true
|
|
243
|
+
schema:
|
|
244
|
+
type: integer
|
|
245
|
+
responses:
|
|
246
|
+
'200':
|
|
247
|
+
description: OK
|
|
248
|
+
content:
|
|
249
|
+
text/plain:
|
|
250
|
+
schema:
|
|
251
|
+
type: string
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
### code
|
|
255
|
+
|
|
256
|
+
Generate the code and project structure from spec.
|
|
257
|
+
|
|
258
|
+
#### Arguments
|
|
259
|
+
|
|
260
|
+
| Name | Description |
|
|
261
|
+
| ----- | ---------------------------------------------------------- |
|
|
262
|
+
| input | The input spec file from which the code will be generated. |
|
|
263
|
+
|
|
264
|
+
#### Options
|
|
265
|
+
|
|
266
|
+
| Short | Long | Descritpion | Default |
|
|
267
|
+
| ----- | -------- | ------------------------------------------------- | -------------------------- |
|
|
268
|
+
| -f | --format | input format [openapi:3.0:yaml, openapi:3.0:json] | openapi:3.0:(yaml \| json) |
|
|
269
|
+
| -t | --target | source target [ts, js] | ts |
|
|
270
|
+
| -o | --out | output dir | src |
|
|
271
|
+
| -F | --force | force overriding output | false |
|
|
272
|
+
|
|
273
|
+
#### Example
|
|
274
|
+
|
|
275
|
+
For that example, we will generate the Galbe source code from the [Swagger Petstore Openapi spec](https://petstore3.swagger.io/).
|
|
276
|
+
|
|
277
|
+
First, initiate a new bun project and install the galbe dependency.
|
|
278
|
+
|
|
279
|
+
```bash
|
|
280
|
+
$ mkdir petstore && cd petstore
|
|
281
|
+
$ bun init && bun add galbe
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
Now modify the `index.ts` file with the following content:
|
|
285
|
+
|
|
286
|
+
```ts
|
|
287
|
+
import { Galbe } from 'galbe'
|
|
288
|
+
|
|
289
|
+
export default new Galbe()
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
Then download the petstore json spec from Swagger website into `petstore.spec.json`:
|
|
293
|
+
|
|
294
|
+
```bash
|
|
295
|
+
$ curl -o petstore.spec.json https://petstore3.swagger.io/api/v3/openapi.json
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
You can now generate the sources from the petstore spec:
|
|
299
|
+
|
|
300
|
+
```bash
|
|
301
|
+
$ galbe generate code petstore.spec.json
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
This should generate the code of our application in the `src` directory by default.
|
|
305
|
+
|
|
306
|
+
To test that the code was successfully generated, you can run:
|
|
307
|
+
|
|
308
|
+
```bash
|
|
309
|
+
$ galbe dev index.ts
|
|
310
|
+
🏗️ Constructing routes
|
|
311
|
+
|
|
312
|
+
src/routes/pet.route.ts
|
|
313
|
+
[PUT] /pet Update an existing pet
|
|
314
|
+
[POST] /pet Add a new pet to the store
|
|
315
|
+
[GET] /pet/findByStatus Finds Pets by status
|
|
316
|
+
[GET] /pet/findByTags Finds Pets by tags
|
|
317
|
+
[GET] /pet/:petId Find pet by ID
|
|
318
|
+
[POST] /pet/:petId Updates a pet in the store with form data
|
|
319
|
+
[DELETE] /pet/:petId Deletes a pet
|
|
320
|
+
[POST] /pet/:petId/uploadImage uploads an image
|
|
321
|
+
|
|
322
|
+
src/routes/store.route.ts
|
|
323
|
+
[GET] /store/inventory Returns pet inventories by status
|
|
324
|
+
[POST] /store/order Place an order for a pet
|
|
325
|
+
[GET] /store/order/:orderId Find purchase order by ID
|
|
326
|
+
[DELETE] /store/order/:orderId Delete purchase order by ID
|
|
327
|
+
|
|
328
|
+
src/routes/user.route.ts
|
|
329
|
+
[POST] /user Create user
|
|
330
|
+
[POST] /user/createWithList Creates list of users with given input array
|
|
331
|
+
[GET] /user/login Logs user into the system
|
|
332
|
+
[GET] /user/logout Logs out current logged in user session
|
|
333
|
+
[GET] /user/:username Get user by user name
|
|
334
|
+
[PUT] /user/:username Update user
|
|
335
|
+
[DELETE] /user/:username Delete user
|
|
336
|
+
|
|
337
|
+
done
|
|
338
|
+
|
|
339
|
+
🚀 Server running at http://localhost:3000
|
|
340
|
+
```
|
package/docs/getting-started.md
CHANGED
|
@@ -14,29 +14,40 @@ This is the recommended way of setting up a Galbe project.
|
|
|
14
14
|
|
|
15
15
|
```bash
|
|
16
16
|
$ bun create galbe app
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
The Galbe starter CLI will request you to chose a template and a target language for your project. Let's select `hello` as template and `ts` as language. This will create a new project under `app` directory.
|
|
20
|
+
|
|
21
|
+
Now you can navigate to your newly created project and install it:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
17
24
|
$ cd app
|
|
18
25
|
$ bun install
|
|
19
26
|
```
|
|
20
27
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
Now you can start the dev server by running:
|
|
28
|
+
And start the dev server by running:
|
|
24
29
|
|
|
25
30
|
```bash
|
|
26
31
|
$ bun dev
|
|
27
|
-
|
|
32
|
+
🏗️ Constructing routes
|
|
33
|
+
|
|
34
|
+
hello.route.ts
|
|
35
|
+
[GET] /hello/:name Greeting endpoint
|
|
28
36
|
|
|
29
|
-
|
|
37
|
+
done
|
|
30
38
|
|
|
31
|
-
|
|
39
|
+
🚀 Server running at http://localhost:3000
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Let's try to reach the hello endpoint:
|
|
32
43
|
|
|
33
44
|
```bash
|
|
34
|
-
$ curl localhost:3000/hello
|
|
35
|
-
Hello
|
|
45
|
+
$ curl localhost:3000/hello/John?age=32
|
|
46
|
+
Hello John! You're 32 y.o.
|
|
36
47
|
```
|
|
37
48
|
|
|
38
49
|
> [!TIP]
|
|
39
|
-
>
|
|
50
|
+
> If you want to have a more complete view of Galbe capabilities, feel free to take a look at the `demo` template from the Galbe starter CLI.
|
|
40
51
|
|
|
41
52
|
## Manual installation
|
|
42
53
|
|
|
@@ -59,15 +70,15 @@ Open `package.json` file and add the following scripts:
|
|
|
59
70
|
}
|
|
60
71
|
```
|
|
61
72
|
|
|
62
|
-
As you can see, those scripts rely on Galbe CLI to run and build the application. You will find more info about
|
|
73
|
+
As you can see, those scripts rely on Galbe CLI to run and build the application. You will find more info about it on the [CLI](cli.md) page.
|
|
63
74
|
|
|
64
75
|
This require your `index.ts` to export a default Galbe instance in order to work. As in the following example:
|
|
65
76
|
|
|
66
77
|
```ts
|
|
67
78
|
import { Galbe } from 'galbe'
|
|
68
79
|
|
|
69
|
-
const
|
|
70
|
-
|
|
80
|
+
const galbe = new Galbe({ port: 3000 })
|
|
81
|
+
galbe.get('/hello', () => 'Hello Mom!')
|
|
71
82
|
|
|
72
83
|
export default galbe
|
|
73
84
|
```
|
|
@@ -77,40 +88,6 @@ This is the recommended way to proceed but it is not mandatory. Galbe instances
|
|
|
77
88
|
> [!WARNING]
|
|
78
89
|
> In the case you decide to not rely on Galbe CLI to run/build your app, you will not have access to [Automatic Route Analyzer](routes.md#automatic-route-analyzer) feature.
|
|
79
90
|
|
|
80
|
-
### Galbe CLI
|
|
81
|
-
|
|
82
|
-
```bash
|
|
83
|
-
$ galbe <command> <argument> [options]
|
|
84
|
-
```
|
|
85
|
-
|
|
86
|
-
Here are the available commands:
|
|
87
|
-
|
|
88
|
-
**dev**
|
|
89
|
-
|
|
90
|
-
Start a dev server running your Galbe application.
|
|
91
|
-
|
|
92
|
-
_argument_
|
|
93
|
-
|
|
94
|
-
The path of the file exporting your Galbe instance
|
|
95
|
-
|
|
96
|
-
_options_
|
|
97
|
-
|
|
98
|
-
- `--port` or `-p`: port number (default: 3000)
|
|
99
|
-
- `--watch` or `-w`: watch file changes (default: true)
|
|
100
|
-
|
|
101
|
-
**build**
|
|
102
|
-
|
|
103
|
-
Bundle your Galbe application.
|
|
104
|
-
|
|
105
|
-
_argument_
|
|
106
|
-
|
|
107
|
-
The path of the file exporting your Galbe instance
|
|
108
|
-
|
|
109
|
-
_options_
|
|
110
|
-
|
|
111
|
-
- `--out` or `-o`: output file | directory (default: app | dist )
|
|
112
|
-
- `--compile` or `-c`: create a standalone executable (default: false)
|
|
113
|
-
|
|
114
91
|
## Configuration
|
|
115
92
|
|
|
116
93
|
To configure your Galbe server, you should pass your configuration to the Galbe constructor when you instanciate it.
|
|
@@ -121,6 +98,10 @@ const galbe = new Galbe(configuration)
|
|
|
121
98
|
|
|
122
99
|
### Properties
|
|
123
100
|
|
|
101
|
+
**hostname**
|
|
102
|
+
|
|
103
|
+
The hostname of the server. Default is `localhost`.
|
|
104
|
+
|
|
124
105
|
**port**
|
|
125
106
|
|
|
126
107
|
The port number that the server will be listening on. Default is `3000`.
|
|
@@ -137,6 +118,16 @@ A Glob Pattern or a list of Glob patterns defining the route files to be analyze
|
|
|
137
118
|
|
|
138
119
|
A property that can be used by plugins to add plugin's specific configuration. Every key should correspond to a [Unique Plugin Identifier](plugins.md).
|
|
139
120
|
|
|
121
|
+
**tls**
|
|
122
|
+
|
|
123
|
+
Enable or disable TLS support. Default value is `false`.
|
|
124
|
+
|
|
125
|
+
- **tls.key**: The path to the private key file
|
|
126
|
+
|
|
127
|
+
- **tls.cert**: The path to the certificate file
|
|
128
|
+
|
|
129
|
+
- **tls.ca**: The path to the certificate authority file
|
|
130
|
+
|
|
140
131
|
**requestValidator.enabled**
|
|
141
132
|
|
|
142
133
|
Enable or disable the _request_ schema validation (See [Request Schema definition](schemas.md#request-schema-definition)). Default value is `true`.
|
|
@@ -229,3 +220,27 @@ You can find more info about Route Files definition in the [Routes Files](routes
|
|
|
229
220
|
|
|
230
221
|
> [!NOTE]
|
|
231
222
|
> The examples provided above will work with the default configuration, but you can easily customize the routes property to fit your own project structure. Simply redefine the `routes` property with your own pattern(s) to to fit your own project structure.
|
|
223
|
+
|
|
224
|
+
## How to debug
|
|
225
|
+
|
|
226
|
+
The easiest way to debug your app is by installing the [VSCode Bun extension](https://marketplace.visualstudio.com/items?itemName=oven.bun-vscode).
|
|
227
|
+
|
|
228
|
+
You can then create a `.vscode/launch.json` config file in your project root directory. Here is an example of configuration:
|
|
229
|
+
|
|
230
|
+
```json
|
|
231
|
+
{
|
|
232
|
+
"version": "0.2.0",
|
|
233
|
+
"configurations": [
|
|
234
|
+
{
|
|
235
|
+
"type": "bun",
|
|
236
|
+
"request": "launch",
|
|
237
|
+
"name": "Debug Galbe",
|
|
238
|
+
"program": "node_modules/galbe/bin/cli.ts",
|
|
239
|
+
"env": { "TERM": "xterm" },
|
|
240
|
+
"cwd": "${workspaceFolder}",
|
|
241
|
+
"runtime": "bun",
|
|
242
|
+
"runtimeArgs": ["dev", "index.ts", "--watch", "--force"]
|
|
243
|
+
}
|
|
244
|
+
]
|
|
245
|
+
}
|
|
246
|
+
```
|
package/docs/plugins.md
CHANGED
|
@@ -60,8 +60,9 @@ galbe.use(plugin)
|
|
|
60
60
|
|
|
61
61
|
Here is an example of a plugin implementation that handles routes tagged with `@deprecated` metadata (See [Route files](routes.md#route-files) section about metadata).
|
|
62
62
|
|
|
63
|
+
deprecated.plugin.ts
|
|
64
|
+
|
|
63
65
|
```ts
|
|
64
|
-
// myPlugin.ts
|
|
65
66
|
import type { GalbePlugin } from 'galbe'
|
|
66
67
|
import { walkMetaRoutes } from 'galbe/utils'
|
|
67
68
|
|
|
@@ -84,7 +85,6 @@ export default () => {
|
|
|
84
85
|
let r = context.route
|
|
85
86
|
if (!r) return
|
|
86
87
|
if (deprecateds.has(JSON.stringify({ method: r.method, path: r.path }))) {
|
|
87
|
-
context.state[PLUGIN_ID] = { deprecated: true }
|
|
88
88
|
console.warn(`Call to deprecated route "${r.method} ${r.path}"`)
|
|
89
89
|
}
|
|
90
90
|
},
|
|
@@ -92,9 +92,7 @@ export default () => {
|
|
|
92
92
|
afterHandle(response, context) {
|
|
93
93
|
let r = context.route
|
|
94
94
|
if (!r) return
|
|
95
|
-
console.log('yooo', r.method, r.path)
|
|
96
95
|
if (deprecateds.has(JSON.stringify({ method: r.method, path: r.path }))) {
|
|
97
|
-
console.log('OK...')
|
|
98
96
|
response.headers.set('x-deprecated', 'true')
|
|
99
97
|
}
|
|
100
98
|
}
|
|
@@ -102,17 +100,14 @@ export default () => {
|
|
|
102
100
|
}
|
|
103
101
|
```
|
|
104
102
|
|
|
105
|
-
|
|
106
|
-
// index.ts
|
|
103
|
+
index.ts
|
|
107
104
|
|
|
105
|
+
```ts
|
|
108
106
|
import { Galbe } from 'galbe'
|
|
109
|
-
import
|
|
110
|
-
import myPlugin from './myPlugin'
|
|
107
|
+
import deprecatedPlugin from './deprecated.plugin'
|
|
111
108
|
|
|
112
|
-
const galbe = new Galbe(
|
|
113
|
-
galbe.use(
|
|
109
|
+
const galbe = new Galbe()
|
|
110
|
+
galbe.use(deprecatedPlugin())
|
|
114
111
|
|
|
115
112
|
export default galbe
|
|
116
113
|
```
|
|
117
|
-
|
|
118
|
-
As you can see in this example, the [Context](context.md#definition) `state` property is used to persist information between plugins interceptor methods. It is a good practice to scope any information stored in the state with the plugin name, as it can also be used by other plugins and hooks to store data in the context.
|
package/docs/routes.md
CHANGED
|
@@ -82,7 +82,7 @@ galbe.get(
|
|
|
82
82
|
> [!NOTE]
|
|
83
83
|
> This feature is only available if you run/build the app via the [Galbe CLI](getting-started.md#galbe-cli), which is the case by default if you created your app following the [Automatic Installation](getting-started.md#automatic-installation) step or if you configured your package.json to do so.
|
|
84
84
|
|
|
85
|
-
The Automatic Route Analyzer is responsible for analyzing all the Route Files of your project and setting up the route definitions for your Galbe server automatically. By default, the analyzer will search for Route Files matching paths like `src/**/*.route.{js,ts}`. This can be configured by modifying the value of `routes` property of your Galbe configuration. A value of `false` will disable the analyzer.
|
|
85
|
+
The Automatic Route Analyzer is responsible for analyzing all the Route Files of your project and setting up the route definitions for your Galbe server automatically. By default, the analyzer will search for Route Files matching paths like `src/**/*.route.{js,ts}`. This can be configured by modifying the value of `routes` property of your Galbe configuration. A value of `false` will disable the route analyzer.
|
|
86
86
|
|
|
87
87
|
### Route Files
|
|
88
88
|
|
|
@@ -94,15 +94,6 @@ export default g => {
|
|
|
94
94
|
}
|
|
95
95
|
```
|
|
96
96
|
|
|
97
|
-
The same example in Typescript:
|
|
98
|
-
|
|
99
|
-
```ts
|
|
100
|
-
import type { Galbe } from 'galbe'
|
|
101
|
-
export default (g: Galbe) => {
|
|
102
|
-
g.get('/foo/:bar', ctx => ctx.params.bar)
|
|
103
|
-
}
|
|
104
|
-
```
|
|
105
|
-
|
|
106
97
|
The Automatic Route Analyzer can also collect metadata about your Route File and your routes by analyzing multiline comments. This can be used by some plugins to perform specific tasks. Here's an example of a Route File with multiline comment metadata:
|
|
107
98
|
|
|
108
99
|
```js
|
|
@@ -120,5 +111,3 @@ export default g => {
|
|
|
120
111
|
g.get('/foo/:bar', ctx => ctx.params.bar)
|
|
121
112
|
}
|
|
122
113
|
```
|
|
123
|
-
|
|
124
|
-
You will find more information about comment metadata and how to use them along with examples in the [Plugin](plugins.md) section.
|
package/package.json
CHANGED
|
@@ -165,7 +165,10 @@ export const OpenAPISerializer = async (g: Galbe, version = '3.0.3'): Promise<Op
|
|
|
165
165
|
let meta = metaRoutes?.[r.path]?.[r.method]
|
|
166
166
|
let path = r.path.replaceAll(/:([^\/]+)/g, '{$1}')
|
|
167
167
|
if (!(path in paths)) paths[path] = {}
|
|
168
|
-
let tags = [
|
|
168
|
+
let tags = [
|
|
169
|
+
...(meta?.tags?.split(' ')?.map((t: string) => t.trim()) || []),
|
|
170
|
+
...(typeof meta?.tag === 'string' ? [meta?.tag] : meta?.tag || [])
|
|
171
|
+
]
|
|
169
172
|
let security: Record<string, any> = []
|
|
170
173
|
|
|
171
174
|
let pathParam = r.schema?.params
|
package/src/index.ts
CHANGED
|
@@ -122,7 +122,9 @@ export class Galbe {
|
|
|
122
122
|
config: GalbeConfig
|
|
123
123
|
meta?: Array<RouteFileMeta> = []
|
|
124
124
|
router: GalbeRouter
|
|
125
|
-
|
|
125
|
+
startCb: (() => void)[] = []
|
|
126
|
+
stopCb: (() => void)[] = []
|
|
127
|
+
errorCb: ErrorHandler[] = []
|
|
126
128
|
listening: boolean = false
|
|
127
129
|
server?: Server
|
|
128
130
|
plugins: GalbePlugin[] = []
|
|
@@ -148,24 +150,34 @@ export class Galbe {
|
|
|
148
150
|
if (p.init) await p.init(this.config?.plugin?.[p.name] || {}, this)
|
|
149
151
|
}
|
|
150
152
|
}
|
|
151
|
-
async listen(port?: number) {
|
|
153
|
+
async listen(port?: number, hostname?: string) {
|
|
152
154
|
port = port || this.config?.port || 3000
|
|
155
|
+
hostname = hostname || this.config?.hostname || 'localhost'
|
|
153
156
|
this.config.port = port
|
|
157
|
+
this.config.hostname = hostname
|
|
154
158
|
if (this.listening) this.stop()
|
|
155
159
|
await this.init()
|
|
156
|
-
this.server = await server(this, port)
|
|
160
|
+
this.server = await server(this, port, hostname)
|
|
157
161
|
if (Bun.env.BUN_ENV === 'development') {
|
|
158
|
-
const url = `http
|
|
159
|
-
console.log(`\x1b[
|
|
162
|
+
const url = `http${this.config.tls ? 's' : ''}://${hostname}:${port}${this.config?.basePath || ''}`
|
|
163
|
+
console.log(`\x1b[1m🚀 Server running at\x1b[0m \x1b[4;34m${url}\x1b[0m\n`)
|
|
160
164
|
}
|
|
161
165
|
this.listening = true
|
|
166
|
+
for (let sh of this.startCb) sh()
|
|
162
167
|
return this.server
|
|
163
168
|
}
|
|
164
169
|
stop() {
|
|
165
170
|
this.server?.stop(true)
|
|
171
|
+
for (let sh of this.stopCb) sh()
|
|
172
|
+
}
|
|
173
|
+
onStart(callback: () => void) {
|
|
174
|
+
this.startCb.push(callback)
|
|
175
|
+
}
|
|
176
|
+
onStop(callback: () => void) {
|
|
177
|
+
this.stopCb.push(callback)
|
|
166
178
|
}
|
|
167
179
|
onError(handler: ErrorHandler) {
|
|
168
|
-
this.
|
|
180
|
+
this.errorCb.push(handler)
|
|
169
181
|
}
|
|
170
182
|
get: Endpoint<'get'> = <
|
|
171
183
|
Path extends string,
|
|
@@ -203,7 +215,6 @@ export class Galbe {
|
|
|
203
215
|
| Hook<'post', Path, RequestSchema<'post', Path, H, P, Q, B, R>>[]
|
|
204
216
|
| Handler<'post', Path, RequestSchema<'post', Path, H, P, Q, B, R>>,
|
|
205
217
|
arg4?: Handler<'post', Path, RequestSchema<'post', Path, H, P, Q, B, R>>
|
|
206
|
-
//@ts-ignore
|
|
207
218
|
) => this.add(overloadDiscriminer(this, 'post', path, arg2, arg3, arg4))
|
|
208
219
|
put: Endpoint<'put'> = <
|
|
209
220
|
Path extends string,
|
package/src/server.ts
CHANGED
|
@@ -4,6 +4,9 @@ import { InternalError, RequestError } from './types'
|
|
|
4
4
|
import { parseEntry, requestBodyParser, requestPathParser, responseParser } from './parser'
|
|
5
5
|
import { Galbe } from './index'
|
|
6
6
|
import { validateResponse } from './validator'
|
|
7
|
+
import { logger } from 'girok'
|
|
8
|
+
|
|
9
|
+
type MakeOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>
|
|
7
10
|
|
|
8
11
|
const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD']
|
|
9
12
|
const EMPTY_BODY_METHODS = ['GET', 'OPTIONS', 'HEAD']
|
|
@@ -20,7 +23,7 @@ const setupPluginCallbacks = (galbe: Galbe) => ({
|
|
|
20
23
|
afterHandle: galbe.plugins.filter(p => p.afterHandle)
|
|
21
24
|
})
|
|
22
25
|
|
|
23
|
-
export default async (galbe: Galbe, port?: number) => {
|
|
26
|
+
export default async (galbe: Galbe, port?: number, hostname?: string) => {
|
|
24
27
|
const router = galbe.router
|
|
25
28
|
if (galbe?.config?.basePath && galbe?.config?.basePath[0] !== '/')
|
|
26
29
|
galbe.config.basePath = `/${galbe?.config?.basePath}`
|
|
@@ -28,17 +31,16 @@ export default async (galbe: Galbe, port?: number) => {
|
|
|
28
31
|
|
|
29
32
|
return Bun.serve({
|
|
30
33
|
port: port || galbe.config?.port || 3000,
|
|
34
|
+
hostname: hostname || galbe.config?.hostname || 'localhost',
|
|
35
|
+
tls: galbe.config?.tls,
|
|
36
|
+
|
|
31
37
|
async fetch(req) {
|
|
32
38
|
if (!METHODS.includes(req.method)) return new Response('', { status: 501 })
|
|
33
|
-
const context
|
|
39
|
+
const context = {
|
|
34
40
|
request: req,
|
|
35
41
|
set: { headers: {} },
|
|
36
|
-
headers: {},
|
|
37
|
-
params: {},
|
|
38
|
-
query: {},
|
|
39
|
-
body: {},
|
|
40
42
|
state: {}
|
|
41
|
-
}
|
|
43
|
+
} as MakeOptional<Context, 'headers' | 'params' | 'query' | 'body'>
|
|
42
44
|
for (const p of pluginsCb.onFetch) {
|
|
43
45
|
//@ts-ignore
|
|
44
46
|
const r = await p.onFetch(context)
|
|
@@ -130,23 +132,23 @@ export default async (galbe: Galbe, port?: number) => {
|
|
|
130
132
|
await callChain[idx + 1].call()
|
|
131
133
|
}
|
|
132
134
|
}
|
|
133
|
-
let r = await hook(context, next)
|
|
135
|
+
let r = await hook(context as Context, next)
|
|
134
136
|
if (r) return r
|
|
135
137
|
if (!nextCalled && !handlerCalled) await next()
|
|
136
138
|
}
|
|
137
139
|
}))
|
|
138
140
|
callChain.push({
|
|
139
141
|
call: async () => {
|
|
140
|
-
response = await handlerWrapper(context)
|
|
142
|
+
response = await handlerWrapper(context as Context)
|
|
141
143
|
context.set.status = response instanceof Response ? response.status : 200
|
|
142
144
|
}
|
|
143
145
|
})
|
|
144
146
|
if (callChain.length > 1) {
|
|
145
147
|
let r = await callChain[0].call()
|
|
146
148
|
if (r) response = r
|
|
147
|
-
} else response = await handlerWrapper(context)
|
|
149
|
+
} else response = await handlerWrapper(context as Context)
|
|
148
150
|
|
|
149
|
-
const parsedResponse = responseParser(response, context, schema.response)
|
|
151
|
+
const parsedResponse = responseParser(response, context as Context, schema.response)
|
|
150
152
|
|
|
151
153
|
if (galbe.config?.responseValidator?.enabled && schema.response)
|
|
152
154
|
validateResponse(response, schema.response, parsedResponse.status || 200)
|
|
@@ -161,7 +163,7 @@ export default async (galbe: Galbe, port?: number) => {
|
|
|
161
163
|
} catch (error) {
|
|
162
164
|
context.set.status = error instanceof RequestError ? error.status : 500
|
|
163
165
|
let customError
|
|
164
|
-
|
|
166
|
+
for (let eh of galbe.errorCb) customError = responseParser(eh(error, context as Context), context as Context)
|
|
165
167
|
if (customError) return customError
|
|
166
168
|
if (error instanceof InternalError) {
|
|
167
169
|
console.log(`Internal Error`, error?.payload || '')
|
package/src/types.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ServeOptions, TLSServeOptions } from 'bun'
|
|
1
|
+
import type { ServeOptions, TLSOptions, TLSServeOptions } from 'bun'
|
|
2
2
|
import type {
|
|
3
3
|
STAny,
|
|
4
4
|
STArray,
|
|
@@ -96,7 +96,9 @@ export type STQuery = Record<string, STQueryValue>
|
|
|
96
96
|
*/
|
|
97
97
|
export type GalbeConfig = {
|
|
98
98
|
port?: number
|
|
99
|
+
hostname?: string
|
|
99
100
|
basePath?: string
|
|
101
|
+
tls?: TLSOptions
|
|
100
102
|
server?: Exclude<ServeOptions, 'port'> | TLSServeOptions
|
|
101
103
|
routes?: boolean | string | string[]
|
|
102
104
|
router?: { cacheEnabled: boolean }
|
|
@@ -306,8 +308,8 @@ export class InternalError extends RequestError {
|
|
|
306
308
|
export type GalbePlugin = {
|
|
307
309
|
name: string
|
|
308
310
|
init?: (config: any, galbe: Galbe) => MaybePromise<void>
|
|
309
|
-
onFetch?: (context: Context) => MaybePromise<Response | void>
|
|
310
|
-
onRoute?: (context: Context) => MaybePromise<Response | void>
|
|
311
|
+
onFetch?: (context: Pick<Context, 'request' | 'set' | 'state'>) => MaybePromise<Response | void>
|
|
312
|
+
onRoute?: (context: Pick<Context, 'request' | 'set' | 'state' | 'route'>) => MaybePromise<Response | void>
|
|
311
313
|
beforeHandle?: (context: Context) => MaybePromise<Response | void>
|
|
312
314
|
afterHandle?: (response: Response, context: Context) => MaybePromise<Response | void>
|
|
313
315
|
cli?: (commands: GalbeCLICommand[]) => MaybePromise<GalbeCLICommand[] | void>
|
package/src/util.ts
CHANGED
|
@@ -10,6 +10,7 @@ const METHOD_COLOR: Record<string, string> = {
|
|
|
10
10
|
options: '',
|
|
11
11
|
head: ''
|
|
12
12
|
}
|
|
13
|
+
const ansiRegex = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g
|
|
13
14
|
|
|
14
15
|
export const logRoute = (
|
|
15
16
|
r: { method: string; path: string },
|
|
@@ -17,11 +18,11 @@ export const logRoute = (
|
|
|
17
18
|
format?: { maxPathLength?: number }
|
|
18
19
|
) => {
|
|
19
20
|
let color = METHOD_COLOR?.[r.method] || ''
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
)
|
|
21
|
+
let routeLog = `[${color}${`${r.method.toUpperCase()}\x1b[0m]`.padEnd(12, ' ')} ${r.path
|
|
22
|
+
.padEnd(format?.maxPathLength ?? r.path.length, ' ')
|
|
23
|
+
.replaceAll(/:([^\/]+)/g, '\x1b[0;33m:$1\x1b[0m')}${meta?.head ? ` ${meta.head}` : ''}\x1b[0m`
|
|
24
|
+
if (meta?.deprecated) routeLog = `\x1b[0;9m\x1b[38;5;244m${routeLog.replaceAll(ansiRegex, '')}\x1b[0m`
|
|
25
|
+
console.log(` ${routeLog}`)
|
|
25
26
|
}
|
|
26
27
|
|
|
27
28
|
/**
|