@getcronit/pylon
Version:

769 lines (761 loc) • 32.5 kB
JavaScript
import {
app
} from "./chunk-OYREJ7HU.js";
import "./chunk-R6NNLVZJ.js";
// src/plugins/use-pages/setup/index.tsx
import fs from "fs";
import path from "path";
import reactServer from "react-dom/server";
import { trimTrailingSlash } from "hono/trailing-slash";
import {
createStaticHandler,
createStaticRouter,
StaticRouterProvider
} from "react-router";
import { PassThrough, Readable as Readable2 } from "stream";
// src/lib/utils.ts
import { clsx } from "clsx";
import { twMerge } from "tailwind-merge";
function cn(...inputs) {
return twMerge(clsx(inputs));
}
// src/components/logo.tsx
import { jsx, jsxs } from "react/jsx-runtime";
var Logo = (props) => {
return /* @__PURE__ */ jsxs(
"svg",
{
className: cn("h-12 w-auto", props.className),
xmlns: "http://www.w3.org/2000/svg",
xmlnsXlink: "http://www.w3.org/1999/xlink",
zoomAndPan: "magnify",
viewBox: "0 0 286.5 121.500001",
preserveAspectRatio: "xMidYMid meet",
version: "1.0",
children: [
/* @__PURE__ */ jsxs("defs", { children: [
/* @__PURE__ */ jsx("g", {}),
/* @__PURE__ */ jsx("clipPath", { id: "38f6fcde47", children: /* @__PURE__ */ jsx(
"path",
{
d: "M 0.339844 42 L 10 42 L 10 79 L 0.339844 79 Z M 0.339844 42 ",
clipRule: "nonzero"
}
) }),
/* @__PURE__ */ jsx("clipPath", { id: "af000f7256", children: /* @__PURE__ */ jsx(
"path",
{
d: "M 64 23.925781 L 72.789062 23.925781 L 72.789062 96.378906 L 64 96.378906 Z M 64 23.925781 ",
clipRule: "nonzero"
}
) })
] }),
/* @__PURE__ */ jsx("g", { fill: "currentColor", fillOpacity: "1", children: /* @__PURE__ */ jsx("g", { transform: "translate(107.11969, 78.49768)", children: /* @__PURE__ */ jsx("g", { children: /* @__PURE__ */ jsx("path", { d: "M 10.078125 -25.046875 C 11.109375 -26.398438 12.507812 -27.535156 14.28125 -28.453125 C 16.0625 -29.378906 18.070312 -29.84375 20.3125 -29.84375 C 22.863281 -29.84375 25.195312 -29.210938 27.3125 -27.953125 C 29.425781 -26.691406 31.085938 -24.921875 32.296875 -22.640625 C 33.503906 -20.367188 34.109375 -17.757812 34.109375 -14.8125 C 34.109375 -11.863281 33.503906 -9.222656 32.296875 -6.890625 C 31.085938 -4.566406 29.425781 -2.753906 27.3125 -1.453125 C 25.195312 -0.160156 22.863281 0.484375 20.3125 0.484375 C 18.070312 0.484375 16.078125 0.03125 14.328125 -0.875 C 12.585938 -1.78125 11.171875 -2.910156 10.078125 -4.265625 L 10.078125 13.96875 L 4 13.96875 L 4 -29.359375 L 10.078125 -29.359375 Z M 27.921875 -14.8125 C 27.921875 -16.84375 27.503906 -18.59375 26.671875 -20.0625 C 25.835938 -21.539062 24.734375 -22.660156 23.359375 -23.421875 C 21.992188 -24.179688 20.53125 -24.5625 18.96875 -24.5625 C 17.445312 -24.5625 16 -24.171875 14.625 -23.390625 C 13.257812 -22.609375 12.160156 -21.472656 11.328125 -19.984375 C 10.492188 -18.492188 10.078125 -16.734375 10.078125 -14.703125 C 10.078125 -12.679688 10.492188 -10.914062 11.328125 -9.40625 C 12.160156 -7.894531 13.257812 -6.75 14.625 -5.96875 C 16 -5.1875 17.445312 -4.796875 18.96875 -4.796875 C 20.53125 -4.796875 21.992188 -5.191406 23.359375 -5.984375 C 24.734375 -6.785156 25.835938 -7.953125 26.671875 -9.484375 C 27.503906 -11.015625 27.921875 -12.789062 27.921875 -14.8125 Z M 27.921875 -14.8125 " }) }) }) }),
/* @__PURE__ */ jsx("g", { fill: "currentColor", fillOpacity: "1", children: /* @__PURE__ */ jsx("g", { transform: "translate(143.259256, 78.49768)", children: /* @__PURE__ */ jsx("g", { children: /* @__PURE__ */ jsx("path", { d: "M 30.4375 -29.359375 L 12.421875 13.796875 L 6.125 13.796875 L 12.09375 -0.484375 L 0.53125 -29.359375 L 7.296875 -29.359375 L 15.5625 -6.984375 L 24.140625 -29.359375 Z M 30.4375 -29.359375 " }) }) }) }),
/* @__PURE__ */ jsx("g", { fill: "currentColor", fillOpacity: "1", children: /* @__PURE__ */ jsx("g", { transform: "translate(174.281707, 78.49768)", children: /* @__PURE__ */ jsx("g", { children: /* @__PURE__ */ jsx("path", { d: "M 10.078125 -39.4375 L 10.078125 0 L 4 0 L 4 -39.4375 Z M 10.078125 -39.4375 " }) }) }) }),
/* @__PURE__ */ jsx("g", { fill: "currentColor", fillOpacity: "1", children: /* @__PURE__ */ jsx("g", { transform: "translate(188.353752, 78.49768)", children: /* @__PURE__ */ jsx("g", { children: /* @__PURE__ */ jsx("path", { d: "M 16.734375 0.484375 C 13.960938 0.484375 11.457031 -0.144531 9.21875 -1.40625 C 6.976562 -2.664062 5.21875 -4.441406 3.9375 -6.734375 C 2.664062 -9.035156 2.03125 -11.691406 2.03125 -14.703125 C 2.03125 -17.691406 2.6875 -20.335938 4 -22.640625 C 5.3125 -24.953125 7.101562 -26.726562 9.375 -27.96875 C 11.65625 -29.21875 14.195312 -29.84375 17 -29.84375 C 19.8125 -29.84375 22.351562 -29.21875 24.625 -27.96875 C 26.894531 -26.726562 28.6875 -24.953125 30 -22.640625 C 31.320312 -20.335938 31.984375 -17.691406 31.984375 -14.703125 C 31.984375 -11.722656 31.304688 -9.078125 29.953125 -6.765625 C 28.597656 -4.453125 26.757812 -2.664062 24.4375 -1.40625 C 22.113281 -0.144531 19.546875 0.484375 16.734375 0.484375 Z M 16.734375 -4.796875 C 18.296875 -4.796875 19.757812 -5.164062 21.125 -5.90625 C 22.5 -6.65625 23.613281 -7.773438 24.46875 -9.265625 C 25.320312 -10.765625 25.75 -12.578125 25.75 -14.703125 C 25.75 -16.835938 25.335938 -18.640625 24.515625 -20.109375 C 23.703125 -21.585938 22.617188 -22.695312 21.265625 -23.4375 C 19.910156 -24.1875 18.453125 -24.5625 16.890625 -24.5625 C 15.328125 -24.5625 13.878906 -24.1875 12.546875 -23.4375 C 11.210938 -22.695312 10.15625 -21.585938 9.375 -20.109375 C 8.59375 -18.640625 8.203125 -16.835938 8.203125 -14.703125 C 8.203125 -11.546875 9.007812 -9.101562 10.625 -7.375 C 12.25 -5.65625 14.285156 -4.796875 16.734375 -4.796875 Z M 16.734375 -4.796875 " }) }) }) }),
/* @__PURE__ */ jsx("g", { fill: "currentColor", fillOpacity: "1", children: /* @__PURE__ */ jsx("g", { transform: "translate(222.361196, 78.49768)", children: /* @__PURE__ */ jsx("g", { children: /* @__PURE__ */ jsx("path", { d: "M 18.8125 -29.84375 C 21.125 -29.84375 23.191406 -29.363281 25.015625 -28.40625 C 26.847656 -27.445312 28.28125 -26.023438 29.3125 -24.140625 C 30.34375 -22.253906 30.859375 -19.984375 30.859375 -17.328125 L 30.859375 0 L 24.84375 0 L 24.84375 -16.421875 C 24.84375 -19.046875 24.179688 -21.054688 22.859375 -22.453125 C 21.546875 -23.859375 19.753906 -24.5625 17.484375 -24.5625 C 15.210938 -24.5625 13.410156 -23.859375 12.078125 -22.453125 C 10.742188 -21.054688 10.078125 -19.046875 10.078125 -16.421875 L 10.078125 0 L 4 0 L 4 -29.359375 L 10.078125 -29.359375 L 10.078125 -26.015625 C 11.066406 -27.222656 12.332031 -28.160156 13.875 -28.828125 C 15.425781 -29.503906 17.070312 -29.84375 18.8125 -29.84375 Z M 18.8125 -29.84375 " }) }) }) }),
/* @__PURE__ */ jsx(
"path",
{
fill: "currentColor",
d: "M 53.359375 31.652344 L 53.359375 88.6875 L 62.410156 90.859375 L 62.410156 29.484375 Z M 53.359375 31.652344 ",
fillOpacity: "1",
fillRule: "nonzero"
}
),
/* @__PURE__ */ jsx("g", { clipPath: "url(#38f6fcde47)", children: /* @__PURE__ */ jsx(
"path",
{
fill: "currentColor",
d: "M 0.339844 47.433594 L 0.339844 72.910156 C 0.339844 73.34375 0.410156 73.769531 0.554688 74.179688 C 0.699219 74.59375 0.90625 74.96875 1.175781 75.3125 C 1.445312 75.65625 1.765625 75.945312 2.132812 76.179688 C 2.503906 76.414062 2.898438 76.582031 3.324219 76.683594 L 9.390625 78.140625 L 9.390625 42.195312 L 3.3125 43.660156 C 2.890625 43.761719 2.492188 43.929688 2.125 44.164062 C 1.761719 44.402344 1.441406 44.6875 1.171875 45.03125 C 0.902344 45.375 0.695312 45.75 0.554688 46.164062 C 0.410156 46.574219 0.339844 46.996094 0.339844 47.433594 Z M 0.339844 47.433594 ",
fillOpacity: "1",
fillRule: "nonzero"
}
) }),
/* @__PURE__ */ jsx("g", { clipPath: "url(#af000f7256)", children: /* @__PURE__ */ jsx(
"path",
{
fill: "currentColor",
d: "M 64.996094 95.085938 L 64.996094 25.253906 C 64.996094 25.082031 65.027344 24.917969 65.09375 24.761719 C 65.160156 24.601562 65.253906 24.460938 65.375 24.339844 C 65.496094 24.21875 65.636719 24.125 65.792969 24.0625 C 65.953125 23.996094 66.117188 23.960938 66.289062 23.960938 L 71.460938 23.960938 C 71.632812 23.960938 71.796875 23.996094 71.957031 24.0625 C 72.113281 24.125 72.253906 24.21875 72.375 24.339844 C 72.496094 24.460938 72.589844 24.601562 72.65625 24.761719 C 72.722656 24.917969 72.753906 25.082031 72.753906 25.253906 L 72.753906 95.085938 C 72.753906 95.257812 72.722656 95.421875 72.65625 95.582031 C 72.589844 95.738281 72.496094 95.878906 72.375 96 C 72.253906 96.121094 72.113281 96.214844 71.957031 96.28125 C 71.796875 96.347656 71.632812 96.378906 71.460938 96.378906 L 66.289062 96.378906 C 66.117188 96.378906 65.953125 96.347656 65.792969 96.28125 C 65.636719 96.214844 65.496094 96.121094 65.375 96 C 65.253906 95.878906 65.160156 95.738281 65.09375 95.582031 C 65.027344 95.421875 64.996094 95.257812 64.996094 95.085938 Z M 64.996094 95.085938 ",
fillOpacity: "1",
fillRule: "nonzero"
}
) }),
/* @__PURE__ */ jsx(
"path",
{
fill: "currentColor",
d: "M 22.320312 81.238281 L 22.320312 39.101562 L 11.976562 41.585938 L 11.976562 78.757812 Z M 22.320312 81.238281 ",
fillOpacity: "1",
fillRule: "nonzero"
}
),
/* @__PURE__ */ jsx(
"path",
{
fill: "currentColor",
d: "M 50.769531 88.066406 L 50.769531 32.277344 L 37.839844 35.378906 L 37.839844 84.960938 Z M 50.769531 88.066406 ",
fillOpacity: "1",
fillRule: "nonzero"
}
),
/* @__PURE__ */ jsx(
"path",
{
fill: "currentColor",
d: "M 24.90625 81.863281 L 35.253906 84.34375 L 35.253906 35.996094 L 24.90625 38.480469 Z M 24.90625 81.863281 ",
fillOpacity: "1",
fillRule: "nonzero"
}
)
]
}
);
};
var logo_default = Logo;
// src/components/global-error-page.tsx
import { useEffect } from "react";
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
function GlobalError({
error,
standalone = true,
...rest
}) {
useEffect(() => {
console.error("Global error:", error);
}, [error]);
const reset = () => {
window.location.reload();
};
const manifest = globalThis.__PYLON_MANIFEST__;
const content = /* @__PURE__ */ jsx2("div", { className: "fixed inset-0 bg-black/90 z-50 overflow-y-auto p-4 flex items-center justify-center", children: /* @__PURE__ */ jsxs2("div", { className: "w-full max-w-3xl bg-black border border-red-600 rounded-lg overflow-hidden text-white font-sans", children: [
/* @__PURE__ */ jsx2("div", { className: "flex items-center justify-between border-b border-neutral-800 p-4", children: /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-3", children: [
/* @__PURE__ */ jsx2("div", { className: "flex-shrink-0", children: /* @__PURE__ */ jsx2(logo_default, { className: "h-8 w-auto text-white" }) }),
/* @__PURE__ */ jsx2("div", { children: /* @__PURE__ */ jsx2("h1", { className: "text-xl font-medium text-red-500", children: "Application Crashed" }) })
] }) }),
/* @__PURE__ */ jsxs2("div", { className: "p-4", children: [
/* @__PURE__ */ jsx2("div", { className: "mb-4 text-neutral-400", children: "The application encountered a critical error and could not continue." }),
/* @__PURE__ */ jsx2("h2", { className: "text-2xl font-bold mb-4 text-white", children: error.message || "A critical error occurred" }),
error.digest && /* @__PURE__ */ jsxs2("div", { className: "mb-4", children: [
/* @__PURE__ */ jsx2("h3", { className: "text-sm uppercase tracking-wider text-neutral-500 font-medium mb-2", children: "Error ID" }),
/* @__PURE__ */ jsx2("div", { className: "bg-neutral-900 rounded-md p-3 text-neutral-300 font-mono", children: error.digest })
] })
] })
] }) });
if (standalone) {
return /* @__PURE__ */ jsxs2("html", { lang: "en", children: [
/* @__PURE__ */ jsxs2("head", { children: [
/* @__PURE__ */ jsx2("meta", { charSet: "utf-8" }),
/* @__PURE__ */ jsx2("meta", { name: "viewport", content: "width=device-width, initial-scale=1" }),
manifest?.["index.css"] && /* @__PURE__ */ jsx2(
"link",
{
rel: "stylesheet",
href: manifest["index.css"],
precedence: "high"
}
)
] }),
/* @__PURE__ */ jsx2("body", { children: content })
] });
}
return content;
}
// src/plugins/use-pages/setup/index.tsx
import { etag } from "hono/etag";
import { tmpdir } from "os";
import { pipeline } from "stream/promises";
import { __PYLON_INTERNALS_DO_NOT_USE } from "@getcronit/pylon/pages";
import { createHash } from "crypto";
import glob from "tiny-glob/sync.js";
// src/plugins/use-pages/setup/serve-file-path.ts
import { createReadStream } from "fs";
import { stat } from "fs/promises";
import mime from "mime";
import { Readable } from "stream";
var serveFilePath = async ({
filePath,
context
}) => {
let fileStat;
try {
fileStat = await stat(filePath);
} catch (error) {
return context.notFound();
}
const lastModified = fileStat.mtime.toUTCString();
const ifModifiedSince = context.req.header("If-Modified-Since");
if (ifModifiedSince === lastModified) {
return context.body(null, 304);
}
context.header("Last-Modified", lastModified);
const contentType = mime.getType(filePath) || "application/octet-stream";
context.header("Content-Type", contentType);
context.header("Accept-Ranges", "bytes");
const contentLength = fileStat.size;
if (context.req.method === "HEAD") {
context.header("Content-Length", contentLength.toString());
return context.body(null, 200);
}
let start = 0;
let end = contentLength - 1;
let isPartial = false;
const range = context.req.header("Range");
if (range && range.startsWith("bytes=")) {
const parts = range.replace("bytes=", "").split("-");
const rangeStart = parts[0] ? parseInt(parts[0], 10) : 0;
const rangeEnd = parts[1] ? parseInt(parts[1], 10) : contentLength - 1;
if (!isNaN(rangeStart) && !isNaN(rangeEnd) && rangeStart <= rangeEnd) {
start = rangeStart;
end = rangeEnd;
isPartial = true;
}
}
const retrievedLength = end - start + 1;
context.status(isPartial ? 206 : 200);
context.header("Content-Length", retrievedLength.toString());
if (isPartial) {
context.header("Content-Range", `bytes ${start}-${end}/${contentLength}`);
}
const stream = createReadStream(filePath, { start, end });
const webStream = Readable.toWeb(stream);
return context.body(webStream);
};
// src/plugins/use-pages/setup/index.tsx
import { jsx as jsx3 } from "react/jsx-runtime";
function isResponse(value) {
return value != null && typeof value.status === "number" && typeof value.clone === "function";
}
var setup = async (app2) => {
const pagesManifestPath = path.join(
process.cwd(),
".pylon/__pylon/pages/manifest.json"
);
const staticManifestPath = path.join(
process.cwd(),
".pylon/__pylon/static/manifest.json"
);
let pagesManifest = {};
let staticManifest = {};
try {
pagesManifest = JSON.parse(
await fs.promises.readFile(pagesManifestPath, "utf8")
);
} catch (err) {
throw new Error("Failed to read pages manifest.json:", err);
}
try {
staticManifest = JSON.parse(
await fs.promises.readFile(staticManifestPath, "utf8")
);
globalThis.__PYLON_MANIFEST__ = staticManifest;
if (pagesManifest["version"]) {
;
globalThis.__PYLON_VERSION__ = pagesManifest["version"];
}
} catch (err) {
throw new Error("Failed to read static manifest.json:", err);
}
const routes = (await import(`${process.cwd()}/${pagesManifest["app.js"]}`)).default;
const handler = createStaticHandler(routes);
app2.use(trimTrailingSlash());
const publicFilesPath = path.resolve(
process.cwd(),
".pylon",
"__pylon",
"public"
);
let publicFiles = [];
try {
publicFiles = glob(`**/*`, {
filesOnly: true,
cwd: publicFilesPath
});
} catch (error) {
}
const sitemapCache = /* @__PURE__ */ new Map();
if (pagesManifest["sitemap.js"]) {
try {
const sitemapModule = await import(`${process.cwd()}/${pagesManifest["sitemap.js"]}`);
app2.get("/sitemap.xml", async (c) => {
const cacheKey = "sitemap.xml";
const cached = sitemapCache.get(cacheKey);
const now = Date.now();
const baseUrl = new URL(c.req.url);
const revalidate = sitemapModule.revalidate;
if (revalidate === false || revalidate === 0) {
c.header(
"Cache-Control",
"no-store, no-cache, must-revalidate, proxy-revalidate"
);
} else if (typeof revalidate === "number") {
c.header(
"Cache-Control",
`public, max-age=${revalidate}, s-maxage=${revalidate}, stale-while-revalidate`
);
}
if (cached && cached.expiresAt > now) {
c.header("Content-Type", "application/xml");
return c.body(cached.xml);
}
let xml = "";
if (sitemapModule.generateSitemaps) {
const sitemaps = await sitemapModule.generateSitemaps();
const indexItems = sitemaps.map((s) => ({
url: `${baseUrl.origin}/sitemap/${s.id}.xml`
}));
xml = renderSitemapIndexXml(indexItems);
} else {
const sitemapFn = sitemapModule.sitemap || sitemapModule.default;
if (sitemapFn) {
const items = await sitemapFn();
xml = renderSitemapXml(items, baseUrl.origin);
} else {
return c.text("Sitemap not found", 404);
}
}
if (typeof revalidate === "number" && revalidate > 0) {
sitemapCache.set(cacheKey, {
xml,
expiresAt: now + revalidate * 1e3
});
}
c.header("Content-Type", "application/xml");
return c.body(xml);
});
app2.get("/sitemap/:id", async (c) => {
const idParam = c.req.param("id");
if (!idParam.endsWith(".xml")) {
return c.text("Sitemap not found", 404);
}
const id = idParam.replace(".xml", "");
const cacheKey = `sitemap-${id}.xml`;
const cached = sitemapCache.get(cacheKey);
const now = Date.now();
const baseUrl = new URL(c.req.url);
const revalidate = sitemapModule.revalidate;
if (revalidate === false || revalidate === 0) {
c.header(
"Cache-Control",
"no-store, no-cache, must-revalidate, proxy-revalidate"
);
} else if (typeof revalidate === "number") {
c.header(
"Cache-Control",
`public, max-age=${revalidate}, s-maxage=${revalidate}, stale-while-revalidate`
);
}
if (cached && cached.expiresAt > now) {
c.header("Content-Type", "application/xml");
return c.body(cached.xml);
}
let xml = "";
const sitemapFn = sitemapModule.sitemap || sitemapModule.default;
if (sitemapFn) {
const items = await sitemapFn({ id });
xml = renderSitemapXml(items, baseUrl.origin);
} else {
return c.text("Sitemap not found", 404);
}
if (typeof revalidate === "number" && revalidate > 0) {
sitemapCache.set(cacheKey, {
xml,
expiresAt: now + revalidate * 1e3
});
}
c.header("Content-Type", "application/xml");
return c.body(xml);
});
} catch (e) {
console.error("Failed to load sitemap module:", e);
}
}
app2.on(
"GET",
publicFiles.map((file) => `/${file}`),
etag(),
async (c) => {
const publicFilePath = path.resolve(
process.cwd(),
".pylon",
"__pylon",
"public",
c.req.path.replace("/", "")
);
return serveFilePath({ filePath: publicFilePath, context: c });
}
);
app2.get("/__pylon/static/*", etag(), async (c) => {
const filePath = path.resolve(
process.cwd(),
".pylon",
"__pylon",
"static",
c.req.path.replace("/__pylon/static/", "")
);
return serveFilePath({ filePath, context: c });
});
app2.get("/__pylon/image", async (c) => {
try {
let isSupportedFormat2 = function(format2) {
const supportedFormats = sharp.format;
return Object.keys(supportedFormats).includes(format2);
};
var isSupportedFormat = isSupportedFormat2;
const {
src,
w,
h,
q = "75",
format = "webp",
lqip = "false"
} = c.req.query();
if (!src) {
return c.json({ error: "Missing parameters." }, 400);
}
const isSrcAbsolute = src.startsWith("http://") || src.startsWith("https://");
let imagePath;
if (isSrcAbsolute) {
imagePath = await downloadImage(src);
} else {
if (!src.startsWith("/")) {
return c.json({ error: "Invalid image path." }, 400);
}
if (!src.startsWith("/__pylon/static/media")) {
imagePath = path.join(
process.cwd(),
".pylon",
"__pylon",
"public",
src
);
} else {
imagePath = path.join(process.cwd(), ".pylon", src);
}
}
const cachedImageFileName = getCachedImagePath({
src,
width: w ? parseInt(w) : 0,
height: h ? parseInt(h) : 0,
quality: q,
lqip: lqip === "true",
format
});
try {
await fs.promises.access(imagePath);
} catch {
try {
imagePath = await downloadImage(src);
} catch (error) {
return c.json({ error: "Image not found" }, 404);
}
}
if (IS_IMAGE_CACHE_POSSIBLE) {
try {
await fs.promises.access(cachedImageFileName);
const stream = fs.createReadStream(cachedImageFileName);
c.res.headers.set("Content-Type", getContentType(format));
return c.body(Readable2.toWeb(stream));
} catch (e) {
}
}
const sharp = (await import("sharp")).default;
const metadata = await sharp(imagePath).metadata();
if (!metadata.width || !metadata.height) {
return c.json(
{
error: "Invalid image metadata. Width and height are required for resizing."
},
400
);
}
const { width: finalWidth, height: finalHeight } = calculateDimensions(
metadata.width,
metadata.height,
w ? parseInt(w) : void 0,
h ? parseInt(h) : void 0
);
let imageFormat = format.toLowerCase();
if (!isSupportedFormat2(imageFormat)) {
throw new Error("Unsupported image format");
}
const quality = parseInt(q);
let data = sharp(imagePath);
if (lqip === "true") {
data = data.resize({
width: Math.min(finalWidth ?? 16, 16),
height: Math.min(finalHeight ?? 16, 16),
fit: "inside"
}).toFormat("webp", {
quality: 30,
alphaQuality: 20,
smartSubsample: true
});
} else {
data = data.resize(finalWidth, finalHeight).toFormat(imageFormat, {
quality
});
}
if (IS_IMAGE_CACHE_POSSIBLE) {
const image = await data.toFile(cachedImageFileName);
c.res.headers.set("Content-Type", getContentType(image.format));
return c.body(
Readable2.toWeb(
fs.createReadStream(cachedImageFileName)
)
);
} else {
const image = await data.toBuffer({ resolveWithObject: true });
c.res.headers.set("Content-Type", getContentType(image.info.format));
return c.body(image.data);
}
} catch (error) {
console.error("Error processing the image:", error);
return c.json({ error: "Error processing the image" }, 500);
}
});
const _client = await import(`${process.cwd()}/.pylon/client/index.js?t=${Date.now()}`);
app2.get("*", async (c) => {
const pagesContext = c.get("pagesContext") || {};
const pagesClient = _client.createPylonPagesClient();
const staticHandlerContext = await handler.query(c.req.raw, {
requestContext: { pagesContext }
});
if (isResponse(staticHandlerContext)) {
const status = staticHandlerContext.status;
if (status >= 300 && status < 400) {
const location = staticHandlerContext.headers.get("Location");
if (location) return c.redirect(location, status);
}
c.status(status);
return c.body(await staticHandlerContext.text());
}
const context = staticHandlerContext;
const router = createStaticRouter(handler.dataRoutes, context);
const prerenderComponent = /* @__PURE__ */ jsx3(
__PYLON_INTERNALS_DO_NOT_USE.DataClientProvider,
{
client: pagesClient,
staticData: {
context: pagesContext
},
children: /* @__PURE__ */ jsx3(StaticRouterProvider, { router, context })
}
);
let cacheSnapshot = void 0;
try {
const result = await pagesClient.prepareReactRender(prerenderComponent);
cacheSnapshot = result.cacheSnapshot;
} catch (errorOrResponse) {
if (isResponse(errorOrResponse)) {
const status = errorOrResponse.status;
if (status >= 300 && status < 400) {
const location = errorOrResponse.headers.get("Location");
if (location) return c.redirect(location, status);
}
const leafMatch = context.matches[context.matches.length - 1];
if (leafMatch) {
let errorData = errorOrResponse.statusText;
try {
errorData = await errorOrResponse.text();
} catch {
}
context.errors = context.errors || {};
context.errors[leafMatch.route.id] = {
status,
statusText: errorOrResponse.statusText,
data: errorData,
internal: true
};
context.statusCode = status;
}
} else {
const leafMatch = context.matches[context.matches.length - 1];
if (leafMatch) {
context.errors = context.errors || {};
context.errors[leafMatch.route.id] = errorOrResponse;
context.statusCode = 500;
} else {
throw errorOrResponse;
}
}
}
const finalComponent = /* @__PURE__ */ jsx3(
__PYLON_INTERNALS_DO_NOT_USE.DataClientProvider,
{
client: pagesClient,
staticData: {
cache: cacheSnapshot,
context: pagesContext
},
children: /* @__PURE__ */ jsx3(StaticRouterProvider, { router, context })
}
);
try {
if (reactServer.renderToReadableStream) {
const stream = await reactServer.renderToReadableStream(
finalComponent,
{
bootstrapModules: staticManifest["app.js"] ? [staticManifest["app.js"]] : void 0
}
);
c.status(context.statusCode);
c.header("Content-Type", "text/html");
return c.body(stream);
} else if (reactServer.renderToPipeableStream) {
return await new Promise((resolve, reject) => {
const { pipe } = reactServer.renderToPipeableStream(finalComponent, {
bootstrapModules: staticManifest["app.js"] ? [staticManifest["app.js"]] : void 0,
onShellReady: async () => {
c.status(context.statusCode);
c.header("Content-Type", "text/html");
const passThrough = new PassThrough();
pipe(passThrough);
resolve(c.body(Readable2.toWeb(passThrough)));
},
onShellError: async (error) => {
reject(error);
}
});
});
} else {
throw new Error("Environment not supported");
}
} catch (criticalError) {
console.error("CRITICAL STREAM ERROR", criticalError);
c.status(500);
c.header("Content-Type", "text/html");
return c.html(
reactServer.renderToString(/* @__PURE__ */ jsx3(GlobalError, { error: criticalError }))
);
}
});
};
var IMAGE_CACHE_DIR = path.join(process.cwd(), ".cache/__pylon/images");
var IS_IMAGE_CACHE_POSSIBLE = true;
try {
await fs.promises.mkdir(IMAGE_CACHE_DIR, { recursive: true });
} catch (error) {
IS_IMAGE_CACHE_POSSIBLE = false;
}
var getCachedImagePath = (args) => {
const fileName = `${path.basename(
createHash("md5").update(JSON.stringify(args)).digest("hex"),
path.extname(args.src)
)}-${args.width}x${args.height}.${args.format}`;
return path.join(IMAGE_CACHE_DIR, fileName);
};
var calculateDimensions = (originalWidth, originalHeight, width, height) => {
if (!width && !height) {
return { width: originalWidth, height: originalHeight };
}
if (width && !height) {
height = Math.round(width * originalHeight / originalWidth);
} else if (height && !width) {
width = Math.round(height * originalWidth / originalHeight);
}
return { width, height };
};
var getContentType = (format) => {
switch (format.toLowerCase()) {
case "webp":
return "image/webp";
case "jpeg":
case "jpg":
return "image/jpeg";
case "png":
return "image/png";
case "gif":
return "image/gif";
case "svg":
return "image/svg+xml";
default:
return "application/octet-stream";
}
};
var downloadImage = async (url) => {
const isSrcAbsoluteUrl = url.startsWith("http://") || url.startsWith("https://");
const _fetch = isSrcAbsoluteUrl ? fetch : app.request;
const response = await _fetch(url);
if (!response.ok)
throw new Error(`Failed to download image: ${response.statusText}`);
const ext = path.extname(url) || ".jpg";
const tempFilePath = path.join(tmpdir(), `image-${Date.now()}${ext}`);
const fileStream = fs.createWriteStream(tempFilePath);
await pipeline(response.body, fileStream);
return tempFilePath;
};
function escapeXml(unsafe) {
return unsafe.replace(/[<>&'"]/g, (c) => {
switch (c) {
case "<":
return "<";
case ">":
return ">";
case "&":
return "&";
case "'":
return "'";
case '"':
return """;
}
return c;
});
}
function renderSitemapXml(items, baseUrl) {
let xml = `<?xml version="1.0" encoding="UTF-8"?>
`;
xml += `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
`;
for (const item of items) {
const isAbsolute = item.url.startsWith("http://") || item.url.startsWith("https://");
const loc = isAbsolute ? item.url : `${baseUrl}/${item.url.replace(/^\//, "")}`;
xml += ` <url>
`;
xml += ` <loc>${escapeXml(loc)}</loc>
`;
if (item.lastmod) {
const date = item.lastmod instanceof Date ? item.lastmod.toISOString().split("T")[0] : item.lastmod;
xml += ` <lastmod>${escapeXml(String(date))}</lastmod>
`;
}
if (item.changefreq) {
xml += ` <changefreq>${escapeXml(item.changefreq)}</changefreq>
`;
}
if (item.priority !== void 0) {
xml += ` <priority>${item.priority}</priority>
`;
}
xml += ` </url>
`;
}
xml += `</urlset>`;
return xml;
}
function renderSitemapIndexXml(items) {
let xml = `<?xml version="1.0" encoding="UTF-8"?>
`;
xml += `<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
`;
for (const item of items) {
xml += ` <sitemap>
`;
xml += ` <loc>${escapeXml(item.url)}</loc>
`;
if (item.lastmod) {
const date = item.lastmod instanceof Date ? item.lastmod.toISOString().split("T")[0] : item.lastmod;
xml += ` <lastmod>${escapeXml(String(date))}</lastmod>
`;
}
xml += ` </sitemap>
`;
}
xml += `</sitemapindex>`;
return xml;
}
export {
setup
};
//# sourceMappingURL=setup-ZUBSGCMW.js.map