From 1e876c503db9497d214351e9ac514c4c5ca5b88e Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 00:14:25 +0530 Subject: [PATCH 01/29] fix: answer notFound and forbidden over RPC with their status A forbidden(), notFound() or unauthorized() thrown in a server action called from a component answered a logged 500, while the no-JS form path rendered the right 403, 404 or 401. An agent building on the scaffold spent six turns reading actions.js to find out why. RPC now answers the same status with the kind in x-webjs-control, never hands it to onError, and the stub and invokeActionForTest rethrow the sentinel so isForbidden(err) holds in the caller. Refs #1697 --- packages/server/AGENTS.md | 2 +- packages/server/src/action-error.js | 24 +++++ packages/server/src/actions.js | 29 +++++- packages/server/src/testing.js | 8 +- .../actions/action-control-flow-rpc.test.js | 91 +++++++++++++++++++ .../actions/action-error-sanitization.test.js | 3 +- test/bun/action-control-flow-rpc.mjs | 63 +++++++++++++ .../app/(site)/docs/error-handling/page.ts | 4 +- .../app/(site)/docs/server-actions/page.ts | 2 +- 9 files changed, 218 insertions(+), 8 deletions(-) create mode 100644 packages/server/test/actions/action-control-flow-rpc.test.js create mode 100644 test/bun/action-control-flow-rpc.mjs diff --git a/packages/server/AGENTS.md b/packages/server/AGENTS.md index 22fde30d1..a70b54212 100644 --- a/packages/server/AGENTS.md +++ b/packages/server/AGENTS.md @@ -57,7 +57,7 @@ with metadata, Suspense, streaming) for HTML, or `api.js` / | `actions.js` | `.server.js` / `.server.ts` scanner. Generates RPC stubs for browser-bound imports and serves the RPC endpoints. `buildActionIndex` is a pure file -> hash mapping (loads no module). The generated stub reads the SSR seed before its `fetch` (#472): `__call(fn, args)` computes `stringify(args)` (both the seed lookup key and the RPC body) and returns `takeSeed(hash, fn, key)` on a hit, else POSTs; so a seeded first call does no network and a later refetch / arg-change misses and goes to RPC. **Input validation (#245):** `runValidate(validate, input)` is the shared seam the RPC path and the `route()` REST adapter route through, so a validator declared via the `validate` config export (#488) interprets a `{ success, fieldErrors }` envelope, a throw, and a transform-return identically across transports. `invokeAction` (RPC) runs it on the first arg before the body, returning a `{ success: false, fieldErrors, status: 422 }` envelope as a normal 200 RPC payload on a structured failure (the client reads `result.fieldErrors`) and a sanitized error response on a throw (#749: `actionErrorResponse` returns a GENERIC message + a correlation `digest` in prod via `action-error.js`, never the raw message, the full error logged server-side; `redirect()` / `notFound()` sentinels pass through). A public REST endpoint is a `route.ts` that imports and calls the action (optionally via the `route()` adapter in `action-route.js`). **Streaming results (#489):** when a completed action returns a streamable value (`isStreamable` from `action-stream.js`), `invokeAction` returns `streamActionResponse` instead of buffering; the generated stub carries a `__readStream` decode path its `__handle` dispatches to on the `application/vnd.webjs+stream` content type | | `action-route.js` | The optional `route(action, opts?)` adapter (#488): wraps a plain `'use server'` action as a `route.ts`-style handler `(req, ctx?) => Promise`, merging `{ ...query, ...params, ...jsonBody }` into the single input object, running the optional `opts.validate` through the shared `runValidate` seam (422 on a structured failure or a schema library's throw, with its issues as `fieldErrors` plus the raw `issues`; 400 on any other thrown validator), and dispatching through `runWithActionSignal` + the `opts.middleware` chain. A returned `Response` passes through verbatim; otherwise the result is `Response.json`'d. The always-works baseline is a hand-written `route.ts` that imports and calls the action; this adapter is the one-liner convenience | | `action-stream.js` | Streaming RPC results (#489), server side. `isStreamable(value)` detects a return value that should stream (a web `ReadableStream`, an async iterable, an async generator, a Node `Readable`; NOT a plain object / array / string / Promise / ActionResult). `streamActionResponse(source, { signal, onError, headers })` builds the `application/vnd.webjs+stream` `Response`: a back-pressured `ReadableStream` of frames (one rich-serialized CHUNK per source value via core's `encodeFrame`, a terminal END, or an ERROR frame carrying a SANITIZED message if the source throws mid-flight (#749: a generic message + a `digest` in prod via `action-error.js`, the real message in dev, a `redirect()` / `notFound()` sentinel passed through), since the 200 status is already sent). Back-pressure is real (chunks are pulled + serialized one at a time as the consumer reads); an aborted request signal (#492, client disconnect / superseded render) returns the source iterator, stopping a server generator. Wired in `actions.js`'s `invokeAction` after the action runs: a COMPLETED action whose result `isStreamable` streams (never cached / ETagged / seeded; a mutation still emits `X-Webjs-Invalidate`), a middleware short-circuit falls through to normal verb handling. The generated client stub's `__handle` branches on the stream content type and returns an async iterable the caller `for await`s | -| `action-error.js` | Server-action error sanitization (#749). `errorDigest(err)` is a short correlation hash (Web Crypto via `crypto-utils.js`) of the error message + stack, returned to the client AND logged server-side so a generic client error maps to the full log line; `isControlFlowThrow(err)` detects the `redirect()` / `notFound()` `__webjs` sentinels (passed through, not sanitized); `GENERIC_ERROR_MESSAGE` is the client-facing prod string. A leaf module so both the buffered path (`actions.js` `actionErrorResponse`) and the streaming path (`action-stream.js` error frame) import it without a cycle. The prod contract: a thrown action NEVER returns its raw message to the client (Postgres constraint names, internal IPs, fs paths are not author-controlled); a user-facing message rides the `ActionResult` `{ success: false, error }` envelope instead. The generated client stub and `invokeActionForTest` attach `digest` to the thrown error | +| `action-error.js` | Server-action error sanitization (#749). `errorDigest(err)` is a short correlation hash (Web Crypto via `crypto-utils.js`) of the error message + stack, returned to the client AND logged server-side so a generic client error maps to the full log line; `isControlFlowThrow(err)` detects the `redirect()` / `notFound()` `__webjs` sentinels (passed through, not sanitized); `controlFlowStatus(err)` maps `notFound()` / `forbidden()` / `unauthorized()` to 404 / 403 / 401, which `actions.js` answers over RPC with the kind in `x-webjs-control` and never hands to `onError` (#1697), and the generated stub and `invokeActionForTest` rethrow the matching sentinel; `GENERIC_ERROR_MESSAGE` is the client-facing prod string. A leaf module so both the buffered path (`actions.js` `actionErrorResponse`) and the streaming path (`action-stream.js` error frame) import it without a cycle. The prod contract: a thrown action NEVER returns its raw message to the client (Postgres constraint names, internal IPs, fs paths are not author-controlled); a user-facing message rides the `ActionResult` `{ success: false, error }` envelope instead. The generated client stub and `invokeActionForTest` attach `digest` to the thrown error | | `api.js` | `route.ts` `GET` / `POST` / `PUT` / `DELETE` handler dispatch | | `middleware-load.js` | Root and segment middleware, the Next.js way: the function is the default export, a named `middleware` or a named `proxy` (a root `proxy.{ts,js,mts,mjs}` file too, both files being a boot error), `export const config = { matcher }` compiled with `URLPattern` (string, array, `has` / `missing`), returning `undefined` continues, `next()` is memoized, `request.cookies` is the `cookies()` store, and `request.nextUrl` throws in dev. A load failure fails CLOSED. The wrapper and its compiled matcher are memoized per imported module object, since segment middleware is loaded on every request; a dev edit yields a new module (the re-import is keyed on content), so it gets a fresh wrapper. Tests: `test/dev/middleware-conventions.test.js` | | `auth.js` | `createAuth()` with Credentials / Google / GitHub providers; JWT signing. `readSession()` (reached by `auth()`) calls `markDynamicAccess()`, so an `auth()`-gated page is auto-excluded from the HTML cache even if it wrongly set `revalidate` (#241, the auth-path leak fix). The session-`user` type is opt-in (#451): the overlay exposes an augmentable `AuthUser` interface and a generic `createAuth()`, so `auth().user` can be typed with no cast and typo-checked, defaulting to `Record` when neither is used (types-only, no runtime effect) | diff --git a/packages/server/src/action-error.js b/packages/server/src/action-error.js index cf4d82ffb..dd56580d8 100644 --- a/packages/server/src/action-error.js +++ b/packages/server/src/action-error.js @@ -41,6 +41,30 @@ export function isControlFlowThrow(err) { return isRedirect(err) || isNotFound(err) || isForbidden(err) || isUnauthorized(err); } +/** + * The response header that names a `notFound()` / `forbidden()` / + * `unauthorized()` thrown by an action called over RPC. The generated stub + * reads it and rejects with the same sentinel, so `isForbidden(err)` holds on + * the client the way it does on the server. + */ +export const CONTROL_HEADER = 'x-webjs-control'; + +/** + * The status an RPC answers for a boundary sentinel thrown in an action: the + * same 404 / 403 / 401 the no-JS form path renders. Not an error, so it is + * never logged or sanitized. `null` for anything else (a redirect has its own + * branch). + * + * @param {unknown} err + * @returns {{ kind: 'not-found' | 'forbidden' | 'unauthorized', status: number } | null} + */ +export function controlFlowStatus(err) { + if (isNotFound(err)) return { kind: 'not-found', status: 404 }; + if (isForbidden(err)) return { kind: 'forbidden', status: 403 }; + if (isUnauthorized(err)) return { kind: 'unauthorized', status: 401 }; + return null; +} + /** * A short, stable correlation digest for a thrown error (a hash of its message * and stack). The SAME value is logged server-side and returned to the client, diff --git a/packages/server/src/actions.js b/packages/server/src/actions.js index a6eb74057..456e690b4 100644 --- a/packages/server/src/actions.js +++ b/packages/server/src/actions.js @@ -15,7 +15,7 @@ import { revalidateTags } from './cache-tags.js'; import { runWithActionSignal } from './action-signal.js'; import { runActionChain } from './action-middleware.js'; import { isStreamable, streamActionResponse } from './action-stream.js'; -import { isControlFlowThrow, errorDigest, GENERIC_ERROR_MESSAGE } from './action-error.js'; +import { isControlFlowThrow, controlFlowStatus, CONTROL_HEADER, errorDigest, GENERIC_ERROR_MESSAGE } from './action-error.js'; import { ifNoneMatchSatisfied } from './conditional-get.js'; import { getBodyLimits, refreshHeaderValue } from './context.js'; import { basePath } from './importmap.js'; @@ -372,7 +372,7 @@ function buildStubBody({ hash, method, fnNames, actionUrl }) { // `method` is a default POST), so the first client call resolves from the // seed with no hydration round-trip. The browser-cache staleness check is // GET-only (only a GET is browser-cached). - const imports = ['stringify as __s', 'parse as __p', 'takeSeed as __seedTake', 'SEED_MISS as __MISS', 'markStale as __markStale', 'parseTagHeader as __tagHdr', 'activeActionSignal as __sig', 'applyActionRefresh as __refresh', 'followActionRedirect as __redirect', 'installActionBind as __bindable', + const imports = ['stringify as __s', 'parse as __p', 'takeSeed as __seedTake', 'SEED_MISS as __MISS', 'markStale as __markStale', 'parseTagHeader as __tagHdr', 'activeActionSignal as __sig', 'applyActionRefresh as __refresh', 'followActionRedirect as __redirect', 'installActionBind as __bindable', 'notFound as __nf', 'forbidden as __fb', 'unauthorized as __ua', // Streaming RPC (#489): an action returning a stream / async iterable sends // back a framed body; the stub decodes it into an async iterable the caller // `for await`s. The imports are small constants + one decoder factory. @@ -396,6 +396,9 @@ function buildStubBody({ hash, method, fnNames, actionUrl }) { // redirect() in the action (Next parity): navigate there; the call's promise // rejects with the redirect sentinel, which the page ignores unhandled. lines.push(` const rd = res.headers.get('x-webjs-redirect'); if (rd) return __redirect(rd);`); + // notFound() / forbidden() / unauthorized() in the action: reject with the + // same sentinel, so `isForbidden(err)` holds in the caller's catch. + lines.push(` const cf = res.headers.get('x-webjs-control'); if (cf === 'not-found') __nf(); if (cf === 'forbidden') __fb(); if (cf === 'unauthorized') __ua();`); // revalidatePath() in the action: refresh the page on screen in place when // it was revalidated, BEFORE the caller's await resolves (Next behaviour). lines.push(` const rf = res.headers.get('x-webjs-refresh'); if (rf) await __refresh(rf);`); @@ -583,6 +586,8 @@ export async function invokeAction(idx, hash, fnName, req, onError, allowedOrigi // A THROWN validator behaves like a thrown action: a sanitized error // response (non-200, so the client stub throws), with prod stack // sanitization. The onError sink sees the original error too. + const cf = controlFlowStatus(v.thrown); + if (cf) return controlFlowResponse(v.thrown, cf); if (typeof onError === 'function') onError(v.thrown); return actionErrorResponse(v.thrown, idx.dev); } @@ -659,11 +664,31 @@ export async function invokeAction(idx, hash, fnName, req, onError, allowedOrigi if (refresh) headers['x-webjs-refresh'] = refresh; return rpcResponse(null, { headers: { ...headers, 'cache-control': 'no-store' } }); } + // notFound() / forbidden() / unauthorized() (Next.js parity with the + // no-JS form path): the same 404 / 403 / 401, not a logged 500. + const cf = controlFlowStatus(e); + if (cf) return controlFlowResponse(e, cf); if (typeof onError === 'function') onError(e); return actionErrorResponse(e, idx.dev); } } +/** + * The RPC answer for a boundary sentinel thrown in an action: its status, the + * kind in `x-webjs-control` for the stub to rethrow, never cached. + * + * @param {unknown} err + * @param {{ kind: string, status: number }} cf + * @returns {Promise} + */ +function controlFlowResponse(err, cf) { + const msg = err instanceof Error ? err.message : String(err); + return rpcResponse({ error: msg }, { + status: cf.status, + headers: { [CONTROL_HEADER]: cf.kind, 'cache-control': 'no-store' }, + }); +} + /** * Build a GET action's response (#488): the serialized body plus a weak ETag * (content hash), the `Cache-Control` from the `cache` config (else `no-store`), diff --git a/packages/server/src/testing.js b/packages/server/src/testing.js index 1665a3b97..451bbe7b6 100644 --- a/packages/server/src/testing.js +++ b/packages/server/src/testing.js @@ -33,7 +33,7 @@ */ import { hashFile, RPC_CONTENT_TYPE } from './actions.js'; -import { FORM_ACTION_FIELD, redirect } from '@webjsdev/core'; +import { FORM_ACTION_FIELD, redirect, notFound, forbidden, unauthorized } from '@webjsdev/core'; import { getSerializer } from './serializer.js'; import { join, sep } from 'node:path'; @@ -487,6 +487,12 @@ export async function invokeActionForTest(app, serverFilePath, fnName, args = [] const type = rd.slice(cut + 1) === 'replace' ? 'replace' : 'push'; redirect(cut === -1 ? rd : rd.slice(0, cut), type); } + // notFound() / forbidden() / unauthorized(): rethrow the sentinel, as the + // client stub does, so a test asserts with isForbidden(err). + const cf = res.headers.get('x-webjs-control'); + if (cf === 'not-found') notFound(); + if (cf === 'forbidden') forbidden(); + if (cf === 'unauthorized') unauthorized(); const ct = res.headers.get('content-type') || ''; let parsed; if (ct.includes(RPC_CONTENT_TYPE)) parsed = serializer.deserialize(text); diff --git a/packages/server/test/actions/action-control-flow-rpc.test.js b/packages/server/test/actions/action-control-flow-rpc.test.js new file mode 100644 index 000000000..2a858fcba --- /dev/null +++ b/packages/server/test/actions/action-control-flow-rpc.test.js @@ -0,0 +1,91 @@ +/** + * notFound() / forbidden() / unauthorized() inside a server action called over + * RPC answer the same 404 / 403 / 401 the no-JS form path renders (#1697), are + * never handed to the error sink as a failure, and the generated stub plus + * invokeActionForTest reject with the matching sentinel. They used to answer a + * logged 500, which an agent then spent turns chasing. + */ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, mkdir, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, resolve, dirname } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +import { buildActionIndex, resolveServerModule, invokeAction, serveActionStub, RPC_CONTENT_TYPE } from '../../src/actions.js'; +import { withRequest } from '../../src/context.js'; +import { createRequestHandler } from '../../src/dev.js'; +import { invokeActionForTest } from '../../src/testing.js'; +import { isNotFound, isForbidden, isUnauthorized } from '../../../core/src/nav.js'; +import { stringify as wjStringify, parse as wjParse } from '../../../core/src/serialize.js'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const CORE = pathToFileURL(resolve(__dirname, '../../../core/index.js')).toString(); + +async function scaffold() { + const dir = await mkdtemp(join(tmpdir(), 'webjs-rpc-control-')); + await mkdir(join(dir, 'actions'), { recursive: true }); + await writeFile(join(dir, 'package.json'), '{"name":"c","type":"module"}'); + await writeFile(join(dir, 'actions/guard.server.js'), `'use server'; + import { notFound, forbidden, unauthorized } from ${JSON.stringify(CORE)}; + export async function missing() { notFound(); } + export async function denied() { forbidden(); } + export async function anon() { unauthorized(); } + `); + await writeFile(join(dir, 'actions/checked.server.js'), `'use server'; + import { forbidden } from ${JSON.stringify(CORE)}; + export const validate = () => forbidden(); + export async function checked() { return 1; } + `); + return dir; +} + +async function call(dir, file, fn, dev, onError) { + const idx = await buildActionIndex(dir, dev); + const abs = resolveServerModule(idx, file); + const hash = idx.fileToHash.get(abs); + const req = new Request(`http://x/__webjs/action/${hash}/${fn}`, { + method: 'POST', + headers: { 'content-type': RPC_CONTENT_TYPE, 'sec-fetch-site': 'same-origin' }, + body: await wjStringify([]), + }); + return withRequest(req, () => invokeAction(idx, hash, fn, req, onError)); +} + +for (const [fn, status, kind] of [['missing', 404, 'not-found'], ['denied', 403, 'forbidden'], ['anon', 401, 'unauthorized']]) { + for (const dev of [true, false]) { + test(`${fn}() over RPC answers ${status} in ${dev ? 'dev' : 'prod'}, not a logged 500`, async () => { + const dir = await scaffold(); + const res = await call(dir, '/actions/guard.server.js', fn, dev, () => assert.fail('a boundary sentinel is not an error')); + assert.equal(res.status, status); + assert.equal(res.headers.get('x-webjs-control'), kind); + assert.equal(res.headers.get('cache-control'), 'no-store'); + const body = wjParse(await res.text()); + assert.match(body.error, /^webjs: /, 'the sentinel message, never the generic prod one'); + assert.equal(body.digest, undefined); + }); + } +} + +test('a validator that throws forbidden() answers 403 too', async () => { + const dir = await scaffold(); + const res = await call(dir, '/actions/checked.server.js', 'checked', false, () => assert.fail('not an error')); + assert.equal(res.status, 403); + assert.equal(res.headers.get('x-webjs-control'), 'forbidden'); +}); + +test('the generated stub rethrows the sentinel the header names', async () => { + const dir = await scaffold(); + const idx = await buildActionIndex(dir, false); + const stub = await serveActionStub(idx, resolveServerModule(idx, '/actions/guard.server.js')); + assert.match(stub, /notFound as __nf, forbidden as __fb, unauthorized as __ua/); + assert.match(stub, /x-webjs-control'\); if \(cf === 'not-found'\) __nf\(\); if \(cf === 'forbidden'\) __fb\(\); if \(cf === 'unauthorized'\) __ua\(\);/); +}); + +test('invokeActionForTest rejects with the sentinel, so isForbidden(err) holds', async () => { + const dir = await scaffold(); + const app = await createRequestHandler({ appDir: dir, dev: true }); + await assert.rejects(invokeActionForTest(app, 'actions/guard.server.js', 'denied'), (e) => isForbidden(e)); + await assert.rejects(invokeActionForTest(app, 'actions/guard.server.js', 'missing'), (e) => isNotFound(e)); + await assert.rejects(invokeActionForTest(app, 'actions/guard.server.js', 'anon'), (e) => isUnauthorized(e)); +}); diff --git a/packages/server/test/actions/action-error-sanitization.test.js b/packages/server/test/actions/action-error-sanitization.test.js index 55fc4adcd..f6cf14308 100644 --- a/packages/server/test/actions/action-error-sanitization.test.js +++ b/packages/server/test/actions/action-error-sanitization.test.js @@ -101,7 +101,8 @@ test('prod: a redirect()/notFound() control-flow throw passes through (not gener const orig = console.error; console.error = () => {}; try { const { res, body } = await callBoom(dir, false, 'cf'); - assert.equal(res.status, 500); + // A 404 since #1697, the status the no-JS form path renders. + assert.equal(res.status, 404); assert.equal(body.error, 'webjs: notFound()', 'control-flow message preserved'); assert.equal(body.digest, undefined, 'no digest for a control-flow sentinel'); } finally { diff --git a/test/bun/action-control-flow-rpc.mjs b/test/bun/action-control-flow-rpc.mjs new file mode 100644 index 000000000..5be2cbe23 --- /dev/null +++ b/test/bun/action-control-flow-rpc.mjs @@ -0,0 +1,63 @@ +/** + * Cross-runtime proof that notFound() / forbidden() / unauthorized() in a + * server action called over RPC answer 404 / 403 / 401 through the real + * listener, with the kind in x-webjs-control, the same status the no-JS form + * path renders (#1697). They used to answer a logged 500. + * + * node test/bun/action-control-flow-rpc.mjs + * bun test/bun/action-control-flow-rpc.mjs + */ +import assert from 'node:assert/strict'; +import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const CORE = pathToFileURL(resolve(__dirname, '../../packages/core/index.js')).toString(); +const { startServer } = await import(pathToFileURL(resolve(__dirname, '../../packages/server/index.js')).toString()); +const { stringify } = await import(pathToFileURL(resolve(__dirname, '../../packages/core/src/serialize.js')).toString()); +const runtime = process.versions.bun ? `bun ${process.versions.bun}` : `node ${process.versions.node}`; +const errors = []; +const quiet = { info() {}, warn() {}, error(...a) { errors.push(a.join(' ')); }, debug() {} }; + +const dir = mkdtempSync(join(tmpdir(), 'wj-act-control-')); +const w = (rel, body) => { const abs = join(dir, rel); mkdirSync(dirname(abs), { recursive: true }); writeFileSync(abs, body); }; +let close; +let failure = null; +try { + writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'ac', type: 'module' })); + w('modules/guard.server.ts', `'use server';\nimport { notFound, forbidden, unauthorized } from ${JSON.stringify(CORE)};\nexport async function denied() { forbidden(); }\nexport async function missing() { notFound(); }\nexport async function anon() { unauthorized(); }\n`); + w('app/page.ts', `import { html } from ${JSON.stringify(CORE)};\nimport { denied } from '../modules/guard.server.ts';\nexport default () => html\`
\`;\n`); + + let server; + ({ server, close } = await startServer({ appDir: dir, dev: false, port: 0, logger: quiet })); + const port = typeof server.port === 'number' ? server.port : server.address().port; + const base = `http://localhost:${port}`; + const html = await (await fetch(`${base}/`)).text(); + const id = /name="__webjs_action" value="([^"]+)"/.exec(html)?.[1]; + assert.ok(id, `the form renders an identity on ${runtime}`); + const hash = id.split('/')[0]; + + for (const [fn, status, kind] of [['denied', 403, 'forbidden'], ['missing', 404, 'not-found'], ['anon', 401, 'unauthorized']]) { + const rpc = await fetch(`${base}/__webjs/action/${hash}/${fn}`, { + method: 'POST', + headers: { 'content-type': 'application/vnd.webjs+json', 'sec-fetch-site': 'same-origin' }, + body: await stringify([]), + }); + await rpc.text(); + assert.equal(rpc.status, status, `${fn}() over RPC is a ${status} on ${runtime}`); + assert.equal(rpc.headers.get('x-webjs-control'), kind); + } + assert.deepEqual(errors.filter((e) => /action threw/.test(e)), [], `no sentinel is logged as an action error on ${runtime}`); + console.log(`ok action control flow over RPC on ${runtime}`); +} catch (e) { + failure = e; +} finally { + if (close) await close(); + rmSync(dir, { recursive: true, force: true }); +} +if (failure) { + console.error(failure); + process.exit(1); +} diff --git a/website/app/(site)/docs/error-handling/page.ts b/website/app/(site)/docs/error-handling/page.ts index 794e1cf49..4b0033c0f 100644 --- a/website/app/(site)/docs/error-handling/page.ts +++ b/website/app/(site)/docs/error-handling/page.ts @@ -102,7 +102,7 @@ export default async function AdminPage() { return html${'`'}...${'`'}; } -

