resuxjs 0.2.43 → 0.3.0

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.
Files changed (266) hide show
  1. package/README.md +991 -666
  2. package/dist/cli.js +1990 -355
  3. package/dist/cli.js.map +1 -1
  4. package/dist/compiler/adapter.d.ts +17 -0
  5. package/dist/compiler/adapter.js +106 -0
  6. package/dist/compiler/adapter.js.map +1 -0
  7. package/dist/compiler/dev-warnings.d.ts +11 -0
  8. package/dist/compiler/dev-warnings.js +360 -0
  9. package/dist/compiler/dev-warnings.js.map +1 -0
  10. package/dist/compiler/directives.d.ts +13 -0
  11. package/dist/compiler/directives.js +167 -0
  12. package/dist/compiler/directives.js.map +1 -0
  13. package/dist/compiler/implementation.d.ts +129 -0
  14. package/dist/compiler/implementation.js +3745 -0
  15. package/dist/compiler/implementation.js.map +1 -0
  16. package/dist/compiler/index.d.ts +9 -103
  17. package/dist/compiler/index.js +74 -1971
  18. package/dist/compiler/index.js.map +1 -1
  19. package/dist/core/config.d.ts +8 -0
  20. package/dist/core/config.js +21 -0
  21. package/dist/core/config.js.map +1 -0
  22. package/dist/core/hooks.d.ts +133 -0
  23. package/dist/core/hooks.js +54 -0
  24. package/dist/core/hooks.js.map +1 -0
  25. package/dist/core/index.d.ts +4 -0
  26. package/dist/core/index.js +5 -0
  27. package/dist/core/index.js.map +1 -0
  28. package/dist/core/module-container.d.ts +100 -0
  29. package/dist/core/module-container.js +171 -0
  30. package/dist/core/module-container.js.map +1 -0
  31. package/dist/core/resux.d.ts +18 -0
  32. package/dist/core/resux.js +18 -0
  33. package/dist/core/resux.js.map +1 -0
  34. package/dist/create.d.ts +1 -0
  35. package/dist/create.js +878 -22
  36. package/dist/create.js.map +1 -1
  37. package/dist/deploy/cloudflare.js +17 -3
  38. package/dist/deploy/cloudflare.js.map +1 -1
  39. package/dist/deploy/common.js +4 -3
  40. package/dist/deploy/common.js.map +1 -1
  41. package/dist/fonts/index.d.ts +16 -0
  42. package/dist/fonts/index.js +154 -0
  43. package/dist/fonts/index.js.map +1 -0
  44. package/dist/globals.d.ts +27 -2
  45. package/dist/halal-core/ai/classifyProject.d.ts +4 -0
  46. package/dist/halal-core/ai/classifyProject.js +104 -0
  47. package/dist/halal-core/ai/classifyProject.js.map +1 -0
  48. package/dist/halal-core/ai/createProjectSummary.d.ts +39 -0
  49. package/dist/halal-core/ai/createProjectSummary.js +42 -0
  50. package/dist/halal-core/ai/createProjectSummary.js.map +1 -0
  51. package/dist/halal-core/ai/halalClassifierPrompt.d.ts +1 -0
  52. package/dist/halal-core/ai/halalClassifierPrompt.js +20 -0
  53. package/dist/halal-core/ai/halalClassifierPrompt.js.map +1 -0
  54. package/dist/halal-core/ai/redactSensitiveData.d.ts +1 -0
  55. package/dist/halal-core/ai/redactSensitiveData.js +139 -0
  56. package/dist/halal-core/ai/redactSensitiveData.js.map +1 -0
  57. package/dist/halal-core/ai/validateAiResponse.d.ts +2 -0
  58. package/dist/halal-core/ai/validateAiResponse.js +97 -0
  59. package/dist/halal-core/ai/validateAiResponse.js.map +1 -0
  60. package/dist/halal-core/cli/check.d.ts +1 -0
  61. package/dist/halal-core/cli/check.js +36 -0
  62. package/dist/halal-core/cli/check.js.map +1 -0
  63. package/dist/halal-core/cli/explain.d.ts +1 -0
  64. package/dist/halal-core/cli/explain.js +35 -0
  65. package/dist/halal-core/cli/explain.js.map +1 -0
  66. package/dist/halal-core/cli/report.d.ts +1 -0
  67. package/dist/halal-core/cli/report.js +15 -0
  68. package/dist/halal-core/cli/report.js.map +1 -0
  69. package/dist/halal-core/cli/submitReview.d.ts +1 -0
  70. package/dist/halal-core/cli/submitReview.js +12 -0
  71. package/dist/halal-core/cli/submitReview.js.map +1 -0
  72. package/dist/halal-core/cli/verifyReview.d.ts +1 -0
  73. package/dist/halal-core/cli/verifyReview.js +19 -0
  74. package/dist/halal-core/cli/verifyReview.js.map +1 -0
  75. package/dist/halal-core/config.d.ts +40 -0
  76. package/dist/halal-core/config.js +128 -0
  77. package/dist/halal-core/config.js.map +1 -0
  78. package/dist/halal-core/crypto/integrity.d.ts +9 -0
  79. package/dist/halal-core/crypto/integrity.js +101 -0
  80. package/dist/halal-core/crypto/integrity.js.map +1 -0
  81. package/dist/halal-core/enforce.d.ts +5 -0
  82. package/dist/halal-core/enforce.js +119 -0
  83. package/dist/halal-core/enforce.js.map +1 -0
  84. package/dist/halal-core/index.d.ts +14 -0
  85. package/dist/halal-core/index.js +17 -0
  86. package/dist/halal-core/index.js.map +1 -0
  87. package/dist/halal-core/lifecycle.d.ts +1 -0
  88. package/dist/halal-core/lifecycle.js +15 -0
  89. package/dist/halal-core/lifecycle.js.map +1 -0
  90. package/dist/halal-core/policy.d.ts +2 -0
  91. package/dist/halal-core/policy.js +5 -0
  92. package/dist/halal-core/policy.js.map +1 -0
  93. package/dist/halal-core/report/formatBrowserOverlay.d.ts +2 -0
  94. package/dist/halal-core/report/formatBrowserOverlay.js +41 -0
  95. package/dist/halal-core/report/formatBrowserOverlay.js.map +1 -0
  96. package/dist/halal-core/report/formatTerminalReport.d.ts +2 -0
  97. package/dist/halal-core/report/formatTerminalReport.js +39 -0
  98. package/dist/halal-core/report/formatTerminalReport.js.map +1 -0
  99. package/dist/halal-core/report/generateHalalReport.d.ts +7 -0
  100. package/dist/halal-core/report/generateHalalReport.js +46 -0
  101. package/dist/halal-core/report/generateHalalReport.js.map +1 -0
  102. package/dist/halal-core/report/signReport.d.ts +3 -0
  103. package/dist/halal-core/report/signReport.js +17 -0
  104. package/dist/halal-core/report/signReport.js.map +1 -0
  105. package/dist/halal-core/report/verifyReport.d.ts +11 -0
  106. package/dist/halal-core/report/verifyReport.js +45 -0
  107. package/dist/halal-core/report/verifyReport.js.map +1 -0
  108. package/dist/halal-core/review/createReviewRequest.d.ts +2 -0
  109. package/dist/halal-core/review/createReviewRequest.js +21 -0
  110. package/dist/halal-core/review/createReviewRequest.js.map +1 -0
  111. package/dist/halal-core/review/reviewPolicy.d.ts +3 -0
  112. package/dist/halal-core/review/reviewPolicy.js +21 -0
  113. package/dist/halal-core/review/reviewPolicy.js.map +1 -0
  114. package/dist/halal-core/review/signedReviewFile.d.ts +13 -0
  115. package/dist/halal-core/review/signedReviewFile.js +28 -0
  116. package/dist/halal-core/review/signedReviewFile.js.map +1 -0
  117. package/dist/halal-core/review/verifyReviewApproval.d.ts +10 -0
  118. package/dist/halal-core/review/verifyReviewApproval.js +68 -0
  119. package/dist/halal-core/review/verifyReviewApproval.js.map +1 -0
  120. package/dist/halal-core/rules/adultContentRules.d.ts +2 -0
  121. package/dist/halal-core/rules/adultContentRules.js +26 -0
  122. package/dist/halal-core/rules/adultContentRules.js.map +1 -0
  123. package/dist/halal-core/rules/alcoholDrugVapeRules.d.ts +2 -0
  124. package/dist/halal-core/rules/alcoholDrugVapeRules.js +25 -0
  125. package/dist/halal-core/rules/alcoholDrugVapeRules.js.map +1 -0
  126. package/dist/halal-core/rules/childSafetyRules.d.ts +2 -0
  127. package/dist/halal-core/rules/childSafetyRules.js +22 -0
  128. package/dist/halal-core/rules/childSafetyRules.js.map +1 -0
  129. package/dist/halal-core/rules/coreCategories.d.ts +7 -0
  130. package/dist/halal-core/rules/coreCategories.js +112 -0
  131. package/dist/halal-core/rules/coreCategories.js.map +1 -0
  132. package/dist/halal-core/rules/cyberAbuseRules.d.ts +2 -0
  133. package/dist/halal-core/rules/cyberAbuseRules.js +30 -0
  134. package/dist/halal-core/rules/cyberAbuseRules.js.map +1 -0
  135. package/dist/halal-core/rules/defaultBlockedRules.d.ts +20 -0
  136. package/dist/halal-core/rules/defaultBlockedRules.js +216 -0
  137. package/dist/halal-core/rules/defaultBlockedRules.js.map +1 -0
  138. package/dist/halal-core/rules/dependencyRules.d.ts +9 -0
  139. package/dist/halal-core/rules/dependencyRules.js +59 -0
  140. package/dist/halal-core/rules/dependencyRules.js.map +1 -0
  141. package/dist/halal-core/rules/endpointRules.d.ts +6 -0
  142. package/dist/halal-core/rules/endpointRules.js +26 -0
  143. package/dist/halal-core/rules/endpointRules.js.map +1 -0
  144. package/dist/halal-core/rules/environmentalHarmRules.d.ts +2 -0
  145. package/dist/halal-core/rules/environmentalHarmRules.js +20 -0
  146. package/dist/halal-core/rules/environmentalHarmRules.js.map +1 -0
  147. package/dist/halal-core/rules/financeRibaRules.d.ts +2 -0
  148. package/dist/halal-core/rules/financeRibaRules.js +23 -0
  149. package/dist/halal-core/rules/financeRibaRules.js.map +1 -0
  150. package/dist/halal-core/rules/gamblingRules.d.ts +2 -0
  151. package/dist/halal-core/rules/gamblingRules.js +25 -0
  152. package/dist/halal-core/rules/gamblingRules.js.map +1 -0
  153. package/dist/halal-core/rules/generalHarmRules.d.ts +2 -0
  154. package/dist/halal-core/rules/generalHarmRules.js +18 -0
  155. package/dist/halal-core/rules/generalHarmRules.js.map +1 -0
  156. package/dist/halal-core/rules/healthHarmRules.d.ts +2 -0
  157. package/dist/halal-core/rules/healthHarmRules.js +22 -0
  158. package/dist/halal-core/rules/healthHarmRules.js.map +1 -0
  159. package/dist/halal-core/rules/keywordRules.d.ts +10 -0
  160. package/dist/halal-core/rules/keywordRules.js +41 -0
  161. package/dist/halal-core/rules/keywordRules.js.map +1 -0
  162. package/dist/halal-core/rules/privacyAbuseRules.d.ts +2 -0
  163. package/dist/halal-core/rules/privacyAbuseRules.js +24 -0
  164. package/dist/halal-core/rules/privacyAbuseRules.js.map +1 -0
  165. package/dist/halal-core/rules/scamFraudRules.d.ts +2 -0
  166. package/dist/halal-core/rules/scamFraudRules.js +32 -0
  167. package/dist/halal-core/rules/scamFraudRules.js.map +1 -0
  168. package/dist/halal-core/rules/selfHarmRules.d.ts +2 -0
  169. package/dist/halal-core/rules/selfHarmRules.js +20 -0
  170. package/dist/halal-core/rules/selfHarmRules.js.map +1 -0
  171. package/dist/halal-core/rules/violenceExtremismRules.d.ts +2 -0
  172. package/dist/halal-core/rules/violenceExtremismRules.js +33 -0
  173. package/dist/halal-core/rules/violenceExtremismRules.js.map +1 -0
  174. package/dist/halal-core/scanner/scanApiRoutes.d.ts +1 -0
  175. package/dist/halal-core/scanner/scanApiRoutes.js +40 -0
  176. package/dist/halal-core/scanner/scanApiRoutes.js.map +1 -0
  177. package/dist/halal-core/scanner/scanComponents.d.ts +1 -0
  178. package/dist/halal-core/scanner/scanComponents.js +17 -0
  179. package/dist/halal-core/scanner/scanComponents.js.map +1 -0
  180. package/dist/halal-core/scanner/scanContent.d.ts +5 -0
  181. package/dist/halal-core/scanner/scanContent.js +302 -0
  182. package/dist/halal-core/scanner/scanContent.js.map +1 -0
  183. package/dist/halal-core/scanner/scanDependencies.d.ts +1 -0
  184. package/dist/halal-core/scanner/scanDependencies.js +19 -0
  185. package/dist/halal-core/scanner/scanDependencies.js.map +1 -0
  186. package/dist/halal-core/scanner/scanDomains.d.ts +4 -0
  187. package/dist/halal-core/scanner/scanDomains.js +14 -0
  188. package/dist/halal-core/scanner/scanDomains.js.map +1 -0
  189. package/dist/halal-core/scanner/scanEnvNames.d.ts +1 -0
  190. package/dist/halal-core/scanner/scanEnvNames.js +30 -0
  191. package/dist/halal-core/scanner/scanEnvNames.js.map +1 -0
  192. package/dist/halal-core/scanner/scanMetadata.d.ts +6 -0
  193. package/dist/halal-core/scanner/scanMetadata.js +33 -0
  194. package/dist/halal-core/scanner/scanMetadata.js.map +1 -0
  195. package/dist/halal-core/scanner/scanPages.d.ts +1 -0
  196. package/dist/halal-core/scanner/scanPages.js +19 -0
  197. package/dist/halal-core/scanner/scanPages.js.map +1 -0
  198. package/dist/halal-core/scanner/scanProject.d.ts +13 -0
  199. package/dist/halal-core/scanner/scanProject.js +62 -0
  200. package/dist/halal-core/scanner/scanProject.js.map +1 -0
  201. package/dist/halal-core/scanner/scanRoutes.d.ts +1 -0
  202. package/dist/halal-core/scanner/scanRoutes.js +43 -0
  203. package/dist/halal-core/scanner/scanRoutes.js.map +1 -0
  204. package/dist/halal-core/scanner/scanTranslations.d.ts +1 -0
  205. package/dist/halal-core/scanner/scanTranslations.js +32 -0
  206. package/dist/halal-core/scanner/scanTranslations.js.map +1 -0
  207. package/dist/halal-core/status.d.ts +14 -0
  208. package/dist/halal-core/status.js +2 -0
  209. package/dist/halal-core/status.js.map +1 -0
  210. package/dist/halal-core/tamper/verifyCoreIntegrity.d.ts +1 -0
  211. package/dist/halal-core/tamper/verifyCoreIntegrity.js +28 -0
  212. package/dist/halal-core/tamper/verifyCoreIntegrity.js.map +1 -0
  213. package/dist/halal-core/tamper/verifyLifecycleHooks.d.ts +1 -0
  214. package/dist/halal-core/tamper/verifyLifecycleHooks.js +14 -0
  215. package/dist/halal-core/tamper/verifyLifecycleHooks.js.map +1 -0
  216. package/dist/halal-core/tamper/verifyReportSignature.d.ts +5 -0
  217. package/dist/halal-core/tamper/verifyReportSignature.js +18 -0
  218. package/dist/halal-core/tamper/verifyReportSignature.js.map +1 -0
  219. package/dist/i18n/index.d.ts +45 -0
  220. package/dist/i18n/index.js +284 -0
  221. package/dist/i18n/index.js.map +1 -0
  222. package/dist/i18n/shared.d.ts +35 -0
  223. package/dist/i18n/shared.js +270 -0
  224. package/dist/i18n/shared.js.map +1 -0
  225. package/dist/icons/index.d.ts +159 -0
  226. package/dist/icons/index.js +286 -0
  227. package/dist/icons/index.js.map +1 -0
  228. package/dist/kit/index.d.ts +29 -0
  229. package/dist/kit/index.js +72 -0
  230. package/dist/kit/index.js.map +1 -0
  231. package/dist/nitro-server/index.d.ts +7 -0
  232. package/dist/nitro-server/index.js +4 -0
  233. package/dist/nitro-server/index.js.map +1 -0
  234. package/dist/reactivity/computed.js +9 -4
  235. package/dist/reactivity/computed.js.map +1 -1
  236. package/dist/reactivity/effect.d.ts +3 -1
  237. package/dist/reactivity/effect.js +56 -6
  238. package/dist/reactivity/effect.js.map +1 -1
  239. package/dist/reactivity/reactive.js +64 -15
  240. package/dist/reactivity/reactive.js.map +1 -1
  241. package/dist/reactivity/ref.d.ts +1 -0
  242. package/dist/reactivity/ref.js +13 -6
  243. package/dist/reactivity/ref.js.map +1 -1
  244. package/dist/reactivity/scheduler.js +36 -4
  245. package/dist/reactivity/scheduler.js.map +1 -1
  246. package/dist/reactivity/watch.js +27 -5
  247. package/dist/reactivity/watch.js.map +1 -1
  248. package/dist/runtime/index.d.ts +226 -3
  249. package/dist/runtime/index.js +13344 -6395
  250. package/dist/runtime/index.js.map +1 -1
  251. package/dist/ui/index.d.ts +1828 -0
  252. package/dist/ui/index.js +938 -0
  253. package/dist/ui/index.js.map +1 -0
  254. package/dist/vite-builder/index.d.ts +6 -0
  255. package/dist/vite-builder/index.js +4 -0
  256. package/dist/vite-builder/index.js.map +1 -0
  257. package/package.json +145 -105
  258. package/templates/default/.env.example +1 -0
  259. package/templates/default/README.md +18 -14
  260. package/templates/default/_gitignore +8 -5
  261. package/templates/default/assets/css/main.css +4 -0
  262. package/templates/default/nitro.config.ts +9 -5
  263. package/templates/default/pages/index.vue +102 -87
  264. package/templates/default/public/favicon.svg +4 -0
  265. package/templates/default/types/app.d.ts +3 -0
  266. package/templates/default/.resux-nitro/handler.ts +0 -21
package/dist/cli.js CHANGED
@@ -1,14 +1,17 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { readdirSync, statSync, watch } from "node:fs";
3
3
  import { createServer as createHttpServer, } from "node:http";
