wooks 0.0.1-beta.9 → 0.2.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
@@ -3,225 +3,45 @@
3
3
  **!!! This is work-in-progress library, breaking changes are expected !!!**
4
4
 
5
5
  <p align="center">
6
- <img src="./docs/icon.png" width="128px"><br>
7
- <a href="https://github.com/prostojs/wooks/blob/main/LICENSE">
6
+ <img src="../../logo.png" width="128px"><br>
7
+ <a href="https://github.com/wooksjs/wooksjs/blob/main/LICENSE">
8
8
  <img src="https://img.shields.io/badge/License-MIT-green?style=for-the-badge" />
9
9
  </a>
10
10
  </p>
11
11
 
12
+ Wooks is a Event Processing Framework based on composable (hooks) functions.
12
13
 
13
- Wooks is a Web Application Framework with hooks.
14
+ `wooks` + `@wooksjs/event-http` = Web Application Framework with hooks.
14
15
 
15
16
  As an alternative for `express` and `fastify`, `wooks` brings the whole different approach for processing http requests.
16
17
  It utilizes such a technique as you can see in React Hooks or Vue Composables. It has only a dependency on [@prostojs/router](https://github.com/prostojs/router) (an alternative to `find-my-way` used by `fastify`) which is a very fast (see benchmarks [here](https://github.com/prostojs/router-benchmark)) and robust URI router.
17
18
 
18
- `wooks` supports cookie parsing, proxy and serving files out of the box with no impact on performance.
19
+ ### HTTP Composables packs:
19
20
 
20
- The main ideas behind wooks are:
21
-
22
- 1. Never mutate request object (`req`). Accumulate a request context in a separate object(s) instead;
23
- 2. Never parse anything (cookies, body) before it is really requested by the request handler;
24
- 3. Get rid of complex predefined data objects containing everything (cookies, headers, body, parsed body etc.) and use composable functions (hooks) instead;
25
- 4. Get rid of tons of dependencies (middlewares) and implement everything that is needed for web app in a simple way.
26
-
27
- `wooks` uses [@wooksjs/composables](https://github.com/wooksjs/composables) under the hood.
28
-
29
- ### Official Composables packs:
30
-
31
- - [@wooksjs/body](https://github.com/wooksjs/body) - to parse body
32
- - [@wooksjs/serve-file](https://github.com/wooksjs/serve-file) - to serve static files
33
- - [@wooksjs/proxy](https://github.com/wooksjs/proxy) - to proxy requests
34
-
35
- ## Quick Start
36
-
37
- ```js
38
- import { Wooks } from 'wooks'
39
- // commonjs
40
- // const { Wooks } = require('wooks')
41
-
42
- const app = new Wooks()
43
-
44
- app.get('test', () => {
45
- return { message: 'hello world!' }
46
- })
47
-
48
- app.listen(3000, () => { console.log('Wooks Server is up on port 3000') })
49
- ```
21
+ - [@wooksjs/event-http](https://github.com/wooksjs/wooksjs/tree/main/packages/event-http) - HTTP event package with core functionality
22
+ - [@wooksjs/http-body](https://github.com/wooksjs/wooksjs/tree/main/packages/http-body) - to parse body
23
+ - [@wooksjs/http-static](https://github.com/wooksjs/wooksjs/tree/main/packages/http-static) - to serve static files
24
+ - [@wooksjs/http-proxy](https://github.com/wooksjs/wooksjs/tree/main/packages/http-proxy) - to proxy requests
50
25
 
51
26
  ## Install
52
27
 
53
28
  `npm install wooks`
54
29
 
55
- ## Routes
56
-
57
- It supports static, parametric and wildcard routes with regex expressions (see details in [@prostojs/router](https://github.com/prostojs/router))
58
-
59
- Static route:
60
- ```js
61
- app.get('static/route', () => {})
62
- ```
63
-
64
- Parametric route:
65
- ```js
66
- app.get('parametric/:param1/:param2/...', () => {})
67
- ```
68
-
69
- Wildcard route:
70
- ```js
71
- app.get('wildcard/*', () => {})
72
- ```
73
-
74
- Complex wildcard route (use as many asterisks as you need and even specify a static parts after them):
75
- ```js
76
- app.get('wildcard/start-*/*.html', () => {})
77
- ```
78
-
79
-
80
- ## URL Parameters
81
-
82
- To get access to URL parameters use composable function `useRouteParams`
83
-
84
- ```js
85
- import { useRouteParams } from '@wooksjs/composables'
86
- app.get('parametric/:param1/:param2/...', () => {
87
- const { routeParams, getRouteParam } = useRouteParams()
88
- // presume we had a request on `/parametric/value1/value2`
89
- console.log('param1=' + getRouteParam('param1'))
90
- // prints "param1=value1"
91
- console.log('param2=' + getRouteParam('param2'))
92
- // prints "param2=value2"
93
- console.log(routeParams)
94
- // prints {
95
- // param1: "value1",
96
- // param2: "value2"
97
- // }
98
- })
99
- ```
100
-
101
- ## Query Parameters
102
-
103
- To get access to Query parameters use composable function `useSearchParams`
104
-
105
- ```js
106
- import { useSearchParams } from '@wooksjs/composables'
107
- app.get('with-query', () => {
108
- const { jsonSearchParams, urlSearchParams } = useSearchParams()
109
- // presume we had a request on `/with-query?param1=abc&param2=cde`
110
- console.log('param1=' + urlSearchParams('param1'))
111
- // prints "param1=abc"
112
- console.log('param2=' + urlSearchParams('param2'))
113
- // prints "param1=cde"
114
- console.log(jsonSearchParams)
115
- // prints {
116
- // param1: "abc",
117
- // param2: "cde"
118
- // }
119
- })
120
- ```
121
-
122
- ## Composables
123
-
124
- [More details on how to use composables here](https://github.com/wooksjs/composables)
125
-
126
-
127
- ## Error Handling
128
- All the exeptions occured in handler are cought by the framework and interpreted as Server Error 500.
129
-
130
-
131
- ```js
132
- app.get('error', () => {
133
- throw new Error('Some Error')
134
- // A call of this endpoint will result in
135
- // 500 Internal Server Error
136
- // "Some Error"
137
- })
138
- ```
139
-
140
- By default the Error Handler renders the response according to the `Accept` request header:
141
- - if it accepts 'application/json' then the response will be in JSON format
142
- - else if it accepts 'text/html' then the response will be in HTML format
143
- - else if it accepts 'text/plain' then the response will be rendered in a plain text
144
- - else the response will be in JSON format anyways
30
+ ## Quick Start with a Web App
145
31
 
146
- It's possible to return your own error:
32
+ `npm install wooks @wooksjs/event-http`
147
33
 
148
34
  ```js
149
- import { WooksError } from '@wooksjs/composables'
150
- app.get('error', () => {
151
- throw new WooksError('429', 'My Description')
152
- // A call of this endpoint will result in
153
- // 429 Too Many Requests
154
- // "My Description"
155
- })
156
- ```
157
-
158
- In this case if you have an alternative (fallback) handler for the same route the error may not occure, the next handler will be called instead.
159
-
160
- As an alternative you may not throw the error but return its instance:
161
-
162
- ```js
163
- import { WooksError } from '@wooksjs/composables'
164
- app.get('error', () => {
165
- return new WooksError('429', 'My Description')
166
- // A call of this endpoint will result in
167
- // 429 Too Many Requests
168
- // "My Description"
169
- })
170
- ```
171
-
172
- In this case if you have an alternative (fallback) handler for the same route the error will occure anyways as you explicitly return its instance.
173
-
174
- ## Fallback Handler
35
+ import { useRouteParams } from 'wooks'
36
+ import { createHttpApp } from '@wooksjs/event-http'
175
37
 
176
- It's possible to assign several handlers for the same route. Every next handler will work as a fallback for the previous one.
38
+ const app = createHttpApp()
177
39
 
178
- The fallback handler is called only when exception is thrown out of the previous handler.
40
+ app.on('GET', 'hello/:name', () => `Hello ${ useRouteParams().get('name') }!`)
179
41
 
180
- If the previous handler returns an Error Instance then the fallback handler won't be called.
42
+ // shortcuts for some methods are supported:
43
+ // app.get('hello/:name', () => `Hello ${ useRouteParams().get('name') }!`)
181
44
 
182
- For example you serve files, but for some 'not found' files you want to do something else:
183
-
184
- ```js
185
- import { Wooks, useRouteParams } from '@wooksjs/composables'
186
- import { serveFile } from '@wooksjs/serve-file'
187
- const app = new Wooks()
188
-
189
- app.get('static/*', () => {
190
- const { getRouteParam } = useRouteParams()
191
- // serveFile will throw 404 error if the file is not found
192
- return serveFile(getRouteParam('*'), { maxAge: '10m' })
193
- })
194
-
195
- app.get('static/*', () => {
196
- // this handler will be called every time the file is not found
197
- return 'Here\'s my fallback response'
198
- })
199
-
200
- app.listen(3000)
201
- ```
202
-
203
- In order to prevent the fallback to be invoked you must return an Error Instance explicitly:
204
-
205
- ```js
206
- import { Wooks, useRouteParams } from '@wooksjs/composables'
207
- import { serveFile } from '@wooksjs/serve-file'
208
- const app = new Wooks()
209
-
210
- app.get('static/*', () => {
211
- const { getRouteParam } = useRouteParams()
212
- try {
213
- return serveFile(getRouteParam('*'), { maxAge: '10m' })
214
- }
215
- catch (e) {
216
- // now we catch error and return it explicitly
217
- return e
218
- }
219
- })
220
-
221
- app.get('static/*', () => {
222
- // this handler will be never called now
223
- return 'Here\'s my fallback response which is never (ever) called'
224
- })
225
-
226
- app.listen(3000)
45
+ app.listen(3000, () => { console.log('Wooks Server is up on port 3000') })
227
46
  ```
47
+ See full documentation [here](https://github.com/wooksjs/wooksjs/tree/main/packages/event-http)
package/dist/index.cjs ADDED
@@ -0,0 +1,58 @@
1
+ 'use strict';
2
+
3
+ var router = require('@prostojs/router');
4
+ var eventCore = require('@wooksjs/event-core');
5
+
6
+ class Wooks {
7
+ constructor() {
8
+ this.router = new router.ProstoRouter({
9
+ silent: true,
10
+ });
11
+ }
12
+ getRouter() {
13
+ return this.router;
14
+ }
15
+ lookup(method, path) {
16
+ var _a, _b;
17
+ const found = this.getRouter().lookup(method, path || '');
18
+ eventCore.useEventContext().store('routeParams').value = ((_a = found === null || found === void 0 ? void 0 : found.ctx) === null || _a === void 0 ? void 0 : _a.params) || {};
19
+ return ((_b = found === null || found === void 0 ? void 0 : found.route) === null || _b === void 0 ? void 0 : _b.handlers) || null;
20
+ }
21
+ on(method, path, handler) {
22
+ return this.router.on(method, path, handler);
23
+ }
24
+ }
25
+ let gWooks;
26
+ function getGlobalWooks() {
27
+ if (!gWooks) {
28
+ gWooks = new Wooks();
29
+ }
30
+ return gWooks;
31
+ }
32
+ class WooksAdapterBase {
33
+ constructor(wooks) {
34
+ if (wooks && wooks instanceof WooksAdapterBase) {
35
+ this.wooks = wooks.getWooks();
36
+ }
37
+ else if (wooks && wooks instanceof Wooks) {
38
+ this.wooks = wooks;
39
+ }
40
+ else {
41
+ this.wooks = getGlobalWooks();
42
+ }
43
+ }
44
+ getWooks() {
45
+ return this.wooks;
46
+ }
47
+ on(method, path, handler) {
48
+ return this.wooks.on(method, path, handler);
49
+ }
50
+ }
51
+
52
+ Object.defineProperty(exports, 'useRouteParams', {
53
+ enumerable: true,
54
+ get: function () { return eventCore.useRouteParams; }
55
+ });
56
+ exports.Wooks = Wooks;
57
+ exports.WooksAdapterBase = WooksAdapterBase;
58
+ exports.getGlobalWooks = getGlobalWooks;
@@ -0,0 +1,31 @@
1
+ import { ProstoRouter } from '@prostojs/router';
2
+ import { TProstoRouterPathBuilder } from '@prostojs/router';
3
+
4
+ export declare function getGlobalWooks(): Wooks;
5
+
6
+ export declare type TWooksHandler<ResType = unknown> = () => Promise<ResType> | ResType;
7
+
8
+ export declare interface TWooksOptions {
9
+ }
10
+
11
+ export declare function useRouteParams<T extends object = Record<string, string | string[]>>(): {
12
+ params: T;
13
+ get: <K extends keyof T>(name: K) => T[K];
14
+ };
15
+
16
+ export declare class Wooks {
17
+ protected router: ProstoRouter<TWooksHandler>;
18
+ constructor();
19
+ getRouter(): ProstoRouter<TWooksHandler<unknown>>;
20
+ lookup(method: string, path: string): TWooksHandler<unknown>[] | null;
21
+ on<ResType = unknown, ParamsType = Record<string, string | string[]>>(method: string, path: string, handler: TWooksHandler<ResType>): TProstoRouterPathBuilder<ParamsType>;
22
+ }
23
+
24
+ export declare class WooksAdapterBase {
25
+ protected wooks: Wooks;
26
+ constructor(wooks?: Wooks | WooksAdapterBase);
27
+ getWooks(): Wooks;
28
+ on<ResType = unknown, ParamsType = Record<string, string | string[]>>(method: string, path: string, handler: TWooksHandler<ResType>): TProstoRouterPathBuilder<ParamsType>;
29
+ }
30
+
31
+ export { }
package/dist/index.mjs ADDED
@@ -0,0 +1,51 @@
1
+ import { ProstoRouter } from '@prostojs/router';
2
+ import { useEventContext } from '@wooksjs/event-core';
3
+ export { useRouteParams } from '@wooksjs/event-core';
4
+
5
+ class Wooks {
6
+ constructor() {
7
+ this.router = new ProstoRouter({
8
+ silent: true,
9
+ });
10
+ }
11
+ getRouter() {
12
+ return this.router;
13
+ }
14
+ lookup(method, path) {
15
+ var _a, _b;
16
+ const found = this.getRouter().lookup(method, path || '');
17
+ useEventContext().store('routeParams').value = ((_a = found === null || found === void 0 ? void 0 : found.ctx) === null || _a === void 0 ? void 0 : _a.params) || {};
18
+ return ((_b = found === null || found === void 0 ? void 0 : found.route) === null || _b === void 0 ? void 0 : _b.handlers) || null;
19
+ }
20
+ on(method, path, handler) {
21
+ return this.router.on(method, path, handler);
22
+ }
23
+ }
24
+ let gWooks;
25
+ function getGlobalWooks() {
26
+ if (!gWooks) {
27
+ gWooks = new Wooks();
28
+ }
29
+ return gWooks;
30
+ }
31
+ class WooksAdapterBase {
32
+ constructor(wooks) {
33
+ if (wooks && wooks instanceof WooksAdapterBase) {
34
+ this.wooks = wooks.getWooks();
35
+ }
36
+ else if (wooks && wooks instanceof Wooks) {
37
+ this.wooks = wooks;
38
+ }
39
+ else {
40
+ this.wooks = getGlobalWooks();
41
+ }
42
+ }
43
+ getWooks() {
44
+ return this.wooks;
45
+ }
46
+ on(method, path, handler) {
47
+ return this.wooks.on(method, path, handler);
48
+ }
49
+ }
50
+
51
+ export { Wooks, WooksAdapterBase, getGlobalWooks };
package/package.json CHANGED
@@ -1,30 +1,22 @@
1
1
  {
2
2
  "name": "wooks",
3
- "version": "0.0.1-beta.9",
4
- "description": "Web Application Framework with hooks",
5
- "main": "index.js",
6
- "module": "dist/wooks.esm-bundler.js",
7
- "types": "dist/wooks.d.ts",
3
+ "version": "0.2.1",
4
+ "description": "wooks",
5
+ "main": "dist/index.cjs",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
8
  "files": [
9
- "index.js",
10
9
  "dist"
11
10
  ],
12
- "scripts": {
13
- "build": "node ./scripts/build",
14
- "release": "node ./scripts/release",
15
- "test": "jest --runInBand",
16
- "test:cov": "jest --runInBand --coverage",
17
- "lint": "eslint --ext .ts src/**/**.ts",
18
- "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s",
19
- "version": "conventional-changelog -p angular -i CHANGELOG.md -s && git add CHANGELOG.md"
20
- },
21
11
  "repository": {
22
12
  "type": "git",
23
- "url": "git+https://github.com/wooksjs/wooks.git"
13
+ "url": "git+https://github.com/wooksjs/wooksjs.git",
14
+ "directory": "packages/wooks"
24
15
  },
25
16
  "keywords": [
26
17
  "http",
27
18
  "wooks",
19
+ "composables",
28
20
  "web",
29
21
  "framework",
30
22
  "app",
@@ -33,60 +25,14 @@
33
25
  "restful",
34
26
  "prostojs"
35
27
  ],
36
- "buildOptions": {
37
- "formats": [
38
- "esm-bundler",
39
- "cjs"
40
- ],
41
- "filename": "wooks"
42
- },
43
- "dependencies": {
44
- "@prostojs/router": "^0.0.14",
45
- "@wooksjs/composables": "^0.0.1-alpha.12"
46
- },
47
- "gitHooks": {
48
- "commit-msg": "node scripts/verifyCommit.js"
49
- },
50
28
  "author": "Artem Maltsev",
51
29
  "license": "MIT",
52
30
  "bugs": {
53
- "url": "https://github.com/wooksjs/wooks/issues"
31
+ "url": "https://github.com/wooksjs/wooksjs/issues"
32
+ },
33
+ "dependencies": {
34
+ "@prostojs/router": "^0.0.16",
35
+ "@wooksjs/event-core": "0.2.1"
54
36
  },
55
- "homepage": "https://github.com/wooksjs/wooks#readme",
56
- "devDependencies": {
57
- "@microsoft/api-extractor": "^7.15.1",
58
- "@prostojs/dye": "^0.3.0",
59
- "@rollup/plugin-commonjs": "^23.0.2",
60
- "@rollup/plugin-node-resolve": "^15.0.1",
61
- "@rollup/plugin-replace": "^5.0.1",
62
- "@types/jest": "^29.2.0",
63
- "@types/node": "^18.11.0",
64
- "@types/node-fetch": "^2.6.2",
65
- "@typescript-eslint/eslint-plugin": "^5.42.0",
66
- "@typescript-eslint/parser": "^5.0.0",
67
- "@wooksjs/body": "^0.0.1-alpha.4",
68
- "@wooksjs/proxy": "^0.0.1-alpha.1",
69
- "@wooksjs/serve-file": "^0.0.1-alpha.2",
70
- "brotli": "^1.3.2",
71
- "conventional-changelog": "^3.1.24",
72
- "conventional-changelog-cli": "^2.1.1",
73
- "enquirer": "^2.3.6",
74
- "eslint": "^7.32.0",
75
- "eslint-config-prettier": "^8.3.0",
76
- "eslint-plugin-import": "^2.24.2",
77
- "execa": "^5.1.1",
78
- "fs-extra": "^10.0.0",
79
- "jest": "^29.2.2",
80
- "jiti": "^1.16.0",
81
- "minimist": "^1.2.6",
82
- "rollup": "^2.0.0",
83
- "rollup-plugin-terser": "^7.0.2",
84
- "rollup-plugin-typescript2": "^0.34.1",
85
- "semver": "^7.3.5",
86
- "ts-jest": "^29.0.3",
87
- "tslib": "^2.4.1",
88
- "typescript": "^4.8.4",
89
- "yorkie": "^2.0.0",
90
- "zlib": "^1.0.5"
91
- }
37
+ "homepage": "https://github.com/wooksjs/wooksjs/tree/main/packages/wooks#readme"
92
38
  }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2022 prostojs
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=e2e.spec.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"e2e.spec.d.ts","sourceRoot":"","sources":["../../src/e2e.spec.ts"],"names":[],"mappings":""}
@@ -1,7 +0,0 @@
1
- /// <reference types="node" />
2
- import { RequestListener, Server } from 'http';
3
- export interface THttpOptions {
4
- port: number;
5
- }
6
- export declare function createServer(opts: THttpOptions, cb: RequestListener, hostname?: string, onListen?: () => void): Server;
7
- //# sourceMappingURL=http.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../src/http.ts"],"names":[],"mappings":";AAAA,OAAa,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAEpD,MAAM,WAAW,YAAY;IACzB,IAAI,EAAE,MAAM,CAAA;CACf;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,YAAY,EAAE,EAAE,EAAE,eAAe,EAAE,QAAQ,CAAC,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,IAAI,GAAG,MAAM,CAStH"}
@@ -1,3 +0,0 @@
1
- export * from './wooks';
2
- export { TWooksOptions, TWooksHandler } from './types';
3
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAA;AAEvB,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA"}
@@ -1,5 +0,0 @@
1
- import { BaseWooksResponse } from '@wooksjs/composables';
2
- export interface TWooksOptions {
3
- }
4
- export declare type TWooksHandler<ResType = unknown> = () => Promise<ResType> | ResType | Error | Promise<Error> | BaseWooksResponse<ResType> | Promise<BaseWooksResponse<ResType>>;
5
- //# sourceMappingURL=types.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAA;AAExD,MAAM,WAAW,aAAa;CAE7B;AAED,oBAAY,aAAa,CAAC,OAAO,GAAG,OAAO,IAAI,MACxC,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,GAAG,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,iBAAiB,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC,CAAA"}
@@ -1,2 +0,0 @@
1
- export declare const banner: () => string;
2
- //# sourceMappingURL=banner.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"banner.d.ts","sourceRoot":"","sources":["../../../src/utils/banner.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,MAAM,cAA8F,CAAA"}
@@ -1,5 +0,0 @@
1
- export declare function log(text: string): void;
2
- export declare function logBright(text: string): void;
3
- export declare function warn(text: string): void;
4
- export declare function logError(error: string): void;
5
- //# sourceMappingURL=log.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"log.d.ts","sourceRoot":"","sources":["../../../src/utils/log.ts"],"names":[],"mappings":"AAGA,wBAAgB,GAAG,CAAC,IAAI,EAAE,MAAM,QAE/B;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,QAErC;AAED,wBAAgB,IAAI,CAAC,IAAI,EAAE,MAAM,QAEhC;AAED,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,QAErC"}
@@ -1,2 +0,0 @@
1
- export declare function panic(error: string): Error;
2
- //# sourceMappingURL=panic.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"panic.d.ts","sourceRoot":"","sources":["../../../src/utils/panic.ts"],"names":[],"mappings":"AAEA,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,SAGlC"}
@@ -1,32 +0,0 @@
1
- /// <reference types="node" />
2
- import { ProstoRouter, THttpMethod, TProstoLookupResult, TProstoParamsType } from '@prostojs/router';
3
- import { IncomingMessage, Server, ServerResponse } from 'http';
4
- import { TWooksHandler, TWooksOptions } from './types';
5
- export declare class Wooks {
6
- private options?;
7
- protected router: ProstoRouter<TWooksHandler>;
8
- protected server?: Server;
9
- protected responder: {
10
- createResponse: <T = unknown>(data: T) => import("@wooksjs/composables").BaseWooksResponse<T | import("@wooksjs/composables").TWooksErrorBodyExt> | null;
11
- respond: (data: unknown) => Promise<unknown> | undefined;
12
- };
13
- protected _uncoughtExceptionHandler: (error: Error) => void;
14
- constructor(options?: TWooksOptions | undefined);
15
- getRouter(): ProstoRouter<TWooksHandler<unknown>>;
16
- listen(port: number): Promise<void>;
17
- listen(port: number, cb: () => void): Promise<void>;
18
- listen(port: number, hostname: string): Promise<void>;
19
- listen(port: number, hostname: string, cb: () => void): Promise<void>;
20
- close(): Promise<unknown>;
21
- protected processRequest(req: IncomingMessage, res: ServerResponse): void;
22
- protected processHandlers(req: IncomingMessage, res: ServerResponse, found: TProstoLookupResult<TWooksHandler>): Promise<void>;
23
- protected printError(expl: string, e: Error): void;
24
- protected respond(data: unknown): void;
25
- get<ResType = unknown, ParamsType = TProstoParamsType>(path: string, handler: TWooksHandler<ResType>): import("@prostojs/router").TProstoRouterPathBuilder<ParamsType>;
26
- post<ResType = unknown, ParamsType = TProstoParamsType>(path: string, handler: TWooksHandler<ResType>): import("@prostojs/router").TProstoRouterPathBuilder<ParamsType>;
27
- put<ResType = unknown, ParamsType = TProstoParamsType>(path: string, handler: TWooksHandler<ResType>): import("@prostojs/router").TProstoRouterPathBuilder<ParamsType>;
28
- delete<ResType = unknown, ParamsType = TProstoParamsType>(path: string, handler: TWooksHandler<ResType>): import("@prostojs/router").TProstoRouterPathBuilder<ParamsType>;
29
- patch<ResType = unknown, ParamsType = TProstoParamsType>(path: string, handler: TWooksHandler<ResType>): import("@prostojs/router").TProstoRouterPathBuilder<ParamsType>;
30
- on<ResType = unknown, ParamsType = TProstoParamsType>(method: THttpMethod | '*', path: string, handler: TWooksHandler<ResType>): import("@prostojs/router").TProstoRouterPathBuilder<ParamsType>;
31
- }
32
- //# sourceMappingURL=wooks.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"wooks.d.ts","sourceRoot":"","sources":["../../src/wooks.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAA;AACpG,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,MAAM,CAAA;AAG9D,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAItD,qBAAa,KAAK;IASF,OAAO,CAAC,OAAO,CAAC;IAR5B,SAAS,CAAC,MAAM,EAAE,YAAY,CAAC,aAAa,CAAC,CAAA;IAE7C,SAAS,CAAC,MAAM,CAAC,EAAE,MAAM,CAAA;IAEzB,SAAS,CAAC,SAAS;;;MAAyB;IAE5C,SAAS,CAAC,yBAAyB,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAA;gBAEvC,OAAO,CAAC,2BAAe;IAOpC,SAAS;IAIT,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAEnC,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAEnD,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAErD,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IA2BrE,KAAK;IAUZ,SAAS,CAAC,cAAc,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,cAAc;cA0BlD,eAAe,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,cAAc,EAAE,KAAK,EAAE,mBAAmB,CAAC,aAAa,CAAC;IA0BpH,SAAS,CAAC,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC,EAAE,KAAK;IAO3C,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO;IAM/B,GAAG,CAAC,OAAO,GAAG,OAAO,EAAE,UAAU,GAAG,iBAAiB,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,CAAC,OAAO,CAAC;IAKpG,IAAI,CAAC,OAAO,GAAG,OAAO,EAAE,UAAU,GAAG,iBAAiB,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,CAAC,OAAO,CAAC;IAIrG,GAAG,CAAC,OAAO,GAAG,OAAO,EAAE,UAAU,GAAG,iBAAiB,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,CAAC,OAAO,CAAC;IAIpG,MAAM,CAAC,OAAO,GAAG,OAAO,EAAE,UAAU,GAAG,iBAAiB,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,CAAC,OAAO,CAAC;IAIvG,KAAK,CAAC,OAAO,GAAG,OAAO,EAAE,UAAU,GAAG,iBAAiB,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,CAAC,OAAO,CAAC;IAItG,EAAE,CAAC,OAAO,GAAG,OAAO,EAAE,UAAU,GAAG,iBAAiB,EAAE,MAAM,EAAE,WAAW,GAAG,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,CAAC,OAAO,CAAC;CAGjI"}
@@ -1,158 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var router = require('@prostojs/router');
6
- var composables = require('@wooksjs/composables');
7
- var http = require('http');
8
-
9
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
10
-
11
- var http__default = /*#__PURE__*/_interopDefaultLegacy(http);
12
-
13
- function createServer(opts, cb, hostname, onListen) {
14
- const server = http__default.createServer(cb);
15
- if (hostname) {
16
- server.listen(opts.port, hostname, onListen);
17
- }
18
- else {
19
- server.listen(opts.port, onListen);
20
- }
21
- return server;
22
- }
23
-
24
- const banner = () => `[wooks][${new Date().toISOString().replace('T', ' ').replace(/\.\d{3}z$/i, '')}] `;
25
-
26
- function logError(error) {
27
- console.error('' + '' + banner() + error + '');
28
- }
29
-
30
- function panic(error) {
31
- logError(error);
32
- return new Error(error);
33
- }
34
-
35
- class Wooks {
36
- options;
37
- router;
38
- server;
39
- responder = composables.createWooksResponder();
40
- _uncoughtExceptionHandler;
41
- constructor(options) {
42
- this.options = options;
43
- this.router = new router.ProstoRouter();
44
- this._uncoughtExceptionHandler = ((err) => {
45
- this.printError('Uncought exception: ', err);
46
- }).bind(this);
47
- }
48
- getRouter() {
49
- return this.router;
50
- }
51
- listen(port, hostname, cb) {
52
- return new Promise((resolve, reject) => {
53
- const myCb = () => {
54
- const fn = typeof hostname === 'function' ? hostname : cb;
55
- process.on('uncaughtException', this._uncoughtExceptionHandler);
56
- if (fn) {
57
- fn();
58
- }
59
- this.server?.off('error', reject);
60
- resolve();
61
- };
62
- try {
63
- this.server = createServer({
64
- port,
65
- }, this.processRequest.bind(this), typeof hostname === 'string' ? hostname : '', myCb);
66
- this.server?.on('error', reject);
67
- }
68
- catch (e) {
69
- reject(e);
70
- }
71
- });
72
- }
73
- close() {
74
- return new Promise((resolve, reject) => {
75
- this.server?.close((err) => {
76
- if (err)
77
- return reject(err);
78
- process.off('uncaughtException', this._uncoughtExceptionHandler);
79
- resolve(this.server);
80
- });
81
- });
82
- }
83
- processRequest(req, res) {
84
- const found = this.router.lookup(req.method, req.url);
85
- const params = found?.ctx?.params || {};
86
- const { restoreCtx, clearCtx } = composables.createWooksCtx({ req, res, params });
87
- if (found) {
88
- this.processHandlers(req, res, found)
89
- .catch((e) => {
90
- this.printError('Internal error, please report: ', e);
91
- restoreCtx();
92
- this.respond(e);
93
- clearCtx();
94
- console.error('' + '' + banner(), e, '');
95
- });
96
- }
97
- else {
98
- this.respond(new composables.WooksError(404));
99
- clearCtx();
100
- }
101
- }
102
- async processHandlers(req, res, found) {
103
- const { restoreCtx, clearCtx } = composables.useWooksCtx();
104
- for (const [i, handler] of found.route.handlers.entries()) {
105
- const isLastHandler = found.route.handlers.length === i + 1;
106
- try {
107
- restoreCtx();
108
- const promise = handler();
109
- clearCtx();
110
- const result = await promise;
111
- restoreCtx();
112
- this.respond(result);
113
- clearCtx();
114
- break;
115
- }
116
- catch (e) {
117
- this.printError('Uncought route handler exception: ' + (req.url || '') + '\n', e);
118
- if (isLastHandler) {
119
- restoreCtx();
120
- this.respond(e);
121
- clearCtx();
122
- }
123
- }
124
- }
125
- }
126
- printError(expl, e) {
127
- if (!(e instanceof composables.WooksError)) {
128
- panic(expl + e.message);
129
- console.error('' + (e.stack || '') + '');
130
- }
131
- }
132
- respond(data) {
133
- void this.responder.respond(data)?.catch((e) => {
134
- this.printError('Uncought response exception:\n', e);
135
- });
136
- }
137
- get(path, handler) {
138
- this.router.on('HEAD', path, handler);
139
- return this.router.on('GET', path, handler);
140
- }
141
- post(path, handler) {
142
- return this.router.on('POST', path, handler);
143
- }
144
- put(path, handler) {
145
- return this.router.on('PUT', path, handler);
146
- }
147
- delete(path, handler) {
148
- return this.router.on('DELETE', path, handler);
149
- }
150
- patch(path, handler) {
151
- return this.router.on('PATCH', path, handler);
152
- }
153
- on(method, path, handler) {
154
- return this.router.on(method, path, handler);
155
- }
156
- }
157
-
158
- exports.Wooks = Wooks;
package/dist/wooks.d.ts DELETED
@@ -1,47 +0,0 @@
1
- /// <reference types="node" />
2
-
3
- import { BaseWooksResponse } from '@wooksjs/composables';
4
- import { IncomingMessage } from 'http';
5
- import { ProstoRouter } from '@prostojs/router';
6
- import { Server } from 'http';
7
- import { ServerResponse } from 'http';
8
- import { THttpMethod } from '@prostojs/router';
9
- import { TProstoLookupResult } from '@prostojs/router';
10
- import { TProstoParamsType } from '@prostojs/router';
11
- import { TProstoRouterPathBuilder } from '@prostojs/router';
12
- import { TWooksErrorBodyExt } from '@wooksjs/composables';
13
-
14
- export declare type TWooksHandler<ResType = unknown> = () => Promise<ResType> | ResType | Error | Promise<Error> | BaseWooksResponse<ResType> | Promise<BaseWooksResponse<ResType>>;
15
-
16
- export declare interface TWooksOptions {
17
- }
18
-
19
- export declare class Wooks {
20
- private options?;
21
- protected router: ProstoRouter<TWooksHandler>;
22
- protected server?: Server;
23
- protected responder: {
24
- createResponse: <T = unknown>(data: T) => BaseWooksResponse<T | TWooksErrorBodyExt> | null;
25
- respond: (data: unknown) => Promise<unknown> | undefined;
26
- };
27
- protected _uncoughtExceptionHandler: (error: Error) => void;
28
- constructor(options?: TWooksOptions | undefined);
29
- getRouter(): ProstoRouter<TWooksHandler<unknown>>;
30
- listen(port: number): Promise<void>;
31
- listen(port: number, cb: () => void): Promise<void>;
32
- listen(port: number, hostname: string): Promise<void>;
33
- listen(port: number, hostname: string, cb: () => void): Promise<void>;
34
- close(): Promise<unknown>;
35
- protected processRequest(req: IncomingMessage, res: ServerResponse): void;
36
- protected processHandlers(req: IncomingMessage, res: ServerResponse, found: TProstoLookupResult<TWooksHandler>): Promise<void>;
37
- protected printError(expl: string, e: Error): void;
38
- protected respond(data: unknown): void;
39
- get<ResType = unknown, ParamsType = TProstoParamsType>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathBuilder<ParamsType>;
40
- post<ResType = unknown, ParamsType = TProstoParamsType>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathBuilder<ParamsType>;
41
- put<ResType = unknown, ParamsType = TProstoParamsType>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathBuilder<ParamsType>;
42
- delete<ResType = unknown, ParamsType = TProstoParamsType>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathBuilder<ParamsType>;
43
- patch<ResType = unknown, ParamsType = TProstoParamsType>(path: string, handler: TWooksHandler<ResType>): TProstoRouterPathBuilder<ParamsType>;
44
- on<ResType = unknown, ParamsType = TProstoParamsType>(method: THttpMethod | '*', path: string, handler: TWooksHandler<ResType>): TProstoRouterPathBuilder<ParamsType>;
45
- }
46
-
47
- export { }
@@ -1,150 +0,0 @@
1
- import { ProstoRouter } from '@prostojs/router';
2
- import { createWooksResponder, createWooksCtx, WooksError, useWooksCtx } from '@wooksjs/composables';
3
- import http from 'http';
4
-
5
- function createServer(opts, cb, hostname, onListen) {
6
- const server = http.createServer(cb);
7
- if (hostname) {
8
- server.listen(opts.port, hostname, onListen);
9
- }
10
- else {
11
- server.listen(opts.port, onListen);
12
- }
13
- return server;
14
- }
15
-
16
- const banner = () => `[wooks][${new Date().toISOString().replace('T', ' ').replace(/\.\d{3}z$/i, '')}] `;
17
-
18
- function logError(error) {
19
- console.error('' + '' + banner() + error + '');
20
- }
21
-
22
- function panic(error) {
23
- logError(error);
24
- return new Error(error);
25
- }
26
-
27
- class Wooks {
28
- options;
29
- router;
30
- server;
31
- responder = createWooksResponder();
32
- _uncoughtExceptionHandler;
33
- constructor(options) {
34
- this.options = options;
35
- this.router = new ProstoRouter();
36
- this._uncoughtExceptionHandler = ((err) => {
37
- this.printError('Uncought exception: ', err);
38
- }).bind(this);
39
- }
40
- getRouter() {
41
- return this.router;
42
- }
43
- listen(port, hostname, cb) {
44
- return new Promise((resolve, reject) => {
45
- const myCb = () => {
46
- const fn = typeof hostname === 'function' ? hostname : cb;
47
- process.on('uncaughtException', this._uncoughtExceptionHandler);
48
- if (fn) {
49
- fn();
50
- }
51
- this.server?.off('error', reject);
52
- resolve();
53
- };
54
- try {
55
- this.server = createServer({
56
- port,
57
- }, this.processRequest.bind(this), typeof hostname === 'string' ? hostname : '', myCb);
58
- this.server?.on('error', reject);
59
- }
60
- catch (e) {
61
- reject(e);
62
- }
63
- });
64
- }
65
- close() {
66
- return new Promise((resolve, reject) => {
67
- this.server?.close((err) => {
68
- if (err)
69
- return reject(err);
70
- process.off('uncaughtException', this._uncoughtExceptionHandler);
71
- resolve(this.server);
72
- });
73
- });
74
- }
75
- processRequest(req, res) {
76
- const found = this.router.lookup(req.method, req.url);
77
- const params = found?.ctx?.params || {};
78
- const { restoreCtx, clearCtx } = createWooksCtx({ req, res, params });
79
- if (found) {
80
- this.processHandlers(req, res, found)
81
- .catch((e) => {
82
- this.printError('Internal error, please report: ', e);
83
- restoreCtx();
84
- this.respond(e);
85
- clearCtx();
86
- console.error('' + '' + banner(), e, '');
87
- });
88
- }
89
- else {
90
- this.respond(new WooksError(404));
91
- clearCtx();
92
- }
93
- }
94
- async processHandlers(req, res, found) {
95
- const { restoreCtx, clearCtx } = useWooksCtx();
96
- for (const [i, handler] of found.route.handlers.entries()) {
97
- const isLastHandler = found.route.handlers.length === i + 1;
98
- try {
99
- restoreCtx();
100
- const promise = handler();
101
- clearCtx();
102
- const result = await promise;
103
- restoreCtx();
104
- this.respond(result);
105
- clearCtx();
106
- break;
107
- }
108
- catch (e) {
109
- this.printError('Uncought route handler exception: ' + (req.url || '') + '\n', e);
110
- if (isLastHandler) {
111
- restoreCtx();
112
- this.respond(e);
113
- clearCtx();
114
- }
115
- }
116
- }
117
- }
118
- printError(expl, e) {
119
- if (!(e instanceof WooksError)) {
120
- panic(expl + e.message);
121
- console.error('' + (e.stack || '') + '');
122
- }
123
- }
124
- respond(data) {
125
- void this.responder.respond(data)?.catch((e) => {
126
- this.printError('Uncought response exception:\n', e);
127
- });
128
- }
129
- get(path, handler) {
130
- this.router.on('HEAD', path, handler);
131
- return this.router.on('GET', path, handler);
132
- }
133
- post(path, handler) {
134
- return this.router.on('POST', path, handler);
135
- }
136
- put(path, handler) {
137
- return this.router.on('PUT', path, handler);
138
- }
139
- delete(path, handler) {
140
- return this.router.on('DELETE', path, handler);
141
- }
142
- patch(path, handler) {
143
- return this.router.on('PATCH', path, handler);
144
- }
145
- on(method, path, handler) {
146
- return this.router.on(method, path, handler);
147
- }
148
- }
149
-
150
- export { Wooks };
package/index.js DELETED
@@ -1,2 +0,0 @@
1
- 'use strict'
2
- module.exports = require('./dist/wooks.cjs.prod.js')