Inside a 'use server' RPC action (one a client component calls), return a { success: false, error, status } ActionResult for an auth failure rather than throwing forbidden() / unauthorized(). The boundary render is a page-routing concern, the same guidance as for notFound() / redirect().

+

Inside a 'use server' action a client component calls, a thrown notFound(), forbidden() or unauthorized() answers the same 404, 403 or 401 the no-JS form path renders, and the call rejects with that sentinel, so the caller tests it with isForbidden(err) (and invokeActionForTest rejects the same way). It is never logged as an error. When the component should show a message instead, return a { success: false, error, status } ActionResult.

global-error.ts and global-not-found.ts

Two root-only boundaries (in app/ exactly). global-error.ts is the app-wide catch-all, tried after the nested error.ts boundaries are exhausted, and it renders its OWN full document (a root-layout failure is when it fires):

@@ -149,7 +149,7 @@ export default function GlobalError({ error }: { error: Error }) {

Tearing content back out is covered too, and it has to be, because a teardown has no next render to repair it. Unbinding a ref while a row is removed can never abort the removal of the rest of the list, and repeat() drops each leftover key from its map before touching that row, so the map never describes a row that has already been removed. Without that, a throw part-way through left the row you had DELETED on screen, reordered the survivors, and let a later render that re-added the key reinsert the disposed instance. The cost is that a ref whose object value setter throws is swallowed on teardown, matching the ref callback, which was already swallowed everywhere (lit guards neither and propagates from both, so this is a deliberate divergence). It applies to teardown only: on the COMMIT path a throwing object-ref setter still reaches renderError(). Covered also means a removal takes the row's own boundary markers with it, so a list that grows and shrinks all day is net zero on the nodes the renderer added, rather than accruing one invisible comment per removed row for the life of the region.

Server action errors

-

Errors thrown from server actions are sanitized in production: the client gets a generic "Internal server error" message plus a short digest, never the raw thrown message or the stack trace. The full error is logged server-side keyed by that digest, so a client-reported digest maps back to the server log line. A redirect() / notFound() control-flow throw passes through. To surface a specific user-facing message, return an ActionResult { success: false, error } envelope instead of throwing.

+

Errors thrown from server actions are sanitized in production: the client gets a generic "Internal server error" message plus a short digest, never the raw thrown message or the stack trace. The full error is logged server-side keyed by that digest, so a client-reported digest maps back to the server log line. A redirect(), notFound(), forbidden() or unauthorized() throw passes through with its own status. To surface a specific user-facing message, return an ActionResult { success: false, error } envelope instead of throwing.

Reporting errors with onRequestError

An app-root instrumentation.ts may export Next.js's onRequestError. The server calls it for every error a request hits on the server: a page or layout render, a metadata route, a route.ts handler, a server action, or middleware. It receives the same three arguments Next passes, so an existing Sentry or OpenTelemetry reporter works unchanged.

diff --git a/website/app/(site)/docs/server-actions/page.ts b/website/app/(site)/docs/server-actions/page.ts index e0422e851..dcc5363fd 100644 --- a/website/app/(site)/docs/server-actions/page.ts +++ b/website/app/(site)/docs/server-actions/page.ts @@ -364,7 +364,7 @@ export async function createPost(input: { title: string }) {

When a server action throws (rather than returning an error envelope), WebJs catches the exception and returns a JSON error response:

  • Development: the response includes both the error message and the full stack trace, making debugging easy.
  • -
  • Production: the client gets a generic "Internal server error" message plus a short digest, never the raw thrown message (a DB-driver message, an internal IP, or a file path is not author-controlled) and never the stack. The full error is logged server-side keyed by the same digest, so a client report maps to the server log. A redirect() / notFound() control-flow throw passes through. To show the user a specific message, return an ActionResult { success: false, error } envelope instead of throwing.
  • +
  • Production: the client gets a generic "Internal server error" message plus a short digest, never the raw thrown message (a DB-driver message, an internal IP, or a file path is not author-controlled) and never the stack. The full error is logged server-side keyed by the same digest, so a client report maps to the server log. A redirect(), notFound(), forbidden() or unauthorized() throw passes through with its own status (404, 403 or 401 for the last three, as on the no-JS form path). To show the user a specific message, return an ActionResult { success: false, error } envelope instead of throwing.

This prevents accidental leakage of file paths, database schemas, or other implementation details to end users.

From 6379a0419337161243da9afb8a442bfda223332f Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 00:16:37 +0530 Subject: [PATCH 02/29] feat: name the missing action field in a page POST's 405 Agents verifying a form with curl posted the visible fields alone, got a bare Method Not Allowed, and read form-dispatch.js to learn why (about five turns across three of eight eval builds). The body now names the hidden __webjs_action field and submitForm(), and the troubleshooting page covers the hand-posted case. Refs #1697 --- packages/server/src/form-dispatch.js | 17 ++++++++++++++--- .../server/test/routing/form-dispatch.test.js | 5 +++++ website/app/(site)/docs/troubleshooting/page.ts | 1 + 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/packages/server/src/form-dispatch.js b/packages/server/src/form-dispatch.js index cd337d7a4..b5858be6b 100644 --- a/packages/server/src/form-dispatch.js +++ b/packages/server/src/form-dispatch.js @@ -416,12 +416,23 @@ function withSubmittedValues(result, formData) { return { ...result, values: { ...textValuesOf(formData), ...ownValues } }; } +/** + * The body a page POST with no action identity gets, naming the fix (#1697): + * agents verifying a form with curl posted the visible fields alone and read + * the framework source to learn why the page answered 405. + */ +export const MISSING_ACTION_HINT = + 'Method Not Allowed. A POST to a page runs the server action named by the form\'s ' + + `hidden ${FORM_ACTION_FIELD} field, so send that field with the others (copy its value ` + + 'from the rendered form), or in a test call submitForm() from @webjsdev/server, which does.'; + /** * A page path exists but only renders: the method is the problem, not the url. + * @param {string} [body] * @returns {Response} */ -function methodNotAllowed() { - return new Response('Method Not Allowed', { +function methodNotAllowed(body = 'Method Not Allowed') { + return new Response(body, { status: 405, headers: { allow: 'GET, HEAD' }, }); @@ -499,7 +510,7 @@ export async function runFormAction(route, params, url, req, ssrOpts, deps) { // only as a bare 405. The dev-time client guard covers it instead. if (typeof id !== 'string' || !id) { reportFormActionMissing(url, req, formData, onError, logger, !!ssrOpts.dev, route); - return methodNotAllowed(); + return methodNotAllowed(MISSING_ACTION_HINT); } // The field is framework wire, not app data. Removing it keeps an action // that iterates the FormData (building a record, echoing values back into a diff --git a/packages/server/test/routing/form-dispatch.test.js b/packages/server/test/routing/form-dispatch.test.js index 1194bda91..144a5b7df 100644 --- a/packages/server/test/routing/form-dispatch.test.js +++ b/packages/server/test/routing/form-dispatch.test.js @@ -269,6 +269,11 @@ test('a page that binds no action answers 405 on POST, not 404', async () => { const post = await app.handle(new Request('http://x/info', form({ x: '1' }))); assert.equal(post.status, 405); assert.equal(post.headers.get('allow'), 'GET, HEAD'); + // #1697: the body names the missing field and the test helper, since agents + // verifying a form with curl read the framework source to learn why. + const body = await post.text(); + assert.match(body, /__webjs_action/); + assert.match(body, /submitForm\(\)/); }); test('a non-form POST to a page is 405, decided BEFORE the body is parsed', async () => { diff --git a/website/app/(site)/docs/troubleshooting/page.ts b/website/app/(site)/docs/troubleshooting/page.ts index 7dc101f24..fdff2357f 100644 --- a/website/app/(site)/docs/troubleshooting/page.ts +++ b/website/app/(site)/docs/troubleshooting/page.ts @@ -83,6 +83,7 @@ export default function Troubleshooting() {

Symptom: submitting a form returns 405 Method Not Allowed with Allow: GET, HEAD, and the page itself renders fine on a GET.

Cause: the form binds no action. A page has no action export, so a bare <form method="post"> has nothing to run: the url exists and only renders, which is what the 405 says. The other way to get one is binding an action whose file declares export const method = 'GET'; a GET action rides its arguments in the url and skips the CSRF check, so it cannot answer a form POST. That case answers Allow: GET, and webjs check's form-action-not-a-get-action rule catches it before it ships.

Fix: bind the action (<form action=\${submitFeedback}>), or drop the method export from the action's file so it is an ordinary POST.

+

Posting by hand (curl, a script) to a page whose form IS bound answers the same 405 when the request leaves out the form's hidden __webjs_action field, and the response body says so. Copy that field's value from the rendered form and send it with the others, or in a test use submitForm(), which reads it from the page for you.

A button submits and the page just re-renders

Symptom: clicking a formaction=\${action} button reloads the same page with a 200, nothing was written, no error appears anywhere, and the address bar has grown a ?__webjs_action= parameter.

From a15145478079af31ca0dd2ff3857dcf23511bfaa Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 00:16:43 +0530 Subject: [PATCH 03/29] feat: answer common lookups in the catalogue and scaffold Every eval build runs a bare `webjs source` first, then grepped node_modules for facts it did not state: which database `webjs test` uses (16 turns across five builds), what `webjs db seed` runs, whether pages are cached by default, and what a route handler receives. The catalogue now says each in a few words and stays at 1855 characters. The scaffold's AGENTS.md names the `git rm -r` that removes the example module and says the removal is already staged, since five of eight builds ran `git add` on the removed paths and chased the pathspec error. Refs #1697 --- .github/workflows/ci.yml | 4 ++++ packages/cli/templates/AGENTS.md | 3 ++- packages/mcp/src/catalog.js | 11 ++++++++--- packages/mcp/test/catalog.test.mjs | 10 ++++++++++ test/scaffolds/scaffold-integration.test.js | 5 ++++- 5 files changed, 28 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e00c686bd..95724d019 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -143,6 +143,10 @@ jobs: # machines, which are independent and must be kept in step by hand. - name: WebJs form-action guard parity on Bun run: bun test/bun/form-action-guard.mjs + # notFound() / forbidden() / unauthorized() in an action called over RPC + # (#1697): 404 / 403 / 401 through the Bun.serve listener, never a 500. + - name: Action control flow over RPC on Bun + run: bun test/bun/action-control-flow-rpc.mjs # live() in an attribute hole (#1443): the SSR unwrap must produce # byte-identical attribute emission on Bun, across both server machines. # The bug class this guards was a server/client disagreement (a falsy diff --git a/packages/cli/templates/AGENTS.md b/packages/cli/templates/AGENTS.md index dcdc67eff..c82f3f9a8 100644 --- a/packages/cli/templates/AGENTS.md +++ b/packages/cli/templates/AGENTS.md @@ -39,7 +39,8 @@ Keep app data in the wired-up Drizzle database (`db/`), never in a JSON file or an in-memory array. Put each feature in `modules//` (`actions/` with one `'use server'` action per `*.server.ts`, `queries/`, `components/`, `types.ts`) and keep routes thin. `modules/users/` is an example of that shape: read it, then -delete it, its test and whatever uses it before you build the app. +remove it with `git rm -r modules/users test/users` (already staged, so never +`git add` those paths) and whatever uses it before you build the app. In components, use Lit's APIs over raw DOM calls: `@click=${...}` and `ref()`, not `document.getElementById`, `document.querySelector` or `addEventListener`. diff --git a/packages/mcp/src/catalog.js b/packages/mcp/src/catalog.js index e21878275..e42800525 100644 --- a/packages/mcp/src/catalog.js +++ b/packages/mcp/src/catalog.js @@ -32,15 +32,15 @@ export const FEATURE_CATALOG = [ { need: 'Auth', names: ['createAuth', 'Credentials', 'GitHub', 'Google', 'AuthError'], note: "Auth.js's API: auth(), signIn(), signOut(), handlers" }, { need: 'Sessions and cookies', names: ['session', 'getSession', 'cookies', 'headers'] }, { need: 'Redirects and errors', names: ['redirect', 'permanentRedirect', 'notFound', 'forbidden', 'unauthorized'] }, - { need: 'Caching', names: ['cache', 'revalidatePath', 'revalidateTag', 'revalidateAll'] }, + { need: 'Caching', names: ['cache', 'revalidatePath', 'revalidateTag', 'revalidateAll'], note: 'a page renders per request unless it exports revalidate' }, { need: 'Rate limits and CORS', names: ['rateLimit', 'cors', 'clientIp'] }, { need: 'File uploads', names: ['getFileStore', 'setFileStore', 'diskStore', 'generateKey', 'signedUrl', 'verifySignedUrl'] }, { need: 'Realtime', names: ['broadcast'], note: 'a route.ts exporting WS handles WebSocket connections' }, { need: 'Streaming responses', names: ['stream', 'streamResponse', 'acceptsStream'] }, - { need: 'Route handlers', names: ['json', 'readBody', 'route'] }, + { need: 'Route handlers', names: ['json', 'readBody', 'route'], note: 'route.ts exports GET(req, { params }), params awaited' }, { need: 'SEO', names: ['sitemap', 'sitemapIndex', 'robots'] }, { need: 'Env validation', names: ['validateEnv'], note: 'an env.ts schema checks process.env at boot' }, - { need: 'Server tests', names: ['testRequest', 'submitForm', 'invokeActionForTest', 'loginAndGetCookies', 'createRequestHandler'] }, + { need: 'Server tests', names: ['testRequest', 'submitForm', 'invokeActionForTest', 'loginAndGetCookies', 'createRequestHandler'], note: 'npx webjs test gives a SQLite app a fresh migrated database, never db/dev.db' }, ], }, { @@ -78,5 +78,10 @@ export function featureCatalog(catalog = FEATURE_CATALOG) { out.push(` ${g.need}: ${g.names.join(', ')}${g.note ? ` (${g.note})` : ''}`); } } + out.push( + '', + 'Database: Drizzle tables in db/schema.server.ts; npx webjs db generate then', + 'npx webjs db migrate; npx webjs db seed runs db/seed.server.ts.', + ); return out.join('\n'); } diff --git a/packages/mcp/test/catalog.test.mjs b/packages/mcp/test/catalog.test.mjs index bd73357e8..41a458eb4 100644 --- a/packages/mcp/test/catalog.test.mjs +++ b/packages/mcp/test/catalog.test.mjs @@ -92,6 +92,16 @@ test('the catalogue text names every entry and stays short', () => { assert.ok(text.length < 2500, `the catalogue stays under 2500 characters (${text.length})`); }); +// #1697: the facts agents in the eval builds grepped node_modules for, after +// reading this very listing. Each cost one to sixteen turns across builds. +test('the catalogue answers the lookups agents grepped the framework source for', () => { + const text = featureCatalog(); + assert.match(text, /fresh migrated database, never db\/dev\.db/, 'which database `webjs test` uses'); + assert.match(text, /webjs db seed runs db\/seed\.server\.ts/, 'which file the seed command runs'); + assert.match(text, /renders per request unless it exports revalidate/, 'whether pages are cached by default'); + assert.match(text, /GET\(req, \{ params \}\)/, 'what a route handler receives'); +}); + test('the MCP source tool returns the catalogue for no arguments, and a listing for `package`', async () => { const deps = { roots: [], readFile, readdir: listDir }; assert.equal(await runSourceTool(deps, {}), featureCatalog()); diff --git a/test/scaffolds/scaffold-integration.test.js b/test/scaffolds/scaffold-integration.test.js index ded81cab1..3affb58a2 100644 --- a/test/scaffolds/scaffold-integration.test.js +++ b/test/scaffolds/scaffold-integration.test.js @@ -869,7 +869,10 @@ test('scaffoldApp: AGENTS.md is the brief alone, the same for both templates', a assert.match(fs, /document\.getElementById/, 'naming the raw DOM calls to avoid'); assert.match(fs, /Style with Tailwind utilities on the kit's design tokens/, 'steers styling to Tailwind on the kit tokens'); assert.match(fs, /npx webjs ui init --preset/, 'and theming to a kit preset'); - assert.match(fs, /`modules\/users\/` is an example of that shape: read it, then\ndelete it, its test and whatever uses it before you build the app\./, 'tells the agent to delete the example module before building'); + assert.match(fs, /`modules\/users\/` is an example of that shape: read it, then\nremove it with `git rm -r modules\/users test\/users`/, 'tells the agent to delete the example module before building'); + // #1697: five of eight eval builds ran `git add` on the removed paths and + // spent turns on the pathspec error. + assert.match(fs, /already staged, so never\n`git add` those paths/, 'and that the removal is already staged'); assert.match(fs, /\n## This app\n\nReplace this paragraph with what /, 'ends with a This app section the agent fills in'); assert.match(fs, /`CLAUDE\.md` imports this file, so notes go here\./, 'which says app notes live in AGENTS.md, not CLAUDE.md'); // The brief plus the scaffold's rules plus the This app stub: still short, From 2efc239eb96ab5976d3b97ac6aee67ef5e1ccc4d Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 00:20:16 +0530 Subject: [PATCH 04/29] feat: fit the scaffold's first read in one tool call An agent's first move on a fresh app is one cat of the source it will build on. In six of eight eval builds that read was 43 to 60 KB, over the 50 KB tool-output limit, so the agent re-read file by file and the text sat in context for the rest of the run. lib/utils/cn.ts was 24.7 KB, 15 KB of it commentary on the class merger that packages/ui/AGENTS.md already carries; it is now 12 KB with the code byte for byte the same. The layout's comments shrink too, and the read set goes from 58 KB to 43 KB, held under 45 KB by a scaffold test. The layout's content wrapper is a div and the home page renders its own main, as a create-next-app page does, since agents wrote a main inside the layout's. Refs #1697 --- packages/cli/lib/create.js | 126 ++++------ packages/ui/packages/registry/lib/utils.ts | 242 +++----------------- test/scaffolds/scaffold-integration.test.js | 42 +++- 3 files changed, 107 insertions(+), 303 deletions(-) diff --git a/packages/cli/lib/create.js b/packages/cli/lib/create.js index cd29e550f..c95ce6a58 100644 --- a/packages/cli/lib/create.js +++ b/packages/cli/lib/create.js @@ -1392,38 +1392,16 @@ html:has(> body > header[class~="2xl:fixed"]) { @variant 2xl { scroll-padding-to import type { LayoutProps } from '@webjsdev/core'; import '#components/theme-toggle.ts'; -/** - * Root layout: the ONLY file that writes the document shell. It wires a neutral - * design-token palette, the light/dark theme, and the Tailwind stylesheet, then - * renders \${children} in a bare container. Grow it in place: add a header, nav, - * footer, or reading column here as your app needs them. Design tokens live as - * plain CSS custom properties (they resolve with JavaScript disabled) and are - * mapped into Tailwind via @theme in public/input.css, so bg-background, - * text-foreground, bg-card, bg-primary, and border-border all work. - */ - -// The favicon and manifest are app/icon.svg and app/manifest.webmanifest: the -// framework links them into itself, so nothing is declared here. Replace -// the placeholder icon with this app's own. - -// LayoutProps types every layout argument (children, params, searchParams, -// url) from the framework, so children is a TemplateResult rather than an -// untyped value. Derive types like this everywhere instead of widening to -// unknown. +// The root layout, the only file that writes the document shell. Grow it in +// place (header, nav, footer). The favicon and manifest are app/icon.svg and +// app/manifest.webmanifest, which the framework links itself. Design tokens +// are in styles/globals.css, mapped into Tailwind by public/input.css. export default function RootLayout({ children }: LayoutProps) { - // Read the in-flight request's CSP nonce so the theme-detection inline script - // passes strict CSP. Returns '' when no CSP nonce is set. - const nonce = cspNonce(); + const nonce = cspNonce(); // '' unless CSP is on return html\` - + - - + - - +
@@ -1476,11 +1433,10 @@ export default function RootLayout({ children }: LayoutProps) {
- -
+ +
\${children} -
+ \`; } `); @@ -1647,31 +1603,33 @@ export default async function Home({ actionData }: PageProps) { const latest = await listUsers(); const error = actionData?.fieldErrors?.email; return html\` -
- -

- WebJs - -

-

Your WebJs app starts here. Edit app/page.ts.

-
- -
-
-
- - - \${error ? html\`\` : nothing} -
- -
- - \${latest.length > 0 ? html\` -
- -
\` : nothing} -
+
+
+ +

+ WebJs + +

+

Your WebJs app starts here. Edit app/page.ts.

+
+ +
+
+
+ + + \${error ? html\`\` : nothing} +
+ +
+ + \${latest.length > 0 ? html\` +
+ +
\` : nothing} +
+
\`; } `); diff --git a/packages/ui/packages/registry/lib/utils.ts b/packages/ui/packages/registry/lib/utils.ts index 435d40050..72adfe85e 100644 --- a/packages/ui/packages/registry/lib/utils.ts +++ b/packages/ui/packages/registry/lib/utils.ts @@ -1,23 +1,7 @@ /** - * Tiny class-name merger. Drop-in replacement for the clsx + tailwind-merge - * pair used in shadcn. - * - * - Concatenates truthy arguments separated by spaces. - * - Later Tailwind utilities win when they target the same property, mimicking - * `tailwind-merge`'s behaviour for the cases components actually hit - * (background colour, image, clip, origin, blend mode, position, size, - * repeat, attachment; text colour, size, alignment, wrapping, overflow; - * box-shadow and text-shadow, each split into size and colour; padding, - * margin, width, height, border, rounded, opacity, display). - * - * For projects that want the full tailwind-merge behaviour, install - * `clsx` + `tailwind-merge` and replace this file: - * - * import { clsx, type ClassValue } from 'clsx'; - * import { twMerge } from 'tailwind-merge'; - * export function cn(...inputs: ClassValue[]) { - * return twMerge(clsx(inputs)); - * } + * `cn()`, shadcn's clsx + tailwind-merge in one: joins the truthy arguments, + * and a later utility wins over an earlier one for the same CSS property. + * Below it are the layout and typography class helpers. */ export type ClassValue = string | number | null | false | undefined | ClassValue[] | Record; @@ -44,64 +28,35 @@ function walk(value: ClassValue, out: string[]): void { } } -// Conflict groups: classes with the same group key: last one wins. -// Covers ~95% of in-component overrides the registry exposes. -// -// IMPORTANT: text-size (text-sm, text-xs, text-base, text-lg, …) and -// text-color (text-primary, text-foreground, …) are DIFFERENT properties -// and must be in different groups. Same for bg-size vs bg-color etc. -// Built on FIRST USE, not at module load, so a module that imports `cn` does no -// work at load and a page that never merges a class never builds the table -// (#1320). +// The merger. One group per CSS property (never per class prefix); a later +// class evicts an earlier one in its group. Built on first use (#1320). let _groups: Array<[RegExp, string]> | undefined; function GROUPS(): Array<[RegExp, string]> { return (_groups ??= [ [/^p-/, 'p'], [/^px-/, 'px'], [/^py-/, 'py'], [/^pt-/, 'pt'], [/^pr-/, 'pr'], [/^pb-/, 'pb'], [/^pl-/, 'pl'], [/^ps-/, 'ps'], [/^pe-/, 'pe'], [/^m-/, 'm'], [/^mx-/, 'mx'], [/^my-/, 'my'], [/^mt-/, 'mt'], [/^mr-/, 'mr'], [/^mb-/, 'mb'], [/^ml-/, 'ml'], [/^ms-/, 'ms'], [/^me-/, 'me'], [/^w-/, 'w'], [/^h-/, 'h'], [/^size-/, 'size'], - // A `bg-[url(…)]` / `bg-[linear-gradient(…)]` background image is classified - // by its FUNCTION, since it carries no type hint to classify it by. The - // hinted forms are handled centrally, in `hintedGroup`. [/^bg-\[(url\(|linear-gradient|radial-gradient|conic-gradient)/, 'bg-image'], [/^bg-(linear|gradient|conic|radial|none)/, 'bg-image'], [/^bg-(no-repeat|repeat|repeat-x|repeat-y|repeat-round|repeat-space)$/, 'bg-repeat'], [/^bg-(fixed|local|scroll)$/, 'bg-attach'], [/^bg-(auto|cover|contain)$/, 'bg-size'], [/^bg-size-/, 'bg-size'], - // Two entries rather than one alternation: the first covers the live v4 - // compounds (`bg-top-left`), the second the bare keywords plus the v4.1 - // deprecated reversed compounds (`bg-left-top`), which tailwind-merge still - // carries. An unmatched `bg-*` token falls into the colour catch-all below and - // evicts a real colour, so admitting a dead spelling is the safe direction. [/^bg-(top|bottom)(-(left|right))?$/, 'bg-position'], [/^bg-(left|right|center)(-(top|bottom))?$/, 'bg-position'], [/^bg-position-/, 'bg-position'], - // Clip, origin, and blend mode are three more properties under the same - // prefix. Each sat in `bg-color` before, so `bg-clip-text` evicted a real - // background colour (the gradient-text idiom lost its clip silently). [/^bg-clip-(border|padding|content|text)$/, 'bg-clip'], [/^bg-origin-(border|padding|content)$/, 'bg-origin'], [/^bg-blend-(normal|multiply|screen|overlay|darken|lighten|color-dodge|color-burn|hard-light|soft-light|difference|exclusion|hue|saturation|color|luminosity)$/, 'bg-blend'], [/^bg-/, 'bg-color'], - // text-shadow is its own property, and its size scale and its colour are two - // properties again. All three entries precede the text- patterns below, which - // is what keeps a `text-shadow-*` token out of `text-size` and `text-color`. [/^text-shadow(-(2xs|xs|sm|md|lg|none))?(\/([\d.]+|\[[^\]]*\]))?$/, 'text-shadow'], [/^text-shadow-(\[(inset|-|\.|\d|var\()|\(--)/, 'text-shadow'], [/^text-shadow-/, 'text-shadow-color'], - // Font size: explicit list of Tailwind size scale. [/^text-(xs|sm|base|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|8xl|9xl)$/, 'text-size'], - // Alignment, wrapping, and overflow are three more properties under the same - // prefix. Each was previously excluded from text-color by a lookahead and then - // matched nothing at all, so two alignments never collapsed. [/^text-(left|center|right|justify|start|end)$/, 'text-align'], [/^text-(wrap|nowrap|balance|pretty)$/, 'text-wrap'], [/^text-(ellipsis|clip)$/, 'text-overflow'], - // Text color: anything else under the prefix. The specific groups above are - // the whole carve-out, so no negative lookahead is needed here as well. [/^text-/, 'text-color'], - // Border sub-properties that are neither a width nor a colour. These come - // FIRST so the width / colour classifier below never sees them. [/^border-(collapse|separate)$/, 'border-collapse'], [/^border-spacing(-[xy])?-/, 'border-spacing'], [/^border-(solid|dashed|dotted|double|hidden|none)$/, 'border-style'], @@ -111,47 +66,20 @@ function GROUPS(): Array<[RegExp, string]> { [/^opacity-/, 'opacity'], [/^leading-/, 'leading'], [/^font-(thin|light|normal|medium|semibold|bold|black|extralight|extrabold)$/, 'font-weight'], - // Box-shadow SIZE and box-shadow COLOUR are two properties (`box-shadow` and - // `--tw-shadow-color`), so they need two groups. `shadow-none` is a size, - // `shadow-inherit` / `shadow-initial` are colours, and Tailwind accepts an - // alpha modifier on a size as well as on a colour, so `shadow-lg/25` has to - // stay on the size side. An unhinted arbitrary value is a SIZE when it opens - // with `inset`, a sign, a dot, or a digit (a shadow offset list) and also - // when it is a bare `var()` or the `(--x)` variable shorthand: Tailwind - // itself resolves an ambiguous arbitrary shadow to `box-shadow` unless the - // value is provably a colour, and `shadow-[var(--shadow-glow)]` is the normal - // way to write a design-token shadow. This is the one place the - // `borderGroups()` convention inverts, because a bare `border-[var(--x)]` is - // far more often a colour while a bare `shadow-[var(--x)]` is far more often - // a shadow. The size entries must precede the colour catch-all, or every - // size lands in the colour group and the bug inverts rather than being fixed. + // Shadow size and shadow colour are two properties; an unhinted arbitrary + // value is a size when it opens like an offset list or is a bare var(). [/^shadow(-(2xs|xs|sm|md|lg|xl|2xl|inner|none))?(\/([\d.]+|\[[^\]]*\]))?$/, 'shadow'], [/^shadow-(\[(inset|-|\.|\d|var\()|\(--)/, 'shadow'], - // A bare name the size scale does not list reads as a colour, because - // `shadow-primary` is overwhelmingly more common than a `@theme`-extended - // `--shadow-card`. A project that adds a custom shadow NAME is the residual - // gap, and the docs say so rather than claiming the split is total. [/^shadow-/, 'shadow-color'], [/^z-/, 'z'], - // A bare `flex` / `grid` is a DISPLAY value, not a member of the flex / grid - // sub-property groups below, so it must never dedupe against them: an element - // can be both a flex container and a flex child (`class="flex flex-1"`), and - // collapsing the two silently drops `display:flex`. It still belongs to a - // group of its own, alongside every other display keyword, so a repeated one - // collapses and `cn('hidden', open && 'flex')` resolves to one display. + // Display keywords, apart from the flex / grid sub-properties below. [/^(inline-block|inline-flex|inline-grid|inline-table|inline|block|flex|grid|flow-root|contents|hidden|list-item|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table)$/, 'display'], - // Each sub-utility below gets the group of the real CSS property it sets, so - // none of them collapses against the display value or against each other. [/^flex-(row|row-reverse|col|col-reverse)$/, 'flex-direction'], [/^flex-(wrap|wrap-reverse|nowrap)$/, 'flex-wrap'], [/^flex-(\d+|auto|initial|none|\[[^\]]*\])$/, 'flex'], [/^grid-cols-/, 'grid-cols'], [/^grid-rows-/, 'grid-rows'], [/^grid-flow-/, 'grid-flow'], - // Flex basis and the alignment properties, one group per property: - // `justify-items-*` and `justify-self-*` precede `justify-*`, which is - // justify-content, and likewise `self-*` is align-self, apart from - // `items-*` (align-items). [/^basis-/, 'basis'], [/^justify-items-/, 'justify-items'], [/^justify-self-/, 'justify-self'], @@ -162,34 +90,12 @@ function GROUPS(): Array<[RegExp, string]> { } /** - * Border WIDTH and border COLOUR share the `border-` prefix but are different - * CSS properties, so they need different groups: `cn('border-2', - * 'border-primary')` must keep BOTH, while `cn('border-border', - * 'border-accent')` must keep only the later colour (today the winner is - * decided by compiled stylesheet order, which silently loses whenever the - * override sorts alphabetically earlier). - * - * Classification, after an optional side / axis segment: a bare or numeric - * value is a width (`border`, `border-2`, `border-t-4`), an arbitrary value - * that opens with a digit, a dot, or `length:` is a width (`border-[3px]`, - * `border-[length:var(--w)]`, and the v4 paren spelling - * `border-(length:--w)`), and everything else is a colour - * (`border-primary`, `border-red-500/50`, `border-[#fff]`). An ambiguous - * `border-[var(--x)]`, or its paren spelling `border-(--x)`, falls to colour, - * which is the far more common intent. - * - * Each side is its own group so a per-side utility only overrides its own side, - * and the shorthand / axis subsumption is declared in CONFLICTS below, exactly - * like padding and margin. The logical inline sides (`border-s-*`, - * `border-e-*`) get their own groups but are subsumed only by the all-sides - * shorthand, never by `border-x-*`: which physical side they land on depends on - * the writing direction, so an axis override there would be a guess. + * Border width and colour groups, one per side. A bare or numeric value, or an + * arbitrary length, is a width; anything else is a colour. */ function borderGroups(): Array<[RegExp, string]> { const width = '(\\d+(\\.\\d+)?|\\[(length:|\\d|\\.)[^\\]]*\\]|\\(length:[^)]*\\))'; const out: Array<[RegExp, string]> = []; - // Sides before the bare form: `border-t-primary` must match the `t` colour - // group, not be swallowed by the side-less `^border-` colour pattern. const sides = ['x', 'y', 't', 'r', 'b', 'l', 's', 'e', '']; for (const side of sides) { const seg = side ? `-${side}` : ''; @@ -203,34 +109,9 @@ function borderGroups(): Array<[RegExp, string]> { } /** - * An arbitrary value may carry a Tailwind TYPE HINT: `bg-[image:var(--g)]`, - * `text-[length:14px]`, `shadow-[color:red]`, and in the v4 paren shorthand - * `bg-(image:--g)`, `shadow-(color:--x)`. The hint exists precisely because - * the utility prefix is ambiguous, so the PREFIX cannot decide the group and - * the hint must. Letting a hinted value fall into the prefix's default group - * evicts a class that sets an entirely different property (`shadow-[color:red]` - * would eat `shadow-lg`). - * - * Every `:` pair listed here names the group it belongs to; an - * empty string means the hint names the prefix's OWN default property, so the - * GROUPS table above is already right for it and matching falls through. A pair - * that is NOT listed gets a group of its own, so it can only ever collide with - * the identical hint under the identical prefix, never with the prefix's - * default. That is the safe direction to fail: an extra class renders, a - * dropped one does not. - * - * This is central rather than per-prefix on purpose. Handling only the prefixes - * that came to mind is how `shadow-[color:red]` was left evicting `shadow-lg` - * while `bg-` and `text-` were correct. - * - * These reach the matcher at all only because `variantPrefix` splits on the - * last colon OUTSIDE brackets AND parentheses; see the comment there. - * - * Both spellings of one hint produce the identical `:` key, so - * the map needs no paren-specific entries. The closing delimiter is - * deliberately not validated: the hint names the CSS property, and how the - * value terminates cannot change which property that is (the bracket branch - * has never validated its own close either). + * A type-hinted arbitrary value (`bg-[image:...]`, `shadow-(color:--x)`) is + * grouped by its hint. '' means the prefix's own default property; an unlisted + * pair gets a group of its own. */ const HINTED_GROUPS: Record = { 'bg:color': '', @@ -240,10 +121,6 @@ const HINTED_GROUPS: Record = { 'bg:length': 'bg-size', 'text:color': '', 'text:length': 'text-size', - // Both shadow prefixes carry a colour that is a DIFFERENT property from the - // prefix's own default (the size), so the hint has a named group to point at - // and must, or `shadow-[color:red]` keeps an isolated bucket and stops - // deduping against `shadow-red-500`, which sets the identical property. 'shadow:color': 'shadow-color', 'text-shadow:color': 'text-shadow-color', }; @@ -259,22 +136,12 @@ function hintedGroup(bare: string): string | null | undefined { const hint = m[2]; const key = `${prefix}:${hint}`; if (key in HINTED_GROUPS) return HINTED_GROUPS[key] || null; - // A border width or colour hint is read by `borderGroups()`'s value parser, - // which already classifies `border-[length:2px]` as a width and everything - // else after `border-` as a colour. The side list MUST match the one - // `borderGroups()` enumerates, logical inline sides included, or the hinted - // and plain spellings of one utility land in different groups. if (/^border(-[xytrbles])?$/.test(prefix) && (hint === 'length' || hint === 'color')) return null; return `hint:${key}`; } -// Directional shorthand conflicts (the tailwind-merge model). A shorthand -// utility invalidates the axis / side utilities it SUBSUMES, because Tailwind's -// cascade makes the shorthand win: `p-0` after `px-4 py-2` drops both, but -// `px-4` after `p-2` refines only the x-axis so BOTH survive (the conflict is -// directional, not symmetric). Keyed by the group a NEWLY-seen token belongs to; -// the value lists the EARLIER groups whose survivors it removes (its own group -// is always removed too, handled below). +// A shorthand evicts the sides it subsumes (`p-0` drops an earlier `px-4`), not +// the other way round. const CONFLICTS: Record = { p: ['px', 'py', 'pt', 'pr', 'pb', 'pl', 'ps', 'pe'], px: ['pl', 'pr'], @@ -298,14 +165,9 @@ function dedupeUtilities(input: string): string { const result: Array = []; for (const token of tokens) { - // Strip variant prefix (`hover:`, `dark:md:`, …) before testing each dedupe - // regex so `hover:bg-red-500` still matches the `bg-color` group. Conflicts - // only apply WITHIN the same variant (`px-4 hover:p-0` keeps both). + // Conflicts apply within one variant set (`px-4 hover:p-0` keeps both). const prefix = variantPrefix(token); const bare = prefix ? token.slice(prefix.length) : token; - // A type-hinted arbitrary value is classified by its HINT, which overrides - // the prefix-keyed table below (`hintedGroup` returns null when the hint - // names the prefix's own default property and the table is already right). const hinted = hintedGroup(bare); let gk: string | null = hinted ?? null; if (hinted === undefined || hinted === null) { @@ -314,7 +176,6 @@ function dedupeUtilities(input: string): string { } } if (gk) { - // Remove earlier survivors in this group AND in every group it subsumes. for (const g of [gk, ...(CONFLICTS[gk] ?? [])]) { const k = `${prefix}::${g}`; const idx = lastByKey.get(k); @@ -328,23 +189,8 @@ function dedupeUtilities(input: string): string { } function variantPrefix(token: string): string { - // Capture leading variants like `hover:`, `dark:`, `md:`: overrides only - // conflict within the same variant set. The split is the last colon at top - // level, meaning outside BOTH square brackets and parentheses, because an - // arbitrary value can contain a colon of its own in either delimiter - // (`border-[length:2px]`, `bg-[url(https://x/y.png)]`, `text-[color:var(--c)]`, - // and the v4 paren spelling `shadow-(color:--x)`, `bg-(image:--g)`). - // Splitting on the last colon anywhere hands the group matcher a fragment - // like `2px]` or `--x)`, which matches nothing, so the utility silently - // stops deduping against its own property. - // - // TWO counters, both required to be zero, rather than one shared counter. - // Tailwind's own top-level splitter (`segment()`, in the upstream - // tailwindlabs/tailwindcss repo at packages/tailwindcss/src/utils/segment.ts, - // NOT a path in this repo) is a MATCHED-PAIR stack, so a - // stray closer never cancels a live opener of the other kind. A single - // shared counter would let `)` cancel `[` and read `x-[y)-z:w` as having a - // top-level colon, which is the fragment bug above wearing a different hat. + // The variants end at the last colon outside both brackets and parens, each + // counted on its own, since an arbitrary value has colons of its own. let bracketDepth = 0; let parenDepth = 0; let i = -1; @@ -359,15 +205,8 @@ function variantPrefix(token: string): string { return i === -1 ? '' : token.slice(0, i + 1); } -// --------------------------------------------------------------------------- -// Stable DOM ids for wiring ARIA relationships (aria-controls / -// aria-labelledby / aria-describedby) between sibling light-DOM nodes. -// A monotonic counter is fine for uniqueness within a document: the id is -// only consumed as an attribute value, never persisted. When SSR emits an -// id on a host element, the upgraded element reuses it (ensureId is a no-op -// when an id is already present), so the server and client agree. -// --------------------------------------------------------------------------- - +// Stable DOM ids for ARIA wiring between light-DOM nodes. An id already on +// the element (author-set, or from SSR) is kept, so server and client agree. let _idSeq = 0; /** A fresh, document-unique id string with a readable prefix. */ @@ -395,18 +234,10 @@ export type ClassHost = { }; /** - * The class an author wrote on a Tier-2 part's host, which is shadcn's - * `className` and belongs on the element the part renders. Read once per - * element, then `hostClass` replaces it on the host (`null` removes the - * class, `undefined` leaves the attribute to the caller, for a host that - * styles itself). - * - * The first read records the class in `data-authored-class`, which the server - * serves, because the class attribute cannot be trusted on hydration: the - * server sends the class a tag was written with, and a host written with none - * is sent the class the element gave it (`contents`, its own classes). The - * element that upgrades the served markup is a fresh instance, so without the - * record it would read that class back as the author's. + * The class an author wrote on a Tier-2 part's host (shadcn's `className`), + * recorded in `data-authored-class` on first read so a hydrating instance + * reads the author's class, not the one the element served. `hostClass` + * replaces it on the host (`null` removes it). */ export function takeAuthoredClass(host: ClassHost, hostClass?: string | null): string | null { if (host._authoredClass === undefined) { @@ -420,18 +251,7 @@ export function takeAuthoredClass(host: ClassHost, hostClass?: string | null): s return host._authoredClass; } -// NOTE: the old `HTMLElement`-era `Base` / `defineElement` / SSR-stub helpers -// were removed. The ui registry components extend `WebComponent` from -// `@webjsdev/core` now, so those helpers were dead code, and referencing -// `HTMLElement` / `customElements` at module scope marked this util (and any -// page that imports `cn`) as client-effecting. Everything below is pure or -// SSR-safe, so importing `cn` no longer pins a page to the browser (#819). - -// --------------------------------------------------------------------------- -// Layout helpers: encode the design-system rhythm (spacing between label / -// input / hint, between form fields, between sections). Change one helper to -// retune the whole app: call sites stay readable inline Tailwind. -// --------------------------------------------------------------------------- +// Layout helpers: the design system's spacing rhythm, in one place. /** Vertical rhythm inside a single form field: label ↔ control ↔ hint/error. */ export const fieldClass = () => 'grid gap-2'; @@ -442,13 +262,7 @@ export const fieldRowClass = () => 'flex items-center gap-3'; /** Gap step for `stackClass({ gap })`. */ export type StackGap = 'sm' | 'md' | 'lg'; -/** - * Stack of form fields. `sm` for tight groupings, `lg` for spaced-out sections. - * - * Object-arg shape matches the rest of the kit (`buttonClass({ variant, size })`, - * `badgeClass({ variant })`, etc.): predictable across all helpers and - * extensible if a second dimension (e.g. `direction`) is ever added. - */ +/** Stack of form fields: `sm` tight, `lg` spaced out. */ export const stackClass = (opts: { gap?: StackGap } = {}): string => { const gap = opts.gap ?? 'md'; return gap === 'sm' ? 'grid gap-3' : gap === 'lg' ? 'grid gap-8' : 'grid gap-6'; @@ -460,9 +274,7 @@ export const formClass = () => 'grid gap-6'; /** Top-level section separation (between form groups, between sections of a page). */ export const sectionClass = () => 'grid gap-8'; -// --------------------------------------------------------------------------- -// Typography helpers: fixed text styles used across the design system. -// --------------------------------------------------------------------------- +// Typography helpers. /** Form-field label: `
/, - 'layout main fills the viewport minus the navbar'); + // Geist), with a floating top navbar and a container that fills the + // viewport minus the navbar. The page renders its own
, as a + // create-next-app page does (#1697: agents nested one inside the layout's). + assert.match(layoutSrc, /
/, + 'layout container fills the viewport minus the navbar'); + assert.doesNotMatch(layoutSrc, / to the page'); + assert.match(readFileSync(join(appDir, 'app', 'page.ts'), 'utf8'), /
/, 'the home page renders its own
'); assert.match(layoutSrc, / { + const cwd = await mkdtemp(join(tmpdir(), 'webjs-first-read-')); + try { + await scaffoldApp('first-read', cwd, { template: 'full-stack' }); + const appDir = join(cwd, 'first-read'); + const sizes = []; + const walk = (rel) => { + const abs = join(appDir, rel); + if (!existsSync(abs)) return; + if (statSync(abs).isDirectory()) { + for (const e of readdirSync(abs)) walk(join(rel, e)); + } else if (/\.(ts|js)$/.test(rel)) { + sizes.push([rel, statSync(abs).size]); + } + }; + for (const rel of ['app', 'db', 'modules', 'test/users', 'components', 'lib', 'drizzle.config.ts', 'instrumentation.ts']) walk(rel); + const total = sizes.reduce((n, [, s]) => n + s, 0); + const largest = sizes.sort((a, b) => b[1] - a[1]).slice(0, 3).map(([f, s]) => `${f} ${s}`).join(', '); + assert.ok(total < 45_000, `the first-read source totals ${total} bytes, over 45 KB (largest: ${largest})`); + const cn = statSync(join(appDir, 'lib', 'utils', 'cn.ts')).size; + assert.ok(cn < 14_000, `lib/utils/cn.ts is ${cn} bytes, so its commentary grew back`); + } finally { + await rm(cwd, { recursive: true, force: true }); + } +}); + test('scaffoldApp api: writes API-only template (no layout, no components)', async () => { const cwd = await tempCwd(); const restore = muteConsole(); From e592a9734b1ba567a13f2bc04cc6c1fac3b5de2b Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 00:21:57 +0530 Subject: [PATCH 05/29] fix: type the redirecting signIn and signOut as Promise Auth.js v5 types the redirecting form of signIn and signOut as Promise, since inside a request it throws the redirect. WebJs typed it Promise, so `return signIn('credentials', formData)` in an action typed Promise, the way the scaffold types every action, failed with TS2322 and an eval build spent a round widening the type. The agent-habits fixture now types that action as the scaffold does. Refs #1697 --- packages/server/index.d.ts | 19 ++++++++++++------- test/types/agent-habits.test-d.ts | 6 ++++-- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/packages/server/index.d.ts b/packages/server/index.d.ts index e93285969..0ecbdc0bb 100644 --- a/packages/server/index.d.ts +++ b/packages/server/index.d.ts @@ -1666,10 +1666,12 @@ export interface AuthInstance { * redirect, so `await signIn('credentials', formData)` in a form action signs * in and navigates; a credentials failure throws {@link CredentialsSignin}. * `{ redirect: false }` (in the options or, as Auth.js accepts it, in the - * data) returns the target url instead of throwing. With no request in scope - * it returns the Response the `/api/auth/*` routes send. The redirecting - * form is typed `Promise`, so `return signIn(...)` fits an action - * that returns `ActionResult | Response`. + * data) returns the target url instead of throwing. The redirecting form is + * typed `Promise`, as Auth.js v5 types it, so `return signIn(...)` + * fits an action typed `Promise`. (Outside a request, which + * only the `/api/auth/*` routes do, and for a provider id the config does + * not name, it resolves to a Response instead, which a form action passes + * through as is.) */ signIn: { ( @@ -1686,12 +1688,15 @@ export interface AuthInstance { provider: string, data?: FormData | Record, opts?: { redirectTo?: string; redirect?: true; req?: Request }, - ): Promise; + ): Promise; }; - /** Auth.js v5's `signOut`: clears the session and throws a redirect inside a request. */ + /** + * Auth.js v5's `signOut`: clears the session and throws a redirect inside a + * request, so the redirecting form is typed `Promise` as in Auth.js. + */ signOut: { (opts: { redirectTo?: string; redirect: false; req?: Request }): Promise; - (opts?: { redirectTo?: string; redirect?: true; req?: Request }): Promise; + (opts?: { redirectTo?: string; redirect?: true; req?: Request }): Promise; }; handlers: { GET: (req: Request) => Promise; POST: (req: Request) => Promise }; } diff --git a/test/types/agent-habits.test-d.ts b/test/types/agent-habits.test-d.ts index f5c94a8ca..a14a61fa1 100644 --- a/test/types/agent-habits.test-d.ts +++ b/test/types/agent-habits.test-d.ts @@ -31,12 +31,14 @@ export function fieldErrorHabits({ actionData }: PageProps<'/rooms/[id]'>): stri // Auth.js's signIn redirects by throwing, so an action returns it as is, and // redirect: false (in the options or in the data) yields the target url. -// (Replay r3-before-roomly3: a sign-up action.) +// (Replay r3-before-roomly3: a sign-up action.) The action is typed the way +// the scaffold types every action, Promise, which a Response +// return did not fit (#1697, an eval build's TS2322). export async function signInHabits( signIn: AuthInstance['signIn'], signOut: AuthInstance['signOut'], form: FormData, -): Promise { +): Promise { const url: string = await signIn('credentials', form, { redirect: false }); const url2: string = await signIn('credentials', { email: 'a@b.c', redirect: false }); const out: string = await signOut({ redirect: false }); From 430f7a2afdc2e54027a712d14451ab32a07c3218 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 12 Nov 2026 00:23:37 +0530 Subject: [PATCH 06/29] feat: let the kit's class helpers take className like cva shadcn's cva exports (buttonVariants and the rest) take a className, and the kit mirrors each under shadcn's name. An eval agent wrote the habit under the kit's own name, buttonClass({ variant: 'link', className }), and spent a typecheck round switching to buttonVariants. The 17 helpers with a shadcn alias now take className themselves, merged through cn() only when given, so every existing call returns the same string. Each alias is now the helper itself. Refs #1697 --- packages/ui/AGENTS.md | 5 +++- .../registry/components/attachment.ts | 10 ++++---- .../ui/packages/registry/components/badge.ts | 5 ++-- .../ui/packages/registry/components/bubble.ts | 10 ++++---- .../registry/components/button-group.ts | 5 ++-- .../ui/packages/registry/components/button.ts | 5 ++-- .../registry/components/code-block.ts | 10 ++++---- .../registry/components/input-group.ts | 10 ++++---- .../ui/packages/registry/components/item.ts | 10 ++++---- .../ui/packages/registry/components/marker.ts | 5 ++-- .../packages/registry/components/sidebar.ts | 5 ++-- .../ui/packages/registry/components/tabs.ts | 5 ++-- .../ui/packages/registry/components/toggle.ts | 5 ++-- packages/ui/test/class-helpers.test.js | 23 +++++++++++++++++++ 14 files changed, 78 insertions(+), 35 deletions(-) diff --git a/packages/ui/AGENTS.md b/packages/ui/AGENTS.md index 6d9dc546c..1708f6dc9 100644 --- a/packages/ui/AGENTS.md +++ b/packages/ui/AGENTS.md @@ -284,7 +284,10 @@ function per component (`buttonVariants`, `badgeVariants`, `toggleVariants`, `tabsListVariants`, and later `buttonGroupVariants`, `markerVariants`, `navigationMenuTriggerStyle`). The kit exports each under the same name, beside its own helper, so shadcn code ports verbatim. Each returns exactly what the -helper returns, and like `cva` it merges a `className` option into the result. +helper returns, and like `cva` both merge a `className` option into the result +(#1697: the kit's own name takes it too, since an agent writes +`buttonClass({ variant, className })` from the same habit). With no +`className` the helper's output is unchanged. ## Blocks and charts (#1666, D18) diff --git a/packages/ui/packages/registry/components/attachment.ts b/packages/ui/packages/registry/components/attachment.ts index 621e9e9c3..6e7426266 100644 --- a/packages/ui/packages/registry/components/attachment.ts +++ b/packages/ui/packages/registry/components/attachment.ts @@ -50,7 +50,8 @@ const ATTACHMENT_ORIENTATIONS = { } as const; /** The part, with its variant options. Set its `data-slot` and any `data-variant` / `data-size` to match. */ -export function attachmentClass(opts: { size?: keyof typeof ATTACHMENT_SIZES; orientation?: keyof typeof ATTACHMENT_ORIENTATIONS } = {}): string { +export function attachmentClass(opts: { size?: keyof typeof ATTACHMENT_SIZES; orientation?: keyof typeof ATTACHMENT_ORIENTATIONS } & { className?: string } = {}): string { + if (opts.className) return cn(attachmentClass({ ...opts, className: undefined }), opts.className); return cn(ATTACHMENT_BASE, ATTACHMENT_SIZES[opts.size ?? 'default'], ATTACHMENT_ORIENTATIONS[opts.orientation ?? 'horizontal']); } @@ -59,7 +60,7 @@ export function attachmentClass(opts: { size?: keyof typeof ATTACHMENT_SIZES; or * it merges a `className` into the result. */ export function attachmentVariants(opts: { size?: keyof typeof ATTACHMENT_SIZES; orientation?: keyof typeof ATTACHMENT_ORIENTATIONS } & { className?: string } = {}): string { - return cn(attachmentClass(opts), opts.className); + return attachmentClass(opts); } const ATTACHMENT_MEDIA_BASE = @@ -71,7 +72,8 @@ const ATTACHMENT_MEDIA_VARIANTS = { } as const; /** The part, with its variant options. Set its `data-slot` and any `data-variant` / `data-size` to match. */ -export function attachmentMediaClass(opts: { variant?: keyof typeof ATTACHMENT_MEDIA_VARIANTS } = {}): string { +export function attachmentMediaClass(opts: { variant?: keyof typeof ATTACHMENT_MEDIA_VARIANTS } & { className?: string } = {}): string { + if (opts.className) return cn(attachmentMediaClass({ ...opts, className: undefined }), opts.className); return cn(ATTACHMENT_MEDIA_BASE, ATTACHMENT_MEDIA_VARIANTS[opts.variant ?? 'icon']); } @@ -80,7 +82,7 @@ export function attachmentMediaClass(opts: { variant?: keyof typeof ATTACHMENT_M * it merges a `className` into the result. */ export function attachmentMediaVariants(opts: { variant?: keyof typeof ATTACHMENT_MEDIA_VARIANTS } & { className?: string } = {}): string { - return cn(attachmentMediaClass(opts), opts.className); + return attachmentMediaClass(opts); } /** Set `data-slot="attachment-content"` on the element. */ diff --git a/packages/ui/packages/registry/components/badge.ts b/packages/ui/packages/registry/components/badge.ts index ee961acdb..d31d02838 100644 --- a/packages/ui/packages/registry/components/badge.ts +++ b/packages/ui/packages/registry/components/badge.ts @@ -39,7 +39,8 @@ const VARIANTS = { export type BadgeVariant = keyof typeof VARIANTS; -export function badgeClass(opts: { variant?: BadgeVariant } = {}): string { +export function badgeClass(opts: { variant?: BadgeVariant } & { className?: string } = {}): string { + if (opts.className) return cn(badgeClass({ ...opts, className: undefined }), opts.className); return cn(BASE, VARIANTS[opts.variant ?? 'default']); } @@ -49,5 +50,5 @@ export function badgeClass(opts: { variant?: BadgeVariant } = {}): string { * merges a `className` into the result. */ export function badgeVariants(opts: { variant?: BadgeVariant } & { className?: string } = {}): string { - return cn(badgeClass(opts), opts.className); + return badgeClass(opts); } diff --git a/packages/ui/packages/registry/components/bubble.ts b/packages/ui/packages/registry/components/bubble.ts index 6a7aea581..26720b166 100644 --- a/packages/ui/packages/registry/components/bubble.ts +++ b/packages/ui/packages/registry/components/bubble.ts @@ -51,7 +51,8 @@ const BUBBLE_VARIANTS = { } as const; /** The part, with its variant options. Set its `data-slot` and any `data-variant` / `data-size` to match. */ -export function bubbleClass(opts: { variant?: keyof typeof BUBBLE_VARIANTS } = {}): string { +export function bubbleClass(opts: { variant?: keyof typeof BUBBLE_VARIANTS } & { className?: string } = {}): string { + if (opts.className) return cn(bubbleClass({ ...opts, className: undefined }), opts.className); return cn(BUBBLE_BASE, BUBBLE_VARIANTS[opts.variant ?? 'default']); } @@ -60,7 +61,7 @@ export function bubbleClass(opts: { variant?: keyof typeof BUBBLE_VARIANTS } = { * it merges a `className` into the result. */ export function bubbleVariants(opts: { variant?: keyof typeof BUBBLE_VARIANTS } & { className?: string } = {}): string { - return cn(bubbleClass(opts), opts.className); + return bubbleClass(opts); } /** Set `data-slot="bubble-content"` on the element. */ @@ -82,7 +83,8 @@ const BUBBLE_REACTIONS_ALIGNS = { } as const; /** The part, with its variant options. Set its `data-slot` and any `data-variant` / `data-size` to match. */ -export function bubbleReactionsClass(opts: { side?: keyof typeof BUBBLE_REACTIONS_SIDES; align?: keyof typeof BUBBLE_REACTIONS_ALIGNS } = {}): string { +export function bubbleReactionsClass(opts: { side?: keyof typeof BUBBLE_REACTIONS_SIDES; align?: keyof typeof BUBBLE_REACTIONS_ALIGNS } & { className?: string } = {}): string { + if (opts.className) return cn(bubbleReactionsClass({ ...opts, className: undefined }), opts.className); return cn(BUBBLE_REACTIONS_BASE, BUBBLE_REACTIONS_SIDES[opts.side ?? 'bottom'], BUBBLE_REACTIONS_ALIGNS[opts.align ?? 'end']); } @@ -91,5 +93,5 @@ export function bubbleReactionsClass(opts: { side?: keyof typeof BUBBLE_REACTION * it merges a `className` into the result. */ export function bubbleReactionsVariants(opts: { side?: keyof typeof BUBBLE_REACTIONS_SIDES; align?: keyof typeof BUBBLE_REACTIONS_ALIGNS } & { className?: string } = {}): string { - return cn(bubbleReactionsClass(opts), opts.className); + return bubbleReactionsClass(opts); } diff --git a/packages/ui/packages/registry/components/button-group.ts b/packages/ui/packages/registry/components/button-group.ts index 04342e01c..ab5645a8a 100644 --- a/packages/ui/packages/registry/components/button-group.ts +++ b/packages/ui/packages/registry/components/button-group.ts @@ -46,7 +46,8 @@ const ORIENTATIONS = { export type ButtonGroupOrientation = keyof typeof ORIENTATIONS; /** The group container. Pair with `role="group"` and `data-orientation`. */ -export function buttonGroupClass(opts: { orientation?: ButtonGroupOrientation } = {}): string { +export function buttonGroupClass(opts: { orientation?: ButtonGroupOrientation } & { className?: string } = {}): string { + if (opts.className) return cn(buttonGroupClass({ ...opts, className: undefined }), opts.className); return cn(BASE, ORIENTATIONS[opts.orientation ?? 'horizontal']); } @@ -56,7 +57,7 @@ export function buttonGroupClass(opts: { orientation?: ButtonGroupOrientation } * Like cva, it merges a `className` into the result. */ export function buttonGroupVariants(opts: { orientation?: ButtonGroupOrientation } & { className?: string } = {}): string { - return cn(buttonGroupClass(opts), opts.className); + return buttonGroupClass(opts); } /** A non-interactive label or value sitting inside the group. */ diff --git a/packages/ui/packages/registry/components/button.ts b/packages/ui/packages/registry/components/button.ts index 055a88ee3..b0c2a1d6f 100644 --- a/packages/ui/packages/registry/components/button.ts +++ b/packages/ui/packages/registry/components/button.ts @@ -74,7 +74,8 @@ export interface ButtonClassOptions { } /** Compose Tailwind classes for a button. Stable shape: object-arg, both optional. */ -export function buttonClass(opts: ButtonClassOptions = {}): string { +export function buttonClass(opts: ButtonClassOptions & { className?: string } = {}): string { + if (opts.className) return cn(buttonClass({ ...opts, className: undefined }), opts.className); const variant = opts.variant ?? 'default'; const size = opts.size ?? 'default'; return cn(BASE, VARIANTS[variant], SIZES[size]); @@ -86,5 +87,5 @@ export function buttonClass(opts: ButtonClassOptions = {}): string { * merges a `className` into the result. */ export function buttonVariants(opts: ButtonClassOptions & { className?: string } = {}): string { - return cn(buttonClass(opts), opts.className); + return buttonClass(opts); } diff --git a/packages/ui/packages/registry/components/code-block.ts b/packages/ui/packages/registry/components/code-block.ts index 6d449dee2..2e6130a43 100644 --- a/packages/ui/packages/registry/components/code-block.ts +++ b/packages/ui/packages/registry/components/code-block.ts @@ -56,13 +56,14 @@ const CODE_BLOCK_VARIANTS = { export type CodeBlockVariant = keyof typeof CODE_BLOCK_VARIANTS; /** The frame's classes. */ -export function codeBlockClass(opts: { variant?: CodeBlockVariant } = {}): string { +export function codeBlockClass(opts: { variant?: CodeBlockVariant } & { className?: string } = {}): string { + if (opts.className) return cn(codeBlockClass({ ...opts, className: undefined }), opts.className); return cn('cn-code-block group/code-block relative flex w-full min-w-0 flex-col overflow-hidden', CODE_BLOCK_VARIANTS[opts.variant ?? 'default']); } /** shadcn's name for {@link codeBlockClass}. Like cva, it merges a `className`. */ export function codeBlockVariants(opts: { variant?: CodeBlockVariant; className?: string } = {}): string { - return cn(codeBlockClass(opts), opts.className); + return codeBlockClass(opts); } /** The header row. */ @@ -100,7 +101,8 @@ const CODE_BLOCK_LINE_VARIANTS = { export type CodeBlockLineVariant = keyof typeof CODE_BLOCK_LINE_VARIANTS; /** One line's classes. */ -export function codeBlockLineClass(opts: { variant?: CodeBlockLineVariant } = {}): string { +export function codeBlockLineClass(opts: { variant?: CodeBlockLineVariant } & { className?: string } = {}): string { + if (opts.className) return cn(codeBlockLineClass({ ...opts, className: undefined }), opts.className); return cn( "cn-code-block-line relative block min-h-lh after:absolute after:top-0 after:select-none in-data-numbered:col-span-2 in-data-numbered:grid in-data-numbered:grid-cols-subgrid in-data-numbered:[counter-increment:line] in-data-numbered:before:content-[counter(line)] in-data-numbered:before:select-none in-data-numbered:supports-[content:counter(line)_/_'']:before:content-[counter(line)_/_'']", CODE_BLOCK_LINE_VARIANTS[opts.variant ?? 'default'], @@ -109,7 +111,7 @@ export function codeBlockLineClass(opts: { variant?: CodeBlockLineVariant } = {} /** shadcn's name for {@link codeBlockLineClass}. Like cva, it merges a `className`. */ export function codeBlockLineVariants(opts: { variant?: CodeBlockLineVariant; className?: string } = {}): string { - return cn(codeBlockLineClass(opts), opts.className); + return codeBlockLineClass(opts); } /** The footer row. */ diff --git a/packages/ui/packages/registry/components/input-group.ts b/packages/ui/packages/registry/components/input-group.ts index 3bc89ba72..2d452b63c 100644 --- a/packages/ui/packages/registry/components/input-group.ts +++ b/packages/ui/packages/registry/components/input-group.ts @@ -55,7 +55,8 @@ const INPUT_GROUP_ADDON_ALIGNS = { } as const; /** The part, with its variant options. Set its `data-slot` and any `data-variant` / `data-size` to match. */ -export function inputGroupAddonClass(opts: { align?: keyof typeof INPUT_GROUP_ADDON_ALIGNS } = {}): string { +export function inputGroupAddonClass(opts: { align?: keyof typeof INPUT_GROUP_ADDON_ALIGNS } & { className?: string } = {}): string { + if (opts.className) return cn(inputGroupAddonClass({ ...opts, className: undefined }), opts.className); return cn(INPUT_GROUP_ADDON_BASE, INPUT_GROUP_ADDON_ALIGNS[opts.align ?? 'inline-start']); } @@ -64,7 +65,7 @@ export function inputGroupAddonClass(opts: { align?: keyof typeof INPUT_GROUP_AD * it merges a `className` into the result. */ export function inputGroupAddonVariants(opts: { align?: keyof typeof INPUT_GROUP_ADDON_ALIGNS } & { className?: string } = {}): string { - return cn(inputGroupAddonClass(opts), opts.className); + return inputGroupAddonClass(opts); } const INPUT_GROUP_BUTTON_BASE = @@ -84,7 +85,8 @@ const INPUT_GROUP_BUTTON_SIZES = { * with these classes on top, so the button's own classes come first and the * group's size wins a conflict. */ -export function inputGroupButtonClass(opts: { size?: keyof typeof INPUT_GROUP_BUTTON_SIZES; variant?: ButtonVariant } = {}): string { +export function inputGroupButtonClass(opts: { size?: keyof typeof INPUT_GROUP_BUTTON_SIZES; variant?: ButtonVariant } & { className?: string } = {}): string { + if (opts.className) return cn(inputGroupButtonClass({ ...opts, className: undefined }), opts.className); return cn(buttonClass({ variant: opts.variant ?? 'ghost' }), INPUT_GROUP_BUTTON_BASE, INPUT_GROUP_BUTTON_SIZES[opts.size ?? 'xs']); } @@ -93,7 +95,7 @@ export function inputGroupButtonClass(opts: { size?: keyof typeof INPUT_GROUP_BU * it merges a `className` into the result. */ export function inputGroupButtonVariants(opts: { size?: keyof typeof INPUT_GROUP_BUTTON_SIZES; variant?: ButtonVariant } & { className?: string } = {}): string { - return cn(inputGroupButtonClass(opts), opts.className); + return inputGroupButtonClass(opts); } /** A part with no `data-slot` of its own. */ diff --git a/packages/ui/packages/registry/components/item.ts b/packages/ui/packages/registry/components/item.ts index 2cfb39a27..0bd35bad1 100644 --- a/packages/ui/packages/registry/components/item.ts +++ b/packages/ui/packages/registry/components/item.ts @@ -69,7 +69,8 @@ const ITEM_SIZES = { } as const; /** The part, with its variant options. Set its `data-slot` and any `data-variant` / `data-size` to match. */ -export function itemClass(opts: { variant?: keyof typeof ITEM_VARIANTS; size?: keyof typeof ITEM_SIZES } = {}): string { +export function itemClass(opts: { variant?: keyof typeof ITEM_VARIANTS; size?: keyof typeof ITEM_SIZES } & { className?: string } = {}): string { + if (opts.className) return cn(itemClass({ ...opts, className: undefined }), opts.className); return cn(ITEM_BASE, ITEM_VARIANTS[opts.variant ?? 'default'], ITEM_SIZES[opts.size ?? 'default']); } @@ -78,7 +79,7 @@ export function itemClass(opts: { variant?: keyof typeof ITEM_VARIANTS; size?: k * it merges a `className` into the result. */ export function itemVariants(opts: { variant?: keyof typeof ITEM_VARIANTS; size?: keyof typeof ITEM_SIZES } & { className?: string } = {}): string { - return cn(itemClass(opts), opts.className); + return itemClass(opts); } const ITEM_MEDIA_BASE = @@ -91,7 +92,8 @@ const ITEM_MEDIA_VARIANTS = { } as const; /** The part, with its variant options. Set its `data-slot` and any `data-variant` / `data-size` to match. */ -export function itemMediaClass(opts: { variant?: keyof typeof ITEM_MEDIA_VARIANTS } = {}): string { +export function itemMediaClass(opts: { variant?: keyof typeof ITEM_MEDIA_VARIANTS } & { className?: string } = {}): string { + if (opts.className) return cn(itemMediaClass({ ...opts, className: undefined }), opts.className); return cn(ITEM_MEDIA_BASE, ITEM_MEDIA_VARIANTS[opts.variant ?? 'default']); } @@ -100,7 +102,7 @@ export function itemMediaClass(opts: { variant?: keyof typeof ITEM_MEDIA_VARIANT * it merges a `className` into the result. */ export function itemMediaVariants(opts: { variant?: keyof typeof ITEM_MEDIA_VARIANTS } & { className?: string } = {}): string { - return cn(itemMediaClass(opts), opts.className); + return itemMediaClass(opts); } /** Set `data-slot="item-content"` on the element. */ diff --git a/packages/ui/packages/registry/components/marker.ts b/packages/ui/packages/registry/components/marker.ts index 14303a62f..40933711c 100644 --- a/packages/ui/packages/registry/components/marker.ts +++ b/packages/ui/packages/registry/components/marker.ts @@ -40,7 +40,8 @@ const VARIANTS = { export type MarkerVariant = keyof typeof VARIANTS; /** The marker row. Pair with `data-variant` set to the same variant. */ -export function markerClass(opts: { variant?: MarkerVariant } = {}): string { +export function markerClass(opts: { variant?: MarkerVariant } & { className?: string } = {}): string { + if (opts.className) return cn(markerClass({ ...opts, className: undefined }), opts.className); return cn(BASE, VARIANTS[opts.variant ?? 'default']); } @@ -49,7 +50,7 @@ export function markerClass(opts: { variant?: MarkerVariant } = {}): string { * cva, it merges a `className` into the result. */ export function markerVariants(opts: { variant?: MarkerVariant } & { className?: string } = {}): string { - return cn(markerClass(opts), opts.className); + return markerClass(opts); } /** The leading icon. */ diff --git a/packages/ui/packages/registry/components/sidebar.ts b/packages/ui/packages/registry/components/sidebar.ts index d88a9949f..72343cd3c 100644 --- a/packages/ui/packages/registry/components/sidebar.ts +++ b/packages/ui/packages/registry/components/sidebar.ts @@ -164,7 +164,8 @@ export type SidebarMenuButtonVariant = keyof typeof MENU_BUTTON_VARIANTS; export type SidebarMenuButtonSize = keyof typeof MENU_BUTTON_SIZES; /** A menu button (an or a + \${latest.length > 0 ? html\`
- +
\` : nothing}
@@ -1637,95 +1588,6 @@ export default async function Home({ actionData }: PageProps) { // AGENTS.md is copied via the `templateFiles` loop above, from // `packages/cli/templates/AGENTS.md` with `{{APP_NAME}}` substitution. - // --- Theme toggle component --- - - await writeFile(join(appDir, 'components', 'theme-toggle.ts'), `import { WebComponent, html } from '@webjsdev/core'; -import { buttonClass } from '#components/ui/button.ts'; - -type Theme = 'system' | 'light' | 'dark'; - -/** - * is a light-DOM component styled with Tailwind utilities. - * - * Light DOM is the default: no static shadow = true, no static styles. It - * is the UI kit's ghost icon Button (components/ui/button.ts), and it reacts - * through Lit's APIs (reactive state, an @click binding, the connected / - * disconnected lifecycle), never a