@stonyx/rest-server 0.2.1-alpha.4 → 0.2.1-alpha.6

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/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "stonyx-async",
5
5
  "stonyx-module"
6
6
  ],
7
- "version": "0.2.1-alpha.4",
7
+ "version": "0.2.1-alpha.6",
8
8
  "description": "Rest Server Module for Stonyx Framework",
9
9
  "repository": {
10
10
  "type": "git",
@@ -20,6 +20,11 @@
20
20
  "contributors": [
21
21
  "Stone Costa <stone.costa@synamicd.com>"
22
22
  ],
23
+ "files": [
24
+ "src",
25
+ "config",
26
+ "README.md"
27
+ ],
23
28
  "publishConfig": {
24
29
  "access": "public",
25
30
  "provenance": true
@@ -27,10 +32,10 @@
27
32
  "dependencies": {
28
33
  "cors": "^2.8.5",
29
34
  "express": "^5.1.0",
30
- "stonyx": "0.2.3-beta.4"
35
+ "stonyx": "0.2.3-beta.11"
31
36
  },
32
37
  "devDependencies": {
33
- "@stonyx/utils": "0.2.3-beta.4",
38
+ "@stonyx/utils": "0.2.3-beta.7",
34
39
  "qunit": "^2.24.1",
35
40
  "sinon": "^21.0.0"
36
41
  },
package/src/request.js CHANGED
@@ -59,7 +59,7 @@ export default class Request {
59
59
 
60
60
  if (response === undefined) response = await mainCall(req, getState(req));
61
61
  if (Number.isInteger(response)) return sendStatusResponse(res, response);
62
-
62
+
63
63
  // Handle redirect if set via call state object
64
64
  const { redirect } = getState(req);
65
65
  if (redirect) return res.redirect(redirect);
@@ -1,44 +0,0 @@
1
- # Improvement Opportunities
2
-
3
- ## 1. `new express()` in RestServer constructor
4
-
5
- **File**: `src/main.js`, line 30
6
-
7
- ```js
8
- this.api = new express();
9
- ```
10
-
11
- Express 5 (which this project targets via `"express": "^5.1.0"`) documents calling `express()` as a plain function, not as a constructor with `new`. While `new express()` works in practice because the function returns a new object regardless, it is unconventional and may break if Express ever enforces non-constructor semantics. Consider changing to:
12
-
13
- ```js
14
- this.api = express();
15
- ```
16
-
17
- Note: The `Request` class in `src/request.js` line 26 already uses the correct pattern (`const api = express();` without `new`).
18
-
19
- ## 2. `setupGlobalMiddleware` is `async` but contains no awaits
20
-
21
- **File**: `src/main.js`, lines 63-70
22
-
23
- ```js
24
- async setupGlobalMiddleware() {
25
- const { origin, methods } = config.restServer;
26
-
27
- this.api.use([
28
- cors({ origin, methods }),
29
- express.json()
30
- ]);
31
- }
32
- ```
33
-
34
- The `async` keyword is unnecessary here since the method body contains no `await` expressions and `app.use()` is synchronous. The `async` keyword causes the method to return a `Promise` wrapping `undefined`, but the caller (`setupRouter`) does not `await` it either — it calls `this.setupGlobalMiddleware()` without `await` on line 52. Removing `async` would make the intent clearer.
35
-
36
- ## 3. `logMethod` config option is not used in rest-server source
37
-
38
- **File**: `config/environment.js`, line 16
39
-
40
- ```js
41
- logMethod: 'api'
42
- ```
43
-
44
- The `logMethod` property is defined in the default config but is never referenced anywhere in `src/main.js` or `src/request.js`. It is likely consumed by the Stonyx framework core (`stonyx/log`) for registering a named log method, but this should be verified. If it is indeed framework-level plumbing, consider documenting that it is a Stonyx convention rather than a rest-server feature. If it is unused, consider removing it to reduce config surface area.
@@ -1,150 +0,0 @@
1
- # @stonyx/rest-server — Project Structure
2
-
3
- ## Overview
4
-
5
- REST server module for the Stonyx framework. Provides dynamic route registration from a file directory, built-in CORS/JSON middleware, per-route authorization hooks, and a structured `Request` base class for defining handlers.
6
-
7
- - **Package**: `@stonyx/rest-server` (v0.2.1-beta.1)
8
- - **License**: Apache-2.0
9
- - **Entry point**: `src/main.js`
10
- - **Module type**: ESM (`"type": "module"`)
11
- - **Node version**: v24.13.0 (per `.nvmrc`)
12
- - **Package manager**: pnpm
13
-
14
- ## Architecture
15
-
16
- ### RestServer (src/main.js)
17
-
18
- Singleton class wrapping an Express 5 instance.
19
-
20
- - **Constructor** — enforces singleton via `RestServer.instance`; creates the Express app with `new express()`
21
- - **`init()`** — calls `setupRouter()`, then starts listening on the configured port
22
- - **`setupRouter()`** — calls `setupGlobalMiddleware()`, then uses `forEachFileImport` (from `@stonyx/utils/file`) to dynamically import all files in the configured `dir` and mount each as a route via `mountRoute()`. Optionally registers a `/health` endpoint.
23
- - **`setupGlobalMiddleware()`** — attaches `cors()` and `express.json()` middleware to the Express app
24
- - **`mountRoute(routeClass, { name, options })`** — instantiates the imported Request subclass, wires up the `authorization` middleware if present, calls `registerCalls()`, and mounts the sub-app at `/<filename>`
25
- - **`RestServer.close()`** — static method to close the server
26
-
27
- ### Request (src/request.js)
28
-
29
- Base class for route definitions. Each file in the requests directory exports a class extending `Request`.
30
-
31
- - **Constructor** — creates a child Express instance with `x-powered-by` disabled
32
- - **`handlers`** — instance property: object mapping HTTP methods (`get`, `post`, `put`, `delete`, `patch`) to route-path/handler pairs
33
- - **`auth(req, state)`** — optional hook. Return an integer status code to reject the request; return nothing to allow it through.
34
- - **`authorization(req, res, next)`** — wrapper that calls `auth()` and short-circuits with a status response if it returns a code
35
- - **`registerCalls()`** — iterates `handlers`, registers each route on the child Express instance. Supports:
36
- - Single handler function or array (last element is the main handler, preceding elements are middleware)
37
- - Middleware functions are bound to the class instance and executed in order
38
- - Integer return = status code response (via `sendStatusResponse`)
39
- - Object return = JSON response
40
- - `undefined` return = 200 OK
41
- - Pipe support via `state.pipe` (sets headers and pipes a stream)
42
- - **`Request.getState(req)`** — attaches/retrieves a `__stonyxState` object on the Express request
43
- - **`Request.sendStatusResponse(res, status)`** — sends status with optional custom message from `config.restServer.statusMap`
44
-
45
- Valid HTTP methods (enforced): `get`, `post`, `put`, `delete`, `patch`
46
-
47
- ## Configuration Reference
48
-
49
- From `config/environment.js`. All values are overridable via environment variables.
50
-
51
- | Option | Type | Default | Env Var | Description |
52
- |---------------------|-------------------|-------------------------------|----------------------------|-----------------------------------------------------------------|
53
- | `enableHealthCheck` | **Boolean** | `true` | `REST_HEALTH_CHECK_DISABLE=true` to disable | Registers `GET /health` returning 200 |
54
- | `trustProxy` | **Boolean** | `false` | `REST_TRUST_PROXY=true` to enable | Trust reverse proxy headers (`X-Forwarded-Proto`) for correct protocol detection behind load balancers |
55
- | `origin` | **String** | `'*'` | `REST_CORS_ORIGIN` | CORS allowed origin(s) |
56
- | `methods` | **String** | `'GET,POST,PATCH,PUT,DELETE'` | `REST_CORS_METHODS` | CORS allowed methods |
57
- | `dir` | **String** | `'./requests'` | `REST_REQUEST_PATH` | Directory containing Request class files to mount as routes |
58
- | `port` | **Number/String** | `2666` | `REST_PORT` | Port the REST server listens on |
59
- | `logColor` | **String** | `'yellow'` | — | Console log color for this module (Stonyx logging integration) |
60
- | `logMethod` | **String** | `'api'` | — | Log method name (Stonyx logging integration) |
61
-
62
- Additional config used (not rest-server-specific):
63
- - `config.debug` (top-level Stonyx config) — if truthy, logs errors during route setup
64
- - `config.restServer.statusMap` (optional, no default in environment.js) — maps status codes to custom message strings
65
- - `config.restServer.camelCaseRoutes` (optional, no default in environment.js) — when falsy, passes `rawName: true` to `forEachFileImport` so filenames are used as-is for route paths
66
-
67
- ## Test Structure
68
-
69
- Tests use **QUnit** and run via `stonyx test` (the `npm test` script).
70
-
71
- ### test/config/environment.js
72
- Overrides `restServer.dir` to `'./test/sample/requests'` so tests load sample request classes.
73
-
74
- ### test/unit/request-test.js
75
- Unit tests for `Request` static methods:
76
- - `getState` — creates/returns state object on request
77
- - `sendStatusResponse` — sends status with optional `statusMap` message
78
-
79
- ### test/integration/rest-server-test.js
80
- Integration tests that boot the full server and make HTTP requests:
81
- - 404 for non-existent routes
82
- - `/public` — JSON response, 200 OK default, URL params, middleware (success/failure), `this` binding for handlers and middleware
83
- - `/private` — authenticated success, auth hook rejection (505)
84
- - `/health` — health check endpoint returns 200
85
-
86
- ### test/sample/requests/
87
- Sample Request subclasses used by integration tests:
88
- - `public.js` — `PublicRequest` with various GET handlers demonstrating middleware, params, binding
89
- - `private.js` — `PrivateRequest` with `auth()` hook that rejects `/failure` with 505
90
-
91
- ## CI/CD
92
-
93
- ### .github/workflows/ci.yml
94
- Runs on pull requests to `dev` and `main`. Delegates to shared workflow at `abofs/stonyx-workflows`.
95
-
96
- ### .github/workflows/publish.yml
97
- Publishes to NPM. Triggered by:
98
- - `workflow_dispatch` with version-type selection (patch/minor/major) or custom version
99
- - Pull requests to `main`/`dev`
100
- - Pushes to `main`
101
-
102
- Delegates to `abofs/stonyx-workflows/.github/workflows/npm-publish.yml@main`.
103
-
104
- ## File Structure
105
-
106
- ```
107
- stonyx-rest-server/
108
- ├── .claude/
109
- │ ├── improvements.md
110
- │ └── project-structure.md # this file
111
- ├── .github/
112
- │ └── workflows/
113
- │ ├── ci.yml # PR CI — delegates to shared workflow
114
- │ └── publish.yml # NPM publish — delegates to shared workflow
115
- ├── config/
116
- │ └── environment.js # Default config with env var overrides
117
- ├── src/
118
- │ ├── main.js # RestServer class (singleton, Express wrapper)
119
- │ └── request.js # Request base class (handler registration, auth hook)
120
- ├── test/
121
- │ ├── config/
122
- │ │ └── environment.js # Test config override (dir → test/sample/requests)
123
- │ ├── integration/
124
- │ │ └── rest-server-test.js # Integration tests (QUnit)
125
- │ ├── sample/
126
- │ │ └── requests/
127
- │ │ ├── private.js # Sample private request with auth hook
128
- │ │ └── public.js # Sample public request with middleware demos
129
- │ └── unit/
130
- │ └── request-test.js # Unit tests for Request statics (QUnit)
131
- ├── .gitignore
132
- ├── .npmignore
133
- ├── .nvmrc # Node v24.13.0
134
- ├── LICENSE.md # Apache 2.0
135
- ├── package.json
136
- ├── pnpm-lock.yaml
137
- └── README.md
138
- ```
139
-
140
- ## Dependencies
141
-
142
- ### Runtime
143
- - `cors` ^2.8.5 — CORS middleware
144
- - `express` ^5.1.0 — HTTP framework
145
- - `stonyx` (local link) — Framework core (config, logging)
146
-
147
- ### Dev
148
- - `@stonyx/utils` (local link) — Utility functions (file import, object helpers)
149
- - `qunit` ^2.24.1 — Test framework
150
- - `sinon` ^21.0.0 — Test stubs/spies
@@ -1,16 +0,0 @@
1
- name: CI
2
-
3
- on:
4
- pull_request:
5
- branches: [dev, main]
6
-
7
- concurrency:
8
- group: ci-${{ github.head_ref || github.ref }}
9
- cancel-in-progress: true
10
-
11
- permissions:
12
- contents: read
13
-
14
- jobs:
15
- test:
16
- uses: abofs/stonyx-workflows/.github/workflows/ci.yml@main
@@ -1,51 +0,0 @@
1
- name: Publish to NPM
2
-
3
- on:
4
- repository_dispatch:
5
- types: [cascade-publish]
6
- workflow_dispatch:
7
- inputs:
8
- version-type:
9
- description: 'Version type'
10
- required: true
11
- type: choice
12
- options:
13
- - patch
14
- - minor
15
- - major
16
- custom-version:
17
- description: 'Custom version (optional, overrides version-type)'
18
- required: false
19
- type: string
20
- pull_request:
21
- types: [opened, synchronize, reopened]
22
- branches: [main]
23
- push:
24
- branches: [main]
25
-
26
- concurrency:
27
- group: ${{ github.event_name == 'repository_dispatch' && 'cascade-update' || format('publish-{0}', github.ref) }}
28
- cancel-in-progress: false
29
-
30
- permissions:
31
- contents: write
32
- id-token: write
33
- pull-requests: write
34
-
35
- jobs:
36
- publish:
37
- if: "!contains(github.event.head_commit.message, '[skip ci]')"
38
- uses: abofs/stonyx-workflows/.github/workflows/npm-publish.yml@main
39
- with:
40
- version-type: ${{ github.event.inputs.version-type }}
41
- custom-version: ${{ github.event.inputs.custom-version }}
42
- cascade-source: ${{ github.event.client_payload.source_package || '' }}
43
- secrets: inherit
44
-
45
- cascade:
46
- needs: publish
47
- uses: abofs/stonyx-workflows/.github/workflows/cascade.yml@main
48
- with:
49
- package-name: ${{ needs.publish.outputs.package-name }}
50
- published-version: ${{ needs.publish.outputs.published-version }}
51
- secrets: inherit