@maiyunnet/kebab 9.25.2 → 9.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,203 +1,254 @@
1
- <p align="center"><img src="./doc/icon.png" width="64" height="64" alt="Kebab"></p>
2
- <p align="center">
3
- <a href="https://github.com/maiyun/kebab/blob/main/LICENSE">
4
- <img alt="License" src="https://img.shields.io/github/license/maiyun/kebab?color=blue" />
5
- </a>
6
- <a href="https://www.npmjs.com/package/@maiyunnet/kebab">
7
- <img alt="NPM stable version" src="https://img.shields.io/npm/v/@maiyunnet/kebab?color=brightgreen&logo=npm" />
8
- </a>
9
- <a href="https://github.com/maiyun/kebab/releases">
10
- <img alt="GitHub releases" src="https://img.shields.io/github/v/release/maiyun/kebab?color=brightgreen&logo=github" />
11
- </a>
12
- <a href="https://github.com/maiyun/kebab/issues">
13
- <img alt="GitHub issues" src="https://img.shields.io/github/issues/maiyun/kebab?color=blue&logo=github" />
14
- </a>
15
- </p>
16
-
17
- Simple, easy-to-use, and fully-featured Node.js framework that is ready-to-use out of the box.
18
-
19
- ## Languages
20
-
21
- [简体中文](doc/README.sc.md) | [繁體中文](doc/README.tc.md)
22
-
23
- ## Requirement
24
-
25
- Node 22+
26
-
27
- ## Installation
28
-
29
- Run `npm i @maiyunnet/kebab` to install the latest version. After installation, run `npx kebab init` to initialize, then run `npx kebab` to start the project.
30
-
31
- You can also use pm2 to start the project by running:
32
-
33
- `pm2 start npx --name "kebab" -- kebab`
34
-
35
- ## Library
36
-
37
- Ai, Buffer, Captcha, Consistent, Core, Cron, Crypto, Db (MySQL, PostgreSQL), Dns (DNSPod, Alibaba Cloud), Fs, Kv (Redis), Lan, Lang, Net, S3, Scan, Session, Socket, Sql, Ssh (Shell, Sftp), Text, Time, Turnstile (Cloudflare, Tencent Cloud), Vector (Milvus), Ws, Zip, Zlib.
38
-
39
- ## Partial Features
40
-
41
- ### Ready-to-use
42
-
43
- Following the principle of "ready-to-use", this package includes commonly used libraries in a unified style.
44
-
45
- ### Hot update
46
-
47
- By calling the Core.sendRestart method, you can smoothly achieve alternating hot updates between old and new code without interrupting any existing business or connections.
48
-
49
- ### Multi-process support
50
-
51
- Create a multi-process model based on the number of CPU cores to fully utilize the multi-core CPU.
52
-
53
- ### Global connection pool
54
-
55
- If different sites in the same process connect to the same server, such as db, kv, etc., they share the same connection pool, maximizing efficiency and reducing overhead.
56
-
57
- ### Super Easy-to-use net Library
58
-
59
- ```typescript
60
- const res = await lNet.open('https://xxx/test').post().data({ 'a': '1', 'b': '2' }).request();
61
- ```
62
-
63
- It can also be used like this:
64
-
65
- ```typescript
66
- const res = await lNet.get('https://xxx/test');
67
- ```
68
-
69
- You can set custom parsing results:
70
-
71
- ```typescript
72
- const res = await lNet.get('https://xxx/test', {
73
- 'hosts': {
74
- 'xxx': '111.111.111.111'
75
- }
76
- });
77
- ```
78
-
79
- You can also choose other local network cards to access:
80
-
81
- ```typescript
82
- const res = await lNet.get('https://xxx/test', {
83
- 'local': '123.123.123.123'
84
- });
85
- ```
86
-
87
- It also has a complete cookie manager, which can easily obtain and store cookies anywhere. When sending a request, the system will select the domain and path based on the cookie settings. If Set-Cookie has an illegal cross-domain setting, it will be discarded and not recorded, just like a real browser.
88
-
89
- ```typescript
90
- const res1 = await lNet.get('https://xxx1.xxx/test1', { 'cookie': cookie });
91
- const res2 = await lNet.get('https://xxx2.xxx/test2', { 'cookie': cookie });
92
- ```
93
-
94
- > Note: The net library supports both options and open chain operations. For example, await lNet.open('xxx').follow().timeout(60).save(this._config.const.rootPath + 'doc/test.txt').request();
95
-
96
- ### Easy-to-Use Db Library
97
-
98
- With a large number of useful interfaces, you can easily filter the data you need from the database:
99
-
100
- ```typescript
101
- const ls = Order.where<Order>(this, db, {
102
- 'state': '1'
103
- }).by('id', 'DESC').page(10, 1);
104
- const list = await ls.all();
105
- const count = await ls.count();
106
- const total = await ls.total();
107
- ```
108
-
109
- Get a user:
110
-
111
- ```typescript
112
- const user = await User.select<User>(this, db, ['id', 'user']).filter([
113
- ['time_add', '>=', '1583405134']
114
- ]).first();
115
- ```
116
-
117
- ### XSRF Detection
118
-
119
- Use the _checkXInput method to perform XSRF detection and prevent malicious access.
120
-
121
- ### Scan Login
122
-
123
- With the help of the Scan library, it's easy to implement scan login.
124
-
125
- ### Reverse Proxy
126
-
127
- Achieve reverse proxy functionality effortlessly by utilizing the rproxy method from the net library, combined with route parameters.
128
-
129
- #### There are more features waiting for you to explore
130
-
131
- ## Examples
132
-
133
- ### Creating a 16-bit random number
134
-
135
- ```typescript
136
- let str: string = Core.random(16, Core.RANDOM_N)
137
- ```
138
-
139
- ### Creating a verification code
140
-
141
- ```typescript
142
- Captcha.get(400, 100).getBuffer();
143
- ```
144
-
145
- ### Getting a list
146
-
147
- ```typescript
148
- const userList = await User.where<User>(this, db, [
149
- ['state', '!=', '0'],
150
- {
151
- 'type': ['1', '2', '3'],
152
- 'is_lock': '0'
153
- }
154
- ]).all();
155
- ```
156
-
157
- > Note: All database operations have been protected against injection attacks.
158
-
159
- ### Sql Library Automatically Adds Table Prefixes and Wrapping Characters "`"
160
-
161
- ```typescript
162
- sql.select(['SUM(user.age) age'], 'order').leftJoin('user', {'order.user_id': lSql.column('user.id')});
163
- ```
164
-
165
- The output will be:
166
-
167
- ```sql
168
- SELECT SUM(`test_user`.`age`) AS `age` FROM `test_order` LEFT JOIN `test_user` ON `test_order`.`user_id` = `test_user`.`id`
169
- ```
170
-
171
- It's so easy to write!
172
-
173
- ### Localization
174
-
175
- ```typescript
176
- await this._loadLocale(this._get['lang'], 'test');
177
- return this._l('copy');
178
- ```
179
-
180
- Based on the different values of lang, the output will be: Copy, 复制, 複製, コピー, etc., configured in the /data/locale/ directory.
181
-
182
- ### Data Validation
183
-
184
- Directly validate submitted data based on strings, numbers, comparisons, and even regular expressions. It's convenient!
185
-
186
- ```typescript
187
- {
188
- 'he': ['require', [0, 'The he param does not exist.']],
189
- 'num': ['> 10', [0, 'The num param must > 10.']],
190
- 'reg': ['/^[A-CX-Z5-7]+$/', [0, 'The reg param is incorrect.']],
191
- 'arr': [['a', 'x', 'hehe'], [0, 'The arr param is incorrect.']]
192
- }
193
- ```
194
-
195
- See: /test/ctr-checkinput
196
-
197
- ### Other Examples
198
-
199
- You can visit /test/ to see more examples.
200
-
201
- ## License
202
-
203
- This library is published under [Apache-2.0](./LICENSE) license.
1
+ <p align="center"><img src="./doc/icon.png" width="64" height="64" alt="Kebab"></p>
2
+ <p align="center">
3
+ <a href="https://github.com/maiyun/kebab/blob/main/LICENSE">
4
+ <img alt="License" src="https://img.shields.io/github/license/maiyun/kebab?color=blue" />
5
+ </a>
6
+ <a href="https://www.npmjs.com/package/@maiyunnet/kebab">
7
+ <img alt="NPM stable version" src="https://img.shields.io/npm/v/@maiyunnet/kebab?color=brightgreen&logo=npm" />
8
+ </a>
9
+ <a href="https://github.com/maiyun/kebab/releases">
10
+ <img alt="GitHub releases" src="https://img.shields.io/github/v/release/maiyun/kebab?color=brightgreen&logo=github" />
11
+ </a>
12
+ <a href="https://github.com/maiyun/kebab/issues">
13
+ <img alt="GitHub issues" src="https://img.shields.io/github/issues/maiyun/kebab?color=blue&logo=github" />
14
+ </a>
15
+ </p>
16
+
17
+ A simple, easy-to-use, full-featured Node.js framework, ready to use out of the box.
18
+
19
+ > Project statement: This project was first committed to GitHub on February 25, 2019. Its predecessor, the Mutton framework, was first committed on July 13, 2015, after several years of development. In 2026, the project formally introduced AI-assisted development and adaptations for AI integration, but software engineers still lead, review, verify and test the project; it is not automatically generated by simply telling AI what we want. Non-Chinese content is translated with assistance from Byterun Translator, so the wording may have an AI-like tone.
20
+
21
+ > The releases on GitHub may be incomplete. For versions after 2.0.0, refer to NPM as the source of record: [NPM](https://www.npmjs.com/package/@maiyunnet/kebab?activeTab=versions)
22
+
23
+ ## Languages
24
+
25
+ [简体中文](doc/README.sc.md) | [繁體中文](doc/README.tc.md)
26
+
27
+ ## Requirements
28
+
29
+ Node.js 24+
30
+
31
+ ## Installation
32
+
33
+ Run `npm i @maiyunnet/kebab` to install the latest version. After installation, run `npx kebab init` to initialize, then run `npx kebab` to start the project.
34
+
35
+ You can also start the project with pm2 by running `pm2 start npx --name "kebab" -- kebab`.
36
+
37
+ ## Libraries
38
+
39
+ Ai, Buffer, Captcha, Consistent, Cookie, Core, Cron, Crypto, Db (MySQL, PostgreSQL), Dns (DNSPod, Alibaba Cloud), Fs, Kv (Redis), Lan, Lang, Net, Ratelimit, S3, Scan, Session, Socket, Sql, Ssh (Shell, Sftp), Text, Time, Turnstile (Cloudflare, Tencent Cloud), Undici, Vector (Milvus), Ws, Zip, Zlib.
40
+
41
+ Use Undici for new HTTP requests; Net remains available for compatibility with existing code.
42
+
43
+ ## Selected features
44
+
45
+ ### Ready to use
46
+
47
+ Following the principle of being ready to use out of the box, Kebab wraps commonly used libraries in a consistent style.
48
+
49
+ ### Hot updates
50
+
51
+ Call `lCore.sendRestart()` to initiate a graceful restart: new processes accept connections, while old processes exit once their existing connections have ended.
52
+
53
+ ### Multiple processes
54
+
55
+ Create multiple processes based on the number of CPU cores to make full use of a multi-core CPU.
56
+
57
+ ### Shared connection pools
58
+
59
+ Different sites in the same process share a connection pool when connecting to the same Db, Kv or other server, maximizing efficiency and reducing overhead.
60
+
61
+ ### Easy-to-use Undici library
62
+
63
+ ```typescript
64
+ import * as lUndici from '@maiyunnet/kebab/lib/undici.js';
65
+
66
+ const res = await lUndici.open('https://example.com/test').post().data({ 'a': '1', 'b': '2' }).request();
67
+ const content = await res.getContent();
68
+ ```
69
+
70
+ You can also use it like this:
71
+
72
+ ```typescript
73
+ const res = await lUndici.get('https://example.com/test');
74
+ const content = await res.getContent();
75
+ ```
76
+
77
+ When you only need a JSON response, use the corresponding shortcut method. Request or read failures return `null`; JSON parsing failures return `false`:
78
+
79
+ ```typescript
80
+ const data = await lUndici.getResponseJson('https://example.com/data');
81
+ ```
82
+
83
+ You can customize hostname resolution. Here, `hostsMap` is a caller-provided mapping of hostnames to IP addresses:
84
+
85
+ ```typescript
86
+ const res = await lUndici.get('https://example.com/test', {
87
+ 'hosts': hostsMap,
88
+ });
89
+ const content = await res.getContent();
90
+ ```
91
+
92
+ You can also use another local network interface. Here, `localAddress` is the local IP address from your configuration:
93
+
94
+ ```typescript
95
+ const res = await lUndici.get('https://example.com/test', {
96
+ 'local': localAddress,
97
+ });
98
+ const content = await res.getContent();
99
+ ```
100
+
101
+ It also has a complete cookie manager that stores received cookies in a caller-provided object. When sending requests, the system selects cookies based on their domain, path and other attributes, and discards Set-Cookie values with invalid cross-domain settings:
102
+
103
+ ```typescript
104
+ import * as lCookie from '@maiyunnet/kebab/lib/cookie.js';
105
+
106
+ const cookie: Record<string, lCookie.ICookie> = {};
107
+ const res1 = await lUndici.get('https://example.com/login', { 'cookie': cookie });
108
+ await res1.getContent();
109
+ const res2 = await lUndici.get('https://example.com/profile', { 'cookie': cookie });
110
+ await res2.getContent();
111
+ ```
112
+
113
+ > Note: Undici supports both options and chained open calls, such as `await lUndici.open('https://example.com/file').follow().timeout(60).save(filePath).request()`; `filePath` is a caller-provided local file path.
114
+
115
+ ### Easy-to-use Db library
116
+
117
+ A wide range of useful interfaces makes it easy to select the data you need from a database. In the following controller method snippets, `db` is a database connection pool, and `mOrder` and `mUser` are application-defined models:
118
+
119
+ ```typescript
120
+ const query = mOrder.where<mOrder>(db, {
121
+ 'state': '1',
122
+ }, { 'ctr': this }).by('id', 'DESC').page(10, 1);
123
+ const list = await query.all();
124
+ if (list === false) {
125
+ return [0, 'Query failed.'];
126
+ }
127
+ const count = list.length;
128
+ const total = await query.total();
129
+ ```
130
+
131
+ Get a user:
132
+
133
+ ```typescript
134
+ const user = await mUser.select<mUser>(db, ['id', 'user'], { 'ctr': this }).filter([
135
+ ['time_add', '>=', '1583405134']
136
+ ]).first();
137
+ ```
138
+
139
+ ### XSRF checks
140
+
141
+ For data-changing endpoints that rely on browser session cookies, use `_valibotx` to validate input and check XSRF, preventing cross-site request forgery. Pages generate a token with `_enabledXsrf()` and submit it as `_xsrf`; read-only endpoints use `_valibot`.
142
+
143
+ ### QR code login
144
+
145
+ The Scan library makes QR code login easy to implement.
146
+
147
+ ### Reverse proxy
148
+
149
+ Use the Undici library’s `rproxy` method with the current controller and a route-prefix mapping to implement a reverse proxy.
150
+
151
+ #### More features await your exploration
152
+
153
+ ## Code examples
154
+
155
+ ### Generate a random 16-digit string
156
+
157
+ ```typescript
158
+ import * as lCore from '@maiyunnet/kebab/lib/core.js';
159
+
160
+ const str = lCore.random(16, lCore.RANDOM_N);
161
+ ```
162
+
163
+ ### Generate a CAPTCHA image
164
+
165
+ ```typescript
166
+ import * as lCaptcha from '@maiyunnet/kebab/lib/captcha.js';
167
+
168
+ const captcha = lCaptcha.get(400, 100);
169
+ const svg = captcha.getBuffer();
170
+ const phrase = captcha.getPhrase();
171
+ ```
172
+
173
+ `getBuffer()` returns an SVG string; `phrase` is the corresponding CAPTCHA text, which should be stored on the server for subsequent verification.
174
+
175
+ ### Get a list
176
+
177
+ ```typescript
178
+ const userList = await mUser.where<mUser>(db, [
179
+ ['state', '!=', '0'],
180
+ {
181
+ 'type': ['1', '2', '3'],
182
+ 'is_lock': '0',
183
+ },
184
+ ], { 'ctr': this }).all();
185
+ ```
186
+
187
+ > Note: Values in query conditions are passed through parameter binding. Handwritten SQL should also bind user input, and dynamic table and column names should be restricted to trusted values.
188
+
189
+ ### Automatic table prefixes and identifier quoting with Sql
190
+
191
+ ```typescript
192
+ import * as lSql from '@maiyunnet/kebab/lib/sql.js';
193
+
194
+ const sql = lSql.get({ 'service': lSql.ESERVICE.MYSQL, 'pre': 'test' });
195
+ sql.select(['SUM(user.age) age'], 'order').leftJoin('user', { 'order.user_id': lSql.column('user.id') });
196
+ const statement = sql.getSql();
197
+ ```
198
+
199
+ The following output is for MySQL with the `test_` table prefix; PostgreSQL uses schemas and double quotes:
200
+
201
+ ```sql
202
+ SELECT SUM(`test_user`.`age`) AS `age` FROM `test_order` LEFT JOIN `test_user` ON `test_order`.`user_id` = `test_user`.`id`
203
+ ```
204
+
205
+ ### Localization
206
+
207
+ In the following controller method snippet, `lang` is a validated language code:
208
+
209
+ ```typescript
210
+ if (!await this._loadLocale(lang, 'test')) {
211
+ return 'Could not load locale.';
212
+ }
213
+ return this._l('copy');
214
+ ```
215
+
216
+ Depending on the value of lang, the output will be Copy, 复制, 複製, コピー, etc., configured in the site’s /data/locale/ directory.
217
+
218
+ ### Data validation
219
+
220
+ New endpoints use Valibot to validate strings, numbers, value ranges and regular expressions. On success, use `output` to obtain the converted data. Define rules in an application module for reuse, such as `lib/schema/input.ts`:
221
+
222
+ ```typescript
223
+ import * as lCore from '@maiyunnet/kebab/lib/core.js';
224
+
225
+ const v = lCore.v;
226
+ export const inputSchema = v.strictObject({
227
+ 'he': v.pipe(v.string(), v.nonEmpty()),
228
+ 'num': v.pipe(v.string(), v.toNumber(), v.gtValue(10)),
229
+ 'reg': v.pipe(v.string(), v.regex(/^[A-CX-Z5-7]+$/)),
230
+ 'arr': v.picklist(['a', 'x', 'hehe']),
231
+ });
232
+ ```
233
+
234
+ Import the rules in the `ctr/main.ts` controller and validate within a method:
235
+
236
+ ```typescript
237
+ import * as lInputSchema from '../lib/schema/input.js';
238
+
239
+ const parsed = this._valibot(lInputSchema.inputSchema, this._post);
240
+ if (!parsed.success) {
241
+ return parsed.response;
242
+ }
243
+ return [1, parsed.output];
244
+ ```
245
+
246
+ Use `_valibotx` instead for data-changing endpoints that rely on browser session cookies. See the [quick start](doc/sc/quick-start.md#使用-valibot-进行类型安全校验) for multilingual messages and XSRF usage, and `/test/ctr-valibot` for a working example.
247
+
248
+ ### Other examples
249
+
250
+ Visit /test/ to see more examples.
251
+
252
+ ## License
253
+
254
+ This framework is licensed under [Apache-2.0](./LICENSE).