@paralect/hive 0.1.47 → 0.1.49

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.
@@ -0,0 +1,12 @@
1
+ # Remove AI code slop
2
+
3
+ Check the diff against main, and remove all AI generated slop introduced in this branch.
4
+
5
+ This includes:
6
+
7
+ - Extra comments that a human wouldn't add or is inconsistent with the rest of the file
8
+ - Extra defensive checks or try/catch blocks that are abnormal for that area of the codebase (especially if called by trusted / validated codepaths)
9
+ - Casts to any to get around type issues
10
+ - Any other style that is inconsistent with the file
11
+
12
+ Report at the end with only a 1-3 sentence summary of what you changed
package/AGENTS.md ADDED
@@ -0,0 +1,96 @@
1
+ # AGENTS.md
2
+
3
+ ## Agent Persona
4
+
5
+ You are a **Hive framework developer** — building tools for engineers who are pissed off about the complexity of modern technology. Hive lets them build, iterate, and grow products faster.
6
+
7
+ **Your mindset:**
8
+ - Prioritize product outcomes over technical purity
9
+ - Minimize boilerplate and cognitive overhead
10
+ - Challenge complexity — if it doesn't serve the user, remove it
11
+ - Less code = better outcome
12
+
13
+ ---
14
+
15
+ ## What is Hive
16
+
17
+ Hive is a Koa-based Node.js framework with MongoDB, Zod validation, and auto-sync for embedded documents. It provides:
18
+
19
+ - **Resource pattern** — convention-based feature modules with schemas, endpoints, handlers
20
+ - **Auto-sync** — embedded document references stay in sync automatically
21
+ - **CLI** — `hive run`, `hive prepare`, `hive deploy`, `hive install`
22
+
23
+ ---
24
+
25
+ ## Repository Structure
26
+
27
+ ```
28
+ /
29
+ ├── cli/ # Hive CLI (commander.js)
30
+ │ ├── hive.js # CLI entry point
31
+ │ └── helpers/ # CLI utilities
32
+ ├── starter/ # Framework core (copied to .hive/ on run)
33
+ │ ├── src/ # Framework source
34
+ │ │ ├── app.js # Server bootstrap
35
+ │ │ ├── db.js # Database layer
36
+ │ │ ├── routes/ # Route registration
37
+ │ │ ├── middlewares/ # Built-in middlewares
38
+ │ │ ├── helpers/ # Internal helpers
39
+ │ │ ├── resources/ # Built-in resources (users, tokens, health)
40
+ │ │ ├── autoMap/ # Auto-sync system
41
+ │ │ └── scheduler/ # Cron job system
42
+ │ └── .cursor/skills/ # Cursor skills for projects using Hive
43
+ └── package.json
44
+ ```
45
+
46
+ ---
47
+
48
+ ## How It Works
49
+
50
+ 1. User runs `npx hive run ./src` from their project
51
+ 2. CLI copies `starter/` to `.hive/` in user's project
52
+ 3. Framework loads user's code from `HIVE_SRC` env var
53
+ 4. Schemas, endpoints, handlers merge at runtime
54
+
55
+ **Key mechanism:** User code in `/src/` extends framework code in `/.hive/`. The framework reads from `process.env.HIVE_SRC` to find user schemas, endpoints, handlers, and config.
56
+
57
+ ---
58
+
59
+ ## Development
60
+
61
+ ```bash
62
+ # Test CLI locally (from repo root)
63
+ node cli/hive.js run ./path/to/test-project/src
64
+
65
+ # The starter/ folder IS the framework
66
+ # Changes here affect all projects using Hive
67
+ ```
68
+
69
+ ---
70
+
71
+ ## Boundaries
72
+
73
+ | Location | What it is | Editable |
74
+ |----------|-----------|----------|
75
+ | `cli/` | CLI tools | ✅ Yes |
76
+ | `starter/` | Framework core | ✅ Yes |
77
+ | `starter/.cursor/skills/` | Cursor skills for end-users | ✅ Yes |
78
+ | User's `/src/` | User code (not in this repo) | N/A |
79
+ | User's `/.hive/` | Auto-generated, never edit | N/A |
80
+
81
+ ---
82
+
83
+ ## When Editing Skills
84
+
85
+ Skills in `starter/.cursor/skills/` are documentation for projects **using** Hive. Each skill:
86
+ - Has a `SKILL.md` with frontmatter (name, description, globs)
87
+ - Teaches Cursor how to write code for Hive projects
88
+ - Should be concise and pattern-focused
89
+
90
+ ---
91
+
92
+ ## Philosophy
93
+
94
+ > Technology should solve people's issues, not create new weird ones.
95
+
96
+ When in doubt: simpler is better. Challenge unnecessary complexity.
package/README.md ADDED
@@ -0,0 +1,271 @@
1
+ # 🐝 Hive
2
+
3
+ **An AI-native backend framework for engineers who are *pissed off* about the complexity of modern technology.**
4
+
5
+ Hive preconfigures the entire backend stack: database, cache, queues, event handlers, auth, real-time — so you don't duct-tape different pieces yourself. It dictates a clean architecture that's easy to understand, easy to read, and scales to millions of users.
6
+
7
+ ```bash
8
+ npm install -g @paralect/hive
9
+
10
+ hive init my-app
11
+ cd my-app
12
+ hive run ./src
13
+ ```
14
+
15
+ Your API is live. MongoDB, validation, auth infrastructure, real-time events — all preconfigured.
16
+
17
+ ---
18
+
19
+ ## 🤖 AI-Native Development
20
+
21
+ Hive is designed for AI coding assistants. Open your project in Cursor and build with natural language:
22
+
23
+ ```
24
+ add-resource tasks
25
+ add-endpoint tasks post title, status, assignee: { _id }
26
+ add-endpoint tasks get page, perPage
27
+ add-handler tasks
28
+ ```
29
+
30
+ ### Commands
31
+
32
+ | Command | What it does |
33
+ |---------|--------------|
34
+ | `add-resource tasks` | Create resource with schema + folders |
35
+ | `add-endpoint tasks post title, dueOn` | Create POST endpoint with inferred types |
36
+ | `add-endpoint tasks get page, perPage` | Create GET list endpoint |
37
+ | `add-endpoint tasks update /:id title` | Create PUT endpoint |
38
+ | `add-handler tasks` | Create event handlers for DB changes |
39
+ | `add-middleware isAdmin` | Create custom middleware |
40
+ | `add-service slack sendMessage` | Create service with go-to library |
41
+ | `add-scheduler sendReport daily at 9am` | Create cron job |
42
+
43
+ The AI understands Hive conventions and generates production-ready code.
44
+
45
+ ---
46
+
47
+ ## What's Preconfigured
48
+
49
+ | Concern | Solution |
50
+ |---------|----------|
51
+ | Database | MongoDB with auto-generated services per schema |
52
+ | Validation | Zod schemas, auto-applied to all endpoints |
53
+ | Auth | Token-based auth infrastructure, ready to extend |
54
+ | Events | Persistent handlers that react to DB changes |
55
+ | Real-time | Socket.io with Redis adapter for scaling |
56
+ | Queues | BullMQ for background jobs |
57
+ | Scheduler | Cron-based jobs, no external service needed |
58
+ | Auto-sync | Embedded documents stay fresh automatically |
59
+
60
+ You focus on your product. Hive handles the plumbing.
61
+
62
+ ---
63
+
64
+ ## Architecture
65
+
66
+ Every feature is a **resource** — a folder with predictable structure:
67
+
68
+ ```
69
+ src/resources/{name}/
70
+ ├── {name}.schema.js # Data shape (required)
71
+ ├── endpoints/ # API routes
72
+ ├── handlers/ # React to DB events
73
+ └── methods/ # Shared logic
74
+ ```
75
+
76
+ This scales. New developers understand it in minutes. Your codebase stays clean at 10 endpoints or 1000.
77
+
78
+ ---
79
+
80
+ ## 📦 Schemas
81
+
82
+ Define your data once. Hive creates the collection and service.
83
+
84
+ ```javascript
85
+ import { z } from 'zod';
86
+ import dbSchema from 'helpers/schema/db.schema.js';
87
+
88
+ const schema = dbSchema.extend({
89
+ title: z.coerce.string().nullable().optional(),
90
+ status: z.coerce.string().default('pending'),
91
+ assignee: z.object({
92
+ _id: z.string(),
93
+ fullName: z.coerce.string().nullable().optional(),
94
+ }).nullable().optional(),
95
+ });
96
+
97
+ export default schema;
98
+ export const secureFields = ['internalNotes'];
99
+ ```
100
+
101
+ Every schema gets `_id`, `createdOn`, `updatedOn` automatically.
102
+
103
+ ---
104
+
105
+ ## 🔌 Endpoints
106
+
107
+ Four exports. No router config.
108
+
109
+ ```javascript
110
+ import { z } from 'zod';
111
+ import db from 'db';
112
+
113
+ const tasksService = db.services.tasks;
114
+
115
+ export const middlewares = [];
116
+
117
+ export const requestSchema = z.object({
118
+ page: z.coerce.number().default(1),
119
+ perPage: z.coerce.number().default(20),
120
+ });
121
+
122
+ export const handler = async (ctx) => {
123
+ const { page, perPage } = ctx.validatedData;
124
+ return tasksService.find({}, { page, perPage, sort: '-createdOn' });
125
+ };
126
+
127
+ export const endpoint = {
128
+ url: '/',
129
+ method: 'get',
130
+ };
131
+ ```
132
+
133
+ Route auto-generated as `GET /tasks`.
134
+
135
+ ---
136
+
137
+ ## 🗄️ Database
138
+
139
+ Auto-generated services for every schema:
140
+
141
+ ```javascript
142
+ import db from 'db';
143
+
144
+ const tasksService = db.services.tasks;
145
+
146
+ // Find
147
+ const { results, count } = await tasksService.find({ status: 'active' }, { page: 1, perPage: 20 });
148
+ const task = await tasksService.findOne({ _id: id });
149
+
150
+ // Create
151
+ const task = await tasksService.create({ title: 'New', user: ctx.state.user });
152
+
153
+ // Update
154
+ await tasksService.updateOne({ _id: id }, (doc) => ({ ...doc, status: 'done' }));
155
+
156
+ // Delete
157
+ await tasksService.remove({ _id: id });
158
+ ```
159
+
160
+ ---
161
+
162
+ ## ⚡ Handlers
163
+
164
+ React to database changes. Perfect for side effects, notifications, syncing data.
165
+
166
+ ```javascript
167
+ import db from 'db';
168
+ import ifUpdated from 'helpers/db/ifUpdated';
169
+
170
+ const tasksService = db.services.tasks;
171
+
172
+ tasksService.on('created', async ({ doc }) => {
173
+ // Send notification, create activity log, etc.
174
+ });
175
+
176
+ tasksService.on('updated', ifUpdated(['status'], async ({ doc, prevDoc }) => {
177
+ // Only runs when status changed
178
+ }));
179
+
180
+ tasksService.on('removed', async ({ doc }) => {
181
+ // Cleanup related data
182
+ });
183
+ ```
184
+
185
+ ---
186
+
187
+ ## 🛡️ Middlewares
188
+
189
+ Built-in: `allowNoAuth`, `isAuthorized`, `shouldExist`, `attachUser`
190
+
191
+ Custom:
192
+
193
+ ```javascript
194
+ export default async (ctx, next) => {
195
+ if (!ctx.state.user?.isAdmin) ctx.throw(403, 'Admin only');
196
+ return next();
197
+ };
198
+ ```
199
+
200
+ ---
201
+
202
+ ## ⏰ Scheduler
203
+
204
+ Background jobs with cron:
205
+
206
+ ```javascript
207
+ import db from 'db';
208
+
209
+ export const handler = async () => {
210
+ await db.services.invoices.updateMany(
211
+ { isPaid: { $ne: true }, dueOn: { $lt: new Date() } },
212
+ (doc) => ({ ...doc, isOverdue: true })
213
+ );
214
+ };
215
+
216
+ export const cron = '0 9 * * *';
217
+ ```
218
+
219
+ ---
220
+
221
+ ## 🔄 Auto-Sync
222
+
223
+ Embedded documents stay fresh. When a user updates their name, all tasks with that user update automatically.
224
+
225
+ ```json
226
+ {
227
+ "tasks": {
228
+ "assignee": { "schema": "users" }
229
+ }
230
+ }
231
+ ```
232
+
233
+ ---
234
+
235
+ ## CLI
236
+
237
+ ```bash
238
+ hive init [name] # Create new project
239
+ hive run [path] # Start dev server
240
+ hive prepare [path] # Build for production
241
+ hive deploy # Deploy to Hive Cloud
242
+ hive install <plugin> # Install plugin
243
+ hive login # Login to Hive Cloud
244
+ ```
245
+
246
+ ---
247
+
248
+ ## Project Structure
249
+
250
+ ```
251
+ my-app/
252
+ ├── src/
253
+ │ ├── resources/ # Your features
254
+ │ ├── middlewares/ # Custom middlewares
255
+ │ ├── services/ # External APIs
256
+ │ └── scheduler/handlers/
257
+ └── .hive/ # Framework (don't edit)
258
+ ```
259
+
260
+ ---
261
+
262
+ ## Tech Stack
263
+
264
+ Proven, boring technology:
265
+
266
+ - **Koa** — Node.js framework
267
+ - **MongoDB** — Document database
268
+ - **Zod** — Schema validation
269
+ - **Socket.io** — Real-time
270
+ - **BullMQ** — Job queues
271
+ - **Redis** — Cache & pub/sub
package/cli/hive.js CHANGED
@@ -8,7 +8,73 @@ const mergeDirs = require('./helpers/mergeDirs');
8
8
  const execCommand = require('./helpers/execCommand');
