resuxjs 0.2.35 → 0.2.37

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/cli.js CHANGED
@@ -17,6 +17,34 @@ let devBuildRevision = 0;
17
17
  let devReloadRevision = 0;
18
18
  let devLastBuildSourceMtime = 0;
19
19
  const devReloadClients = new Set();
20
+ const RESUX_PLACEHOLDER_SVG = `<svg width="96" height="96" viewBox="0 0 96 96" fill="none" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="title desc">
21
+ <title id="title">Resux mark</title>
22
+ <desc id="desc">A compact Resux monogram shaped like a resumable route.</desc>
23
+ <defs>
24
+ <linearGradient id="panel" x1="12" y1="8" x2="88" y2="92" gradientUnits="userSpaceOnUse">
25
+ <stop stop-color="#111827"/>
26
+ <stop offset="1" stop-color="#020617"/>
27
+ </linearGradient>
28
+ <linearGradient id="route" x1="25" y1="22" x2="73" y2="75" gradientUnits="userSpaceOnUse">
29
+ <stop stop-color="#22D3EE"/>
30
+ <stop offset="0.58" stop-color="#7C3AED"/>
31
+ <stop offset="1" stop-color="#10B981"/>
32
+ </linearGradient>
33
+ <filter id="soft" x="8" y="8" width="80" height="80" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
34
+ <feGaussianBlur stdDeviation="4"/>
35
+ </filter>
36
+ </defs>
37
+ <rect x="4" y="4" width="88" height="88" rx="22" fill="url(#panel)"/>
38
+ <path d="M24 29C31 20 43 16 55 18C68 20 77 29 77 41C77 54 67 62 53 62H36V77" stroke="#38BDF8" stroke-opacity="0.18" stroke-width="18" stroke-linecap="round" stroke-linejoin="round" filter="url(#soft)"/>
39
+ <path d="M27 76V25H54C67 25 75 32 75 42C75 52 67 59 54 59H37" stroke="url(#route)" stroke-width="9" stroke-linecap="round" stroke-linejoin="round"/>
40
+ <path d="M50 59L72 76" stroke="url(#route)" stroke-width="9" stroke-linecap="round" stroke-linejoin="round"/>
41
+ <path d="M31 35H54C60 35 64 38 64 42C64 47 60 50 54 50H31" stroke="#F8FAFC" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>
42
+ <circle cx="27" cy="25" r="4" fill="#22D3EE"/>
43
+ <circle cx="72" cy="76" r="4" fill="#10B981"/>
44
+ <path d="M22 14H34" stroke="#F8FAFC" stroke-opacity="0.22" stroke-width="3" stroke-linecap="round"/>
45
+ <path d="M62 82H74" stroke="#F8FAFC" stroke-opacity="0.22" stroke-width="3" stroke-linecap="round"/>
46
+ </svg>
47
+ `;
20
48
  async function runCompilerBuild(appRoot, outDir, options) {
21
49
  const { buildProject } = await import("./compiler/index.js");
22
50
  return buildProject(appRoot, outDir, options);
@@ -968,9 +996,17 @@ Options:
968
996
  }
