@interknot/pom-pom 0.1.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/LICENSE ADDED
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,149 @@
1
+ <div align="center">
2
+ <img src="docs/pom-pom.webp" alt="PomPom Logo" width="150" />
3
+ <h1>PomPom</h1>
4
+ <p>Express-like wrapper around <code>Bun.serve</code></p>
5
+ <sub>Our little Express' Conductor</sub>
6
+ </div>
7
+
8
+ ## Disclaimer
9
+ This project will not work in Node.js, it's built specifically for Bun. If you want an Express-like framework for Node.js, consider using Express itself or Fastify.
10
+
11
+ ## Installation
12
+ ```sh
13
+ bun install @interknot/pom-pom
14
+ ```
15
+
16
+ ## Usage
17
+ Use it exactly as you would use Express.js.
18
+ ```ts
19
+ import { PomPom, PomResponse } from "@interknot/pom-pom"
20
+
21
+ const app = new PomPom()
22
+
23
+ app.get("/hello", (req, res) => {
24
+ return res.text("Hello, world!")
25
+ })
26
+
27
+ app.listen(3000, () => {
28
+ console.log("Server is running on http://localhost:3000")
29
+ })
30
+ ```
31
+
32
+ ## Middlewares
33
+ Supported middlewares: `cors`
34
+ ```ts
35
+ import { cors } from "@interknot/pom-pom/middlewares"
36
+
37
+ app.use(cors({
38
+ origin: "https://example.com"
39
+ }))
40
+ ```
41
+
42
+ ## Router
43
+ PomPom includes a file-system based router that follows Next.js style routing.
44
+ ```ts
45
+ import { PomPom, registerRoutes } from "@interknot/pom-pom"
46
+
47
+ const app = new PomPom()
48
+
49
+ registerRoutes(app, "./routes")
50
+ ```
51
+ ### Example directory structure
52
+ ```
53
+ /routes
54
+ /api
55
+ /users
56
+ [id].ts --> /api/users/:id
57
+ index.ts --> /api/users
58
+ index.ts --> /api
59
+ /about.ts --> /about
60
+ index.ts --> /
61
+ ```
62
+
63
+ ### Example route handler file
64
+ Supported HTTP methods: `GET`, `POST`, `PUT`, `DELETE`, `PATCH`, `OPTIONS`
65
+ ```ts
66
+ // /routes/api/users/[id].ts
67
+ import type { PomRequest, PomResponse } from "@interknot/pom-pom"
68
+
69
+ export async function get(req: PomRequest, res: PomResponse) {
70
+ const userId = req.params.id
71
+ return res.json({ id: userId, name: "User " + userId })
72
+ }
73
+
74
+ export async function post(req: PomRequest, res: PomResponse) {
75
+ const userData = await req.json()
76
+ // Process userData...
77
+ return res.json({ success: true, data: userData })
78
+ }
79
+
80
+ export async function put(req: PomRequest, res: PomResponse) {
81
+ const userData = await req.json()
82
+ // Update userData...
83
+ return res.json({ success: true, data: userData })
84
+ }
85
+
86
+ // Note: 'delete' is a reserved keyword in JavaScript/TypeScript,
87
+ // so we use '_delete' instead
88
+ export async function _delete(req: PomRequest, res: PomResponse) {
89
+ const userId = req.params.id
90
+ // Delete user...
91
+ return res.json({ success: true, id: userId })
92
+ }
93
+
94
+ export async function patch(req: PomRequest, res: PomResponse) {
95
+ const userData = await req.json()
96
+ // Partially update userData...
97
+ return res.json({ success: true, data: userData })
98
+ }
99
+ ```
100
+
101
+ ## Performance
102
+ PomPom is designed to be lightweight and fast. It adds minimal overhead
103
+ over `Bun.serve`, making it suitable for high-performance applications.
104
+
105
+ From my testing, the overhead it around 10-25%, depending on the complexity of the routes and middlewares used. Still faster than Express, though!
106
+
107
+ ### Benchmarks
108
+ I've used Bombardier for benchmarking, the command is the same everywhere.
109
+ ```sh
110
+ ❯ bombardier -n 1000000 -c 1000 "http://localhost:5100/"
111
+ ```
112
+ #### PomPom
113
+ ```sh
114
+ Statistics Avg Stdev Max
115
+ Reqs/sec 81866.28 4143.86 98144.69
116
+ Latency 12.21ms 2.40ms 160.95ms
117
+ HTTP codes:
118
+ 1xx - 0, 2xx - 1000000, 3xx - 0, 4xx - 0, 5xx - 0
119
+ others - 0
120
+ Throughput: 16.16MB/s
121
+ ```
122
+
123
+ #### Bun.serve
124
+ ```sh
125
+ Statistics Avg Stdev Max
126
+ Reqs/sec 94794.96 5274.28 108950.55
127
+ Latency 10.55ms 3.69ms 249.50ms
128
+ HTTP codes:
129
+ 1xx - 0, 2xx - 1000000, 3xx - 0, 4xx - 0, 5xx - 0
130
+ others - 0
131
+ Throughput: 19.97MB/s
132
+ ```
133
+
134
+ ## License
135
+ ```
136
+ Copyright 2026 Night Sky Studio (Konstantin Romanets)
137
+
138
+ Licensed under the Apache License, Version 2.0 (the "License");
139
+ you may not use this file except in compliance with the License.
140
+ You may obtain a copy of the License at
141
+
142
+ http://www.apache.org/licenses/LICENSE-2.0
143
+
144
+ Unless required by applicable law or agreed to in writing, software
145
+ distributed under the License is distributed on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
147
+ See the License for the specific language governing permissions and
148
+ limitations under the License.
149
+ ```
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@interknot/pom-pom",
3
+ "version": "0.1.0",
4
+ "description": "Express-like wrapper for Bun's HTTP server",
5
+ "author": "Night Sky Studio (Konstantin Romanets)",
6
+ "license": "Apache-2.0",
7
+ "homepage": "https://github.com/Night-Sky-Studio/pom-pom",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/Night-Sky-Studio/pom-pom.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/Night-Sky-Studio/pom-pom/issues"
14
+ },
15
+ "keywords": [
16
+ "bun",
17
+ "bun-serve",
18
+ "express",
19
+ "http",
20
+ "server",
21
+ "routing",
22
+ "middleware"
23
+ ],
24
+ "type": "module",
25
+ "main": "./src/index.ts",
26
+ "files": [
27
+ "src"
28
+ ],
29
+ "devDependencies": {
30
+ "@types/bun": "latest"
31
+ },
32
+ "peerDependencies": {
33
+ "typescript": "^5"
34
+ },
35
+ "engines": {
36
+ "bun": ">=1.3.8"
37
+ }
38
+ }
@@ -0,0 +1,168 @@
1
+ import Bun, { type MaybePromise, type BunRequest } from "bun"
2
+ import { PomRequest, type RouteParams } from "./Request"
3
+ import { PomOptions } from "./Options"
4
+ import { PomResponse } from "./Response"
5
+
6
+ export type MiddlewareFunction = (req: PomRequest<any>, res: PomResponse) => MaybePromise<Response | void>
7
+
8
+ /**
9
+ * Middleware modifies the current request
10
+ *
11
+ * It should either return a Response to short-circuit the request,
12
+ * or return nothing to continue processing
13
+ *
14
+ * On 2nd option, it can modify the request/response objects directly
15
+ */
16
+ export type Middleware = MiddlewareFunction | MaybePromise<void>
17
+
18
+ export type RouteHandler<R extends string> = (req: PomRequest<R>, res: PomResponse) => MaybePromise<PomResponse | void>
19
+
20
+ interface RouteHandlers<R extends string = string> {
21
+ GET?: RouteHandler<R>
22
+ POST?: RouteHandler<R>
23
+ PUT?: RouteHandler<R>
24
+ DELETE?: RouteHandler<R>
25
+ PATCH?: RouteHandler<R>
26
+ OPTIONS?: RouteHandler<R>
27
+ [key: string]: RouteHandler<R> | undefined
28
+ }
29
+
30
+ export class PomPom {
31
+ private middlewares: Middleware[] = []
32
+ private routes: Map<string, RouteHandlers<any>> = new Map()
33
+ public opts: PomOptions
34
+
35
+ constructor(opts?: PomOptions) {
36
+ this.opts = opts ?? new PomOptions()
37
+ }
38
+
39
+ public use(middleware: Middleware) {
40
+ this.middlewares.push(middleware)
41
+ }
42
+
43
+ public route<R extends string>(path: R, handlers: RouteHandlers<R>) {
44
+ // remove trailing slash except for root
45
+ const normalizedPath = path.endsWith('/') && path.length > 1
46
+ ? path.slice(0, -1)
47
+ : path
48
+
49
+ if (this.routes.has(normalizedPath)) {
50
+ const existingHandlers = this.routes.get(normalizedPath)!
51
+ this.routes.set(normalizedPath, { ...existingHandlers, ...handlers })
52
+ return this
53
+ }
54
+
55
+ this.routes.set(normalizedPath, handlers)
56
+ return this
57
+ }
58
+
59
+ public get<R extends string>(path: R, handler: RouteHandler<R>) {
60
+ return this.route<R>(path, { GET: handler })
61
+ }
62
+
63
+ public post<R extends string>(path: R, handler: RouteHandler<R>) {
64
+ return this.route<R>(path, { POST: handler })
65
+ }
66
+
67
+ public put<R extends string>(path: R, handler: RouteHandler<R>) {
68
+ return this.route<R>(path, { PUT: handler })
69
+ }
70
+
71
+ /** js syntax workaround */
72
+ private _delete<R extends string>(path: R, handler: RouteHandler<R>) {
73
+ return this.route<R>(path, { DELETE: handler })
74
+ }
75
+
76
+ public delete<R extends string>(path: R, handler: RouteHandler<R>) {
77
+ return this.route<R>(path, { DELETE: handler })
78
+ }
79
+
80
+ public patch<R extends string>(path: R, handler: RouteHandler<R>) {
81
+ return this.route<R>(path, { PATCH: handler })
82
+ }
83
+
84
+ public options<R extends string>(path: R, handler: RouteHandler<R>) {
85
+ return this.route<R>(path, { OPTIONS: handler })
86
+ }
87
+
88
+ private async execMiddleware(mw: Middleware, req: PomRequest<any>, res: PomResponse) {
89
+ return typeof mw === 'function' ? await mw(req, res) : await mw
90
+ }
91
+
92
+ private buildRoutes() {
93
+ const routes: Bun.Serve.Routes<never, any> = {}
94
+
95
+ for (const [path, handlers] of this.routes.entries()) {
96
+ // Pre-parse path structure to avoid parsing on every request
97
+ const pathSegments = path.split('/').filter(Boolean)
98
+ const paramDefs = pathSegments
99
+ .map((segment, index) => {
100
+ if (segment.startsWith(':')) return { index, key: segment.slice(1).replace('?', ''), isWildcard: false }
101
+ if (segment.startsWith('*')) return { index, key: segment.slice(1), isWildcard: true }
102
+ return null
103
+ })
104
+ .filter((def): def is NonNullable<typeof def> => def !== null)
105
+
106
+
107
+ routes[path] = async (request: BunRequest<any>) => {
108
+ try {
109
+ const pomRequest = new PomRequest(request, request.params)
110
+
111
+ const response = new PomResponse()
112
+
113
+ for (const middleware of this.middlewares) {
114
+ const mwResponse = await this.execMiddleware(middleware, pomRequest, response)
115
+ if (mwResponse) {
116
+ return mwResponse
117
+ }
118
+ }
119
+
120
+ const method = request.method.toUpperCase()
121
+ const handler = handlers[method]
122
+
123
+ if (handler) {
124
+ await handler(pomRequest, response)
125
+ return response.build()
126
+ }
127
+
128
+ return PomResponse.init({
129
+ status: 405,
130
+ body: "Method Not Allowed",
131
+ })
132
+ } catch (error) {
133
+ console.error("[SERVER]", error)
134
+ return PomResponse.init({
135
+ status: 500,
136
+ body: `Internal Server Error: ${(error as Error).message}`
137
+ })
138
+ }
139
+ }
140
+
141
+ console.log(`[SERVER] Built ${Object.keys(handlers).join(" ")} ${path}`)
142
+ }
143
+
144
+ return routes
145
+ }
146
+
147
+ public listen(port: number, callback?: () => void) {
148
+ const routes = this.buildRoutes()
149
+
150
+ const server = Bun.serve({
151
+ port,
152
+ routes,
153
+ fetch: () => PomResponse.init({
154
+ status: 404,
155
+ body: "Not Found",
156
+ }),
157
+ error: (error: Error) => {
158
+ console.error("[SERVER]", error)
159
+ return PomResponse.init({
160
+ status: 500,
161
+ body: `${error.message}`
162
+ })
163
+ }
164
+ })
165
+ callback?.()
166
+ return server
167
+ }
168
+ }
package/src/Options.ts ADDED
@@ -0,0 +1,8 @@
1
+ export class PomOptions {
2
+ defaultHeaders: Map<string, string>
3
+
4
+ constructor(options: Partial<PomOptions> = {}) {
5
+ this.defaultHeaders = options.defaultHeaders || new Map()
6
+ this.defaultHeaders.set('X-Powered-By', 'Pom-Pom')
7
+ }
8
+ }
package/src/Request.ts ADDED
@@ -0,0 +1,67 @@
1
+ import Bun, { type BunRequest } from "bun"
2
+
3
+ type ExtractSearchParams<S extends string> = S extends `${infer _}?${infer Q}` ? Q : ""
4
+ type SplitParams<Q extends string> = Q extends `${infer K}&${infer R}`
5
+ ? { [key in K | keyof SplitParams<R>]: string }
6
+ : Q extends `${infer K}`
7
+ ? { [key in K]: string } : {}
8
+ type ParseSearchParams<S extends string> = SplitParams<ExtractSearchParams<S>>
9
+
10
+ export type RouteParams<R extends string = string> = {
11
+ [Key in keyof Bun.Serve.ExtractRouteParams<R>]: Bun.Serve.ExtractRouteParams<R>[Key]
12
+ } & {}
13
+
14
+ export type QueryParams<S extends string = string> = {
15
+ [key in keyof ParseSearchParams<S>]: ParseSearchParams<S>[key]
16
+ } & {}
17
+
18
+ export class PomRequest<R extends string = string> {
19
+ raw: BunRequest
20
+ private _url: URL | undefined = undefined
21
+ params: RouteParams<R>
22
+
23
+ private _query: QueryParams<R> | null = null
24
+
25
+ get cookies(): Bun.CookieMap {
26
+ return this.raw.cookies
27
+ }
28
+
29
+ get query(): QueryParams<R> {
30
+ if (this._query) return this._query
31
+ const q: Record<string, string> = {}
32
+
33
+ this._url = this._url ?? new URL(this.raw.url)
34
+
35
+ const s = this._url.search.slice(1) // remove '?'
36
+ try {
37
+ let i = 0
38
+ while (i < s.length) {
39
+ // find '=' or '&'
40
+ let j = s.indexOf('=', i)
41
+ if (j === -1) break
42
+ const key = decodeURIComponent(s.slice(i, j))
43
+ let k = s.indexOf('&', j + 1)
44
+ if (k === -1) k = s.length
45
+ const val = decodeURIComponent(s.slice(j + 1, k))
46
+ q[key] = val
47
+ i = k + 1
48
+ }
49
+ } catch (e) {
50
+ throw new Error(`[server.PomRequest.query] Failed to parse: ${s}`)
51
+ }
52
+ return this._query = q as any
53
+ }
54
+
55
+ json<T>(): Promise<T> {
56
+ return this.raw.json() as Promise<T>
57
+ }
58
+
59
+ text(): Promise<string> {
60
+ return this.raw.text()
61
+ }
62
+
63
+ constructor(raw: BunRequest, params: RouteParams<R>) {
64
+ this.raw = raw
65
+ this.params = params
66
+ }
67
+ }
@@ -0,0 +1,62 @@
1
+ export interface IPomResponseInit {
2
+ status?: number
3
+ contentType?: string
4
+ headers?: Record<string, string>
5
+ body?: any
6
+ }
7
+
8
+ export class PomResponse {
9
+ code: number = 200
10
+ contentType: string = "text/plain"
11
+ body: any = null
12
+ headers: Record<string, string> = {}
13
+
14
+ static init({
15
+ status,
16
+ contentType = "text/plain",
17
+ headers,
18
+ body
19
+ }: IPomResponseInit = {}): Response {
20
+ const res = new PomResponse()
21
+ res.code = status ?? res.code
22
+ res.contentType = contentType ?? res.contentType
23
+ res.headers = headers ?? res.headers
24
+ res.body = body ?? res.body
25
+ return res.build()
26
+ }
27
+
28
+ json(data: any): PomResponse {
29
+ this.body = JSON.stringify(data)
30
+ this.contentType = "application/json"
31
+ return this
32
+ }
33
+
34
+ text(body: string): PomResponse {
35
+ this.body = body
36
+ this.contentType = "text/plain"
37
+ return this
38
+ }
39
+
40
+ status(code: number): PomResponse {
41
+ this.code = code
42
+ return this
43
+ }
44
+
45
+ header(key: string, value: string): PomResponse {
46
+ this.headers = {
47
+ ...this.headers,
48
+ [key]: value
49
+ }
50
+ return this
51
+ }
52
+
53
+ build(): Response {
54
+ return new Response(this.body, {
55
+ status: this.code,
56
+ headers: {
57
+ "Content-Type": this.contentType,
58
+ ...this.headers
59
+ }
60
+ })
61
+ }
62
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./Conductor"
2
+ export * from "./Request"
3
+ export * from "./Response"
@@ -0,0 +1,24 @@
1
+ import type { MiddlewareFunction, PomRequest, PomResponse } from ".."
2
+
3
+ interface CorsOptions {
4
+ origin?: string
5
+ methods?: string[]
6
+ headers?: string[]
7
+ }
8
+
9
+ export function cors({
10
+ origin = "*",
11
+ methods = ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
12
+ headers = ["Content-Type", "Authorization"]
13
+ }: CorsOptions = {}): MiddlewareFunction {
14
+ return (req: PomRequest<any>, res: PomResponse) => {
15
+ res.header('Access-Control-Allow-Origin', origin)
16
+ res.header('Access-Control-Allow-Methods', methods.join(', '))
17
+ res.header('Access-Control-Allow-Headers', headers.join(', '))
18
+ res.header("Access-Control-Allow-Credentials", `${res.headers["Access-Control-Allow-Origin"] !== "*"}`)
19
+
20
+ if (req.raw.method === "OPTIONS") {
21
+ return res.status(204).build()
22
+ }
23
+ }
24
+ }
@@ -0,0 +1 @@
1
+ export * from "./Cors"
package/src/router.ts ADDED
@@ -0,0 +1,68 @@
1
+ import assert from "node:assert"
2
+ import { readdir, exists, stat } from "node:fs/promises"
3
+ import path from "node:path"
4
+ import { type RouteHandler, PomPom } from "."
5
+
6
+ const Methods = ["get", "post", "put", "_delete", "patch"] as const
7
+
8
+ interface RouteModule<R extends string = string> {
9
+ get?: RouteHandler<R>
10
+ post?: RouteHandler<R>
11
+ put?: RouteHandler<R>
12
+ delete?: RouteHandler<R>
13
+ patch?: RouteHandler<R>
14
+ [key: string]: RouteHandler<R> | undefined
15
+ }
16
+
17
+ function toRouteSegment(fileName: string): string {
18
+ if (fileName === "index") return "/"
19
+ // Replace all [param] with :param
20
+ return "/" + fileName.replace(
21
+ /\[\#([a-zA-Z0-9_]+)\]|\[\*([a-zA-Z0-9_]+)\]|\[([a-zA-Z0-9_]+)\]/g,
22
+ (_match, opt, rest, normal) => {
23
+ if (opt) {
24
+ // Optional param [#name]
25
+ return `:${opt}?`
26
+ } else if (rest) {
27
+ // Catch-all [*rest]
28
+ return `*${rest}`
29
+ } else if (normal) {
30
+ // Required param [name]
31
+ return `:${normal}`
32
+ }
33
+ return _match
34
+ }
35
+ )
36
+ }
37
+
38
+ export async function registerRoutes(app: PomPom, routesDir: string = "routes", baseRoute = "") {
39
+ assert(await exists(routesDir), `Routes directory "${routesDir}" does not exist`)
40
+
41
+ const routesPath = path.resolve(routesDir)
42
+
43
+ const files = await readdir(routesPath)
44
+
45
+ for (const file of files) {
46
+ try {
47
+ const fullPath = path.join(routesPath, file)
48
+ const fileStat = await stat(fullPath)
49
+ if (fileStat.isDirectory()) {
50
+ // Apply toRouteSegment to directory name
51
+ await registerRoutes(app, fullPath, path.posix.join(baseRoute || '/', toRouteSegment(file)))
52
+ } else if (file.endsWith(".ts") || file.endsWith(".js")) {
53
+ const routePath = baseRoute + toRouteSegment(file.replace(/\.(ts|js)$/, ""))
54
+ const module: RouteModule = await import(fullPath)
55
+
56
+ for (const method of Methods) {
57
+ if (typeof module[method] === "function") {
58
+ const handler = module[method] as RouteHandler<any>
59
+ app[method](routePath, handler)
60
+ console.log(`[ROUTER] Registered ${method.toUpperCase()} ${routePath}`)
61
+ }
62
+ }
63
+ }
64
+ } catch (err) {
65
+ console.error(`[ROUTER] Error registering route ${baseRoute + toRouteSegment(file.replace(/\.(ts|js)$/, ""))}\n`, err)
66
+ }
67
+ }
68
+ }