hapta 1.0.2 → 1.0.4

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,201 @@
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
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,252 +1,252 @@
1
-
2
- # 🛠️ **Hapta**
3
-
4
- **Hapta** is a modular, scalable, and feature-rich backend framework designed to extend [Pocketbase](https://pocketbase.io) with authentication, schema validation, caching, and tenant-based service orchestration.
5
-
6
- > Designed to integrate easily into any modern Node.js backend — and purpose-built to unlock Pocketbase for production-scale deployments.
7
-
8
- ---
9
-
10
- ## 📦 Installation
11
-
12
- ```bash
13
- npm install hapta
14
- # or
15
- bun add hapta
16
- # or
17
- yarn add hapta
18
- ```
19
-
20
- ---
21
-
22
- ## 🚀 Key Features
23
-
24
- * ✅ **Authentication via Clover**
25
- Multi-strategy login (OAuth, password, OTP, MFA) with tenant role/clearance support.
26
-
27
- * 🔐 **Context-Based Auth (`ctx.principal`)**
28
- Automatically injects authenticated user state and metadata into each request.
29
-
30
- * 📦 **Zod-Based Schema Validation**
31
- Auto-validates route inputs with fully typed schema files.
32
-
33
- * ⚡ **Smart Caching Layer**
34
- Dynamic TTL, auto-invalidation, optimistic scaffolds, and memory-based caching.
35
-
36
- * 🧱 **Modular Context System**
37
- Unified `Context` class handles services, request metadata, auth, and responses.
38
-
39
- * 🏗️ **Batch Write Mode**
40
- Queue DB changes, defer execution, and optimize complex flows.
41
-
42
- ---
43
-
44
- ## 📁 Project Structure (Recommended)
45
-
46
- ```
47
- /
48
- └── routes/
49
- └── auth/
50
- └── index.ts # Example auth endpoint
51
- └── schemas/
52
- └── auth/
53
- └── index.ts # Zod validation for auth route
54
-
55
- ```
56
-
57
- ---
58
-
59
- ## 🧠 Quick Start
60
-
61
- ### 🧩 Set up config
62
- > hapta-config.json
63
- ```json
64
- {
65
- "port": 8080,
66
- "logLevel": "info",
67
- "origin":"http://localhost:8081",
68
- "AI_ENABLED": false,
69
- "Clover_Tenant_ID": "",
70
- "Clover_Secret":"",
71
- "Clover_Server_Url":"clover.postlyapp.com",
72
- "JWT_SECRET":"*",
73
- "DatabaseUrl":"http://localhost:8080",
74
- "ADMIN_EMAIL":"malikwhitterb@gmail.com",
75
- "ADMIN_PASSWORD":""
76
- }
77
-
78
- ```
79
-
80
- ### 🔐 Use the `principal`
81
-
82
- ```ts
83
- if (ctx.principal.isAuthenticated) {
84
- const username = ctx.principal.username;
85
- const clearance = ctx.principal.highest_clearance;
86
- }
87
- ```
88
-
89
- ---
90
-
91
- ## ⚙️ Usage Example
92
-
93
- ### `/routes/auth/index.ts`
94
-
95
- ```ts
96
- import Context from "hapta";
97
- import { Database } from "hapta";
98
-
99
- export default async function POST(ctx: Context, DB: Database) {
100
- const { type } = ctx.metadata.query as any;
101
-
102
- if (type === "oauth") {
103
- const result = await ctx.services.Clover.Authenticate({ type: "oauth", ...ctx.metadata.query });
104
-
105
- return result.isAuthenticated
106
- ? ctx.json(result)
107
- : ctx.json({ error: true, message: "OAuth failed" }, 401);
108
-
109
- } else if (type === "password") {
110
- const result = await ctx.services.Clover.Authenticate({
111
- type: "passwordAuth",
112
- ...ctx.metadata.json
113
- });
114
-
115
- return result.isAuthenticated
116
- ? ctx.json(result)
117
- : ctx.json({ error: true, message: "Invalid credentials" }, 400);
118
- }
119
-
120
- return ctx.json({ error: true, message: "Unsupported auth type" }, 400);
121
- }
122
- ```
123
-
124
- ## Then simply run
125
-
126
- ```bash
127
- bun --hot run hapta
128
- ```
129
-
130
- ---
131
-
132
- ## 🧬 Database API
133
-
134
- ```ts
135
- import { DatabaseService } from "hapta";
136
-
137
- const DB = new DatabaseService(pocketbase, cacheHandler);
138
- ```
139
-
140
- ### 🔹 Get one (cached)
141
-
142
- ```ts
143
- const record = await DB.get("users", "abc123");
144
- ```
145
-
146
- ### 🔹 List (cached + paginated)
147
-
148
- ```ts
149
- await DB.list("posts", { page: 1, limit: 20 });
150
- ```
151
-
152
- ### 🔹 Create with scaffold
153
-
154
- ```ts
155
- DB.setBatch(true);
156
- await DB.create("comments", { body: "Hello!" }, true);
157
- await DB.saveChanges();
158
- ```
159
-
160
- ---
161
-
162
- ## 🧰 Built-in Response Helpers
163
-
164
- ```ts
165
- ctx.json({ success: true }, 200);
166
- ctx.html("<h1>Welcome</h1>");
167
- ctx.text("Hello world");
168
- ```
169
-
170
- All responses include CORS headers out of the box:
171
-
172
- ```http
173
- Access-Control-Allow-Origin: *
174
- Access-Control-Allow-Headers: Content-Type, Authorization
175
- ```
176
-
177
- ---
178
-
179
- ## 🧪 Validation with Zod
180
-
181
- ```ts
182
- // /schemas/auth/index.ts
183
- import { z } from "zod";
184
-
185
- export default z.object({
186
- emailOrUsername: z.string().min(3),
187
- password: z.string().min(6),
188
- });
189
- ```
190
-
191
- Hapta automatically loads and validates this schema for `/auth` requests before your handler runs.
192
-
193
- ---
194
-
195
- ## 🔄 Batch Mode
196
-
197
- ```ts
198
- DB.setBatch(true);
199
- await DB.create("logs", { message: "Init" });
200
- await DB.update("users", "abc", { active: false });
201
- await DB.delete("sessions", "xyz");
202
- await DB.saveChanges(); // executes all queued ops
203
- ```
204
-
205
- ---
206
-
207
- ## 📦 Caching Details
208
-
209
- | Method | Caches | TTL | Invalidation |
210
- | ---------- | ------ | ------- | ------------------------------- |
211
- | `get()` | ✅ | dynamic | on `update`, `delete` |
212
- | `list()` | ✅ | dynamic | on `create`, `update`, `delete` |
213
- | `create()` | ➖ | ➖ | invalidates all list caches |
214
- | `update()` | ➖ | ➖ | invalidates list + get cache |
215
- | `delete()` | ➖ | ➖ | invalidates list + get cache |
216
-
217
- ---
218
-
219
- ## 🧱 Integrating with Express, Bun, or Custom Server
220
-
221
- You can wire Hapta into any server environment:
222
-
223
- ```ts
224
- const ctx = new Context();
225
- // inject principal, services, metadata, etc.
226
- ctx.metadata = {
227
- requestID: "xyz",
228
- timestamp: new Date(),
229
- json: await req.json(),
230
- headers: req.headers,
231
- ...
232
- };
233
-
234
- // call route handler
235
- const res = await handler(ctx, DB);
236
- return res;
237
- ```
238
-
239
- ---
240
-
241
- ## 🧾 License
242
-
243
- MIT © Postr-Inc — Built for scale.
244
-
245
- ---
246
-
247
- ## 💬 Questions?
248
-
249
- * Open an issue
250
- * PRs welcome
251
- * Built with ❤️ by the Postr-Inc team
252
-
1
+
2
+ # 🛠️ **Hapta**
3
+
4
+ **Hapta** is a modular, scalable, and feature-rich backend framework designed to extend [Pocketbase](https://pocketbase.io) with authentication, schema validation, caching, and tenant-based service orchestration.
5
+
6
+ > Designed to integrate easily into any modern Node.js backend — and purpose-built to unlock Pocketbase for production-scale deployments.
7
+
8
+ ---
9
+
10
+ ## 📦 Installation
11
+
12
+ ```bash
13
+ npm install hapta
14
+ # or
15
+ bun add hapta
16
+ # or
17
+ yarn add hapta
18
+ ```
19
+
20
+ ---
21
+
22
+ ## 🚀 Key Features
23
+
24
+ * ✅ **Authentication via Clover**
25
+ Multi-strategy login (OAuth, password, OTP, MFA) with tenant role/clearance support.
26
+
27
+ * 🔐 **Context-Based Auth (`ctx.principal`)**
28
+ Automatically injects authenticated user state and metadata into each request.
29
+
30
+ * 📦 **Zod-Based Schema Validation**
31
+ Auto-validates route inputs with fully typed schema files.
32
+
33
+ * ⚡ **Smart Caching Layer**
34
+ Dynamic TTL, auto-invalidation, optimistic scaffolds, and memory-based caching.
35
+
36
+ * 🧱 **Modular Context System**
37
+ Unified `Context` class handles services, request metadata, auth, and responses.
38
+
39
+ * 🏗️ **Batch Write Mode**
40
+ Queue DB changes, defer execution, and optimize complex flows.
41
+
42
+ ---
43
+
44
+ ## 📁 Project Structure (Recommended)
45
+
46
+ ```
47
+ /
48
+ └── routes/
49
+ └── auth/
50
+ └── index.ts # Example auth endpoint
51
+ └── schemas/
52
+ └── auth/
53
+ └── index.ts # Zod validation for auth route
54
+
55
+ ```
56
+
57
+ ---
58
+
59
+ ## 🧠 Quick Start
60
+
61
+ ### 🧩 Set up config
62
+ > hapta-config.json
63
+ ```json
64
+ {
65
+ "port": 8080,
66
+ "logLevel": "info",
67
+ "origin":"http://localhost:8081",
68
+ "AI_ENABLED": false,
69
+ "Clover_Tenant_ID": "",
70
+ "Clover_Secret":"",
71
+ "Clover_Server_Url":"clover.postlyapp.com",
72
+ "JWT_SECRET":"*",
73
+ "DatabaseUrl":"http://localhost:8080",
74
+ "ADMIN_EMAIL":"malikwhitterb@gmail.com",
75
+ "ADMIN_PASSWORD":""
76
+ }
77
+
78
+ ```
79
+
80
+ ### 🔐 Use the `principal`
81
+
82
+ ```ts
83
+ if (ctx.principal.isAuthenticated) {
84
+ const username = ctx.principal.username;
85
+ const clearance = ctx.principal.highest_clearance;
86
+ }
87
+ ```
88
+
89
+ ---
90
+
91
+ ## ⚙️ Usage Example
92
+
93
+ ### `/routes/auth/index.ts`
94
+
95
+ ```ts
96
+ import Context from "hapta";
97
+ import { Database } from "hapta";
98
+
99
+ export default async function POST(ctx: Context, DB: Database) {
100
+ const { type } = ctx.metadata.query as any;
101
+
102
+ if (type === "oauth") {
103
+ const result = await ctx.services.Clover.Authenticate({ type: "oauth", ...ctx.metadata.query });
104
+
105
+ return result.isAuthenticated
106
+ ? ctx.json(result)
107
+ : ctx.json({ error: true, message: "OAuth failed" }, 401);
108
+
109
+ } else if (type === "password") {
110
+ const result = await ctx.services.Clover.Authenticate({
111
+ type: "passwordAuth",
112
+ ...ctx.metadata.json
113
+ });
114
+
115
+ return result.isAuthenticated
116
+ ? ctx.json(result)
117
+ : ctx.json({ error: true, message: "Invalid credentials" }, 400);
118
+ }
119
+
120
+ return ctx.json({ error: true, message: "Unsupported auth type" }, 400);
121
+ }
122
+ ```
123
+
124
+ ## Then simply run
125
+
126
+ ```bash
127
+ bun --hot run hapta
128
+ ```
129
+
130
+ ---
131
+
132
+ ## 🧬 Database API
133
+
134
+ ```ts
135
+ import { DatabaseService } from "hapta";
136
+
137
+ const DB = new DatabaseService(pocketbase, cacheHandler);
138
+ ```
139
+
140
+ ### 🔹 Get one (cached)
141
+
142
+ ```ts
143
+ const record = await DB.get("users", "abc123");
144
+ ```
145
+
146
+ ### 🔹 List (cached + paginated)
147
+
148
+ ```ts
149
+ await DB.list("posts", { page: 1, limit: 20 });
150
+ ```
151
+
152
+ ### 🔹 Create with scaffold
153
+
154
+ ```ts
155
+ DB.setBatch(true);
156
+ await DB.create("comments", { body: "Hello!" }, true);
157
+ await DB.saveChanges();
158
+ ```
159
+
160
+ ---
161
+
162
+ ## 🧰 Built-in Response Helpers
163
+
164
+ ```ts
165
+ ctx.json({ success: true }, 200);
166
+ ctx.html("<h1>Welcome</h1>");
167
+ ctx.text("Hello world");
168
+ ```
169
+
170
+ All responses include CORS headers out of the box:
171
+
172
+ ```http
173
+ Access-Control-Allow-Origin: *
174
+ Access-Control-Allow-Headers: Content-Type, Authorization
175
+ ```
176
+
177
+ ---
178
+
179
+ ## 🧪 Validation with Zod
180
+
181
+ ```ts
182
+ // /schemas/auth/index.ts
183
+ import { z } from "zod";
184
+
185
+ export default z.object({
186
+ emailOrUsername: z.string().min(3),
187
+ password: z.string().min(6),
188
+ });
189
+ ```
190
+
191
+ Hapta automatically loads and validates this schema for `/auth` requests before your handler runs.
192
+
193
+ ---
194
+
195
+ ## 🔄 Batch Mode
196
+
197
+ ```ts
198
+ DB.setBatch(true);
199
+ await DB.create("logs", { message: "Init" });
200
+ await DB.update("users", "abc", { active: false });
201
+ await DB.delete("sessions", "xyz");
202
+ await DB.saveChanges(); // executes all queued ops
203
+ ```
204
+
205
+ ---
206
+
207
+ ## 📦 Caching Details
208
+
209
+ | Method | Caches | TTL | Invalidation |
210
+ | ---------- | ------ | ------- | ------------------------------- |
211
+ | `get()` | ✅ | dynamic | on `update`, `delete` |
212
+ | `list()` | ✅ | dynamic | on `create`, `update`, `delete` |
213
+ | `create()` | ➖ | ➖ | invalidates all list caches |
214
+ | `update()` | ➖ | ➖ | invalidates list + get cache |
215
+ | `delete()` | ➖ | ➖ | invalidates list + get cache |
216
+
217
+ ---
218
+
219
+ ## 🧱 Integrating with Express, Bun, or Custom Server
220
+
221
+ You can wire Hapta into any server environment:
222
+
223
+ ```ts
224
+ const ctx = new Context();
225
+ // inject principal, services, metadata, etc.
226
+ ctx.metadata = {
227
+ requestID: "xyz",
228
+ timestamp: new Date(),
229
+ json: await req.json(),
230
+ headers: req.headers,
231
+ ...
232
+ };
233
+
234
+ // call route handler
235
+ const res = await handler(ctx, DB);
236
+ return res;
237
+ ```
238
+
239
+ ---
240
+
241
+ ## 🧾 License
242
+
243
+ MIT © Postr-Inc — Built for scale.
244
+
245
+ ---
246
+
247
+ ## 💬 Questions?
248
+
249
+ * Open an issue
250
+ * PRs welcome
251
+ * Built with ❤️ by the Postr-Inc team
252
+
@@ -1,5 +1,5 @@
1
1
  import { config } from "../../../src/core/config";
2
- export const corsHeaders = {
2
+ const corsHeaders = {
3
3
  "Access-Control-Allow-Origin": config.origin,
4
4
  "Access-Control-Allow-Methods": "OPTIONS, GET, POST, PUT, PATCH, DELETE",
5
5
  "Access-Control-Allow-Headers": "Content-Type, Authorization",
@@ -80,7 +80,7 @@ type TokenOptions = {
80
80
  iat: number
81
81
  }
82
82
  type VerifyFn = (token: string) => Promise<Principal>;
83
- type TempTokenFn = (amount_of_uses: number, expiresAt: '1h' | '1d' | '1y'|'') => Promise<string | null>
83
+
84
84
  export type ServiceConfigs = {
85
85
  Clover: {
86
86
  Tenant_ID: string;
@@ -88,8 +88,7 @@ export type ServiceConfigs = {
88
88
  Authorized_Users: string[];
89
89
  Authenticate: AuthenticateFn;
90
90
  Register: RegisterFn;
91
- Verify?: VerifyFn;
92
- createTemporaryToken: TempTokenFn // just verify token
91
+ Verify?: VerifyFn; // just verify token
93
92
  };
94
93
  };
95
94
 
@@ -207,4 +206,4 @@ export default class Context implements IContext {
207
206
  }
208
207
  });
209
208
  }
210
- }
209
+ }
package/index.ts CHANGED
@@ -25,8 +25,8 @@ const router = new FileSystemRouter({
25
25
 
26
26
  // --- Validation: Ensure required config vars are present ---
27
27
  if (!config.Clover_Secret || !config.Clover_Tenant_ID) {
28
- console.error(" Clover_Secret and Clover_Tenant_ID must be set in your config.");
29
- process.exit(1);
28
+ console.error("Using Basic Auth");
29
+
30
30
  }
31
31
 
32
32
  if (!config.ADMIN_EMAIL || !config.ADMIN_PASSWORD) {
@@ -34,7 +34,7 @@ if (!config.ADMIN_EMAIL || !config.ADMIN_PASSWORD) {
34
34
  process.exit(1);
35
35
  }
36
36
 
37
- if(!fs.existsSync(path.join(process.cwd(), "routes"))){
37
+ if (!fs.existsSync(path.join(process.cwd(), "routes"))) {
38
38
  console.error("❌ Please create a routes folder and create your first route");
39
39
  process.exit(1);
40
40
  }
@@ -46,16 +46,19 @@ try {
46
46
  } catch (_) { }
47
47
 
48
48
  // --- Primary Tenant Data ---
49
- const primaryTenantData = await fetch(`${config.Clover_Server_Url}/tenants/${config.Clover_Tenant_ID}`, {
49
+ var primaryTenantData: any = {};
50
+ if(config.Clover_Tenant_ID){
51
+ primaryTenantData = await fetch(`${config.Clover_Server_Url}/tenants/${config.Clover_Tenant_ID}`, {
50
52
  headers: { Authorization_Secret: config.Clover_Secret },
51
53
  }).then(async (res) => {
52
54
  if (!res.ok) throw new Error(`Failed to fetch primary tenant data: ${res.status} ${res.statusText}`);
53
55
  return res.json();
54
56
  });
57
+ }
55
58
  console.log("✅ Primary tenant data loaded.");
56
59
 
57
60
  const cache = new Cache();
58
- const db = new DatabaseService(pb, cache);
61
+ const db = new DatabaseService(pb, cache);
59
62
  // --- Server Configuration Builder ---
60
63
  async function createServeConfig(): Promise<Serve> {
61
64
  console.log("🛠️ Building server configuration...");
@@ -67,7 +70,7 @@ async function createServeConfig(): Promise<Serve> {
67
70
  const schemas = new Map();
68
71
  const middlewares = new Map<string, (ctx: Context) => Promise<Response | boolean>>();
69
72
 
70
- const reimportModule = async (modulePath: string) => {
73
+ const reimportModule = async (modulePath: string) => {
71
74
  const resolvedPath = path.resolve(modulePath);
72
75
  if (require.cache[resolvedPath]) {
73
76
  delete require.cache[resolvedPath];
@@ -94,7 +97,7 @@ async function createServeConfig(): Promise<Serve> {
94
97
  const middleware = await reimportModule(middlewarePath);
95
98
  if (middleware.default) middlewares.set(pathname, middleware.default);
96
99
  }
97
- } catch (e) {
100
+ } catch (e) {
98
101
  console.error(`❌ Error loading module for route ${pathname}:`, e);
99
102
  }
100
103
  }
@@ -105,7 +108,7 @@ async function createServeConfig(): Promise<Serve> {
105
108
  port: config.port,
106
109
  async fetch(req: Request) {
107
110
  console.log(req.method)
108
- if (req.method === "OPTIONS") {
111
+ if (req.method === "OPTIONS") {
109
112
  console.log("ran")
110
113
  return new Response(null, {
111
114
  status: 200,
@@ -130,7 +133,7 @@ async function createServeConfig(): Promise<Serve> {
130
133
  const schema = schemas.get(routeMatch.name);
131
134
 
132
135
  if (!routeHandler) {
133
- return new Response(`Route handler for ${routeMatch.name} not found.`, { status: 404, headers:{...corsHeaders} });
136
+ return new Response(`Route handler for ${routeMatch.name} not found.`, { status: 404, headers: { ...corsHeaders } });
134
137
  }
135
138
 
136
139
  try {
@@ -147,7 +150,6 @@ async function createServeConfig(): Promise<Serve> {
147
150
  if (result instanceof Response) return result;
148
151
  if (result === false) return new Response("Forbidden", { status: 403 });
149
152
  }
150
-
151
153
  if (schema) {
152
154
  const validation = {
153
155
  body: schema.body?.safeParse(context.metadata.json),
@@ -156,7 +158,7 @@ async function createServeConfig(): Promise<Serve> {
156
158
  };
157
159
  for (const key of ["body", "query", "headers"] as const) {
158
160
  if (validation[key] && !validation[key]?.success) {
159
- return new Response(JSON.stringify({ success: false, error: validation[key]?.error.flatten() }), { status: 400, headers: { "Content-Type": "application/json" , ...corsHeaders} });
161
+ return new Response(JSON.stringify({ success: false, error: validation[key]?.error.flatten() }), { status: 400, headers: { "Content-Type": "application/json", ...corsHeaders } });
160
162
  }
161
163
  }
162
164
  }
@@ -166,12 +168,12 @@ async function createServeConfig(): Promise<Serve> {
166
168
  return await routeHandler(context, db);
167
169
  } catch (err) {
168
170
  console.error(`❌ Error handling ${url.pathname}:`, err);
169
- return new Response("Internal Server Error", { status: 500, headers:{...corsHeaders} });
171
+ return new Response("Internal Server Error", { status: 500, headers: { ...corsHeaders } });
170
172
  }
171
173
  },
172
174
  error(error) {
173
175
  console.error("☠️ Uncaught Error:", error);
174
- return new Response("Something went wrong!", { status: 500, headers:{...corsHeaders} });
176
+ return new Response("Something went wrong!", { status: 500, headers: { ...corsHeaders } });
175
177
  },
176
178
  };
177
179
  }
@@ -220,20 +222,19 @@ async function buildRequestContext(req: Request, headers: Headers) {
220
222
  const reqJSON = await req.json().catch(() => ({}));
221
223
 
222
224
  const hasToken = headers.has("Authorization")
223
- var isAuthenticated = false;
225
+ var isAuthenticated = false;
224
226
  if (hasToken) {
225
-
227
+
226
228
  try {
227
-
229
+
228
230
  isAuthenticated = true
229
231
  } catch (error) {
230
232
  isAuthenticated = false
231
233
  }
232
234
  }
233
- const context = {
235
+ const context = {
234
236
  principal: { isAuthenticated: isAuthenticated as boolean },
235
- services: {
236
- Clover: {
237
+ services: {
237
238
  Tenant_ID: primaryTenantData.id,
238
239
  Authorized_Users: primaryTenantData.expand?.Tenant_Groups?.Users || [],
239
240
  Register: async (data: any) => {
@@ -257,77 +258,100 @@ async function buildRequestContext(req: Request, headers: Headers) {
257
258
  return await res.json()
258
259
 
259
260
  },
260
- Authenticate: async (options) => {
261
- const fetchBody = {
262
- Tenant_Id: primaryTenantData.id,
263
- Secret: config.Clover_Secret,
264
- type: options.type,
265
- };
261
+ Authenticate: async (options: any) => {
262
+ if (config.Clover_Tenant_ID) {
263
+ const fetchBody = {
264
+ Tenant_Id: primaryTenantData.id,
265
+ Secret: config.Clover_Secret,
266
+ type: options.type,
267
+ };
266
268
 
267
- if (options.type === "passwordAuth") {
268
- fetchBody.emailOrUsername = options.emailOrUsername;
269
- fetchBody.password = options.password;
270
- }
269
+ if (options.type === "passwordAuth") {
270
+ fetchBody.emailOrUsername = options.emailOrUsername;
271
+ fetchBody.password = options.password;
272
+ }
271
273
 
272
- if (options.type === "oauth") {
273
- fetchBody.code = options.code;
274
- fetchBody.redirectUri = options.redirectUri;
275
- fetchBody.client_secret = config.Clover_Secret
276
- fetchBody.authenticated_id = options.authenticated_id
277
- }
274
+ if (options.type === "oauth") {
275
+ fetchBody.code = options.code;
276
+ fetchBody.redirectUri = options.redirectUri;
277
+ fetchBody.client_secret = config.Clover_Secret
278
+ fetchBody.authenticated_id = options.authenticated_id
279
+ }
278
280
 
279
281
 
280
- const authRes = await fetch(`${config.Clover_Server_Url}/${options.type === "oauth" ? 'oauth/token' :'auth'}`, {
281
- method: "POST",
282
- headers: {
283
- "Content-Type": "application/json",
284
- Authorization_Secret: config.Clover_Secret,
285
- tenantid: config.Clover_Tenant_ID,
286
- "User-Agent": headers.get("User-Agent") || "",
287
- },
288
- body: JSON.stringify(fetchBody),
289
- });
282
+ const authRes = await fetch(`${config.Clover_Server_Url}/${options.type === "oauth" ? 'oauth/token' : 'auth'}`, {
283
+ method: "POST",
284
+ headers: {
285
+ "Content-Type": "application/json",
286
+ Authorization_Secret: config.Clover_Secret,
287
+ tenantid: config.Clover_Tenant_ID,
288
+ "User-Agent": headers.get("User-Agent") || "",
289
+ },
290
+ body: JSON.stringify(fetchBody),
291
+ });
292
+
293
+ if (!authRes.ok) {
294
+ return {
295
+ isAuthenticated: false,
296
+ error: true,
297
+ message: "Authentication failed",
298
+ };
299
+ }
290
300
 
291
- if (!authRes.ok) {
292
- return {
293
- isAuthenticated: false,
294
- error: true,
295
- message: "Authentication failed",
296
- };
301
+ const responseJson = await authRes.json();
302
+ const record = responseJson.AuthenticatedModal;
303
+ record.clover_assigned_id = primaryTenantData.id;
304
+ token_uses.set(record.token, 0)
305
+
306
+ record.token = jwt.sign(
307
+ {
308
+ id: record.id,
309
+ clover_assigned_id: record.clover_assigned_id,
310
+ Roles: record.Roles,
311
+ Group: record.clover_group_assigned_To,
312
+ Token_Uses: token_uses.get(token) || 0
313
+ },
314
+ config.JWT_SECRET,
315
+ );
316
+
317
+ record.isAuthenticated = true;
318
+
319
+ return record;
320
+ } else {
321
+ switch (options.type) {
322
+ case "passwordAuth":
323
+ if(options.password && options.emailOrUsername){
324
+ try {
325
+ const { record } = await pb.collection("users").authWithPassword(options.emailOrUsername, options.password);
326
+
327
+ record.token = jwt.sign( {
328
+ id: record.id,
329
+ token_uses: 0
330
+ }, config.JWT_SECRET)
331
+ token_uses.set(record.token, 0)
332
+ return record
333
+ } catch (error) {
334
+ console.error(error);
335
+ return { isAuthenticated: false, error: true, message: "Authentication failed" };
336
+ }
337
+ }
338
+ }
297
339
  }
298
-
299
- const responseJson = await authRes.json();
300
- const record = responseJson.AuthenticatedModal;
301
- record.clover_assigned_id = primaryTenantData.id;
302
-
303
- record.token = jwt.sign(
304
- {
305
- id: record.id,
306
- clover_assigned_id: record.clover_assigned_id,
307
- Roles: record.Roles,
308
- Group: record.clover_group_assigned_To,
309
- },
310
- config.JWT_SECRET,
311
- );
312
-
313
- record.isAuthenticated = true;
314
-
315
- return record;
316
340
  },
317
- Verify: async (token) => {
341
+ Verify: async (token: string) => {
318
342
  try {
319
343
  const payload = jwt.verify(token, config.JWT_SECRET);
320
- if(token_uses.has(token) && token_uses.get(token) >= payload.amount_of_uses){
344
+ if (token_uses.has(token) && token_uses.get(token) >= payload.amount_of_uses) {
321
345
  // this is basic auth token
322
346
  throw new Error("token has been used wayy to many times, it is expired")
323
- }else{
347
+ } else {
324
348
  token_uses.set(token, Number(token_uses.get(token)) + 1)
325
349
  }
326
350
  return {
327
- isAuthenticated: true,
351
+ isAuthenticated: true,
328
352
  id: payload.id || crypto.randomUUID(),
329
353
  clover_group_assigned_To: payload.Group || [],
330
- clover_assigned_id: payload.clover_assigned_id || primaryTenantData.id,
354
+ clover_assigned_id: config.Clover_Tenant_ID ? payload.clover_assigned_id ? config.Clover_Tenant_ID : payload.clover_assigned_id : null,
331
355
  Roles: payload.Roles || [],
332
356
  token,
333
357
  };
@@ -336,14 +360,14 @@ async function buildRequestContext(req: Request, headers: Headers) {
336
360
  }
337
361
  },
338
362
  createTemporaryToken(amount_of_uses: number, expiresAt: string) {
339
- const token = jwt.sign({amount_of_uses, isBasicAuth: true, security_level: 0}, config.JWT_SECRET, { expiresIn: expiresAt })
363
+ const token = jwt.sign({ amount_of_uses, isBasicAuth: true, security_level: 0 }, config.JWT_SECRET, { expiresIn: expiresAt })
340
364
  token_uses.set(token, 0)
341
365
  return token
342
366
  },
343
367
  Roles: Array.isArray(primaryTenantData.Tenant_Roles)
344
368
  ? primaryTenantData.Tenant_Roles
345
369
  : [primaryTenantData.Tenant_Roles],
346
- },
370
+
347
371
  },
348
372
  metadata: {
349
373
  requestID: crypto.randomUUID(),
@@ -351,12 +375,12 @@ async function buildRequestContext(req: Request, headers: Headers) {
351
375
  params: {},
352
376
  query: {},
353
377
  json: reqJSON,
354
- headers : {}
378
+ headers: {}
355
379
  },
356
380
  tenantId: headers.get("tenantid") ?? undefined,
357
- json: (value: any, status?: number, statusText?:string) => {
381
+ json: (value: any, status?: number, statusText?: string) => {
358
382
  return Response.json(value, {
359
- ...(status && {status}),
383
+ ...(status && { status }),
360
384
  headers: {
361
385
  "Access-Control-Allow-Origin": config.origin,
362
386
  "Access-Control-Allow-Methods": "GET,PATCH,PUT,DELETE",
@@ -367,9 +391,9 @@ async function buildRequestContext(req: Request, headers: Headers) {
367
391
 
368
392
  html: (value: string, status: number, statusText?: string) => {
369
393
  return new Response(value, {
370
- ...(status && {status}),
371
- ...(statusText && {statusText}),
372
- headers:{
394
+ ...(status && { status }),
395
+ ...(statusText && { statusText }),
396
+ headers: {
373
397
  "Content-Type": "text/html",
374
398
  "Access-Control-Allow-Origin": config.origin,
375
399
  "Access-Control-Allow-Methods": "GET,PATCH,PUT,DELETE",
@@ -377,11 +401,11 @@ async function buildRequestContext(req: Request, headers: Headers) {
377
401
  }
378
402
  })
379
403
  },
380
- text: (value: string, status?:number, statusText?: string) => {
404
+ text: (value: string, status?: number, statusText?: string) => {
381
405
  return new Response(value, {
382
- ...(status && {status}),
383
- ...(statusText && {statusText}),
384
- headers:{
406
+ ...(status && { status }),
407
+ ...(statusText && { statusText }),
408
+ headers: {
385
409
  "Content-Type": "text/html",
386
410
  "Access-Control-Allow-Origin": config.origin,
387
411
  "Access-Control-Allow-Methods": "GET,PATCH,PUT,DELETE",
@@ -393,22 +417,28 @@ async function buildRequestContext(req: Request, headers: Headers) {
393
417
 
394
418
  const authHeader = headers.get("authorization");
395
419
  const token = authHeader?.startsWith("Bearer ") ? authHeader.split(" ")[1] : authHeader;
396
-
397
420
 
398
- if (token) {
399
- context.principal = await context.services.Clover.Verify(token);
421
+
422
+ if (token) {
423
+ if (config.Clover_Tenant_ID) {
424
+ context.principal = await context.services.Verify(token);
425
+ } else {
426
+ const tokenValid = validateToken(token)
427
+ context.principal.isAuthenticated = tokenValid ? true : false
428
+ }
429
+
400
430
  }
401
431
 
402
432
  return context;
403
433
  }
404
434
 
405
-
435
+
406
436
  // --- Initial Server Start ---
407
437
  server = Bun.serve(await createServeConfig());
408
438
  console.log(`🚀 Hapta listening at http://localhost:${server.port}`);
409
439
  watchFiles();
410
-
440
+
411
441
  export {
412
442
  DatabaseService,
413
443
  Context
414
- };
444
+ };
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "bin": {
4
4
  "hapta":"./index.ts"
5
5
  },
6
- "version": "1.0.2",
6
+ "version": "1.0.4",
7
7
  "description": "modular, scalable, and feature-rich backend framework designed to extend Pocketbase with authentication, schema validation, caching, and tenant-based service orchestration.",
8
8
  "dependencies": {
9
9
  "jsonwebtoken": "^9.0.2",
File without changes
@@ -36,7 +36,8 @@ function findAndLoadConfig(): AppConfig {
36
36
  if (fs.existsSync(localConfigPath)) {
37
37
  console.log(`Loading configuration from: ${localConfigPath}`);
38
38
  const fileContent = fs.readFileSync(localConfigPath, 'utf-8');
39
- const userConfig = JSON.parse(fileContent);
39
+ const userConfig = JSON.parse(fileContent);
40
+ console.log(userConfig)
40
41
 
41
42
  // Merge user config with defaults, so user only has to specify what they want to change
42
43
  return { ...defaultConfig, ...userConfig };
@@ -1,23 +0,0 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>Document</title>
7
- </head>
8
- <body>
9
- <input type="text" placeholder="Username" id ="username" />
10
- <input type="text" placeholder="Password" id="password" />
11
- <button onclick="login()"></button>
12
- <script>
13
- function login(){
14
-
15
- const username = document.getElementById("username").value
16
- const password = document.getElementById("password").value
17
- console.log(username,password)
18
- }
19
-
20
-
21
- </script>
22
- </body>
23
- </html>