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