@lucidcms/core
Version:
The core of the Lucid CMS. It's responsible for spinning up the API and serving the CMS.
315 lines (309 loc) • 8.99 kB
JavaScript
import {
authenticate_default,
client_authenticate_default,
content_locale_default,
log_route_default,
permissions_default,
validate_body_default,
validate_csrf_default,
validate_params_default,
validate_query_default
} from "./chunk-HLKZRFCZ.js";
import {
constants_default,
translations_default
} from "./chunk-7XW7FQ7W.js";
// src/utils/build-response.ts
var constructBaseUrl = (request) => {
if (request.server.config.host) {
const originalUrl = request.originalUrl.startsWith("/") ? request.originalUrl : `/${request.originalUrl}`;
return new URL(originalUrl, request.server.config.host);
}
return new URL(`${request.protocol}://${request.host}${request.originalUrl}`);
};
var getPath = (request) => {
try {
return constructBaseUrl(request)?.toString().split("?")[0] || "";
} catch (error) {
return request.originalUrl || "";
}
};
var buildMetaLinks = (request, params) => {
const links = [];
if (!params.pagination) return links;
const { page, perPage, count } = params.pagination;
const totalPages = Math.ceil(count / Number(perPage));
try {
const baseUrl = constructBaseUrl(request);
for (let i = 0; i < totalPages; i++) {
const pageUrl = new URL(baseUrl.toString());
if (i !== 0) pageUrl.searchParams.set("page", String(i + 1));
else pageUrl.searchParams.delete("page");
links.push({
active: page === i + 1,
label: String(i + 1),
url: pageUrl.toString(),
page: i + 1
});
}
return links;
} catch (error) {
console.error("Error in buildMetaLinks:", error);
return links;
}
};
var buildLinks = (request, params) => {
if (!params.pagination) return void 0;
try {
const { page, perPage, count } = params.pagination;
const totalPages = perPage === -1 ? 1 : Math.ceil(count / Number(perPage));
const baseUrl = constructBaseUrl(request);
const links = {
first: null,
last: null,
next: null,
prev: null
};
const firstUrl = new URL(baseUrl.toString());
firstUrl.searchParams.delete("page");
links.first = firstUrl.toString();
const lastUrl = new URL(baseUrl.toString());
if (page !== totalPages)
lastUrl.searchParams.set("page", String(totalPages));
links.last = lastUrl.toString();
if (page !== totalPages) {
const nextUrl = new URL(baseUrl.toString());
nextUrl.searchParams.set("page", String(Number(page) + 1));
links.next = nextUrl.toString();
}
if (page !== 1) {
const prevUrl = new URL(baseUrl.toString());
prevUrl.searchParams.set("page", String(Number(page) - 1));
links.prev = prevUrl.toString();
}
return links;
} catch (error) {
console.error("Error in buildLinks:", error);
return void 0;
}
};
var formatAPIResponse = (request, params) => {
let lastPage = null;
if (params.pagination) {
if (params.pagination.perPage === -1) {
lastPage = 1;
} else {
lastPage = Math.ceil(
params.pagination.count / Number(params.pagination.perPage)
);
}
}
const meta = {
path: getPath(request),
links: buildMetaLinks(request, params),
currentPage: params.pagination?.page ?? null,
perPage: params.pagination?.perPage ?? null,
total: Number(params.pagination?.count) || null,
lastPage
};
const links = buildLinks(request, params);
return {
data: params.data || null,
meta,
links
};
};
var build_response_default = formatAPIResponse;
// src/libs/fastify/route.ts
var route = (fastify, opts) => {
const preValidation = [];
const preHandler = [log_route_default("prehandler")];
if (opts.middleware?.authenticate) preHandler.push(authenticate_default);
if (opts.middleware?.clientAuthentication)
preHandler.push(client_authenticate_default);
if (opts.middleware?.validateCSRF) preHandler.push(validate_csrf_default);
if (opts.middleware?.contentLocale) preHandler.push(content_locale_default);
if (opts.zodSchema?.body !== void 0)
preValidation.push(validate_body_default(opts.zodSchema.body));
if (opts.zodSchema?.params !== void 0)
preValidation.push(validate_params_default(opts.zodSchema.params));
if (opts.zodSchema?.query?.formatted !== void 0)
preValidation.push(validate_query_default(opts.zodSchema.query.formatted));
if (opts.permissions) preHandler.push(permissions_default(opts.permissions));
fastify.route({
method: opts.method,
url: opts.url,
// @ts-expect-error - comes from "& { formattedQuery }" on the RouteController
handler: opts.controller,
preValidation,
preHandler,
schema: opts.swaggerSchema,
onResponse: [log_route_default("onResponse")],
bodyLimit: opts.bodyLimit
});
};
var route_default = route;
// src/utils/swagger/swagger-refs.ts
var refs = {
defaultError: "DefaultError"
};
var defaultErrorResponse = {
$id: refs.defaultError,
type: "object",
description: translations_default("swagger_response_default"),
properties: {
status: {
type: "number",
nullable: true
},
code: {
type: "string",
nullable: true
},
name: {
type: "string",
nullable: true
},
message: {
type: "string",
nullable: true
},
errors: {
type: "object",
nullable: true,
additionalProperties: true
}
},
additionalProperties: true
};
var swaggerRegisterRefs = (fastify) => {
fastify.addSchema(defaultErrorResponse);
};
var swagger_refs_default = refs;
// src/utils/swagger/swagger-response.ts
var metaObject = {
type: "object",
properties: {
path: { type: "string" },
links: { type: "array" },
currentPage: { type: "number", nullable: true, example: null },
lastPage: { type: "number", nullable: true, example: null },
perPage: { type: "number", nullable: true, example: null },
total: { type: "number", nullable: true, example: null }
}
};
var paginatedMetaObject = {
type: "object",
properties: {
path: { type: "string" },
links: {
type: "array",
items: {
type: "object",
properties: {
active: { type: "boolean" },
label: { type: "string" },
url: { type: "string", nullable: true },
page: { type: "number" }
}
}
},
currentPage: {
type: "number",
nullable: true,
example: constants_default.query.page
},
lastPage: {
type: "number",
nullable: true,
example: 200 / constants_default.query.perPage
},
perPage: {
type: "number",
nullable: true,
example: constants_default.query.perPage
},
total: { type: "number", nullable: true, example: 200 }
}
};
var linksObject = {
type: "object",
properties: {
first: { type: "string", nullable: true },
last: { type: "string", nullable: true },
next: { type: "string", nullable: true },
prev: { type: "string", nullable: true }
}
};
var swaggerResponse = (config) => {
const response = {};
if (config.schema) {
response[200] = {
description: translations_default("swagger_response_200"),
type: config.noProperties === true ? "null" : "object",
properties: config.noProperties === true ? void 0 : {
data: config.schema,
meta: config.paginated ? paginatedMetaObject : metaObject,
...config.paginated ? { links: linksObject } : {}
}
};
} else {
response[204] = {
description: translations_default("swagger_response_204"),
type: "null"
};
}
response.default = {
$ref: swagger_refs_default.defaultError
};
return response;
};
var swagger_response_default = swaggerResponse;
// src/utils/swagger/swagger-headers.ts
var swaggerHeaders = (headers) => {
const propertise = {};
const required = [];
if (headers.csrf !== void 0) {
propertise._csrf = {
type: "string",
description: translations_default("swagger_csrf_header_description")
};
if (headers.csrf) {
required.push("_csrf");
}
}
if (headers.contentLocale !== void 0) {
propertise["lucid-content-locale"] = {
type: "string",
description: translations_default("swagger_content_locale_header_description"),
example: "en"
};
}
if (headers.clientKey !== void 0) {
propertise["lucid-client-key"] = {
type: "string",
description: translations_default("swagger_client_key_header_description")
};
}
if (headers.authorization !== void 0) {
propertise.Authorization = {
type: "string",
description: translations_default("swagger_authorization_header_description")
};
}
return {
type: "object",
properties: propertise,
required
};
};
var swagger_headers_default = swaggerHeaders;
export {
build_response_default,
route_default,
swaggerRegisterRefs,
swagger_refs_default,
swagger_response_default,
swagger_headers_default
};
//# sourceMappingURL=chunk-JNP7DCNX.js.map