969
997
  async function handleRequest(request, response, options) {
970
998
  const requestOrigin = requestOriginFromHeaders(request);
971
- const requestUrl = new URL(request.url ?? "/", requestOrigin);
999
+ const requestUrl = safeParseRequestUrl(request.url, requestOrigin);
972
1000
  try {
973
1001
  applyDefaultSecurityHeaders(response, options.securityHeaders);
1002
+ if (!requestUrl) {
1003
+ response.writeHead(404, {
1004
+ "content-type": "text/plain; charset=utf-8",
1005
+ "cache-control": "no-store",
1006
+ });
1007
+ response.end("Not found");
1008
+ return;
1009
+ }
974
1010
  if (options.dev &&
975
1011
  options.vite &&
976
1012
  isViteInternalRequest(requestUrl.pathname)) {
@@ -981,6 +1017,10 @@ async function handleRequest(request, response, options) {
981
1017
  serveDevEvents(request, response);
982
1018
  return;
983
1019
  }
1020
+ if (requestUrl.pathname === "/__resux/resux-placeholder.svg") {
1021
+ serveResuxPlaceholderAsset(response);
1022
+ return;
1023
+ }
984
1024
  if (requestUrl.pathname === "/__resux/health") {
985
1025
  await serveHealthCheck(response, options);
986
1026
  return;
@@ -993,6 +1033,10 @@ async function handleRequest(request, response, options) {
993
1033
  await serveResuxImage(request, response, requestUrl, requestOrigin);
994
1034
  return;
995
1035
  }
1036
+ if (requestUrl.pathname.startsWith("/_resux/generated/images/")) {
1037
+ await serveGeneratedResuxImage(request, response, requestUrl, requestOrigin, options.appRoot);
1038
+ return;
1039
+ }
996
1040
  if (requestUrl.pathname.startsWith("/__resux/")) {
997
1041
  if (activeDevBuild) {
998
1042
  await activeDevBuild;
@@ -1050,9 +1094,10 @@ async function handleRequest(request, response, options) {
1050
1094
  response.end(rendered.message);
1051
1095
  return;
1052
1096
  }
1053
- const html = renderDocument(rendered, "Resux App", {
1097
+ const normalizedRendered = withPrioritizedHeadImagePreloads(rendered);
1098
+ const html = promoteDocumentImagePreloads(renderDocument(normalizedRendered, "Resux App", {
1054
1099
  devReload: options.dev,
1055
- });
1100
+ }));
1056
1101
  response.writeHead(routeRule?.statusCode ?? 200, {
1057
1102
  "content-type": "text/html; charset=utf-8",
1058
1103
  });
@@ -1065,6 +1110,28 @@ async function handleRequest(request, response, options) {
1065
1110
  await serveErrorDocument(response, options, undefined, 500, error);
1066
1111
  }
1067
1112
  }
1113
+ function safeParseRequestUrl(rawUrl, requestOrigin) {
1114
+ const candidate = typeof rawUrl === "string" ? rawUrl.trim() : "/";
1115
+ if (!candidate) {
1116
+ return null;
1117
+ }
1118
+ if (candidate.startsWith("//")) {
1119
+ return null;
1120
+ }
1121
+ try {
1122
+ return new URL(candidate, requestOrigin);
1123
+ }
1124
+ catch {
1125
+ return null;
1126
+ }
1127
+ }
1128
+ function serveResuxPlaceholderAsset(response) {
1129
+ response.writeHead(200, {
1130
+ "content-type": "image/svg+xml; charset=utf-8",
1131
+ "cache-control": "public, max-age=31536000, immutable",
1132
+ });
1133
+ response.end(RESUX_PLACEHOLDER_SVG);
1134
+ }
1068
1135
  async function serveErrorDocument(response, options, loadedManifest, statusCode, error) {
1069
1136
  const statusMessage = statusCode === 404 ? "Not Found" : "Internal Server Error";
1070
1137
  const errorPayload = createErrorPayload(error, statusCode, statusMessage, options.dev);
@@ -1093,7 +1160,8 @@ async function serveErrorDocument(response, options, loadedManifest, statusCode,
1093
1160
  response.writeHead(statusCode, {
1094
1161
  "content-type": "text/html; charset=utf-8",
1095
1162
  });
1096
- response.end(renderDocument(rendered, statusMessage, { devReload: options.dev }));
1163
+ const normalizedRendered = withPrioritizedHeadImagePreloads(rendered);
1164
+ response.end(promoteDocumentImagePreloads(renderDocument(normalizedRendered, statusMessage, { devReload: options.dev })));
1097
1165
  return;
1098
1166
  }
1099
1167
  }
@@ -1168,7 +1236,7 @@ function createPlainErrorBody(error, dev) {
1168
1236
  }
1169
1237
  async function serveRoutePayload(response, requestUrl, options, requestOrigin) {
1170
1238
  const targetPath = requestUrl.searchParams.get("path");
1171
- if (!targetPath || !targetPath.startsWith("/")) {
1239
+ if (!targetPath || !targetPath.startsWith("/") || targetPath.startsWith("//")) {
1172
1240
  response.writeHead(400, {
1173
1241
  "content-type": "application/json; charset=utf-8",
1174
1242
  });
@@ -1219,11 +1287,12 @@ async function serveRoutePayload(response, requestUrl, options, requestOrigin) {
1219
1287
  response.end(JSON.stringify({ error: rendered.message }));
1220
1288
  return;
1221
1289
  }
1290
+ const normalizedRendered = withPrioritizedHeadImagePreloads(rendered);
1222
1291
  response.writeHead(200, {
1223
1292
  "content-type": "application/json; charset=utf-8",
1224
1293
  "cache-control": "no-store",
1225
1294
  });
1226
- response.end(JSON.stringify(rendered));
1295
+ response.end(JSON.stringify(normalizedRendered));
1227
1296
  }
1228
1297
  const RESUX_IMAGE_SUPPORTED_FORMATS = new Set([
1229
1298
  "avif",
@@ -1306,11 +1375,23 @@ function shouldTransformImage(options) {
1306
1375
  || options.quality
1307
1376
  || options.format);
1308
1377
  }
1378
+ function shouldConvertImageFormat(inputFormat, outputFormat) {
1379
+ if (!outputFormat) {
1380
+ return false;
1381
+ }
1382
+ if (!inputFormat) {
1383
+ return true;
1384
+ }
1385
+ return inputFormat !== outputFormat;
1386
+ }
1309
1387
  function resolveResuxImageSource(rawSource, requestOrigin) {
1310
1388
  const source = rawSource.trim();
1311
1389
  if (!source) {
1312
1390
  return null;
1313
1391
  }
1392
+ if (source.startsWith("//")) {
1393
+ return null;
1394
+ }
1314
1395
  if (source.startsWith("/")) {
1315
1396
  return new URL(source, requestOrigin);
1316
1397
  }
@@ -1331,8 +1412,7 @@ async function loadSharpFactory() {
1331
1412
  }
1332
1413
  sharpFactoryPromise = (async () => {
1333
1414
  try {
1334
- const sharpPath = require.resolve("sharp");
1335
- const sharpModule = await import(pathToFileURL(sharpPath).href);
1415
+ const sharpModule = await import("sharp");
1336
1416
  const factory = sharpModule.default
1337
1417
  ?? sharpModule;
1338
1418
  sharpFactoryLoadError = null;
@@ -1343,7 +1423,7 @@ async function loadSharpFactory() {
1343
1423
  catch (error) {
1344
1424
  const message = error instanceof Error ? error.message : String(error);
1345
1425
  sharpFactoryLoadError =
1346
- `Image transforms require "sharp". Install it in your app dependency tree. (${message})`;
1426
+ `Resux image transforms require "sharp" in the server runtime. (${message})`;
1347
1427
  return null;
1348
1428
  }
1349
1429
  })();
@@ -1358,8 +1438,9 @@ async function transformResuxImage(source, contentType, options) {
1358
1438
  return null;
1359
1439
  }
1360
1440
  const inputFormat = parseFormatFromContentType(contentType);
1361
- const outputFormat = options.format
1362
- ?? (options.quality && inputFormat ? inputFormat : undefined);
1441
+ const outputFormat = options.format;
1442
+ const shouldConvertFormat = shouldConvertImageFormat(inputFormat, outputFormat);
1443
+ const shouldResize = Boolean(options.width || options.height);
1363
1444
  try {
1364
1445
  let pipeline = sharp(source, { failOn: "none" });
1365
1446
  if (options.width || options.height) {
@@ -1370,17 +1451,21 @@ async function transformResuxImage(source, contentType, options) {
1370
1451
  withoutEnlargement: true,
1371
1452
  });
1372
1453
  }
1373
- if (outputFormat) {
1374
- const quality = options.quality;
1375
- const formatOptions = Number.isFinite(quality)
1376
- ? { quality: Math.min(100, Math.max(1, quality)) }
1377
- : undefined;
1454
+ if (shouldConvertFormat) {
1455
+ const quality = normalizeImageQuality(options.quality);
1456
+ const formatOptions = quality ? { quality } : undefined;
1378
1457
  pipeline = pipeline.toFormat(outputFormat, formatOptions);
1379
1458
  }
1459
+ else if (Number.isFinite(options.quality)) {
1460
+ const quality = normalizeImageQuality(options.quality);
1461
+ if (quality && inputFormat && inputFormat !== "gif") {
1462
+ pipeline = pipeline.toFormat(inputFormat, { quality });
1463
+ }
1464
+ }
1380
1465
  const transformed = await pipeline.toBuffer();
1381
1466
  return {
1382
1467
  buffer: transformed,
1383
- contentType: outputFormat
1468
+ contentType: shouldConvertFormat && outputFormat
1384
1469
  ? mimeTypeFromImageFormat(outputFormat)
1385
1470
  : contentType ?? "application/octet-stream",
1386
1471
  };
@@ -1389,6 +1474,230 @@ async function transformResuxImage(source, contentType, options) {
1389
1474
  return null;
1390
1475
  }
1391
1476
  }
1477
+ function normalizeImageQuality(quality) {
1478
+ if (!Number.isFinite(quality)) {
1479
+ return undefined;
1480
+ }
1481
+ return Math.min(100, Math.max(1, Math.round(quality)));
1482
+ }
1483
+ const RESUX_IMAGE_RESERVED_QUERY_KEYS = new Set([
1484
+ "src",
1485
+ "url",
1486
+ "original",
1487
+ "w",
1488
+ "width",
1489
+ "h",
1490
+ "height",
1491
+ "q",
1492
+ "quality",
1493
+ "f",
1494
+ "format",
1495
+ "fit",
1496
+ "mode",
1497
+ "cache",
1498
+ "c",
1499
+ ]);
1500
+ function parseImageExtraModifiers(searchParams) {
1501
+ const modifiers = {};
1502
+ for (const [key, value] of searchParams.entries()) {
1503
+ if (RESUX_IMAGE_RESERVED_QUERY_KEYS.has(key)) {
1504
+ continue;
1505
+ }
1506
+ if (!value) {
1507
+ continue;
1508
+ }
1509
+ modifiers[key] = value;
1510
+ }
1511
+ return modifiers;
1512
+ }
1513
+ function parseImageCacheMaxAgeSeconds(value) {
1514
+ if (!value) {
1515
+ return undefined;
1516
+ }
1517
+ const normalized = value.trim().toLowerCase();
1518
+ if (!normalized || normalized === "false" || normalized === "0" || normalized === "off" || normalized === "no") {
1519
+ return undefined;
1520
+ }
1521
+ if (normalized === "true" || normalized === "1" || normalized === "yes" || normalized === "on") {
1522
+ return 86400;
1523
+ }
1524
+ const directNumber = Number(normalized);
1525
+ if (Number.isFinite(directNumber) && directNumber > 0) {
1526
+ return Math.max(1, Math.round(directNumber));
1527
+ }
1528
+ const durationMatch = /^(\d+)\s*(s|m|h|d|w)$/.exec(normalized);
1529
+ if (!durationMatch) {
1530
+ return undefined;
1531
+ }
1532
+ const amount = Number(durationMatch[1]);
1533
+ if (!Number.isFinite(amount) || amount <= 0) {
1534
+ return undefined;
1535
+ }
1536
+ const unit = durationMatch[2];
1537
+ const multiplier = unit === "s" ? 1
1538
+ : unit === "m" ? 60
1539
+ : unit === "h" ? 3600
1540
+ : unit === "d" ? 86400
1541
+ : 604800;
1542
+ return Math.max(1, Math.round(amount * multiplier));
1543
+ }
1544
+ function inferImageExtensionFromSource(value) {
1545
+ if (!value) {
1546
+ return undefined;
1547
+ }
1548
+ const trimmed = value.trim();
1549
+ if (!trimmed) {
1550
+ return undefined;
1551
+ }
1552
+ if (trimmed.startsWith("data:")) {
1553
+ const mimeMatch = /^data:image\/([a-zA-Z0-9.+-]+);/i.exec(trimmed);
1554
+ if (!mimeMatch) {
1555
+ return undefined;
1556
+ }
1557
+ const normalized = mimeMatch[1].toLowerCase();
1558
+ return normalized === "jpg" ? "jpeg" : normalized;
1559
+ }
1560
+ const withoutQuery = trimmed.split(/[?#]/)[0];
1561
+ const dotIndex = withoutQuery.lastIndexOf(".");
1562
+ if (dotIndex < 0) {
1563
+ return undefined;
1564
+ }
1565
+ const extension = withoutQuery.slice(dotIndex + 1).toLowerCase();
1566
+ if (!extension) {
1567
+ return undefined;
1568
+ }
1569
+ return extension === "jpg" ? "jpeg" : extension;
1570
+ }
1571
+ function createImageTransformSignature(source, originalSource, format, options) {
1572
+ const entries = [`src=${source}`];
1573
+ if (originalSource) {
1574
+ entries.push(`original=${originalSource}`);
1575
+ }
1576
+ if (Number.isFinite(options.width) && options.width > 0) {
1577
+ entries.push(`w=${Math.round(options.width)}`);
1578
+ }
1579
+ if (Number.isFinite(options.height) && options.height > 0) {
1580
+ entries.push(`h=${Math.round(options.height)}`);
1581
+ }
1582
+ if (typeof options.fit === "string" && options.fit.length > 0) {
1583
+ entries.push(`fit=${options.fit}`);
1584
+ }
1585
+ if (format) {
1586
+ entries.push(`f=${format}`);
1587
+ }
1588
+ if (Number.isFinite(options.quality) && options.quality > 0) {
1589
+ entries.push(`q=${Math.round(options.quality)}`);
1590
+ }
1591
+ const extras = options.extraModifiers ?? {};
1592
+ for (const key of Object.keys(extras).sort()) {
1593
+ const value = extras[key];
1594
+ if (!value) {
1595
+ continue;
1596
+ }
1597
+ entries.push(`${key}=${value}`);
1598
+ }
1599
+ return entries.join("&");
1600
+ }
1601
+ function hashImageSignature(value) {
1602
+ let hash = 2166136261;
1603
+ for (let index = 0; index < value.length; index++) {
1604
+ hash ^= value.charCodeAt(index);
1605
+ hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);
1606
+ }
1607
+ return (hash >>> 0).toString(16).padStart(8, "0");
1608
+ }
1609
+ function createGeneratedImageRoutePath(source, originalSource, format, options) {
1610
+ const extension = format
1611
+ ?? inferImageExtensionFromSource(source)
1612
+ ?? inferImageExtensionFromSource(originalSource)
1613
+ ?? "bin";
1614
+ const signature = createImageTransformSignature(source, originalSource, format, options);
1615
+ const digest = hashImageSignature(signature);
1616
+ return `/_resux/generated/images/${digest}.${extension}`;
1617
+ }
1618
+ function resolveGeneratedImageDiskPath(appRoot, pathname) {
1619
+ const publicRoot = path.resolve(appRoot, "public");
1620
+ const generatedRoot = path.resolve(publicRoot, "_resux", "generated", "images");
1621
+ let decodedPath;
1622
+ try {
1623
+ decodedPath = decodeURIComponent(pathname);
1624
+ }
1625
+ catch {
1626
+ return null;
1627
+ }
1628
+ const resolved = path.resolve(publicRoot, `.${decodedPath}`);
1629
+ if (!resolved.startsWith(generatedRoot)) {
1630
+ return null;
1631
+ }
1632
+ return {
1633
+ filePath: resolved,
1634
+ relativePath: decodedPath,
1635
+ };
1636
+ }
1637
+ async function readGeneratedImageMetadata(metadataPath) {
1638
+ if (!(await exists(metadataPath))) {
1639
+ return null;
1640
+ }
1641
+ try {
1642
+ const payload = JSON.parse(await readFile(metadataPath, "utf8"));
1643
+ if (!payload || payload.version !== 1) {
1644
+ return null;
1645
+ }
1646
+ return payload;
1647
+ }
1648
+ catch {
1649
+ return null;
1650
+ }
1651
+ }
1652
+ function generatedImageMetadataValid(metadata, key, now, sourceInfo) {
1653
+ if (!metadata || metadata.version !== 1) {
1654
+ return false;
1655
+ }
1656
+ if (metadata.key !== key) {
1657
+ return false;
1658
+ }
1659
+ if (!Number.isFinite(metadata.expiresAt) || metadata.expiresAt <= now) {
1660
+ return false;
1661
+ }
1662
+ if (sourceInfo) {
1663
+ if (metadata.sourceMtimeMs !== sourceInfo.mtimeMs) {
1664
+ return false;
1665
+ }
1666
+ if (metadata.sourceSize !== sourceInfo.size) {
1667
+ return false;
1668
+ }
1669
+ }
1670
+ return true;
1671
+ }
1672
+ async function resolveLocalSourceFileInfo(sourceUrl, requestOrigin, appRoot) {
1673
+ const sameOrigin = sourceUrl.origin === requestOrigin;
1674
+ if (!sameOrigin || !sourceUrl.pathname.startsWith("/")) {
1675
+ return null;
1676
+ }
1677
+ const publicRoot = path.resolve(appRoot, "public");
1678
+ let decodedPath;
1679
+ try {
1680
+ decodedPath = decodeURIComponent(sourceUrl.pathname);
1681
+ }
1682
+ catch {
1683
+ return null;
1684
+ }
1685
+ const resolved = path.resolve(publicRoot, `.${decodedPath}`);
1686
+ if (!resolved.startsWith(publicRoot)) {
1687
+ return null;
1688
+ }
1689
+ if (!(await exists(resolved))) {
1690
+ return null;
1691
+ }
1692
+ const sourceStats = await stat(resolved);
1693
+ if (!sourceStats.isFile()) {
1694
+ return null;
1695
+ }
1696
+ return {
1697
+ mtimeMs: sourceStats.mtimeMs,
1698
+ size: sourceStats.size,
1699
+ };
1700
+ }
1392
1701
  async function serveResuxImage(request, response, requestUrl, requestOrigin) {
1393
1702
  const method = request.method ?? "GET";
1394
1703
  if (method !== "GET" && method !== "HEAD") {
@@ -1425,6 +1734,7 @@ async function serveResuxImage(request, response, requestUrl, requestOrigin) {
1425
1734
  ?? normalizeImageFormat(requestUrl.searchParams.get("format")),
1426
1735
  fit: normalizeImageFit(requestUrl.searchParams.get("fit"))
1427
1736
  ?? normalizeImageFit(requestUrl.searchParams.get("mode")),
1737
+ extraModifiers: parseImageExtraModifiers(requestUrl.searchParams),
1428
1738
  };
1429
1739
  const forwardedAccept = firstHeaderValue(request.headers.accept);
1430
1740
  const upstream = await fetch(sourceUrl, {
@@ -1480,6 +1790,192 @@ async function serveResuxImage(request, response, requestUrl, requestOrigin) {
1480
1790
  }
1481
1791
  response.end(body);
1482
1792
  }
1793
+ async function serveGeneratedResuxImage(request, response, requestUrl, requestOrigin, appRoot) {
1794
+ const method = request.method ?? "GET";
1795
+ if (method !== "GET" && method !== "HEAD") {
1796
+ response.writeHead(405, {
1797
+ "content-type": "text/plain; charset=utf-8",
1798
+ allow: "GET, HEAD",
1799
+ });
1800
+ response.end("Method Not Allowed");
1801
+ return;
1802
+ }
1803
+ const resolvedDiskPath = resolveGeneratedImageDiskPath(appRoot, requestUrl.pathname);
1804
+ if (!resolvedDiskPath) {
1805
+ response.writeHead(404, {
1806
+ "content-type": "text/plain; charset=utf-8",
1807
+ "cache-control": "no-store",
1808
+ });
1809
+ response.end("Not found");
1810
+ return;
1811
+ }
1812
+ const { filePath, relativePath } = resolvedDiskPath;
1813
+ const metadataPath = `${filePath}.meta.json`;
1814
+ const sourceParam = requestUrl.searchParams.get("src")
1815
+ ?? requestUrl.searchParams.get("url")
1816
+ ?? "";
1817
+ const originalSourceParam = requestUrl.searchParams.get("original") ?? "";
1818
+ const sourceCandidate = originalSourceParam.trim() || sourceParam;
1819
+ const cacheRaw = requestUrl.searchParams.get("cache") ?? requestUrl.searchParams.get("c");
1820
+ const cacheMaxAgeSeconds = parseImageCacheMaxAgeSeconds(cacheRaw);
1821
+ if (!sourceCandidate) {
1822
+ if (!(await exists(filePath))) {
1823
+ response.writeHead(404, {
1824
+ "content-type": "text/plain; charset=utf-8",
1825
+ "cache-control": "no-store",
1826
+ });
1827
+ response.end("Not found");
1828
+ return;
1829
+ }
1830
+ response.writeHead(200, {
1831
+ "content-type": mimeType(filePath),
1832
+ "cache-control": "public, max-age=86400",
1833
+ });
1834
+ if (method === "HEAD") {
1835
+ response.end();
1836
+ return;
1837
+ }
1838
+ response.end(await readFile(filePath));
1839
+ return;
1840
+ }
1841
+ const sourceUrl = resolveResuxImageSource(sourceCandidate, requestOrigin);
1842
+ if (!sourceUrl) {
1843
+ response.writeHead(400, {
1844
+ "content-type": "application/json; charset=utf-8",
1845
+ "cache-control": "no-store",
1846
+ });
1847
+ response.end(JSON.stringify({
1848
+ error: 'Generated image requests require "src" (or "url") with an absolute path or http(s) URL.',
1849
+ }));
1850
+ return;
1851
+ }
1852
+ const options = {
1853
+ width: parseImageInteger(requestUrl.searchParams.get("w"), 1, 8192)
1854
+ ?? parseImageInteger(requestUrl.searchParams.get("width"), 1, 8192),
1855
+ height: parseImageInteger(requestUrl.searchParams.get("h"), 1, 8192)
1856
+ ?? parseImageInteger(requestUrl.searchParams.get("height"), 1, 8192),
1857
+ quality: parseImageInteger(requestUrl.searchParams.get("q"), 1, 100)
1858
+ ?? parseImageInteger(requestUrl.searchParams.get("quality"), 1, 100),
1859
+ format: normalizeImageFormat(requestUrl.searchParams.get("f"))
1860
+ ?? normalizeImageFormat(requestUrl.searchParams.get("format")),
1861
+ fit: normalizeImageFit(requestUrl.searchParams.get("fit"))
1862
+ ?? normalizeImageFit(requestUrl.searchParams.get("mode")),
1863
+ extraModifiers: parseImageExtraModifiers(requestUrl.searchParams),
1864
+ };
1865
+ const generatedRoutePath = createGeneratedImageRoutePath(sourceParam, originalSourceParam || undefined, options.format, options);
1866
+ if (generatedRoutePath !== relativePath) {
1867
+ response.writeHead(404, {
1868
+ "content-type": "application/json; charset=utf-8",
1869
+ "cache-control": "no-store",
1870
+ });
1871
+ response.end(JSON.stringify({ error: "Generated image URL is not valid for the provided transform." }));
1872
+ return;
1873
+ }
1874
+ const sourceInfo = await resolveLocalSourceFileInfo(sourceUrl, requestOrigin, appRoot);
1875
+ const cacheKey = hashImageSignature(createImageTransformSignature(sourceParam, originalSourceParam || undefined, options.format, options));
1876
+ const now = Date.now();
1877
+ const metadata = await readGeneratedImageMetadata(metadataPath);
1878
+ if (cacheMaxAgeSeconds
1879
+ && (await exists(filePath))
1880
+ && metadata
1881
+ && generatedImageMetadataValid(metadata, cacheKey, now, sourceInfo)) {
1882
+ const remaining = Math.max(1, Math.floor((metadata.expiresAt - now) / 1000));
1883
+ response.writeHead(200, {
1884
+ "content-type": mimeType(filePath),
1885
+ "cache-control": `public, max-age=${remaining}`,
1886
+ "x-resux-cache": "hit",
1887
+ });
1888
+ if (method === "HEAD") {
1889
+ response.end();
1890
+ return;
1891
+ }
1892
+ response.end(await readFile(filePath));
1893
+ return;
1894
+ }
1895
+ const forwardedAccept = firstHeaderValue(request.headers.accept);
1896
+ const upstream = await fetch(sourceUrl, {
1897
+ headers: forwardedAccept ? { accept: forwardedAccept } : undefined,
1898
+ redirect: "follow",
1899
+ }).catch(() => null);
1900
+ if (!upstream) {
1901
+ response.writeHead(502, {
1902
+ "content-type": "application/json; charset=utf-8",
1903
+ "cache-control": "no-store",
1904
+ });
1905
+ response.end(JSON.stringify({ error: "Failed to fetch image source." }));
1906
+ return;
1907
+ }
1908
+ if (!upstream.ok) {
1909
+ response.writeHead(upstream.status, {
1910
+ "content-type": "application/json; charset=utf-8",
1911
+ "cache-control": "no-store",
1912
+ });
1913
+ response.end(JSON.stringify({
1914
+ error: `Image source request failed with status ${upstream.status}.`,
1915
+ }));
1916
+ return;
1917
+ }
1918
+ const sourceBuffer = Buffer.from(await upstream.arrayBuffer());
1919
+ const sourceContentType = upstream.headers.get("content-type");
1920
+ const needsTransform = shouldTransformImage(options);
1921
+ const transformed = await transformResuxImage(sourceBuffer, sourceContentType, options);
1922
+ if (needsTransform && !transformed) {
1923
+ response.writeHead(501, {
1924
+ "content-type": "application/json; charset=utf-8",
1925
+ "cache-control": "no-store",
1926
+ });
1927
+ response.end(JSON.stringify({
1928
+ error: sharpFactoryLoadError
1929
+ ?? "Image transform failed. Verify source format and requested modifiers.",
1930
+ }));
1931
+ return;
1932
+ }
1933
+ const body = transformed?.buffer ?? sourceBuffer;
1934
+ const contentType = transformed?.contentType ?? sourceContentType ?? "application/octet-stream";
1935
+ const expiresAt = cacheMaxAgeSeconds
1936
+ ? now + (cacheMaxAgeSeconds * 1000)
1937
+ : now;
1938
+ const responseMaxAge = cacheMaxAgeSeconds
1939
+ ? Math.max(1, Math.floor((expiresAt - now) / 1000))
1940
+ : 0;
1941
+ if (cacheMaxAgeSeconds) {
1942
+ await mkdir(path.dirname(filePath), { recursive: true });
1943
+ await writeFile(filePath, body);
1944
+ const metadataPayload = {
1945
+ version: 1,
1946
+ key: cacheKey,
1947
+ createdAt: now,
1948
+ expiresAt,
1949
+ originalSource: sourceCandidate,
1950
+ generatedPath: relativePath,
1951
+ transform: {
1952
+ ...(options.width ? { width: options.width } : {}),
1953
+ ...(options.height ? { height: options.height } : {}),
1954
+ ...(options.quality ? { quality: options.quality } : {}),
1955
+ ...(options.format ? { format: options.format } : {}),
1956
+ ...(options.fit ? { fit: options.fit } : {}),
1957
+ ...(options.extraModifiers && Object.keys(options.extraModifiers).length > 0
1958
+ ? { modifiers: options.extraModifiers }
1959
+ : {}),
1960
+ },
1961
+ ...(sourceInfo ? { sourceMtimeMs: sourceInfo.mtimeMs, sourceSize: sourceInfo.size } : {}),
1962
+ };
1963
+ await writeFile(metadataPath, `${JSON.stringify(metadataPayload, null, 2)}\n`, "utf8");
1964
+ }
1965
+ response.writeHead(200, {
1966
+ "content-type": contentType,
1967
+ "cache-control": cacheMaxAgeSeconds
1968
+ ? `public, max-age=${responseMaxAge}`
1969
+ : "no-store",
1970
+ "x-resux-cache": cacheMaxAgeSeconds ? "miss" : "bypass",
1971
+ vary: "Accept",
1972
+ });
1973
+ if (method === "HEAD") {
1974
+ response.end();
1975
+ return;
1976
+ }
1977
+ response.end(body);
1978
+ }
1483
1979
  function applyDefaultSecurityHeaders(response, enabled) {
1484
1980
  if (!enabled) {
1485
1981
  return;
@@ -1624,6 +2120,62 @@ function normalizeMiddlewareResult(result) {
1624
2120
  }
1625
2121
  return null;
1626
2122
  }
2123
+ function isPriorityImagePreloadLinkRecord(link) {
2124
+ return (String(link.rel ?? "").trim().toLowerCase() === "preload"
2125
+ && String(link.as ?? "").trim().toLowerCase() === "image");
2126
+ }
2127
+ function prioritizeHeadImagePreloads(head) {
2128
+ if (!head?.link || !head.link.length) {
2129
+ return;
2130
+ }
2131
+ const priorityLinks = head.link.filter((link) => isPriorityImagePreloadLinkRecord(link));
2132
+ if (!priorityLinks.length) {
2133
+ return;
2134
+ }
2135
+ const remainingLinks = head.link.filter((link) => !isPriorityImagePreloadLinkRecord(link));
2136
+ head.link = [...priorityLinks, ...remainingLinks];
2137
+ }
2138
+ function withPrioritizedHeadImagePreloads(result) {
2139
+ const clonedHead = result.head
2140
+ ? {
2141
+ ...result.head,
2142
+ link: result.head.link ? [...result.head.link] : result.head.link,
2143
+ }
2144
+ : result.head;
2145
+ prioritizeHeadImagePreloads(clonedHead);
2146
+ if (clonedHead === result.head) {
2147
+ return result;
2148
+ }
2149
+ return {
2150
+ ...result,
2151
+ head: clonedHead,
2152
+ };
2153
+ }
2154
+ function promoteDocumentImagePreloads(html) {
2155
+ const headStart = html.indexOf("<head>");
2156
+ const headEnd = html.indexOf("</head>");
2157
+ if (headStart === -1 || headEnd === -1 || headEnd <= headStart) {
2158
+ return html;
2159
+ }
2160
+ const headOpenEnd = headStart + "<head>".length;
2161
+ const headContent = html.slice(headOpenEnd, headEnd);
2162
+ const preloadPattern = /<link\b[^>]*\brel="preload"[^>]*\bas="image"[^>]*>/gi;
2163
+ const preloadTags = headContent.match(preloadPattern) ?? [];
2164
+ if (!preloadTags.length) {
2165
+ return html;
2166
+ }
2167
+ const headWithoutPreloads = headContent.replace(preloadPattern, "");
2168
+ const titleMatch = headWithoutPreloads.match(/<title\b[^>]*>[\s\S]*?<\/title>/i);
2169
+ const insertionPoint = titleMatch
2170
+ ? headWithoutPreloads.indexOf(titleMatch[0]) + titleMatch[0].length
2171
+ : 0;
2172
+ const reorderedHeadContent = headWithoutPreloads.slice(0, insertionPoint)
2173
+ + preloadTags.join("")
2174
+ + headWithoutPreloads.slice(insertionPoint);
2175
+ return (html.slice(0, headOpenEnd)
2176
+ + reorderedHeadContent
2177
+ + html.slice(headEnd));
2178
+ }
1627
2179
  function matchRouteRule(routeRules, pathname) {
1628
2180
  if (!routeRules) {
1629
2181
  return null;
@@ -1829,6 +2381,11 @@ function mimeType(file) {
1829
2381
  ".jpg": "image/jpeg",
1830
2382
  ".jpeg": "image/jpeg",
1831
2383
  ".webp": "image/webp",
2384
+ ".avif": "image/avif",
2385
+ ".gif": "image/gif",
2386
+ ".mp4": "video/mp4",
2387
+ ".webm": "video/webm",
2388
+ ".mov": "video/quicktime",
1832
2389
  ".ico": "image/x-icon",
1833
2390
  };
1834
2391
  return types[ext] ?? "application/octet-stream";