4
- import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
4
+ import { cp, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
5
5
  import { createRequire } from "node:module";
6
6
  import path from "node:path";
7
7
  import { fileURLToPath, pathToFileURL } from "node:url";
8
+ import { createResux } from "./core/resux.js";
8
9
  import { runCreateResux } from "./create.js";
9
10
  import { applyDeploymentPostBuild, resolveDeployment, } from "./deploy/index.js";
11
+ import { loadResuxDeployConfig, readJsonRecord } from "./deploy/common.js";
10
12
  import { renderApp, renderDocument, } from "./runtime/index.js";
11
13
  export * from "./runtime/index.js";
14
+ import { enforceDevGuard, enforceBuildGuard, enforcePreviewGuard, enforceProductionServerGuard, enforceDeploymentGuard, loadProjectPolicy, scanProject, evaluateRules, formatBrowserOverlayScript, runHalalCheck, runHalalReport, runHalalExplain, runHalalSubmitReview, runHalalVerifyReview } from "./halal-core/index.js";
12
15
  const require = createRequire(import.meta.url);
13
16
  const version = require("../package.json").version ?? "0.0.0";
14
17
  let activeDevBuild = null;
@@ -17,33 +20,50 @@ let devBuildRevision = 0;
17
20
  let devReloadRevision = 0;
18
21
  let devLastBuildSourceMtime = 0;
19
22
  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>
23
+ let devHalalOverlayScript = "";
24
+ 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">
25
+ <title id="title">Resux mark</title>
26
+ <desc id="desc">A compact Resux monogram shaped like a resumable route.</desc>
27
+ <defs>
28
+ <linearGradient id="panel" x1="12" y1="8" x2="88" y2="92" gradientUnits="userSpaceOnUse">
29
+ <stop stop-color="#111827"/>
30
+ <stop offset="1" stop-color="#020617"/>
31
+ </linearGradient>
32
+ <linearGradient id="route" x1="25" y1="22" x2="73" y2="75" gradientUnits="userSpaceOnUse">
33
+ <stop stop-color="#22D3EE"/>
34
+ <stop offset="0.58" stop-color="#7C3AED"/>
35
+ <stop offset="1" stop-color="#10B981"/>
36
+ </linearGradient>
37
+ <filter id="soft" x="8" y="8" width="80" height="80" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
38
+ <feGaussianBlur stdDeviation="4"/>
39
+ </filter>
40
+ </defs>
41
+ <rect x="4" y="4" width="88" height="88" rx="22" fill="url(#panel)"/>
42
+ <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)"/>
43
+ <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"/>
44
+ <path d="M50 59L72 76" stroke="url(#route)" stroke-width="9" stroke-linecap="round" stroke-linejoin="round"/>
45
+ <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"/>
46
+ <circle cx="27" cy="25" r="4" fill="#22D3EE"/>
47
+ <circle cx="72" cy="76" r="4" fill="#10B981"/>
48
+ <path d="M22 14H34" stroke="#F8FAFC" stroke-opacity="0.22" stroke-width="3" stroke-linecap="round"/>
49
+ <path d="M62 82H74" stroke="#F8FAFC" stroke-opacity="0.22" stroke-width="3" stroke-linecap="round"/>
50
+ </svg>
51
+ `;
52
+ const REQUIRED_GITIGNORE_ENTRIES = [
53
+ ".resux",
54
+ ".resux-nitro",
55
+ ".nitro",
56
+ ".output",
57
+ "dist",
58
+ "node_modules",
59
+ ".env",
60
+ ".env.*",
61
+ "!.env.example",
62
+ ];
63
+ const GENERATED_DTS_PLACEHOLDER = `// Generated by Resux. Do not edit manually.
64
+ // This file will be updated by \`resux dev\` or \`resux build\`.
65
+
66
+ export {};
47
67
  `;
48
68
  async function runCompilerBuild(appRoot, outDir, options) {
49
69
  const { buildProject } = await import("./compiler/index.js");
@@ -53,6 +73,8 @@ export function createResuxNodeHandler(options = {}) {
53
73
  const appRoot = path.resolve(options.appRoot ?? process.cwd());
54
74
  const outDir = path.resolve(options.outDir ?? path.join(appRoot, ".resux"));
55
75
  const buildOptions = {};
76
+ // Run framework-level safety and compliance checks
77
+ enforceProductionServerGuard(outDir);
56
78
  return (request, response) => {
57
79
  void handleRequest(request, response, {
58
80
  appRoot,
@@ -64,7 +86,10 @@ export function createResuxNodeHandler(options = {}) {
64
86
  };
65
87
  }
66
88
  if (isMainModule()) {
67
- await runResuxCli(process.argv.slice(2));
89
+ void runResuxCli(process.argv.slice(2)).catch((error) => {
90
+ console.error(error instanceof Error ? error.message : String(error));
91
+ process.exitCode = 1;
92
+ });
68
93
  }
69
94
  export async function runResuxCli(args) {
70
95
  const command = readCommand(args);
@@ -81,49 +106,204 @@ export async function runResuxCli(args) {
81
106
  await runCreateResux(commandArgs);
82
107
  return;
83
108
  }
84
- const cliOptions = readCliOptions(commandArgs);
109
+ if (command === "halal") {
110
+ const subcommand = commandArgs[0];
111
+ const cliOptions = readCliOptions(commandArgs.slice(1), subcommand);
112
+ const appRoot = path.resolve(cliOptions.appRoot);
113
+ const resolvedBuildDir = await resolveConfiguredBuildDir(appRoot);
114
+ const outDir = path.resolve(appRoot, resolvedBuildDir);
115
+ if (subcommand === "check") {
116
+ const ok = await runHalalCheck(appRoot, outDir);
117
+ if (!ok)
118
+ process.exit(1);
119
+ return;
120
+ }
121
+ if (subcommand === "report") {
122
+ await runHalalReport(appRoot, outDir);
123
+ return;
124
+ }
125
+ if (subcommand === "explain") {
126
+ await runHalalExplain(appRoot);
127
+ return;
128
+ }
129
+ if (subcommand === "submit-review") {
130
+ await runHalalSubmitReview(appRoot, outDir);
131
+ return;
132
+ }
133
+ if (subcommand === "verify-review") {
134
+ const ok = await runHalalVerifyReview(appRoot);
135
+ if (!ok)
136
+ process.exit(1);
137
+ return;
138
+ }
139
+ console.error(`Unknown halal subcommand "${subcommand}". Allowed: check, report, explain, submit-review, verify-review`);
140
+ process.exit(1);
141
+ }
142
+ const cliOptions = readCliOptions(commandArgs, command);
85
143
  const appRoot = path.resolve(cliOptions.appRoot);
86
- const outDir = path.join(appRoot, ".resux");
87
- const buildOptions = {};
144
+ const resolvedBuildDir = await resolveConfiguredBuildDir(appRoot);
145
+ const outDir = path.resolve(appRoot, resolvedBuildDir);
146
+ const buildOptions = {
147
+ traceBuild: cliOptions.traceBuild === true
148
+ };
149
+ const resuxCore = createResux({ rootDir: appRoot, buildDir: outDir, config: {} });
150
+ buildOptions.hooks = resuxCore.hooks;
88
151
  const securityHeaders = cliOptions.securityHeaders ?? command !== "dev";
89
152
  const port = readPort(cliOptions.port ?? process.env.PORT, 3000);
90
153
  const tailwind = await resolveTailwindPipeline(appRoot);
154
+ if (cliOptions.traceResume) {
155
+ process.env.RESUX_TRACE_RESUME = "1";
156
+ }
157
+ if (cliOptions.traceRoutes) {
158
+ process.env.RESUX_TRACE_ROUTES = "1";
159
+ }
160
+ if (cliOptions.traceBuild) {
161
+ process.env.RESUX_TRACE_BUILD = "1";
162
+ }
163
+ if (cliOptions.https) {
164
+ console.warn("resux --https currently enables HTTPS URLs for routing/open but uses HTTP local server transport.");
165
+ }
166
+ if (cliOptions.debug) {
167
+ console.log(`[resux:debug] command=${command} root=${appRoot} outDir=${outDir} port=${port} host=${cliOptions.host ?? "localhost"}`);
168
+ }
91
169
  try {
170
+ if (command === "dev" || command === "build" || command === "preview" || command === "start" || command === "prepare") {
171
+ const safeFiles = await ensureSafeProjectFiles(appRoot, { fix: true });
172
+ for (const created of safeFiles.created) {
173
+ console.log(`Created missing safe file: ${created}`);
174
+ }
175
+ for (const updated of safeFiles.updated) {
176
+ console.log(`Updated safe file: ${updated}`);
177
+ }
178
+ }
179
+ if (command === "dev"
180
+ || command === "build"
181
+ || command === "preview"
182
+ || command === "start"
183
+ || command === "prepare") {
184
+ await ensureGeneratedDirectories(appRoot, outDir, { debug: cliOptions.debug === true || command === "dev" });
185
+ await ensureGeneratedPlaceholders(appRoot, outDir);
186
+ await ensureNitroBuildFiles(appRoot);
187
+ }
92
188
  if (command === "build") {
189
+ await enforceBuildGuard(appRoot, outDir);
93
190
  await runTailwindBuild(appRoot, tailwind, true);
94
191
  const result = await runCompilerBuild(appRoot, outDir, {
95
192
  ...buildOptions,
96
193
  vite: "build",
97
194
  });
195
+ await ensureGeneratedDirectories(appRoot, outDir, { debug: cliOptions.debug === true });
196
+ await ensureGeneratedPlaceholders(appRoot, outDir);
98
197
  console.log(`Built ${result.routes.length} route(s) into ${path.relative(process.cwd(), outDir)}`);
99
198
  await ensureNitroBuildFiles(appRoot);
100
- await runNitroBuild(appRoot, outDir);
199
+ await runNitroBuild(appRoot, outDir, buildOptions);
101
200
  }
102
201
  else if (command === "compile") {
202
+ await enforceBuildGuard(appRoot, outDir);
103
203
  await runTailwindBuild(appRoot, tailwind, true);
104
204
  const result = await runCompilerBuild(appRoot, outDir, {
105
205
  ...buildOptions,
106
206
  vite: "build",
107
207
  });
208
+ await ensureGeneratedDirectories(appRoot, outDir, { debug: cliOptions.debug === true });
209
+ await ensureGeneratedPlaceholders(appRoot, outDir);
108
210
  console.log(`Compiled ${result.routes.length} route(s) into ${path.relative(process.cwd(), outDir)}`);
109
211
  }
110
212
  else if (command === "deploy") {
213
+ enforceDeploymentGuard(outDir);
111
214
  await generateDeploymentFiles(appRoot, cliOptions.deployPreset, cliOptions.force);
112
215
  }
113
216
  else if (command === "inspect") {
114
- await inspectProject(appRoot, outDir, buildOptions, cliOptions.json);
217
+ await inspectProject(appRoot, outDir, buildOptions, cliOptions.json, cliOptions.inspectTarget);
218
+ }
219
+ else if (command === "check") {
220
+ const report = await checkProject(appRoot, outDir, { fix: cliOptions.fix, debug: cliOptions.debug });
221
+ if (cliOptions.json) {
222
+ console.log(JSON.stringify(report, null, 2));
223
+ }
224
+ else {
225
+ console.log(`Resux check: ${report.ok ? "ok" : "issues found"}`);
226
+ console.log(`Root: ${report.appRoot}`);
227
+ if (report.details.createdSafeFiles && Array.isArray(report.details.createdSafeFiles) && report.details.createdSafeFiles.length > 0) {
228
+ console.log("\nCreated safe files");
229
+ for (const created of report.details.createdSafeFiles) {
230
+ console.log(` - ${created}`);
231
+ }
232
+ }
233
+ if (report.details.updatedSafeFiles && Array.isArray(report.details.updatedSafeFiles) && report.details.updatedSafeFiles.length > 0) {
234
+ console.log("\nUpdated safe files");
235
+ for (const updated of report.details.updatedSafeFiles) {
236
+ console.log(` - ${updated}`);
237
+ }
238
+ }
239
+ if (report.details.createdGeneratedDirs
240
+ && Array.isArray(report.details.createdGeneratedDirs)
241
+ && report.details.createdGeneratedDirs.length > 0) {
242
+ console.log("\nCreated generated directories");
243
+ for (const createdDir of report.details.createdGeneratedDirs) {
244
+ console.log(` - ${createdDir}`);
245
+ }
246
+ }
247
+ if (report.details.createdGeneratedPlaceholders
248
+ && Array.isArray(report.details.createdGeneratedPlaceholders)
249
+ && report.details.createdGeneratedPlaceholders.length > 0) {
250
+ console.log("\nCreated generated placeholders");
251
+ for (const createdPlaceholder of report.details.createdGeneratedPlaceholders) {
252
+ console.log(` - ${createdPlaceholder}`);
253
+ }
254
+ }
255
+ if (report.errors.length) {
256
+ console.log("\nErrors");
257
+ for (const error of report.errors) {
258
+ console.log(` - ${error}`);
259
+ }
260
+ }
261
+ if (report.warnings.length) {
262
+ console.log("\nWarnings");
263
+ for (const warning of report.warnings) {
264
+ console.log(` - ${warning}`);
265
+ }
266
+ }
267
+ }
268
+ if (!report.ok) {
269
+ process.exitCode = 1;
270
+ }
271
+ }
272
+ else if (command === "prepare") {
273
+ await runTailwindBuild(appRoot, tailwind, false);
274
+ await runCompilerBuild(appRoot, outDir, { ...buildOptions, vite: "build" });
275
+ await ensureGeneratedDirectories(appRoot, outDir, { debug: cliOptions.debug === true });
276
+ await ensureGeneratedPlaceholders(appRoot, outDir);
277
+ await ensureNitroBuildFiles(appRoot);
278
+ const report = await checkProject(appRoot, outDir, { fix: false, debug: cliOptions.debug });
279
+ if (!report.ok) {
280
+ throw new Error(`resux prepare failed validation. Run "resux check --fix" and retry.`);
281
+ }
282
+ console.log(`Prepared Resux project at ${path.relative(process.cwd(), appRoot) || "."}.`);
115
283
  }
116
284
  else if (command === "dev") {
285
+ await enforceDevGuard(appRoot, outDir);
286
+ const policy = await loadProjectPolicy(appRoot);
287
+ const scanned = scanProject(appRoot);
288
+ const report = evaluateRules(scanned, policy);
289
+ if (report.status !== "allowed") {
290
+ devHalalOverlayScript = formatBrowserOverlayScript(report);
291
+ }
117
292
  await runTailwindBuild(appRoot, tailwind, false);
118
293
  startTailwindWatch(appRoot, tailwind);
119
294
  await runCompilerBuild(appRoot, outDir, { ...buildOptions, vite: "dev" });
120
- const vite = await startViteDevServer(outDir);
295
+ await ensureGeneratedDirectories(appRoot, outDir, { debug: cliOptions.debug === true });
296
+ await ensureGeneratedPlaceholders(appRoot, outDir);
297
+ await ensureNitroBuildFiles(appRoot);
298
+ const vite = await startViteDevServer(outDir, buildOptions, cliOptions);
121
299
  startDevWatcher(vite, appRoot, outDir, buildOptions);
122
300
  await startServer({
123
301
  appRoot,
124
302
  outDir,
125
303
  port,
126
304
  host: cliOptions.host,
305
+ open: cliOptions.open === true,
306
+ https: cliOptions.https === true,
127
307
  dev: true,
128
308
  buildOptions,
129
309
  vite,
@@ -131,15 +311,20 @@ export async function runResuxCli(args) {
131
311
  });
132
312
  }
133
313
  else if (command === "preview" || command === "start") {
314
+ enforcePreviewGuard(outDir);
134
315
  if (await previewNeedsBuild(outDir, buildOptions)) {
135
316
  await runTailwindBuild(appRoot, tailwind, true);
136
317
  await runCompilerBuild(appRoot, outDir, { ...buildOptions, vite: "build" });
318
+ await ensureGeneratedDirectories(appRoot, outDir, { debug: cliOptions.debug === true });
319
+ await ensureGeneratedPlaceholders(appRoot, outDir);
137
320
  }
138
321
  await startServer({
139
322
  appRoot,
140
323
  outDir,
141
324
  port,
142
325
  host: cliOptions.host,
326
+ open: cliOptions.open === true,
327
+ https: cliOptions.https === true,
143
328
  dev: false,
144
329
  buildOptions,
145
330
  securityHeaders,
@@ -301,14 +486,23 @@ function readCommand(args) {
301
486
  }
302
487
  return first;
303
488
  }
304
- function readCliOptions(args) {
489
+ function readCliOptions(args, command) {
305
490
  let appRoot = process.cwd();
306
491
  let port;
307
492
  let host;
493
+ let open;
494
+ let https;
495
+ let debug;
496
+ let traceResume;
497
+ let traceRoutes;
498
+ let traceBuild;
499
+ let inspectTarget;
308
500
  let securityHeaders;
309
501
  let json = false;
310
502
  let deployPreset = "node";
311
503
  let force = false;
504
+ let fix = false;
505
+ const inspectTargets = new Set(["routes", "plugins", "enhancements", "middleware", "imports", "components", "build", "images", "server", "packages", "templates", "bundles", "seo"]);
312
506
  for (let index = 0; index < args.length; index++) {
313
507
  const arg = args[index];
314
508
  if (arg === "--security-headers") {
@@ -329,6 +523,9 @@ function readCliOptions(args) {
329
523
  else if (arg === "--force") {
330
524
  force = true;
331
525
  }
526
+ else if (arg === "--fix") {
527
+ fix = true;
528
+ }
332
529
  else if (arg === "--port" || arg === "-p") {
333
530
  port = readRequiredOptionValue(args[++index], arg);
334
531
  }
@@ -341,14 +538,59 @@ function readCliOptions(args) {
341
538
  else if (arg.startsWith("--host=")) {
342
539
  host = arg.slice("--host=".length);
343
540
  }
541
+ else if (arg === "--open") {
542
+ open = true;
543
+ }
544
+ else if (arg === "--https") {
545
+ https = true;
546
+ }
547
+ else if (arg === "--debug") {
548
+ debug = true;
549
+ }
550
+ else if (arg === "--trace-resume") {
551
+ traceResume = true;
552
+ }
553
+ else if (arg === "--trace-routes") {
554
+ traceRoutes = true;
555
+ }
556
+ else if (arg === "--trace-build") {
557
+ traceBuild = true;
558
+ }
344
559
  else if (arg.startsWith("-")) {
345
560
  throw new Error(`Unknown option "${arg}". Run resux --help for usage.`);
346
561
  }
347
562
  else if (!arg.startsWith("-")) {
348
- appRoot = arg;
563
+ if (command === "inspect" && inspectTargets.has(arg)) {
564
+ inspectTarget = arg;
565
+ }
566
+ else if (appRoot === process.cwd()) {
567
+ appRoot = arg;
568
+ }
569
+ else if (command === "inspect" && !inspectTarget) {
570
+ inspectTarget = arg;
571
+ }
572
+ else {
573
+ appRoot = arg;
574
+ }
349
575
  }
350
576
  }
351
- return { appRoot, port, host, securityHeaders, json, deployPreset, force };
577
+ return {
578
+ appRoot,
579
+ port,
580
+ host,
581
+ open,
582
+ https,
583
+ debug,
584
+ traceResume,
585
+ traceRoutes,
586
+ traceBuild,
587
+ inspectTarget,
588
+ securityHeaders,
589
+ json,
590
+ deployPreset,
591
+ force,
592
+ fix,
593
+ };
352
594
  }
353
595
  function readRequiredOptionValue(value, option) {
354
596
  if (!value || value.startsWith("-")) {
@@ -356,6 +598,29 @@ function readRequiredOptionValue(value, option) {
356
598
  }
357
599
  return value;
358
600
  }
601
+ async function resolveConfiguredBuildDir(appRoot) {
602
+ const candidates = [
603
+ path.join(appRoot, "resux.config.ts"),
604
+ path.join(appRoot, "resux.config.mjs"),
605
+ path.join(appRoot, "resux.config.js"),
606
+ ];
607
+ for (const candidate of candidates) {
608
+ if (!(await exists(candidate))) {
609
+ continue;
610
+ }
611
+ try {
612
+ const source = await readFile(candidate, "utf8");
613
+ const match = /buildDir\s*:\s*["'`]([^"'`]+)["'`]/.exec(source);
614
+ if (match?.[1]) {
615
+ return match[1];
616
+ }
617
+ }
618
+ catch {
619
+ // Fall back to default buildDir.
620
+ }
621
+ }
622
+ return ".resux";
623
+ }
359
624
  function readDeployPreset(value) {
360
625
  if (value === "node" || value === "docker" || value === "nitro") {
361
626
  return value;
@@ -368,19 +633,125 @@ async function previewNeedsBuild(outDir, buildOptions) {
368
633
  }
369
634
  try {
370
635
  const manifest = JSON.parse(await readFile(path.join(outDir, "manifest.json"), "utf8"));
371
- return (manifest.features?.vite !== "build" ||
372
- manifest.features?.server !== "bundle");
636
+ if (manifest.features?.vite !== "build" ||
637
+ manifest.features?.server !== "bundle") {
638
+ return true;
639
+ }
640
+ const requiredAssets = collectRequiredPreviewAssets(manifest);
641
+ for (const relativePath of requiredAssets) {
642
+ if (!(await exists(path.join(outDir, relativePath)))) {
643
+ if (process.env.RESUX_TRACE_BUILD === "1") {
644
+ console.warn(`[resux:trace-build] preview rebuild required, missing asset: ${relativePath}`);
645
+ }
646
+ return true;
647
+ }
648
+ }
649
+ return false;
373
650
  }
374
651
  catch {
375
652
  return true;
376
653
  }
377
654
  }
378
- async function inspectProject(appRoot, outDir, buildOptions, json = false) {
655
+ function collectRequiredPreviewAssets(manifest) {
656
+ const required = new Set(["client/runtime-client.mjs", "client/client-enhancements.mjs"]);
657
+ const componentEntries = Array.isArray(manifest.components)
658
+ ? manifest.components
659
+ : [];
660
+ const pluginEntries = Array.isArray(manifest.plugins) ? manifest.plugins : [];
661
+ const middlewareEntries = Array.isArray(manifest.middleware)
662
+ ? manifest.middleware
663
+ : [];
664
+ const islandEntries = Array.isArray(manifest.vueIslands)
665
+ ? manifest.vueIslands
666
+ : [];
667
+ for (const component of componentEntries) {
668
+ if (!component?.id) {
669
+ continue;
670
+ }
671
+ required.add(`client/handlers/${component.id}.mjs`);
672
+ }
673
+ for (const plugin of pluginEntries) {
674
+ if (!plugin?.id || plugin.mode === "server") {
675
+ continue;
676
+ }
677
+ required.add(`client/plugins/${plugin.id}.mjs`);
678
+ }
679
+ for (const middleware of middlewareEntries) {
680
+ if (!middleware?.id || middleware.mode === "server") {
681
+ continue;
682
+ }
683
+ required.add(`client/middleware/${middleware.id}.mjs`);
684
+ }
685
+ for (const island of islandEntries) {
686
+ if (!island?.name) {
687
+ continue;
688
+ }
689
+ required.add(`client/vue-islands/${island.name}.mjs`);
690
+ }
691
+ return [...required];
692
+ }
693
+ async function readJsonFile(file) {
694
+ try {
695
+ return JSON.parse(await readFile(file, "utf8"));
696
+ }
697
+ catch {
698
+ return null;
699
+ }
700
+ }
701
+ async function readGeneratedDefaultExport(file) {
702
+ if (!(await exists(file))) {
703
+ return null;
704
+ }
705
+ try {
706
+ const imported = await import(`${pathToFileURL(file).href}?t=${Date.now()}`);
707
+ return (imported.default ?? null);
708
+ }
709
+ catch {
710
+ return null;
711
+ }
712
+ }
713
+ async function listRelativeFiles(dir, rootDir = dir) {
714
+ if (!(await exists(dir))) {
715
+ return [];
716
+ }
717
+ const entries = await readdir(dir, { withFileTypes: true });
718
+ const files = [];
719
+ for (const entry of entries) {
720
+ const fullPath = path.join(dir, entry.name);
721
+ if (entry.isDirectory()) {
722
+ files.push(...await listRelativeFiles(fullPath, rootDir));
723
+ continue;
724
+ }
725
+ if (!entry.isFile()) {
726
+ continue;
727
+ }
728
+ files.push(normalizePath(path.relative(rootDir, fullPath)));
729
+ }
730
+ return files.sort((left, right) => left.localeCompare(right));
731
+ }
732
+ function normalizePath(value) {
733
+ return value.split(path.sep).join("/");
734
+ }
735
+ async function inspectProject(appRoot, outDir, buildOptions, json = false, target) {
379
736
  if (await previewNeedsBuild(outDir, buildOptions)) {
380
737
  await runCompilerBuild(appRoot, outDir, { ...buildOptions, vite: "build" });
381
738
  }
382
739
  const manifest = JSON.parse(await readFile(path.join(outDir, "manifest.json"), "utf8"));
740
+ const buildManifest = await readJsonFile(path.join(outDir, "manifest", "build-manifest.json"));
741
+ const imports = await readGeneratedDefaultExport(path.join(outDir, "imports.mjs"));
742
+ const templateFiles = await listRelativeFiles(path.join(outDir, "templates"));
743
+ const bundleClientFiles = await listRelativeFiles(path.join(outDir, "client"));
744
+ const bundleServerFiles = await listRelativeFiles(path.join(outDir, "server-bundle"));
745
+ const components = manifest.components ?? [];
746
+ const plugins = manifest.plugins ?? [];
747
+ const clientEnhancements = manifest.clientEnhancements ?? [];
748
+ const middleware = manifest.middleware ?? [];
749
+ const serverHandlers = manifest.serverHandlers ?? [];
750
+ const packages = Array.isArray((buildManifest ?? {}).packages)
751
+ ? buildManifest.packages
752
+ : [];
383
753
  const routeRules = manifest.routeRules ?? {};
754
+ const seo = await inspectSeoMetadata(appRoot, manifest.routes ?? [], packages);
384
755
  const summary = {
385
756
  appRoot,
386
757
  outDir,
@@ -389,6 +760,7 @@ async function inspectProject(appRoot, outDir, buildOptions, json = false) {
389
760
  components: manifest.components?.length ?? 0,
390
761
  layouts: manifest.layouts?.length ?? 0,
391
762
  plugins: manifest.plugins?.length ?? 0,
763
+ clientEnhancements: clientEnhancements.length,
392
764
  middleware: manifest.middleware?.length ?? 0,
393
765
  serverMiddleware: manifest.serverMiddleware?.length ?? 0,
394
766
  serverHandlers: manifest.serverHandlers?.length ?? 0,
@@ -399,12 +771,41 @@ async function inspectProject(appRoot, outDir, buildOptions, json = false) {
399
771
  server: manifest.features?.server ?? "modules",
400
772
  },
401
773
  routes: manifest.routes ?? [],
402
- serverHandlers: manifest.serverHandlers ?? [],
774
+ serverHandlers,
403
775
  routeRules,
776
+ build: buildManifest ?? {},
777
+ imports: imports ?? [],
778
+ components,
779
+ plugins,
780
+ clientEnhancements,
781
+ middleware,
782
+ packages,
783
+ templates: templateFiles,
784
+ bundles: {
785
+ client: bundleClientFiles,
786
+ server: bundleServerFiles,
787
+ },
788
+ images: {
789
+ routeRule: routeRules["/__resux/image"] ?? null,
790
+ transforms: Array.isArray((buildManifest ?? {}).imageTransforms)
791
+ ? buildManifest.imageTransforms
792
+ : [],
793
+ },
794
+ server: {
795
+ handlers: serverHandlers,
796
+ middleware: manifest.serverMiddleware ?? [],
797
+ },
798
+ seo,
404
799
  diagnostics: createInspectDiagnostics(manifest),
405
800
  };
801
+ const targetPayload = readInspectTarget(summary, target);
406
802
  if (json) {
407
- console.log(JSON.stringify(summary, null, 2));
803
+ console.log(JSON.stringify(targetPayload ?? summary, null, 2));
804
+ return;
805
+ }
806
+ if (targetPayload) {
807
+ console.log(`Resux inspect target: ${target}`);
808
+ console.log(JSON.stringify(targetPayload, null, 2));
408
809
  return;
409
810
  }
410
811
  console.log(`Resux app: ${summary.appRoot}`);
@@ -413,6 +814,7 @@ async function inspectProject(appRoot, outDir, buildOptions, json = false) {
413
814
  console.log(`Components: ${summary.counts.components}`);
414
815
  console.log(`Layouts: ${summary.counts.layouts}`);
415
816
  console.log(`Plugins: ${summary.counts.plugins}`);
817
+ console.log(`Client enhancements: ${summary.counts.clientEnhancements}`);
416
818
  console.log(`Middleware: ${summary.counts.middleware}`);
417
819
  console.log(`Server middleware: ${summary.counts.serverMiddleware}`);
418
820
  console.log(`Server handlers: ${summary.counts.serverHandlers}`);
@@ -443,6 +845,107 @@ async function inspectProject(appRoot, outDir, buildOptions, json = false) {
443
845
  }
444
846
  }
445
847
  }
848
+ async function inspectSeoMetadata(appRoot, routes, packages) {
849
+ const pages = [];
850
+ const warnings = [];
851
+ const packageWarnings = [];
852
+ for (const route of routes) {
853
+ let source = "";
854
+ try {
855
+ source = await readFile(route.file, "utf8");
856
+ }
857
+ catch {
858
+ continue;
859
+ }
860
+ const hasSeoMeta = /useSeoMeta\s*\(/.test(source);
861
+ const hasHead = /useHead\s*\(/.test(source);
862
+ const hasH1 = /<h1[\s>]/i.test(source);
863
+ const hasMain = /<main[\s>]/i.test(source);
864
+ const hasCanonical = /canonical/i.test(source) || /rel\s*:\s*["']canonical["']/.test(source);
865
+ const hasClientOnlyBlock = /<ClientOnly[\s>]/.test(source) || /<LazyClientOnly[\s>]/.test(source);
866
+ const pageWarnings = [];
867
+ if (!hasH1) {
868
+ pageWarnings.push("Missing <h1> heading.");
869
+ }
870
+ if (!hasMain) {
871
+ pageWarnings.push("Missing <main> landmark.");
872
+ }
873
+ if (!hasSeoMeta && !hasHead) {
874
+ pageWarnings.push("Missing useSeoMeta()/useHead() metadata.");
875
+ }
876
+ if (hasClientOnlyBlock && /<ClientOnly[\s\S]*<main[\s>]/i.test(source)) {
877
+ pageWarnings.push("ClientOnly appears to wrap a major content block. Prefer SSR-first content plus enhancement.");
878
+ }
879
+ if (route.path.startsWith("/package-tests") && !hasCanonical) {
880
+ pageWarnings.push("Package demo page is missing canonical metadata.");
881
+ }
882
+ if (pageWarnings.length > 0) {
883
+ warnings.push(`${route.path}: ${pageWarnings.join(" ")}`);
884
+ }
885
+ pages.push({
886
+ route: route.path,
887
+ file: path.relative(appRoot, route.file),
888
+ hasSeoMeta,
889
+ hasHead,
890
+ hasH1,
891
+ hasMain,
892
+ hasCanonical,
893
+ hasClientOnlyBlock,
894
+ warnings: pageWarnings,
895
+ });
896
+ }
897
+ for (const entry of packages) {
898
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
899
+ continue;
900
+ }
901
+ const packageName = typeof entry.name === "string"
902
+ ? entry.name
903
+ : "unknown";
904
+ const packageEntryWarnings = Array.isArray(entry.warnings)
905
+ ? entry.warnings
906
+ : [];
907
+ for (const warning of packageEntryWarnings) {
908
+ packageWarnings.push(`${packageName}: ${String(warning)}`);
909
+ }
910
+ }
911
+ return {
912
+ pages,
913
+ warnings,
914
+ packageWarnings,
915
+ };
916
+ }
917
+ function readInspectTarget(summary, target) {
918
+ if (!target) {
919
+ return null;
920
+ }
921
+ if (target === "routes")
922
+ return summary.routes;
923
+ if (target === "plugins")
924
+ return summary.plugins;
925
+ if (target === "enhancements")
926
+ return summary.clientEnhancements;
927
+ if (target === "middleware")
928
+ return summary.middleware;
929
+ if (target === "imports")
930
+ return summary.imports;
931
+ if (target === "components")
932
+ return summary.components;
933
+ if (target === "packages")
934
+ return summary.packages;
935
+ if (target === "templates")
936
+ return summary.templates;
937
+ if (target === "bundles")
938
+ return summary.bundles;
939
+ if (target === "build")
940
+ return summary.build;
941
+ if (target === "images")
942
+ return summary.images;
943
+ if (target === "server")
944
+ return summary.server;
945
+ if (target === "seo")
946
+ return summary.seo;
947
+ return null;
948
+ }
446
949
  function createInspectDiagnostics(manifest) {
447
950
  const diagnostics = [];
448
951
  if (!manifest.routes?.length) {
@@ -465,6 +968,403 @@ function createInspectDiagnostics(manifest) {
465
968
  }
466
969
  return diagnostics;
467
970
  }
971
+ function generatedRootPaths(appRoot, outDir) {
972
+ return [path.resolve(outDir), path.join(appRoot, ".resux-nitro"), path.join(appRoot, ".nitro")];
973
+ }
974
+ function generatedDirectoryPaths(appRoot, outDir) {
975
+ const absoluteOutDir = path.resolve(outDir);
976
+ const resuxNitroDir = path.join(appRoot, ".resux-nitro");
977
+ const nitroDir = path.join(appRoot, ".nitro");
978
+ return [
979
+ absoluteOutDir,
980
+ path.join(absoluteOutDir, "dev"),
981
+ path.join(absoluteOutDir, "cache"),
982
+ path.join(absoluteOutDir, "types"),
983
+ path.join(absoluteOutDir, "manifest"),
984
+ path.join(absoluteOutDir, "vite-client"),
985
+ resuxNitroDir,
986
+ path.join(resuxNitroDir, "cache"),
987
+ path.join(resuxNitroDir, "types"),
988
+ path.join(resuxNitroDir, "manifest"),
989
+ nitroDir,
990
+ path.join(nitroDir, "types"),
991
+ path.join(nitroDir, "cache"),
992
+ ];
993
+ }
994
+ function generatedPlaceholderFiles(appRoot, outDir) {
995
+ return [
996
+ {
997
+ file: path.join(outDir, "types", "resux.d.ts"),
998
+ contents: GENERATED_DTS_PLACEHOLDER,
999
+ },
1000
+ {
1001
+ file: path.join(outDir, "types", "imports.d.ts"),
1002
+ contents: GENERATED_DTS_PLACEHOLDER,
1003
+ },
1004
+ {
1005
+ file: path.join(outDir, "manifest", "routes.json"),
1006
+ contents: `${JSON.stringify({
1007
+ generatedBy: "resux",
1008
+ note: "Generated placeholder. Updated by `resux dev` or `resux build`.",
1009
+ routes: [],
1010
+ }, null, 2)}\n`,
1011
+ },
1012
+ {
1013
+ file: path.join(outDir, "manifest", "plugins.json"),
1014
+ contents: `${JSON.stringify({
1015
+ generatedBy: "resux",
1016
+ note: "Generated placeholder. Updated by `resux dev` or `resux build`.",
1017
+ plugins: [],
1018
+ }, null, 2)}\n`,
1019
+ },
1020
+ {
1021
+ file: path.join(outDir, "manifest", "middleware.json"),
1022
+ contents: `${JSON.stringify({
1023
+ generatedBy: "resux",
1024
+ note: "Generated placeholder. Updated by `resux dev` or `resux build`.",
1025
+ middleware: [],
1026
+ }, null, 2)}\n`,
1027
+ },
1028
+ {
1029
+ file: path.join(appRoot, ".resux-nitro", "manifest", "server-handlers.json"),
1030
+ contents: `${JSON.stringify({
1031
+ generatedBy: "resux",
1032
+ note: "Generated placeholder. Updated by `resux dev` or `resux build`.",
1033
+ handlers: [],
1034
+ }, null, 2)}\n`,
1035
+ },
1036
+ {
1037
+ file: path.join(appRoot, ".nitro", "types", "nitro.d.ts"),
1038
+ contents: GENERATED_DTS_PLACEHOLDER,
1039
+ },
1040
+ ];
1041
+ }
1042
+ function toAppRelativePath(appRoot, targetPath) {
1043
+ const relativePath = path.relative(appRoot, targetPath);
1044
+ return normalizePath(relativePath || ".");
1045
+ }
1046
+ async function ensureGeneratedDirectories(appRoot, outDir, options = { debug: false }) {
1047
+ const created = [];
1048
+ const missingBeforeCreation = [];
1049
+ const generatedDirs = generatedDirectoryPaths(appRoot, outDir);
1050
+ const topLevelDirs = new Set(generatedRootPaths(appRoot, outDir).map((entry) => path.resolve(entry)));
1051
+ for (const dir of generatedDirs) {
1052
+ const absoluteDir = path.resolve(dir);
1053
+ const alreadyExists = await exists(absoluteDir);
1054
+ if (!alreadyExists) {
1055
+ const displayPath = toAppRelativePath(appRoot, absoluteDir);
1056
+ missingBeforeCreation.push(displayPath);
1057
+ created.push(displayPath);
1058
+ if (options.debug && topLevelDirs.has(absoluteDir)) {
1059
+ console.log(`[resux] Created generated directory: ${displayPath}`);
1060
+ }
1061
+ }
1062
+ await mkdir(absoluteDir, { recursive: true });
1063
+ }
1064
+ return { created, missingBeforeCreation };
1065
+ }
1066
+ async function ensureGeneratedPlaceholders(appRoot, outDir) {
1067
+ const created = [];
1068
+ const placeholders = generatedPlaceholderFiles(appRoot, outDir);
1069
+ for (const placeholder of placeholders) {
1070
+ if (await exists(placeholder.file)) {
1071
+ continue;
1072
+ }
1073
+ await mkdir(path.dirname(placeholder.file), { recursive: true });
1074
+ await writeFile(placeholder.file, placeholder.contents, "utf8");
1075
+ created.push(toAppRelativePath(appRoot, placeholder.file));
1076
+ }
1077
+ return { created };
1078
+ }
1079
+ function missingGitignoreEntries(source) {
1080
+ const lines = source
1081
+ .split(/\r?\n/g)
1082
+ .map((entry) => entry.trim())
1083
+ .filter((entry) => entry.length > 0 && !entry.startsWith("#"));
1084
+ const existing = new Set(lines);
1085
+ return REQUIRED_GITIGNORE_ENTRIES.filter((entry) => !existing.has(entry));
1086
+ }
1087
+ async function checkProject(appRoot, outDir, options = {}) {
1088
+ const errors = [];
1089
+ const warnings = [];
1090
+ const details = {};
1091
+ const safeFilesResult = await ensureSafeProjectFiles(appRoot, { fix: options.fix === true });
1092
+ if (safeFilesResult.created.length > 0) {
1093
+ details.createdSafeFiles = safeFilesResult.created;
1094
+ }
1095
+ if (safeFilesResult.updated.length > 0) {
1096
+ details.updatedSafeFiles = safeFilesResult.updated;
1097
+ }
1098
+ for (const missing of safeFilesResult.missing) {
1099
+ warnings.push(`Missing required safe file: ${missing}. Run "resux check --fix" to scaffold it.`);
1100
+ }
1101
+ const generatedDirs = generatedDirectoryPaths(appRoot, outDir);
1102
+ const missingGenerated = [];
1103
+ for (const directory of generatedDirs) {
1104
+ if (!(await exists(directory))) {
1105
+ missingGenerated.push(toAppRelativePath(appRoot, directory));
1106
+ }
1107
+ }
1108
+ if (missingGenerated.length > 0) {
1109
+ details.missingGeneratedDirs = missingGenerated;
1110
+ if (options.fix) {
1111
+ for (const directory of missingGenerated) {
1112
+ console.log(`[resux check] Missing generated directory: ${directory}`);
1113
+ }
1114
+ const ensured = await ensureGeneratedDirectories(appRoot, outDir, { debug: false });
1115
+ for (const createdDir of ensured.created) {
1116
+ console.log(`[resux check] Created: ${createdDir}`);
1117
+ }
1118
+ details.createdGeneratedDirs = ensured.created;
1119
+ const placeholderResult = await ensureGeneratedPlaceholders(appRoot, outDir);
1120
+ if (placeholderResult.created.length > 0) {
1121
+ details.createdGeneratedPlaceholders = placeholderResult.created;
1122
+ }
1123
+ await ensureNitroBuildFiles(appRoot);
1124
+ }
1125
+ else {
1126
+ for (const directory of missingGenerated) {
1127
+ warnings.push(`Missing generated directory: ${directory}. Run "resux check --fix" or "resux prepare".`);
1128
+ }
1129
+ }
1130
+ }
1131
+ else if (options.fix) {
1132
+ const placeholderResult = await ensureGeneratedPlaceholders(appRoot, outDir);
1133
+ if (placeholderResult.created.length > 0) {
1134
+ details.createdGeneratedPlaceholders = placeholderResult.created;
1135
+ }
1136
+ await ensureNitroBuildFiles(appRoot);
1137
+ }
1138
+ const packageFile = path.join(appRoot, "package.json");
1139
+ if (!(await exists(packageFile))) {
1140
+ errors.push("Missing package.json.");
1141
+ }
1142
+ const configFile = await firstExistingPath([
1143
+ path.join(appRoot, "resux.config.ts"),
1144
+ path.join(appRoot, "resux.config.mjs"),
1145
+ path.join(appRoot, "resux.config.js"),
1146
+ ]);
1147
+ if (!configFile) {
1148
+ if (options.fix) {
1149
+ const generatedConfig = path.join(appRoot, "resux.config.ts");
1150
+ await writeFile(generatedConfig, `export default defineResuxConfig({\n runtimeConfig: {\n public: {\n appName: "Resux App"\n }\n }\n})\n`, "utf8");
1151
+ details.configFile = path.relative(appRoot, generatedConfig);
1152
+ warnings.push("Created minimal resux.config.ts.");
1153
+ }
1154
+ else {
1155
+ errors.push("Missing Resux config file (resux.config.ts/mjs/js).");
1156
+ }
1157
+ }
1158
+ else {
1159
+ details.configFile = path.relative(appRoot, configFile);
1160
+ }
1161
+ const tsconfigFile = path.join(appRoot, "tsconfig.json");
1162
+ if (!(await exists(tsconfigFile))) {
1163
+ if (options.fix) {
1164
+ await writeFile(tsconfigFile, `{\n "compilerOptions": {\n "target": "ES2022",\n "module": "ESNext",\n "moduleResolution": "Bundler",\n "strict": true,\n "types": ["node", "resuxjs/globals"]\n },\n "include": ["**/*.ts", "**/*.tsx", "**/*.vue", "types/**/*.d.ts", "env.d.ts"]\n}\n`, "utf8");
1165
+ details.tsconfigFile = path.relative(appRoot, tsconfigFile);
1166
+ warnings.push("Created minimal tsconfig.json.");
1167
+ }
1168
+ else {
1169
+ warnings.push("Missing tsconfig.json. Run \"resux check --fix\" or scaffold it during project creation.");
1170
+ }
1171
+ }
1172
+ else {
1173
+ details.tsconfigFile = path.relative(appRoot, tsconfigFile);
1174
+ }
1175
+ if (!(await exists(path.join(appRoot, "nitro.config.ts")))) {
1176
+ if (options.fix) {
1177
+ await ensureNitroBuildFiles(appRoot);
1178
+ warnings.push("Created missing nitro.config.ts.");
1179
+ }
1180
+ else {
1181
+ warnings.push("Missing nitro.config.ts. Run \"resux check --fix\" to scaffold it.");
1182
+ }
1183
+ }
1184
+ if (!(await exists(path.join(appRoot, ".resux-nitro", "handler.ts")))) {
1185
+ if (options.fix) {
1186
+ await ensureNitroBuildFiles(appRoot);
1187
+ warnings.push("Created missing .resux-nitro/handler.ts.");
1188
+ }
1189
+ else {
1190
+ warnings.push("Missing .resux-nitro/handler.ts. Run \"resux check --fix\" to scaffold it.");
1191
+ }
1192
+ }
1193
+ if (!(await exists(path.join(appRoot, "app.vue")))) {
1194
+ warnings.push("Missing app.vue (Resux will still run but starter conventions expect it).");
1195
+ }
1196
+ if (!(await exists(path.join(appRoot, "pages")))) {
1197
+ errors.push("Missing pages/ directory.");
1198
+ }
1199
+ if (!(await exists(path.join(appRoot, "layouts")))) {
1200
+ warnings.push("Missing layouts/ directory.");
1201
+ }
1202
+ let packageJson = null;
1203
+ if (await exists(packageFile)) {
1204
+ try {
1205
+ packageJson = JSON.parse(await readFile(packageFile, "utf8"));
1206
+ }
1207
+ catch (error) {
1208
+ errors.push(`Invalid package.json: ${error instanceof Error ? error.message : String(error)}`);
1209
+ }
1210
+ }
1211
+ if (packageJson) {
1212
+ const requiredScripts = ["prepare", "dev", "build", "preview", "start", "inspect"];
1213
+ const scripts = packageJson.scripts ?? {};
1214
+ for (const scriptName of requiredScripts) {
1215
+ if (!scripts[scriptName]) {
1216
+ warnings.push(`Recommended npm script "${scriptName}" is missing.`);
1217
+ }
1218
+ }
1219
+ const deps = { ...(packageJson.dependencies ?? {}), ...(packageJson.devDependencies ?? {}) };
1220
+ if (!deps.resuxjs) {
1221
+ errors.push("Dependency \"resuxjs\" is missing from package.json.");
1222
+ }
1223
+ details.dependencies = Object.keys(deps).sort();
1224
+ }
1225
+ const builtManifestFile = path.join(outDir, "manifest.json");
1226
+ const buildManifestFile = path.join(outDir, "manifest", "build-manifest.json");
1227
+ const hasBuiltOutput = await exists(builtManifestFile);
1228
+ details.hasBuiltOutput = hasBuiltOutput;
1229
+ if (hasBuiltOutput) {
1230
+ if (!(await exists(path.join(outDir, "server", "manifest.mjs")))) {
1231
+ errors.push("Built output is missing .resux/server/manifest.mjs.");
1232
+ }
1233
+ if (!(await exists(buildManifestFile))) {
1234
+ warnings.push("Built output is missing .resux/manifest/build-manifest.json.");
1235
+ }
1236
+ if (!(await exists(path.join(outDir, "client", "runtime-client.mjs")))) {
1237
+ errors.push("Built output is missing .resux/client/runtime-client.mjs.");
1238
+ }
1239
+ if (!(await exists(path.join(outDir, "client", "client-enhancements.mjs")))) {
1240
+ errors.push("Built output is missing .resux/client/client-enhancements.mjs.");
1241
+ }
1242
+ if (!(await exists(path.join(appRoot, ".output", "server", "index.mjs")))) {
1243
+ warnings.push("Nitro output .output/server/index.mjs is missing. Run \"resux build\".");
1244
+ }
1245
+ if (!(await exists(path.join(appRoot, ".output", "public", "__resux", "runtime-client.mjs")))) {
1246
+ warnings.push("Nitro public asset .output/public/__resux/runtime-client.mjs is missing.");
1247
+ }
1248
+ if (!(await exists(path.join(appRoot, ".output", "public", "__resux", "client-enhancements.mjs")))) {
1249
+ warnings.push("Nitro public asset .output/public/__resux/client-enhancements.mjs is missing.");
1250
+ }
1251
+ }
1252
+ else {
1253
+ warnings.push("No .resux build output found yet. Run \"resux build\" to validate generated artifacts.");
1254
+ }
1255
+ if (configFile) {
1256
+ try {
1257
+ const configSource = await readFile(configFile, "utf8");
1258
+ if (/packages\s*:\s*\{[\s\S]*clientOnly\s*:/m.test(configSource) && packageJson) {
1259
+ const deps = { ...(packageJson.dependencies ?? {}), ...(packageJson.devDependencies ?? {}) };
1260
+ const matches = [...configSource.matchAll(/clientOnly\s*:\s*\[([^\]]*)\]/g)];
1261
+ for (const match of matches) {
1262
+ const values = match[1]
1263
+ .split(",")
1264
+ .map((entry) => entry.replace(/["'`\s]/g, ""))
1265
+ .filter(Boolean);
1266
+ for (const pkg of values) {
1267
+ if (!deps[pkg]) {
1268
+ warnings.push(`packages.clientOnly references "${pkg}" but it is not installed.`);
1269
+ }
1270
+ }
1271
+ }
1272
+ }
1273
+ }
1274
+ catch {
1275
+ // ignore
1276
+ }
1277
+ }
1278
+ return {
1279
+ ok: errors.length === 0,
1280
+ appRoot,
1281
+ outDir,
1282
+ errors,
1283
+ warnings,
1284
+ details,
1285
+ };
1286
+ }
1287
+ async function ensureSafeProjectFiles(appRoot, options) {
1288
+ const created = [];
1289
+ const updated = [];
1290
+ const missing = [];
1291
+ const pagesDir = path.join(appRoot, "pages");
1292
+ const hasPagesDir = await exists(pagesDir);
1293
+ const gitignorePath = path.join(appRoot, ".gitignore");
1294
+ if (await exists(gitignorePath)) {
1295
+ const gitignoreSource = await readFile(gitignorePath, "utf8");
1296
+ const entriesToAdd = missingGitignoreEntries(gitignoreSource);
1297
+ if (entriesToAdd.length > 0) {
1298
+ if (!options.fix) {
1299
+ missing.push(`.gitignore entries: ${entriesToAdd.join(", ")}`);
1300
+ }
1301
+ else {
1302
+ const newline = gitignoreSource.includes("\r\n") ? "\r\n" : "\n";
1303
+ const suffix = gitignoreSource.endsWith("\n") || gitignoreSource.length === 0 ? "" : newline;
1304
+ const appendedSource = `${gitignoreSource}${suffix}${entriesToAdd.join(newline)}${newline}`;
1305
+ await writeFile(gitignorePath, appendedSource, "utf8");
1306
+ updated.push(".gitignore");
1307
+ }
1308
+ }
1309
+ }
1310
+ const safeFiles = [
1311
+ {
1312
+ path: ".gitignore",
1313
+ contents: `${REQUIRED_GITIGNORE_ENTRIES.join("\n")}\n`,
1314
+ },
1315
+ {
1316
+ path: ".npmrc",
1317
+ contents: "engine-strict=true\n",
1318
+ },
1319
+ {
1320
+ path: ".env.example",
1321
+ contents: "# Example runtime variables\nAPP_ORIGIN=http://localhost:3000\n",
1322
+ },
1323
+ {
1324
+ path: "types/app.d.ts",
1325
+ contents: 'import "resuxjs/globals";\n\nexport {};\n',
1326
+ },
1327
+ {
1328
+ path: "env.d.ts",
1329
+ contents: '/// <reference types="resuxjs/globals" />\n',
1330
+ },
1331
+ {
1332
+ path: "assets/css/main.css",
1333
+ contents: "body { margin: 0; font-family: \"Segoe UI\", system-ui, sans-serif; }\n",
1334
+ },
1335
+ {
1336
+ path: "public/favicon.svg",
1337
+ contents: RESUX_PLACEHOLDER_SVG,
1338
+ },
1339
+ {
1340
+ path: "app.vue",
1341
+ contents: `<template>
1342
+ <ResuxLayout>
1343
+ <ResuxPage />
1344
+ </ResuxLayout>
1345
+ </template>
1346
+ `,
1347
+ condition: hasPagesDir,
1348
+ },
1349
+ ];
1350
+ for (const file of safeFiles) {
1351
+ if (file.condition === false) {
1352
+ continue;
1353
+ }
1354
+ const absoluteFile = path.join(appRoot, file.path);
1355
+ if (await exists(absoluteFile)) {
1356
+ continue;
1357
+ }
1358
+ if (!options.fix) {
1359
+ missing.push(file.path);
1360
+ continue;
1361
+ }
1362
+ await mkdir(path.dirname(absoluteFile), { recursive: true });
1363
+ await writeFile(absoluteFile, file.contents, "utf8");
1364
+ created.push(file.path);
1365
+ }
1366
+ return { created, updated, missing };
1367
+ }
468
1368
  async function generateDeploymentFiles(appRoot, preset, force) {
469
1369
  await assertDirectory(appRoot);
470
1370
  const files = [
@@ -501,30 +1401,118 @@ async function generateDeploymentFiles(appRoot, preset, force) {
501
1401
  for (const file of files) {
502
1402
  written.push(await writeDeploymentFile(appRoot, file.relativePath, file.contents, force));
503
1403
  }
504
- console.log(`Generated Resux ${preset} deployment file(s):`);
505
- for (const file of written) {
506
- console.log(` ${file}`);
1404
+ console.log(`Generated Resux ${preset} deployment file(s):`);
1405
+ for (const file of written) {
1406
+ console.log(` ${file}`);
1407
+ }
1408
+ }
1409
+ async function ensureNitroBuildFiles(appRoot) {
1410
+ const nitroConfigFile = path.join(appRoot, "nitro.config.ts");
1411
+ if (!(await exists(nitroConfigFile))) {
1412
+ await writeDeploymentFile(appRoot, "nitro.config.ts", createNitroConfig(), false);
1413
+ }
1414
+ else {
1415
+ await upgradeNitroConfigForResux(nitroConfigFile);
1416
+ }
1417
+ if (!(await exists(path.join(appRoot, ".resux-nitro", "handler.ts")))) {
1418
+ await writeDeploymentFile(appRoot, ".resux-nitro/handler.ts", createNitroHandler(), false);
1419
+ }
1420
+ const resolvedBuildDir = await resolveConfiguredBuildDir(appRoot);
1421
+ const outDir = path.resolve(appRoot, resolvedBuildDir);
1422
+ await updateNitroConfigPrerenderRoutes(appRoot, outDir);
1423
+ }
1424
+ async function updateNitroConfigPrerenderRoutes(appRoot, outDir) {
1425
+ const configFile = path.join(appRoot, "nitro.config.ts");
1426
+ if (!(await exists(configFile))) {
1427
+ return;
1428
+ }
1429
+ const deployConfig = await loadResuxDeployConfig(appRoot, outDir);
1430
+ const isStatic = deployConfig.target === "static";
1431
+ let source = await readFile(configFile, "utf8").catch(() => "");
1432
+ if (!source)
1433
+ return;
1434
+ let prerenderRoutes = [];
1435
+ if (isStatic) {
1436
+ const manifestPath = path.join(outDir, "manifest.json");
1437
+ const manifest = await readJsonRecord(manifestPath);
1438
+ if (manifest && Array.isArray(manifest.routes)) {
1439
+ for (const route of manifest.routes) {
1440
+ if (!route.params || route.params.length === 0) {
1441
+ const rpath = route.path;
1442
+ prerenderRoutes.push(rpath);
1443
+ if (rpath === "/") {
1444
+ prerenderRoutes.push("/__resux/route/payloads/index.json");
1445
+ }
1446
+ else {
1447
+ prerenderRoutes.push("/__resux/route/payloads" + rpath.replace(/\/$/, "") + ".json");
1448
+ }
1449
+ }
1450
+ }
1451
+ }
1452
+ }
1453
+ let updated = source;
1454
+ const prerenderBlockRegex = /prerender\s*:\s*\{[\s\S]*?\}/m;
1455
+ const newPrerenderBlock = `prerender: {
1456
+ crawlLinks: ${isStatic ? "true" : "false"},
1457
+ routes: ${JSON.stringify(prerenderRoutes, null, 2)}
1458
+ }`;
1459
+ if (prerenderBlockRegex.test(updated)) {
1460
+ updated = updated.replace(prerenderBlockRegex, newPrerenderBlock);
1461
+ }
1462
+ else {
1463
+ updated = updated.replace(/export\s+default\s+defineNitroConfig\s*\(\s*\{/, `export default defineNitroConfig({\n ${newPrerenderBlock},`);
1464
+ }
1465
+ if (updated !== source) {
1466
+ await writeFile(configFile, updated, "utf8");
1467
+ console.log(`Updated nitro.config.ts with ${prerenderRoutes.length} prerender routes for static target.`);
507
1468
  }
508
1469
  }
509
- async function ensureNitroBuildFiles(appRoot) {
510
- if (!(await exists(path.join(appRoot, "nitro.config.ts")))) {
511
- await writeDeploymentFile(appRoot, "nitro.config.ts", createNitroConfig(), false);
1470
+ async function upgradeNitroConfigForResux(configFile) {
1471
+ let source;
1472
+ try {
1473
+ source = await readFile(configFile, "utf8");
512
1474
  }
513
- if (!(await exists(path.join(appRoot, ".resux-nitro", "handler.ts")))) {
514
- await writeDeploymentFile(appRoot, ".resux-nitro/handler.ts", createNitroHandler(), false);
1475
+ catch {
1476
+ return;
1477
+ }
1478
+ let updated = source;
1479
+ const resuxClientAssetBlock = /dir:\s*["']\.resux\/client["']\s*,\s*\n\s*baseURL:\s*["']\/__resux["']\s*\n\s*\}/m;
1480
+ const match = updated.match(resuxClientAssetBlock);
1481
+ if (match && !match[0].includes("fallthrough")) {
1482
+ updated = updated.replace(resuxClientAssetBlock, match[0].replace(/\n\s*\}$/, ",\n fallthrough: true\n }"));
1483
+ }
1484
+ if (!updated.includes('"/__resux/image"') &&
1485
+ updated.includes('"/api/**":')) {
1486
+ updated = updated.replace(/(\s+)\"\/api\/\*\*\":\s*\{/, ` "/__resux/image": {\n headers: {\n "cache-control": "public, max-age=31536000, immutable"\n }\n },\n$1"/api/**": {`);
1487
+ }
1488
+ if (updated === source) {
1489
+ return;
515
1490
  }
1491
+ await writeFile(configFile, updated, "utf8");
1492
+ console.log("Updated nitro.config.ts with Resux compatibility defaults.");
516
1493
  }
517
- async function runNitroBuild(appRoot, outDir) {
1494
+ async function runNitroBuild(appRoot, outDir, buildOptions) {
1495
+ await buildOptions.hooks?.callHook("nitro:init", { appRoot });
518
1496
  const nitroPackageJson = require.resolve("nitropack/package.json");
519
1497
  const nitroCli = path.join(path.dirname(nitroPackageJson), "dist", "cli", "index.mjs");
520
1498
  const nitroEnv = { ...process.env };
521
1499
  const deployment = await resolveDeployment(appRoot, outDir, nitroEnv);
1500
+ await buildOptions.hooks?.callHook("nitro:config", {
1501
+ config: {
1502
+ target: deployment.target,
1503
+ nitroPreset: deployment.nitroPreset,
1504
+ },
1505
+ });
522
1506
  if (deployment.nitroPreset && !nitroEnv.NITRO_PRESET) {
523
1507
  nitroEnv.NITRO_PRESET = deployment.nitroPreset;
524
1508
  console.log(`Detected deploy target: ${deployment.target} (${deployment.reason})`);
525
1509
  console.log(`Detected Nitro preset: ${deployment.nitroPreset}`);
526
1510
  }
527
1511
  console.log(`Building Nitro output into ${deployment.outputLabel}`);
1512
+ await buildOptions.hooks?.callHook("nitro:build:before", {
1513
+ appRoot,
1514
+ preset: deployment.nitroPreset ?? undefined,
1515
+ });
528
1516
  await new Promise((resolve, reject) => {
529
1517
  const child = spawn(process.execPath, [nitroCli, "build"], {
530
1518
  cwd: appRoot,
@@ -548,6 +1536,20 @@ async function runNitroBuild(appRoot, outDir) {
548
1536
  nitroPreset: deployment.nitroPreset,
549
1537
  target: deployment.target,
550
1538
  });
1539
+ // Resux references app static files under /assets/* (from `@/assets/*` imports
1540
+ // and the `css` config), so mirror the app's assets/ dir into the built public
1541
+ // dir alongside public/ for production serving.
1542
+ const builtPublicDir = path.join(appRoot, ".output", "public");
1543
+ const appAssetsDir = path.join(appRoot, "assets");
1544
+ if ((await exists(appAssetsDir)) && (await exists(builtPublicDir))) {
1545
+ await cp(appAssetsDir, path.join(builtPublicDir, "assets"), {
1546
+ recursive: true,
1547
+ });
1548
+ }
1549
+ await buildOptions.hooks?.callHook("nitro:build:public-assets", {
1550
+ appRoot,
1551
+ publicDir: path.join(appRoot, ".output", "public"),
1552
+ });
551
1553
  }
552
1554
  async function assertDirectory(directory) {
553
1555
  const stats = await stat(directory);
@@ -566,225 +1568,233 @@ async function writeDeploymentFile(appRoot, relativePath, contents, force) {
566
1568
  }
567
1569
  function createDeploymentGuide(preset) {
568
1570
  const dockerSection = preset === "docker"
569
- ? `
570
- ## Docker
571
-
572
- \`\`\`sh
573
- docker build -t resux-app .
574
- docker run --rm -p 3000:3000 resux-app
575
- \`\`\`
1571
+ ? `
1572
+ ## Docker
1573
+
1574
+ \`\`\`sh
1575
+ docker build -t resux-app .
1576
+ docker run --rm -p 3000:3000 resux-app
1577
+ \`\`\`
576
1578
  `
577
1579
  : "";
578
1580
  const nitroSection = preset === "nitro"
579
- ? `
580
- ## Nitro
581
-
582
- Install the Nitro build dependencies:
583
-
584
- \`\`\`sh
585
- npm install -D nitropack h3
586
- \`\`\`
587
-
588
- Build Resux. The default production build creates both \`.resux\` and Nitro \`.output\`:
589
-
590
- \`\`\`sh
591
- npm run build
592
- node .output/server/index.mjs
593
- \`\`\`
594
-
595
- Nitro reads \`NITRO_PRESET\` for provider-specific output. For example:
596
-
597
- \`\`\`sh
598
- NITRO_PRESET=vercel npx nitro build
599
- \`\`\`
600
-
601
- The generated Nitro handler wraps the Resux Node request handler. \`resux build\` runs Nitro from the project root so \`.output\` can be started with Node.
1581
+ ? `
1582
+ ## Nitro
1583
+
1584
+ Install the Nitro build dependencies:
1585
+
1586
+ \`\`\`sh
1587
+ npm install -D nitropack h3
1588
+ \`\`\`
1589
+
1590
+ Build Resux. The default production build creates both \`.resux\` and Nitro \`.output\`:
1591
+
1592
+ \`\`\`sh
1593
+ npm run build
1594
+ node .output/server/index.mjs
1595
+ \`\`\`
1596
+
1597
+ Nitro reads \`NITRO_PRESET\` for provider-specific output. For example:
1598
+
1599
+ \`\`\`sh
1600
+ NITRO_PRESET=vercel npx nitro build
1601
+ \`\`\`
1602
+
1603
+ The generated Nitro handler wraps the Resux Node request handler. \`resux build\` runs Nitro from the project root so \`.output\` can be started with Node.
602
1604
  `
603
1605
  : "";
604
- return `# Deployment
605
-
606
- ## Node Server
607
-
608
- \`\`\`sh
609
- npm install
610
- npm run build
611
- npm run start
612
- \`\`\`
613
-
614
- The production server reads \`PORT\`, so most Node hosts can run the same start command:
615
-
616
- \`\`\`sh
617
- PORT=3000 npm run start
618
- \`\`\`
619
-
620
- Health checks can call:
621
-
622
- \`\`\`txt
623
- /__resux/health
624
- \`\`\`
625
- ${dockerSection}
626
- ${nitroSection}
627
- ## Diagnostics
628
-
629
- \`\`\`sh
630
- npm run inspect
631
- npm run inspect -- --json
632
- \`\`\`
633
-
634
- Production serving enables Resux default security headers. Disable them only when a host or reverse proxy owns those headers:
635
-
636
- \`\`\`sh
637
- resux start . --no-security-headers
638
- \`\`\`
1606
+ return `# Deployment
1607
+
1608
+ ## Node Server
1609
+
1610
+ \`\`\`sh
1611
+ npm install
1612
+ npm run build
1613
+ npm run start
1614
+ \`\`\`
1615
+
1616
+ The production server reads \`PORT\`, so most Node hosts can run the same start command:
1617
+
1618
+ \`\`\`sh
1619
+ PORT=3000 npm run start
1620
+ \`\`\`
1621
+
1622
+ Health checks can call:
1623
+
1624
+ \`\`\`txt
1625
+ /__resux/health
1626
+ \`\`\`
1627
+ ${dockerSection}
1628
+ ${nitroSection}
1629
+ ## Diagnostics
1630
+
1631
+ \`\`\`sh
1632
+ npm run inspect
1633
+ npm run inspect -- --json
1634
+ \`\`\`
1635
+
1636
+ Production serving enables Resux default security headers. Disable them only when a host or reverse proxy owns those headers:
1637
+
1638
+ \`\`\`sh
1639
+ resux start . --no-security-headers
1640
+ \`\`\`
639
1641
  `;
640
1642
  }
641
1643
  function createNitroConfig() {
642
- return `import { defineNitroConfig } from "nitropack/config";
643
-
644
- export default defineNitroConfig({
645
- compatibilityDate: "2026-05-02",
646
- // Resux uses top-level /plugins, /modules, and /middleware for app features.
647
- // Nitro auto-scans these folders too, so exclude them from Nitro scanning.
648
- ignore: ["plugins/**", "modules/**", "middleware/**"],
649
- // Keep Nitro discovery scoped to the generated adapter directory.
650
- scanDirs: [".resux-nitro"],
651
- publicAssets: [
652
- {
653
- dir: "public",
654
- baseURL: "/"
655
- },
656
- {
657
- dir: ".resux/client",
658
- baseURL: "/__resux"
659
- }
660
- ],
661
- serverAssets: [
662
- {
663
- baseName: "resux",
664
- dir: ".resux/server"
665
- }
666
- ],
667
- handlers: [
668
- {
669
- route: "/**",
670
- handler: "./.resux-nitro/handler.ts"
671
- }
672
- ],
673
- routeRules: {
674
- "/__resux/route": {
675
- headers: {
676
- "cache-control": "no-store"
677
- }
678
- },
679
- "/__resux/dev-events": {
680
- headers: {
681
- "cache-control": "no-store"
682
- }
683
- },
684
- "/__resux/handlers/**": {
685
- headers: {
686
- "cache-control": "public, max-age=31536000, immutable"
687
- }
688
- },
689
- "/__resux/plugins/**": {
690
- headers: {
691
- "cache-control": "public, max-age=31536000, immutable"
692
- }
693
- },
694
- "/__resux/middleware/**": {
695
- headers: {
696
- "cache-control": "public, max-age=31536000, immutable"
697
- }
698
- },
699
- "/__resux/vue-islands/**": {
700
- headers: {
701
- "cache-control": "public, max-age=31536000, immutable"
702
- }
703
- },
704
- "/__resux/runtime-client.mjs": {
705
- headers: {
706
- "cache-control": "public, max-age=31536000, immutable"
707
- }
708
- },
709
- "/__resux/image": {
710
- headers: {
711
- "cache-control": "public, max-age=31536000, immutable"
712
- }
713
- },
714
- "/api/**": {
715
- headers: {
716
- "cache-control": "no-store"
717
- }
718
- },
719
- "/**": {
720
- headers: {
721
- "cache-control": "no-store"
722
- }
723
- }
724
- },
725
- prerender: {
726
- crawlLinks: false,
727
- routes: []
728
- }
729
- });
1644
+ return `import { defineNitroConfig } from "nitropack/config";
1645
+
1646
+ export default defineNitroConfig({
1647
+ srcDir: ".resux-nitro",
1648
+ compatibilityDate: "2026-05-02",
1649
+ // Resux uses top-level /plugins, /modules, and /middleware for app features.
1650
+ // Nitro auto-scans these folders too, so exclude them from Nitro scanning.
1651
+ ignore: ["plugins/**", "modules/**", "middleware/**", "assets/**"],
1652
+ // Keep Nitro discovery scoped to the generated adapter directory.
1653
+ scanDirs: ["."],
1654
+ publicAssets: [
1655
+ {
1656
+ dir: "../public",
1657
+ baseURL: "/"
1658
+ },
1659
+ {
1660
+ dir: "../.resux/client",
1661
+ baseURL: "/__resux",
1662
+ fallthrough: true
1663
+ }
1664
+ ],
1665
+ serverAssets: [
1666
+ {
1667
+ baseName: "resux",
1668
+ dir: "../.resux/server"
1669
+ }
1670
+ ],
1671
+ handlers: [
1672
+ {
1673
+ route: "/**",
1674
+ handler: "./.resux-nitro/handler.ts"
1675
+ }
1676
+ ],
1677
+ routeRules: {
1678
+ "/__resux/route": {
1679
+ headers: {
1680
+ "cache-control": "no-store"
1681
+ }
1682
+ },
1683
+ "/__resux/dev-events": {
1684
+ headers: {
1685
+ "cache-control": "no-store"
1686
+ }
1687
+ },
1688
+ "/__resux/handlers/**": {
1689
+ headers: {
1690
+ "cache-control": "public, max-age=31536000, immutable"
1691
+ }
1692
+ },
1693
+ "/__resux/plugins/**": {
1694
+ headers: {
1695
+ "cache-control": "public, max-age=31536000, immutable"
1696
+ }
1697
+ },
1698
+ "/__resux/middleware/**": {
1699
+ headers: {
1700
+ "cache-control": "public, max-age=31536000, immutable"
1701
+ }
1702
+ },
1703
+ "/__resux/vue-islands/**": {
1704
+ headers: {
1705
+ "cache-control": "public, max-age=31536000, immutable"
1706
+ }
1707
+ },
1708
+ "/__resux/runtime-client.mjs": {
1709
+ headers: {
1710
+ "cache-control": "public, max-age=31536000, immutable"
1711
+ }
1712
+ },
1713
+ "/__resux/client-enhancements.mjs": {
1714
+ headers: {
1715
+ "cache-control": "public, max-age=31536000, immutable"
1716
+ }
1717
+ },
1718
+ "/__resux/image": {
1719
+ headers: {
1720
+ "cache-control": "public, max-age=31536000, immutable"
1721
+ }
1722
+ },
1723
+ "/api/**": {
1724
+ headers: {
1725
+ "cache-control": "no-store"
1726
+ }
1727
+ },
1728
+ "/**": {
1729
+ headers: {
1730
+ "cache-control": "no-store"
1731
+ }
1732
+ }
1733
+ },
1734
+ prerender: {
1735
+ crawlLinks: false,
1736
+ routes: []
1737
+ }
1738
+ });
730
1739
  `;
731
1740
  }
732
1741
  function createNitroHandler() {
733
- return `import { fromNodeMiddleware } from "h3";
734
- import { createResuxNodeHandler } from "resuxjs/node";
735
-
736
- const resuxHandler = createResuxNodeHandler();
737
-
738
- export default fromNodeMiddleware((req, res, next) => {
739
- resuxHandler(req, res);
740
-
741
- if (res.writableEnded) {
742
- return;
743
- }
744
-
745
- const done = () => {
746
- res.off("finish", done);
747
- res.off("close", done);
748
- next();
749
- };
750
-
751
- res.once("finish", done);
752
- res.once("close", done);
753
- });
1742
+ return `import { fromNodeMiddleware } from "h3";
1743
+ import { createResuxNodeHandler } from "resuxjs/node";
1744
+
1745
+ const resuxHandler = createResuxNodeHandler();
1746
+
1747
+ export default fromNodeMiddleware((req, res, next) => {
1748
+ resuxHandler(req, res);
1749
+
1750
+ if (res.writableEnded) {
1751
+ return;
1752
+ }
1753
+
1754
+ const done = () => {
1755
+ res.off("finish", done);
1756
+ res.off("close", done);
1757
+ next();
1758
+ };
1759
+
1760
+ res.once("finish", done);
1761
+ res.once("close", done);
1762
+ });
754
1763
  `;
755
1764
  }
756
1765
  function createDockerfile() {
757
- return `FROM node:24-alpine AS build
758
- WORKDIR /app
759
- COPY package*.json ./
760
- RUN npm install
761
- COPY . .
762
- RUN npm run build
763
- RUN npm prune --omit=dev
764
-
765
- FROM node:24-alpine AS runner
766
- WORKDIR /app
767
- ENV NODE_ENV=production
768
- ENV PORT=3000
769
- COPY --from=build /app /app
770
- EXPOSE 3000
771
- CMD ["npm", "run", "start"]
1766
+ return `FROM node:24-alpine AS build
1767
+ WORKDIR /app
1768
+ COPY package*.json ./
1769
+ RUN npm install
1770
+ COPY . .
1771
+ RUN npm run build
1772
+ RUN npm prune --omit=dev
1773
+
1774
+ FROM node:24-alpine AS runner
1775
+ WORKDIR /app
1776
+ ENV NODE_ENV=production
1777
+ ENV PORT=3000
1778
+ COPY --from=build /app /app
1779
+ EXPOSE 3000
1780
+ CMD ["npm", "run", "start"]
772
1781
  `;
773
1782
  }
774
1783
  function createDockerignore() {
775
- return `node_modules
776
- .resux
777
- dist
778
- .git
779
- *.log
780
- .env
781
- .env.*
1784
+ return `node_modules
1785
+ .resux
1786
+ dist
1787
+ .git
1788
+ *.log
1789
+ .env
1790
+ .env.*
782
1791
  `;
783
1792
  }
784
- async function startViteDevServer(outDir) {
1793
+ async function startViteDevServer(outDir, buildOptions, cliOptions) {
1794
+ const appRoot = path.dirname(outDir);
785
1795
  const [{ createServer: createViteServer }, { default: vuePlugin }] = await Promise.all([import("vite"), import("@vitejs/plugin-vue")]);
786
1796
  const hmrPort = 30000 + Math.floor(Math.random() * 20000);
787
- const vite = await createViteServer({
1797
+ const viteConfig = {
788
1798
  root: path.join(outDir, "vite-client"),
789
1799
  configFile: false,
790
1800
  publicDir: false,
@@ -796,18 +1806,28 @@ async function startViteDevServer(outDir) {
796
1806
  alias: {
797
1807
  "/__resux/runtime-client.mjs": path.join(outDir, "vite-client", "runtime-client.mjs"),
798
1808
  vue: require.resolve("vue"),
1809
+ "@": normalizePath(appRoot),
1810
+ "~": normalizePath(appRoot)
799
1811
  },
800
1812
  },
801
1813
  server: {
802
1814
  middlewareMode: true,
1815
+ host: cliOptions.host,
1816
+ https: cliOptions.https ? {} : false,
803
1817
  hmr: {
804
1818
  port: hmrPort,
805
1819
  },
806
1820
  watch: {
807
- ignored: ["**/.resux/**", "**/node_modules/**"],
1821
+ ignored: ["**/.resux/**", "**/node_modules/**", "**/.nitro/**", "**/.resux-nitro/**"],
808
1822
  },
809
1823
  },
1824
+ };
1825
+ await buildOptions.hooks?.callHook("vite:extendConfig", {
1826
+ config: viteConfig,
1827
+ dev: true,
810
1828
  });
1829
+ const vite = await createViteServer(viteConfig);
1830
+ await buildOptions.hooks?.callHook("vite:serverCreated", { server: vite });
811
1831
  console.log("Vite dev middleware ready for Resux client modules.");
812
1832
  return vite;
813
1833
  }
@@ -818,13 +1838,16 @@ function startDevWatcher(vite, appRoot, outDir, buildOptions) {
818
1838
  return;
819
1839
  }
820
1840
  devBuildDirty = true;
1841
+ buildOptions.changedPath = changedPath;
821
1842
  void ensureDevBuild(appRoot, outDir, buildOptions, vite)
822
1843
  .then((rebuilt) => {
823
1844
  if (rebuilt) {
1845
+ void buildOptions.hooks?.callHook("dev:reload", { appRoot, changedPath });
824
1846
  notifyDevReloadClients("reload");
825
1847
  }
826
1848
  })
827
1849
  .catch((error) => {
1850
+ void buildOptions.hooks?.callHook("dev:error", { appRoot, error });
828
1851
  console.error(error instanceof Error ? (error.stack ?? error.message) : error);
829
1852
  });
830
1853
  };
@@ -852,7 +1875,13 @@ function startDevWatcher(vite, appRoot, outDir, buildOptions) {
852
1875
  }
853
1876
  function shouldSkipDevWatch(changedPath, appRoot, outDir) {
854
1877
  const resolved = path.resolve(changedPath);
1878
+ const generatedMediaRoot = path.resolve(appRoot, "public", "_resux", "generated", "images");
1879
+ const nitroDir = path.resolve(appRoot, ".nitro");
1880
+ const resuxNitroDir = path.resolve(appRoot, ".resux-nitro");
855
1881
  return (resolved.startsWith(path.resolve(outDir)) ||
1882
+ resolved.startsWith(nitroDir) ||
1883
+ resolved.startsWith(resuxNitroDir) ||
1884
+ resolved.startsWith(generatedMediaRoot) ||
856
1885
  resolved.includes(`${path.sep}node_modules${path.sep}`) ||
857
1886
  resolved.includes(`${path.sep}dist${path.sep}`) ||
858
1887
  !resolved.startsWith(path.resolve(appRoot)));
@@ -897,7 +1926,12 @@ async function startServer(options) {
897
1926
  if (boundPort !== options.port) {
898
1927
  console.log(`Port ${options.port} is busy, using ${boundPort} instead.`);
899
1928
  }
900
- console.log(`Resux ${options.dev ? "dev" : "preview"} server running at http://${options.host ?? "localhost"}:${boundPort}`);
1929
+ const protocol = options.https ? "https" : "http";
1930
+ const url = `${protocol}://${options.host ?? "localhost"}:${boundPort}`;
1931
+ console.log(`Resux ${options.dev ? "dev" : "preview"} server running at ${url}`);
1932
+ if (options.open) {
1933
+ openInBrowser(url);
1934
+ }
901
1935
  }
902
1936
  async function listenOnAvailablePort(server, requestedPort, host) {
903
1937
  const maxAttempts = 20;
@@ -933,6 +1967,18 @@ function listen(server, portToTry, host) {
933
1967
  function isAddressInUse(error) {
934
1968
  return (error instanceof Error && "code" in error && error.code === "EADDRINUSE");
935
1969
  }
1970
+ function openInBrowser(url) {
1971
+ const command = process.platform === "win32"
1972
+ ? { file: "cmd", args: ["/c", "start", "", url] }
1973
+ : process.platform === "darwin"
1974
+ ? { file: "open", args: [url] }
1975
+ : { file: "xdg-open", args: [url] };
1976
+ const child = spawn(command.file, command.args, {
1977
+ stdio: "ignore",
1978
+ detached: true,
1979
+ });
1980
+ child.unref();
1981
+ }
936
1982
  function requestOriginFromHeaders(request) {
937
1983
  const forwardedProto = firstHeaderValue(request.headers["x-forwarded-proto"]);
938
1984
  const forwardedHost = firstHeaderValue(request.headers["x-forwarded-host"]);
@@ -959,39 +2005,50 @@ function readPort(value, fallback) {
959
2005
  return parsed;
960
2006
  }
961
2007
  function printHelp() {
962
- console.log(`resux ${version}
963
-
964
- Usage:
965
- resux dev [app-root] [options]
966
- resux init [project-dir] [options]
967
- resux build [app-root] [options]
968
- resux compile [app-root] [options]
969
- resux preview [app-root] [options]
970
- resux start [app-root] [options]
971
- resux inspect [app-root] [options]
972
- resux deploy [app-root] [options]
973
-
974
- Commands:
975
- init Scaffold a new Resux app
976
- dev Start the Resux dev server with Vite middleware
977
- build Build server/client output into .resux and Nitro .output
978
- compile Build only the lower-level .resux output
979
- preview Serve the built app, rebuilding when needed
980
- start Alias for preview, intended for production Node servers
981
- inspect Print a build manifest summary for debugging
982
- deploy Generate Node, Docker, or Nitro deployment files
983
-
984
- Options:
985
- --security-headers Enable default production security headers
986
- --no-security-headers
987
- Disable default production security headers
988
- --json Print JSON output for inspect
989
- --preset <preset> Deployment preset for deploy: node, docker, or nitro
990
- --force Overwrite existing deployment files
991
- -p, --port <port> Set the server port, default 3000 or PORT
992
- --host <host> Set the server host
993
- -v, --version Print the Resux version
994
- -h, --help Show this help message
2008
+ console.log(`resux ${version}
2009
+
2010
+ Usage:
2011
+ resux dev [app-root] [options]
2012
+ resux init [project-dir] [options]
2013
+ resux build [app-root] [options]
2014
+ resux compile [app-root] [options]
2015
+ resux prepare [app-root] [options]
2016
+ resux preview [app-root] [options]
2017
+ resux start [app-root] [options]
2018
+ resux inspect [app-root] [target] [options]
2019
+ resux check [app-root] [options]
2020
+ resux deploy [app-root] [options]
2021
+
2022
+ Commands:
2023
+ init Scaffold a new Resux app
2024
+ dev Start the Resux dev server with Vite middleware
2025
+ build Build server/client output into .resux and Nitro .output
2026
+ compile Build only the lower-level .resux output
2027
+ prepare Generate safe files, generated directories, manifests, and type stubs
2028
+ preview Serve the built app, rebuilding when needed
2029
+ start Alias for preview, intended for production Node servers
2030
+ inspect Print build/debug metadata (routes/plugins/enhancements/middleware/imports/components/build/images/server/packages/templates/bundles/seo)
2031
+ check Validate a Resux user project structure and build readiness
2032
+ deploy Generate Node, Docker, or Nitro deployment files
2033
+
2034
+ Options:
2035
+ --security-headers Enable default production security headers
2036
+ --no-security-headers
2037
+ Disable default production security headers
2038
+ --json Print JSON output for inspect
2039
+ --open Open the app in your default browser
2040
+ --https Emit HTTPS dev/preview URL (transport stays HTTP locally)
2041
+ --debug Print debug diagnostics
2042
+ --trace-resume Enable resumability tracing diagnostics
2043
+ --trace-routes Enable route trace diagnostics
2044
+ --trace-build Enable build trace diagnostics
2045
+ --preset <preset> Deployment preset for deploy: node, docker, or nitro
2046
+ --force Overwrite existing deployment files
2047
+ --fix Apply safe autofixes for check/dev/build/prepare missing files
2048
+ -p, --port <port> Set the server port, default 3000 or PORT
2049
+ --host <host> Set the server host
2050
+ -v, --version Print the Resux version
2051
+ -h, --help Show this help message
995
2052
  `);
996
2053
  }
997
2054
  async function handleRequest(request, response, options) {
@@ -1025,18 +2082,40 @@ async function handleRequest(request, response, options) {
1025
2082
  await serveHealthCheck(response, options);
1026
2083
  return;
1027
2084
  }
1028
- if (requestUrl.pathname === "/__resux/route") {
1029
- await serveRoutePayload(response, requestUrl, options, requestOrigin);
2085
+ if (requestUrl.pathname === "/__resux/route" || requestUrl.pathname.startsWith("/__resux/route/payloads/")) {
2086
+ let routePath = "";
2087
+ if (requestUrl.pathname === "/__resux/route") {
2088
+ routePath = requestUrl.searchParams.get("path") || "/";
2089
+ }
2090
+ else {
2091
+ const sub = requestUrl.pathname.slice("/__resux/route/payloads/".length);
2092
+ if (sub === "index.json") {
2093
+ routePath = "/";
2094
+ }
2095
+ else {
2096
+ routePath = "/" + sub.replace(/\.json$/, "");
2097
+ }
2098
+ }
2099
+ requestUrl.searchParams.set("path", routePath);
2100
+ await serveRoutePayload(request, response, requestUrl, options, requestOrigin);
1030
2101
  return;
1031
2102
  }
1032
2103
  if (requestUrl.pathname === "/__resux/image") {
1033
2104
  await serveResuxImage(request, response, requestUrl, requestOrigin);
1034
2105
  return;
1035
2106
  }
2107
+ if (requestUrl.pathname === "/__resux/video") {
2108
+ await serveResuxVideo(request, response, requestUrl, requestOrigin);
2109
+ return;
2110
+ }
1036
2111
  if (requestUrl.pathname.startsWith("/_resux/generated/images/")) {
1037
2112
  await serveGeneratedResuxImage(request, response, requestUrl, requestOrigin, options.appRoot);
1038
2113
  return;
1039
2114
  }
2115
+ if (requestUrl.pathname.startsWith("/_resux/generated/videos/")) {
2116
+ await serveGeneratedResuxVideo(request, response, requestUrl, requestOrigin, options.appRoot);
2117
+ return;
2118
+ }
1040
2119
  if (requestUrl.pathname.startsWith("/__resux/")) {
1041
2120
  if (activeDevBuild) {
1042
2121
  await activeDevBuild;
@@ -1044,7 +2123,7 @@ async function handleRequest(request, response, options) {
1044
2123
  if (options.dev &&
1045
2124
  options.vite &&
1046
2125
  resolveResuxViteAssetUrl(requestUrl.pathname)) {
1047
- await serveViteResuxAsset(response, options.vite, requestUrl.pathname);
2126
+ await serveViteResuxAsset(response, options.vite, requestUrl.pathname, options.outDir);
1048
2127
  return;
1049
2128
  }
1050
2129
  await serveResuxAsset(response, options.outDir, requestUrl.pathname);
@@ -1077,7 +2156,7 @@ async function handleRequest(request, response, options) {
1077
2156
  if (publicHandled) {
1078
2157
  return;
1079
2158
  }
1080
- const rendered = await renderRoute(requestUrl, options, manifest, requestOrigin);
2159
+ const rendered = await renderRoute(requestUrl, options, manifest, requestOrigin, request.headers["user-agent"]);
1081
2160
  if (!rendered) {
1082
2161
  await serveErrorDocument(response, options, manifest, 404, "Page not found");
1083
2162
  return;
@@ -1095,15 +2174,19 @@ async function handleRequest(request, response, options) {
1095
2174
  return;
1096
2175
  }
1097
2176
  const normalizedRendered = withPrioritizedHeadImagePreloads(rendered);
1098
- const html = promoteDocumentImagePreloads(renderDocument(normalizedRendered, "Resux App", {
2177
+ let html = promoteDocumentImagePreloads(renderDocument(normalizedRendered, "Resux App", {
1099
2178
  devReload: options.dev,
1100
2179
  }));
2180
+ if (options.dev && devHalalOverlayScript) {
2181
+ html = html.replace("</body>", `<script>${devHalalOverlayScript}</script></body>`);
2182
+ }
1101
2183
  response.writeHead(routeRule?.statusCode ?? 200, {
1102
2184
  "content-type": "text/html; charset=utf-8",
1103
2185
  });
1104
2186
  response.end(html);
1105
2187
  }
1106
2188
  catch (error) {
2189
+ console.error("Request failed:", error);
1107
2190
  if (response.writableEnded) {
1108
2191
  return;
1109
2192
  }
@@ -1234,7 +2317,7 @@ function createPlainErrorBody(error, dev) {
1234
2317
  }
1235
2318
  return error.message;
1236
2319
  }
1237
- async function serveRoutePayload(response, requestUrl, options, requestOrigin) {
2320
+ async function serveRoutePayload(request, response, requestUrl, options, requestOrigin) {
1238
2321
  const targetPath = requestUrl.searchParams.get("path");
1239
2322
  if (!targetPath || !targetPath.startsWith("/") || targetPath.startsWith("//")) {
1240
2323
  response.writeHead(400, {
@@ -1262,7 +2345,7 @@ async function serveRoutePayload(response, requestUrl, options, requestOrigin) {
1262
2345
  }));
1263
2346
  return;
1264
2347
  }
1265
- const rendered = await renderRoute(targetUrl, options, manifest, requestOrigin);
2348
+ const rendered = await renderRoute(targetUrl, options, manifest, requestOrigin, request.headers["user-agent"]);
1266
2349
  if (!rendered) {
1267
2350
  response.writeHead(404, {
1268
2351
  "content-type": "application/json; charset=utf-8",
@@ -1304,6 +2387,13 @@ const RESUX_IMAGE_SUPPORTED_FORMATS = new Set([
1304
2387
  ]);
1305
2388
  let sharpFactoryPromise = null;
1306
2389
  let sharpFactoryLoadError = null;
2390
+ const RESUX_VIDEO_SUPPORTED_FORMATS = new Set([
2391
+ "mp4",
2392
+ "webm",
2393
+ ]);
2394
+ let ffmpegBinaryPromise = null;
2395
+ let ffmpegBinaryLoadError = null;
2396
+ let ffmpegTransformLastError = null;
1307
2397
  function parseImageInteger(value, min, max) {
1308
2398
  if (!value) {
1309
2399
  return undefined;
@@ -1369,6 +2459,161 @@ function mimeTypeFromImageFormat(format) {
1369
2459
  }
1370
2460
  return `image/${format}`;
1371
2461
  }
2462
+ function normalizeVideoFormat(value) {
2463
+ if (!value) {
2464
+ return undefined;
2465
+ }
2466
+ const normalized = value.trim().toLowerCase();
2467
+ if (!normalized) {
2468
+ return undefined;
2469
+ }
2470
+ if (normalized === "video/mp4" || normalized === "mp4") {
2471
+ return "mp4";
2472
+ }
2473
+ if (normalized === "video/webm" || normalized === "webm") {
2474
+ return "webm";
2475
+ }
2476
+ return undefined;
2477
+ }
2478
+ function normalizeVideoQuality(value) {
2479
+ if (!value) {
2480
+ return undefined;
2481
+ }
2482
+ const normalized = value.trim().toLowerCase();
2483
+ if (!normalized) {
2484
+ return undefined;
2485
+ }
2486
+ const numeric = normalized.endsWith("p")
2487
+ ? normalized.slice(0, -1)
2488
+ : normalized;
2489
+ const parsed = Number.parseInt(numeric, 10);
2490
+ if (!Number.isFinite(parsed) || parsed <= 0) {
2491
+ return undefined;
2492
+ }
2493
+ return Math.max(144, Math.min(4320, Math.round(parsed)));
2494
+ }
2495
+ function inferVideoFormatFromSource(value) {
2496
+ if (!value) {
2497
+ return undefined;
2498
+ }
2499
+ const normalized = value.trim().toLowerCase().split(/[?#]/)[0] ?? "";
2500
+ if (!normalized) {
2501
+ return undefined;
2502
+ }
2503
+ if (normalized.endsWith(".mp4") || normalized.endsWith(".m4v")) {
2504
+ return "mp4";
2505
+ }
2506
+ if (normalized.endsWith(".webm")) {
2507
+ return "webm";
2508
+ }
2509
+ return undefined;
2510
+ }
2511
+ function mimeTypeFromVideoFormat(format) {
2512
+ if (format === "mp4") {
2513
+ return "video/mp4";
2514
+ }
2515
+ if (format === "webm") {
2516
+ return "video/webm";
2517
+ }
2518
+ return "application/octet-stream";
2519
+ }
2520
+ function shouldTransformVideo(options) {
2521
+ return Boolean(options.format || options.quality);
2522
+ }
2523
+ async function resolveFfmpegBinary() {
2524
+ if (ffmpegBinaryPromise) {
2525
+ return ffmpegBinaryPromise;
2526
+ }
2527
+ ffmpegBinaryPromise = (async () => {
2528
+ const explicitPath = process.env.RESUX_FFMPEG_PATH || process.env.FFMPEG_PATH;
2529
+ const candidates = explicitPath ? [explicitPath, "ffmpeg"] : ["ffmpeg"];
2530
+ for (const candidate of candidates) {
2531
+ const isReady = await new Promise((resolve) => {
2532
+ const child = spawn(candidate, ["-version"], {
2533
+ stdio: ["ignore", "ignore", "ignore"],
2534
+ });
2535
+ child.once("error", () => resolve(false));
2536
+ child.once("close", (code) => resolve(code === 0));
2537
+ });
2538
+ if (isReady) {
2539
+ ffmpegBinaryLoadError = null;
2540
+ return candidate;
2541
+ }
2542
+ }
2543
+ ffmpegBinaryLoadError =
2544
+ "Resux video transforms require ffmpeg in PATH or RESUX_FFMPEG_PATH.";
2545
+ return null;
2546
+ })();
2547
+ return ffmpegBinaryPromise;
2548
+ }
2549
+ function buildFfmpegVideoArgs(format, quality) {
2550
+ const args = [
2551
+ "-v",
2552
+ "error",
2553
+ "-i",
2554
+ "pipe:0",
2555
+ ];
2556
+ if (quality) {
2557
+ args.push("-vf", `scale=-2:${Math.round(quality)}`);
2558
+ }
2559
+ if (format === "webm") {
2560
+ args.push("-c:v", "libvpx-vp9", "-b:v", "0", "-crf", "33", "-c:a", "libopus", "-f", "webm");
2561
+ }
2562
+ else {
2563
+ args.push("-c:v", "libx264", "-preset", "veryfast", "-movflags", "+faststart+frag_keyframe+empty_moov", "-c:a", "aac", "-f", "mp4");
2564
+ }
2565
+ args.push("pipe:1");
2566
+ return args;
2567
+ }
2568
+ async function transformResuxVideo(source, sourceHint, options) {
2569
+ if (!shouldTransformVideo(options)) {
2570
+ return null;
2571
+ }
2572
+ const ffmpegBinary = await resolveFfmpegBinary();
2573
+ if (!ffmpegBinary) {
2574
+ return null;
2575
+ }
2576
+ const inputFormat = inferVideoFormatFromSource(sourceHint);
2577
+ const outputFormat = options.format ?? inputFormat ?? "mp4";
2578
+ if (!RESUX_VIDEO_SUPPORTED_FORMATS.has(outputFormat)) {
2579
+ ffmpegTransformLastError = `Unsupported output format "${outputFormat}".`;
2580
+ return null;
2581
+ }
2582
+ const args = buildFfmpegVideoArgs(outputFormat, options.quality);
2583
+ const transformed = await new Promise((resolve) => {
2584
+ const child = spawn(ffmpegBinary, args, {
2585
+ stdio: ["pipe", "pipe", "pipe"],
2586
+ });
2587
+ const stdoutChunks = [];
2588
+ const stderrChunks = [];
2589
+ child.stdout.on("data", (chunk) => {
2590
+ stdoutChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
2591
+ });
2592
+ child.stderr.on("data", (chunk) => {
2593
+ stderrChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
2594
+ });
2595
+ child.once("error", () => {
2596
+ resolve(null);
2597
+ });
2598
+ child.once("close", (code) => {
2599
+ if (code === 0) {
2600
+ resolve(Buffer.concat(stdoutChunks));
2601
+ return;
2602
+ }
2603
+ const stderr = Buffer.concat(stderrChunks).toString("utf8").trim();
2604
+ ffmpegTransformLastError = stderr || `ffmpeg exited with code ${code ?? -1}.`;
2605
+ resolve(null);
2606
+ });
2607
+ child.stdin.end(source);
2608
+ });
2609
+ if (!transformed || transformed.length === 0) {
2610
+ return null;
2611
+ }
2612
+ return {
2613
+ buffer: transformed,
2614
+ contentType: mimeTypeFromVideoFormat(outputFormat),
2615
+ };
2616
+ }
1372
2617
  function shouldTransformImage(options) {
1373
2618
  return Boolean(options.width
1374
2619
  || options.height
@@ -1615,6 +2860,22 @@ function createGeneratedImageRoutePath(source, originalSource, format, options)
1615
2860
  const digest = hashImageSignature(signature);
1616
2861
  return `/_resux/generated/images/${digest}.${extension}`;
1617
2862
  }
2863
+ function createVideoTransformSignature(source, format, quality) {
2864
+ const entries = [`src=${source}`];
2865
+ if (format) {
2866
+ entries.push(`f=${format}`);
2867
+ }
2868
+ if (Number.isFinite(quality) && quality > 0) {
2869
+ entries.push(`q=${Math.round(quality)}`);
2870
+ }
2871
+ return entries.join("&");
2872
+ }
2873
+ function createGeneratedVideoRoutePath(source, format, quality) {
2874
+ const extension = format ?? inferVideoFormatFromSource(source) ?? "mp4";
2875
+ const signature = createVideoTransformSignature(source, format, quality);
2876
+ const digest = hashImageSignature(signature);
2877
+ return `/_resux/generated/videos/${digest}.${extension}`;
2878
+ }
1618
2879
  function resolveGeneratedImageDiskPath(appRoot, pathname) {
1619
2880
  const publicRoot = path.resolve(appRoot, "public");
1620
2881
  const generatedRoot = path.resolve(publicRoot, "_resux", "generated", "images");
@@ -1634,6 +2895,25 @@ function resolveGeneratedImageDiskPath(appRoot, pathname) {
1634
2895
  relativePath: decodedPath,
1635
2896
  };
1636
2897
  }
2898
+ function resolveGeneratedVideoDiskPath(appRoot, pathname) {
2899
+ const publicRoot = path.resolve(appRoot, "public");
2900
+ const generatedRoot = path.resolve(publicRoot, "_resux", "generated", "videos");
2901
+ let decodedPath;
2902
+ try {
2903
+ decodedPath = decodeURIComponent(pathname);
2904
+ }
2905
+ catch {
2906
+ return null;
2907
+ }
2908
+ const resolved = path.resolve(publicRoot, `.${decodedPath}`);
2909
+ if (!resolved.startsWith(generatedRoot)) {
2910
+ return null;
2911
+ }
2912
+ return {
2913
+ filePath: resolved,
2914
+ relativePath: decodedPath,
2915
+ };
2916
+ }
1637
2917
  async function readGeneratedImageMetadata(metadataPath) {
1638
2918
  if (!(await exists(metadataPath))) {
1639
2919
  return null;
@@ -1649,6 +2929,21 @@ async function readGeneratedImageMetadata(metadataPath) {
1649
2929
  return null;
1650
2930
  }
1651
2931
  }
2932
+ async function readGeneratedVideoMetadata(metadataPath) {
2933
+ if (!(await exists(metadataPath))) {
2934
+ return null;
2935
+ }
2936
+ try {
2937
+ const payload = JSON.parse(await readFile(metadataPath, "utf8"));
2938
+ if (!payload || payload.version !== 1) {
2939
+ return null;
2940
+ }
2941
+ return payload;
2942
+ }
2943
+ catch {
2944
+ return null;
2945
+ }
2946
+ }
1652
2947
  function generatedImageMetadataValid(metadata, key, now, sourceInfo) {
1653
2948
  if (!metadata || metadata.version !== 1) {
1654
2949
  return false;
@@ -1669,6 +2964,26 @@ function generatedImageMetadataValid(metadata, key, now, sourceInfo) {
1669
2964
  }
1670
2965
  return true;
1671
2966
  }
2967
+ function generatedVideoMetadataValid(metadata, key, now, sourceInfo) {
2968
+ if (!metadata || metadata.version !== 1) {
2969
+ return false;
2970
+ }
2971
+ if (metadata.key !== key) {
2972
+ return false;
2973
+ }
2974
+ if (!Number.isFinite(metadata.expiresAt) || metadata.expiresAt <= now) {
2975
+ return false;
2976
+ }
2977
+ if (sourceInfo) {
2978
+ if (metadata.sourceMtimeMs !== sourceInfo.mtimeMs) {
2979
+ return false;
2980
+ }
2981
+ if (metadata.sourceSize !== sourceInfo.size) {
2982
+ return false;
2983
+ }
2984
+ }
2985
+ return true;
2986
+ }
1672
2987
  async function resolveLocalSourceFileInfo(sourceUrl, requestOrigin, appRoot) {
1673
2988
  const sameOrigin = sourceUrl.origin === requestOrigin;
1674
2989
  if (!sameOrigin || !sourceUrl.pathname.startsWith("/")) {
@@ -1693,12 +3008,104 @@ async function resolveLocalSourceFileInfo(sourceUrl, requestOrigin, appRoot) {
1693
3008
  if (!sourceStats.isFile()) {
1694
3009
  return null;
1695
3010
  }
1696
- return {
1697
- mtimeMs: sourceStats.mtimeMs,
1698
- size: sourceStats.size,
1699
- };
3011
+ return {
3012
+ mtimeMs: sourceStats.mtimeMs,
3013
+ size: sourceStats.size,
3014
+ };
3015
+ }
3016
+ async function serveResuxImage(request, response, requestUrl, requestOrigin) {
3017
+ const method = request.method ?? "GET";
3018
+ if (method !== "GET" && method !== "HEAD") {
3019
+ response.writeHead(405, {
3020
+ "content-type": "text/plain; charset=utf-8",
3021
+ allow: "GET, HEAD",
3022
+ });
3023
+ response.end("Method Not Allowed");
3024
+ return;
3025
+ }
3026
+ const sourceParam = requestUrl.searchParams.get("src")
3027
+ ?? requestUrl.searchParams.get("url")
3028
+ ?? "";
3029
+ const originalSourceParam = requestUrl.searchParams.get("original") ?? "";
3030
+ const sourceCandidate = originalSourceParam.trim() || sourceParam;
3031
+ const sourceUrl = resolveResuxImageSource(sourceCandidate, requestOrigin);
3032
+ if (!sourceUrl) {
3033
+ response.writeHead(400, {
3034
+ "content-type": "application/json; charset=utf-8",
3035
+ });
3036
+ response.end(JSON.stringify({
3037
+ error: 'Image requests require "src" (or "url") with an absolute path or http(s) URL.',
3038
+ }));
3039
+ return;
3040
+ }
3041
+ const options = {
3042
+ width: parseImageInteger(requestUrl.searchParams.get("w"), 1, 8192)
3043
+ ?? parseImageInteger(requestUrl.searchParams.get("width"), 1, 8192),
3044
+ height: parseImageInteger(requestUrl.searchParams.get("h"), 1, 8192)
3045
+ ?? parseImageInteger(requestUrl.searchParams.get("height"), 1, 8192),
3046
+ quality: parseImageInteger(requestUrl.searchParams.get("q"), 1, 100)
3047
+ ?? parseImageInteger(requestUrl.searchParams.get("quality"), 1, 100),
3048
+ format: normalizeImageFormat(requestUrl.searchParams.get("f"))
3049
+ ?? normalizeImageFormat(requestUrl.searchParams.get("format")),
3050
+ fit: normalizeImageFit(requestUrl.searchParams.get("fit"))
3051
+ ?? normalizeImageFit(requestUrl.searchParams.get("mode")),
3052
+ extraModifiers: parseImageExtraModifiers(requestUrl.searchParams),
3053
+ };
3054
+ const forwardedAccept = firstHeaderValue(request.headers.accept);
3055
+ const upstream = await fetch(sourceUrl, {
3056
+ headers: forwardedAccept ? { accept: forwardedAccept } : undefined,
3057
+ redirect: "follow",
3058
+ }).catch(() => null);
3059
+ if (!upstream) {
3060
+ response.writeHead(502, {
3061
+ "content-type": "application/json; charset=utf-8",
3062
+ "cache-control": "no-store",
3063
+ });
3064
+ response.end(JSON.stringify({ error: "Failed to fetch image source." }));
3065
+ return;
3066
+ }
3067
+ if (!upstream.ok) {
3068
+ response.writeHead(upstream.status, {
3069
+ "content-type": "application/json; charset=utf-8",
3070
+ "cache-control": "no-store",
3071
+ });
3072
+ response.end(JSON.stringify({
3073
+ error: `Image source request failed with status ${upstream.status}.`,
3074
+ }));
3075
+ return;
3076
+ }
3077
+ const sourceBuffer = Buffer.from(await upstream.arrayBuffer());
3078
+ const sourceContentType = upstream.headers.get("content-type");
3079
+ const needsTransform = shouldTransformImage(options);
3080
+ const transformed = await transformResuxImage(sourceBuffer, sourceContentType, options);
3081
+ if (needsTransform && !transformed) {
3082
+ response.writeHead(501, {
3083
+ "content-type": "application/json; charset=utf-8",
3084
+ "cache-control": "no-store",
3085
+ });
3086
+ response.end(JSON.stringify({
3087
+ error: sharpFactoryLoadError
3088
+ ?? "Image transform failed. Verify source format and requested modifiers.",
3089
+ }));
3090
+ return;
3091
+ }
3092
+ const body = transformed?.buffer ?? sourceBuffer;
3093
+ const contentType = transformed?.contentType ?? sourceContentType ?? "application/octet-stream";
3094
+ const cacheControl = shouldTransformImage(options)
3095
+ ? "public, max-age=31536000, immutable"
3096
+ : "public, max-age=86400";
3097
+ response.writeHead(200, {
3098
+ "content-type": contentType,
3099
+ "cache-control": cacheControl,
3100
+ vary: "Accept",
3101
+ });
3102
+ if (method === "HEAD") {
3103
+ response.end();
3104
+ return;
3105
+ }
3106
+ response.end(body);
1700
3107
  }
1701
- async function serveResuxImage(request, response, requestUrl, requestOrigin) {
3108
+ async function serveGeneratedResuxImage(request, response, requestUrl, requestOrigin, appRoot) {
1702
3109
  const method = request.method ?? "GET";
1703
3110
  if (method !== "GET" && method !== "HEAD") {
1704
3111
  response.writeHead(405, {
@@ -1708,18 +3115,52 @@ async function serveResuxImage(request, response, requestUrl, requestOrigin) {
1708
3115
  response.end("Method Not Allowed");
1709
3116
  return;
1710
3117
  }
3118
+ const resolvedDiskPath = resolveGeneratedImageDiskPath(appRoot, requestUrl.pathname);
3119
+ if (!resolvedDiskPath) {
3120
+ response.writeHead(404, {
3121
+ "content-type": "text/plain; charset=utf-8",
3122
+ "cache-control": "no-store",
3123
+ });
3124
+ response.end("Not found");
3125
+ return;
3126
+ }
3127
+ const { filePath, relativePath } = resolvedDiskPath;
3128
+ const metadataPath = `${filePath}.meta.json`;
1711
3129
  const sourceParam = requestUrl.searchParams.get("src")
1712
3130
  ?? requestUrl.searchParams.get("url")
1713
3131
  ?? "";
1714
3132
  const originalSourceParam = requestUrl.searchParams.get("original") ?? "";
1715
3133
  const sourceCandidate = originalSourceParam.trim() || sourceParam;
3134
+ const cacheRaw = requestUrl.searchParams.get("cache") ?? requestUrl.searchParams.get("c");
3135
+ const cacheMaxAgeSeconds = parseImageCacheMaxAgeSeconds(cacheRaw);
3136
+ if (!sourceCandidate) {
3137
+ if (!(await exists(filePath))) {
3138
+ response.writeHead(404, {
3139
+ "content-type": "text/plain; charset=utf-8",
3140
+ "cache-control": "no-store",
3141
+ });
3142
+ response.end("Not found");
3143
+ return;
3144
+ }
3145
+ response.writeHead(200, {
3146
+ "content-type": mimeType(filePath),
3147
+ "cache-control": "public, max-age=86400",
3148
+ });
3149
+ if (method === "HEAD") {
3150
+ response.end();
3151
+ return;
3152
+ }
3153
+ response.end(await readFile(filePath));
3154
+ return;
3155
+ }
1716
3156
  const sourceUrl = resolveResuxImageSource(sourceCandidate, requestOrigin);
1717
3157
  if (!sourceUrl) {
1718
3158
  response.writeHead(400, {
1719
3159
  "content-type": "application/json; charset=utf-8",
3160
+ "cache-control": "no-store",
1720
3161
  });
1721
3162
  response.end(JSON.stringify({
1722
- error: 'Image requests require "src" (or "url") with an absolute path or http(s) URL.',
3163
+ error: 'Generated image requests require "src" (or "url") with an absolute path or http(s) URL.',
1723
3164
  }));
1724
3165
  return;
1725
3166
  }
@@ -1736,6 +3177,36 @@ async function serveResuxImage(request, response, requestUrl, requestOrigin) {
1736
3177
  ?? normalizeImageFit(requestUrl.searchParams.get("mode")),
1737
3178
  extraModifiers: parseImageExtraModifiers(requestUrl.searchParams),
1738
3179
  };
3180
+ const generatedRoutePath = createGeneratedImageRoutePath(sourceParam, originalSourceParam || undefined, options.format, options);
3181
+ if (generatedRoutePath !== relativePath) {
3182
+ response.writeHead(404, {
3183
+ "content-type": "application/json; charset=utf-8",
3184
+ "cache-control": "no-store",
3185
+ });
3186
+ response.end(JSON.stringify({ error: "Generated image URL is not valid for the provided transform." }));
3187
+ return;
3188
+ }
3189
+ const sourceInfo = await resolveLocalSourceFileInfo(sourceUrl, requestOrigin, appRoot);
3190
+ const cacheKey = hashImageSignature(createImageTransformSignature(sourceParam, originalSourceParam || undefined, options.format, options));
3191
+ const now = Date.now();
3192
+ const metadata = await readGeneratedImageMetadata(metadataPath);
3193
+ if (cacheMaxAgeSeconds
3194
+ && (await exists(filePath))
3195
+ && metadata
3196
+ && generatedImageMetadataValid(metadata, cacheKey, now, sourceInfo)) {
3197
+ const remaining = Math.max(1, Math.floor((metadata.expiresAt - now) / 1000));
3198
+ response.writeHead(200, {
3199
+ "content-type": mimeType(filePath),
3200
+ "cache-control": `public, max-age=${remaining}`,
3201
+ "x-resux-cache": "hit",
3202
+ });
3203
+ if (method === "HEAD") {
3204
+ response.end();
3205
+ return;
3206
+ }
3207
+ response.end(await readFile(filePath));
3208
+ return;
3209
+ }
1739
3210
  const forwardedAccept = firstHeaderValue(request.headers.accept);
1740
3211
  const upstream = await fetch(sourceUrl, {
1741
3212
  headers: forwardedAccept ? { accept: forwardedAccept } : undefined,
@@ -1776,7 +3247,123 @@ async function serveResuxImage(request, response, requestUrl, requestOrigin) {
1776
3247
  }
1777
3248
  const body = transformed?.buffer ?? sourceBuffer;
1778
3249
  const contentType = transformed?.contentType ?? sourceContentType ?? "application/octet-stream";
1779
- const cacheControl = shouldTransformImage(options)
3250
+ const expiresAt = cacheMaxAgeSeconds
3251
+ ? now + (cacheMaxAgeSeconds * 1000)
3252
+ : now;
3253
+ const responseMaxAge = cacheMaxAgeSeconds
3254
+ ? Math.max(1, Math.floor((expiresAt - now) / 1000))
3255
+ : 0;
3256
+ if (cacheMaxAgeSeconds) {
3257
+ await mkdir(path.dirname(filePath), { recursive: true });
3258
+ await writeFile(filePath, body);
3259
+ const metadataPayload = {
3260
+ version: 1,
3261
+ key: cacheKey,
3262
+ createdAt: now,
3263
+ expiresAt,
3264
+ originalSource: sourceCandidate,
3265
+ generatedPath: relativePath,
3266
+ transform: {
3267
+ ...(options.width ? { width: options.width } : {}),
3268
+ ...(options.height ? { height: options.height } : {}),
3269
+ ...(options.quality ? { quality: options.quality } : {}),
3270
+ ...(options.format ? { format: options.format } : {}),
3271
+ ...(options.fit ? { fit: options.fit } : {}),
3272
+ ...(options.extraModifiers && Object.keys(options.extraModifiers).length > 0
3273
+ ? { modifiers: options.extraModifiers }
3274
+ : {}),
3275
+ },
3276
+ ...(sourceInfo ? { sourceMtimeMs: sourceInfo.mtimeMs, sourceSize: sourceInfo.size } : {}),
3277
+ };
3278
+ await writeFile(metadataPath, `${JSON.stringify(metadataPayload, null, 2)}\n`, "utf8");
3279
+ }
3280
+ response.writeHead(200, {
3281
+ "content-type": contentType,
3282
+ "cache-control": cacheMaxAgeSeconds
3283
+ ? `public, max-age=${responseMaxAge}`
3284
+ : "no-store",
3285
+ "x-resux-cache": cacheMaxAgeSeconds ? "miss" : "bypass",
3286
+ vary: "Accept",
3287
+ });
3288
+ if (method === "HEAD") {
3289
+ response.end();
3290
+ return;
3291
+ }
3292
+ response.end(body);
3293
+ }
3294
+ async function serveResuxVideo(request, response, requestUrl, requestOrigin) {
3295
+ const method = request.method ?? "GET";
3296
+ if (method !== "GET" && method !== "HEAD") {
3297
+ response.writeHead(405, {
3298
+ "content-type": "text/plain; charset=utf-8",
3299
+ allow: "GET, HEAD",
3300
+ });
3301
+ response.end("Method Not Allowed");
3302
+ return;
3303
+ }
3304
+ const sourceParam = requestUrl.searchParams.get("src")
3305
+ ?? requestUrl.searchParams.get("url")
3306
+ ?? "";
3307
+ const sourceUrl = resolveResuxImageSource(sourceParam, requestOrigin);
3308
+ if (!sourceUrl) {
3309
+ response.writeHead(400, {
3310
+ "content-type": "application/json; charset=utf-8",
3311
+ });
3312
+ response.end(JSON.stringify({
3313
+ error: 'Video requests require "src" (or "url") with an absolute path or http(s) URL.',
3314
+ }));
3315
+ return;
3316
+ }
3317
+ const options = {
3318
+ format: normalizeVideoFormat(requestUrl.searchParams.get("f"))
3319
+ ?? normalizeVideoFormat(requestUrl.searchParams.get("format")),
3320
+ quality: normalizeVideoQuality(requestUrl.searchParams.get("q"))
3321
+ ?? normalizeVideoQuality(requestUrl.searchParams.get("quality")),
3322
+ };
3323
+ const forwardedAccept = firstHeaderValue(request.headers.accept);
3324
+ const upstream = await fetch(sourceUrl, {
3325
+ headers: forwardedAccept ? { accept: forwardedAccept } : undefined,
3326
+ redirect: "follow",
3327
+ }).catch(() => null);
3328
+ if (!upstream) {
3329
+ response.writeHead(502, {
3330
+ "content-type": "application/json; charset=utf-8",
3331
+ "cache-control": "no-store",
3332
+ });
3333
+ response.end(JSON.stringify({ error: "Failed to fetch video source." }));
3334
+ return;
3335
+ }
3336
+ if (!upstream.ok) {
3337
+ response.writeHead(upstream.status, {
3338
+ "content-type": "application/json; charset=utf-8",
3339
+ "cache-control": "no-store",
3340
+ });
3341
+ response.end(JSON.stringify({
3342
+ error: `Video source request failed with status ${upstream.status}.`,
3343
+ }));
3344
+ return;
3345
+ }
3346
+ const sourceBuffer = Buffer.from(await upstream.arrayBuffer());
3347
+ const sourceContentType = upstream.headers.get("content-type");
3348
+ const needsTransform = shouldTransformVideo(options);
3349
+ const transformed = await transformResuxVideo(sourceBuffer, sourceParam || sourceUrl.pathname, options);
3350
+ if (needsTransform && !transformed) {
3351
+ response.writeHead(501, {
3352
+ "content-type": "application/json; charset=utf-8",
3353
+ "cache-control": "no-store",
3354
+ });
3355
+ response.end(JSON.stringify({
3356
+ error: ffmpegBinaryLoadError
3357
+ ?? ffmpegTransformLastError
3358
+ ?? "Video transform failed. Verify ffmpeg availability and requested options.",
3359
+ }));
3360
+ return;
3361
+ }
3362
+ const body = transformed?.buffer ?? sourceBuffer;
3363
+ const contentType = transformed?.contentType
3364
+ ?? sourceContentType
3365
+ ?? mimeTypeFromVideoFormat(inferVideoFormatFromSource(sourceParam || sourceUrl.pathname) ?? "mp4");
3366
+ const cacheControl = needsTransform
1780
3367
  ? "public, max-age=31536000, immutable"
1781
3368
  : "public, max-age=86400";
1782
3369
  response.writeHead(200, {
@@ -1790,7 +3377,7 @@ async function serveResuxImage(request, response, requestUrl, requestOrigin) {
1790
3377
  }
1791
3378
  response.end(body);
1792
3379
  }
1793
- async function serveGeneratedResuxImage(request, response, requestUrl, requestOrigin, appRoot) {
3380
+ async function serveGeneratedResuxVideo(request, response, requestUrl, requestOrigin, appRoot) {
1794
3381
  const method = request.method ?? "GET";
1795
3382
  if (method !== "GET" && method !== "HEAD") {
1796
3383
  response.writeHead(405, {
@@ -1800,7 +3387,7 @@ async function serveGeneratedResuxImage(request, response, requestUrl, requestOr
1800
3387
  response.end("Method Not Allowed");
1801
3388
  return;
1802
3389
  }
1803
- const resolvedDiskPath = resolveGeneratedImageDiskPath(appRoot, requestUrl.pathname);
3390
+ const resolvedDiskPath = resolveGeneratedVideoDiskPath(appRoot, requestUrl.pathname);
1804
3391
  if (!resolvedDiskPath) {
1805
3392
  response.writeHead(404, {
1806
3393
  "content-type": "text/plain; charset=utf-8",
@@ -1814,8 +3401,7 @@ async function serveGeneratedResuxImage(request, response, requestUrl, requestOr
1814
3401
  const sourceParam = requestUrl.searchParams.get("src")
1815
3402
  ?? requestUrl.searchParams.get("url")
1816
3403
  ?? "";
1817
- const originalSourceParam = requestUrl.searchParams.get("original") ?? "";
1818
- const sourceCandidate = originalSourceParam.trim() || sourceParam;
3404
+ const sourceCandidate = sourceParam.trim();
1819
3405
  const cacheRaw = requestUrl.searchParams.get("cache") ?? requestUrl.searchParams.get("c");
1820
3406
  const cacheMaxAgeSeconds = parseImageCacheMaxAgeSeconds(cacheRaw);
1821
3407
  if (!sourceCandidate) {
@@ -1845,40 +3431,33 @@ async function serveGeneratedResuxImage(request, response, requestUrl, requestOr
1845
3431
  "cache-control": "no-store",
1846
3432
  });
1847
3433
  response.end(JSON.stringify({
1848
- error: 'Generated image requests require "src" (or "url") with an absolute path or http(s) URL.',
3434
+ error: 'Generated video requests require "src" (or "url") with an absolute path or http(s) URL.',
1849
3435
  }));
1850
3436
  return;
1851
3437
  }
1852
3438
  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),
3439
+ format: normalizeVideoFormat(requestUrl.searchParams.get("f"))
3440
+ ?? normalizeVideoFormat(requestUrl.searchParams.get("format")),
3441
+ quality: normalizeVideoQuality(requestUrl.searchParams.get("q"))
3442
+ ?? normalizeVideoQuality(requestUrl.searchParams.get("quality")),
1864
3443
  };
1865
- const generatedRoutePath = createGeneratedImageRoutePath(sourceParam, originalSourceParam || undefined, options.format, options);
3444
+ const generatedRoutePath = createGeneratedVideoRoutePath(sourceParam, options.format, options.quality);
1866
3445
  if (generatedRoutePath !== relativePath) {
1867
3446
  response.writeHead(404, {
1868
3447
  "content-type": "application/json; charset=utf-8",
1869
3448
  "cache-control": "no-store",
1870
3449
  });
1871
- response.end(JSON.stringify({ error: "Generated image URL is not valid for the provided transform." }));
3450
+ response.end(JSON.stringify({ error: "Generated video URL is not valid for the provided transform." }));
1872
3451
  return;
1873
3452
  }
1874
3453
  const sourceInfo = await resolveLocalSourceFileInfo(sourceUrl, requestOrigin, appRoot);
1875
- const cacheKey = hashImageSignature(createImageTransformSignature(sourceParam, originalSourceParam || undefined, options.format, options));
3454
+ const cacheKey = hashImageSignature(createVideoTransformSignature(sourceParam, options.format, options.quality));
1876
3455
  const now = Date.now();
1877
- const metadata = await readGeneratedImageMetadata(metadataPath);
3456
+ const metadata = await readGeneratedVideoMetadata(metadataPath);
1878
3457
  if (cacheMaxAgeSeconds
1879
3458
  && (await exists(filePath))
1880
3459
  && metadata
1881
- && generatedImageMetadataValid(metadata, cacheKey, now, sourceInfo)) {
3460
+ && generatedVideoMetadataValid(metadata, cacheKey, now, sourceInfo)) {
1882
3461
  const remaining = Math.max(1, Math.floor((metadata.expiresAt - now) / 1000));
1883
3462
  response.writeHead(200, {
1884
3463
  "content-type": mimeType(filePath),
@@ -1902,7 +3481,7 @@ async function serveGeneratedResuxImage(request, response, requestUrl, requestOr
1902
3481
  "content-type": "application/json; charset=utf-8",
1903
3482
  "cache-control": "no-store",
1904
3483
  });
1905
- response.end(JSON.stringify({ error: "Failed to fetch image source." }));
3484
+ response.end(JSON.stringify({ error: "Failed to fetch video source." }));
1906
3485
  return;
1907
3486
  }
1908
3487
  if (!upstream.ok) {
@@ -1911,27 +3490,30 @@ async function serveGeneratedResuxImage(request, response, requestUrl, requestOr
1911
3490
  "cache-control": "no-store",
1912
3491
  });
1913
3492
  response.end(JSON.stringify({
1914
- error: `Image source request failed with status ${upstream.status}.`,
3493
+ error: `Video source request failed with status ${upstream.status}.`,
1915
3494
  }));
1916
3495
  return;
1917
3496
  }
1918
3497
  const sourceBuffer = Buffer.from(await upstream.arrayBuffer());
1919
3498
  const sourceContentType = upstream.headers.get("content-type");
1920
- const needsTransform = shouldTransformImage(options);
1921
- const transformed = await transformResuxImage(sourceBuffer, sourceContentType, options);
3499
+ const needsTransform = shouldTransformVideo(options);
3500
+ const transformed = await transformResuxVideo(sourceBuffer, sourceParam || sourceUrl.pathname, options);
1922
3501
  if (needsTransform && !transformed) {
1923
3502
  response.writeHead(501, {
1924
3503
  "content-type": "application/json; charset=utf-8",
1925
3504
  "cache-control": "no-store",
1926
3505
  });
1927
3506
  response.end(JSON.stringify({
1928
- error: sharpFactoryLoadError
1929
- ?? "Image transform failed. Verify source format and requested modifiers.",
3507
+ error: ffmpegBinaryLoadError
3508
+ ?? ffmpegTransformLastError
3509
+ ?? "Video transform failed. Verify ffmpeg availability and requested options.",
1930
3510
  }));
1931
3511
  return;
1932
3512
  }
1933
3513
  const body = transformed?.buffer ?? sourceBuffer;
1934
- const contentType = transformed?.contentType ?? sourceContentType ?? "application/octet-stream";
3514
+ const contentType = transformed?.contentType
3515
+ ?? sourceContentType
3516
+ ?? mimeTypeFromVideoFormat(options.format ?? inferVideoFormatFromSource(sourceParam) ?? "mp4");
1935
3517
  const expiresAt = cacheMaxAgeSeconds
1936
3518
  ? now + (cacheMaxAgeSeconds * 1000)
1937
3519
  : now;
@@ -1949,14 +3531,8 @@ async function serveGeneratedResuxImage(request, response, requestUrl, requestOr
1949
3531
  originalSource: sourceCandidate,
1950
3532
  generatedPath: relativePath,
1951
3533
  transform: {
1952
- ...(options.width ? { width: options.width } : {}),
1953
- ...(options.height ? { height: options.height } : {}),
1954
- ...(options.quality ? { quality: options.quality } : {}),
1955
3534
  ...(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
- : {}),
3535
+ ...(options.quality ? { quality: options.quality } : {}),
1960
3536
  },
1961
3537
  ...(sourceInfo ? { sourceMtimeMs: sourceInfo.mtimeMs, sourceSize: sourceInfo.size } : {}),
1962
3538
  };
@@ -1991,7 +3567,7 @@ function setHeaderIfUnset(response, name, value) {
1991
3567
  response.setHeader(name, value);
1992
3568
  }
1993
3569
  }
1994
- async function renderRoute(requestUrl, options, loadedManifest, requestOrigin) {
3570
+ async function renderRoute(requestUrl, options, loadedManifest, requestOrigin, userAgent) {
1995
3571
  if (options.dev && !loadedManifest) {
1996
3572
  await ensureDevBuild(options.appRoot, options.outDir, options.buildOptions, options.vite);
1997
3573
  }
@@ -2005,6 +3581,7 @@ async function renderRoute(requestUrl, options, loadedManifest, requestOrigin) {
2005
3581
  params: matched.params,
2006
3582
  query: readQuery(requestUrl),
2007
3583
  origin: requestOrigin ?? requestUrl.origin,
3584
+ userAgent,
2008
3585
  };
2009
3586
  const middlewareResult = await runRouteMiddleware(manifest, routeContext, matched.route.meta);
2010
3587
  if (middlewareResult) {
@@ -2347,25 +3924,37 @@ function isServerAbortResult(value) {
2347
3924
  }
2348
3925
  async function servePublicFile(response, appRoot, pathname) {
2349
3926
  const publicRoot = path.resolve(appRoot, "public");
2350
- const resolved = path.resolve(publicRoot, `.${decodeURIComponent(pathname)}`);
2351
- if (!resolved.startsWith(publicRoot)) {
2352
- return false;
2353
- }
2354
- if (!(await exists(resolved))) {
2355
- return false;
2356
- }
2357
- const fileStats = await stat(resolved);
2358
- if (!fileStats.isFile()) {
2359
- return false;
3927
+ const candidates = [
3928
+ { base: publicRoot, boundary: publicRoot },
3929
+ ];
3930
+ // Resux compiles `@/assets/*` imports (and the `css` config) to `/assets/*`
3931
+ // URLs, so also serve the app's assets/ directory as a static root. The
3932
+ // boundary check keeps this scoped to assets/ and blocks path traversal.
3933
+ if (pathname === "/assets" || pathname.startsWith("/assets/")) {
3934
+ candidates.push({ base: appRoot, boundary: path.resolve(appRoot, "assets") });
3935
+ }
3936
+ for (const { base, boundary } of candidates) {
3937
+ const resolved = path.resolve(base, `.${decodeURIComponent(pathname)}`);
3938
+ if (!resolved.startsWith(boundary)) {
3939
+ continue;
3940
+ }
3941
+ if (!(await exists(resolved))) {
3942
+ continue;
3943
+ }
3944
+ const fileStats = await stat(resolved);
3945
+ if (!fileStats.isFile()) {
3946
+ continue;
3947
+ }
3948
+ response.writeHead(200, {
3949
+ "content-type": mimeType(resolved),
3950
+ ...(!response.hasHeader("cache-control")
3951
+ ? { "cache-control": "no-store" }
3952
+ : {}),
3953
+ });
3954
+ response.end(await readFile(resolved));
3955
+ return true;
2360
3956
  }
2361
- response.writeHead(200, {
2362
- "content-type": mimeType(resolved),
2363
- ...(!response.hasHeader("cache-control")
2364
- ? { "cache-control": "no-store" }
2365
- : {}),
2366
- });
2367
- response.end(await readFile(resolved));
2368
- return true;
3957
+ return false;
2369
3958
  }
2370
3959
  function mimeType(file) {
2371
3960
  const ext = path.extname(file).toLowerCase();
@@ -2444,7 +4033,31 @@ function notifyDevReloadClients(eventName = "hmr") {
2444
4033
  }
2445
4034
  }
2446
4035
  }
2447
- async function serveViteResuxAsset(response, vite, pathname) {
4036
+ async function serveViteResuxAsset(response, vite, pathname, outDir) {
4037
+ if (pathname === "/__resux/runtime-client.mjs") {
4038
+ const source = `export * from "/runtime-client.mjs";\nimport "/runtime-client.mjs";\n`;
4039
+ response.writeHead(200, {
4040
+ "content-type": "text/javascript; charset=utf-8",
4041
+ "cache-control": "no-store",
4042
+ });
4043
+ response.end(source);
4044
+ return;
4045
+ }
4046
+ if (pathname === "/__resux/client-enhancements.mjs") {
4047
+ const manifestFile = path.join(outDir, "vite-client", "client-enhancements.mjs");
4048
+ if (!(await exists(manifestFile))) {
4049
+ response.writeHead(404);
4050
+ response.end("Not found");
4051
+ return;
4052
+ }
4053
+ const source = await readFile(manifestFile, "utf8");
4054
+ response.writeHead(200, {
4055
+ "content-type": "text/javascript; charset=utf-8",
4056
+ "cache-control": "no-store",
4057
+ });
4058
+ response.end(source);
4059
+ return;
4060
+ }
2448
4061
  const viteUrl = resolveResuxViteAssetUrl(pathname);
2449
4062
  if (!viteUrl) {
2450
4063
  response.writeHead(404);
@@ -2506,20 +4119,27 @@ async function serveResuxAsset(response, outDir, pathname) {
2506
4119
  return;
2507
4120
  }
2508
4121
  if (!(await exists(resolved))) {
4122
+ if (process.env.RESUX_TRACE_BUILD === "1") {
4123
+ console.warn(`[resux:trace-build] asset missing for ${pathname} resolved to ${resolved}`);
4124
+ }
2509
4125
  response.writeHead(404);
2510
4126
  response.end("Not found");
2511
4127
  return;
2512
4128
  }
4129
+ const fileContents = await readFile(resolved);
2513
4130
  response.writeHead(200, {
2514
4131
  "content-type": mimeType(resolved),
2515
4132
  "cache-control": "no-store",
2516
4133
  });
2517
- response.end(await readFile(resolved, "utf8"));
4134
+ response.end(fileContents);
2518
4135
  }
2519
4136
  function resolveResuxAssetPath(pathname) {
2520
4137
  if (pathname === "/__resux/runtime-client.mjs") {
2521
4138
  return "client/runtime-client.mjs";
2522
4139
  }
4140
+ if (pathname === "/__resux/client-enhancements.mjs") {
4141
+ return "client/client-enhancements.mjs";
4142
+ }
2523
4143
  if (pathname.startsWith("/__resux/plugins/")) {
2524
4144
  return pathname.replace(/^\/__resux\/plugins\//, "client/plugins/");
2525
4145
  }
@@ -2532,12 +4152,21 @@ function resolveResuxAssetPath(pathname) {
2532
4152
  if (pathname.startsWith("/__resux/vue-islands/")) {
2533
4153
  return pathname.replace(/^\/__resux\/vue-islands\//, "client/vue-islands/");
2534
4154
  }
4155
+ if (pathname.startsWith("/__resux/chunks/")) {
4156
+ return pathname.replace(/^\/__resux\/chunks\//, "client/chunks/");
4157
+ }
4158
+ if (pathname.startsWith("/__resux/assets/")) {
4159
+ return pathname.replace(/^\/__resux\/assets\//, "client/assets/");
4160
+ }
2535
4161
  return null;
2536
4162
  }
2537
4163
  function resolveResuxViteAssetUrl(pathname) {
2538
4164
  if (pathname === "/__resux/runtime-client.mjs") {
2539
4165
  return "/runtime-client.mjs";
2540
4166
  }
4167
+ if (pathname === "/__resux/client-enhancements.mjs") {
4168
+ return "/client-enhancements.mjs";
4169
+ }
2541
4170
  if (pathname.startsWith("/__resux/plugins/")) {
2542
4171
  return pathname.replace(/^\/__resux\/plugins\//, "/plugins/");
2543
4172
  }
@@ -2550,6 +4179,12 @@ function resolveResuxViteAssetUrl(pathname) {
2550
4179
  if (pathname.startsWith("/__resux/vue-islands/")) {
2551
4180
  return pathname.replace(/^\/__resux\/vue-islands\//, "/vue-islands/");
2552
4181
  }
4182
+ if (pathname.startsWith("/__resux/chunks/")) {
4183
+ return pathname.replace(/^\/__resux\/chunks\//, "/chunks/");
4184
+ }
4185
+ if (pathname.startsWith("/__resux/assets/")) {
4186
+ return pathname.replace(/^\/__resux\/assets\//, "/assets/");
4187
+ }
2553
4188
  return null;
2554
4189
  }
2555
4190
  function isViteInternalRequest(pathname) {