@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,161 @@
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-express.ts
129
+ function expressRouter(express, reg, ctxFactory, options) {
130
+ const router = express.Router();
131
+ for (const spec of reg.list()) {
132
+ const method = spec.transport?.rest?.method ?? (spec.meta.kind === "query" ? "GET" : "POST");
133
+ const path = (options?.basePath ?? "") + (spec.transport?.rest?.path ?? `/${spec.meta.key.replace(/\./g, "/")}/v${spec.meta.version}`);
134
+ router[method.toLowerCase()](path, async (req, res) => {
135
+ const url = new URL(`${req.protocol}://${req.get("host")}${req.originalUrl}`);
136
+ const request = new Request(url.toString(), {
137
+ method,
138
+ headers: Object.fromEntries(Object.entries(req.headers).map(([k, v]) => [k, String(v)])),
139
+ body: method === "POST" ? JSON.stringify(req.body ?? {}) : undefined
140
+ });
141
+ const handler = createFetchHandler(reg, () => ctxFactory(req), options);
142
+ const response = await handler(request);
143
+ res.status(response.status);
144
+ response.headers.forEach((v, k) => res.setHeader(k, v));
145
+ const text = await response.text();
146
+ res.send(text);
147
+ });
148
+ }
149
+ if (options?.cors) {
150
+ router.options("*", (_req, res) => {
151
+ const h = new Headers;
152
+ const resp = new Response(null, { status: 204 });
153
+ resp.headers.forEach((v, k) => h.set(k, v));
154
+ res.status(204).send();
155
+ });
156
+ }
157
+ return router;
158
+ }
159
+ export {
160
+ expressRouter
161
+ };
@@ -0,0 +1,129 @@
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
+ export {
128
+ createFetchHandler
129
+ };
@@ -0,0 +1,137 @@
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-next-app.ts
129
+ function makeNextAppHandler(reg, ctxFactory, options) {
130
+ const handler = createFetchHandler(reg, ctxFactory, options);
131
+ return async function requestHandler(req) {
132
+ return handler(req);
133
+ };
134
+ }
135
+ export {
136
+ makeNextAppHandler
137
+ };
@@ -0,0 +1,148 @@
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-next-pages.ts
129
+ function makeNextPagesHandler(reg, ctxFactory, options) {
130
+ return async function handler(req, res) {
131
+ const url = `${req.headers["x-forwarded-proto"] ?? "http"}://${req.headers.host}${req.url}`;
132
+ const method = req.method?.toUpperCase() || "GET";
133
+ const request = new Request(url, {
134
+ method,
135
+ headers: Object.fromEntries(Object.entries(req.headers).map(([k, v]) => [k, String(v)])),
136
+ body: method === "POST" ? JSON.stringify(req.body ?? {}) : undefined
137
+ });
138
+ const perReqHandler = createFetchHandler(reg, () => ctxFactory(req), options);
139
+ const response = await perReqHandler(request);
140
+ res.status(response.status);
141
+ response.headers.forEach((v, k) => res.setHeader(k, v));
142
+ const text = await response.text();
143
+ res.send(text);
144
+ };
145
+ }
146
+ export {
147
+ makeNextPagesHandler
148
+ };
@@ -0,0 +1,11 @@
1
+ import type { ResourceRegistry } from '@contractspec/lib.contracts-spec/resources';
2
+ export interface ReturnsDecl {
3
+ isList: boolean;
4
+ inner: string;
5
+ }
6
+ export declare function parseReturns(returnsLike: string): ReturnsDecl;
7
+ export declare function hydrateResourceIfNeeded(resources: ResourceRegistry | undefined, result: unknown, opts: {
8
+ template?: string;
9
+ varName?: string;
10
+ returns: ReturnsDecl;
11
+ }): Promise<unknown>;
@@ -0,0 +1,41 @@
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
+ export {
39
+ parseReturns,
40
+ hydrateResourceIfNeeded
41
+ };
@@ -0,0 +1,5 @@
1
+ import type { AnySchemaModel } from '@contractspec/lib.schema';
2
+ import type { SchemaTypes } from '@pothos/core';
3
+ export declare function createInputTypeBuilder<T extends SchemaTypes>(builder: PothosSchemaTypes.SchemaBuilder<T>): {
4
+ buildInputFieldArgs: (model: AnySchemaModel | null) => null;
5
+ };