@fluixi/api 1.0.0-alpha.107 → 1.0.0-alpha.109

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/dist/input.mjs CHANGED
@@ -1,66 +1,10 @@
1
- // src/errors.ts
2
- var ApiError = class extends Error {
3
- constructor(status, code, message, details) {
4
- super(message);
5
- this.name = "ApiError";
6
- this.status = status;
7
- this.code = code;
8
- this.details = details;
9
- }
10
- };
11
-
12
- // src/input.ts
13
- var DEFAULT_BODY_LIMIT = 1024 * 1024;
14
- function readQuery(url) {
15
- const out = {};
16
- for (const [key, value] of url.searchParams) {
17
- const seen = out[key];
18
- if (seen === void 0) out[key] = value;
19
- else out[key] = Array.isArray(seen) ? [...seen, value] : [seen, value];
20
- }
21
- return out;
22
- }
23
- async function readJson(request, limit = DEFAULT_BODY_LIMIT) {
24
- const declared = Number(request.headers.get("content-length"));
25
- if (Number.isFinite(declared) && declared > limit) throw tooLarge(limit);
26
- if (!request.body) return void 0;
27
- const type = request.headers.get("content-type") ?? "";
28
- const reader = request.body.getReader();
29
- const chunks = [];
30
- let size = 0;
31
- for (; ; ) {
32
- const { done, value } = await reader.read();
33
- if (done) break;
34
- size += value.byteLength;
35
- if (size > limit) {
36
- await reader.cancel();
37
- throw tooLarge(limit);
38
- }
39
- chunks.push(value);
40
- }
41
- if (size === 0) return void 0;
42
- if (!isJson(type)) {
43
- throw new ApiError(415, "unsupported_media_type", "Send the body as application/json.");
44
- }
45
- const bytes = new Uint8Array(size);
46
- let offset = 0;
47
- for (const chunk of chunks) {
48
- bytes.set(chunk, offset);
49
- offset += chunk.byteLength;
50
- }
51
- try {
52
- return JSON.parse(new TextDecoder().decode(bytes));
53
- } catch {
54
- throw new ApiError(400, "invalid_json", "The body is not valid JSON.");
55
- }
56
- }
57
- function isJson(type) {
58
- const mime = type.split(";")[0].trim().toLowerCase();
59
- return mime === "application/json" || mime.endsWith("+json");
60
- }
61
- function tooLarge(limit) {
62
- return new ApiError(413, "payload_too_large", `The body is larger than ${limit} bytes.`);
63
- }
1
+ import {
2
+ DEFAULT_BODY_LIMIT,
3
+ readJson,
4
+ readQuery
5
+ } from "./chunk-QZA7GDGB.mjs";
6
+ import "./chunk-FIHRBQUV.mjs";
7
+ import "./chunk-GTIH4MXK.mjs";
64
8
  export {
65
9
  DEFAULT_BODY_LIMIT,
66
10
  readJson,
@@ -1,19 +1,8 @@
1
- // src/middleware.ts
2
- function withHeaders(response, set) {
3
- try {
4
- set(response.headers);
5
- return response;
6
- } catch {
7
- const copy = new Response(response.body, response);
8
- set(copy.headers);
9
- return copy;
10
- }
11
- }
12
- function appendVary(headers, name) {
13
- const vary = headers.get("vary");
14
- if (!vary) headers.set("vary", name);
15
- else if (!vary.split(",").some((v) => v.trim().toLowerCase() === name.toLowerCase())) headers.set("vary", `${vary}, ${name}`);
16
- }
1
+ import {
2
+ appendVary,
3
+ withHeaders
4
+ } from "./chunk-MI6ZXL3J.mjs";
5
+ import "./chunk-GTIH4MXK.mjs";
17
6
  export {
18
7
  appendVary,
19
8
  withHeaders
package/dist/openapi.mjs CHANGED
@@ -1,255 +1,14 @@
1
- // src/input.ts
2
- var DEFAULT_BODY_LIMIT = 1024 * 1024;
3
-
4
- // src/route.ts
5
- var CONTRACT = /* @__PURE__ */ Symbol.for("fluixi.api.contract");
6
- function contractOf(handler) {
7
- return typeof handler === "function" ? handler[CONTRACT] : void 0;
8
- }
9
-
10
- // src/openapi.ts
11
- var convert;
12
- function setJsonSchemaConverter(converter) {
13
- convert = converter;
14
- }
15
- var METHODS = ["get", "post", "put", "patch", "delete"];
16
- var DESCRIBES = /* @__PURE__ */ Symbol.for("fluixi.api.describes");
17
- var DESCRIBED_BY = /* @__PURE__ */ Symbol.for("fluixi.api.described-by");
18
- function describedBy(document, handler) {
19
- Object.defineProperty(handler, DESCRIBED_BY, { value: document });
20
- return handler;
21
- }
22
- var ERROR_SCHEMA = {
23
- type: "object",
24
- required: ["error"],
25
- properties: {
26
- error: {
27
- type: "object",
28
- required: ["code", "message"],
29
- properties: {
30
- code: { type: "string", description: "Machine-readable, stable: `validation_failed`, `not_found`, `internal`." },
31
- message: { type: "string", description: "For people. May change between versions." },
32
- details: { description: "For `validation_failed`, the list of `{ path, message }` issues." }
33
- }
34
- }
35
- }
36
- };
37
- function createOpenApiDocument(routes, info) {
38
- const paths = {};
39
- const securitySchemes = {};
40
- for (const route of routes) {
41
- if (!route.path) continue;
42
- for (const method of METHODS) {
43
- const handler = route.mod[method.toUpperCase()];
44
- if (typeof handler !== "function") continue;
45
- const marks = handler;
46
- if (marks[DESCRIBES] || marks[DESCRIBED_BY]) continue;
47
- (paths[route.path] ??= {})[method] = operation(method, route.path, contractOf(handler), securitySchemes);
48
- }
49
- }
50
- const { servers, ...rest } = info;
51
- return {
52
- openapi: "3.1.0",
53
- info: rest,
54
- ...servers?.length ? { servers } : {},
55
- paths,
56
- components: { schemas: { Error: ERROR_SCHEMA }, ...Object.keys(securitySchemes).length ? { securitySchemes } : {} }
57
- };
58
- }
59
- function openApiRoute(routes, info) {
60
- let cached;
61
- const handler = async () => {
62
- cached ??= describe(routes(), info).catch((error) => {
63
- cached = void 0;
64
- throw error;
65
- });
66
- return new Response(await cached, { headers: { "content-type": "application/json; charset=utf-8" } });
67
- };
68
- Object.defineProperty(handler, DESCRIBES, { value: true });
69
- return handler;
70
- }
71
- async function describe(routes, info) {
72
- const doc = createOpenApiDocument(routes, info);
73
- const mounts = /* @__PURE__ */ new Map();
74
- for (const route of routes) {
75
- if (!route.path) continue;
76
- for (const handler of Object.values(route.mod)) {
77
- const source = typeof handler === "function" ? handler[DESCRIBED_BY] : void 0;
78
- if (source && !mounts.has(source)) mounts.set(source, route.path.replace(/\/\{[^}]+\}$/, ""));
79
- }
80
- }
81
- for (const [source, mount] of mounts) includeDocument(doc, await source(), mount);
82
- return JSON.stringify(doc, null, 2);
83
- }
84
- function includeDocument(target, source, mount) {
85
- const prefix = pascal(mount.split("/").filter(Boolean).pop() ?? "included");
86
- const components = target.components ??= {};
87
- const prefixed = (name) => prefix + name[0].toUpperCase() + name.slice(1);
88
- const renames = /* @__PURE__ */ new Map();
89
- for (const [section, entries] of Object.entries(source.components ?? {})) {
90
- for (const [name, value] of Object.entries(entries)) {
91
- const existing = components[section]?.[name];
92
- if (existing !== void 0 && JSON.stringify(existing) !== JSON.stringify(value)) {
93
- renames.set(`#/components/${section}/${name}`, `#/components/${section}/${prefixed(name)}`);
94
- }
95
- }
96
- }
97
- const rewrite = (node) => {
98
- if (Array.isArray(node)) return node.map(rewrite);
99
- if (!node || typeof node !== "object") return node;
100
- const out = Object.fromEntries(
101
- Object.entries(node).map(([key, value]) => [key, key === "$ref" && typeof value === "string" ? renames.get(value) ?? value : rewrite(value)])
102
- );
103
- return "nullable" in out ? nullable(out) : out;
104
- };
105
- for (const [section, entries] of Object.entries(source.components ?? {})) {
106
- const into = components[section] ??= {};
107
- for (const [name, value] of Object.entries(entries)) {
108
- const renamed = renames.has(`#/components/${section}/${name}`) ? prefixed(name) : name;
109
- into[renamed] = rewrite(value);
110
- }
111
- }
112
- const paths = target.paths ??= {};
113
- const ids = new Set(Object.values(paths).flatMap((item) => Object.values(item).map((op) => op?.operationId)));
114
- for (const [path, item] of Object.entries(source.paths ?? {})) {
115
- const described = rewrite(item);
116
- for (const [method, op] of Object.entries(described)) {
117
- if (Array.isArray(op.security)) {
118
- op.security = op.security.map(
119
- (requirement) => Object.fromEntries(
120
- Object.entries(requirement).map(([name, scopes]) => [
121
- renames.has(`#/components/securitySchemes/${name}`) ? prefixed(name) : name,
122
- scopes
123
- ])
124
- )
125
- );
126
- }
127
- if (METHODS.includes(method) && !op.summary) op.summary = summaryOf(op, method, mount + path);
128
- if (typeof op.operationId === "string" && ids.has(op.operationId)) {
129
- op.operationId = prefix[0].toLowerCase() + prefix.slice(1) + op.operationId[0].toUpperCase() + op.operationId.slice(1);
130
- }
131
- if (typeof op.operationId === "string") ids.add(op.operationId);
132
- }
133
- paths[mount + path] = described;
134
- }
135
- const tags = source.tags ?? [];
136
- if (tags.length) {
137
- const known = target.tags ??= [];
138
- for (const tag of tags) if (!known.some((t) => t.name === tag.name)) known.push(tag);
139
- }
140
- }
141
- function nullable(schema) {
142
- const { nullable: isNullable, ...rest } = schema;
143
- if (isNullable !== true) return rest;
144
- if (typeof rest.type === "string") return { ...rest, type: [rest.type, "null"] };
145
- if (Array.isArray(rest.type)) return rest.type.includes("null") ? rest : { ...rest, type: [...rest.type, "null"] };
146
- return { anyOf: [rest, { type: "null" }] };
147
- }
148
- function summaryOf(op, method, path) {
149
- const description = typeof op.description === "string" ? op.description.split(/\.\s|\n/)[0].trim() : "";
150
- if (description && description.length <= 60) return description.replace(/\.$/, "");
151
- return typeof op.operationId === "string" ? op.operationId.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/^./, (c) => c.toUpperCase()) : summaryFor(method, path);
152
- }
153
- function pascal(word) {
154
- return word.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join("");
155
- }
156
- function operation(method, path, contract, schemes) {
157
- const operationId = contract?.operationId ?? idFor(method, path);
158
- if (!contract) {
159
- return {
160
- operationId,
161
- tags: [tagFor(path)],
162
- summary: `${method.toUpperCase()} ${path}`,
163
- description: "This route declares no contract, so nothing about its input or output is known.",
164
- "x-fluixi-contract": false,
165
- responses: { default: { description: "Undocumented." } }
166
- };
167
- }
168
- const parameters = [
169
- ...parametersFrom(contract.params, "path", pathNames(path)),
170
- ...parametersFrom(contract.query, "query", [])
171
- ];
172
- const success = contract.status ?? (contract.response ? 200 : 204);
173
- const responses = {
174
- [success]: contract.response ? { description: "Success.", content: { "application/json": { schema: schemaFor(contract.response, "output") } } } : { description: "Success, no content." }
175
- };
176
- const error = (description) => ({ description, content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } });
177
- if (contract.params || contract.query || contract.body) responses[400] = error("The request is not valid: `validation_failed`, `invalid_json`.");
178
- if (contract.body) {
179
- responses[413] = error("The body is over the limit.");
180
- responses[415] = error("The body is not JSON.");
181
- }
182
- const guard = contract.guard;
183
- if (guard) {
184
- const refuses = guard.refuses ?? [401];
185
- if (refuses.includes(401)) responses[401] = error("Not signed in: `unauthorized`.");
186
- if (refuses.includes(403)) responses[403] = error("Signed in, not allowed: `forbidden`, or a more precise code.");
187
- if (refuses.includes(503)) responses[503] = error("A service the check depends on cannot answer now; try again.");
188
- }
189
- if (pathNames(path).length) responses[404] = error("Nothing at this path.");
190
- responses[500] = error("A fault on the server. Its detail is logged, never sent.");
191
- return {
192
- operationId,
193
- tags: contract.tags?.length ? contract.tags : [tagFor(path)],
194
- // Tools name the request after it (Postman does), so there is always one.
195
- summary: contract.summary ?? summaryFor(method, path),
196
- ...contract.description ? { description: contract.description } : {},
197
- ...contract.deprecated ? { deprecated: true } : {},
198
- // Stated on every contracted route, so a public one reads as public rather than unknown.
199
- security: security(guard, schemes),
200
- ...parameters.length ? { parameters } : {},
201
- ...contract.body ? { requestBody: { required: true, content: { "application/json": { schema: schemaFor(contract.body, "input") } } } } : {},
202
- responses
203
- };
204
- }
205
- function security(guard, schemes) {
206
- if (!guard?.security) return [];
207
- const { name, scheme, scopes } = guard.security;
208
- schemes[name] = scheme;
209
- return [{ [name]: scopes ?? [] }];
210
- }
211
- function parametersFrom(schema, where, names) {
212
- if (!schema) return where === "path" ? names.map((name) => ({ name, in: "path", required: true, schema: { type: "string" } })) : [];
213
- const json = schemaFor(schema, "input");
214
- const properties = json.properties ?? {};
215
- const required = new Set(json.required ?? []);
216
- return Object.entries(properties).map(([name, property]) => ({
217
- name,
218
- in: where,
219
- required: where === "path" ? true : required.has(name),
220
- ...typeof property.description === "string" ? { description: property.description } : {},
221
- schema: property,
222
- ...where === "query" && property.type === "array" ? { style: "form", explode: true } : {}
223
- }));
224
- }
225
- function schemaFor(schema, io) {
226
- const standard = schema["~standard"].jsonSchema;
227
- try {
228
- const json = standard?.[io]({ target: "draft-2020-12", libraryOptions: { unrepresentable: "any" } }) ?? convert?.(schema, io);
229
- if (json) {
230
- const { $schema: _dialect, ...rest } = json;
231
- return rest;
232
- }
233
- } catch {
234
- }
235
- return { "x-fluixi-unconverted": schema["~standard"].vendor };
236
- }
237
- function pathNames(path) {
238
- return [...path.matchAll(/\{([^}]+)\}/g)].map((m) => m[1]);
239
- }
240
- function tagFor(path) {
241
- const segments = path.split("/").filter((s) => s && !s.startsWith("{"));
242
- const meaningful = segments.filter((s, i) => !(i === 0 && s === "api") && !/^v\d+$/.test(s));
243
- return meaningful[0] ?? "default";
244
- }
245
- function summaryFor(method, path) {
246
- const words = idFor(method, path).replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase();
247
- return words[0].toUpperCase() + words.slice(1);
248
- }
249
- function idFor(method, path) {
250
- const words = path.split("/").filter((s) => s && s !== "api" && !/^v\d+$/.test(s)).map((s) => s.startsWith("{") ? `By-${s.slice(1, -1)}` : s).flatMap((s) => s.split(/[^a-zA-Z0-9]+/)).filter(Boolean);
251
- return method + words.map((w) => w[0].toUpperCase() + w.slice(1)).join("");
252
- }
1
+ import {
2
+ createOpenApiDocument,
3
+ describedBy,
4
+ includeDocument,
5
+ openApiRoute,
6
+ setJsonSchemaConverter
7
+ } from "./chunk-H7XKDP6F.mjs";
8
+ import "./chunk-GKZ2OUXD.mjs";
9
+ import "./chunk-QZA7GDGB.mjs";
10
+ import "./chunk-FIHRBQUV.mjs";
11
+ import "./chunk-GTIH4MXK.mjs";
253
12
  export {
254
13
  createOpenApiDocument,
255
14
  describedBy,