9
9
  const downloadDirectory = require('./helpers/downloadDirectory');
10
10
  const axios = require('axios');
11
- const tsx = require('tsx/cjs/api')
11
+ const tsx = require('tsx/cjs/api');
12
+ const fs = require('fs');
13
+
14
+ program
15
+ .command('init [projectName]')
16
+ .description('Initialize a new Hive project')
17
+ .action(async (projectName) => {
18
+ try {
19
+ let name = projectName;
20
+
21
+ if (!name) {
22
+ const answer = await inquirer.prompt([
23
+ {
24
+ type: 'input',
25
+ name: 'projectName',
26
+ message: 'Project name:',
27
+ default: 'my-hive-app'
28
+ }
29
+ ]);
30
+ name = answer.projectName;
31
+ }
32
+
33
+ const projectDir = path.resolve(process.cwd(), name);
34
+
35
+ console.log(`\n🐝 Creating Hive project: ${name}\n`);
36
+
37
+ await execCommand(`mkdir -p ${projectDir}/src/resources`);
38
+ await execCommand(`mkdir -p ${projectDir}/src/middlewares`);
39
+ await execCommand(`mkdir -p ${projectDir}/src/services`);
40
+ await execCommand(`mkdir -p ${projectDir}/src/scheduler/handlers`);
41
+
42
+ fs.writeFileSync(
43
+ path.join(projectDir, 'package.json'),
44
+ JSON.stringify({
45
+ name,
46
+ version: '1.0.0',
47
+ scripts: {
48
+ dev: 'hive run ./src',
49
+ start: 'hive run ./src'
50
+ },
51
+ dependencies: {}
52
+ }, null, 2)
53
+ );
54
+
55
+ fs.writeFileSync(
56
+ path.join(projectDir, '.env'),
57
+ `MONGO_URI=mongodb://localhost:27017/${name}\nPORT=3001\nNODE_ENV=development\n`
58
+ );
59
+
60
+ fs.writeFileSync(
61
+ path.join(projectDir, '.gitignore'),
62
+ `node_modules\n.hive\n.env\n`
63
+ );
64
+
65
+ await execCommand(`cp -r ${path.resolve(__dirname, '..')}/starter/.cursor ${projectDir}/`);
66
+
67
+ console.log(`✅ Project created!\n`);
68
+ console.log(`Next steps:\n`);
69
+ console.log(` cd ${name}`);
70
+ console.log(` hive run ./src\n`);
71
+ console.log(`Start building with AI commands:`);
72
+ console.log(` add-resource tasks`);
73
+ console.log(` add-endpoint tasks post title, status\n`);
74
+ } catch (error) {
75
+ console.error('An error occurred:', error.message);
76
+ }
77
+ });
12
78
 
