Skip to content

feat: redesgin lading page - #12

Merged
abdelkabirouadoukou merged 11 commits into
mainfrom
redesign-landing-page
Jul 31, 2026
Merged

abdelkabirouadoukou merged 11 commits into
mainfrom
redesign-landing-page

Conversation

@abdelkabirouadoukou

@abdelkabirouadoukou abdelkabirouadoukou commented Jul 31, 2026 •

Copy link
Copy Markdown
Member
  • Replaced Google Fonts with Oswald and Inter for improved typography.
  • Updated CSS variables for a refreshed color palette and design.
  • Introduced new animations for elements like dashed lines and pin drops.
  • Adjusted global styles for better responsiveness and aesthetics.

feat: enhance x.config.ts with image proxy configuration

  • Added remote image proxy settings to allow fetching images from specified hosts.
  • Implemented security headers to manage content security policy for external resources.

feat: implement image proxy handler

  • Created a minimal remote-image proxy to fetch and serve images from allow-listed hosts.
  • Ensured compliance with content security policies by preventing cross-origin requests.

feat: add route resolver and route rush components

  • Developed RouteResolver component to confirm server-side route resolution.
  • Created RouteRush component for an interactive quiz on route-file mapping.

feat: introduce Ship It component for build timing

  • Added Ship It component to measure and display build times with local storage for best times.
  • Implemented user feedback for build performance.

fix: optimize response handling in security headers and logging

  • Improved response handling to avoid unnecessary re-wrapping of streams.
  • Enhanced logging for request and security header applications.

Summary by CodeRabbit

  • New Features
    • Added interactive route tools, deployment simulation, and framework-themed arcade games.
    • Added command-palette navigation, Konami-code easter egg, and Stardance branding.
    • Added secure remote image loading with approved-host allowlisting and caching.
    • Improved client-side navigation, prefetching, route handling, and production static serving.
  • Visual Updates
    • Refreshed the landing page with a light drafting-paper theme, updated typography, animations, and styling.
  • Documentation
    • Added guides for client navigation, remote images, error overlays, and custom 404 handling.
  • Reliability
    • Improved streaming connections, request identification, security headers, response logging, and deployment support.

- Replaced Google Fonts with Oswald and Inter for improved typography.
- Updated CSS variables for a refreshed color palette and design.
- Introduced new animations for elements like dashed lines and pin drops.
- Adjusted global styles for better responsiveness and aesthetics.

feat: enhance x.config.ts with image proxy configuration

- Added remote image proxy settings to allow fetching images from specified hosts.
- Implemented security headers to manage content security policy for external resources.

feat: implement image proxy handler

- Created a minimal remote-image proxy to fetch and serve images from allow-listed hosts.
- Ensured compliance with content security policies by preventing cross-origin requests.

feat: add route resolver and route rush components

- Developed RouteResolver component to confirm server-side route resolution.
- Created RouteRush component for an interactive quiz on route-file mapping.

feat: introduce Ship It component for build timing

- Added Ship It component to measure and display build times with local storage for best times.
- Implemented user feedback for build performance.

fix: optimize response handling in security headers and logging

- Improved response handling to avoid unnecessary re-wrapping of streams.
- Enhanced logging for request and security header applications.
@vercel

vercel Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
thexjs-basic Error Error Jul 31, 2026 4:07pm
x Ready Ready Preview Jul 31, 2026 4:07pm

@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The PR redesigns the landing site with route tools, arcade games, new branding, and documentation. It adds an allow-listed remote image proxy, layout-aware island bundles, static build serving, improved reload SSE handling, and in-place response header updates.

Changes

Landing experience

Layer / File(s) Summary
Route resolution and interactive experiences
examples/landing/src/actions/resolve.ts, examples/landing/src/components/route-resolver.tsx, examples/landing/src/components/route-rush.tsx, examples/landing/src/components/ship-it.tsx
The site adds route classification, server confirmation, a route quiz, and a timed build simulation.
Arcade page and games
examples/landing/src/components/leak-check.tsx, examples/landing/src/components/mode-call.tsx, examples/landing/src/pages/play.tsx
The static /play page presents interactive games with scoring, timers, feedback, and replay controls.
Landing composition and visual system
examples/landing/src/pages/index.tsx, examples/landing/src/pages/features.tsx, examples/landing/src/layouts/main.tsx, examples/landing/src/styles/globals.css, examples/landing/src/components/*
The landing site adds shared branding, command-palette and easter-egg controls, new navigation, feature entries, attribution, typography, colors, and animations.

Remote image proxy and runtime

Layer / File(s) Summary
Image proxy implementation
packages/core/src/images/proxy.ts, packages/core/src/index.ts
The public image proxy validates requests, hostnames, upstream responses, and image content before returning cached image responses.
Application and adapter integration
examples/landing/x.config.ts, packages/cli/src/index.ts, packages/core/src/createApp.ts, packages/adapter-vercel/src/*
Image settings flow through CLI detection, core request handling, Vercel manifests, and generated Vercel configuration.

Core runtime behavior

Layer / File(s) Summary
Layout-aware island bundles
packages/core/src/build.ts, packages/core/src/createApp.ts, packages/core/src/island-bundle.ts
Island hydration entries and bundles include layout paths and resolve islands from route and layout registries.
Static serving and project loading
packages/cli/src/index.ts
The CLI resolves core modules from the project directory and serves static client builds with URL decoding, traversal protection, file serving, and SPA fallback.
Request lifecycle and response handling
packages/core/src/createApp.ts, packages/core/src/observability/logger.ts, packages/core/src/security/headers.ts
Reload SSE connections use heartbeats and abort cleanup. Logging and security processing mutate existing response headers while preserving response bodies.

Documentation and package updates

Layer / File(s) Summary
Client navigation and image documentation
README.md, examples/landing/src/pages/docs/*, examples/landing/src/x-routes.ts
Documentation and typed routes describe client navigation, prefetching, typed links, image proxy configuration, error overlays, custom 404 handling, and the new pages.
Data exports and consumers
packages/core/package.json, packages/core/src/data/sqlite.ts, examples/*/src/lib/auth.ts, packages/create-thexjs-app/templates/*
The core package publishes a data entry point. SQLite loading becomes runtime-specific. Examples and templates use the new subpath.
Template and release updates
packages/create-thexjs-app/src/index.ts, packages/create-thexjs-app/templates/*, packages/*/package.json, examples/landing/package.json
Generated templates add button types and label associations. Template lookup handles missing entries. Package versions and the landing start script are updated.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Visitor
  participant RouteResolver
  participant resolveRoute
  Visitor->>RouteResolver: enter a source path
  RouteResolver->>RouteResolver: resolvePath locally
  Visitor->>RouteResolver: request server confirmation
  RouteResolver->>resolveRoute: submit rawPath
  resolveRoute-->>RouteResolver: return route classification and timestamp
  RouteResolver-->>Visitor: display resolution results
Loading
sequenceDiagram
  participant Browser
  participant createApp
  participant createImageProxyHandler
  participant RemoteHost
  Browser->>createApp: request /_x/image with remote url
  createApp->>createImageProxyHandler: handle image request
  createImageProxyHandler->>RemoteHost: fetch allow-listed URL
  RemoteHost-->>createImageProxyHandler: return image response
  createImageProxyHandler-->>Browser: stream image with cache headers
Loading

Possibly related PRs

  • abdelkabirouadoukou/x#1: Both changes modify island hydration and build infrastructure.
  • abdelkabirouadoukou/x#6: Both changes modify the Vercel adapter, preloaded route handling, scratch directories, and image configuration.
  • abdelkabirouadoukou/x#7: Both changes modify core application configuration, request logging, and response-header handling.
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Title check ⚠️ Warning The title 'feat: redesgin lading page' contains a typo ('redesgin' instead of 'redesign' and 'lading' instead of 'landing') and does not accurately represent the comprehensive scope of changes, which include image proxy, security headers, server functions, and multiple new components across core and adapter packages. Correct the typos and broaden the title to reflect the primary changes. Consider: 'feat: redesign landing page, add image proxy, and improve security headers' or similar.
Docstring Coverage ⚠️ Warning Docstring coverage is 14.12% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Fix failing CI checks
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch redesign-landing-page

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 9

🧹 Nitpick comments (2)
examples/landing/src/actions/resolve.ts (1)

10-42: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the shared route-classification logic instead of duplicating it in two files. resolveRoute in examples/landing/src/actions/resolve.ts and resolvePath in examples/landing/src/components/route-resolver.tsx implement the same trimming, isApi detection, extension stripping, _layout/_middleware/_404 checks, and dynamic/catch-all segment conversion. Both also contain the same dead check (if (!route.startsWith("/")) route = "/" + route;), which never runs since route always starts with "/" by construction.

  • examples/landing/src/actions/resolve.ts#L10-L42: move this parsing logic into a shared module (e.g. examples/landing/src/lib/route-classifier.ts) and import it here; drop the dead leading-slash check.
  • examples/landing/src/components/route-resolver.tsx#L27-L56: import the same shared module for resolvePath instead of reimplementing the algorithm; drop the matching dead check at line 53.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/landing/src/actions/resolve.ts` around lines 10 - 42, Extract the
shared route parsing and classification algorithm from resolveRoute into a
shared route-classifier module, preserving trimming, API detection, extension
removal, special-file handling, and dynamic segment conversion; remove the dead
leading-slash check. In examples/landing/src/actions/resolve.ts#L10-L42, import
and use the shared classifier. In
examples/landing/src/components/route-resolver.tsx#L27-L56, replace
resolvePath’s duplicated implementation with the same shared module and remove
its matching dead check.
packages/core/src/images/proxy.ts (1)

60-68: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Cancel the upstream body on early-return error paths.

When upstream.ok is false or the content type is rejected, the handler returns an error response without consuming or cancelling upstream.body. Under sustained load, this can leave underlying connections open longer than necessary. Call upstream.body?.cancel() before returning in both branches.

