@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
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/rest-generic.ts
|
|
3
|
+
import { defaultRestPath } from "@contractspec/lib.contracts-spec/jsonschema";
|
|
4
|
+
function corsHeaders(opt) {
|
|
5
|
+
const h = {};
|
|
6
|
+
const origin = typeof opt === "object" ? opt.origin ?? "*" : "*";
|
|
7
|
+
h["access-control-allow-origin"] = origin;
|
|
8
|
+
h["vary"] = "Origin";
|
|
9
|
+
if (typeof opt === "object") {
|
|
10
|
+
if (opt.methods)
|
|
11
|
+
h["access-control-allow-methods"] = opt.methods.join(", ");
|
|
12
|
+
if (opt.headers)
|
|
13
|
+
h["access-control-allow-headers"] = opt.headers.join(", ");
|
|
14
|
+
if (opt.credentials)
|
|
15
|
+
h["access-control-allow-credentials"] = "true";
|
|
16
|
+
if (typeof opt.maxAge === "number") {
|
|
17
|
+
h["access-control-max-age"] = String(opt.maxAge);
|
|
18
|
+
}
|
|
19
|
+
} else {
|
|
20
|
+
h["access-control-allow-methods"] = "GET,POST,OPTIONS";
|
|
21
|
+
h["access-control-allow-headers"] = "content-type,x-idempotency-key,x-trace-id";
|
|
22
|
+
}
|
|
23
|
+
return h;
|
|
24
|
+
}
|
|
25
|
+
function joinPath(a, b) {
|
|
26
|
+
const left = (a ?? "").replace(/\/+$/g, "");
|
|
27
|
+
const right = b.replace(/^\/+/g, "");
|
|
28
|
+
return `${left}/${right}`.replace(/\/{2,}/g, "/");
|
|
29
|
+
}
|
|
30
|
+
function createFetchHandler(reg, ctxFactory, options) {
|
|
31
|
+
const opts = {
|
|
32
|
+
basePath: options?.basePath ?? "",
|
|
33
|
+
cors: options?.cors ?? false,
|
|
34
|
+
prettyJson: options?.prettyJson ?? false,
|
|
35
|
+
onError: options?.onError
|
|
36
|
+
};
|
|
37
|
+
const routes = reg.list().map((spec) => ({
|
|
38
|
+
method: spec.transport?.rest?.method ?? (spec.meta.kind === "query" ? "GET" : "POST"),
|
|
39
|
+
path: joinPath(opts.basePath, spec.transport?.rest?.path ?? defaultRestPath(spec.meta.key, spec.meta.version)),
|
|
40
|
+
name: spec.meta.key,
|
|
41
|
+
version: spec.meta.version
|
|
42
|
+
}));
|
|
43
|
+
const routeTable = new Map;
|
|
44
|
+
for (const r of routes)
|
|
45
|
+
routeTable.set(`${r.method} ${r.path}`, r);
|
|
46
|
+
const makeJson = (status, data, extraHeaders) => {
|
|
47
|
+
const body = opts.prettyJson ? JSON.stringify(data, null, opts.prettyJson) : JSON.stringify(data);
|
|
48
|
+
const base = {
|
|
49
|
+
"content-type": "application/json; charset=utf-8"
|
|
50
|
+
};
|
|
51
|
+
return new Response(body, {
|
|
52
|
+
status,
|
|
53
|
+
headers: extraHeaders ? { ...base, ...extraHeaders } : base
|
|
54
|
+
});
|
|
55
|
+
};
|
|
56
|
+
return async function handle(req) {
|
|
57
|
+
const url = new URL(req.url);
|
|
58
|
+
const key = `${req.method.toUpperCase()} ${url.pathname}`;
|
|
59
|
+
if (opts.cors && req.method.toUpperCase() === "OPTIONS") {
|
|
60
|
+
const h = corsHeaders(opts.cors === true ? {} : opts.cors);
|
|
61
|
+
return new Response(null, {
|
|
62
|
+
status: 204,
|
|
63
|
+
headers: { ...h, "content-length": "0" }
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
const route = routeTable.get(key);
|
|
67
|
+
if (!route) {
|
|
68
|
+
const headers = {};
|
|
69
|
+
if (opts.cors)
|
|
70
|
+
Object.assign(headers, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
71
|
+
return makeJson(404, { error: "NotFound", path: url.pathname }, headers);
|
|
72
|
+
}
|
|
73
|
+
try {
|
|
74
|
+
let input = {};
|
|
75
|
+
if (route.method === "GET") {
|
|
76
|
+
if (url.searchParams.has("input")) {
|
|
77
|
+
const raw = url.searchParams.get("input");
|
|
78
|
+
input = raw ? JSON.parse(raw) : {};
|
|
79
|
+
} else {
|
|
80
|
+
const obj = {};
|
|
81
|
+
for (const [k, v] of url.searchParams.entries())
|
|
82
|
+
obj[k] = v;
|
|
83
|
+
input = obj;
|
|
84
|
+
}
|
|
85
|
+
} else {
|
|
86
|
+
const contentType = req.headers.get("content-type") || "";
|
|
87
|
+
if (contentType.includes("application/json")) {
|
|
88
|
+
input = await req.json();
|
|
89
|
+
} else if (contentType.includes("application/x-www-form-urlencoded")) {
|
|
90
|
+
const form = await req.formData();
|
|
91
|
+
input = Object.fromEntries(form.entries());
|
|
92
|
+
} else if (!contentType) {
|
|
93
|
+
input = {};
|
|
94
|
+
} else {
|
|
95
|
+
return makeJson(415, { error: "UnsupportedMediaType", contentType });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const ctx = ctxFactory(req);
|
|
99
|
+
const result = await reg.execute(route.name, route.version, input, ctx);
|
|
100
|
+
const headers = {};
|
|
101
|
+
if (opts.cors)
|
|
102
|
+
Object.assign(headers, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
103
|
+
return makeJson(200, result, headers);
|
|
104
|
+
} catch (err) {
|
|
105
|
+
if (opts.onError) {
|
|
106
|
+
const mapped = opts.onError(err);
|
|
107
|
+
const headers2 = {};
|
|
108
|
+
if (opts.cors)
|
|
109
|
+
Object.assign(headers2, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
110
|
+
return makeJson(mapped.status, mapped.body, headers2);
|
|
111
|
+
}
|
|
112
|
+
const headers = {};
|
|
113
|
+
if (opts.cors)
|
|
114
|
+
Object.assign(headers, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
115
|
+
if (err?.issues) {
|
|
116
|
+
return makeJson(400, {
|
|
117
|
+
error: "ValidationError",
|
|
118
|
+
issues: err.issues
|
|
119
|
+
}, headers);
|
|
120
|
+
}
|
|
121
|
+
if (typeof err?.message === "string" && err.message.startsWith("PolicyDenied")) {
|
|
122
|
+
return makeJson(403, { error: "PolicyDenied" }, headers);
|
|
123
|
+
}
|
|
124
|
+
return makeJson(500, { error: "InternalError" }, headers);
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// src/rest-express.ts
|
|
130
|
+
function expressRouter(express, reg, ctxFactory, options) {
|
|
131
|
+
const router = express.Router();
|
|
132
|
+
for (const spec of reg.list()) {
|
|
133
|
+
const method = spec.transport?.rest?.method ?? (spec.meta.kind === "query" ? "GET" : "POST");
|
|
134
|
+
const path = (options?.basePath ?? "") + (spec.transport?.rest?.path ?? `/${spec.meta.key.replace(/\./g, "/")}/v${spec.meta.version}`);
|
|
135
|
+
router[method.toLowerCase()](path, async (req, res) => {
|
|
136
|
+
const url = new URL(`${req.protocol}://${req.get("host")}${req.originalUrl}`);
|
|
137
|
+
const request = new Request(url.toString(), {
|
|
138
|
+
method,
|
|
139
|
+
headers: Object.fromEntries(Object.entries(req.headers).map(([k, v]) => [k, String(v)])),
|
|
140
|
+
body: method === "POST" ? JSON.stringify(req.body ?? {}) : undefined
|
|
141
|
+
});
|
|
142
|
+
const handler = createFetchHandler(reg, () => ctxFactory(req), options);
|
|
143
|
+
const response = await handler(request);
|
|
144
|
+
res.status(response.status);
|
|
145
|
+
response.headers.forEach((v, k) => res.setHeader(k, v));
|
|
146
|
+
const text = await response.text();
|
|
147
|
+
res.send(text);
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
if (options?.cors) {
|
|
151
|
+
router.options("*", (_req, res) => {
|
|
152
|
+
const h = new Headers;
|
|
153
|
+
const resp = new Response(null, { status: 204 });
|
|
154
|
+
resp.headers.forEach((v, k) => h.set(k, v));
|
|
155
|
+
res.status(204).send();
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
return router;
|
|
159
|
+
}
|
|
160
|
+
export {
|
|
161
|
+
expressRouter
|
|
162
|
+
};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { OperationSpecRegistry } from '@contractspec/lib.contracts-spec/operations/registry';
|
|
2
|
+
import type { HandlerCtx } from '@contractspec/lib.contracts-spec/types';
|
|
3
|
+
export interface RestOptions {
|
|
4
|
+
basePath?: string;
|
|
5
|
+
cors?: boolean | {
|
|
6
|
+
origin?: string | '*';
|
|
7
|
+
methods?: string[];
|
|
8
|
+
headers?: string[];
|
|
9
|
+
credentials?: boolean;
|
|
10
|
+
maxAge?: number;
|
|
11
|
+
};
|
|
12
|
+
prettyJson?: number | false;
|
|
13
|
+
onError?: (err: unknown) => {
|
|
14
|
+
status: number;
|
|
15
|
+
body: unknown;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export declare function createFetchHandler(reg: OperationSpecRegistry, ctxFactory: (req: Request) => HandlerCtx, options?: RestOptions): (req: Request) => Promise<Response>;
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/rest-generic.ts
|
|
3
|
+
import { defaultRestPath } from "@contractspec/lib.contracts-spec/jsonschema";
|
|
4
|
+
function corsHeaders(opt) {
|
|
5
|
+
const h = {};
|
|
6
|
+
const origin = typeof opt === "object" ? opt.origin ?? "*" : "*";
|
|
7
|
+
h["access-control-allow-origin"] = origin;
|
|
8
|
+
h["vary"] = "Origin";
|
|
9
|
+
if (typeof opt === "object") {
|
|
10
|
+
if (opt.methods)
|
|
11
|
+
h["access-control-allow-methods"] = opt.methods.join(", ");
|
|
12
|
+
if (opt.headers)
|
|
13
|
+
h["access-control-allow-headers"] = opt.headers.join(", ");
|
|
14
|
+
if (opt.credentials)
|
|
15
|
+
h["access-control-allow-credentials"] = "true";
|
|
16
|
+
if (typeof opt.maxAge === "number") {
|
|
17
|
+
h["access-control-max-age"] = String(opt.maxAge);
|
|
18
|
+
}
|
|
19
|
+
} else {
|
|
20
|
+
h["access-control-allow-methods"] = "GET,POST,OPTIONS";
|
|
21
|
+
h["access-control-allow-headers"] = "content-type,x-idempotency-key,x-trace-id";
|
|
22
|
+
}
|
|
23
|
+
return h;
|
|
24
|
+
}
|
|
25
|
+
function joinPath(a, b) {
|
|
26
|
+
const left = (a ?? "").replace(/\/+$/g, "");
|
|
27
|
+
const right = b.replace(/^\/+/g, "");
|
|
28
|
+
return `${left}/${right}`.replace(/\/{2,}/g, "/");
|
|
29
|
+
}
|
|
30
|
+
function createFetchHandler(reg, ctxFactory, options) {
|
|
31
|
+
const opts = {
|
|
32
|
+
basePath: options?.basePath ?? "",
|
|
33
|
+
cors: options?.cors ?? false,
|
|
34
|
+
prettyJson: options?.prettyJson ?? false,
|
|
35
|
+
onError: options?.onError
|
|
36
|
+
};
|
|
37
|
+
const routes = reg.list().map((spec) => ({
|
|
38
|
+
method: spec.transport?.rest?.method ?? (spec.meta.kind === "query" ? "GET" : "POST"),
|
|
39
|
+
path: joinPath(opts.basePath, spec.transport?.rest?.path ?? defaultRestPath(spec.meta.key, spec.meta.version)),
|
|
40
|
+
name: spec.meta.key,
|
|
41
|
+
version: spec.meta.version
|
|
42
|
+
}));
|
|
43
|
+
const routeTable = new Map;
|
|
44
|
+
for (const r of routes)
|
|
45
|
+
routeTable.set(`${r.method} ${r.path}`, r);
|
|
46
|
+
const makeJson = (status, data, extraHeaders) => {
|
|
47
|
+
const body = opts.prettyJson ? JSON.stringify(data, null, opts.prettyJson) : JSON.stringify(data);
|
|
48
|
+
const base = {
|
|
49
|
+
"content-type": "application/json; charset=utf-8"
|
|
50
|
+
};
|
|
51
|
+
return new Response(body, {
|
|
52
|
+
status,
|
|
53
|
+
headers: extraHeaders ? { ...base, ...extraHeaders } : base
|
|
54
|
+
});
|
|
55
|
+
};
|
|
56
|
+
return async function handle(req) {
|
|
57
|
+
const url = new URL(req.url);
|
|
58
|
+
const key = `${req.method.toUpperCase()} ${url.pathname}`;
|
|
59
|
+
if (opts.cors && req.method.toUpperCase() === "OPTIONS") {
|
|
60
|
+
const h = corsHeaders(opts.cors === true ? {} : opts.cors);
|
|
61
|
+
return new Response(null, {
|
|
62
|
+
status: 204,
|
|
63
|
+
headers: { ...h, "content-length": "0" }
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
const route = routeTable.get(key);
|
|
67
|
+
if (!route) {
|
|
68
|
+
const headers = {};
|
|
69
|
+
if (opts.cors)
|
|
70
|
+
Object.assign(headers, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
71
|
+
return makeJson(404, { error: "NotFound", path: url.pathname }, headers);
|
|
72
|
+
}
|
|
73
|
+
try {
|
|
74
|
+
let input = {};
|
|
75
|
+
if (route.method === "GET") {
|
|
76
|
+
if (url.searchParams.has("input")) {
|
|
77
|
+
const raw = url.searchParams.get("input");
|
|
78
|
+
input = raw ? JSON.parse(raw) : {};
|
|
79
|
+
} else {
|
|
80
|
+
const obj = {};
|
|
81
|
+
for (const [k, v] of url.searchParams.entries())
|
|
82
|
+
obj[k] = v;
|
|
83
|
+
input = obj;
|
|
84
|
+
}
|
|
85
|
+
} else {
|
|
86
|
+
const contentType = req.headers.get("content-type") || "";
|
|
87
|
+
if (contentType.includes("application/json")) {
|
|
88
|
+
input = await req.json();
|
|
89
|
+
} else if (contentType.includes("application/x-www-form-urlencoded")) {
|
|
90
|
+
const form = await req.formData();
|
|
91
|
+
input = Object.fromEntries(form.entries());
|
|
92
|
+
} else if (!contentType) {
|
|
93
|
+
input = {};
|
|
94
|
+
} else {
|
|
95
|
+
return makeJson(415, { error: "UnsupportedMediaType", contentType });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const ctx = ctxFactory(req);
|
|
99
|
+
const result = await reg.execute(route.name, route.version, input, ctx);
|
|
100
|
+
const headers = {};
|
|
101
|
+
if (opts.cors)
|
|
102
|
+
Object.assign(headers, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
103
|
+
return makeJson(200, result, headers);
|
|
104
|
+
} catch (err) {
|
|
105
|
+
if (opts.onError) {
|
|
106
|
+
const mapped = opts.onError(err);
|
|
107
|
+
const headers2 = {};
|
|
108
|
+
if (opts.cors)
|
|
109
|
+
Object.assign(headers2, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
110
|
+
return makeJson(mapped.status, mapped.body, headers2);
|
|
111
|
+
}
|
|
112
|
+
const headers = {};
|
|
113
|
+
if (opts.cors)
|
|
114
|
+
Object.assign(headers, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
115
|
+
if (err?.issues) {
|
|
116
|
+
return makeJson(400, {
|
|
117
|
+
error: "ValidationError",
|
|
118
|
+
issues: err.issues
|
|
119
|
+
}, headers);
|
|
120
|
+
}
|
|
121
|
+
if (typeof err?.message === "string" && err.message.startsWith("PolicyDenied")) {
|
|
122
|
+
return makeJson(403, { error: "PolicyDenied" }, headers);
|
|
123
|
+
}
|
|
124
|
+
return makeJson(500, { error: "InternalError" }, headers);
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
export {
|
|
129
|
+
createFetchHandler
|
|
130
|
+
};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type RestOptions } from './rest-generic';
|
|
2
|
+
import type { OperationSpecRegistry } from '@contractspec/lib.contracts-spec/operations/registry';
|
|
3
|
+
import type { HandlerCtx } from '@contractspec/lib.contracts-spec/types';
|
|
4
|
+
export declare function makeNextAppHandler(reg: OperationSpecRegistry, ctxFactory: (req: Request) => HandlerCtx, options?: RestOptions): (req: Request) => Promise<Response>;
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/rest-generic.ts
|
|
3
|
+
import { defaultRestPath } from "@contractspec/lib.contracts-spec/jsonschema";
|
|
4
|
+
function corsHeaders(opt) {
|
|
5
|
+
const h = {};
|
|
6
|
+
const origin = typeof opt === "object" ? opt.origin ?? "*" : "*";
|
|
7
|
+
h["access-control-allow-origin"] = origin;
|
|
8
|
+
h["vary"] = "Origin";
|
|
9
|
+
if (typeof opt === "object") {
|
|
10
|
+
if (opt.methods)
|
|
11
|
+
h["access-control-allow-methods"] = opt.methods.join(", ");
|
|
12
|
+
if (opt.headers)
|
|
13
|
+
h["access-control-allow-headers"] = opt.headers.join(", ");
|
|
14
|
+
if (opt.credentials)
|
|
15
|
+
h["access-control-allow-credentials"] = "true";
|
|
16
|
+
if (typeof opt.maxAge === "number") {
|
|
17
|
+
h["access-control-max-age"] = String(opt.maxAge);
|
|
18
|
+
}
|
|
19
|
+
} else {
|
|
20
|
+
h["access-control-allow-methods"] = "GET,POST,OPTIONS";
|
|
21
|
+
h["access-control-allow-headers"] = "content-type,x-idempotency-key,x-trace-id";
|
|
22
|
+
}
|
|
23
|
+
return h;
|
|
24
|
+
}
|
|
25
|
+
function joinPath(a, b) {
|
|
26
|
+
const left = (a ?? "").replace(/\/+$/g, "");
|
|
27
|
+
const right = b.replace(/^\/+/g, "");
|
|
28
|
+
return `${left}/${right}`.replace(/\/{2,}/g, "/");
|
|
29
|
+
}
|
|
30
|
+
function createFetchHandler(reg, ctxFactory, options) {
|
|
31
|
+
const opts = {
|
|
32
|
+
basePath: options?.basePath ?? "",
|
|
33
|
+
cors: options?.cors ?? false,
|
|
34
|
+
prettyJson: options?.prettyJson ?? false,
|
|
35
|
+
onError: options?.onError
|
|
36
|
+
};
|
|
37
|
+
const routes = reg.list().map((spec) => ({
|
|
38
|
+
method: spec.transport?.rest?.method ?? (spec.meta.kind === "query" ? "GET" : "POST"),
|
|
39
|
+
path: joinPath(opts.basePath, spec.transport?.rest?.path ?? defaultRestPath(spec.meta.key, spec.meta.version)),
|
|
40
|
+
name: spec.meta.key,
|
|
41
|
+
version: spec.meta.version
|
|
42
|
+
}));
|
|
43
|
+
const routeTable = new Map;
|
|
44
|
+
for (const r of routes)
|
|
45
|
+
routeTable.set(`${r.method} ${r.path}`, r);
|
|
46
|
+
const makeJson = (status, data, extraHeaders) => {
|
|
47
|
+
const body = opts.prettyJson ? JSON.stringify(data, null, opts.prettyJson) : JSON.stringify(data);
|
|
48
|
+
const base = {
|
|
49
|
+
"content-type": "application/json; charset=utf-8"
|
|
50
|
+
};
|
|
51
|
+
return new Response(body, {
|
|
52
|
+
status,
|
|
53
|
+
headers: extraHeaders ? { ...base, ...extraHeaders } : base
|
|
54
|
+
});
|
|
55
|
+
};
|
|
56
|
+
return async function handle(req) {
|
|
57
|
+
const url = new URL(req.url);
|
|
58
|
+
const key = `${req.method.toUpperCase()} ${url.pathname}`;
|
|
59
|
+
if (opts.cors && req.method.toUpperCase() === "OPTIONS") {
|
|
60
|
+
const h = corsHeaders(opts.cors === true ? {} : opts.cors);
|
|
61
|
+
return new Response(null, {
|
|
62
|
+
status: 204,
|
|
63
|
+
headers: { ...h, "content-length": "0" }
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
const route = routeTable.get(key);
|
|
67
|
+
if (!route) {
|
|
68
|
+
const headers = {};
|
|
69
|
+
if (opts.cors)
|
|
70
|
+
Object.assign(headers, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
71
|
+
return makeJson(404, { error: "NotFound", path: url.pathname }, headers);
|
|
72
|
+
}
|
|
73
|
+
try {
|
|
74
|
+
let input = {};
|
|
75
|
+
if (route.method === "GET") {
|
|
76
|
+
if (url.searchParams.has("input")) {
|
|
77
|
+
const raw = url.searchParams.get("input");
|
|
78
|
+
input = raw ? JSON.parse(raw) : {};
|
|
79
|
+
} else {
|
|
80
|
+
const obj = {};
|
|
81
|
+
for (const [k, v] of url.searchParams.entries())
|
|
82
|
+
obj[k] = v;
|
|
83
|
+
input = obj;
|
|
84
|
+
}
|
|
85
|
+
} else {
|
|
86
|
+
const contentType = req.headers.get("content-type") || "";
|
|
87
|
+
if (contentType.includes("application/json")) {
|
|
88
|
+
input = await req.json();
|
|
89
|
+
} else if (contentType.includes("application/x-www-form-urlencoded")) {
|
|
90
|
+
const form = await req.formData();
|
|
91
|
+
input = Object.fromEntries(form.entries());
|
|
92
|
+
} else if (!contentType) {
|
|
93
|
+
input = {};
|
|
94
|
+
} else {
|
|
95
|
+
return makeJson(415, { error: "UnsupportedMediaType", contentType });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const ctx = ctxFactory(req);
|
|
99
|
+
const result = await reg.execute(route.name, route.version, input, ctx);
|
|
100
|
+
const headers = {};
|
|
101
|
+
if (opts.cors)
|
|
102
|
+
Object.assign(headers, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
103
|
+
return makeJson(200, result, headers);
|
|
104
|
+
} catch (err) {
|
|
105
|
+
if (opts.onError) {
|
|
106
|
+
const mapped = opts.onError(err);
|
|
107
|
+
const headers2 = {};
|
|
108
|
+
if (opts.cors)
|
|
109
|
+
Object.assign(headers2, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
110
|
+
return makeJson(mapped.status, mapped.body, headers2);
|
|
111
|
+
}
|
|
112
|
+
const headers = {};
|
|
113
|
+
if (opts.cors)
|
|
114
|
+
Object.assign(headers, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
115
|
+
if (err?.issues) {
|
|
116
|
+
return makeJson(400, {
|
|
117
|
+
error: "ValidationError",
|
|
118
|
+
issues: err.issues
|
|
119
|
+
}, headers);
|
|
120
|
+
}
|
|
121
|
+
if (typeof err?.message === "string" && err.message.startsWith("PolicyDenied")) {
|
|
122
|
+
return makeJson(403, { error: "PolicyDenied" }, headers);
|
|
123
|
+
}
|
|
124
|
+
return makeJson(500, { error: "InternalError" }, headers);
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// src/rest-next-app.ts
|
|
130
|
+
function makeNextAppHandler(reg, ctxFactory, options) {
|
|
131
|
+
const handler = createFetchHandler(reg, ctxFactory, options);
|
|
132
|
+
return async function requestHandler(req) {
|
|
133
|
+
return handler(req);
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
export {
|
|
137
|
+
makeNextAppHandler
|
|
138
|
+
};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { NextApiRequest, NextApiResponse } from 'next';
|
|
2
|
+
import { type RestOptions } from './rest-generic';
|
|
3
|
+
import type { OperationSpecRegistry } from '@contractspec/lib.contracts-spec/operations/registry';
|
|
4
|
+
import type { HandlerCtx } from '@contractspec/lib.contracts-spec/types';
|
|
5
|
+
export declare function makeNextPagesHandler(reg: OperationSpecRegistry, ctxFactory: (req: NextApiRequest) => HandlerCtx, options?: RestOptions): (req: NextApiRequest, res: NextApiResponse) => Promise<void>;
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/rest-generic.ts
|
|
3
|
+
import { defaultRestPath } from "@contractspec/lib.contracts-spec/jsonschema";
|
|
4
|
+
function corsHeaders(opt) {
|
|
5
|
+
const h = {};
|
|
6
|
+
const origin = typeof opt === "object" ? opt.origin ?? "*" : "*";
|
|
7
|
+
h["access-control-allow-origin"] = origin;
|
|
8
|
+
h["vary"] = "Origin";
|
|
9
|
+
if (typeof opt === "object") {
|
|
10
|
+
if (opt.methods)
|
|
11
|
+
h["access-control-allow-methods"] = opt.methods.join(", ");
|
|
12
|
+
if (opt.headers)
|
|
13
|
+
h["access-control-allow-headers"] = opt.headers.join(", ");
|
|
14
|
+
if (opt.credentials)
|
|
15
|
+
h["access-control-allow-credentials"] = "true";
|
|
16
|
+
if (typeof opt.maxAge === "number") {
|
|
17
|
+
h["access-control-max-age"] = String(opt.maxAge);
|
|
18
|
+
}
|
|
19
|
+
} else {
|
|
20
|
+
h["access-control-allow-methods"] = "GET,POST,OPTIONS";
|
|
21
|
+
h["access-control-allow-headers"] = "content-type,x-idempotency-key,x-trace-id";
|
|
22
|
+
}
|
|
23
|
+
return h;
|
|
24
|
+
}
|
|
25
|
+
function joinPath(a, b) {
|
|
26
|
+
const left = (a ?? "").replace(/\/+$/g, "");
|
|
27
|
+
const right = b.replace(/^\/+/g, "");
|
|
28
|
+
return `${left}/${right}`.replace(/\/{2,}/g, "/");
|
|
29
|
+
}
|
|
30
|
+
function createFetchHandler(reg, ctxFactory, options) {
|
|
31
|
+
const opts = {
|
|
32
|
+
basePath: options?.basePath ?? "",
|
|
33
|
+
cors: options?.cors ?? false,
|
|
34
|
+
prettyJson: options?.prettyJson ?? false,
|
|
35
|
+
onError: options?.onError
|
|
36
|
+
};
|
|
37
|
+
const routes = reg.list().map((spec) => ({
|
|
38
|
+
method: spec.transport?.rest?.method ?? (spec.meta.kind === "query" ? "GET" : "POST"),
|
|
39
|
+
path: joinPath(opts.basePath, spec.transport?.rest?.path ?? defaultRestPath(spec.meta.key, spec.meta.version)),
|
|
40
|
+
name: spec.meta.key,
|
|
41
|
+
version: spec.meta.version
|
|
42
|
+
}));
|
|
43
|
+
const routeTable = new Map;
|
|
44
|
+
for (const r of routes)
|
|
45
|
+
routeTable.set(`${r.method} ${r.path}`, r);
|
|
46
|
+
const makeJson = (status, data, extraHeaders) => {
|
|
47
|
+
const body = opts.prettyJson ? JSON.stringify(data, null, opts.prettyJson) : JSON.stringify(data);
|
|
48
|
+
const base = {
|
|
49
|
+
"content-type": "application/json; charset=utf-8"
|
|
50
|
+
};
|
|
51
|
+
return new Response(body, {
|
|
52
|
+
status,
|
|
53
|
+
headers: extraHeaders ? { ...base, ...extraHeaders } : base
|
|
54
|
+
});
|
|
55
|
+
};
|
|
56
|
+
return async function handle(req) {
|
|
57
|
+
const url = new URL(req.url);
|
|
58
|
+
const key = `${req.method.toUpperCase()} ${url.pathname}`;
|
|
59
|
+
if (opts.cors && req.method.toUpperCase() === "OPTIONS") {
|
|
60
|
+
const h = corsHeaders(opts.cors === true ? {} : opts.cors);
|
|
61
|
+
return new Response(null, {
|
|
62
|
+
status: 204,
|
|
63
|
+
headers: { ...h, "content-length": "0" }
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
const route = routeTable.get(key);
|
|
67
|
+
if (!route) {
|
|
68
|
+
const headers = {};
|
|
69
|
+
if (opts.cors)
|
|
70
|
+
Object.assign(headers, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
71
|
+
return makeJson(404, { error: "NotFound", path: url.pathname }, headers);
|
|
72
|
+
}
|
|
73
|
+
try {
|
|
74
|
+
let input = {};
|
|
75
|
+
if (route.method === "GET") {
|
|
76
|
+
if (url.searchParams.has("input")) {
|
|
77
|
+
const raw = url.searchParams.get("input");
|
|
78
|
+
input = raw ? JSON.parse(raw) : {};
|
|
79
|
+
} else {
|
|
80
|
+
const obj = {};
|
|
81
|
+
for (const [k, v] of url.searchParams.entries())
|
|
82
|
+
obj[k] = v;
|
|
83
|
+
input = obj;
|
|
84
|
+
}
|
|
85
|
+
} else {
|
|
86
|
+
const contentType = req.headers.get("content-type") || "";
|
|
87
|
+
if (contentType.includes("application/json")) {
|
|
88
|
+
input = await req.json();
|
|
89
|
+
} else if (contentType.includes("application/x-www-form-urlencoded")) {
|
|
90
|
+
const form = await req.formData();
|
|
91
|
+
input = Object.fromEntries(form.entries());
|
|
92
|
+
} else if (!contentType) {
|
|
93
|
+
input = {};
|
|
94
|
+
} else {
|
|
95
|
+
return makeJson(415, { error: "UnsupportedMediaType", contentType });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const ctx = ctxFactory(req);
|
|
99
|
+
const result = await reg.execute(route.name, route.version, input, ctx);
|
|
100
|
+
const headers = {};
|
|
101
|
+
if (opts.cors)
|
|
102
|
+
Object.assign(headers, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
103
|
+
return makeJson(200, result, headers);
|
|
104
|
+
} catch (err) {
|
|
105
|
+
if (opts.onError) {
|
|
106
|
+
const mapped = opts.onError(err);
|
|
107
|
+
const headers2 = {};
|
|
108
|
+
if (opts.cors)
|
|
109
|
+
Object.assign(headers2, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
110
|
+
return makeJson(mapped.status, mapped.body, headers2);
|
|
111
|
+
}
|
|
112
|
+
const headers = {};
|
|
113
|
+
if (opts.cors)
|
|
114
|
+
Object.assign(headers, corsHeaders(opts.cors === true ? {} : opts.cors));
|
|
115
|
+
if (err?.issues) {
|
|
116
|
+
return makeJson(400, {
|
|
117
|
+
error: "ValidationError",
|
|
118
|
+
issues: err.issues
|
|
119
|
+
}, headers);
|
|
120
|
+
}
|
|
121
|
+
if (typeof err?.message === "string" && err.message.startsWith("PolicyDenied")) {
|
|
122
|
+
return makeJson(403, { error: "PolicyDenied" }, headers);
|
|
123
|
+
}
|
|
124
|
+
return makeJson(500, { error: "InternalError" }, headers);
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// src/rest-next-pages.ts
|
|
130
|
+
function makeNextPagesHandler(reg, ctxFactory, options) {
|
|
131
|
+
return async function handler(req, res) {
|
|
132
|
+
const url = `${req.headers["x-forwarded-proto"] ?? "http"}://${req.headers.host}${req.url}`;
|
|
133
|
+
const method = req.method?.toUpperCase() || "GET";
|
|
134
|
+
const request = new Request(url, {
|
|
135
|
+
method,
|
|
136
|
+
headers: Object.fromEntries(Object.entries(req.headers).map(([k, v]) => [k, String(v)])),
|
|
137
|
+
body: method === "POST" ? JSON.stringify(req.body ?? {}) : undefined
|
|
138
|
+
});
|
|
139
|
+
const perReqHandler = createFetchHandler(reg, () => ctxFactory(req), options);
|
|
140
|
+
const response = await perReqHandler(request);
|
|
141
|
+
res.status(response.status);
|
|
142
|
+
response.headers.forEach((v, k) => res.setHeader(k, v));
|
|
143
|
+
const text = await response.text();
|
|
144
|
+
res.send(text);
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
export {
|
|
148
|
+
makeNextPagesHandler
|
|
149
|
+
};
|