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