♻️ Proposed fix
     if (!upstream.ok) {
+      await upstream.body?.cancel();
       return new Response("upstream error", { status: 502 });
     }

     const contentType = upstream.headers.get("content-type") ?? "";
     const baseContentType = (contentType.split(";")[0] ?? "").trim();
     if (!ALLOWED_CONTENT_TYPES.has(baseContentType)) {
+      await upstream.body?.cancel();
       return new Response("upstream did not return an image", { status: 502 });
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/images/proxy.ts` around lines 60 - 68, In the upstream
error and rejected-content-type branches of the proxy handler, call
upstream.body?.cancel() before returning the 502 Response. Apply this to both
!upstream.ok and !ALLOWED_CONTENT_TYPES.has(baseContentType) paths while leaving
successful image handling unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@examples/landing/src/components/route-resolver.tsx`:
- Around line 63-77: Update the route resolver’s confirmWithServer flow to track
the latest value with a useRef and check it before applying either success or
error state updates. Refresh the ref when value changes, and skip responses from
requests started for an older value so the useEffect reset for the current input
is not overwritten.

In `@examples/landing/src/components/ship-it.tsx`:
- Around line 9-13: Guard the localStorage calls in loadBest and the best
persistence within handleClick with exception handling so storage failures do
not escape from the mount effect or click handler. Preserve the existing null
fallback when reading and continue the elapsed/phase updates even when saving
the best time fails.

In `@examples/landing/src/styles/globals.css`:
- Line 1: Update the stylesheet’s Google Fonts import to use Stylelint’s quoted
import notation by removing the url() wrapper while preserving the existing URL
and font parameters.

In `@examples/landing/x.config.ts`:
- Around line 25-30: Replace the blanket 'unsafe-inline' in the
contentSecurityPolicy configuration with a per-request nonce or hash authorizing
only the island-hydration bootstrap script. Update the render pipeline to
generate the nonce, attach it to the emitted inline script, and include the
matching value in the script-src CSP directive, preserving the remaining
directives.

In `@packages/core/src/images/proxy.ts`:
- Around line 13-21: Remove "image/svg+xml" from the ALLOWED_CONTENT_TYPES
allow-list so the image proxy cannot re-serve SVG content from the site's
origin; leave the other permitted content types unchanged.
- Line 58: Update the error handling around the upstream fetch in the image
proxy to log the caught error server-side, while returning only a generic 502
response message to the client. Remove the use of String(err) from the Response
body and preserve the existing failure status.
- Around line 54-62: Update the upstream fetch in the image proxy handler to use
an abort timeout signal so stalled requests terminate, and enforce a maximum
response size before returning upstream content. Treat timeout, aborted, and
oversized responses as 502 errors while preserving the existing fetch-error and
non-OK handling.
- Around line 44-59: Disable automatic redirects in the image proxy’s fetch call
by using manual redirect handling, and reject redirect responses before
returning or processing them. Update the fetch logic around the parsed URL
allow-list check and upstream response handling so requests cannot follow
redirects to hosts outside allowedHosts.

In `@packages/core/src/security/headers.ts`:
- Around line 58-78: Update applySecurityHeaders in
packages/core/src/security/headers.ts (lines 58-78) to attempt mutating the
original response headers, then fall back to a replacement Response when an
immutable header guard rejects a required header, preserving merged headers,
status, statusText, and body. Apply the same fallback in withRequestLogging in
packages/core/src/observability/logger.ts (lines 64-69) when security-header
hardening is disabled.

---

Nitpick comments:
In `@examples/landing/src/actions/resolve.ts`:
- Around line 10-42: Extract the shared route parsing and classification
algorithm from resolveRoute into a shared route-classifier module, preserving
trimming, API detection, extension removal, special-file handling, and dynamic
segment conversion; remove the dead leading-slash check. In
examples/landing/src/actions/resolve.ts#L10-L42, import and use the shared
classifier. In examples/landing/src/components/route-resolver.tsx#L27-L56,
replace resolvePath’s duplicated implementation with the same shared module and
remove its matching dead check.

In `@packages/core/src/images/proxy.ts`:
- Around line 60-68: In the upstream error and rejected-content-type branches of
the proxy handler, call upstream.body?.cancel() before returning the 502
Response. Apply this to both !upstream.ok and
!ALLOWED_CONTENT_TYPES.has(baseContentType) paths while leaving successful image
handling unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 4f6c6b16-05ee-4c6a-ae1a-ee26c2e8547d

📥 Commits

Reviewing files that changed from the base of the PR and between d6f5258 and b02ea79.

⛔ Files ignored due to path filters (1)
  • examples/landing/public/favicon.ico is excluded by !**/*.ico
📒 Files selected for processing (17)
  • examples/landing/src/actions/resolve.ts
  • examples/landing/src/components/code-block.tsx
  • examples/landing/src/components/logo.tsx
  • examples/landing/src/components/route-resolver.tsx
  • examples/landing/src/components/route-rush.tsx
  • examples/landing/src/components/ship-it.tsx
  • examples/landing/src/layouts/main.tsx
  • examples/landing/src/pages/features.tsx
  • examples/landing/src/pages/index.tsx
  • examples/landing/src/styles/globals.css
  • examples/landing/x.config.ts
  • packages/cli/src/index.ts
  • packages/core/src/createApp.ts
  • packages/core/src/images/proxy.ts
  • packages/core/src/index.ts
  • packages/core/src/observability/logger.ts
  • packages/core/src/security/headers.ts

Comment on lines +63 to +77
useEffect(() => {
setServer({ status: "idle" });
}, [value]);

async function confirmWithServer() {
setServer({ status: "loading" });
const startedAt = performance.now();
try {
const result = await resolveRoute(value);
const ms = Math.round(performance.now() - startedAt);
setServer({ status: "done", route: result.route, ms });
} catch {
setServer({ status: "error" });
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Fix stale server response overwrite when the input changes mid-request.

The resolver sends the edited path to the server action and handles timing, success, and error states, but there is no guard against the input changing while the request is in flight.

Sequence: user clicks confirm for value A (status → "loading"). While awaiting, the user edits the input to value B. The useEffect at lines 63-65 resets server to "idle" for value B. When the promise for A resolves, confirmWithServer still calls setServer({ status: "done", route: result.route, ms }), overwriting the idle state with A's result while the input now shows B. The UI then displays a stale "server says …" result for a path the user is no longer viewing.

Guard against this with a ref that tracks the latest value, and skip the update if the request is stale.

🐛 Proposed fix for stale response overwrite
 export default function RouteResolver() {
   const [value, setValue] = useState("pages/blog/[slug].tsx");
   const resolved = useMemo(() => resolvePath(value), [value]);
   const [server, setServer] = useState<ServerCheck>({ status: "idle" });
+  const valueRef = useRef(value);
+
+  useEffect(() => {
+    valueRef.current = value;
+  }, [value]);

   useEffect(() => {
     setServer({ status: "idle" });
   }, [value]);

   async function confirmWithServer() {
     setServer({ status: "loading" });
+    const requestedValue = value;
     const startedAt = performance.now();
     try {
-      const result = await resolveRoute(value);
+      const result = await resolveRoute(requestedValue);
+      if (valueRef.current !== requestedValue) return;
       const ms = Math.round(performance.now() - startedAt);
       setServer({ status: "done", route: result.route, ms });
     } catch {
+      if (valueRef.current !== requestedValue) return;
       setServer({ status: "error" });
     }
   }

Add useRef to the existing react import.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
useEffect(() => {
setServer({ status: "idle" });
}, [value]);
async function confirmWithServer() {
setServer({ status: "loading" });
const startedAt = performance.now();
try {
const result = await resolveRoute(value);
const ms = Math.round(performance.now() - startedAt);
setServer({ status: "done", route: result.route, ms });
} catch {
setServer({ status: "error" });
}
}
const valueRef = useRef(value);
useEffect(() => {
valueRef.current = value;
}, [value]);
useEffect(() => {
setServer({ status: "idle" });
}, [value]);
async function confirmWithServer() {
setServer({ status: "loading" });
const requestedValue = value;
const startedAt = performance.now();
try {
const result = await resolveRoute(requestedValue);
if (valueRef.current !== requestedValue) return;
const ms = Math.round(performance.now() - startedAt);
setServer({ status: "done", route: result.route, ms });
} catch {
if (valueRef.current !== requestedValue) return;
setServer({ status: "error" });
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/landing/src/components/route-resolver.tsx` around lines 63 - 77,
Update the route resolver’s confirmWithServer flow to track the latest value
with a useRef and check it before applying either success or error state
updates. Refresh the ref when value changes, and skip responses from requests
started for an older value so the useEffect reset for the current input is not
overwritten.

Comment on lines +9 to +13
function loadBest(): number | null {
if (typeof window === "undefined") return null;
const raw = window.localStorage.getItem(BEST_KEY);
return raw ? Number(raw) : null;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Guard localStorage access against thrown exceptions.

loadBest and the best persistence in handleClick call window.localStorage.getItem/setItem directly. In restricted environments (Safari private browsing, storage quota exceeded, or storage disabled by browser policy), these calls throw. loadBest throwing inside the mount effect, or setItem throwing inside handleClick after setElapsed/setPhase already ran, produces an uncaught exception logged to the console for a purely cosmetic best-time feature.

🛡️ Proposed fix to guard localStorage access
 function loadBest(): number | null {
   if (typeof window === "undefined") return null;
-  const raw = window.localStorage.getItem(BEST_KEY);
-  return raw ? Number(raw) : null;
+  try {
+    const raw = window.localStorage.getItem(BEST_KEY);
+    return raw ? Number(raw) : null;
+  } catch {
+    return null;
+  }
 }
       if (best === null || ms < best) {
         setBest(ms);
-        window.localStorage.setItem(BEST_KEY, String(ms));
+        try {
+          window.localStorage.setItem(BEST_KEY, String(ms));
+        } catch {
+          // best-effort persistence only
+        }
       }

Also applies to: 54-57

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/landing/src/components/ship-it.tsx` around lines 9 - 13, Guard the
localStorage calls in loadBest and the best persistence within handleClick with
exception handling so storage failures do not escape from the mount effect or
click handler. Preserve the existing null fallback when reading and continue the
elapsed/phase updates even when saving the best time fails.

@@ -1,13 +1,13 @@
@import url("https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,400;0,9..40,500;0,9..40,600;0,9..40,700&family=IBM+Plex+Mono:wght@400;500&family=Syne:wght@600;700;800&display=swap");
@import url("https://fonts.googleapis.com/css2?family=Oswald:wght@500;600;700&family=Inter:wght@400;500;600;700;800&family=IBM+Plex+Mono:wght@400;500&display=swap");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use the import syntax required by Stylelint.

Stylelint rejects Line 1 with import-notation. This causes the stylesheet lint check to fail. Replace url("...") with a quoted import URL.

Proposed fix
-@import url("https://fonts.googleapis.com/css2?family=Oswald:wght@500;600;700&family=Inter:wght@400;500;600;700;800&family=IBM+Plex+Mono:wght@400;500&display=swap");
+@import "https://fonts.googleapis.com/css2?family=Oswald:wght@500;600;700&family=Inter:wght@400;500;600;700;800&family=IBM+Plex+Mono:wght@400;500&display=swap";
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@import url("https://fonts.googleapis.com/css2?family=Oswald:wght@500;600;700&family=Inter:wght@400;500;600;700;800&family=IBM+Plex+Mono:wght@400;500&display=swap");
`@import` "https://fonts.googleapis.com/css2?family=Oswald:wght@500;600;700&family=Inter:wght@400;500;600;700;800&family=IBM+Plex+Mono:wght@400;500&display=swap";
🧰 Tools
🪛 Stylelint (17.14.1)

[error] 1-1: Expected "url("https://fonts.googleapis.com/css2?family=Oswald:wght@500;600;700&family=Inter:wght@400;500;600;700;800&family=IBM+Plex+Mono:wght@400;500&display=swap")" to be ""https://fonts.googleapis.com/css2?family=Oswald:wght@500;600;700&family=Inter:wght@400;500;600;700;800&family=IBM+Plex+Mono:wght@400;500&display=swap"" (import-notation)

(import-notation)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/landing/src/styles/globals.css` at line 1, Update the stylesheet’s
Google Fonts import to use Stylelint’s quoted import notation by removing the
url() wrapper while preserving the existing URL and font parameters.

Source: Linters/SAST tools

Comment on lines +25 to +30
contentSecurityPolicy:
"default-src 'self'; " +
"script-src 'self' 'unsafe-inline'; " +
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " +
"font-src 'self' https://fonts.gstatic.com; " +
"connect-src 'self';",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

'unsafe-inline' on script-src removes most of CSP's XSS protection.

The comment explains this is a workaround so the island-hydration bootstrap script (an inline <script>) isn't blocked. 'unsafe-inline' on script-src allows any inline script to execute, not just the hydration bootstrap — this defeats CSP's core defense against script injection. This also interacts with the image/svg+xml allowance in packages/core/src/images/proxy.ts: since images are now proxied same-origin, 'unsafe-inline' would allow any injected/embedded script in that flow to run in this origin's context.

Use a per-request nonce (script-src 'self' 'nonce-<value>') or a hash-based CSP for the specific hydration bootstrap script instead of a blanket 'unsafe-inline'. This requires the render pipeline to generate and attach a matching nonce to the emitted <script> tag and to the CSP header, which is a larger change than this file alone, but it's the standard fix for this exact problem.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/landing/x.config.ts` around lines 25 - 30, Replace the blanket
'unsafe-inline' in the contentSecurityPolicy configuration with a per-request
nonce or hash authorizing only the island-hydration bootstrap script. Update the
render pipeline to generate the nonce, attach it to the emitted inline script,
and include the matching value in the script-src CSP directive, preserving the
remaining directives.

Comment on lines +13 to +21
const ALLOWED_CONTENT_TYPES = new Set([
"image/png",
"image/jpeg",
"image/gif",
"image/webp",
"image/svg+xml",
"image/avif",
"image/x-icon",
]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

image/svg+xml in the allow-list creates a same-origin XSS surface.

SVG files can embed <script> elements. The file's own purpose statement (Lines 1-5) is to move image loading to the site's own origin so the browser "never makes a cross-origin request." Before this proxy existed, any script embedded in a remote SVG stayed scoped to the remote origin. Now that /_x/image?url=... re-serves the SVG from the site's own origin, a malicious or compromised allow-listed upstream (or an SVG containing untrusted user content on that host) could execute script in this site's origin if the proxy URL is navigated to directly.

Remove image/svg+xml from ALLOWED_CONTENT_TYPES, or sanitize the SVG server-side before returning it, or serve it with Content-Disposition: attachment to prevent inline rendering as a document.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/images/proxy.ts` around lines 13 - 21, Remove
"image/svg+xml" from the ALLOWED_CONTENT_TYPES allow-list so the image proxy
cannot re-serve SVG content from the site's origin; leave the other permitted
content types unchanged.

Comment on lines +44 to +59
// Allow-list check first — this is what prevents the proxy from being
// used as an open SSRF relay to internal hosts. Only http(s) to an
// explicitly configured hostname is ever fetched.
if (
(parsed.protocol !== "http:" && parsed.protocol !== "https:") ||
!allowedHosts.has(parsed.hostname)
) {
return new Response("host not allow-listed for image proxy", { status: 403 });
}

let upstream: Response;
try {
upstream = await fetch(parsed);
} catch (err) {
return new Response(`upstream fetch failed: ${String(err)}`, { status: 502 });
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== repo files matching proxy.ts =="
fd -a 'proxy\.ts$' . | sed 's#^\./##'

echo "== target snippet =="
if [ -f packages/core/src/images/proxy.ts ]; then
  nl -ba packages/core/src/images/proxy.ts | sed -n '1,120p'
fi

echo "== package/runtime hints =="
for f in package.json bun.lock bun.lockb pnpm-lock.yaml yarn.lock package-lock.json packages/core/package.json; do
  [ -f "$f" ] && { echo "--- $f"; sed -n '1,220p' "$f" | sed -n '1,180p'; }
done

echo "== fetch/redirect/usages =="
rg -n "proxy\\(|fetch\\(|redirect|allowedHosts|image proxy|new Response" packages/core/src packages -g '*.ts' -g '*.tsx' -g '*.js' -g '*.jsx' || true

Repository: abdelkabirouadoukou/x

Length of output: 308


🌐 Web query:

MDN fetch redirect option defaults follow error manual redirect response opaqueredirect status 0 301

💡 Result:

In the Fetch API, the redirect option determines how the browser handles server-side redirects [1][2]. It accepts three values: follow, error, and manual [2][3]. The default value is follow [1][2][3]. 1. follow: The browser automatically follows all redirects [1][3]. 2. error: If the server returns a redirect, the fetch promise rejects with a network error [1][3]. 3. manual: The browser returns an opaque-redirect filtered response [3][4]. When the redirect mode is set to manual, the returned Response object is specifically designed to be opaque [3][4]. It has a status of 0, an empty status message, an empty header list, and a null body [3][4][5]. This design is intended to prevent the leakage of information about the redirect, such as the target URL, to client-side scripts [3][4]. Because of these constraints, you cannot inspect the original redirect status (e.g., 301 or 302) or the Location header when using redirect: 'manual' [5][6]. This mode is primarily intended for use within Service Workers to allow the interception and manual handling (replaying) of requests [1][3][4].

Citations:


🌐 Web query:

Bun fetch redirect option manual default fetch redirect follow

💡 Result:

In Bun, the fetch API implements the WHATWG fetch standard, meaning that by default, requests follow redirects [1][2]. The redirect behavior is controlled by the redirect option within the RequestInit object (or the redirect property of a Request object) [3][4]. The available modes are: - follow (default): The fetch request automatically follows HTTP redirects [1][5]. - manual: The fetch request does not follow redirects; instead, it returns a response with the redirect status code (e.g., 301, 302, 307, 308) and allows you to handle the redirect logic yourself [5][3]. - error: The fetch request throws an error if a redirect is encountered. If you need to prevent automatic redirection, you can explicitly set the redirect option to manual when calling fetch: fetch(url, { redirect: "manual" }); This manual setting is often used to inspect redirect responses or to avoid issues when a large number of redirects are involved [5].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== target snippet with wc/head =="
wc -l packages/core/src/images/proxy.ts
sed -n '1,140p' packages/core/src/images/proxy.ts

echo "== package/runtime hints =="
for f in package.json bun.lock pnpm-lock.yaml yarn.lock package-lock.json packages/core/package.json; do
  [ -f "$f" ] && { echo "--- $f"; sed -n '1,180p' "$f"; }
done

echo "== fetch/redirect/usages =="
rg -n "proxy\\(|fetch\\(|redirect|allowedHosts|image proxy|new Response" packages/core/src packages -g '*.[jt]s' -g '*.[jt]sx' || true

echo "== node fetch redirect default behavioral probe (no repo code executed) =="
node - <<'JS'
(async () => {
  const response = await fetch("https://httpbin.org/status/302", { redirect: "follow", headers: { "accept": "*/*" } });
  console.log(JSON.stringify({ status: response.status, ok: response.ok, redirected: response.redirected, url: response.url }));
})();
JS

Repository: abdelkabirouadoukou/x

Length of output: 30346


🌐 Web query:

Bun fetch Response status redirect manual returns 0 null body

💡 Result:

In Bun, encountering a status of 0 or a null body when using fetch with redirect: "manual" often points to specific implementation behaviors, potential bugs, or misconfigurations regarding how Bun handles manual redirects and response objects [1][2][3]. 1. Redirect Manual Behavior: While Bun supports redirect: "manual", there have been reported issues where the fetch implementation incorrectly ignores the redirect option, particularly when passed via a Request object instead of directly in the fetch options [1]. When working correctly, "manual" mode should return a Response object with the redirect status (e.g., 302, 307) and allow you to inspect headers like Location [2]. 2. Status 0 and Null Body: A status of 0 is typically a sign that the fetch request failed internally or did not complete as expected (e.g., due to network errors, CORS issues, or malformed responses) [3]. A null body is standard for responses with certain status codes (such as 204 No Content or 304 Not Modified) [4]. However, if you are receiving a status of 0 and a null body when you expect a redirect, it may indicate: - Unexpected network-level failure: Bun's internal HTTP client may be failing to finalize the request, resulting in a status of 0 [3][5]. - Version-specific bugs: Several issues regarding redirect handling and empty responses have been tracked and fixed in various Bun releases [6][5][7]. Ensure you are using the latest version of Bun to take advantage of these fixes. 3. Troubleshooting Steps: - Direct Options: Ensure you are passing { redirect: "manual" } directly to the fetch function, as passing it inside a Request object has been known to be ignored in some versions [1]. - Verbose Logging: Use the verbose: true option in your fetch call (e.g., fetch(url, { redirect: "manual", verbose: true })) to see detailed logs of the request/response lifecycle, which can help pinpoint if a failure is occurring before or during the redirect [5]. - Check Bun Version: Verify your Bun version, as many redirect-related bugs have been addressed in recent updates [6][5][7]. - Response Handling: Verify if the response body is being accessed correctly. If the status is a redirect code, the body is typically empty by spec, but the headers should be accessible [8][4]. If you continue to experience this, it is recommended to search the official Bun GitHub issues for similar reports matching your specific use case, as active development frequently addresses these networking behaviors [1][6][7].

Citations:


Disable automatic fetch redirects for the image proxy.

