@paralect/hive 0.1.48 → 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,104 @@
1
+ ---
2
+ name: hive-middleware
3
+ description: How to create and use middlewares in Hive framework
4
+ globs:
5
+ - src/middlewares/*.js
6
+ alwaysApply: false
7
+ ---
8
+
9
+ # Middlewares
10
+
11
+ Location: `/src/middlewares/{name}.js`
12
+
13
+ ## Built-in Middlewares
14
+
15
+ | Name | Purpose |
16
+ |------|---------|
17
+ | `allowNoAuth` | Skip authentication |
18
+ | `isAuthorized` | Require authenticated user |
19
+ | `shouldExist` | Load resource, 404 if not found |
20
+ | `attachUser` | Load user from token |
21
+
22
+ ## Creating Middleware
23
+
24
+ **Simple:**
25
+ ```javascript
26
+ export default async (ctx, next) => {
27
+ // Before handler
28
+ if (!ctx.state.user?.isAdmin) {
29
+ ctx.throw(403, 'Admin only');
30
+ }
31
+ return next(); // Don't forget!
32
+ };
33
+ ```
34
+
35
+ **With parameters:**
36
+ ```javascript
37
+ export default (resourceName) => async (ctx, next) => {
38
+ const doc = await db.services[resourceName].findOne({
39
+ _id: ctx.params[`${resourceName}Id`],
40
+ });
41
+
42
+ if (!doc) ctx.throw(404, `${resourceName} not found`);
43
+
44
+ ctx.state[resourceName] = doc;
45
+ return next();
46
+ };
47
+ ```
48
+
49
+ **With runOrder (lower runs first):**
50
+ ```javascript
51
+ const middleware = async (ctx, next) => {
52
+ ctx.state.isSkipAuth = true;
53
+ return next();
54
+ };
55
+ middleware.runOrder = -1;
56
+ export default middleware;
57
+ ```
58
+
59
+ ## Using in Endpoints
60
+
61
+ ```javascript
62
+ // By name
63
+ export const middlewares = ['allowNoAuth'];
64
+
65
+ // With arguments
66
+ export const middlewares = [{ name: 'shouldExist', args: ['projects'] }];
67
+
68
+ // Direct import
69
+ import isAdmin from 'middlewares/isAdmin';
70
+ export const middlewares = [isAdmin];
71
+
72
+ // Factory function
73
+ import canEditProject from 'middlewares/canEditProject';
74
+ export const middlewares = [canEditProject((ctx) => ctx.params.projectId)];
75
+
76
+ // Inline
77
+ export const middlewares = [
78
+ async (ctx, next) => {
79
+ // Custom logic
80
+ return next();
81
+ },
82
+ ];
83
+ ```
84
+
85
+ ## Global Middleware
86
+
87
+ Create `/src/middlewares/global.js` to run on all endpoints:
88
+
89
+ ```javascript
90
+ import isAuthorized from 'middlewares/isAuthorized';
91
+ import attachRootProject from 'middlewares/attachRootProject';
92
+
93
+ export default async (ctx, next) => {
94
+ await isAuthorized(ctx, async () => {
95
+ await attachRootProject(ctx, next);
96
+ });
97
+ };
98
+ ```
99
+
100
+ ## Rules
101
+
102
+ - Always call `next()` or throw
103
+ - Use `runOrder` to control execution order
104
+ - Factory functions for parameterized middlewares
@@ -0,0 +1,50 @@
1
+ ---
2
+ name: hive-overview
3
+ description: Hive framework structure and conventions. Apply when working with this codebase.
4
+ globs:
5
+ - src/**/*.js
6
+ alwaysApply: false
7
+ ---
8
+
9
+ # Hive Framework Overview
10
+
11
+ Hive is a Koa-based Node.js framework with MongoDB, Zod validation, and auto-sync for embedded documents.
12
+
13
+ ## Directory Structure
14
+
15
+ | Directory | Purpose | Edit? |
16
+ |-----------|---------|-------|
17
+ | `/.hive/` | Framework core | No - read only |
18
+ | `/src/` | Application code | Yes |
19
+
20
+ ## Resources
21
+
22
+ A resource is a feature module in `/src/resources/{name}/`:
23
+
24
+ ```
25
+ src/resources/{name}/
26
+ ├── {name}.schema.js # Required: DB schema
27
+ ├── endpoints/ # API routes
28
+ ├── handlers/ # Event listeners
29
+ └── methods/ # Reusable functions
30
+ ```
31
+
32
+ ## Built-in (in .hive/)
33
+
34
+ - `tokens` - Auth token storage
35
+ - `users` - Base user schema
36
+ - `db` - Database layer with services
37
+
38
+ ## Key Imports
39
+
40
+ ```javascript
41
+ import db from 'db'; // Database
42
+ import config from 'app-config'; // Config
43
+ import { z } from 'zod'; // Validation
44
+ ```
45
+
46
+ ## Services Access
47
+
48
+ ```javascript
49
+ const taskService = db.services.tasks; // Auto-created from schema
50
+ ```
@@ -0,0 +1,94 @@
1
+ ---
2
+ name: hive-scheduler
3
+ description: How to create scheduled jobs in Hive framework
4
+ globs:
5
+ - src/scheduler/handlers/*.js
6
+ alwaysApply: false
7
+ ---
8
+
9
+ # Scheduler Jobs
10
+
11
+ Background jobs on cron schedules.
12
+
13
+ Location: `/src/scheduler/handlers/{jobName}.js`
14
+
15
+ ## Template
16
+
17
+ ```javascript
18
+ import db from 'db';
19
+
20
+ export const handler = async () => {
21
+ // Job logic
22
+ };
23
+
24
+ export const cron = '0 * * * *'; // Every hour
25
+ ```
26
+
27
+ ## Cron Patterns
28
+
29
+ ```
30
+ ┌─ minute (0-59)
31
+ │ ┌─ hour (0-23)
32
+ │ │ ┌─ day of month (1-31)
33
+ │ │ │ ┌─ month (1-12)
34
+ │ │ │ │ ┌─ day of week (0-6)
35
+ * * * * *
36
+ ```
37
+
38
+ | Pattern | Schedule |
39
+ |---------|----------|
40
+ | `* * * * *` | Every minute |
41
+ | `*/5 * * * *` | Every 5 minutes |
42
+ | `0 * * * *` | Every hour |
43
+ | `0 */12 * * *` | Every 12 hours |
44
+ | `0 0 * * *` | Daily at midnight |
45
+ | `0 9 * * 1` | Mondays at 9am |
46
+
47
+ ## Examples
48
+
49
+ **Sync external data:**
50
+ ```javascript
51
+ import db from 'db';
52
+ import moment from 'moment';
53
+ import externalApi from 'services/externalApi';
54
+
55
+ export const handler = async () => {
56
+ const items = await externalApi.list({
57
+ updatedSince: moment().subtract(5, 'minutes').toDate(),
58
+ });
59
+
60
+ for (const item of items) {
61
+ await db.services.items.updateOne(
62
+ { externalId: item.id },
63
+ (doc) => ({ ...doc, ...item })
64
+ );
65
+ }
66
+ };
67
+
68
+ export const cron = '*/5 * * * *';
69
+ ```
70
+
71
+ **Mark overdue:**
72
+ ```javascript
73
+ import db from 'db';
74
+ import moment from 'moment';
75
+
76
+ export const handler = async () => {
77
+ await db.services.invoices.updateMany(
78
+ {
79
+ isPaid: { $ne: true },
80
+ isDue: { $ne: true },
81
+ dueOn: { $lt: new Date() },
82
+ },
83
+ (doc) => ({ ...doc, isDue: true })
84
+ );
85
+ };
86
+
87
+ export const cron = '0 */12 * * *';
88
+ ```
89
+
90
+ ## Rules
91
+
92
+ - Export both `handler` and `cron`
93
+ - Keep jobs idempotent (safe to re-run)
94
+ - Log progress for debugging
@@ -0,0 +1,73 @@
1
+ ---
2
+ name: hive-schema
3
+ description: How to create database schemas in Hive framework
4
+ globs:
5
+ - src/resources/**/*.schema.js
6
+ alwaysApply: false
7
+ ---
8
+
9
+ # Creating Database Schemas
10
+
11
+ Location: `/src/resources/{name}/{name}.schema.js`
12
+
13
+ ## Template
14
+
15
+ ```javascript
16
+ import { z } from 'zod';
17
+ import dbSchema from 'helpers/schema/db.schema.js';
18
+
19
+ const schema = dbSchema.extend({
20
+ // Fields here
21
+ });
22
+
23
+ export default schema;
24
+
25
+ export const secureFields = []; // Hidden from API responses
26
+ ```
27
+
28
+ ## Field Patterns
29
+
30
+ **Simple fields:**
31
+ ```javascript
32
+ title: z.coerce.string().nullable().optional(),
33
+ count: z.coerce.number().nullable().optional(),
34
+ isActive: z.coerce.boolean().nullable().optional(),
35
+ dueOn: z.coerce.date().nullable().optional(),
36
+ ```
37
+
38
+ **Reference to another document:**
39
+ ```javascript
40
+ user: z
41
+ .object({
42
+ _id: z.string(),
43
+ fullName: z.coerce.string().nullable().optional(),
44
+ avatarUrl: z.coerce.string().nullable().optional(),
45
+ })
46
+ .nullable()
47
+ .optional(),
48
+ ```
49
+
50
+ **Array of references:**
51
+ ```javascript
52
+ managers: z
53
+ .array(
54
+ z.object({
55
+ _id: z.string(),
56
+ fullName: z.coerce.string().nullable().optional(),
57
+ }).nullable().optional(),
58
+ )
59
+ .nullable()
60
+ .optional(),
61
+ ```
62
+
63
+ **Flexible object:**
64
+ ```javascript
65
+ data: z.object({}).passthrough().nullable().optional(),
66
+ ```
67
+
68
+ ## Rules
69
+
70
+ - Always use `z.coerce` for type safety
71
+ - Always add `.nullable().optional()` unless required
72
+ - Include fields you need in references (for auto-sync)
73
+ - Add sensitive fields to `secureFields` array
@@ -0,0 +1,90 @@
1
+ ---
2
+ name: hive-service
3
+ description: How to create external services in Hive framework
4
+ globs:
5
+ - src/services/*.js
6
+ alwaysApply: false
7
+ ---
8
+
9
+ # Services
10
+
11
+ Services wrap external APIs and utilities.
12
+
13
+ Location: `/src/services/{name}.js`
14
+
15
+ ## API Client Template
16
+
17
+ ```javascript
18
+ import config from 'app-config';
19
+ import axios from 'axios';
20
+
21
+ const client = axios.create({
22
+ baseURL: 'https://api.example.com',
23
+ headers: {
24
+ Authorization: `Bearer ${config.example.apiKey}`,
25
+ },
26
+ });
27
+
28
+ export default {
29
+ getItems: async (params) => {
30
+ const response = await client.get('/items', { params });
31
+ return response.data;
32
+ },
33
+
34
+ createItem: async (data) => {
35
+ const response = await client.post('/items', data);
36
+ return response.data;
37
+ },
38
+ };
39
+ ```
40
+
41
+ ## SDK Wrapper Template
42
+
43
+ ```javascript
44
+ import config from 'app-config';
45
+ import { WebClient } from '@slack/web-api';
46
+
47
+ const client = new WebClient(config.slack.botToken);
48
+
49
+ export default {
50
+ client,
51
+
52
+ postMessage: async ({ channel, text }) => {
53
+ return client.chat.postMessage({ channel, text });
54
+ },
55
+ };
56
+ ```
57
+
58
+ ## Utility Service Template
59
+
60
+ ```javascript
61
+ import _ from 'lodash';
62
+
63
+ export const when = (condition, result, elseResult = {}) => {
64
+ if (_.isUndefined(condition)) return {};
65
+ if (!condition) return elseResult;
66
+ return _.isFunction(result) ? result() : result;
67
+ };
68
+
69
+ export const base64 = {
70
+ encode: (obj) => Buffer.from(JSON.stringify(obj)).toString('base64'),
71
+ decode: (str) => JSON.parse(Buffer.from(str, 'base64').toString()),
72
+ };
73
+ ```
74
+
75
+ ## Using Services
76
+
77
+ ```javascript
78
+ import harvest from 'services/harvest';
79
+ import slackService from 'services/slack';
80
+ import { when } from 'services/utils';
81
+
82
+ // API calls
83
+ const invoices = await harvest.getInvoices({ projectId });
84
+
85
+ // SDK usage
86
+ await slackService.postMessage({ channel: '#general', text: 'Hello' });
87
+
88
+ // Utilities
89
+ const query = { ...when(status, { status }) };
90
+ ```
@@ -14,6 +14,7 @@ import cors from "@koa/cors";
14
14
  import helmet from "koa-helmet";
15
15
  import qs from "koa-qs";
16
16
  import bodyParser from "koa-bodyparser";
17
+
17
18
  import requestLogger from "koa-logger";
18
19
  import db from "db";
19
20
  import socketIo from "socketIo";
@@ -42,9 +43,9 @@ const main = async () => {
42
43
  app.use(bodyParser({
43
44
  enableTypes: ["json", "form", "text"],
44
45
 
45
- formLimit: '10mb',
46
- textLimit: '10mb',
47
- jsonLimit: '10mb',
46
+ formLimit: config._hive.bodyParser?.formLimit || "10mb",
47
+ textLimit: config._hive.bodyParser?.textLimit || "10mb",
48
+ jsonLimit: config._hive.bodyParser?.jsonLimit || "10mb",
48
49
  }));
49
50
 
50
51
  app.use(mount("/health", get.handler));