@objectstack/express 3.0.2
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/.turbo/turbo-build.log +22 -0
- package/LICENSE +202 -0
- package/README.md +22 -0
- package/dist/index.d.mts +28 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.js +171 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +145 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +30 -0
- package/src/__mocks__/runtime.ts +4 -0
- package/src/express.test.ts +85 -0
- package/src/index.ts +195 -0
- package/tsconfig.json +13 -0
- package/vitest.config.ts +16 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
|
|
2
|
+
> @objectstack/express@3.0.2 build /home/runner/work/spec/spec/packages/adapters/express
|
|
3
|
+
> tsup --config ../../../tsup.config.ts
|
|
4
|
+
|
|
5
|
+
[34mCLI[39m Building entry: src/index.ts
|
|
6
|
+
[34mCLI[39m Using tsconfig: tsconfig.json
|
|
7
|
+
[34mCLI[39m tsup v8.5.1
|
|
8
|
+
[34mCLI[39m Using tsup config: /home/runner/work/spec/spec/tsup.config.ts
|
|
9
|
+
[34mCLI[39m Target: es2020
|
|
10
|
+
[34mCLI[39m Cleaning output folder
|
|
11
|
+
[34mESM[39m Build start
|
|
12
|
+
[34mCJS[39m Build start
|
|
13
|
+
[32mESM[39m [1mdist/index.mjs [22m[32m5.18 KB[39m
|
|
14
|
+
[32mESM[39m [1mdist/index.mjs.map [22m[32m10.75 KB[39m
|
|
15
|
+
[32mESM[39m ⚡️ Build success in 69ms
|
|
16
|
+
[32mCJS[39m [1mdist/index.js [22m[32m6.26 KB[39m
|
|
17
|
+
[32mCJS[39m [1mdist/index.js.map [22m[32m10.80 KB[39m
|
|
18
|
+
[32mCJS[39m ⚡️ Build success in 73ms
|
|
19
|
+
[34mDTS[39m Build start
|
|
20
|
+
[32mDTS[39m ⚡️ Build success in 10934ms
|
|
21
|
+
[32mDTS[39m [1mdist/index.d.mts [22m[32m934.00 B[39m
|
|
22
|
+
[32mDTS[39m [1mdist/index.d.ts [22m[32m934.00 B[39m
|
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute
|
|
108
|
+
must include a readable copy of the attribution notices
|
|
109
|
+
contained within such NOTICE file, excluding those notices
|
|
110
|
+
that do not pertain to any part of the Derivative Works,
|
|
111
|
+
in at least one of the following places: within a NOTICE
|
|
112
|
+
text file distributed as part of the Derivative Works; within
|
|
113
|
+
the Source form or documentation, if provided along with
|
|
114
|
+
the Derivative Works; or, within a display generated by the
|
|
115
|
+
Derivative Works, if and wherever such third-party notices
|
|
116
|
+
normally appear. The contents of the NOTICE file are for
|
|
117
|
+
informational purposes only and do not modify the License.
|
|
118
|
+
You may add Your own attribution notices within Derivative
|
|
119
|
+
Works that You distribute, alongside or as an addendum to
|
|
120
|
+
the NOTICE text from the Work, provided that such additional
|
|
121
|
+
attribution notices cannot be construed as modifying the
|
|
122
|
+
License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 ObjectStack
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# @objectstack/express
|
|
2
|
+
|
|
3
|
+
The official Express adapter for ObjectStack.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
- Standalone Express router integration
|
|
7
|
+
- Full Auth/GraphQL/Metadata/Data/Storage routes
|
|
8
|
+
- AuthPlugin service support with Web Request conversion
|
|
9
|
+
- Middleware mode for attaching kernel to requests
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
import express from 'express';
|
|
15
|
+
import { createExpressRouter } from '@objectstack/express';
|
|
16
|
+
|
|
17
|
+
const app = express();
|
|
18
|
+
app.use(express.json());
|
|
19
|
+
app.use('/api', createExpressRouter({ kernel }));
|
|
20
|
+
|
|
21
|
+
app.listen(3000);
|
|
22
|
+
```
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { Router, Request, Response, NextFunction } from 'express';
|
|
2
|
+
import { ObjectKernel } from '@objectstack/runtime';
|
|
3
|
+
|
|
4
|
+
interface ExpressAdapterOptions {
|
|
5
|
+
kernel: ObjectKernel;
|
|
6
|
+
prefix?: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Creates an Express Router with all ObjectStack route dispatchers.
|
|
10
|
+
* Provides Auth, GraphQL, Metadata, Data, and Storage routes.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import express from 'express';
|
|
15
|
+
* import { createExpressRouter } from '@objectstack/express';
|
|
16
|
+
*
|
|
17
|
+
* const app = express();
|
|
18
|
+
* app.use('/api', createExpressRouter({ kernel }));
|
|
19
|
+
* app.listen(3000);
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
declare function createExpressRouter(options: ExpressAdapterOptions): Router;
|
|
23
|
+
/**
|
|
24
|
+
* Middleware that attaches the ObjectStack kernel to the request.
|
|
25
|
+
*/
|
|
26
|
+
declare function objectStackMiddleware(kernel: ObjectKernel): (req: Request, _res: Response, next: NextFunction) => void;
|
|
27
|
+
|
|
28
|
+
export { type ExpressAdapterOptions, createExpressRouter, objectStackMiddleware };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { Router, Request, Response, NextFunction } from 'express';
|
|
2
|
+
import { ObjectKernel } from '@objectstack/runtime';
|
|
3
|
+
|
|
4
|
+
interface ExpressAdapterOptions {
|
|
5
|
+
kernel: ObjectKernel;
|
|
6
|
+
prefix?: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Creates an Express Router with all ObjectStack route dispatchers.
|
|
10
|
+
* Provides Auth, GraphQL, Metadata, Data, and Storage routes.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import express from 'express';
|
|
15
|
+
* import { createExpressRouter } from '@objectstack/express';
|
|
16
|
+
*
|
|
17
|
+
* const app = express();
|
|
18
|
+
* app.use('/api', createExpressRouter({ kernel }));
|
|
19
|
+
* app.listen(3000);
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
declare function createExpressRouter(options: ExpressAdapterOptions): Router;
|
|
23
|
+
/**
|
|
24
|
+
* Middleware that attaches the ObjectStack kernel to the request.
|
|
25
|
+
*/
|
|
26
|
+
declare function objectStackMiddleware(kernel: ObjectKernel): (req: Request, _res: Response, next: NextFunction) => void;
|
|
27
|
+
|
|
28
|
+
export { type ExpressAdapterOptions, createExpressRouter, objectStackMiddleware };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
createExpressRouter: () => createExpressRouter,
|
|
24
|
+
objectStackMiddleware: () => objectStackMiddleware
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(index_exports);
|
|
27
|
+
var import_express = require("express");
|
|
28
|
+
var import_runtime = require("@objectstack/runtime");
|
|
29
|
+
function createExpressRouter(options) {
|
|
30
|
+
const router = (0, import_express.Router)();
|
|
31
|
+
const dispatcher = new import_runtime.HttpDispatcher(options.kernel);
|
|
32
|
+
const prefix = options.prefix || "/api";
|
|
33
|
+
const sendResult = (result, res) => {
|
|
34
|
+
if (result.handled) {
|
|
35
|
+
if (result.response) {
|
|
36
|
+
if (result.response.headers) {
|
|
37
|
+
Object.entries(result.response.headers).forEach(([k, v]) => res.set(k, v));
|
|
38
|
+
}
|
|
39
|
+
return res.status(result.response.status).json(result.response.body);
|
|
40
|
+
}
|
|
41
|
+
if (result.result) {
|
|
42
|
+
const response = result.result;
|
|
43
|
+
if (response.type === "redirect" && response.url) {
|
|
44
|
+
return res.redirect(response.url);
|
|
45
|
+
}
|
|
46
|
+
if (response.type === "stream" && response.stream) {
|
|
47
|
+
if (response.headers) {
|
|
48
|
+
Object.entries(response.headers).forEach(([k, v]) => res.set(k, v));
|
|
49
|
+
}
|
|
50
|
+
response.stream.pipe(res);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
return res.status(200).json(response);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return res.status(404).json({ success: false, error: { message: "Not Found", code: 404 } });
|
|
57
|
+
};
|
|
58
|
+
const errorResponse = (err, res) => {
|
|
59
|
+
return res.status(err.statusCode || 500).json({
|
|
60
|
+
success: false,
|
|
61
|
+
error: {
|
|
62
|
+
message: err.message || "Internal Server Error",
|
|
63
|
+
code: err.statusCode || 500
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
};
|
|
67
|
+
router.get("/", (_req, res) => {
|
|
68
|
+
res.json({ data: dispatcher.getDiscoveryInfo(prefix) });
|
|
69
|
+
});
|
|
70
|
+
router.all("/auth/{*path}", async (req, res) => {
|
|
71
|
+
try {
|
|
72
|
+
const path = req.params.path;
|
|
73
|
+
const method = req.method;
|
|
74
|
+
const authService = typeof options.kernel.getService === "function" ? options.kernel.getService("auth") : null;
|
|
75
|
+
if (authService && typeof authService.handleRequest === "function") {
|
|
76
|
+
const protocol = req.protocol || "http";
|
|
77
|
+
const host = req.get?.("host") || req.headers?.host || "localhost";
|
|
78
|
+
const url = `${protocol}://${host}${req.originalUrl || req.url}`;
|
|
79
|
+
const headers = new Headers();
|
|
80
|
+
if (req.headers) {
|
|
81
|
+
Object.entries(req.headers).forEach(([k, v]) => {
|
|
82
|
+
if (typeof v === "string") headers.set(k, v);
|
|
83
|
+
else if (Array.isArray(v)) headers.set(k, v.join(", "));
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
const init = { method, headers };
|
|
87
|
+
if (method !== "GET" && method !== "HEAD" && req.body) {
|
|
88
|
+
init.body = JSON.stringify(req.body);
|
|
89
|
+
if (!headers.has("content-type")) {
|
|
90
|
+
headers.set("content-type", "application/json");
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
const webRequest = new Request(url, init);
|
|
94
|
+
const response = await authService.handleRequest(webRequest);
|
|
95
|
+
res.status(response.status);
|
|
96
|
+
response.headers.forEach((v, k) => res.set(k, v));
|
|
97
|
+
const text = await response.text();
|
|
98
|
+
return res.send(text);
|
|
99
|
+
}
|
|
100
|
+
const body = method === "GET" || method === "HEAD" ? {} : req.body || {};
|
|
101
|
+
const result = await dispatcher.handleAuth(path, method, body, { request: req, response: res });
|
|
102
|
+
return sendResult(result, res);
|
|
103
|
+
} catch (err) {
|
|
104
|
+
return errorResponse(err, res);
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
router.post("/graphql", async (req, res) => {
|
|
108
|
+
try {
|
|
109
|
+
const result = await dispatcher.handleGraphQL(req.body, { request: req });
|
|
110
|
+
return res.json(result);
|
|
111
|
+
} catch (err) {
|
|
112
|
+
return errorResponse(err, res);
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
router.all("/meta/{*path}", async (req, res) => {
|
|
116
|
+
try {
|
|
117
|
+
const subPath = "/" + req.params.path;
|
|
118
|
+
const method = req.method;
|
|
119
|
+
const body = method === "PUT" || method === "POST" ? req.body : void 0;
|
|
120
|
+
const result = await dispatcher.handleMetadata(subPath, { request: req }, method, body);
|
|
121
|
+
return sendResult(result, res);
|
|
122
|
+
} catch (err) {
|
|
123
|
+
return errorResponse(err, res);
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
router.all("/meta", async (req, res) => {
|
|
127
|
+
try {
|
|
128
|
+
const method = req.method;
|
|
129
|
+
const body = method === "PUT" || method === "POST" ? req.body : void 0;
|
|
130
|
+
const result = await dispatcher.handleMetadata("", { request: req }, method, body);
|
|
131
|
+
return sendResult(result, res);
|
|
132
|
+
} catch (err) {
|
|
133
|
+
return errorResponse(err, res);
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
router.all("/data/{*path}", async (req, res) => {
|
|
137
|
+
try {
|
|
138
|
+
const subPath = "/" + req.params.path;
|
|
139
|
+
const method = req.method;
|
|
140
|
+
const body = method === "POST" || method === "PATCH" ? req.body : {};
|
|
141
|
+
const result = await dispatcher.handleData(subPath, method, body, req.query, { request: req });
|
|
142
|
+
return sendResult(result, res);
|
|
143
|
+
} catch (err) {
|
|
144
|
+
return errorResponse(err, res);
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
router.all("/storage/{*path}", async (req, res) => {
|
|
148
|
+
try {
|
|
149
|
+
const subPath = "/" + req.params.path;
|
|
150
|
+
const method = req.method;
|
|
151
|
+
const file = req.file || req.files?.file;
|
|
152
|
+
const result = await dispatcher.handleStorage(subPath, method, file, { request: req });
|
|
153
|
+
return sendResult(result, res);
|
|
154
|
+
} catch (err) {
|
|
155
|
+
return errorResponse(err, res);
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
return router;
|
|
159
|
+
}
|
|
160
|
+
function objectStackMiddleware(kernel) {
|
|
161
|
+
return (req, _res, next) => {
|
|
162
|
+
req.objectStack = kernel;
|
|
163
|
+
next();
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
167
|
+
0 && (module.exports = {
|
|
168
|
+
createExpressRouter,
|
|
169
|
+
objectStackMiddleware
|
|
170
|
+
});
|
|
171
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { type Router, type Request, type Response, type NextFunction, Router as createRouter } from 'express';\nimport { type ObjectKernel, HttpDispatcher, HttpDispatcherResult } from '@objectstack/runtime';\n\nexport interface ExpressAdapterOptions {\n kernel: ObjectKernel;\n prefix?: string;\n}\n\n/**\n * Auth service interface with handleRequest method\n */\ninterface AuthService {\n handleRequest(request: globalThis.Request): Promise<globalThis.Response>;\n}\n\n/**\n * Creates an Express Router with all ObjectStack route dispatchers.\n * Provides Auth, GraphQL, Metadata, Data, and Storage routes.\n *\n * @example\n * ```ts\n * import express from 'express';\n * import { createExpressRouter } from '@objectstack/express';\n *\n * const app = express();\n * app.use('/api', createExpressRouter({ kernel }));\n * app.listen(3000);\n * ```\n */\nexport function createExpressRouter(options: ExpressAdapterOptions): Router {\n const router = createRouter();\n const dispatcher = new HttpDispatcher(options.kernel);\n const prefix = options.prefix || '/api';\n\n const sendResult = (result: HttpDispatcherResult, res: Response) => {\n if (result.handled) {\n if (result.response) {\n if (result.response.headers) {\n Object.entries(result.response.headers).forEach(([k, v]) => res.set(k, v as string));\n }\n return res.status(result.response.status).json(result.response.body);\n }\n if (result.result) {\n const response = result.result;\n if (response.type === 'redirect' && response.url) {\n return res.redirect(response.url);\n }\n if (response.type === 'stream' && response.stream) {\n if (response.headers) {\n Object.entries(response.headers).forEach(([k, v]) => res.set(k, v as string));\n }\n response.stream.pipe(res);\n return;\n }\n return res.status(200).json(response);\n }\n }\n return res.status(404).json({ success: false, error: { message: 'Not Found', code: 404 } });\n };\n\n const errorResponse = (err: any, res: Response) => {\n return res.status(err.statusCode || 500).json({\n success: false,\n error: {\n message: err.message || 'Internal Server Error',\n code: err.statusCode || 500,\n },\n });\n };\n\n // --- Discovery ---\n router.get('/', (_req: Request, res: Response) => {\n res.json({ data: dispatcher.getDiscoveryInfo(prefix) });\n });\n\n // --- Auth ---\n router.all('/auth/{*path}', async (req: Request, res: Response) => {\n try {\n const path = (req.params as any).path;\n const method = req.method;\n\n // Try AuthPlugin service first\n const authService = typeof options.kernel.getService === 'function'\n ? options.kernel.getService<AuthService>('auth')\n : null;\n\n if (authService && typeof authService.handleRequest === 'function') {\n const protocol = req.protocol || 'http';\n const host = req.get?.('host') || req.headers?.host || 'localhost';\n const url = `${protocol}://${host}${req.originalUrl || req.url}`;\n const headers = new Headers();\n if (req.headers) {\n Object.entries(req.headers).forEach(([k, v]) => {\n if (typeof v === 'string') headers.set(k, v);\n else if (Array.isArray(v)) headers.set(k, v.join(', '));\n });\n }\n const init: RequestInit = { method, headers };\n if (method !== 'GET' && method !== 'HEAD' && req.body) {\n init.body = JSON.stringify(req.body);\n if (!headers.has('content-type')) {\n headers.set('content-type', 'application/json');\n }\n }\n const webRequest = new Request(url, init);\n const response = await authService.handleRequest(webRequest);\n res.status(response.status);\n response.headers.forEach((v: string, k: string) => res.set(k, v));\n const text = await response.text();\n return res.send(text);\n }\n\n // Fallback to dispatcher\n const body = method === 'GET' || method === 'HEAD' ? {} : req.body || {};\n const result = await dispatcher.handleAuth(path, method, body, { request: req, response: res });\n return sendResult(result, res);\n } catch (err: any) {\n return errorResponse(err, res);\n }\n });\n\n // --- GraphQL ---\n router.post('/graphql', async (req: Request, res: Response) => {\n try {\n const result = await dispatcher.handleGraphQL(req.body, { request: req });\n return res.json(result);\n } catch (err: any) {\n return errorResponse(err, res);\n }\n });\n\n // --- Metadata ---\n router.all('/meta/{*path}', async (req: Request, res: Response) => {\n try {\n const subPath = '/' + (req.params as any).path;\n const method = req.method;\n const body = (method === 'PUT' || method === 'POST') ? req.body : undefined;\n const result = await dispatcher.handleMetadata(subPath, { request: req }, method, body);\n return sendResult(result, res);\n } catch (err: any) {\n return errorResponse(err, res);\n }\n });\n\n router.all('/meta', async (req: Request, res: Response) => {\n try {\n const method = req.method;\n const body = (method === 'PUT' || method === 'POST') ? req.body : undefined;\n const result = await dispatcher.handleMetadata('', { request: req }, method, body);\n return sendResult(result, res);\n } catch (err: any) {\n return errorResponse(err, res);\n }\n });\n\n // --- Data ---\n router.all('/data/{*path}', async (req: Request, res: Response) => {\n try {\n const subPath = '/' + (req.params as any).path;\n const method = req.method;\n const body = (method === 'POST' || method === 'PATCH') ? req.body : {};\n const result = await dispatcher.handleData(subPath, method, body, req.query, { request: req });\n return sendResult(result, res);\n } catch (err: any) {\n return errorResponse(err, res);\n }\n });\n\n // --- Storage ---\n router.all('/storage/{*path}', async (req: Request, res: Response) => {\n try {\n const subPath = '/' + (req.params as any).path;\n const method = req.method;\n const file = (req as any).file || (req as any).files?.file;\n const result = await dispatcher.handleStorage(subPath, method, file, { request: req });\n return sendResult(result, res);\n } catch (err: any) {\n return errorResponse(err, res);\n }\n });\n\n return router;\n}\n\n/**\n * Middleware that attaches the ObjectStack kernel to the request.\n */\nexport function objectStackMiddleware(kernel: ObjectKernel) {\n return (req: Request, _res: Response, next: NextFunction) => {\n (req as any).objectStack = kernel;\n next();\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,qBAAoG;AACpG,qBAAwE;AA4BjE,SAAS,oBAAoB,SAAwC;AAC1E,QAAM,aAAS,eAAAA,QAAa;AAC5B,QAAM,aAAa,IAAI,8BAAe,QAAQ,MAAM;AACpD,QAAM,SAAS,QAAQ,UAAU;AAEjC,QAAM,aAAa,CAAC,QAA8B,QAAkB;AAClE,QAAI,OAAO,SAAS;AAClB,UAAI,OAAO,UAAU;AACnB,YAAI,OAAO,SAAS,SAAS;AAC3B,iBAAO,QAAQ,OAAO,SAAS,OAAO,EAAE,QAAQ,CAAC,CAAC,GAAG,CAAC,MAAM,IAAI,IAAI,GAAG,CAAW,CAAC;AAAA,QACrF;AACA,eAAO,IAAI,OAAO,OAAO,SAAS,MAAM,EAAE,KAAK,OAAO,SAAS,IAAI;AAAA,MACrE;AACA,UAAI,OAAO,QAAQ;AACjB,cAAM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F,CAAC;AAGD,SAAO,IAAI,oBAAoB,OAAO,KAAc,QAAkB;AACpE,QAAI;AACF,YAAM,UAAU,MAAO,IAAI,OAAe;AAC1C,YAAM,SAAS,IAAI;AACnB,YAAM,OAAQ,IAAY,QAAS,IAAY,OAAO;AACtD,YAAM,SAAS,MAAM,WAAW,cAAc,SAAS,QAAQ,MAAM,EAAE,SAAS,IAAI,CAAC;AACrF,aAAO,WAAW,QAAQ,GAAG;AAAA,IAC/B,SAAS,KAAU;AACjB,aAAO,cAAc,KAAK,GAAG;AAAA,IAC/B;AAAA,EACF,CAAC;AAED,SAAO;AACT;AAKO,SAAS,sBAAsB,QAAsB;AAC1D,SAAO,CAAC,KAAc,MAAgB,SAAuB;AAC3D,IAAC,IAAY,cAAc;AAC3B,SAAK;AAAA,EACP;AACF;","names":["createRouter"]}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { Router as createRouter } from "express";
|
|
3
|
+
import { HttpDispatcher } from "@objectstack/runtime";
|
|
4
|
+
function createExpressRouter(options) {
|
|
5
|
+
const router = createRouter();
|
|
6
|
+
const dispatcher = new HttpDispatcher(options.kernel);
|
|
7
|
+
const prefix = options.prefix || "/api";
|
|
8
|
+
const sendResult = (result, res) => {
|
|
9
|
+
if (result.handled) {
|
|
10
|
+
if (result.response) {
|
|
11
|
+
if (result.response.headers) {
|
|
12
|
+
Object.entries(result.response.headers).forEach(([k, v]) => res.set(k, v));
|
|
13
|
+
}
|
|
14
|
+
return res.status(result.response.status).json(result.response.body);
|
|
15
|
+
}
|
|
16
|
+
if (result.result) {
|
|
17
|
+
const response = result.result;
|
|
18
|
+
if (response.type === "redirect" && response.url) {
|
|
19
|
+
return res.redirect(response.url);
|
|
20
|
+
}
|
|
21
|
+
if (response.type === "stream" && response.stream) {
|
|
22
|
+
if (response.headers) {
|
|
23
|
+
Object.entries(response.headers).forEach(([k, v]) => res.set(k, v));
|
|
24
|
+
}
|
|
25
|
+
response.stream.pipe(res);
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
return res.status(200).json(response);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return res.status(404).json({ success: false, error: { message: "Not Found", code: 404 } });
|
|
32
|
+
};
|
|
33
|
+
const errorResponse = (err, res) => {
|
|
34
|
+
return res.status(err.statusCode || 500).json({
|
|
35
|
+
success: false,
|
|
36
|
+
error: {
|
|
37
|
+
message: err.message || "Internal Server Error",
|
|
38
|
+
code: err.statusCode || 500
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
};
|
|
42
|
+
router.get("/", (_req, res) => {
|
|
43
|
+
res.json({ data: dispatcher.getDiscoveryInfo(prefix) });
|
|
44
|
+
});
|
|
45
|
+
router.all("/auth/{*path}", async (req, res) => {
|
|
46
|
+
try {
|
|
47
|
+
const path = req.params.path;
|
|
48
|
+
const method = req.method;
|
|
49
|
+
const authService = typeof options.kernel.getService === "function" ? options.kernel.getService("auth") : null;
|
|
50
|
+
if (authService && typeof authService.handleRequest === "function") {
|
|
51
|
+
const protocol = req.protocol || "http";
|
|
52
|
+
const host = req.get?.("host") || req.headers?.host || "localhost";
|
|
53
|
+
const url = `${protocol}://${host}${req.originalUrl || req.url}`;
|
|
54
|
+
const headers = new Headers();
|
|
55
|
+
if (req.headers) {
|
|
56
|
+
Object.entries(req.headers).forEach(([k, v]) => {
|
|
57
|
+
if (typeof v === "string") headers.set(k, v);
|
|
58
|
+
else if (Array.isArray(v)) headers.set(k, v.join(", "));
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
const init = { method, headers };
|
|
62
|
+
if (method !== "GET" && method !== "HEAD" && req.body) {
|
|
63
|
+
init.body = JSON.stringify(req.body);
|
|
64
|
+
if (!headers.has("content-type")) {
|
|
65
|
+
headers.set("content-type", "application/json");
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const webRequest = new Request(url, init);
|
|
69
|
+
const response = await authService.handleRequest(webRequest);
|
|
70
|
+
res.status(response.status);
|
|
71
|
+
response.headers.forEach((v, k) => res.set(k, v));
|
|
72
|
+
const text = await response.text();
|
|
73
|
+
return res.send(text);
|
|
74
|
+
}
|
|
75
|
+
const body = method === "GET" || method === "HEAD" ? {} : req.body || {};
|
|
76
|
+
const result = await dispatcher.handleAuth(path, method, body, { request: req, response: res });
|
|
77
|
+
return sendResult(result, res);
|
|
78
|
+
} catch (err) {
|
|
79
|
+
return errorResponse(err, res);
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
router.post("/graphql", async (req, res) => {
|
|
83
|
+
try {
|
|
84
|
+
const result = await dispatcher.handleGraphQL(req.body, { request: req });
|
|
85
|
+
return res.json(result);
|
|
86
|
+
} catch (err) {
|
|
87
|
+
return errorResponse(err, res);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
router.all("/meta/{*path}", async (req, res) => {
|
|
91
|
+
try {
|
|
92
|
+
const subPath = "/" + req.params.path;
|
|
93
|
+
const method = req.method;
|
|
94
|
+
const body = method === "PUT" || method === "POST" ? req.body : void 0;
|
|
95
|
+
const result = await dispatcher.handleMetadata(subPath, { request: req }, method, body);
|
|
96
|
+
return sendResult(result, res);
|
|
97
|
+
} catch (err) {
|
|
98
|
+
return errorResponse(err, res);
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
router.all("/meta", async (req, res) => {
|
|
102
|
+
try {
|
|
103
|
+
const method = req.method;
|
|
104
|
+
const body = method === "PUT" || method === "POST" ? req.body : void 0;
|
|
105
|
+
const result = await dispatcher.handleMetadata("", { request: req }, method, body);
|
|
106
|
+
return sendResult(result, res);
|
|
107
|
+
} catch (err) {
|
|
108
|
+
return errorResponse(err, res);
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
router.all("/data/{*path}", async (req, res) => {
|
|
112
|
+
try {
|
|
113
|
+
const subPath = "/" + req.params.path;
|
|
114
|
+
const method = req.method;
|
|
115
|
+
const body = method === "POST" || method === "PATCH" ? req.body : {};
|
|
116
|
+
const result = await dispatcher.handleData(subPath, method, body, req.query, { request: req });
|
|
117
|
+
return sendResult(result, res);
|
|
118
|
+
} catch (err) {
|
|
119
|
+
return errorResponse(err, res);
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
router.all("/storage/{*path}", async (req, res) => {
|
|
123
|
+
try {
|
|
124
|
+
const subPath = "/" + req.params.path;
|
|
125
|
+
const method = req.method;
|
|
126
|
+
const file = req.file || req.files?.file;
|
|
127
|
+
const result = await dispatcher.handleStorage(subPath, method, file, { request: req });
|
|
128
|
+
return sendResult(result, res);
|
|
129
|
+
} catch (err) {
|
|
130
|
+
return errorResponse(err, res);
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
return router;
|
|
134
|
+
}
|
|
135
|
+
function objectStackMiddleware(kernel) {
|
|
136
|
+
return (req, _res, next) => {
|
|
137
|
+
req.objectStack = kernel;
|
|
138
|
+
next();
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
export {
|
|
142
|
+
createExpressRouter,
|
|
143
|
+
objectStackMiddleware
|
|
144
|
+
};
|
|
145
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { type Router, type Request, type Response, type NextFunction, Router as createRouter } from 'express';\nimport { type ObjectKernel, HttpDispatcher, HttpDispatcherResult } from '@objectstack/runtime';\n\nexport interface ExpressAdapterOptions {\n kernel: ObjectKernel;\n prefix?: string;\n}\n\n/**\n * Auth service interface with handleRequest method\n */\ninterface AuthService {\n handleRequest(request: globalThis.Request): Promise<globalThis.Response>;\n}\n\n/**\n * Creates an Express Router with all ObjectStack route dispatchers.\n * Provides Auth, GraphQL, Metadata, Data, and Storage routes.\n *\n * @example\n * ```ts\n * import express from 'express';\n * import { createExpressRouter } from '@objectstack/express';\n *\n * const app = express();\n * app.use('/api', createExpressRouter({ kernel }));\n * app.listen(3000);\n * ```\n */\nexport function createExpressRouter(options: ExpressAdapterOptions): Router {\n const router = createRouter();\n const dispatcher = new HttpDispatcher(options.kernel);\n const prefix = options.prefix || '/api';\n\n const sendResult = (result: HttpDispatcherResult, res: Response) => {\n if (result.handled) {\n if (result.response) {\n if (result.response.headers) {\n Object.entries(result.response.headers).forEach(([k, v]) => res.set(k, v as string));\n }\n return res.status(result.response.status).json(result.response.body);\n }\n if (result.result) {\n const response = result.result;\n if (response.type === 'redirect' && response.url) {\n return res.redirect(response.url);\n }\n if (response.type === 'stream' && response.stream) {\n if (response.headers) {\n Object.entries(response.headers).forEach(([k, v]) => res.set(k, v as string));\n }\n response.stream.pipe(res);\n return;\n }\n return res.status(200).json(response);\n }\n }\n return res.status(404).json({ success: false, error: { message: 'Not Found', code: 404 } });\n };\n\n const errorResponse = (err: any, res: Response) => {\n return res.status(err.statusCode || 500).json({\n success: false,\n error: {\n message: err.message || 'Internal Server Error',\n code: err.statusCode || 500,\n },\n });\n };\n\n // --- Discovery ---\n router.get('/', (_req: Request, res: Response) => {\n res.json({ data: dispatcher.getDiscoveryInfo(prefix) });\n });\n\n // --- Auth ---\n router.all('/auth/{*path}', async (req: Request, res: Response) => {\n try {\n const path = (req.params as any).path;\n const method = req.method;\n\n // Try AuthPlugin service first\n const authService = typeof options.kernel.getService === 'function'\n ? options.kernel.getService<AuthService>('auth')\n : null;\n\n if (authService && typeof authService.handleRequest === 'function') {\n const protocol = req.protocol || 'http';\n const host = req.get?.('host') || req.headers?.host || 'localhost';\n const url = `${protocol}://${host}${req.originalUrl || req.url}`;\n const headers = new Headers();\n if (req.headers) {\n Object.entries(req.headers).forEach(([k, v]) => {\n if (typeof v === 'string') headers.set(k, v);\n else if (Array.isArray(v)) headers.set(k, v.join(', '));\n });\n }\n const init: RequestInit = { method, headers };\n if (method !== 'GET' && method !== 'HEAD' && req.body) {\n init.body = JSON.stringify(req.body);\n if (!headers.has('content-type')) {\n headers.set('content-type', 'application/json');\n }\n }\n const webRequest = new Request(url, init);\n const response = await authService.handleRequest(webRequest);\n res.status(response.status);\n response.headers.forEach((v: string, k: string) => res.set(k, v));\n const text = await response.text();\n return res.send(text);\n }\n\n // Fallback to dispatcher\n const body = method === 'GET' || method === 'HEAD' ? {} : req.body || {};\n const result = await dispatcher.handleAuth(path, method, body, { request: req, response: res });\n return sendResult(result, res);\n } catch (err: any) {\n return errorResponse(err, res);\n }\n });\n\n // --- GraphQL ---\n router.post('/graphql', async (req: Request, res: Response) => {\n try {\n const result = await dispatcher.handleGraphQL(req.body, { request: req });\n return res.json(result);\n } catch (err: any) {\n return errorResponse(err, res);\n }\n });\n\n // --- Metadata ---\n router.all('/meta/{*path}', async (req: Request, res: Response) => {\n try {\n const subPath = '/' + (req.params as any).path;\n const method = req.method;\n const body = (method === 'PUT' || method === 'POST') ? req.body : undefined;\n const result = await dispatcher.handleMetadata(subPath, { request: req }, method, body);\n return sendResult(result, res);\n } catch (err: any) {\n return errorResponse(err, res);\n }\n });\n\n router.all('/meta', async (req: Request, res: Response) => {\n try {\n const method = req.method;\n const body = (method === 'PUT' || method === 'POST') ? req.body : undefined;\n const result = await dispatcher.handleMetadata('', { request: req }, method, body);\n return sendResult(result, res);\n } catch (err: any) {\n return errorResponse(err, res);\n }\n });\n\n // --- Data ---\n router.all('/data/{*path}', async (req: Request, res: Response) => {\n try {\n const subPath = '/' + (req.params as any).path;\n const method = req.method;\n const body = (method === 'POST' || method === 'PATCH') ? req.body : {};\n const result = await dispatcher.handleData(subPath, method, body, req.query, { request: req });\n return sendResult(result, res);\n } catch (err: any) {\n return errorResponse(err, res);\n }\n });\n\n // --- Storage ---\n router.all('/storage/{*path}', async (req: Request, res: Response) => {\n try {\n const subPath = '/' + (req.params as any).path;\n const method = req.method;\n const file = (req as any).file || (req as any).files?.file;\n const result = await dispatcher.handleStorage(subPath, method, file, { request: req });\n return sendResult(result, res);\n } catch (err: any) {\n return errorResponse(err, res);\n }\n });\n\n return router;\n}\n\n/**\n * Middleware that attaches the ObjectStack kernel to the request.\n */\nexport function objectStackMiddleware(kernel: ObjectKernel) {\n return (req: Request, _res: Response, next: NextFunction) => {\n (req as any).objectStack = kernel;\n next();\n };\n}\n"],"mappings":";AAEA,SAAsE,UAAU,oBAAoB;AACpG,SAA4B,sBAA4C;AA4BjE,SAAS,oBAAoB,SAAwC;AAC1E,QAAM,SAAS,aAAa;AAC5B,QAAM,aAAa,IAAI,eAAe,QAAQ,MAAM;AACpD,QAAM,SAAS,QAAQ,UAAU;AAEjC,QAAM,aAAa,CAAC,QAA8B,QAAkB;AAClE,QAAI,OAAO,SAAS;AAClB,UAAI,OAAO,UAAU;AACnB,YAAI,OAAO,SAAS,SAAS;AAC3B,iBAAO,QAAQ,OAAO,SAAS,OAAO,EAAE,QAAQ,CAAC,CAAC,GAAG,CAAC,MAAM,IAAI,IAAI,GAAG,CAAW,CAAC;AAAA,QACrF;AACA,eAAO,IAAI,OAAO,OAAO,SAAS,MAAM,EAAE,KAAK,OAAO,SAAS,IAAI;AAAA,MACrE;AACA,UAAI,OAAO,QAAQ;AACjB,cAAM,WAAW,OAAO;AACxB,YAAI,SAAS,SAAS,cAAc,SAAS,KAAK;AAChD,iBAAO,IAAI,SAAS,SAAS,GAAG;AAAA,QAClC;AACA,YAAI,SAAS,SAAS,YAAY,SAAS,QAAQ;AACjD,cAAI,SAAS,SAAS;AACpB,mBAAO,QAAQ,SAAS,OAAO,EAAE,QAAQ,CAAC,CAAC,GAAG,CAAC,MAAM,IAAI,IAAI,GAAG,CAAW,CAAC;AAAA,UAC9E;AACA,mBAAS,OAAO,KAAK,GAAG;AACxB;AAAA,QACF;AACA,eAAO,IAAI,OAAO,GAAG,EAAE,KAAK,QAAQ;AAAA,MACtC;AAAA,IACF;AACA,WAAO,IAAI,OAAO,GAAG,EAAE,KAAK,EAAE,SAAS,OAAO,OAAO,EAAE,SAAS,aAAa,MAAM,IAAI,EAAE,CAAC;AAAA,EAC5F;AAE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 -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@objectstack/express",
|
|
3
|
+
"version": "3.0.2",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"import": "./dist/index.mjs",
|
|
11
|
+
"require": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"peerDependencies": {
|
|
15
|
+
"express": "^5.1.0",
|
|
16
|
+
"@objectstack/runtime": "3.0.2"
|
|
17
|
+
},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"@types/express": "^5.0.3",
|
|
20
|
+
"express": "^5.1.0",
|
|
21
|
+
"typescript": "^5.0.0",
|
|
22
|
+
"vitest": "^4.0.18",
|
|
23
|
+
"@objectstack/runtime": "3.0.2"
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "tsup --config ../../../tsup.config.ts",
|
|
27
|
+
"test": "vitest run",
|
|
28
|
+
"test:watch": "vitest"
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
4
|
+
|
|
5
|
+
// Mock dispatcher instance
|
|
6
|
+
const mockDispatcher = {
|
|
7
|
+
getDiscoveryInfo: vi.fn().mockReturnValue({ version: '1.0', endpoints: [] }),
|
|
8
|
+
handleAuth: vi.fn().mockResolvedValue({ handled: true, response: { body: { ok: true }, status: 200 } }),
|
|
9
|
+
handleGraphQL: vi.fn().mockResolvedValue({ data: {} }),
|
|
10
|
+
handleMetadata: vi.fn().mockResolvedValue({ handled: true, response: { body: { objects: [] }, status: 200 } }),
|
|
11
|
+
handleData: vi.fn().mockResolvedValue({ handled: true, response: { body: { records: [] }, status: 200 } }),
|
|
12
|
+
handleStorage: vi.fn().mockResolvedValue({ handled: true, response: { body: {}, status: 200 } }),
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
vi.mock('@objectstack/runtime', () => {
|
|
16
|
+
return {
|
|
17
|
+
HttpDispatcher: function HttpDispatcher() {
|
|
18
|
+
return mockDispatcher;
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
import { createExpressRouter, objectStackMiddleware } from './index';
|
|
24
|
+
|
|
25
|
+
const mockKernel = { name: 'test-kernel' } as any;
|
|
26
|
+
|
|
27
|
+
function createMockRes() {
|
|
28
|
+
const res: any = {
|
|
29
|
+
_status: 200,
|
|
30
|
+
_body: null,
|
|
31
|
+
_headers: {} as Record<string, string>,
|
|
32
|
+
_redirectUrl: null as string | null,
|
|
33
|
+
status(code: number) { res._status = code; return res; },
|
|
34
|
+
json(body: any) { res._body = body; return res; },
|
|
35
|
+
send(body: any) { res._body = body; return res; },
|
|
36
|
+
set(k: string, v: string) { res._headers[k] = v; return res; },
|
|
37
|
+
redirect(url: string) { res._redirectUrl = url; return res; },
|
|
38
|
+
};
|
|
39
|
+
return res;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function createMockReq(overrides: any = {}) {
|
|
43
|
+
return {
|
|
44
|
+
method: 'GET',
|
|
45
|
+
path: '/',
|
|
46
|
+
url: '/',
|
|
47
|
+
originalUrl: '/',
|
|
48
|
+
body: {},
|
|
49
|
+
query: {},
|
|
50
|
+
headers: {},
|
|
51
|
+
params: {},
|
|
52
|
+
protocol: 'http',
|
|
53
|
+
get: (key: string) => key === 'host' ? 'localhost' : undefined,
|
|
54
|
+
...overrides,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
describe('createExpressRouter', () => {
|
|
59
|
+
let router: any;
|
|
60
|
+
|
|
61
|
+
beforeEach(() => {
|
|
62
|
+
vi.clearAllMocks();
|
|
63
|
+
router = createExpressRouter({ kernel: mockKernel });
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('returns a router with registered routes', () => {
|
|
67
|
+
expect(router).toBeDefined();
|
|
68
|
+
expect(router.stack).toBeDefined();
|
|
69
|
+
expect(router.stack.length).toBeGreaterThan(0);
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
describe('objectStackMiddleware', () => {
|
|
74
|
+
it('attaches kernel to request', () => {
|
|
75
|
+
const middleware = objectStackMiddleware(mockKernel);
|
|
76
|
+
const req: any = {};
|
|
77
|
+
const res = createMockRes();
|
|
78
|
+
const next = vi.fn();
|
|
79
|
+
|
|
80
|
+
middleware(req, res, next);
|
|
81
|
+
|
|
82
|
+
expect(req.objectStack).toBe(mockKernel);
|
|
83
|
+
expect(next).toHaveBeenCalled();
|
|
84
|
+
});
|
|
85
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import { type Router, type Request, type Response, type NextFunction, Router as createRouter } from 'express';
|
|
4
|
+
import { type ObjectKernel, HttpDispatcher, HttpDispatcherResult } from '@objectstack/runtime';
|
|
5
|
+
|
|
6
|
+
export interface ExpressAdapterOptions {
|
|
7
|
+
kernel: ObjectKernel;
|
|
8
|
+
prefix?: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Auth service interface with handleRequest method
|
|
13
|
+
*/
|
|
14
|
+
interface AuthService {
|
|
15
|
+
handleRequest(request: globalThis.Request): Promise<globalThis.Response>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Creates an Express Router with all ObjectStack route dispatchers.
|
|
20
|
+
* Provides Auth, GraphQL, Metadata, Data, and Storage routes.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```ts
|
|
24
|
+
* import express from 'express';
|
|
25
|
+
* import { createExpressRouter } from '@objectstack/express';
|
|
26
|
+
*
|
|
27
|
+
* const app = express();
|
|
28
|
+
* app.use('/api', createExpressRouter({ kernel }));
|
|
29
|
+
* app.listen(3000);
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export function createExpressRouter(options: ExpressAdapterOptions): Router {
|
|
33
|
+
const router = createRouter();
|
|
34
|
+
const dispatcher = new HttpDispatcher(options.kernel);
|
|
35
|
+
const prefix = options.prefix || '/api';
|
|
36
|
+
|
|
37
|
+
const sendResult = (result: HttpDispatcherResult, res: Response) => {
|
|
38
|
+
if (result.handled) {
|
|
39
|
+
if (result.response) {
|
|
40
|
+
if (result.response.headers) {
|
|
41
|
+
Object.entries(result.response.headers).forEach(([k, v]) => res.set(k, v as string));
|
|
42
|
+
}
|
|
43
|
+
return res.status(result.response.status).json(result.response.body);
|
|
44
|
+
}
|
|
45
|
+
if (result.result) {
|
|
46
|
+
const response = result.result;
|
|
47
|
+
if (response.type === 'redirect' && response.url) {
|
|
48
|
+
return res.redirect(response.url);
|
|
49
|
+
}
|
|
50
|
+
if (response.type === 'stream' && response.stream) {
|
|
51
|
+
if (response.headers) {
|
|
52
|
+
Object.entries(response.headers).forEach(([k, v]) => res.set(k, v as string));
|
|
53
|
+
}
|
|
54
|
+
response.stream.pipe(res);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
return res.status(200).json(response);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return res.status(404).json({ success: false, error: { message: 'Not Found', code: 404 } });
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const errorResponse = (err: any, res: Response) => {
|
|
64
|
+
return res.status(err.statusCode || 500).json({
|
|
65
|
+
success: false,
|
|
66
|
+
error: {
|
|
67
|
+
message: err.message || 'Internal Server Error',
|
|
68
|
+
code: err.statusCode || 500,
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
// --- Discovery ---
|
|
74
|
+
router.get('/', (_req: Request, res: Response) => {
|
|
75
|
+
res.json({ data: dispatcher.getDiscoveryInfo(prefix) });
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
// --- Auth ---
|
|
79
|
+
router.all('/auth/{*path}', async (req: Request, res: Response) => {
|
|
80
|
+
try {
|
|
81
|
+
const path = (req.params as any).path;
|
|
82
|
+
const method = req.method;
|
|
83
|
+
|
|
84
|
+
// Try AuthPlugin service first
|
|
85
|
+
const authService = typeof options.kernel.getService === 'function'
|
|
86
|
+
? options.kernel.getService<AuthService>('auth')
|
|
87
|
+
: null;
|
|
88
|
+
|
|
89
|
+
if (authService && typeof authService.handleRequest === 'function') {
|
|
90
|
+
const protocol = req.protocol || 'http';
|
|
91
|
+
const host = req.get?.('host') || req.headers?.host || 'localhost';
|
|
92
|
+
const url = `${protocol}://${host}${req.originalUrl || req.url}`;
|
|
93
|
+
const headers = new Headers();
|
|
94
|
+
if (req.headers) {
|
|
95
|
+
Object.entries(req.headers).forEach(([k, v]) => {
|
|
96
|
+
if (typeof v === 'string') headers.set(k, v);
|
|
97
|
+
else if (Array.isArray(v)) headers.set(k, v.join(', '));
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
const init: RequestInit = { method, headers };
|
|
101
|
+
if (method !== 'GET' && method !== 'HEAD' && req.body) {
|
|
102
|
+
init.body = JSON.stringify(req.body);
|
|
103
|
+
if (!headers.has('content-type')) {
|
|
104
|
+
headers.set('content-type', 'application/json');
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const webRequest = new Request(url, init);
|
|
108
|
+
const response = await authService.handleRequest(webRequest);
|
|
109
|
+
res.status(response.status);
|
|
110
|
+
response.headers.forEach((v: string, k: string) => res.set(k, v));
|
|
111
|
+
const text = await response.text();
|
|
112
|
+
return res.send(text);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Fallback to dispatcher
|
|
116
|
+
const body = method === 'GET' || method === 'HEAD' ? {} : req.body || {};
|
|
117
|
+
const result = await dispatcher.handleAuth(path, method, body, { request: req, response: res });
|
|
118
|
+
return sendResult(result, res);
|
|
119
|
+
} catch (err: any) {
|
|
120
|
+
return errorResponse(err, res);
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
// --- GraphQL ---
|
|
125
|
+
router.post('/graphql', async (req: Request, res: Response) => {
|
|
126
|
+
try {
|
|
127
|
+
const result = await dispatcher.handleGraphQL(req.body, { request: req });
|
|
128
|
+
return res.json(result);
|
|
129
|
+
} catch (err: any) {
|
|
130
|
+
return errorResponse(err, res);
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
// --- Metadata ---
|
|
135
|
+
router.all('/meta/{*path}', async (req: Request, res: Response) => {
|
|
136
|
+
try {
|
|
137
|
+
const subPath = '/' + (req.params as any).path;
|
|
138
|
+
const method = req.method;
|
|
139
|
+
const body = (method === 'PUT' || method === 'POST') ? req.body : undefined;
|
|
140
|
+
const result = await dispatcher.handleMetadata(subPath, { request: req }, method, body);
|
|
141
|
+
return sendResult(result, res);
|
|
142
|
+
} catch (err: any) {
|
|
143
|
+
return errorResponse(err, res);
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
router.all('/meta', async (req: Request, res: Response) => {
|
|
148
|
+
try {
|
|
149
|
+
const method = req.method;
|
|
150
|
+
const body = (method === 'PUT' || method === 'POST') ? req.body : undefined;
|
|
151
|
+
const result = await dispatcher.handleMetadata('', { request: req }, method, body);
|
|
152
|
+
return sendResult(result, res);
|
|
153
|
+
} catch (err: any) {
|
|
154
|
+
return errorResponse(err, res);
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
// --- Data ---
|
|
159
|
+
router.all('/data/{*path}', async (req: Request, res: Response) => {
|
|
160
|
+
try {
|
|
161
|
+
const subPath = '/' + (req.params as any).path;
|
|
162
|
+
const method = req.method;
|
|
163
|
+
const body = (method === 'POST' || method === 'PATCH') ? req.body : {};
|
|
164
|
+
const result = await dispatcher.handleData(subPath, method, body, req.query, { request: req });
|
|
165
|
+
return sendResult(result, res);
|
|
166
|
+
} catch (err: any) {
|
|
167
|
+
return errorResponse(err, res);
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
// --- Storage ---
|
|
172
|
+
router.all('/storage/{*path}', async (req: Request, res: Response) => {
|
|
173
|
+
try {
|
|
174
|
+
const subPath = '/' + (req.params as any).path;
|
|
175
|
+
const method = req.method;
|
|
176
|
+
const file = (req as any).file || (req as any).files?.file;
|
|
177
|
+
const result = await dispatcher.handleStorage(subPath, method, file, { request: req });
|
|
178
|
+
return sendResult(result, res);
|
|
179
|
+
} catch (err: any) {
|
|
180
|
+
return errorResponse(err, res);
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
return router;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Middleware that attaches the ObjectStack kernel to the request.
|
|
189
|
+
*/
|
|
190
|
+
export function objectStackMiddleware(kernel: ObjectKernel) {
|
|
191
|
+
return (req: Request, _res: Response, next: NextFunction) => {
|
|
192
|
+
(req as any).objectStack = kernel;
|
|
193
|
+
next();
|
|
194
|
+
};
|
|
195
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "../../../tsconfig.json",
|
|
3
|
+
"compilerOptions": {
|
|
4
|
+
"outDir": "./dist",
|
|
5
|
+
"rootDir": "./src",
|
|
6
|
+
"module": "NodeNext",
|
|
7
|
+
"moduleResolution": "NodeNext",
|
|
8
|
+
"esModuleInterop": true,
|
|
9
|
+
"skipLibCheck": true
|
|
10
|
+
},
|
|
11
|
+
"include": ["src/**/*"],
|
|
12
|
+
"exclude": ["node_modules", "dist"]
|
|
13
|
+
}
|
package/vitest.config.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
|
|
2
|
+
|
|
3
|
+
import { defineConfig } from 'vitest/config';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
export default defineConfig({
|
|
7
|
+
test: {
|
|
8
|
+
globals: true,
|
|
9
|
+
environment: 'node',
|
|
10
|
+
},
|
|
11
|
+
resolve: {
|
|
12
|
+
alias: {
|
|
13
|
+
'@objectstack/runtime': path.resolve(__dirname, 'src/__mocks__/runtime.ts'),
|
|
14
|
+
},
|
|
15
|
+
},
|
|
16
|
+
});
|