fetch(parsed) uses the default follow/redirect mode, so this allow-list only checks the initial URL. An allow-listed host can return a 3xx redirect and fetch() can reach that final destination without another host check. Use fetch(parsed, { redirect: "manual" }), reject redirect responses before returning them, or re-check the final reachable URL hostname against allowedHosts.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/images/proxy.ts` around lines 44 - 59, Disable automatic
redirects in the image proxy’s fetch call by using manual redirect handling, and
reject redirect responses before returning or processing them. Update the fetch
logic around the parsed URL allow-list check and upstream response handling so
requests cannot follow redirects to hosts outside allowedHosts.

Comment on lines +54 to +62
let upstream: Response;
try {
upstream = await fetch(parsed);
} catch (err) {
return new Response(`upstream fetch failed: ${String(err)}`, { status: 502 });
}
if (!upstream.ok) {
return new Response("upstream error", { status: 502 });
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Add a timeout and cap the upstream fetch.

fetch(parsed) has no signal and no size limit. A slow or stalled upstream keeps the request open indefinitely, tying up server resources per request. Add a timeout and treat oversized responses as errors.

🕐 Proposed fix
     let upstream: Response;
     try {
-      upstream = await fetch(parsed);
+      upstream = await fetch(parsed, { signal: AbortSignal.timeout(10_000) });
     } catch (err) {
       return new Response(`upstream fetch failed: ${String(err)}`, { status: 502 });
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/images/proxy.ts` around lines 54 - 62, Update the upstream
fetch in the image proxy handler to use an abort timeout signal so stalled
requests terminate, and enforce a maximum response size before returning
upstream content. Treat timeout, aborted, and oversized responses as 502 errors
while preserving the existing fetch-error and non-OK handling.