13
79
  program
14
80
  .command('run [dirPath]')
@@ -16,7 +82,7 @@ program
16
82
  .action(async (dirPath = '.') => {
17
83
  try {
18
84
  process.env.HIVE_SRC = path.resolve(process.cwd(), dirPath);
19
-
85
+
20
86
  const hiveProjectDir = path.resolve(process.env.HIVE_SRC, `../.hive`);
21
87
  await execCommand(`mkdir -p ${hiveProjectDir}`);
22
88
  await execCommand(`cp -r ${path.resolve(__dirname, '..')}/starter/ ${hiveProjectDir}`);
@@ -27,7 +93,7 @@ program
27
93
  }
28
94
  });
29
95
 
30
- program
96
+ program
31
97
  .command('prepare [dirPath]')
32
98
  .description('Prepare Hive server')
33
99
  .action(async (dirPath = '.') => {
@@ -42,7 +108,7 @@ program
42
108
  }
43
109
  });
44
110
 
45
- program
111
+ program
46
112
  .command('deploy')
47
113
  .description('Build hive project')
48
114
  .action(async () => {
@@ -50,7 +116,7 @@ program
50
116
  let outDir = path.resolve(process.cwd(), './dist');
51
117
  await mergeDirs({ hiveSrc: path.resolve(process.cwd()), outDir });
52
118
 
53
- console.log('outDir', path.resolve(outDir, `./deploy/script`))
119
+ console.log('outDir', path.resolve(outDir, `./deploy/script`))
54
120
  await execCommand(`npm install --prefix ${path.resolve(outDir, `./deploy/script`)}`);
55
121
 
56
122
  await execCommand('node ./index.js', {
@@ -67,7 +133,7 @@ program
67
133
  .action(async (plugin) => {
68
134
  try {
69
135
  const destDir = process.cwd();
70
-
136
+
71
137
  await downloadDirectory(plugin);
72
138
  } catch (error) {
73
139
  console.error('An error occurred:', error.message);
@@ -80,12 +146,14 @@ program
80
146
  .description('Login into Hive Cloud')
81
147
  .action(async () => {
82
148
  if (process.env.HIVE_TOKEN) {
83
- const user = (await axios({ url: `https://hive-api-test.paralect.co/users/me`, method: 'get', headers: {
84
- 'Authorization': `Bearer ${process.env.HIVE_TOKEN}`
85
- } })).data;
149
+ const user = (await axios({
150
+ url: `https://hive-api-test.paralect.co/users/me`, method: 'get', headers: {
151
+ 'Authorization': `Bearer ${process.env.HIVE_TOKEN}`
152
+ }
153
+ })).data;
86
154
 
87
155
  console.log(`Already logged in!`, user);
88
-
156
+
89
157
  return;
90
158
  }
91
159
 
@@ -99,7 +167,7 @@ program
99
167
 
100
168
  try {
101
169
  await axios({ url: `https://hive-api-test.paralect.co/auth/login-code`, method: 'post', data: { email } });
102
-
170
+
103
171
  const { code } = await inquirer.prompt([
104
172
  {
105
173
  type: 'input',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@paralect/hive",
3
- "version": "0.1.47",
3
+ "version": "0.1.49",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "bin": {
@@ -13,7 +13,6 @@
13
13
  "@koa/cors": "3.1.0",
14
14
  "@koa/multer": "3.0.0",
15
15
  "@koa/router": "10.1.1",
16
- "@paralect/hive": "0.1.44-beta.4",
17
16
  "@paralect/node-mongo": "2.1.1",
18
17
  "@react-email/components": "^0.0.20",
19
18
  "@react-email/render": "^0.0.16",