@contractspec/lib.contracts-runtime-server-rest 2.0.0
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 +3 -0
- package/dist/browser/contracts-adapter-hydration.js +40 -0
- package/dist/browser/contracts-adapter-input.js +99 -0
- package/dist/browser/index.js +346 -0
- package/dist/browser/rest-elysia.js +146 -0
- package/dist/browser/rest-express.js +161 -0
- package/dist/browser/rest-generic.js +129 -0
- package/dist/browser/rest-next-app.js +137 -0
- package/dist/browser/rest-next-pages.js +148 -0
- package/dist/contracts-adapter-hydration.d.ts +11 -0
- package/dist/contracts-adapter-hydration.js +41 -0
- package/dist/contracts-adapter-input.d.ts +5 -0
- package/dist/contracts-adapter-input.js +100 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +347 -0
- package/dist/node/contracts-adapter-hydration.js +40 -0
- package/dist/node/contracts-adapter-input.js +99 -0
- package/dist/node/index.js +346 -0
- package/dist/node/rest-elysia.js +146 -0
- package/dist/node/rest-express.js +161 -0
- package/dist/node/rest-generic.js +129 -0
- package/dist/node/rest-next-app.js +137 -0
- package/dist/node/rest-next-pages.js +148 -0
- package/dist/rest-elysia.d.ts +35 -0
- package/dist/rest-elysia.js +147 -0
- package/dist/rest-express.d.ts +7 -0
- package/dist/rest-express.js +162 -0
- package/dist/rest-generic.d.ts +18 -0
- package/dist/rest-generic.js +130 -0
- package/dist/rest-next-app.d.ts +4 -0
- package/dist/rest-next-app.js +138 -0
- package/dist/rest-next-pages.d.ts +5 -0
- package/dist/rest-next-pages.js +149 -0
- package/package.json +160 -0
package/README.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// src/contracts-adapter-hydration.ts
|
|
2
|
+
function parseReturns(returnsLike) {
|
|
3
|
+
if (!returnsLike)
|
|
4
|
+
return { isList: false, inner: "JSON" };
|
|
5
|
+
const trimmed = String(returnsLike).trim();
|
|
6
|
+
if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
|
|
7
|
+
return { isList: true, inner: trimmed.slice(1, -1).trim() };
|
|
8
|
+
}
|
|
9
|
+
return { isList: false, inner: trimmed };
|
|
10
|
+
}
|
|
11
|
+
async function hydrateResourceIfNeeded(resources, result, opts) {
|
|
12
|
+
if (!resources || !opts.template)
|
|
13
|
+
return result;
|
|
14
|
+
const varName = opts.varName ?? "id";
|
|
15
|
+
const hydrateOne = async (item) => {
|
|
16
|
+
if (item && typeof item === "object" && varName in item) {
|
|
17
|
+
const key = String(item[varName]);
|
|
18
|
+
const uri = (opts.template ?? "").replace("{id}", key);
|
|
19
|
+
const match = resources.match(uri);
|
|
20
|
+
if (match) {
|
|
21
|
+
const resolved = await match.tmpl.resolve(match.params, {});
|
|
22
|
+
try {
|
|
23
|
+
return JSON.parse(String(resolved.data || "null"));
|
|
24
|
+
} catch {
|
|
25
|
+
return resolved.data;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return item;
|
|
30
|
+
};
|
|
31
|
+
if (opts.returns.isList && Array.isArray(result)) {
|
|
32
|
+
const hydrated = await Promise.all(result.map((x) => hydrateOne(x)));
|
|
33
|
+
return hydrated;
|
|
34
|
+
}
|
|
35
|
+
return await hydrateOne(result);
|
|
36
|
+
}
|
|
37
|
+
export {
|
|
38
|
+
parseReturns,
|
|
39
|
+
hydrateResourceIfNeeded
|
|
40
|
+
};
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// src/contracts-adapter-input.ts
|
|
2
|
+
import { isSchemaModel } from "@contractspec/lib.schema";
|
|
3
|
+
function isFieldType(x) {
|
|
4
|
+
return typeof x?.getPothos === "function";
|
|
5
|
+
}
|
|
6
|
+
function isEnumType(x) {
|
|
7
|
+
return typeof x?.getEnumValues === "function" && typeof x?.getPothos === "function";
|
|
8
|
+
}
|
|
9
|
+
function mapScalarName(name) {
|
|
10
|
+
if (name === "Boolean_unsecure")
|
|
11
|
+
return "Boolean";
|
|
12
|
+
if (name === "ID_unsecure")
|
|
13
|
+
return "ID";
|
|
14
|
+
if (name === "String_unsecure")
|
|
15
|
+
return "String";
|
|
16
|
+
if (name === "Int_unsecure")
|
|
17
|
+
return "Int";
|
|
18
|
+
if (name === "Float_unsecure")
|
|
19
|
+
return "Float";
|
|
20
|
+
return name;
|
|
21
|
+
}
|
|
22
|
+
function createInputTypeBuilder(builder) {
|
|
23
|
+
const inputTypeCache = new Map;
|
|
24
|
+
const enumTypeCache = new Set;
|
|
25
|
+
function registerEnumsForModel(model) {
|
|
26
|
+
const entries = Object.entries(model.config.fields);
|
|
27
|
+
for (const [, field] of entries) {
|
|
28
|
+
const fieldType = field.type;
|
|
29
|
+
if (isSchemaModel(fieldType)) {
|
|
30
|
+
registerEnumsForModel(fieldType);
|
|
31
|
+
} else if (isEnumType(field.type)) {
|
|
32
|
+
const enumObj = field.type;
|
|
33
|
+
const name = enumObj.getName?.() ?? enumObj.getPothos().name;
|
|
34
|
+
if (!enumTypeCache.has(name)) {
|
|
35
|
+
builder.enumType(name, {
|
|
36
|
+
values: enumObj.getEnumValues()
|
|
37
|
+
});
|
|
38
|
+
enumTypeCache.add(name);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function ensureInputTypeForModel(model) {
|
|
44
|
+
const typeName = String(model.config?.name ?? "Input");
|
|
45
|
+
const cached = inputTypeCache.get(typeName);
|
|
46
|
+
if (cached)
|
|
47
|
+
return cached;
|
|
48
|
+
registerEnumsForModel(model);
|
|
49
|
+
const created = builder.inputType(model.getPothosInput(), {
|
|
50
|
+
fields: (t) => {
|
|
51
|
+
const entries = Object.entries(model.config.fields);
|
|
52
|
+
const acc = {};
|
|
53
|
+
for (const [key, field] of entries) {
|
|
54
|
+
const fieldType = field.type;
|
|
55
|
+
if (isSchemaModel(fieldType)) {
|
|
56
|
+
const nested = ensureInputTypeForModel(fieldType);
|
|
57
|
+
const typeRef = field.isArray ? [nested] : nested;
|
|
58
|
+
acc[key] = t.field({
|
|
59
|
+
type: typeRef,
|
|
60
|
+
required: !field.isOptional
|
|
61
|
+
});
|
|
62
|
+
} else if (isFieldType(field.type)) {
|
|
63
|
+
const typeName2 = mapScalarName(String(field.type.getPothos().name));
|
|
64
|
+
const typeRef = field.isArray ? [typeName2] : typeName2;
|
|
65
|
+
acc[key] = t.field({
|
|
66
|
+
type: typeRef,
|
|
67
|
+
required: !field.isOptional
|
|
68
|
+
});
|
|
69
|
+
} else {
|
|
70
|
+
const typeRef = field.isArray ? ["JSON"] : "JSON";
|
|
71
|
+
acc[key] = t.field({
|
|
72
|
+
type: typeRef,
|
|
73
|
+
required: !field.isOptional
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return acc;
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
inputTypeCache.set(typeName, created);
|
|
81
|
+
return created;
|
|
82
|
+
}
|
|
83
|
+
function buildInputFieldArgs(model) {
|
|
84
|
+
if (!model)
|
|
85
|
+
return null;
|
|
86
|
+
if (!isSchemaModel(model)) {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
if (!model.config?.fields || Object.keys(model.config.fields).length === 0) {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
const ref = ensureInputTypeForModel(model);
|
|
93
|
+
return ref;
|
|
94
|
+
}
|
|
95
|
+
return { buildInputFieldArgs };
|
|
96
|
+
}
|
|
97
|
+
export {
|
|
98
|
+
createInputTypeBuilder
|
|
99
|
+
};
|
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
// src/contracts-adapter-hydration.ts
|
|
2
|
+
function parseReturns(returnsLike) {
|
|
3
|
+
if (!returnsLike)
|
|
4
|
+
return { isList: false, inner: "JSON" };
|
|
5
|
+
const trimmed = String(returnsLike).trim();
|
|
6
|
+
if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
|
|
7
|
+
return { isList: true, inner: trimmed.slice(1, -1).trim() };
|
|
8
|
+
}
|
|
9
|
+
return { isList: false, inner: trimmed };
|
|
10
|
+
}
|
|
11
|
+
async function hydrateResourceIfNeeded(resources, result, opts) {
|
|
12
|
+
if (!resources || !opts.template)
|
|
13
|
+
return result;
|
|
14
|
+
const varName = opts.varName ?? "id";
|
|
15
|
+
const hydrateOne = async (item) => {
|
|
16
|
+
if (item && typeof item === "object" && varName in item) {
|
|
17
|
+
const key = String(item[varName]);
|
|
18
|
+
const uri = (opts.template ?? "").replace("{id}", key);
|
|
19
|
+
const match = resources.match(uri);
|
|
20
|
+
if (match) {
|
|
21
|
+
const resolved = await match.tmpl.resolve(match.params, {});
|
|
22
|
+
try {
|
|
23
|
+
return JSON.parse(String(resolved.data || "null"));
|
|
24
|
+
} catch {
|
|
25
|
+
return resolved.data;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return item;
|
|
30
|
+
};
|
|
31
|
+
if (opts.returns.isList && Array.isArray(result)) {
|
|
32
|
+
const hydrated = await Promise.all(result.map((x) => hydrateOne(x)));
|
|
33
|
+
return hydrated;
|
|
34
|
+
}
|
|
35
|
+
return await hydrateOne(result);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// src/contracts-adapter-input.ts
|
|
39
|
+
import { isSchemaModel } from "@contractspec/lib.schema";
|
|
40
|
+
function isFieldType(x) {
|
|
41
|
+
return typeof x?.getPothos === "function";
|
|
42
|
+
}
|
|
43
|
+
function isEnumType(x) {
|
|
44
|
+
return typeof x?.getEnumValues === "function" && typeof x?.getPothos === "function";
|
|
45
|
+
}
|
|
46
|
+
function mapScalarName(name) {
|
|
47
|
+
if (name === "Boolean_unsecure")
|
|
48
|
+
return "Boolean";
|
|
49
|
+
if (name === "ID_unsecure")
|
|
50
|
+
return "ID";
|
|
51
|
+
if (name === "String_unsecure")
|
|
52
|
+
return "String";
|
|
53
|
+
if (name === "Int_unsecure")
|
|
54
|
+
return "Int";
|
|
55
|
+
if (name === "Float_unsecure")
|
|
56
|
+
return "Float";
|
|
57
|
+
return name;
|
|
58
|
+
}
|
|
59
|
+
function createInputTypeBuilder(builder) {
|
|
60
|
+
const inputTypeCache = new Map;
|
|
61
|
+
const enumTypeCache = new Set;
|
|
62
|
+
function registerEnumsForModel(model) {
|
|
63
|
+
const entries = Object.entries(model.config.fields);
|
|
64
|
+
for (const [, field] of entries) {
|
|
65
|
+
const fieldType = field.type;
|
|
66
|
+
if (isSchemaModel(fieldType)) {
|
|
67
|
+
registerEnumsForModel(fieldType);
|
|
68
|
+
} else if (isEnumType(field.type)) {
|
|
69
|
+
const enumObj = field.type;
|
|
70
|
+
const name = enumObj.getName?.() ?? enumObj.getPothos().name;
|
|
71
|
+
if (!enumTypeCache.has(name)) {
|
|
72
|
+
builder.enumType(name, {
|
|
73
|
+
values: enumObj.getEnumValues()
|
|
74
|
+
});
|
|
75
|
+
enumTypeCache.add(name);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function ensureInputTypeForModel(model) {
|
|
81
|
+
const typeName = String(model.config?.name ?? "Input");
|
|
82
|
+
const cached = inputTypeCache.get(typeName);
|
|
83
|
+
if (cached)
|
|
84
|
+
return cached;
|
|
85
|
+
registerEnumsForModel(model);
|
|
86
|
+
const created = builder.inputType(model.getPothosInput(), {
|
|
87
|
+
fields: (t) => {
|
|
88
|
+
const entries = Object.entries(model.config.fields);
|
|
89
|
+
const acc = {};
|
|
90
|
+
for (const [key, field] of entries) {
|
|
91
|
+
const fieldType = field.type;
|
|
92
|
+
if (isSchemaModel(fieldType)) {
|
|
93
|
+
const nested = ensureInputTypeForModel(fieldType);
|
|
94
|
+
const typeRef = field.isArray ? [nested] : nested;
|
|
95
|
+
acc[key] = t.field({
|
|
96
|
+
type: typeRef,
|
|
97
|
+
required: !field.isOptional
|
|
98
|
+
});
|
|
99
|
+
} else if (isFieldType(field.type)) {
|
|
100
|
+
const typeName2 = mapScalarName(String(field.type.getPothos().name));
|
|
101
|
+
const typeRef = field.isArray ? [typeName2] : typeName2;
|
|
102
|
+
acc[key] = t.field({
|
|
103
|
+
type: typeRef,
|
|
104
|
+
required: !field.isOptional
|
|
105
|
+
});
|
|
106
|
+
} else {
|
|
107
|
+
const typeRef = field.isArray ? ["JSON"] : "JSON";
|
|
108
|
+
acc[key] = t.field({
|
|
109
|
+
type: typeRef,
|
|
110
|
+
required: !field.isOptional
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return acc;
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
inputTypeCache.set(typeName, created);
|
|
118
|
+
return created;
|
|
119
|
+
}
|
|
120
|
+
function buildInputFieldArgs(model) {
|
|
121
|
+
if (!model)
|
|
122
|
+
return null;
|
|
123
|
+
if (!isSchemaModel(model)) {
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
if (!model.config?.fields || Object.keys(model.config.fields).length === 0) {
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
const ref = ensureInputTypeForModel(model);
|
|
130
|
+
return ref;
|
|
131
|
+
}
|
|
132
|
+
return { buildInputFieldArgs };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// src/rest-generic.ts
|
|
136
|
+
import { defaultRestPath } from "@contractspec/lib.contracts-spec/jsonschema";
|
|
137
|
+
function corsHeaders(opt) {
|
|
138
|
+
const h = {};
|
|
139
|
+
const origin = typeof opt === "object" ? opt.origin ?? "*" : "*";
|
|
140
|
+
h["access-control-allow-origin"] = origin;
|
|
141
|
+
h["vary"] = "Origin";
|
|
142
|
+
if (typeof opt === "object") {
|
|
143
|
+
if (opt.methods)
|
|
144
|
+
h["access-control-allow-methods"] = opt.methods.join(", ");
|
|
145
|
+
if (opt.headers)
|
|
146
|
+
h["access-control-allow-headers"] = opt.headers.join(", ");
|
|
147
|
+
if (opt.credentials)
|
|
148
|
+
h["access-control-allow-credentials"] = "true";
|
|
149
|
+
if (typeof opt.maxAge === "number") {
|
|
150
|
+
h["access-control-max-age"] = String(opt.maxAge);
|
|
151
|
+
}
|
|
152
|
+
} else {
|
|
153
|
+
h["access-control-allow-methods"] = "GET,POST,OPTIONS";
|
|
154
|
+
h["access-control-allow-headers"] = "content-type,x-idempotency-key,x-trace-id";
|
|
155
|
+
}
|
|
156
|
+
return h;
|
|
157
|
+
}
|
|
158
|
+
function joinPath(a, b) {
|
|
159
|
+
const left = (a ?? "").replace(/\/+$/g, "");
|
|
160
|
+
const right = b.replace(/^\/+/g, "");
|
|
161
|
+
return `${left}/${right}`.replace(/\/{2,}/g, "/");
|
|
162
|
+
}
|
|
163
|
+
function createFetchHandler(reg, ctxFactory, options) {
|
|
164
|
+
const opts = {
|
|
165
|
+
basePath: options?.basePath ?? "",
|
|
166
|
+
cors: options?.cors ?? false,
|
|
167
|
+
prettyJson: options?.prettyJson ?? false,
|
|
168
|
+
onError: options?.onError
|
|
169
|
+
};
|
|
170
|
+
const routes = reg.list().map((spec) => ({
|
|
171
|
+
method: spec.transport?.rest?.method ?? (spec.meta.kind === "query" ? "GET" : "POST"),
|
|
172
|
+
path: joinPath(opts.basePath, spec.transport?.rest?.path ?? defaultRestPath(spec.meta.key, spec.meta.version)),
|
|
173
|
+
name: spec.meta.key,
|
|
174
|
+
version: spec.meta.version
|
|
175
|
+
}));
|
|
176
|
+
const routeTable = new Map;
|
|
177
|
+
for (const r of routes)
|
|
178
|
+
routeTable.set(`${r.method} ${r.path}`, r);
|
|
179
|
+
const makeJson = (status, data, extraHeaders) => {
|
|
180
|
+
const body = opts.prettyJson ? JSON.stringify(data, null, opts.prettyJson) : JSON.stringify(data);
|
|
181
|
+
const base = {
|
|
182
|
+
"content-type": "application/json; charset=utf-8"
|
|
183
|
+
};
|
|
184
|
+
return new Response(body, {
|
|
185
|
+
status,
|
|
186
|
+
headers: extraHeaders ? { ...base, ...extraHeaders } : base
|
|
187
|
+
});
|
|
188
|
+
};
|
|
189
|
+
return async function handle(req) {
|
|
190
|
+
const url = new URL(req.url);
|
|
191
|
+
const key = `${req.method.toUpperCase()} ${url.pathname}`;
|
|
192
|
+
if (opts.cors && req.method.toUpperCase() === "OPTIONS") {
|
|
193
|
+
const h = corsHeaders(opts.cors === true ? {} : opts.cors);
|
|
194
|
+
return new Response(null, {
|
|
195
|
+
status: 204,
|
|
196
|
+
headers: { ...h, "content-length": "0" }
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
const route = routeTable.get(key);
|
|
200
|
+
if (!route) {
|
|
201
|
+
const headers = {};
|
|
202
|
+
if (opts.cors)
|
|
203
|
+
Object.assign(headers, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
204
|
+
return makeJson(404, { error: "NotFound", path: url.pathname }, headers);
|
|
205
|
+
}
|
|
206
|
+
try {
|
|
207
|
+
let input = {};
|
|
208
|
+
if (route.method === "GET") {
|
|
209
|
+
if (url.searchParams.has("input")) {
|
|
210
|
+
const raw = url.searchParams.get("input");
|
|
211
|
+
input = raw ? JSON.parse(raw) : {};
|
|
212
|
+
} else {
|
|
213
|
+
const obj = {};
|
|
214
|
+
for (const [k, v] of url.searchParams.entries())
|
|
215
|
+
obj[k] = v;
|
|
216
|
+
input = obj;
|
|
217
|
+
}
|
|
218
|
+
} else {
|
|
219
|
+
const contentType = req.headers.get("content-type") || "";
|
|
220
|
+
if (contentType.includes("application/json")) {
|
|
221
|
+
input = await req.json();
|
|
222
|
+
} else if (contentType.includes("application/x-www-form-urlencoded")) {
|
|
223
|
+
const form = await req.formData();
|
|
224
|
+
input = Object.fromEntries(form.entries());
|
|
225
|
+
} else if (!contentType) {
|
|
226
|
+
input = {};
|
|
227
|
+
} else {
|
|
228
|
+
return makeJson(415, { error: "UnsupportedMediaType", contentType });
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
const ctx = ctxFactory(req);
|
|
232
|
+
const result = await reg.execute(route.name, route.version, input, ctx);
|
|
233
|
+
const headers = {};
|
|
234
|
+
if (opts.cors)
|
|
235
|
+
Object.assign(headers, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
236
|
+
return makeJson(200, result, headers);
|
|
237
|
+
} catch (err) {
|
|
238
|
+
if (opts.onError) {
|
|
239
|
+
const mapped = opts.onError(err);
|
|
240
|
+
const headers2 = {};
|
|
241
|
+
if (opts.cors)
|
|
242
|
+
Object.assign(headers2, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
243
|
+
return makeJson(mapped.status, mapped.body, headers2);
|
|
244
|
+
}
|
|
245
|
+
const headers = {};
|
|
246
|
+
if (opts.cors)
|
|
247
|
+
Object.assign(headers, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
248
|
+
if (err?.issues) {
|
|
249
|
+
return makeJson(400, {
|
|
250
|
+
error: "ValidationError",
|
|
251
|
+
issues: err.issues
|
|
252
|
+
}, headers);
|
|
253
|
+
}
|
|
254
|
+
if (typeof err?.message === "string" && err.message.startsWith("PolicyDenied")) {
|
|
255
|
+
return makeJson(403, { error: "PolicyDenied" }, headers);
|
|
256
|
+
}
|
|
257
|
+
return makeJson(500, { error: "InternalError" }, headers);
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// src/rest-elysia.ts
|
|
263
|
+
function elysiaPlugin(app, reg, ctxFactory, options) {
|
|
264
|
+
const handler = createFetchHandler(reg, (req) => ctxFactory({
|
|
265
|
+
request: req,
|
|
266
|
+
store: app.store
|
|
267
|
+
}), options);
|
|
268
|
+
for (const spec of reg.list()) {
|
|
269
|
+
const method = spec.transport?.rest?.method ?? (spec.meta.kind === "query" ? "GET" : "POST");
|
|
270
|
+
const path = (options?.basePath ?? "") + (spec.transport?.rest?.path ?? `/${spec.meta.key.replace(/\./g, "/")}/v${spec.meta.version}`);
|
|
271
|
+
app[method.toLowerCase()](path, ({ request }) => handler(request));
|
|
272
|
+
}
|
|
273
|
+
if (options?.cors) {
|
|
274
|
+
app.options("*", ({ request }) => handler(request));
|
|
275
|
+
}
|
|
276
|
+
return app;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// src/rest-express.ts
|
|
280
|
+
function expressRouter(express, reg, ctxFactory, options) {
|
|
281
|
+
const router = express.Router();
|
|
282
|
+
for (const spec of reg.list()) {
|
|
283
|
+
const method = spec.transport?.rest?.method ?? (spec.meta.kind === "query" ? "GET" : "POST");
|
|
284
|
+
const path = (options?.basePath ?? "") + (spec.transport?.rest?.path ?? `/${spec.meta.key.replace(/\./g, "/")}/v${spec.meta.version}`);
|
|
285
|
+
router[method.toLowerCase()](path, async (req, res) => {
|
|
286
|
+
const url = new URL(`${req.protocol}://${req.get("host")}${req.originalUrl}`);
|
|
287
|
+
const request = new Request(url.toString(), {
|
|
288
|
+
method,
|
|
289
|
+
headers: Object.fromEntries(Object.entries(req.headers).map(([k, v]) => [k, String(v)])),
|
|
290
|
+
body: method === "POST" ? JSON.stringify(req.body ?? {}) : undefined
|
|
291
|
+
});
|
|
292
|
+
const handler = createFetchHandler(reg, () => ctxFactory(req), options);
|
|
293
|
+
const response = await handler(request);
|
|
294
|
+
res.status(response.status);
|
|
295
|
+
response.headers.forEach((v, k) => res.setHeader(k, v));
|
|
296
|
+
const text = await response.text();
|
|
297
|
+
res.send(text);
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
if (options?.cors) {
|
|
301
|
+
router.options("*", (_req, res) => {
|
|
302
|
+
const h = new Headers;
|
|
303
|
+
const resp = new Response(null, { status: 204 });
|
|
304
|
+
resp.headers.forEach((v, k) => h.set(k, v));
|
|
305
|
+
res.status(204).send();
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
return router;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// src/rest-next-app.ts
|
|
312
|
+
function makeNextAppHandler(reg, ctxFactory, options) {
|
|
313
|
+
const handler = createFetchHandler(reg, ctxFactory, options);
|
|
314
|
+
return async function requestHandler(req) {
|
|
315
|
+
return handler(req);
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// src/rest-next-pages.ts
|
|
320
|
+
function makeNextPagesHandler(reg, ctxFactory, options) {
|
|
321
|
+
return async function handler(req, res) {
|
|
322
|
+
const url = `${req.headers["x-forwarded-proto"] ?? "http"}://${req.headers.host}${req.url}`;
|
|
323
|
+
const method = req.method?.toUpperCase() || "GET";
|
|
324
|
+
const request = new Request(url, {
|
|
325
|
+
method,
|
|
326
|
+
headers: Object.fromEntries(Object.entries(req.headers).map(([k, v]) => [k, String(v)])),
|
|
327
|
+
body: method === "POST" ? JSON.stringify(req.body ?? {}) : undefined
|
|
328
|
+
});
|
|
329
|
+
const perReqHandler = createFetchHandler(reg, () => ctxFactory(req), options);
|
|
330
|
+
const response = await perReqHandler(request);
|
|
331
|
+
res.status(response.status);
|
|
332
|
+
response.headers.forEach((v, k) => res.setHeader(k, v));
|
|
333
|
+
const text = await response.text();
|
|
334
|
+
res.send(text);
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
export {
|
|
338
|
+
parseReturns,
|
|
339
|
+
makeNextPagesHandler,
|
|
340
|
+
makeNextAppHandler,
|
|
341
|
+
hydrateResourceIfNeeded,
|
|
342
|
+
expressRouter,
|
|
343
|
+
elysiaPlugin,
|
|
344
|
+
createInputTypeBuilder,
|
|
345
|
+
createFetchHandler
|
|
346
|
+
};
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// src/rest-generic.ts
|
|
2
|
+
import { defaultRestPath } from "@contractspec/lib.contracts-spec/jsonschema";
|
|
3
|
+
function corsHeaders(opt) {
|
|
4
|
+
const h = {};
|
|
5
|
+
const origin = typeof opt === "object" ? opt.origin ?? "*" : "*";
|
|
6
|
+
h["access-control-allow-origin"] = origin;
|
|
7
|
+
h["vary"] = "Origin";
|
|
8
|
+
if (typeof opt === "object") {
|
|
9
|
+
if (opt.methods)
|
|
10
|
+
h["access-control-allow-methods"] = opt.methods.join(", ");
|
|
11
|
+
if (opt.headers)
|
|
12
|
+
h["access-control-allow-headers"] = opt.headers.join(", ");
|
|
13
|
+
if (opt.credentials)
|
|
14
|
+
h["access-control-allow-credentials"] = "true";
|
|
15
|
+
if (typeof opt.maxAge === "number") {
|
|
16
|
+
h["access-control-max-age"] = String(opt.maxAge);
|
|
17
|
+
}
|
|
18
|
+
} else {
|
|
19
|
+
h["access-control-allow-methods"] = "GET,POST,OPTIONS";
|
|
20
|
+
h["access-control-allow-headers"] = "content-type,x-idempotency-key,x-trace-id";
|
|
21
|
+
}
|
|
22
|
+
return h;
|
|
23
|
+
}
|
|
24
|
+
function joinPath(a, b) {
|
|
25
|
+
const left = (a ?? "").replace(/\/+$/g, "");
|
|
26
|
+
const right = b.replace(/^\/+/g, "");
|
|
27
|
+
return `${left}/${right}`.replace(/\/{2,}/g, "/");
|
|
28
|
+
}
|
|
29
|
+
function createFetchHandler(reg, ctxFactory, options) {
|
|
30
|
+
const opts = {
|
|
31
|
+
basePath: options?.basePath ?? "",
|
|
32
|
+
cors: options?.cors ?? false,
|
|
33
|
+
prettyJson: options?.prettyJson ?? false,
|
|
34
|
+
onError: options?.onError
|
|
35
|
+
};
|
|
36
|
+
const routes = reg.list().map((spec) => ({
|
|
37
|
+
method: spec.transport?.rest?.method ?? (spec.meta.kind === "query" ? "GET" : "POST"),
|
|
38
|
+
path: joinPath(opts.basePath, spec.transport?.rest?.path ?? defaultRestPath(spec.meta.key, spec.meta.version)),
|
|
39
|
+
name: spec.meta.key,
|
|
40
|
+
version: spec.meta.version
|
|
41
|
+
}));
|
|
42
|
+
const routeTable = new Map;
|
|
43
|
+
for (const r of routes)
|
|
44
|
+
routeTable.set(`${r.method} ${r.path}`, r);
|
|
45
|
+
const makeJson = (status, data, extraHeaders) => {
|
|
46
|
+
const body = opts.prettyJson ? JSON.stringify(data, null, opts.prettyJson) : JSON.stringify(data);
|
|
47
|
+
const base = {
|
|
48
|
+
"content-type": "application/json; charset=utf-8"
|
|
49
|
+
};
|
|
50
|
+
return new Response(body, {
|
|
51
|
+
status,
|
|
52
|
+
headers: extraHeaders ? { ...base, ...extraHeaders } : base
|
|
53
|
+
});
|
|
54
|
+
};
|
|
55
|
+
return async function handle(req) {
|
|
56
|
+
const url = new URL(req.url);
|
|
57
|
+
const key = `${req.method.toUpperCase()} ${url.pathname}`;
|
|
58
|
+
if (opts.cors && req.method.toUpperCase() === "OPTIONS") {
|
|
59
|
+
const h = corsHeaders(opts.cors === true ? {} : opts.cors);
|
|
60
|
+
return new Response(null, {
|
|
61
|
+
status: 204,
|
|
62
|
+
headers: { ...h, "content-length": "0" }
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
const route = routeTable.get(key);
|
|
66
|
+
if (!route) {
|
|
67
|
+
const headers = {};
|
|
68
|
+
if (opts.cors)
|
|
69
|
+
Object.assign(headers, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
70
|
+
return makeJson(404, { error: "NotFound", path: url.pathname }, headers);
|
|
71
|
+
}
|
|
72
|
+
try {
|
|
73
|
+
let input = {};
|
|
74
|
+
if (route.method === "GET") {
|
|
75
|
+
if (url.searchParams.has("input")) {
|
|
76
|
+
const raw = url.searchParams.get("input");
|
|
77
|
+
input = raw ? JSON.parse(raw) : {};
|
|
78
|
+
} else {
|
|
79
|
+
const obj = {};
|
|
80
|
+
for (const [k, v] of url.searchParams.entries())
|
|
81
|
+
obj[k] = v;
|
|
82
|
+
input = obj;
|
|
83
|
+
}
|
|
84
|
+
} else {
|
|
85
|
+
const contentType = req.headers.get("content-type") || "";
|
|
86
|
+
if (contentType.includes("application/json")) {
|
|
87
|
+
input = await req.json();
|
|
88
|
+
} else if (contentType.includes("application/x-www-form-urlencoded")) {
|
|
89
|
+
const form = await req.formData();
|
|
90
|
+
input = Object.fromEntries(form.entries());
|
|
91
|
+
} else if (!contentType) {
|
|
92
|
+
input = {};
|
|
93
|
+
} else {
|
|
94
|
+
return makeJson(415, { error: "UnsupportedMediaType", contentType });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const ctx = ctxFactory(req);
|
|
98
|
+
const result = await reg.execute(route.name, route.version, input, ctx);
|
|
99
|
+
const headers = {};
|
|
100
|
+
if (opts.cors)
|
|
101
|
+
Object.assign(headers, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
102
|
+
return makeJson(200, result, headers);
|
|
103
|
+
} catch (err) {
|
|
104
|
+
if (opts.onError) {
|
|
105
|
+
const mapped = opts.onError(err);
|
|
106
|
+
const headers2 = {};
|
|
107
|
+
if (opts.cors)
|
|
108
|
+
Object.assign(headers2, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
109
|
+
return makeJson(mapped.status, mapped.body, headers2);
|
|
110
|
+
}
|
|
111
|
+
const headers = {};
|
|
112
|
+
if (opts.cors)
|
|
113
|
+
Object.assign(headers, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
114
|
+
if (err?.issues) {
|
|
115
|
+
return makeJson(400, {
|
|
116
|
+
error: "ValidationError",
|
|
117
|
+
issues: err.issues
|
|
118
|
+
}, headers);
|
|
119
|
+
}
|
|
120
|
+
if (typeof err?.message === "string" && err.message.startsWith("PolicyDenied")) {
|
|
121
|
+
return makeJson(403, { error: "PolicyDenied" }, headers);
|
|
122
|
+
}
|
|
123
|
+
return makeJson(500, { error: "InternalError" }, headers);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// src/rest-elysia.ts
|
|
129
|
+
function elysiaPlugin(app, reg, ctxFactory, options) {
|
|
130
|
+
const handler = createFetchHandler(reg, (req) => ctxFactory({
|
|
131
|
+
request: req,
|
|
132
|
+
store: app.store
|
|
133
|
+
}), options);
|
|
134
|
+
for (const spec of reg.list()) {
|
|
135
|
+
const method = spec.transport?.rest?.method ?? (spec.meta.kind === "query" ? "GET" : "POST");
|
|
136
|
+
const path = (options?.basePath ?? "") + (spec.transport?.rest?.path ?? `/${spec.meta.key.replace(/\./g, "/")}/v${spec.meta.version}`);
|
|
137
|
+
app[method.toLowerCase()](path, ({ request }) => handler(request));
|
|
138
|
+
}
|
|
139
|
+
if (options?.cors) {
|
|
140
|
+
app.options("*", ({ request }) => handler(request));
|
|
141
|
+
}
|
|
142
|
+
return app;
|
|
143
|
+
}
|
|
144
|
+
export {
|
|
145
|
+
elysiaPlugin
|
|
146
|
+
};
|