try {
upstream = await fetch(parsed);
} catch (err) {
return new Response(`upstream fetch failed: ${String(err)}`, { status: 502 });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Don't return the raw error message to the client.

`upstream fetch failed: ${String(err)}` forwards the raw error object (which can include internal hostnames, DNS errors, or stack details) directly to the client in the response body. Log the error server-side and return a generic message instead.

🛡️ Proposed fix
     } catch (err) {
-      return new Response(`upstream fetch failed: ${String(err)}`, { status: 502 });
+      console.error("[x] image proxy upstream fetch failed:", err);
+      return new Response("upstream fetch failed", { status: 502 });
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/images/proxy.ts` at line 58, Update the error handling
around the upstream fetch in the image proxy to log the caught error
server-side, while returning only a generic 502 response message to the client.
Remove the use of String(err) from the Response body and preserve the existing
failure status.

Comment on lines +58 to +78
// Mutate res.headers in place rather than `new Response(res.body, ...)`.
// Reconstructing the Response re-parents the underlying ReadableStream on
// every single request — harmless for a normal one-shot body, but for a
// long-lived stream (e.g. the /__x/reload SSE endpoint) it was needlessly
// re-wrapping the same live stream twice per request (here and again in
// withRequestLogging), which was contributing to broken chunked framing.
// A constructed Response's headers are mutable, so this is safe.
// Headers.entries()/.keys() exist at runtime in Bun but aren't in the DOM
// lib types tsup builds against, so cast the same way the loop below does
// instead of calling them directly (that mismatch is what broke the DTS build).
let appliedCount = 0;
for (const [key, value] of (
extra as unknown as { entries(): IterableIterator<[string, string]> }
).entries()) {
if (!headers.has(key)) headers.set(key, value);
if (!res.headers.has(key)) {
res.headers.set(key, value);
appliedCount++;
}
}
return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
console.log(`[x][security] applied ${appliedCount} security header(s) to ${res.url || "response"}`);
return res;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

# Find handlers that can return immutable Fetch API responses.
rg -nP -C 3 --glob '*.{ts,tsx}' \
  'return\s+(?:await\s+)?fetch\s*\(|return\s+Response\.(?:redirect|error)\s*\(' .

# Add regression tests for Response.redirect(...) through both wrappers.
# Expected: security headers and x-request-id are present without a TypeError.

Repository: abdelkabirouadoukou/x

Length of output: 159


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

printf 'Tracked files matching headers/logger:\n'
git ls-files | grep -E '(^|/)(headers|logger)\.ts$|(^|/)packages/core/src' | sed -n '1,120p'

printf '\nSecurity/observability files outline:\n'
ast-grep outline packages/core/src/security/headers.ts --view expanded || true
printf '\n'
ast-grep outline packages/core/src/observability/logger.ts --view expanded || true

printf '\nRelevant source snippets:\n'
cat -n packages/core/src/security/headers.ts | sed -n '1,130p'
printf '\n--- logger ---\n'
cat -n packages/core/src/observability/logger.ts | sed -n '1,120p'

printf '\nSearch for wrappers/call sites:\n'
rg -n -C 3 --glob '*.{ts,tsx}' 'applySecurityHeaders|withRequestLogging|x-request-id|security headers|headers\.set|headers\.has' packages/core/src .

Repository: abdelkabirouadoukou/x

Length of output: 45468


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

printf 'App response hardening and dev/prod fetch call graph:\n'
cat -n packages/core/src/createApp.ts | sed -n '220,280p'
printf '\n--- dev/prod sections ---\n'
cat -n packages/core/src/createApp.ts | sed -n '740,845p'

printf '\nBehavioral probe: Response.redirect()/fetch()-like immutable headers in Node fetch API:\n'
node - <<'JS'
(async () => {
  const cases = {
    redirect: Response.redirect('https://example.com', 302),
    fetch: await fetch('data:text/plain;base64,SGVsbG8='),
    constructed: new Response('hi'),
  };
  for (const [name, res] of Object.entries(cases)) {
    console.log(name, res.status, res.headers.get('x-request-id'), typeof res.headers.set);
    try {
      res.headers.set('x-request-id', 'probe');
      console.log(name, 'set=no-throw');
    } catch (err) {
      console.log(name, 'set-throw=' + err.name + ': ' + err.message);
    }
  }
})();
JS

Repository: abdelkabirouadoukou/x

Length of output: 7073


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

printf 'Handlers and middleware return types/usages:\n'
rg -n -C 4 --glob '*.{ts,tsx}' 'type MiddlewareFn|interface MiddlewareFn|MiddlewareFn|handler\(\(|MiddlewareFn|function .*Handler|const .*Handler|handler:' packages/core/src createApp.ts packages/core/src/createApp.ts . 2>/dev/null | sed -n '1,220p'

printf '\nMiddleware outline and source:\n'
ast-grep outline packages/core/src/middleware.ts --view expanded || true
cat -n packages/core/src/middleware.ts | sed -n '1,220p'

printf '\nAll createApp call sites:\n'
rg -n -C 4 --glob '*.{ts,tsx,js}' 'createApp\s*\(|config security headers|observability.*logging|security.*headers' packages examples . 2>/dev/null | sed -n '1,260p'

Repository: abdelkabirouadoukou/x

Length of output: 15062


Handle immutable response headers before mutating.

applySecurityHeaders and withRequestLogging both call res.headers.set(...) on any Response. Headers from Response.redirect(...), Response.error(...), and standard fetch() responses are immutable, so the wrapper throws TypeError and a request that otherwise succeeded fails with a 500. Try a mutable headers set on the original response; if it fails because of an immutable header guard while a new header is still needed, create a replacement Response with the required merged headers, original status, statusText, and body. Use the same fallback in withRequestLogging when security header hardening is disabled.

📍 Affects 2 files
  • packages/core/src/security/headers.ts#L58-L78 (this comment)
  • packages/core/src/observability/logger.ts#L64-L69
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/security/headers.ts` around lines 58 - 78, Update
applySecurityHeaders in packages/core/src/security/headers.ts (lines 58-78) to
attempt mutating the original response headers, then fall back to a replacement
Response when an immutable header guard rejects a required header, preserving
merged headers, status, statusText, and body. Apply the same fallback in
withRequestLogging in packages/core/src/observability/logger.ts (lines 64-69)
when security-header hardening is disabled.

…ng and client navigation documentation

- Introduced a command palette component for quick navigation and actions.
- Implemented an easter egg feature triggered by the Konami code.
- Added a leak check game to demonstrate environment variable safety.
- Created a mode call game to differentiate between static and server rendering scenarios.
- Developed a Stardance badge component for visual branding.
- Enhanced the documentation for client navigation and image proxy usage.
- Updated routing to include new game pages and documentation links.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
packages/core/src/createApp.ts (4)

257-257: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Keep the disabled-route contract consistent.

When options.images is absent, Line 257 still creates a handler, and Lines 769 and 825 invoke it. The proxy documentation says that a missing or empty remoteHosts list disables the route with 404, but matching requests return 400 or 403.

Skip the handler when image configuration is absent, or make the handler return 404 before parsing the request.

Also applies to: 769-770, 825-827

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/createApp.ts` at line 257, Update the createApp image-proxy
setup and invocation paths around createImageProxyHandler, including the
handlers at the referenced request branches, so absent options.images disables
the route consistently with the documented 404 behavior. Either avoid creating
or invoking the handler without image configuration, or ensure the handler
returns 404 before request parsing; preserve existing behavior when valid image
configuration is present.

731-734: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Remove failed SSE clients during heartbeat cleanup.

When send("hb", "") throws, this catch clears only the interval. It does not remove send from sseClients. If the abort event does not fire and no later reload occurs, the closed stream remains retained.

Use one cleanup function that clears the interval and deletes send, then call it from both the heartbeat failure and abort paths.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/createApp.ts` around lines 731 - 734, Update the heartbeat
cleanup around the reload SSE handling to use a shared cleanup function that
clears the heartbeat interval and removes send from sseClients. Invoke this
function both when send("hb", "") throws and from the abort event path,
preserving the existing heartbeat behavior while ensuring failed clients are not
retained.

257-257: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Add a bounded timeout to the upstream image fetch.

packages/core/src/images/proxy.ts:56 awaits fetch(parsed) with no timeout or request abort signal. A stalled allow-listed origin can hold the image proxy request and response path open.

Combine the incoming request signal with a server-side timeout before fetching the upstream image.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/createApp.ts` at line 257, Update createImageProxyHandler
and its upstream fetch flow in the image proxy implementation to combine the
incoming request signal with a bounded server-side timeout, then pass the
combined abort signal to fetch(parsed). Ensure the timeout is cleaned up after
completion while preserving cancellation from the client request.

257-257: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Reject redirects before proxied image fetches.

createImageProxyHandler() checks only the initial url parameter and then calls fetch(parsed). fetch follows redirects by default, so an allowed host can return Location for an internal/private target and bypass the allow-list.

Set redirect: "error" or handle manual redirects and reject non-image redirect targets before returning them.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/createApp.ts` at line 257, Update createImageProxyHandler
and its proxied image fetch to prevent redirects from bypassing host validation.
Configure fetch to reject redirects (or manually inspect each redirect target
and reapply the allow-list before following), ensuring redirected non-image or
private targets are never returned.
🧹 Nitpick comments (2)
examples/landing/src/components/command-palette.tsx (1)

104-165: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add dialog semantics and focus containment to the command palette.

The palette container (lines 105-119) has no role="dialog", aria-modal="true", or accessible label, and there is no focus trap once the input (line 79) receives focus. Screen readers do not announce this as a dialog, and Tab can move keyboard focus out of the palette into the page behind it while it is open.

Add role="dialog", aria-modal="true", and aria-label on the outer container, and contain Tab/Shift+Tab within the visible results and input.

♿ Proposed fix for dialog semantics
     <div
       className="fixed inset-0 z-[200] flex items-start justify-center bg-black/50 px-4 pt-[14vh] backdrop-blur-sm"
       onClick={() => setOpen(false)}
+      role="dialog"
+      aria-modal="true"
+      aria-label="Command palette"
       onKeyDown={(e) => {
         if (e.key === "ArrowDown") {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/landing/src/components/command-palette.tsx` around lines 104 - 165,
Update the outer command-palette container in the component’s return markup with
role="dialog", aria-modal="true", and an accessible aria-label. Extend its
keyboard handling to intercept Tab and Shift+Tab, cycling focus among the input
and visible result buttons so focus cannot leave the open palette; preserve the
existing arrow-key navigation and Enter behavior.
examples/landing/src/styles/globals.css (1)

337-351: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

.leak-item end offset hardcodes the h-72 container height from leak-check.tsx.

@keyframes leak-fall moves items to translateY(288px) (Line 349). This value only works because examples/landing/src/components/leak-check.tsx uses h-72 (288px) for the play field at Line 127. If either value changes independently later, falling items will stop short of, or overshoot, the container's bottom edge without any visible error.

Share the value through a CSS custom property so both sides stay in sync.

Proposed fix
 .leak-item {
   animation-name: leak-fall;
   animation-timing-function: linear;
   animation-fill-mode: forwards;
 }
 `@keyframes` leak-fall {
   from {
     transform: translateY(-10%);
   }
   to {
-    transform: translateY(288px);
+    transform: translateY(var(--leak-field-height, 288px));
   }
 }

Then set --leak-field-height: 18rem; (or an equivalent value) as an inline style or utility on the h-72 container in leak-check.tsx so a future height change updates both places together.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/landing/src/styles/globals.css` around lines 337 - 351, Replace the
hardcoded 288px end offset in the leak-fall keyframes with a shared
--leak-field-height CSS custom property, providing an appropriate fallback if
needed. Update the h-72 play-field container in the leak-check component to
define --leak-field-height as its current 18rem height, so changing the field
height keeps the animation synchronized.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@examples/landing/src/components/leak-check.tsx`:
- Line 34: Split the shared misses state into separate leak and missed-item
counters across catchItem and landed: increment leaks only when an unsafe SECRET
item is clicked, and increment missed only when a safe item reaches the bottom
uncaught. Update the status line and end-of-round message to report leaks and
missed separately, using the leak counter for the “no secret leaked” condition
and secret count.

In `@examples/landing/src/pages/docs/client-navigation.tsx`:
- Around line 68-85: Update the client-navigation documentation around
createImageProxyHandler to clarify that it returns a handler and does not mount
GET /_x/image; show the supported application wiring where consumer routes
dispatch requests through handleRequest(request). Correct the remoteHosts
comment to state that an empty allow-list rejects all remote targets with 403
rather than causing the route to 404.

In `@examples/landing/src/styles/globals.css`:
- Around line 219-229: Update the .ticket-card rule by adding the required blank
line before the multi-line mask-image declaration so it satisfies Stylelint’s
declaration-empty-line-before rule, without changing the masking behavior.

In `@packages/core/src/createApp.ts`:
- Around line 218-227: Update the island bundle URL generation around
buildIslandBundleInMemory and islandEntryId so layout changes cannot publish
different bundles under the same route-derived URL. Include a stable
layout/build generation token derived from the cache key in the published URL,
or otherwise prevent older builds from being published after newer ones; keep
cache lookups and same-generation URL reuse intact.

In `@packages/core/src/island-bundle.ts`:
- Around line 118-122: The bundle identity currently uses only the route,
allowing different layout variants to collide in the entry path and public URL
cache. Update the identity generation around `entryPath` and the corresponding
URL derivation in `createApp` to include the route path, ordered
`layoutFilePaths`, and every other input that changes generated output, then use
that same variant identity for both cache layers. Add a regression test covering
two layout stacks for one route and verifying they produce distinct cached
bundles.

In `@README.md`:
- Around line 202-209: Qualify the client-navigation documentation to state that
automatic navigation applies only when client navigation is enabled and only to
eligible links, excluding external, download, non-default-target, hash-only, and
special-scheme links. Update README.md lines 202-209,
examples/landing/src/pages/docs/client-navigation.tsx lines 12-27 to qualify
page injection and anchor interception,
examples/landing/src/pages/docs/index.tsx lines 100-105 to describe default
navigation for eligible links, and
examples/landing/src/pages/docs/packages/core.tsx lines 122-136 to apply the
same limitation.

---

Outside diff comments:
In `@packages/core/src/createApp.ts`:
- Line 257: Update the createApp image-proxy setup and invocation paths around
createImageProxyHandler, including the handlers at the referenced request
branches, so absent options.images disables the route consistently with the
documented 404 behavior. Either avoid creating or invoking the handler without
image configuration, or ensure the handler returns 404 before request parsing;
preserve existing behavior when valid image configuration is present.
- Around line 731-734: Update the heartbeat cleanup around the reload SSE
handling to use a shared cleanup function that clears the heartbeat interval and
removes send from sseClients. Invoke this function both when send("hb", "")
throws and from the abort event path, preserving the existing heartbeat behavior
while ensuring failed clients are not retained.
- Line 257: Update createImageProxyHandler and its upstream fetch flow in the
image proxy implementation to combine the incoming request signal with a bounded
server-side timeout, then pass the combined abort signal to fetch(parsed).
Ensure the timeout is cleaned up after completion while preserving cancellation
from the client request.
- Line 257: Update createImageProxyHandler and its proxied image fetch to
prevent redirects from bypassing host validation. Configure fetch to reject
redirects (or manually inspect each redirect target and reapply the allow-list
before following), ensuring redirected non-image or private targets are never
returned.

---

Nitpick comments:
In `@examples/landing/src/components/command-palette.tsx`:
- Around line 104-165: Update the outer command-palette container in the
component’s return markup with role="dialog", aria-modal="true", and an
accessible aria-label. Extend its keyboard handling to intercept Tab and
Shift+Tab, cycling focus among the input and visible result buttons so focus
cannot leave the open palette; preserve the existing arrow-key navigation and
Enter behavior.

In `@examples/landing/src/styles/globals.css`:
- Around line 337-351: Replace the hardcoded 288px end offset in the leak-fall
keyframes with a shared --leak-field-height CSS custom property, providing an
appropriate fallback if needed. Update the h-72 play-field container in the
leak-check component to define --leak-field-height as its current 18rem height,
so changing the field height keeps the animation synchronized.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 5e6bb316-7197-426f-9336-5632e47ab96b

📥 Commits

Reviewing files that changed from the base of the PR and between b02ea79 and 220db05.

📒 Files selected for processing (18)
  • README.md
  • examples/landing/src/components/command-palette.tsx
  • examples/landing/src/components/easter-egg.tsx
  • examples/landing/src/components/leak-check.tsx
  • examples/landing/src/components/mode-call.tsx
  • examples/landing/src/components/stardance-badge.tsx
  • examples/landing/src/layouts/main.tsx
  • examples/landing/src/pages/docs/_layout.tsx
  • examples/landing/src/pages/docs/client-navigation.tsx
  • examples/landing/src/pages/docs/index.tsx
  • examples/landing/src/pages/docs/packages/core.tsx
  • examples/landing/src/pages/features.tsx
  • examples/landing/src/pages/index.tsx
  • examples/landing/src/pages/play.tsx
  • examples/landing/src/styles/globals.css
  • examples/landing/src/x-routes.ts
  • packages/core/src/createApp.ts
  • packages/core/src/island-bundle.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/landing/src/layouts/main.tsx

export default function LeakCheck() {
const [items, setItems] = useState<Falling[]>([]);
const [score, setScore] = useState(0);
const [misses, setMisses] = useState(0);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Fix misleading end-of-round message: not all misses are leaked secrets.

misses is incremented in two different situations that have opposite security meaning:

  • Line 98, inside catchItem, when the player clicks an unsafe (SECRET) item — this is an actual leak.
  • Line 105, inside landed, when a safe item reaches the bottom uncaught — this is only a missed point, not a leak.

The end screen at Line 149 reports every miss as a leaked secret: ${misses} secret(s) reached the client. If a player only ever misses safe vars and never clicks a secret, this message still claims secrets reached the client, which is factually wrong and undermines the game's educational point.

Split the counters so the message only reflects actual leaks.

Proposed fix
   const [items, setItems] = useState<Falling[]>([]);
   const [score, setScore] = useState(0);
-  const [misses, setMisses] = useState(0);
+  const [leaks, setLeaks] = useState(0);
+  const [missed, setMissed] = useState(0);
   const [timeLeft, setTimeLeft] = useState(ROUND_MS);
@@
   function start() {
     setItems([]);
     setScore(0);
-    setMisses(0);
+    setLeaks(0);
+    setMissed(0);
     setTimeLeft(ROUND_MS);
     setRunning(true);
   }

   function catchItem(item: Falling) {
     setItems((prev) => prev.filter((i) => i.id !== item.id));
     if (item.safe) {
       setScore((s) => {
         const next = s + 1;
         if (next > bestRef.current) {
           bestRef.current = next;
           setBest(next);
         }
         return next;
       });
     } else {
-      setMisses((m) => m + 1);
+      setLeaks((l) => l + 1);
       setScore((s) => Math.max(0, s - 2));
     }
   }

   function landed(item: Falling) {
     setItems((prev) => prev.filter((i) => i.id !== item.id));
-    if (item.safe) setMisses((m) => m + 1);
+    if (item.safe) setMissed((m) => m + 1);
   }

Update the status line and end message accordingly, e.g. score {score} · leaks {leaks} · missed {missed} · best {best} and {leaks === 0 ? "Not one secret leaked. That's the whole point." : \${leaks} secret(s) reached the client.`}`.

Also applies to: 86-106, 144-150

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/landing/src/components/leak-check.tsx` at line 34, Split the shared
misses state into separate leak and missed-item counters across catchItem and
landed: increment leaks only when an unsafe SECRET item is clicked, and
increment missed only when a safe item reaches the bottom uncaught. Update the
status line and end-of-round message to report leaks and missed separately,
using the leak counter for the “no secret leaked” condition and secret count.

Comment on lines +68 to +85
<span className="text-foreground">createImageProxyHandler</span> mounts a{" "}
<span className="text-foreground">GET /_x/image</span> route that fetches an allow-listed
remote image server-side and streams it back from your own origin. The browser never makes
a cross-origin image request, so a strict{" "}
<span className="text-foreground">img-src 'self'</span> CSP (see{" "}
<a href="/docs/security" className="text-primary underline underline-offset-2">
Security
</a>
) still works even with remote images. This page's own Stardance badge is proxied through
it right now.
</p>
<CodeBlock
label="createApp.ts / x.config.ts wiring"
code={`import { createImageProxyHandler } from "@thexjs/core";

const imageProxy = createImageProxyHandler({
remoteHosts: ["stardance.hackclub.com"], // required allow-list — empty means the route 404s
});`}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 4 'createImageProxyHandler|remoteHosts|/_x/image' packages examples README.md

Repository: abdelkabirouadoukou/x

Length of output: 15931


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '--- packages/core/src/images/proxy.ts ---\n'
cat -n packages/core/src/images/proxy.ts

printf '\n--- packages/core/src/createApp.ts relevant sections ---\n'
sed -n '68,84p' packages/core/src/createApp.ts | cat -n
sed -n '245,265p' packages/core/src/createApp.ts | cat -n

printf '\n--- behavioral probe from source-derived conditions ---\n'
python3 - <<'PY'
from pathlib import Path
src = Path("packages/core/src/images/proxy.ts").read_text()
checks = {
    "function_returns_handler": "export function createImageProxyHandler" in src,
    "returns_null_non_image_path": 'return null;' in src and 'reqUrl.pathname !== "/_x/image"' in src,
    "checks_remoteHosts": "allowedHosts = new Set(options.remoteHosts ?? [])" in src or "new Set(" in src and "allowedHosts.has" in src,
    "empty_remoteHosts_comment": "required — an empty/missing list disables the route (404)" in src,
}
for k, v in checks.items():
    print(f"{k}: {v}")

# Derive the documented behavior from the source comments/conditions, not by executing repo code.
print("empty_remoteHosts_doc_says_404:", checks["empty_remoteHosts_comment"])
print("handler_returns_null_when_path_not_match:", checks["returns_null_non_image_path"])
PY

Repository: abdelkabirouadoukou/x

Length of output: 250


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- packages/core/src/images/proxy.ts ---'
cat -n packages/core/src/images/proxy.ts

echo
echo '--- packages/core/src/createApp.ts relevant sections ---'
sed -n '68,84p' packages/core/src/createApp.ts | cat -n
sed -n '245,265p' packages/core/src/createApp.ts | cat -n

echo
echo '--- behavioral probe from source-derived conditions ---'
python3 - <<'PY'
from pathlib import Path
src = Path("packages/core/src/images/proxy.ts").read_text()
checks = {
    "function_returns_handler": "export function createImageProxyHandler" in src,
    "returns_null_non_image_path": 'return null;' in src and 'reqUrl.pathname !== "/_x/image"' in src,
    "checks_remoteHosts": "allowedHosts = new Set(options.remoteHosts ?? [])" in src or "new Set(" in src and "allowedHosts.has" in src,
    "empty_remoteHosts_comment": "required — an empty/missing list disables the route (404)" in src,
}
for k, v in checks.items():
    print(f"{k}: {v}")

print("empty_remoteHosts_doc_says_404:", checks["empty_remoteHosts_comment"])
print("handler_returns_null_when_path_not_match:", checks["returns_null_non_image_path"])
PY

Repository: abdelkabirouadoukou/x

Length of output: 5665


Correct the image-proxy setup description.

createImageProxyHandler returns a request handler for GET /_x/image; it does not mount the route by itself. The example creates imageProxy but does not attach it to the application request flow.

A request for GET /_x/image matches the handler even with remoteHosts: []; the handler rejects all hosts with 403 because no hostname is allowed. Update the comment from “route 404s” to say that all remote targets are rejected.

Show the supported wiring, such as consumer routes dispatching through handleRequest(request), so the documented example actually serves proxied images.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/landing/src/pages/docs/client-navigation.tsx` around lines 68 - 85,
Update the client-navigation documentation around createImageProxyHandler to
clarify that it returns a handler and does not mount GET /_x/image; show the
supported application wiring where consumer routes dispatch requests through
handleRequest(request). Correct the remoteHosts comment to state that an empty
allow-list rejects all remote targets with 403 rather than causing the route to
404.

Comment on lines +219 to +229
.ticket-card {
--notch: 16px;
mask-image:
radial-gradient(circle var(--notch) at 0 50%, transparent calc(var(--notch) - 1px), #000 var(--notch)),
radial-gradient(circle var(--notch) at 100% 50%, transparent calc(var(--notch) - 1px), #000 var(--notch));
mask-composite: intersect;
-webkit-mask-image:
radial-gradient(circle var(--notch) at 0 50%, transparent calc(var(--notch) - 1px), #000 var(--notch)),
radial-gradient(circle var(--notch) at 100% 50%, transparent calc(var(--notch) - 1px), #000 var(--notch));
-webkit-mask-composite: source-in, source-in;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Fix Stylelint declaration-empty-line-before failure.

Stylelint flags Line 221 (mask-image) for missing a blank line before a multi-line declaration. This causes the stylesheet lint check to fail.

Proposed fix
 .ticket-card {
   --notch: 16px;
+
   mask-image:
     radial-gradient(circle var(--notch) at 0 50%, transparent calc(var(--notch) - 1px), `#000` var(--notch)),
     radial-gradient(circle var(--notch) at 100% 50%, transparent calc(var(--notch) - 1px), `#000` var(--notch));
   mask-composite: intersect;
+
   -webkit-mask-image:
     radial-gradient(circle var(--notch) at 0 50%, transparent calc(var(--notch) - 1px), `#000` var(--notch)),
     radial-gradient(circle var(--notch) at 100% 50%, transparent calc(var(--notch) - 1px), `#000` var(--notch));
   -webkit-mask-composite: source-in, source-in;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
.ticket-card {
--notch: 16px;
mask-image:
radial-gradient(circle var(--notch) at 0 50%, transparent calc(var(--notch) - 1px), #000 var(--notch)),
radial-gradient(circle var(--notch) at 100% 50%, transparent calc(var(--notch) - 1px), #000 var(--notch));
mask-composite: intersect;
-webkit-mask-image:
radial-gradient(circle var(--notch) at 0 50%, transparent calc(var(--notch) - 1px), #000 var(--notch)),
radial-gradient(circle var(--notch) at 100% 50%, transparent calc(var(--notch) - 1px), #000 var(--notch));
-webkit-mask-composite: source-in, source-in;
}
.ticket-card {
--notch: 16px;
mask-image:
radial-gradient(circle var(--notch) at 0 50%, transparent calc(var(--notch) - 1px), `#000` var(--notch)),
radial-gradient(circle var(--notch) at 100% 50%, transparent calc(var(--notch) - 1px), `#000` var(--notch));
mask-composite: intersect;
-webkit-mask-image:
radial-gradient(circle var(--notch) at 0 50%, transparent calc(var(--notch) - 1px), `#000` var(--notch)),
radial-gradient(circle var(--notch) at 100% 50%, transparent calc(var(--notch) - 1px), `#000` var(--notch));
-webkit-mask-composite: source-in, source-in;
}
🧰 Tools
🪛 Stylelint (17.14.1)

[error] 221-223: Expected empty line before declaration (declaration-empty-line-before)

(declaration-empty-line-before)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/landing/src/styles/globals.css` around lines 219 - 229, Update the
.ticket-card rule by adding the required blank line before the multi-line
mask-image declaration so it satisfies Stylelint’s declaration-empty-line-before
rule, without changing the masking behavior.

Source: Linters/SAST tools

Comment on lines +218 to +227
const cacheKey = `${routeFilePath}::${layoutFilePaths.join("|")}::${uniqueNames.join(",")}`;
const cached = islandBundleCache.get(cacheKey);
if (cached) return cached;

const code = await buildIslandBundleInMemory(routeFilePath, uniqueNames, actionModules);
const code = await buildIslandBundleInMemory(
routeFilePath,
layoutFilePaths,
uniqueNames,
actionModules,
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate file =="
git ls-files | rg '(^|/)createApp\.ts$|islandFileCache|islandBundleCache|buildIslandBundleInMemory' || true

echo "== file outline =="
ast-grep outline packages/core/src/createApp.ts --view expanded || true

echo "== relevant createApp.ts lines 180-260 =="
sed -n '180,260p' packages/core/src/createApp.ts | nl -ba -v180

echo "== search cache usages =="
rg -n 'islandFileCache|islandBundleCache|buildIslandBundleInMemory|cacheKey|routeFilePath|layoutFilePaths|uniqueNames' packages/core/src/createApp.ts packages -g '*.ts'

Repository: abdelkabirouadoukou/x

Length of output: 2092


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== file size =="
wc -l packages/core/src/createApp.ts

echo "== createApp.ts lines 180-280 =="
sed -n '180,280p' packages/core/src/createApp.ts | awk '{printf "%5d  %s\n", NR+179, $0}'

echo "== createApp.ts lines 280-380 =="
sed -n '280,380p' packages/core/src/createApp.ts | awk '{printf "%5d  %s\n", NR+279, $0}'

echo "== cache usages in createApp.ts =="
rg -n 'islandFileCache|islandBundleCache|buildIslandBundleInMemory|cacheKey|routeFilePath|layoutFilePaths|uniqueNames|entry id|entryId' packages/core/src/createApp.ts || true

echo "== broader usages =="
rg -n 'islandFileCache|islandBundleCache|buildIslandBundleInMemory' packages -g '*.ts' || true

Repository: abdelkabirouadoukou/x

Length of output: 12024


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== island-bundle outline =="
ast-grep outline packages/core/src/island-bundle.ts --view expanded || true

echo "== island-bundle relevant sections =="
sed -n '1,170p' packages/core/src/island-bundle.ts | awk '{printf "%5d  %s\n", NR, $0}'

echo "== resolveIslandScripts call sites =="
sed -n '430,570p' packages/core/src/createApp.ts | awk '{printf "%5d  %s\n", NR+429, $0}'

echo "== handler registration around serveIslandBundle =="
rg -n 'serveIslandBundle|/_islands' packages/core/src/createApp.ts packages/core/src -g '*.ts' || true

echo "== read-only behavior probe: url derivation vs cache key behavior =="
python3 - <<'PY'
def resolve(cache, url_cache, route, layouts, names):
    unique_names = sorted(set(names))
    cache_key = f"{route}::{'|'.join(layouts)}::{','.join(unique_names)}"
    cached = cache.get(cache_key)
    if cached:
        return cached, cache
    url = f"/_islands/{route}/{route}.js"
    # Simulate a stale rebuild under same route but different layouts:
    another_url = "/_islands/page/page.js"
    url_cache[another_url] = "stale bundle"
    bundle = f"new route={route};layouts={','.join(layouts)};islands={','.join(unique_names)}"
    url_cache[url] = bundle
    cache[cache_key] = [url]
    return [url], cache

url_cache = {}
cache = {}
print("url:", resolve(cache, url_cache, "page", ["A"], ["X"])[0])
print(url_cache)
print("layout change same route:")
resolve(cache, url_cache, "page", ["B"], ["X"])
print(url_cache)
print("cache lookup after layout change:", cache)
print("fetched body:", url_cache["/_islands/page/page.js"])
PY

Repository: abdelkabirouadoukou/x

Length of output: 15929


Version island bundle URLs with the cache key.

cacheKey includes layoutFilePaths, but islandEntryId() derives /_islands/${entryId}/${entryId}.js from routeFilePath only. A same-route request with a changed layout can publish a new bundle at the same URL, so add a layout/build generation token to the URL or reject out-of-order bundle publication.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/createApp.ts` around lines 218 - 227, Update the island
bundle URL generation around buildIslandBundleInMemory and islandEntryId so
layout changes cannot publish different bundles under the same route-derived
URL. Include a stable layout/build generation token derived from the cache key
in the published URL, or otherwise prevent older builds from being published
after newer ones; keep cache lookups and same-generation URL reuse intact.

Comment thread packages/core/src/island-bundle.ts Outdated
Comment on lines +118 to +122
const layoutRels = layoutFilePaths.map((layoutPath) =>
join(relative(scratchDir, join(layoutPath, "..")), basename(layoutPath)),
);
const entryPath = join(scratchDir, `${entryId}.tsx`);
writeFileSync(entryPath, generateHydrateEntry(routeRel), "utf-8");
writeFileSync(entryPath, generateHydrateEntry(routeRel, layoutRels), "utf-8");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Use a layout-aware bundle identity.

When layoutFilePaths differs for the same route, this code generates different client bundles. However, packages/core/src/createApp.ts still derives the public URL from routeFilePath only. islandFileCache.set(url, code) can therefore overwrite one layout variant with another.

Derive the entry ID and URL from the route path, ordered layout paths, and other inputs that change generated output. Use the same variant identity in both cache layers. Add a regression test with two layout stacks for one route.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/island-bundle.ts` around lines 118 - 122, The bundle
identity currently uses only the route, allowing different layout variants to
collide in the entry path and public URL cache. Update the identity generation
around `entryPath` and the corresponding URL derivation in `createApp` to
include the route path, ordered `layoutFilePaths`, and every other input that
changes generated output, then use that same variant identity for both cache
layers. Add a regression test covering two layout stacks for one route and
verifying they produce distinct cached bundles.

Comment thread README.md
Comment on lines +202 to +209
Every `<a>` tag gets SPA-style client-side navigation and hover prefetch automatically — no router setup, opt out per-link with `data-no-nav` / `data-no-prefetch`, or use the typed `<Link>` wrapper. A built-in `/_x/image` proxy streams allow-listed remote images through your own origin so a strict `img-src 'self'` CSP still works with external images:

```tsx
import { Link, createImageProxyHandler } from "@thexjs/core";

<Link href="/docs">Docs</Link>

const imageProxy = createImageProxyHandler({ remoteHosts: ["cdn.example.com"] });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

State the client-navigation eligibility condition.

CLIENT_NAV_SCRIPT is not present when clientNav is false. When enabled, it also skips external links, downloads, non-default targets, hash-only links, and special schemes. Replace “every <a> tag” and “every rendered page” with language that limits the behavior to eligible links when client navigation is enabled.

  • README.md#L202-L209: qualify the automatic-navigation claim.
  • examples/landing/src/pages/docs/client-navigation.tsx#L12-L27: qualify both the page-injection and anchor-interception claims.
  • examples/landing/src/pages/docs/index.tsx#L100-L105: describe default navigation for eligible links.
  • examples/landing/src/pages/docs/packages/core.tsx#L122-L136: qualify the core-package feature description.
🧰 Tools
🪛 LanguageTool

[grammar] ~202-~202: Use a hyphen to join words.
Context: ...tch automatically — no router setup, opt out per-link with data-no-nav / `data-...

(QB_NEW_EN_HYPHEN)

📍 Affects 4 files
  • README.md#L202-L209 (this comment)
  • examples/landing/src/pages/docs/client-navigation.tsx#L12-L27
  • examples/landing/src/pages/docs/index.tsx#L100-L105
  • examples/landing/src/pages/docs/packages/core.tsx#L122-L136
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@README.md` around lines 202 - 209, Qualify the client-navigation
documentation to state that automatic navigation applies only when client
navigation is enabled and only to eligible links, excluding external, download,
non-default-target, hash-only, and special-scheme links. Update README.md lines
202-209, examples/landing/src/pages/docs/client-navigation.tsx lines 12-27 to
qualify page injection and anchor interception,
examples/landing/src/pages/docs/index.tsx lines 100-105 to describe default
navigation for eligible links, and
examples/landing/src/pages/docs/packages/core.tsx lines 122-136 to apply the
same limitation.

…consistency

- Updated various components (LeakCheck, Logo, ModeCall, RouteResolver, ShipIt, DocPage, UserPage, SubscribeForm, etc.) to enhance code formatting and readability by adjusting indentation and line breaks.
- Modified CSS styles in globals.css for better organization and clarity.
- Improved button elements in settings and other pages for consistent styling.
- Enhanced error handling and logging in CLI and server functions.
- Updated TypeScript configurations and template files for better structure and maintainability.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/cli/src/index.ts (1)

223-229: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Apply configured request handling to static builds.

Lines 269-273 bypass createApp and start a new static server. Lines 297-318 do not invoke the image proxy or apply security headers.

As a result, /_x/image?... falls through to index.html instead of the allow-listed proxy. Static-only builds also omit configured security headers. Preserve images and security for cmdStart, run the image proxy before the static fallback, and apply the configured headers to every static response.

Also applies to: 269-273, 297-318

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/index.ts` around lines 223 - 229, Update the options
handling around cmdStart so images and security are preserved instead of removed
from opts. In the static-server path, apply configured security headers to every
response and run the image proxy before the static fallback so /_x/image
requests reach the allow-listed proxy rather than index.html.
🧹 Nitpick comments (2)
packages/core/src/build.ts (1)

220-226: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Add a regression test for layout-owned islands.

Build a static route with an island exported only by a nested or dedicated layout. Assert that the emitted island bundle resolves that island. Add this coverage in packages/core/src/build.test.ts to protect the new layoutFilePaths contract.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/build.ts` around lines 220 - 226, Add a regression test in
build.test.ts covering a static route whose island is exported only by a nested
or dedicated layout. Build the route using the layoutFilePaths contract passed
to bundleRouteIslands, then assert the emitted island bundle resolves and
includes that layout-owned island.
packages/core/src/link.tsx (1)

5-5: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Do not make unnamed links valid by default.

This type allows <Link href="/about" />, which renders an empty <a> element. If the caller does not provide aria-label or another accessible name, users cannot identify the link. Keep children required, or require aria-label for the no-children variant.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/link.tsx` at line 5, Update the Link props type around the
children field so links cannot be used without accessible content by default.
Make children required, or define a type variant that permits omitted children
only when an accessible name such as aria-label is provided; preserve valid
named-link usage.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@examples/landing/src/components/command-palette.tsx`:
- Line 160: Remove the onKeyDown handler that calls stopPropagation from the
command palette input, allowing keydown events to reach the backdrop and window
listeners for Arrow-key navigation, Enter command execution, and Escape
dismissal.

In `@packages/core/src/build.ts`:
- Around line 308-315: Update the generateHydrateEntry and Bun.build flow to
prevent layout modules from exposing server-only imports in browser bundles.
Enforce a browser-safe layout contract or generate a dedicated browser-only
module exporting only island components, ensuring database, secret, and Node API
dependencies cannot enter the client bundle while preserving island hydration.
- Around line 308-315: The build flow around generateHydrateEntry and Bun.build
must enforce unique island names across the route and all layout modules before
generating hydration code. Detect duplicate names across these source modules
and fail the build with a clear error, or consistently namespace both island
markers and generated resolvers by source module so route and layout islands
cannot collide.

In `@packages/create-thexjs-app/templates/landing/src/pages/docs/data-layer.tsx`:
- Line 99: Update the PostgreSQL examples in the data-layer documentation and
core package documentation to match the current API: change connectPostgres
calls to pass an object containing url instead of connectionString or max, and
pass "./data/migrations" as the migrations directory to runPostgresMigrations
instead of an array. Preserve the surrounding example flow and imports.
- Line 23: Update the documented data-layer examples to match the current API:
in packages/create-thexjs-app/templates/landing/src/pages/docs/data-layer.tsx at
lines 23-23, call connectSQLite with a { path } options object and pass
migration directories as strings; at lines 99-99, keep runPostgresMigrations
calls in the runPostgresMigrations(client, migrationsDir: string) form; and in
packages/create-thexjs-app/templates/landing/src/pages/docs/packages/core.tsx at
lines 134-137, use connectSQLite({ path: "./data/dev.db" }) and string
migration-directory arguments.

In
`@packages/create-thexjs-app/templates/landing/src/pages/docs/packages/core.tsx`:
- Around line 134-137: Update the connectSQLite example in the core package
documentation to pass the database location using the supported path option
instead of filename, while preserving the existing migration example and
data/dev.db value.

---

Outside diff comments:
In `@packages/cli/src/index.ts`:
- Around line 223-229: Update the options handling around cmdStart so images and
security are preserved instead of removed from opts. In the static-server path,
apply configured security headers to every response and run the image proxy
before the static fallback so /_x/image requests reach the allow-listed proxy
rather than index.html.

---

Nitpick comments:
In `@packages/core/src/build.ts`:
- Around line 220-226: Add a regression test in build.test.ts covering a static
route whose island is exported only by a nested or dedicated layout. Build the
route using the layoutFilePaths contract passed to bundleRouteIslands, then
assert the emitted island bundle resolves and includes that layout-owned island.

In `@packages/core/src/link.tsx`:
- Line 5: Update the Link props type around the children field so links cannot
be used without accessible content by default. Make children required, or define
a type variant that permits omitted children only when an accessible name such
as aria-label is provided; preserve valid named-link usage.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b228c3be-6593-46cd-8c64-fa71fc583094

📥 Commits

Reviewing files that changed from the base of the PR and between 220db05 and e82c1ef.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (47)
  • examples/basic/src/lib/auth.ts
  • examples/basic/src/pages/placeholder.tsx
  • examples/blog/src/pages/index.tsx
  • examples/landing/package.json
  • examples/landing/src/actions/resolve.ts
  • examples/landing/src/components/command-palette.tsx
  • examples/landing/src/components/easter-egg.tsx
  • examples/landing/src/components/leak-check.tsx
  • examples/landing/src/components/logo.tsx
  • examples/landing/src/components/mode-call.tsx
  • examples/landing/src/components/route-resolver.tsx
  • examples/landing/src/components/route-rush.tsx
  • examples/landing/src/components/ship-it.tsx
  • examples/landing/src/layouts/main.tsx
  • examples/landing/src/pages/docs/client-navigation.tsx
  • examples/landing/src/pages/docs/data-layer.tsx
  • examples/landing/src/pages/docs/packages/core.tsx
  • examples/landing/src/pages/docs/server-functions.tsx
  • examples/landing/src/pages/index.tsx
  • examples/landing/src/pages/play.tsx
  • examples/landing/src/styles/globals.css
  • examples/saas/src/lib/auth.ts
  • examples/saas/src/pages/dashboard/settings.tsx
  • packages/adapter-vercel/package.json
  • packages/cli/package.json
  • packages/cli/src/index.ts
  • packages/core/package.json
  • packages/core/src/build.ts
  • packages/core/src/createApp.ts
  • packages/core/src/index.ts
  • packages/core/src/island-bundle.ts
  • packages/core/src/link.tsx
  • packages/core/src/security/env-isolation.ts
  • packages/core/src/security/headers.ts
  • packages/create-thexjs-app/package.json
  • packages/create-thexjs-app/src/index.ts
  • packages/create-thexjs-app/templates/basic/src/lib/auth.ts
  • packages/create-thexjs-app/templates/basic/src/pages/login.tsx
  • packages/create-thexjs-app/templates/basic/src/pages/placeholder.tsx
  • packages/create-thexjs-app/templates/blog/src/pages/index.tsx
  • packages/create-thexjs-app/templates/landing/src/pages/docs/data-layer.tsx
  • packages/create-thexjs-app/templates/landing/src/pages/docs/packages/core.tsx
  • packages/create-thexjs-app/templates/landing/src/pages/docs/server-functions.tsx
  • packages/create-thexjs-app/templates/landing/tsconfig.json
  • packages/create-thexjs-app/templates/saas/src/lib/auth.ts
  • packages/create-thexjs-app/templates/saas/src/pages/dashboard/settings.tsx
  • packages/env/package.json
💤 Files with no reviewable changes (1)
  • packages/core/src/index.ts
🚧 Files skipped from review as they are similar to previous changes (14)
  • packages/core/src/security/headers.ts
  • examples/landing/src/components/logo.tsx
  • examples/landing/src/components/route-rush.tsx
  • examples/landing/src/components/ship-it.tsx
  • examples/landing/src/actions/resolve.ts
  • examples/landing/src/pages/play.tsx
  • examples/landing/src/pages/docs/client-navigation.tsx
  • examples/landing/src/components/easter-egg.tsx
  • examples/landing/src/components/leak-check.tsx
  • packages/core/src/island-bundle.ts
  • examples/landing/src/components/mode-call.tsx
  • examples/landing/src/components/route-resolver.tsx
  • examples/landing/src/pages/docs/packages/core.tsx
  • packages/core/src/createApp.ts

<div
className="w-full max-w-lg overflow-hidden rounded-2xl border border-border bg-card shadow-2xl"
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => e.stopPropagation()}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 8 'onKeyDown=.*stopPropagation|ArrowDown|ArrowUp|Escape|results\[active\]' \
  examples/landing/src/components/command-palette.tsx

Repository: abdelkabirouadoukou/x

Length of output: 1910


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '130,225p' examples/landing/src/components/command-palette.tsx | cat -n

Repository: abdelkabirouadoukou/x

Length of output: 4339


🌐 Web query:

React component keyboard navigation keyboard accessible dialog Escape document listener React 18 useEffect event listener

💡 Result:

To implement a keyboard-accessible dialog in React 18 that closes on the Escape key, you should use a useEffect hook to attach a document-level event listener [1][2][3]. Always include a cleanup function to remove the listener when the component unmounts or closes to prevent memory leaks and unintended behavior [1][4][5]. Essential implementation steps include: 1. Escape Key Handling: Within useEffect, add a keydown event listener to the document [1][5]. Check for event.key === 'Escape' and call your close handler [1][2][3]. 2. Proper Cleanup: Return a function from useEffect that calls document.removeEventListener to clean up the listener [1][4][5]. 3. Focus Management: When the dialog opens, move focus to the first interactive element or the dialog container itself [2][6][7]. When it closes, restore focus to the trigger element that opened the dialog [1][2][7]. 4. Focus Trapping: Ensure Tab and Shift+Tab navigation stays trapped within the dialog [2][7]. Using specialized libraries like react-focus-lock or headless UI primitives (e.g., Radix UI, React Aria) is highly recommended over manual implementation to ensure robustness against edge cases [2][8][9]. 5. Semantics and Accessibility: Use proper ARIA attributes, such as role="dialog" and aria-modal="true" [2][7][9]. The native HTML dialog element with.showModal can automate many of these requirements, including focus trapping and backdrop handling, when supported [10][8]. Example pattern using useEffect: useEffect( => { if (!isOpen) return; const handleKeyDown = (event) => { if (event.key === 'Escape') { onClose; } }; document.addEventListener('keydown', handleKeyDown); return => document.removeEventListener('keydown', handleKeyDown); }, [isOpen, onClose]); For modern React applications, using an AbortController with addEventListener is an alternative way to handle cleanup automatically without manual unbinding [4]. However, the standard removeEventListener pattern remains the conventional and widely compatible approach [1][5].

Citations:


🌐 Web query:

MDN KeyboardEvent stopPropagation event bubbling input keydown event target bubble capture phase

💡 Result:

KeyboardEvent objects, including keydown, naturally support event bubbling [1]. When a keyboard interaction occurs on an element, the resulting event traverses the DOM in a three-phase process: the capturing phase (from Window down to the target's parent), the target phase (at the target element), and the bubbling phase (from the target's parent back up to Window) [2]. You can prevent a KeyboardEvent from bubbling to ancestor elements by calling event.stopPropagation within your event handler [3][4]. This method, which belongs to the Event interface, stops the event from continuing its path through both the capturing and bubbling phases [3]. Key points regarding this process include: Propagation Control: Calling event.stopPropagation prevents the event from triggering listeners on ancestor elements [3]. If you need to stop propagation to other listeners attached to the same target element, use event.stopImmediatePropagation instead [3][5]. Default Actions: It is important to distinguish between propagation and default browser behavior. event.stopPropagation does not prevent the browser's default action (such as typing a character into an input field). To prevent the default action, use event.preventDefault [3][6]. Event Target: In the context of keyboard events, event.target refers to the element where the interaction initially occurred (e.g., the specific input field), while event.currentTarget refers to the element on which the handler currently executing is attached [4]. Phase Awareness: You can track which phase the event is currently in by checking the event.eventPhase property, which returns an integer value representing the capturing (1), target (2), or bubbling (3) phase [7]. Authoritative documentation on the DOM event flow and KeyboardEvent behavior is available from MDN Web Docs [3][8] and the W3C UI Events specification [2][1].

Citations:


Remove the keyboard propagation stop.

Line 160 stops keydown events started by the input before they reach the backdrop handlers and the window listener. Remove this handler so keyboard users can navigate with Arrow keys, run commands with Enter, and close the palette with Escape.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/landing/src/components/command-palette.tsx` at line 160, Remove the
onKeyDown handler that calls stopPropagation from the command palette input,
allowing keydown events to reach the backdrop and window listeners for Arrow-key
navigation, Enter command execution, and Escape dismissal.

Comment thread packages/core/src/build.ts Resolved
<CodeBlock
label="src/lib/db.ts"
code={`import { connectSQLite, runSQLiteMigrations } from "@thexjs/core";
code={`import { connectSQLite, runSQLiteMigrations } from "@thexjs/core/data";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== candidate files =="
git ls-files | rg 'packages/create-thexjs-app/templates/landing/src/pages/docs/(data-layer|packages/core)\.tsx|packages/create-thexjs-app|packages/core' || true

echo
echo "== relevant snippets =="
for f in \
  packages/create-thexjs-app/templates/landing/src/pages/docs/data-layer.tsx \
  packages/create-thexjs-app/templates/landing/src/pages/docs/packages/core.tsx
do
  if [ -f "$f" ]; then
    echo "--- $f line count ---"
    wc -l "$f"
    echo "--- $f relevant lines ---"
    sed -n '1,170p' "$f" | cat -n
  else
    echo "MISSING: $f"
  fi
done

echo
echo "== locate connection/migration helpers definitions/usages =="
rg -n "connect(SQLite|Postgres)|run(SQLite|Postgres)Migrations|filename|path.*migrations|migrations.*path|filename.*db" -S packages || true

Repository: abdelkabirouadoukou/x

Length of output: 31502


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== data-layer implementation =="
for f in \
  packages/core/src/data/sqlite.ts \
  packages/core/src/data/postgres.ts \
  packages/core/src/data/migrate.ts \
  packages/core/src/data/index.ts
do
  echo "--- $f ---"
  cat -n "$f"
done

echo
echo "== template read usage =="
for f in \
  packages/create-thexjs-app/templates/basic/src/lib/auth.ts \
  packages/create-thexjs-app/templates/saas/src/lib/auth.ts
do
  echo "--- $f ---"
  cat -n "$f"
done

echo
echo "== read-only behavior probe for source text shapes =="
python3 - <<'PY'
from pathlib import Path
import re

files = {
    "landing data-layer": Path("packages/create-thexjs-app/templates/landing/src/pages/docs/data-layer.tsx"),
    "landing core": Path("packages/create-thexjs-app/templates/landing/src/pages/docs/packages/core.tsx"),
    "core sqlite": Path("packages/core/src/data/sqlite.ts"),
    "core postgres": Path("packages/core/src/data/postgres.ts"),
    "core migrate": Path("packages/core/src/data/migrate.ts"),
}
for label, path in files.items():
    s = path.read_text()
    print(f"{label}: lines={s.count(chr(10))+1}")
    if "sqlite" in label.lower():
        print("  options object:", re.search(r"SQLiteOptions|connectSQLite\\([\s\S]{0,250}\\)", s))
    if "postgres" in label.lower():
        print("  options object:", re.search(r"PostgresOptions|connectPostgres\\([\s\S]{0,300}\\)", s))
        print("  connection string refs:", re.findall(r"connectionString|url", s))
    if "migrate" in label.lower():
        print("  sqlite call sig:", re.search(r"runSQLiteMigrations\\([\\s\\S]{0,120}\\)", s))
        print("  postgres call sig:", re.search(r"runPostgresMigrations\\([\\s\\S]{0,220}\\)", s))
PY

Repository: abdelkabirouadoukou/x

Length of output: 10889


Align the documented data-layer examples with the current API.

connectSQLite takes { path }, and both migration helpers accept the migrations directory as a string.

  • packages/create-thexjs-app/templates/landing/src/pages/docs/data-layer.tsx#L25-L27: use connectSQLite({ path: "data/app.db" }) and pass "path/to/migrations" for migrations.
  • packages/create-thexjs-app/templates/landing/src/pages/docs/data-layer.tsx#L99-L120: keep PostgreSQL migration calls aligned with the current signature (runPostgresMigrations(client, migrationsDir: string)).
  • packages/create-thexjs-app/templates/landing/src/pages/docs/packages/core.tsx#L136-L144: use connectSQLite({ path: "./data/dev.db" }) and pass migration directories as strings.
📍 Affects 2 files
  • packages/create-thexjs-app/templates/landing/src/pages/docs/data-layer.tsx#L23-L23 (this comment)
  • packages/create-thexjs-app/templates/landing/src/pages/docs/data-layer.tsx#L99-L99
  • packages/create-thexjs-app/templates/landing/src/pages/docs/packages/core.tsx#L134-L137
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/create-thexjs-app/templates/landing/src/pages/docs/data-layer.tsx`
at line 23, Update the documented data-layer examples to match the current API:
in packages/create-thexjs-app/templates/landing/src/pages/docs/data-layer.tsx at
lines 23-23, call connectSQLite with a { path } options object and pass
migration directories as strings; at lines 99-99, keep runPostgresMigrations
calls in the runPostgresMigrations(client, migrationsDir: string) form; and in
packages/create-thexjs-app/templates/landing/src/pages/docs/packages/core.tsx at
lines 134-137, use connectSQLite({ path: "./data/dev.db" }) and string
migration-directory arguments.

<CodeBlock
label="src/lib/db.ts"
code={`import { connectPostgres, runPostgresMigrations } from "@thexjs/core";
code={`import { connectPostgres, runPostgresMigrations } from "@thexjs/core/data";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Files:"
git ls-files | rg 'packages/(core/src/data|create-thexjs-app/templates/landing/src/pages/docs).*(postgres|migrate|data-layer|core)\.ts|tsx$' || true

echo
echo "Relevant docs snippets:"
for f in $(git ls-files | rg 'packages/create-thexjs-app/templates/landing/src/pages/docs/(data-layer|packages/core)\.tsx$' || true); do
  echo "--- $f"
  nl -ba "$f" | sed -n '1,140p'
done

echo
echo "postgres/migrate implementation outlines:"
for f in $(git ls-files | rg 'packages/core/src/data/(postgres|migrate)\.ts$' || true); do
  echo "--- $f"
  wc -l "$f"
  ast-grep outline "$f" || true
  sed -n '1,260p' "$f"
done

Repository: abdelkabirouadoukou/x

Length of output: 8988


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "--- docs/data-layer.tsx relevant section"
cat -n packages/create-thexjs-app/templates/landing/src/pages/docs/data-layer.tsx | sed -n '85,115p'

echo
echo "--- docs/packages/core.tsx relevant section"
cat -n packages/create-thexjs-app/templates/landing/src/pages/docs/packages/core.tsx | sed -n '1,180p'

echo
echo "--- packages/core/src/data/postgres.ts"
cat -n packages/core/src/data/postgres.ts | sed -n '1,260p'

echo
echo "--- packages/core/src/data/migrate.ts"
cat -n packages/core/src/data/migrate.ts | sed -n '1,260p'

Repository: abdelkabirouadoukou/x

Length of output: 13245


Align the PostgreSQL usage examples with the current data-layer API.

connectPostgres accepts { url }, not { connectionString } / max, and runPostgresMigrations accepts a migrations directory, not an array. Update packages/create-thexjs-app/templates/landing/src/pages/docs/data-layer.tsx and packages/create-thexjs-app/templates/landing/src/pages/docs/packages/core.tsx to use connectPostgres({ url: ... }) and runPostgresMigrations(..., "./data/migrations").

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/create-thexjs-app/templates/landing/src/pages/docs/data-layer.tsx`
at line 99, Update the PostgreSQL examples in the data-layer documentation and
core package documentation to match the current API: change connectPostgres
calls to pass an object containing url instead of connectionString or max, and
pass "./data/migrations" as the migrations directory to runPostgresMigrations
instead of an array. Preserve the surrounding example flow and imports.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/adapter-vercel/src/generate-entry.ts (1)

178-189: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Guard the fatal-error path with res.headersSent.

sendWebResponse streams the body incrementally. If the stream fails after the first res.write, control reaches the catch. At that point the status and headers are already flushed. Assigning res.statusCode has no effect, and res.end("Internal server error") appends that text to the partially streamed body. The client then receives a 200 response with corrupted content.

Check res.headersSent and destroy the socket instead.

🛡️ Proposed fix for the generated handler
     "export default async function handler(req, res) {",
     "  try {",
     "    const request = nodeRequestToWebRequest(req);",
     "    const response = await __x_app.fetch(request);",
     "    await sendWebResponse(response, res);",
     "  } catch (err) {",
     "    console.error('[x] fatal error handling request:', err);",
-    "    res.statusCode = 500;",
-    '    res.end("Internal server error");',
+    "    if (res.headersSent) { res.destroy(err); return; }",
+    "    res.statusCode = 500;",
+    '    res.end("Internal server error");',
     "  }",
     "}",
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/adapter-vercel/src/generate-entry.ts` around lines 178 - 189, Update
the generated handler’s catch block around __x_app.fetch and sendWebResponse to
check res.headersSent before writing the 500 response. If headers have already
been sent, destroy the response/socket without appending an error body;
otherwise preserve the existing statusCode 500 and “Internal server error”
response.
packages/adapter-vercel/src/scan.ts (1)

104-125: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Validate revalidate as a finite number before it reaches the manifest.

The as cast at lines 104-109 is unchecked, so mod.revalidate is whatever the page module exports. packages/adapter-vercel/src/generate-entry.ts line 101 interpolates the value straight into generated source as revalidate: ${r.revalidate},. A non-number export produces a generated entry that either fails to parse or carries unintended expressions. Example: a string export emits an unquoted token.

Reject non-finite values at the scan stage.

🛡️ Proposed fix
+    const revalidate =
+      typeof mod.revalidate === "number" && Number.isFinite(mod.revalidate) && mod.revalidate >= 0
+        ? mod.revalidate
+        : undefined;
+
     routes.push({
       routePath: entry.routePath,
       paramNames: entry.paramNames,
       isApi: false,
       mode: mod.mode ?? "server",
-      ...(mod.revalidate !== undefined ? { revalidate: mod.revalidate } : {}),
+      ...(revalidate !== undefined ? { revalidate } : {}),
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/adapter-vercel/src/scan.ts` around lines 104 - 125, Validate
mod.revalidate in the scan flow before adding it to the route manifest: only
propagate values that are numbers and finite, and reject or skip entries with
invalid exports. Update the revalidate handling in the module import and
routes.push path, ensuring generate-entry receives no non-numeric or non-finite
value.
🧹 Nitpick comments (5)
packages/adapter-vercel/src/index.ts (1)

70-70: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Hoist the .scratch-routes path into one constant.

Line 70 and line 93 repeat the same literal path. manifestScratchDir is declared inside try, so the finally block cannot reuse it. If one literal changes, cleanup silently stops removing the scratch directory. Declare the path next to coreOutDir.

♻️ Proposed refactor
   const coreOutDir = join(outputDir, ".scratch-core");
+  const manifestScratchDir = join(outputDir, ".scratch-routes");
   try {
     console.log("[adapter-vercel] resolving server-mode routes...");
-    const manifestScratchDir = join(outputDir, ".scratch-routes");
     const manifest = await resolveBuildManifest(options, manifestScratchDir);
   } finally {
     rmSync(coreOutDir, { recursive: true, force: true });
-    rmSync(join(outputDir, ".scratch-routes"), { recursive: true, force: true });
+    rmSync(manifestScratchDir, { recursive: true, force: true });
   }

Also applies to: 93-93

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/adapter-vercel/src/index.ts` at line 70, Hoist the `.scratch-routes`
path into a shared constant alongside `coreOutDir`, then reuse that constant for
both the `manifestScratchDir` assignment and the cleanup in the `finally` block.
Remove the inner declaration so both the main flow and cleanup reference the
same path.
packages/cli/src/index.ts (1)

267-268: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Report a missing @thexjs/core install with an actionable message.

Bun.resolveSync throws a raw ResolveMessage if the project does not have @thexjs/core installed. The --adapter vercel branch at lines 243-249 handles the equivalent failure with xError and an install hint. This path prints a stack trace instead. The dev path changed at lines 161-162 has the same shape.

♻️ Proposed refactor
-  const corePath = Bun.resolveSync("`@thexjs/core`", projectDir);
-  const { build } = await import(corePath);
+  let build: (options: Record<string, unknown>) => Promise<void>;
+  try {
+    const corePath = Bun.resolveSync("`@thexjs/core`", projectDir);
+    ({ build } = await import(corePath));
+  } catch {
+    xError("could not resolve `@thexjs/core` from this project.");
+    xError("install it with: bun add `@thexjs/core`");
+    process.exit(1);
+  }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/index.ts` around lines 267 - 268, Wrap the `@thexjs/core`
resolution and import in the relevant build/dev paths around Bun.resolveSync,
including the branch containing corePath and the corresponding dev path, and
catch resolution failures to report them through the existing xError pattern
with an actionable `@thexjs/core` installation hint. Preserve successful
resolution and import behavior.
packages/core/src/createApp.ts (2)

845-881: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Confirm heartbeat cleanup on stream cancellation.

The heartbeat interval is cleared in two places: on a send throw and on req.signal abort. If Bun cancels the ReadableStream without aborting req.signal, the interval keeps running until the next send throws. Add a cancel() handler on the stream to clear the interval and delete the client. This removes the dependency on abort-signal timing.

♻️ Proposed cleanup hook
       start(controller) {
-        },
-      });
+        },
+        cancel() {
+          clearInterval(heartbeat);
+          sseClients.delete(send);
+        },
+      });

Note: heartbeat and send must be declared in the outer ReadableStream scope for cancel() to reach them.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/createApp.ts` around lines 845 - 881, Update the outer
ReadableStream setup around the heartbeat and send logic so both are declared in
scope for the stream’s cancel handler. Add cancel() cleanup that clears the
heartbeat interval and removes the client from sseClients, while preserving the
existing abort and send-failure cleanup behavior.

168-174: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use Blob as the runtime type for Bun.file() before constructing the response.

Bun.file() returns a Blob-compatible BunFile object, and new Response(file) is the documented response body pattern. Keep only { exists(): Promise<boolean> } / BodyInit in the inline Bun declaration, then construct new Response(file as Blob); this keeps BunFile.exists() available and avoids the wide unknown type.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/createApp.ts` around lines 168 - 174, The Bun runtime
declaration in the static asset handler should continue exposing file.exists()
while treating Bun.file()’s result as Blob-compatible. Update the Response
construction in the Bun file-serving flow to cast file to Blob instead of
unknown as BodyInit, while preserving the existing existence check and non-Bun
behavior.
packages/core/src/server-functions.ts (1)

88-93: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Line 89 is dead code.

String.prototype.split always returns at least one element, so parts.length < 1 is never true. Even for the path /__x/actions/, parts is [""]. The empty case is already handled by the !actionName check on line 92. Remove the unreachable guard.

♻️ Proposed cleanup
     const parts = url.pathname.replace("/__x/actions/", "").split("/");
-    if (parts.length < 1) return null;
-
     const actionName = parts.pop();
     if (!actionName) return null;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/server-functions.ts` around lines 88 - 93, Remove the
unreachable guard `if (parts.length < 1) return null;` from the server-functions
path-parsing logic. The guard is dead code because String.prototype.split always
returns at least one element, and the actual empty case is already handled by
the subsequent `if (!actionName) return null;` check. Preserve the actionName
validation and the concretePath assignment that follows.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/src/createApp.ts`:
- Around line 477-534: Update the preloaded branch of buildHandlers to perform
the same resetServerFunctions cleanup before registering route actions, ensuring
repeated builds remove stale exports. Also process options.contentDir in this
branch by scanning it and populating contentHandlers with the expected content
handlers before returning, so preloaded apps serve configured content
consistently.
- Around line 412-451: Update the static cache access in the route handler to
key entries by the concrete request pathname, including params as needed,
instead of route.routePath. Use the same pathname-based key when reading and
writing staticCache, and ensure it matches the body.path key used by
handleRevalidation for targeted invalidation.
- Around line 319-347: Restrict dispatch in makeApiHandler to the fixed HTTP
method allow-list before accessing module[method], preserving case-sensitive
method handling. Require Object.hasOwn(module, method) before invoking a
function so exported handlers and only own allow-listed properties are
reachable, while unsupported methods continue returning 405.

In `@packages/core/src/data/sqlite.ts`:
- Around line 16-24: Update loadBunSQLite to capture the caught error and
preserve it as the cause when throwing the runtime error, while keeping the
existing message for unavailable bun:sqlite. This must allow callers to
distinguish module absence from initialization failures without changing the
successful require path.

---

Outside diff comments:
In `@packages/adapter-vercel/src/generate-entry.ts`:
- Around line 178-189: Update the generated handler’s catch block around
__x_app.fetch and sendWebResponse to check res.headersSent before writing the
500 response. If headers have already been sent, destroy the response/socket
without appending an error body; otherwise preserve the existing statusCode 500
and “Internal server error” response.

In `@packages/adapter-vercel/src/scan.ts`:
- Around line 104-125: Validate mod.revalidate in the scan flow before adding it
to the route manifest: only propagate values that are numbers and finite, and
reject or skip entries with invalid exports. Update the revalidate handling in
the module import and routes.push path, ensuring generate-entry receives no
non-numeric or non-finite value.

---

Nitpick comments:
In `@packages/adapter-vercel/src/index.ts`:
- Line 70: Hoist the `.scratch-routes` path into a shared constant alongside
`coreOutDir`, then reuse that constant for both the `manifestScratchDir`
assignment and the cleanup in the `finally` block. Remove the inner declaration
so both the main flow and cleanup reference the same path.

In `@packages/cli/src/index.ts`:
- Around line 267-268: Wrap the `@thexjs/core` resolution and import in the
relevant build/dev paths around Bun.resolveSync, including the branch containing
corePath and the corresponding dev path, and catch resolution failures to report
them through the existing xError pattern with an actionable `@thexjs/core`
installation hint. Preserve successful resolution and import behavior.

In `@packages/core/src/createApp.ts`:
- Around line 845-881: Update the outer ReadableStream setup around the
heartbeat and send logic so both are declared in scope for the stream’s cancel
handler. Add cancel() cleanup that clears the heartbeat interval and removes the
client from sseClients, while preserving the existing abort and send-failure
cleanup behavior.
- Around line 168-174: The Bun runtime declaration in the static asset handler
should continue exposing file.exists() while treating Bun.file()’s result as
Blob-compatible. Update the Response construction in the Bun file-serving flow
to cast file to Blob instead of unknown as BodyInit, while preserving the
existing existence check and non-Bun behavior.

In `@packages/core/src/server-functions.ts`:
- Around line 88-93: Remove the unreachable guard `if (parts.length < 1) return
null;` from the server-functions path-parsing logic. The guard is dead code
because String.prototype.split always returns at least one element, and the
actual empty case is already handled by the subsequent `if (!actionName) return
null;` check. Preserve the actionName validation and the concretePath assignment
that follows.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 46d1e65b-4f03-42a3-8420-72653f02f146

📥 Commits

Reviewing files that changed from the base of the PR and between e82c1ef and 8c1309b.

📒 Files selected for processing (19)
  • .gitignore
  • examples/basic/.gitignore
  • examples/landing/.gitignore
  • packages/adapter-vercel/src/generate-entry.ts
  • packages/adapter-vercel/src/index.ts
  • packages/adapter-vercel/src/scan.ts
  • packages/adapter-vercel/src/transpile.ts
  • packages/adapter-vercel/src/types.ts
  • packages/adapter-vercel/src/write-output.ts
  • packages/cli/src/index.ts
  • packages/core/src/build.ts
  • packages/core/src/createApp.ts
  • packages/core/src/data/sqlite.ts
  • packages/core/src/server-functions.ts
  • packages/create-thexjs-app/templates/basic/.gitignore
  • packages/create-thexjs-app/templates/blog/.gitignore
  • packages/create-thexjs-app/templates/default/.gitignore
  • packages/create-thexjs-app/templates/landing/.gitignore
  • packages/create-thexjs-app/templates/saas/.gitignore
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/build.ts

Comment thread packages/core/src/createApp.ts Outdated
Comment on lines +319 to +347
const makeApiHandler = (
route: RouteEntry,
module: Record<string, unknown>,
): ((req: Request) => Promise<Response>) =>
async (req: Request) => {
try {
const method = req.method;
const handlerFn = module[method];
if (typeof handlerFn === "function") {
const result = await (handlerFn as (r: Request) => unknown)(req);
if (result instanceof Response) return result;
if (result === undefined || result === null) {
return new Response("OK", { status: 200 });
}
return Response.json(result);
}
return new Response(`Method ${method} not allowed`, { status: 405 });
} catch (err) {
reportException(err, { route: route.routePath, phase: "api" });
console.error("[x] API handler error:", err);
if (dev) {
return new Response(renderErrorOverlay(err), {
status: 500,
headers: { "Content-Type": "text/html; charset=utf-8" },
});
}
return new Response("Internal server error", { status: 500 });
}
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Restrict API dispatch to an HTTP method allow-list.

module[method] uses the raw request method as a property key. The previous HTTP_METHODS declaration was removed, so dispatch is now unbounded over module exports and the prototype chain. A request with method middleware, loader, or constructor resolves a function and invokes it with the Request. HTTP method tokens are case-sensitive and are not normalized for non-standard values, so these keys are reachable. For preloaded routes module is a plain object, so Object.prototype members are also reachable.

Validate the method against a fixed set before lookup, and read the property with Object.hasOwn.

🔒️ Proposed fix to bound method dispatch
+const HTTP_METHODS = new Set([
+  "GET",
+  "HEAD",
+  "POST",
+  "PUT",
+  "PATCH",
+  "DELETE",
+  "OPTIONS",
+]);
+
   const makeApiHandler = (
     route: RouteEntry,
     module: Record<string, unknown>,
   ): ((req: Request) => Promise<Response>) =>
     async (req: Request) => {
       try {
         const method = req.method;
-        const handlerFn = module[method];
+        const handlerFn = HTTP_METHODS.has(method) && Object.hasOwn(module, method)
+          ? module[method]
+          : undefined;
         if (typeof handlerFn === "function") {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const makeApiHandler = (
route: RouteEntry,
module: Record<string, unknown>,
): ((req: Request) => Promise<Response>) =>
async (req: Request) => {
try {
const method = req.method;
const handlerFn = module[method];
if (typeof handlerFn === "function") {
const result = await (handlerFn as (r: Request) => unknown)(req);
if (result instanceof Response) return result;
if (result === undefined || result === null) {
return new Response("OK", { status: 200 });
}
return Response.json(result);
}
return new Response(`Method ${method} not allowed`, { status: 405 });
} catch (err) {
reportException(err, { route: route.routePath, phase: "api" });
console.error("[x] API handler error:", err);
if (dev) {
return new Response(renderErrorOverlay(err), {
status: 500,
headers: { "Content-Type": "text/html; charset=utf-8" },
});
}
return new Response("Internal server error", { status: 500 });
}
};
const HTTP_METHODS = new Set([
"GET",
"HEAD",
"POST",
"PUT",
"PATCH",
"DELETE",
"OPTIONS",
]);
const makeApiHandler = (
route: RouteEntry,
module: Record<string, unknown>,
): ((req: Request) => Promise<Response>) =>
async (req: Request) => {
try {
const method = req.method;
const handlerFn = HTTP_METHODS.has(method) && Object.hasOwn(module, method)
? module[method]
: undefined;
if (typeof handlerFn === "function") {
const result = await (handlerFn as (r: Request) => unknown)(req);
if (result instanceof Response) return result;
if (result === undefined || result === null) {
return new Response("OK", { status: 200 });
}
return Response.json(result);
}
return new Response(`Method ${method} not allowed`, { status: 405 });
} catch (err) {
reportException(err, { route: route.routePath, phase: "api" });
console.error("[x] API handler error:", err);
if (dev) {
return new Response(renderErrorOverlay(err), {
status: 500,
headers: { "Content-Type": "text/html; charset=utf-8" },
});
}
return new Response("Internal server error", { status: 500 });
}
};
🧰 Tools
🪛 GitHub Actions: CI / 0_test.txt

[error] 319-322: Biome formatter check failed. Reformat the makeApiHandler declaration, or run 'biome check --fix --unsafe'.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/createApp.ts` around lines 319 - 347, Restrict dispatch in
makeApiHandler to the fixed HTTP method allow-list before accessing
module[method], preserving case-sensitive method handling. Require
Object.hasOwn(module, method) before invoking a function so exported handlers
and only own allow-listed properties are reachable, while unsupported methods
continue returning 405.

Comment on lines +412 to +451
const cached = staticCache.get(route.routePath);
const revalidateSeconds = revalidate ?? 0;

if (
revalidateSeconds > 0 &&
cached &&
Date.now() - cached.timestamp < revalidateSeconds * 1000
) {
return new Response(cached.html, {
headers: { "Content-Type": "text/html; charset=utf-8", "X-Revalidated": "hit" },
});
}

const registry = createIslandRegistry();
const content = createElement(
IslandProvider,
{ registry },
wrapWithLayouts(Component, ctx.params, loaderData, layoutModules),
);
let scripts: string[] | undefined = islandScripts;
if (scripts === undefined) {
renderPage(content, { stylesheet: stylesheetHref, liveReload: dev });
scripts = await resolveIslandScripts(route.filePath, layoutFilePaths, registry.entries);
}
const html = renderPage(content, {
stylesheet: stylesheetHref,
liveReload: dev,
islandScripts: scripts,
});

if (revalidateSeconds > 0) {
staticCache.set(route.routePath, { html, timestamp: Date.now() });
}

return new Response(html, {
headers: {
"Content-Type": "text/html; charset=utf-8",
"X-Revalidated": revalidateSeconds > 0 ? "miss" : "none",
},
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Key the static cache by request pathname, not by route pattern.

staticCache uses route.routePath, which is the route pattern. For a dynamic static route such as /posts/[slug], the first request caches HTML for one slug and later requests for other slug values receive that same HTML while revalidateSeconds > 0. Loader data and params are then wrong for those responses.

Use the concrete pathname (plus params) as the cache key. Note that handleRevalidation deletes by body.path, so a pathname key also makes targeted revalidation work for dynamic routes.

🐛 Proposed fix for the cache key
-          const cached = staticCache.get(route.routePath);
+          const cacheKey = new URL(ctx.request.url).pathname;
+          const cached = staticCache.get(cacheKey);
           const revalidateSeconds = revalidate ?? 0;
@@
           if (revalidateSeconds > 0) {
-            staticCache.set(route.routePath, { html, timestamp: Date.now() });
+            staticCache.set(cacheKey, { html, timestamp: Date.now() });
           }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const cached = staticCache.get(route.routePath);
const revalidateSeconds = revalidate ?? 0;
if (
revalidateSeconds > 0 &&
cached &&
Date.now() - cached.timestamp < revalidateSeconds * 1000
) {
return new Response(cached.html, {
headers: { "Content-Type": "text/html; charset=utf-8", "X-Revalidated": "hit" },
});
}
const registry = createIslandRegistry();
const content = createElement(
IslandProvider,
{ registry },
wrapWithLayouts(Component, ctx.params, loaderData, layoutModules),
);
let scripts: string[] | undefined = islandScripts;
if (scripts === undefined) {
renderPage(content, { stylesheet: stylesheetHref, liveReload: dev });
scripts = await resolveIslandScripts(route.filePath, layoutFilePaths, registry.entries);
}
const html = renderPage(content, {
stylesheet: stylesheetHref,
liveReload: dev,
islandScripts: scripts,
});
if (revalidateSeconds > 0) {
staticCache.set(route.routePath, { html, timestamp: Date.now() });
}
return new Response(html, {
headers: {
"Content-Type": "text/html; charset=utf-8",
"X-Revalidated": revalidateSeconds > 0 ? "miss" : "none",
},
});
const cacheKey = new URL(ctx.request.url).pathname;
const cached = staticCache.get(cacheKey);
const revalidateSeconds = revalidate ?? 0;
if (
revalidateSeconds > 0 &&
cached &&
Date.now() - cached.timestamp < revalidateSeconds * 1000
) {
return new Response(cached.html, {
headers: { "Content-Type": "text/html; charset=utf-8", "X-Revalidated": "hit" },
});
}
const registry = createIslandRegistry();
const content = createElement(
IslandProvider,
{ registry },
wrapWithLayouts(Component, ctx.params, loaderData, layoutModules),
);
let scripts: string[] | undefined = islandScripts;
if (scripts === undefined) {
renderPage(content, { stylesheet: stylesheetHref, liveReload: dev });
scripts = await resolveIslandScripts(route.filePath, layoutFilePaths, registry.entries);
}
const html = renderPage(content, {
stylesheet: stylesheetHref,
liveReload: dev,
islandScripts: scripts,
});
if (revalidateSeconds > 0) {
staticCache.set(cacheKey, { html, timestamp: Date.now() });
}
return new Response(html, {
headers: {
"Content-Type": "text/html; charset=utf-8",
"X-Revalidated": revalidateSeconds > 0 ? "miss" : "none",
},
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/createApp.ts` around lines 412 - 451, Update the static
cache access in the route handler to key entries by the concrete request
pathname, including params as needed, instead of route.routePath. Use the same
pathname-based key when reading and writing staticCache, and ensure it matches
the body.path key used by handleRevalidation for targeted invalidation.

Comment on lines 477 to +534
async function buildHandlers(): Promise<void> {
if (options.preloaded) {
const preloaded = options.preloaded;
const candidatePublicDir = join(projectRoot, "public");
publicDir = existsSync(candidatePublicDir) ? candidatePublicDir : null;
stylesheetHref =
publicDir && existsSync(join(publicDir, "styles.css")) ? "/styles.css" : undefined;
if (preloaded.notFoundComponent) notFoundComponent = preloaded.notFoundComponent;
if (preloaded.notFoundLayout) notFoundLayout = preloaded.notFoundLayout;

const loaded: RouteHandler[] = [];
for (const p of preloaded.routes) {
const actions = p.module.actions as
| Record<string, (...args: unknown[]) => Promise<unknown>>
| undefined;
if (actions) {
registerServerFunctions(p.entry.routePath, p.entry.paramNames, actions);
}

if (p.entry.isApi) {
loaded.push({
entry: p.entry,
mode: p.mode,
revalidate: undefined,
handler: makeApiHandler(p.entry, p.module),
});
continue;
}

const Component = p.module.default as ComponentType<RouteProps> | undefined;
if (!Component) continue;

const routeMiddleware = p.module.middleware as MiddlewareFn | undefined;
const middlewareModules = routeMiddleware
? [...p.middlewareModules, routeMiddleware]
: p.middlewareModules;

loaded.push({
entry: p.entry,
mode: p.mode,
revalidate: p.revalidate,
handler: makePageHandler({
route: p.entry,
mode: p.mode,
revalidate: p.revalidate,
loader: p.module.loader as ((args: LoaderArgs) => Promise<LoaderReturn>) | undefined,
Component,
layoutModules: p.layoutModules,
layoutFilePaths: p.layoutFilePaths ?? [],
middlewareModules,
islandScripts: p.islandScripts,
}),
});
}
handlers = loaded;
return;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Who builds the preloaded manifest, and does it carry content routes or reset actions?
rg -n 'preloaded|PreloadedAppManifest|PreloadedRoute|contentDir|resetServerFunctions' \
  packages -g '*.ts' -g '*.tsx' -C3

Repository: abdelkabirouadoukou/x

Length of output: 22252


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== createApp relevant regions =="
sed -n '80,120p' packages/core/src/createApp.ts
sed -n '460,750p' packages/core/src/createApp.ts

echo "== server-functions definitions/registration =="
sed -n '1,90p' packages/core/src/server-functions.ts

echo "== Vercel generated entry preloaded manifest =="
sed -n '70,145p' packages/adapter-vercel/src/generate-entry.ts

echo "== build server entry server options =="
sed -n '256,286p' packages/core/src/build.ts

echo "== content scanning/handlers in createApp/build =="
rg -n "contentHandlers|scanContent|routePath: .*content|contentRoute|isContent|ContentEntry|ContentHandler" packages/core/src -g '*.ts' -C3

echo "== generated source usage of preloaded/contentHandlers/APP =="
rg -n "__x_preloadedRoutes|contentHandlers|createApp|contentDir" packages/adapter-vercel packages/core -g '*.ts' -g '*.tsx' -C2

Repository: abdelkabirouadoukou/x

Length of output: 43837


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Vercel scan.ts =="
sed -n '1,180p' packages/adapter-vercel/src/scan.ts

echo "== createApp dev watch/buildHandlers loop and request handling =="
sed -n '740,975p' packages/core/src/createApp.ts

echo "== static file/content 404 behavior =="
sed -n '850,975p' packages/core/src/createApp.ts
sed -n '1,180p' packages/core/src/not-found.tsx

echo "== package config/type declarations around preloaded/contentDir =="
rg -n "preloaded|contentDir" packages -g '*.ts' -g '*.tsx' -g '*.json' -g '*.d.ts' -C2

Repository: abdelkabirouadoukou/x

Length of output: 35367


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== content.ts scan/render =="
sed -n '1,120p' packages/core/src/content.ts

echo "== createApp imports/content API =="
sed -n '200,50p' packages/core/src/createApp.ts

echo "== preloaded manifest shape/types =="
rg -n "interface BuildManifest|interface ResolvedRoute|preloadedRoutes|contentEntries|contentDir" packages/adapter-vercel/src packages/core/src/build.ts packages/core/src/createApp.ts -g '*.ts' -C2

Repository: abdelkabirouadoukou/x

Length of output: 9288


Handle resetServerFunctions() and contentDir in the preloaded path.

The preloaded branch skips the filesystem reset before registering actions, so a second buildHandlers() call can leave stale action exports registered. It also leaves contentHandlers empty because options.contentDir is ignored, while request pipelines still expect populated content handlers. If preloaded apps must serve contentDir, add the scan/handlers and resets to this branch.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/createApp.ts` around lines 477 - 534, Update the preloaded
branch of buildHandlers to perform the same resetServerFunctions cleanup before
registering route actions, ensuring repeated builds remove stale exports. Also
process options.contentDir in this branch by scanning it and populating
contentHandlers with the expected content handlers before returning, so
preloaded apps serve configured content consistently.

Comment on lines +16 to +24
function loadBunSQLite(): { Database: typeof Database } {
try {
return require("bun:sqlite") as { Database: typeof Database };
} catch {
throw new Error(
"connectSQLite requires the Bun runtime (bun:sqlite). Use connectPostgres on non-Bun runtimes like Vercel.",
);
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Bun require("bun:sqlite") createRequire node:module support builtin modules

💡 Result:

In Bun, bun:sqlite is a high-performance, built-in SQLite driver [1][2], while node:sqlite (the module added to Node.js v22.5+) is not implemented [3]. Because bun:sqlite and node:sqlite are distinct modules, codebases aiming for cross-runtime compatibility (Node.js and Bun) typically cannot use a single import statement. Instead, developers often use node:module's createRequire or conditional imports to dynamically detect the environment and load the appropriate driver [4][5][6][7][8]. Key Technical Points: 1. Bun Support for node:module: Bun fully implements the node:module API, including createRequire, which allows for consistent ESM/CJS interaction and the ability to load built-in modules dynamically [9][10]. 2. Driver Selection Pattern: A common pattern in cross-runtime projects is to use createRequire(import.meta.url) to attempt loading node:sqlite (for Node.js) and fallback to bun:sqlite (for Bun) if the former fails [5][6][7]. 3. bun:sqlite vs node:sqlite: While both are synchronous and share similar APIs, they are not interchangeable imports [11]. Developers must either fork their logic based on the detected runtime or use an adapter pattern to wrap the differences [4][8]. Example of the adapter pattern used in the ecosystem: import { createRequire } from "node:module"; const require = createRequire(import.meta.url); let Database; try { // Attempt to load Node's native module Database = require("node:sqlite").DatabaseSync; } catch { // Fallback to Bun's built-in Database = require("bun:sqlite").Database; }

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '--- locate sqlite.ts ---\n'
fd -a sqlite.ts . | sed 's#^\./##'

printf '\n--- relevant file outline ---\n'
ast-grep outline packages/core/src/data/sqlite.ts || true

printf '\n--- file contents ---\n'
cat -n packages/core/src/data/sqlite.ts

printf '\n--- package/runtime config ---\n'
for f in package.json packages/core/package.json bunfig.toml tsconfig.json packages/core/tsconfig.json; do
  if [ -f "$f" ]; then
    echo "### $f"
    sed -n '1,220p' "$f"
  fi
done

printf '\n--- imports/uses and createRequire ---\n'
rg -n "connectSQLite|loadBunSQLite|createRequire|bun:sqlite|Database" packages/core/src data packages || true

Repository: abdelkabirouadoukou/x

Length of output: 250


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- locate sqlite.ts ---'
fd -a sqlite.ts . | sed 's#^\./##'

printf '%s\n' ''
printf '%s\n' '--- relevant file outline ---'
ast-grep outline packages/core/src/data/sqlite.ts || true

printf '%s\n' ''
printf '%s\n' '--- file contents ---'
cat -n packages/core/src/data/sqlite.ts

printf '%s\n' ''
printf '%s\n' '--- package/runtime config ---'
for f in package.json packages/core/package.json bunfig.toml tsconfig.json packages/core/tsconfig.json; do
  if [ -f "$f" ]; then
    echo "### $f"
    sed -n '1,220p' "$f"
  fi
done

printf '%s\n' ''
printf '%s\n' '--- imports/uses and createRequire ---'
rg -n "connectSQLite|loadBunSQLite|createRequire|bun:sqlite|Database" packages/core/src data packages || true

Repository: abdelkabirouadoukou/x

Length of output: 10033


🌐 Web query:

Bun node:module createRequire require builtin builtins node module

💡 Result:

Bun provides full support for the node:module module, including the createRequire function [1][2]. The createRequire function is used to construct a require function in Bun, similar to how it works in Node.js [1][3][4]. When using it, you must provide a filename as a file URL object, file URL string, or absolute path string [1][5]. Key details regarding createRequire and builtins in Bun: - Compatibility: Bun implements the standard Node.js node:module API [1][2]. - Implementation: Bun's implementation of createRequire creates a bound require function that follows Node.js conventions for loading CommonJS modules [6][7]. - Builtin Modules: Bun supports the full suite of Node.js builtin modules [1][2]. You can use the isBuiltin function from node:module to verify if a module is a builtin [1]. The builtinModules property provides an array of the names of these modules [1]. In modern Bun projects, while native ES modules are recommended, createRequire remains available for interoperability with CommonJS-based workflows or for loading specific modules that require synchronous resolution [8]. If you are working in an ES module context, you can import createRequire directly from node:module: import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);

Citations:


🌐 Web query:

Node.js node:module createRequire supports node: builtin modules require

💡 Result:

Yes, the require function created by module.createRequire supports the loading of Node.js built-in modules, including those referenced via the node: protocol [1][2]. The createRequire function is designed to construct a require function that mimics the behavior of the standard CommonJS require found in CJS modules [1][3]. Because this custom require function has access to the Node.js module resolution system, it can resolve and load both CommonJS dependencies and Node.js built-in modules (e.g., node:fs, node:path) [1][2]. This remains consistent across modern versions of Node.js [1][4].

Citations:


🌐 Web query:

@types/bun bun:sqlite import types TypeScript

💡 Result:

To use the built-in SQLite driver in Bun with TypeScript, you do not need to install separate @types packages. The TypeScript type definitions for the bun:sqlite module are included in the bun-types package, which is part of the Bun runtime environment [1]. When running Bun code with TypeScript, these types are automatically available [1]. You can import the necessary classes directly from the bun:sqlite module [2][3]: import { Database } from "bun:sqlite"; Key Usage Notes for TypeScript: 1. Type Safety with Generics: You can define the return type and parameter type for your queries using generics on the query method [2][4]. This provides compile-time type checking for both the results you receive and the parameters you bind [4]. Example: // Generic syntax: db.query<ReturnType, ParamsType>(sql) const query = db.query<User, { id: number }>("SELECT * FROM users WHERE id = $id"); const user = query.get({ id: 1 }); 2. Parameter Binding: Bun's SQLite driver supports various JavaScript types that map to SQLite types [5][3]. For example, strings map to TEXT, numbers to INTEGER/DECIMAL, and Uint8Array/Buffer to BLOB [3][6]. 3. Type Definitions: The official definitions are located within the bun-types repository [1] and are automatically resolved by the Bun runtime [1]. There is no need for a manual @types/bun installation to access these core SQLite types, as they are bundled with the runtime's internal types [1].

Citations:


Preserve the original load error.

The current catch only checks whether bun:sqlite is unavailable. If bun:sqlite exists but fails to initialize, the thrown message says a Bun runtime is missing. Keep the original error as the cause so callers can distinguish an initialization failure from a missing module.

🛡️ Proposed fix
 function loadBunSQLite(): { Database: typeof Database } {
   try {
     return require("bun:sqlite") as { Database: typeof Database };
-  } catch {
+  } catch (err) {
     throw new Error(
       "connectSQLite requires the Bun runtime (bun:sqlite). Use connectPostgres on non-Bun runtimes like Vercel.",
+      { cause: err },
     );
   }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function loadBunSQLite(): { Database: typeof Database } {
try {
return require("bun:sqlite") as { Database: typeof Database };
} catch {
throw new Error(
"connectSQLite requires the Bun runtime (bun:sqlite). Use connectPostgres on non-Bun runtimes like Vercel.",
);
}
}
function loadBunSQLite(): { Database: typeof Database } {
try {
return require("bun:sqlite") as { Database: typeof Database };
} catch (err) {
throw new Error(
"connectSQLite requires the Bun runtime (bun:sqlite). Use connectPostgres on non-Bun runtimes like Vercel.",
{ cause: err },
);
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/data/sqlite.ts` around lines 16 - 24, Update loadBunSQLite
to capture the caught error and preserve it as the cause when throwing the
runtime error, while keeping the existing message for unavailable bun:sqlite.
This must allow callers to distinguish module absence from initialization
failures without changing the successful require path.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/src/render.ts`:
- Line 83: Update buildIslandBundleInMemory and the island script rendering used
by renderPage, renderStaticPage, and renderStreamingPage so the generated bundle
format matches the emitted script tag: either configure Bun.build with a classic
format such as IIFE, or restore type="module" on the tags. Preserve consistent
browser-compatible loading across all three rendering paths.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 9779c8d7-c93d-4333-b470-cec587101701

📥 Commits

Reviewing files that changed from the base of the PR and between 8c1309b and 641a080.

📒 Files selected for processing (9)
  • biome.json
  • packages/adapter-vercel/src/generate-entry.ts
  • packages/adapter-vercel/src/scan.ts
  • packages/adapter-vercel/src/transpile.ts
  • packages/cli/src/index.ts
  • packages/core/src/createApp.ts
  • packages/core/src/data/sqlite.ts
  • packages/core/src/phase3.test.ts
  • packages/core/src/render.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • packages/adapter-vercel/src/scan.ts
  • packages/adapter-vercel/src/transpile.ts
  • packages/core/src/data/sqlite.ts
  • packages/adapter-vercel/src/generate-entry.ts
  • packages/core/src/createApp.ts

Comment thread packages/core/src/render.ts Resolved
…t nesting and add error handling for recoverable hydration issues
…al leakage and enhance command palette functionality
@abdelkabirouadoukou
abdelkabirouadoukou merged commit 15143a9 into main Jul 31, 2026
4 of 5 checks passed
@abdelkabirouadoukou
abdelkabirouadoukou deleted the redesign-landing-page branch August 1, 2026 04:37

This branch had an error being deployed

1 failed and 1 active deployments
Preview – x — 8226cd9a Deployed Jul 31, 2026 by vercel[bot]
Preview – thexjs-basic — 8226cd9a Deployed Jul 31, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant