@ghuri/core 0.1.0-alpha.1 → 0.1.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -101,6 +101,8 @@ setting('PAGE_SIZE', 20) // with a fallback
101
101
  | `MIDDLEWARE` | `[]` | Middleware classes, instances, or plain Hono middleware. |
102
102
  | `ROOT_URLCONF` | — | Your URL patterns. |
103
103
  | `APPEND_SLASH` | `true` | Redirect `/x` → `/x/` when only the slashed URL exists. |
104
+ | `HANDLER_404` | — | Custom 404 view `(c, exception) => Response` (Django's `handler404`). See [Errors](#errors). |
105
+ | `HANDLER_500` | — | Custom 500 view `(c, exception) => Response` (Django's `handler500`). See [Errors](#errors). |
104
106
  | `CACHES` | in-memory | `{ default: kvCache('CACHE') }` |
105
107
  | `CSRF_TRUSTED_ORIGINS` | `[]` | e.g. `['https://*.example.com']` |
106
108
  | `CORS` | `false` | `{ allowOrigins: ['https://app.example.com'], allowCredentials: true }` |
@@ -269,6 +271,39 @@ path is under `/api`; HTML otherwise. With `DEBUG`, 500s show a debug page with
269
271
  request and (masked) settings, and 404s list the URL patterns that were tried — like Django.
270
272
  Production pages never reveal details.
271
273
 
274
+ ### Custom error pages (`HANDLER_404`, `HANDLER_500`)
275
+
276
+ Django's `handler404` / `handler500` are settings in Ghuri. Each is a view that gets the Hono context and
277
+ the exception and returns a Response:
278
+
279
+ ```tsx
280
+ import { defineSettings, notFoundResponse, render, wantsJson } from '@ghuri/core'
281
+
282
+ export default defineSettings((env) => ({
283
+ // …
284
+ HANDLER_404: (c, exception) => {
285
+ if (wantsJson(c)) return notFoundResponse(c) // keep the built-in JSON 404 for API clients
286
+ return render(c, <NotFound tenant={c.get('tenant')} />, { status: 404 })
287
+ },
288
+ HANDLER_500: (c) => c.html('<h1>Something went wrong</h1>', 500),
289
+ }))
290
+ ```
291
+
292
+ - `HANDLER_404` is called for paths no URL pattern matches, **after** the `APPEND_SLASH` redirect and the
293
+ 405 check for method-restricted routes (405s are never sent to it), and for `Http404` /
294
+ `ObjectDoesNotExist` raised by views or middleware. For unmatched paths the exception is a
295
+ `Resolver404`. It runs at the end of the middleware chain, inside the request context, so values set
296
+ by `MIDDLEWARE` (the current tenant, the user, …) are available, and middleware still sees its response.
297
+ - `HANDLER_500` is called for uncaught exceptions — errors not mapped to a status (`PermissionDenied`,
298
+ `ValidationError`, `HttpError` subclasses, Hono's `HTTPException` keep their default responses).
299
+ - Both are used for every client, HTML or JSON, like Django. Use `wantsJson(c)` and `notFoundResponse(c)`
300
+ (the built-in 404, which never calls `HANDLER_404`) to keep JSON errors for API clients.
301
+ `@ghuri/rest` views turn `Http404` into their own JSON `NotFound`, so they never reach it.
302
+ - With `DEBUG` on, they are not called: the technical 404 / 500 pages show instead, as in Django.
303
+ - If a handler throws (or returns something that is not a Response), the error is logged and the default
304
+ 404 / 500 page is used. (Django renders the 500 page when `handler404` fails.)
305
+ - Status codes are whatever the handler returns: pass `404` / `500` yourself.
306
+
272
307
  Packages and projects can map their own errors:
273
308
 
274
309
  ```ts
@@ -849,6 +849,20 @@ function currentResolver(settings) {
849
849
  return void 0;
850
850
  }
851
851
  }
852
+ async function renderErrorView(name, c, exception, settings) {
853
+ if (!hasErrorView(name, settings)) return void 0;
854
+ try {
855
+ const res = await settings[name](c, exception);
856
+ if (res instanceof Response) return res;
857
+ console.error(`${name} did not return a Response; using the default error page.`);
858
+ } catch (err) {
859
+ console.error(`${name} raised an error; using the default error page:`, err);
860
+ }
861
+ return void 0;
862
+ }
863
+ function hasErrorView(name, settings) {
864
+ return typeof settings?.[name] === "function" && !settings?.DEBUG;
865
+ }
852
866
  function errorBody(c, status, payload, html, headers) {
853
867
  const res = wantsJson(c) ? new Response(JSON.stringify(payload), {
854
868
  status,
@@ -912,6 +926,8 @@ async function handleException(err, c) {
912
926
  technical404(c, message, currentResolver(settings), true)
913
927
  );
914
928
  }
929
+ const custom2 = await renderErrorView("HANDLER_404", c, err, settings);
930
+ if (custom2) return custom2;
915
931
  return errorBody(c, 404, { detail: err instanceof Http404 ? message : "Not found." }, simplePage(404, ""));
916
932
  }
917
933
  if (err instanceof MethodNotAllowed) {
@@ -930,6 +946,8 @@ async function handleException(err, c) {
930
946
  );
931
947
  }
932
948
  console.error(err);
949
+ const custom = await renderErrorView("HANDLER_500", c, err, settings);
950
+ if (custom) return custom;
933
951
  if (debug) {
934
952
  const e = err instanceof Error ? err : new Error(String(err));
935
953
  return errorBody(
@@ -969,6 +987,10 @@ function notFoundHandler(urlconf) {
969
987
  return handleException(new MethodNotAllowed(c.req.method, [...allowed]), c);
970
988
  }
971
989
  }
990
+ if (hasErrorView("HANDLER_404", settings)) {
991
+ const exception = new Resolver404(`No URL pattern matches '${c.req.path}'.`);
992
+ return renderErrorView("HANDLER_404", c, exception, settings).then((res) => res ?? notFoundResponse(c));
993
+ }
972
994
  return notFoundResponse(c);
973
995
  };
974
996
  }
@@ -1268,4 +1290,4 @@ export {
1268
1290
  enforceCsrf,
1269
1291
  setCsrfCookieIfNeeded
1270
1292
  };
1271
- //# sourceMappingURL=chunk-BQBV57DI.js.map
1293
+ //# sourceMappingURL=chunk-LDWLVUKY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/context.ts","../src/urls.ts","../src/exceptions.ts","../src/csrf.ts"],"sourcesContent":["/** Base class for every error thrown by Ghuri packages. */\nexport class GhuriError extends Error {\n constructor(message?: string, options?: { cause?: unknown }) {\n super(message, options)\n this.name = new.target.name\n }\n}\n\n/** Settings or app setup is wrong (Django: ImproperlyConfigured). */\nexport class ImproperlyConfigured extends GhuriError {}\n\n/** Apps registry used before `apps.populate()` finished (Django: AppRegistryNotReady). */\nexport class AppRegistryNotReady extends GhuriError {}\n\nexport class ObjectDoesNotExist extends GhuriError {}\nexport class MultipleObjectsReturned extends GhuriError {}\n\n/** HTTP-mapped errors. `status` is used by the default error handler. */\nexport class HttpError extends GhuriError {\n status = 500\n}\nexport class Http404 extends HttpError {\n override status = 404\n constructor(message = 'Not found.') {\n super(message)\n }\n}\nexport class PermissionDenied extends HttpError {\n override status = 403\n constructor(message = 'Permission denied.') {\n super(message)\n }\n}\nexport class BadRequest extends HttpError {\n override status = 400\n constructor(message = 'Bad request.') {\n super(message)\n }\n}\nexport class SuspiciousOperation extends HttpError {\n override status = 400\n constructor(message = 'Suspicious operation.') {\n super(message)\n }\n}\n\nexport type ValidationMessages = string[] | Record<string, string[]>\n\n/**\n * Validation failure. Mirrors Django's ValidationError:\n * - `new ValidationError('msg')` → messages ['msg']\n * - `new ValidationError(['a', 'b'])`\n * - `new ValidationError({ title: ['Too long'] })` → messageDict\n */\nexport class ValidationError extends GhuriError {\n readonly messages: string[]\n readonly messageDict?: Record<string, string[]>\n readonly code?: string\n\n constructor(message: string | string[] | Record<string, string | string[]>, options?: { code?: string }) {\n const normalized = ValidationError.normalize(message)\n super(Array.isArray(normalized) ? normalized.join(' ') : JSON.stringify(normalized))\n this.code = options?.code\n if (Array.isArray(normalized)) {\n this.messages = normalized\n } else {\n this.messageDict = normalized\n this.messages = Object.values(normalized).flat()\n }\n }\n\n get hasFieldErrors(): boolean {\n return this.messageDict !== undefined\n }\n\n /** Merge into a field → messages dict; non-field errors go under `nonFieldKey`. */\n toDict(nonFieldKey = '__all__'): Record<string, string[]> {\n return this.messageDict ?? { [nonFieldKey]: this.messages }\n }\n\n private static normalize(m: string | string[] | Record<string, string | string[]>): ValidationMessages {\n if (typeof m === 'string') return [m]\n if (Array.isArray(m)) return m\n const out: Record<string, string[]> = {}\n for (const [k, v] of Object.entries(m)) out[k] = Array.isArray(v) ? v : [v]\n return out\n }\n}\n\n/** A view does not support the request method (405). `allowed` becomes the `Allow` header. */\nexport class MethodNotAllowed extends HttpError {\n override status = 405\n constructor(\n readonly method: string,\n readonly allowed: string[] = [],\n message = `Method \"${method.toUpperCase()}\" not allowed.`,\n ) {\n super(message)\n }\n}\n\n/** The request's Host header is not in ALLOWED_HOSTS (Django: DisallowedHost). */\nexport class DisallowedHost extends SuspiciousOperation {\n constructor(message = 'Invalid HTTP_HOST header.') {\n super(message)\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { Context as HonoContext } from 'hono'\nimport { ImproperlyConfigured } from './errors'\nimport type { GhuriSettings } from './settings'\n\nexport type Env = Record<string, any>\n\nexport interface ExecutionContextLike {\n waitUntil(promise: Promise<unknown>): void\n passThroughOnException?(): void\n}\n\n/** Everything that belongs to the current request (or CLI/test run). */\nexport interface GhuriContext {\n env: Env\n settings: GhuriSettings\n executionCtx?: ExecutionContextLike\n request?: Request\n hono?: HonoContext\n /** Per-request cache. Packages store their own state under a unique symbol. */\n state: Map<string | symbol, unknown>\n}\n\n// One storage per process, even if the module is loaded twice (e.g. CJS/ESM or bundling quirks).\nconst STORAGE_KEY = Symbol.for('ghuri.core.contextStorage')\nconst GLOBAL_KEY = Symbol.for('ghuri.core.globalContext')\nconst g = globalThis as any\nconst storage: AsyncLocalStorage<GhuriContext> = (g[STORAGE_KEY] ??= new AsyncLocalStorage<GhuriContext>())\n\nexport function runWithContext<T>(ctx: GhuriContext, fn: () => T): T {\n return storage.run(ctx, fn)\n}\n\n/** Fallback context used outside requests (CLI, scripts, tests). */\nexport function setGlobalContext(ctx: GhuriContext | undefined): void {\n g[GLOBAL_KEY] = ctx\n}\n\nexport function tryGetContext(): GhuriContext | undefined {\n return storage.getStore() ?? (g[GLOBAL_KEY] as GhuriContext | undefined)\n}\n\nexport function getContext(): GhuriContext {\n const ctx = tryGetContext()\n if (!ctx) {\n throw new ImproperlyConfigured(\n 'No Ghuri context. Code that touches settings, the database or storage must run inside a request ' +\n 'handled by createApp(), inside runWithContext(), or after app.setup(env) (CLI/tests).',\n )\n }\n return ctx\n}\n\nexport function getEnv(): Env {\n return getContext().env\n}\n\nexport function createContext(\n init: Omit<GhuriContext, 'state'> & { state?: GhuriContext['state'] },\n): GhuriContext {\n return { ...init, state: init.state ?? new Map() }\n}\n","import type { Context, Hono, Next } from 'hono'\nimport { tryGetContext } from './context'\nimport { GhuriError, Http404, ImproperlyConfigured } from './errors'\n\n// ---------------------------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------------------------\n\n/** A view is a plain Hono handler that receives the request context and returns a Response. */\nexport type ViewFunction = (c: Context) => Response | Promise<Response>\n\n/** Any Hono application (escape hatch: `path('legacy/', someHonoApp)`). */\nexport type HonoApp = Hono<any, any, any>\n\n/** One URL pattern. Build it with `path()` / `rePath()` rather than by hand. */\nexport interface UrlEntry {\n /** Django-style route (`'posts/<int:id>/'`) or, when `regex` is true, a regular expression. */\n route: string\n view?: ViewFunction\n /** A mounted Hono application. */\n app?: HonoApp\n /** Included patterns (`include()`, or `path('admin/', admin.site.urls)`). */\n children?: UrlPatterns\n name?: string\n namespace?: string\n /** Restrict the route to these HTTP methods (other methods get 405). */\n methods?: string[]\n /** `true` for `rePath()` entries. */\n regex?: boolean\n /** Extra keyword arguments merged into `kwargs(c)` (Django's `path(..., kwargs={...})`). */\n kwargs?: Record<string, unknown>\n}\n\n/** A list of URL patterns. May carry an `appName` (Django's `app_name`) used as default namespace. */\nexport type UrlPatterns = UrlEntry[] & { appName?: string }\n\nconst INCLUDE = Symbol.for('ghuri.urls.include')\n\n/** Result of `include()`. */\nexport interface UrlInclude {\n readonly [INCLUDE]: true\n patterns: UrlPatterns\n namespace?: string\n}\n\n/** Something that can be included: patterns, an `include()` result, or a urls module. */\nexport type Includable = UrlPatterns | UrlInclude | { urlpatterns: UrlPatterns; appName?: string }\n\n/** Anything with a static `asView()` (class-based views). */\nexport interface ViewClassLike {\n asView(initkwargs?: any): ViewFunction\n}\n\nexport type PathTarget = ViewFunction | ViewClassLike | HonoApp | Includable\n\nexport interface PathOptions {\n name?: string\n methods?: string[]\n kwargs?: Record<string, unknown>\n}\n\n// ---------------------------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------------------------\n\n/** `reverse()` could not build a URL (Django: NoReverseMatch). */\nexport class NoReverseMatch extends GhuriError {}\n\n/** `resolve()` found no pattern (Django: Resolver404). */\nexport class Resolver404 extends Http404 {}\n\n// ---------------------------------------------------------------------------------------------\n// Converters\n// ---------------------------------------------------------------------------------------------\n\nexport interface Converter<T = unknown> {\n /** Regular expression (JS syntax, no anchors) a value must match. */\n regex: string\n /** URL text → JS value (used by `kwargs(c)`). */\n toJs(value: string): T\n /** JS value → URL text (used by `reverse()`). */\n toUrl(value: unknown): string\n}\n\nconst str: Converter<string> = { regex: '[^/]+', toJs: (v) => v, toUrl: (v) => String(v) }\n\nconst CONVERTERS_KEY = Symbol.for('ghuri.core.urlConverters')\n/** Registered path converters, by name. */\nexport const converters: Record<string, Converter> = ((globalThis as any)[CONVERTERS_KEY] ??= {\n str,\n int: { regex: '[0-9]+', toJs: (v: string) => Number.parseInt(v, 10), toUrl: (v: unknown) => String(v) },\n slug: { regex: '[-a-zA-Z0-9_]+', toJs: (v: string) => v, toUrl: (v: unknown) => String(v) },\n uuid: {\n regex: '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}',\n toJs: (v: string) => v,\n toUrl: (v: unknown) => String(v),\n },\n path: { regex: '.+', toJs: (v: string) => v, toUrl: (v: unknown) => String(v) },\n} satisfies Record<string, Converter>)\n\n/** Django's `register_converter`: `registerConverter('year', { regex: '[0-9]{4}', toJs: Number, toUrl: String })`. */\nexport function registerConverter<T>(name: string, converter: Converter<T>): void {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))\n throw new ImproperlyConfigured(`Invalid converter name '${name}'.`)\n converters[name] = converter as Converter\n}\n\n// ---------------------------------------------------------------------------------------------\n// path() / rePath() / include()\n// ---------------------------------------------------------------------------------------------\n\nfunction isInclude(v: unknown): v is UrlInclude {\n return typeof v === 'object' && v !== null && (v as any)[INCLUDE] === true\n}\n\nfunction isHonoApp(v: unknown): v is HonoApp {\n return (\n typeof v === 'object' &&\n v !== null &&\n typeof (v as any).fetch === 'function' &&\n Array.isArray((v as any).routes) &&\n typeof (v as any).route === 'function'\n )\n}\n\nfunction isViewClass(v: unknown): v is ViewClassLike {\n return typeof v === 'function' && typeof (v as any).asView === 'function'\n}\n\n/**\n * Include other URL patterns, optionally under a namespace:\n * `path('blog/', include(blogUrls, { namespace: 'blog' }))`.\n * Patterns carrying `appName` (or a module exporting `urlpatterns` + `appName`) are namespaced automatically.\n */\nexport function include(target: Includable, opts: { namespace?: string } = {}): UrlInclude {\n if (isInclude(target)) {\n return { [INCLUDE]: true, patterns: target.patterns, namespace: opts.namespace ?? target.namespace }\n }\n let patterns: UrlPatterns\n let appName: string | undefined\n if (Array.isArray(target)) {\n patterns = target\n appName = target.appName\n } else if (target && Array.isArray((target as any).urlpatterns)) {\n patterns = (target as any).urlpatterns\n appName = (target as any).appName ?? (target as any).urlpatterns.appName\n } else {\n throw new ImproperlyConfigured(\n 'include() expects an array of url patterns or a module exporting `urlpatterns`.',\n )\n }\n return { [INCLUDE]: true, patterns, namespace: opts.namespace ?? appName }\n}\n\nfunction makeEntry(route: string, target: PathTarget, opts: PathOptions, regex: boolean): UrlEntry {\n if (typeof route !== 'string')\n throw new ImproperlyConfigured(`path() route must be a string, got ${typeof route}.`)\n const base: UrlEntry = { route, regex: regex || undefined }\n if (opts.name) base.name = opts.name\n if (opts.methods) base.methods = opts.methods.map((m) => m.toUpperCase())\n if (opts.kwargs) base.kwargs = opts.kwargs\n if (isInclude(target)) return { ...base, children: target.patterns, namespace: target.namespace }\n if (Array.isArray(target) || (target && Array.isArray((target as any).urlpatterns))) {\n const inc = include(target as Includable)\n return { ...base, children: inc.patterns, namespace: inc.namespace }\n }\n if (isHonoApp(target)) return { ...base, app: target }\n if (isViewClass(target)) return { ...base, view: target.asView() }\n if (typeof target === 'function') return { ...base, view: target as ViewFunction }\n throw new ImproperlyConfigured(\n `path('${route}', …): the target must be a view function, a View class, a Hono app or include(...).`,\n )\n}\n\n/** Django's `path()`: `path('posts/<int:id>/', postDetail, { name: 'post-detail' })`. */\nexport function path(route: string, target: PathTarget, opts: PathOptions = {}): UrlEntry {\n return makeEntry(route, target, opts, false)\n}\n\n/**\n * Django's `re_path()`. Named groups become parameters; both `(?<name>…)` and Python's `(?P<name>…)` work:\n * `rePath('^archive/(?<year>[0-9]{4})/$', archive)`.\n */\nexport function rePath(regex: string, target: PathTarget, opts: PathOptions = {}): UrlEntry {\n return makeEntry(regex, target, opts, true)\n}\n\n/** Build url patterns with an `appName` (Django's `app_name = 'blog'`). */\nexport function urlpatterns(appName: string | undefined, patterns: UrlEntry[]): UrlPatterns {\n const out = [...patterns] as UrlPatterns\n if (appName) out.appName = appName\n return out\n}\n\n// ---------------------------------------------------------------------------------------------\n// Compilation\n// ---------------------------------------------------------------------------------------------\n\ntype Token = { lit: string } | { param: string; regex: string; converter: Converter }\n\ninterface Part {\n regex: boolean\n source: string\n}\n\n/** A flattened, compiled route. */\nexport interface CompiledRoute {\n kind: 'view' | 'app'\n /** Full human-readable route, e.g. `blog/<slug:slug>/`. */\n pattern: string\n /** Anchored regex matched against the path without its leading slash. */\n regex: RegExp\n /** Hono route path, or null when the route needs regex matching (rePath / complex segments). */\n honoPath: string | null\n params: Array<{ name: string; converter: Converter }>\n /** Reverse tokens, or null when the route cannot be reversed. */\n tokens: Token[] | null\n view?: ViewFunction\n app?: HonoApp\n name?: string\n namespaces: string[]\n /** Namespaced name (`'blog:post-detail'`). */\n fullName?: string\n methods?: string[]\n extraKwargs: Record<string, unknown>\n}\n\n/** What `resolve()` returns (Django's ResolverMatch). */\nexport interface ResolverMatch {\n route: string\n urlName?: string\n namespace: string\n namespaces: string[]\n /** `namespace:urlName`. */\n viewName?: string\n kwargs: Record<string, any>\n view?: ViewFunction\n app?: HonoApp\n methods?: string[]\n compiled: CompiledRoute\n}\n\nconst IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\/]/g, '\\\\$&')\n}\n\nfunction tokenizePath(route: string): Token[] {\n const tokens: Token[] = []\n const re = /<(?:([^<>:]+):)?([^<>]+)>/g\n let last = 0\n for (const m of route.matchAll(re)) {\n if (m.index! > last) tokens.push({ lit: route.slice(last, m.index) })\n const convName = m[1] ?? 'str'\n const name = m[2]\n if (!IDENT.test(name)) {\n throw new ImproperlyConfigured(\n `URL route '${route}' uses parameter name '${name}' which isn't a valid identifier.`,\n )\n }\n const converter = converters[convName]\n if (!converter) {\n throw new ImproperlyConfigured(`URL route '${route}' uses invalid converter '${convName}'.`)\n }\n tokens.push({ param: name, regex: converter.regex, converter })\n last = m.index! + m[0].length\n }\n if (last < route.length) tokens.push({ lit: route.slice(last) })\n if (/[<>]/.test(tokens.map((t) => ('lit' in t ? t.lit : '')).join(''))) {\n throw new ImproperlyConfigured(`URL route '${route}' has unmatched '<' or '>'.`)\n }\n return tokens\n}\n\n/** Find the index of the `)` closing the group that opens at `start` (which points at `(`). */\nfunction closingParen(src: string, start: number): number {\n let depth = 0\n let inClass = false\n for (let i = start; i < src.length; i++) {\n const ch = src[i]\n if (ch === '\\\\') {\n i++\n continue\n }\n if (inClass) {\n if (ch === ']') inClass = false\n continue\n }\n if (ch === '[') inClass = true\n else if (ch === '(') depth++\n else if (ch === ')') {\n depth--\n if (depth === 0) return i\n }\n }\n return -1\n}\n\n/** Python-style `(?P<name>` → JS `(?<name>`. */\nfunction normalizeRegex(src: string): string {\n return src.replace(/\\(\\?P</g, '(?<')\n}\n\n/** Try to turn a simple regex (literal text + named groups) into tokens; null if it is not simple. */\nfunction tokenizeRegex(src: string): Token[] | null {\n const tokens: Token[] = []\n let lit = ''\n let i = 0\n while (i < src.length) {\n const ch = src[i]\n if (ch === '\\\\') {\n const next = src[i + 1]\n if (next !== undefined && /[^A-Za-z0-9]/.test(next)) {\n lit += next\n i += 2\n continue\n }\n return null\n }\n if (ch === '(') {\n const m = /^\\(\\?<([A-Za-z_][A-Za-z0-9_]*)>/.exec(src.slice(i))\n if (!m) return null\n const end = closingParen(src, i)\n if (end < 0) return null\n if (lit) tokens.push({ lit })\n lit = ''\n const inner = src.slice(i + m[0].length, end)\n if (/\\(\\?<[A-Za-z_]/.test(inner)) return null\n tokens.push({ param: m[1], regex: inner, converter: str })\n i = end + 1\n continue\n }\n if ('.*+?[]{}|^$'.includes(ch)) return null\n lit += ch\n i++\n }\n if (lit) tokens.push({ lit })\n return tokens\n}\n\n/**\n * Make a converter regex safe for Hono's `:name{regex}` syntax: Hono's parser does not allow `{`/`}`\n * inside the pattern, so simple `X{n}` / `X{n,m}` quantifiers are expanded; capturing groups become\n * non-capturing. Returns null if the regex cannot be represented.\n */\nfunction honoSafeRegex(regex: string): string | null {\n let out = ''\n let i = 0\n let lastAtom = ''\n while (i < regex.length) {\n const ch = regex[i]\n let atom: string\n if (ch === '\\\\') {\n atom = regex.slice(i, i + 2)\n i += 2\n } else if (ch === '[') {\n let j = i + 1\n if (regex[j] === '^') j++\n if (regex[j] === ']') j++\n while (j < regex.length && regex[j] !== ']') j += regex[j] === '\\\\' ? 2 : 1\n if (j >= regex.length) return null\n atom = regex.slice(i, j + 1)\n i = j + 1\n } else if (ch === '{') {\n const m = /^\\{(\\d+)(?:(,)(\\d*))?\\}/.exec(regex.slice(i))\n if (!m || !lastAtom) return null\n const min = Number(m[1])\n const hasComma = m[2] === ','\n const max = m[3] ? Number(m[3]) : undefined\n if (min > 64 || (max ?? 0) > 64) return null\n // remove the atom we already emitted, then expand\n out = out.slice(0, out.length - lastAtom.length)\n let expanded = lastAtom.repeat(min)\n if (hasComma && max === undefined) expanded += `${lastAtom}*`\n else if (hasComma && max !== undefined) expanded += `${lastAtom}?`.repeat(Math.max(0, max - min))\n out += expanded\n i += m[0].length\n lastAtom = ''\n continue\n } else if (ch === '(' || ch === ')') {\n // Groups make quantifier expansion ambiguous; only allow them when no `{` follows anywhere.\n if (regex.includes('{') || regex.includes('}')) return null\n atom = ch === '(' && regex[i + 1] !== '?' ? '(?:' : ch\n i++\n out += atom\n lastAtom = ''\n continue\n } else {\n atom = ch\n i++\n }\n if (atom === '}') return null\n out += atom\n lastAtom = '*+?|'.includes(atom) ? '' : atom\n }\n if (/[{}]/.test(out)) return null\n return out\n}\n\n/** Hono path for tokens, or null when Hono can't express it. */\nfunction tokensToHono(tokens: Token[]): string | null {\n // Join into segments split on '/'.\n const segments: Token[][] = [[]]\n for (const t of tokens) {\n if ('lit' in t) {\n const pieces = t.lit.split('/')\n pieces.forEach((p, idx) => {\n if (idx > 0) segments.push([])\n if (p) segments[segments.length - 1].push({ lit: p })\n })\n } else {\n segments[segments.length - 1].push(t)\n }\n }\n const out: string[] = []\n for (const seg of segments) {\n if (seg.length === 0) {\n out.push('')\n continue\n }\n if (seg.length > 1) return null\n const t = seg[0]\n if ('lit' in t) {\n if (/[:*{}?()]/.test(t.lit)) return null\n out.push(t.lit)\n } else {\n // A param that can span slashes is only representable as the last segment.\n if (t.regex === '[^/]+') {\n out.push(`:${t.param}`)\n } else {\n const safe = honoSafeRegex(t.regex)\n if (safe === null) return null\n out.push(`:${t.param}{${safe.includes('|') ? `(?:${safe})` : safe}}`)\n }\n }\n }\n return `/${out.join('/')}`\n}\n\nfunction tokensToRegexSource(tokens: Token[]): string {\n return tokens.map((t) => ('lit' in t ? escapeRegex(t.lit) : `(?<${t.param}>${t.regex})`)).join('')\n}\n\nfunction stripAnchors(src: string, isLast: boolean): string {\n let s = src\n if (s.startsWith('^')) s = s.slice(1)\n if (isLast && s.endsWith('$') && !s.endsWith('\\\\$')) s = s.slice(0, -1)\n return s\n}\n\ninterface FlattenState {\n parts: Part[]\n namespaces: string[]\n extraKwargs: Record<string, unknown>\n}\n\nfunction displayPart(p: Part, isLast: boolean): string {\n return p.regex ? stripAnchors(normalizeRegex(p.source), isLast) : p.source\n}\n\nfunction compileParts(\n parts: Part[],\n prefixOnly: boolean,\n): {\n regex: RegExp\n honoPath: string | null\n params: Array<{ name: string; converter: Converter }>\n tokens: Token[] | null\n pattern: string\n} {\n let tokens: Token[] | null = []\n let source = ''\n for (let i = 0; i < parts.length; i++) {\n const p = parts[i]\n const isLast = i === parts.length - 1 && !prefixOnly\n if (p.regex) {\n const body = stripAnchors(normalizeRegex(p.source), isLast)\n const t = tokenizeRegex(body)\n if (t && tokens) tokens.push(...t)\n else tokens = null\n source += body\n } else {\n const t = tokenizePath(p.source)\n if (tokens) tokens.push(...t)\n source += tokensToRegexSource(t)\n }\n }\n const params: Array<{ name: string; converter: Converter }> = []\n if (tokens) {\n for (const t of tokens) if ('param' in t) params.push({ name: t.param, converter: t.converter })\n } else {\n for (const m of source.matchAll(/\\(\\?<([A-Za-z_][A-Za-z0-9_]*)>/g))\n params.push({ name: m[1], converter: str })\n }\n const names = params.map((p) => p.name)\n const dup = names.find((n, i) => names.indexOf(n) !== i)\n const pattern = parts.map((p, i) => displayPart(p, i === parts.length - 1)).join('')\n if (dup) throw new ImproperlyConfigured(`URL pattern '${pattern}' uses parameter '${dup}' more than once.`)\n let regex: RegExp\n try {\n regex = new RegExp(`^${source}${prefixOnly ? '' : '$'}`)\n } catch (err) {\n throw new ImproperlyConfigured(\n `URL pattern '${pattern}' is not a valid regular expression: ${(err as Error).message}`,\n )\n }\n const honoPath = tokens ? tokensToHono(tokens) : null\n return { regex, honoPath, params, tokens, pattern }\n}\n\nfunction flatten(patterns: UrlPatterns, state: FlattenState, out: CompiledRoute[]): void {\n if (!Array.isArray(patterns)) throw new ImproperlyConfigured('URL patterns must be an array.')\n for (const entry of patterns) {\n if (!entry || typeof entry.route !== 'string') {\n throw new ImproperlyConfigured(\n `Invalid URL pattern ${String(entry)}; use path() / rePath() / include().`,\n )\n }\n const route = entry.regex ? entry.route : entry.route.replace(/^\\/+/, '')\n const parts = [...state.parts, { regex: !!entry.regex, source: route }]\n const extraKwargs = { ...state.extraKwargs, ...entry.kwargs }\n if (entry.children) {\n const namespaces = entry.namespace ? [...state.namespaces, entry.namespace] : state.namespaces\n flatten(entry.children, { parts, namespaces, extraKwargs }, out)\n continue\n }\n const kind = entry.app ? 'app' : 'view'\n if (!entry.app && !entry.view) throw new ImproperlyConfigured(`URL pattern '${entry.route}' has no view.`)\n const compiled = compileParts(parts, kind === 'app')\n if (kind === 'app' && compiled.honoPath === null) {\n throw new ImproperlyConfigured(`Cannot mount a Hono app under the regex route '${compiled.pattern}'.`)\n }\n const fullName = entry.name ? [...state.namespaces, entry.name].join(':') : undefined\n out.push({\n kind,\n ...compiled,\n view: entry.view,\n app: entry.app,\n name: entry.name,\n namespaces: state.namespaces,\n fullName,\n methods: entry.methods,\n extraKwargs,\n })\n }\n}\n\nfunction decode(v: string): string {\n try {\n return decodeURIComponent(v)\n } catch {\n return v\n }\n}\n\nfunction encodePathValue(v: string): string {\n return encodeURIComponent(v).replace(/%(2F|3A|40|24|26|2B|2C|3B|3D|7E)/gi, (m) => decodeURIComponent(m))\n}\n\n/** A compiled urlconf: resolves paths, reverses names and mounts itself onto a Hono app. */\nexport class UrlResolver {\n readonly routes: CompiledRoute[] = []\n private byName = new Map<string, CompiledRoute[]>()\n\n constructor(readonly patterns: UrlPatterns) {\n flatten(patterns, { parts: [], namespaces: [], extraKwargs: {} }, this.routes)\n for (const r of this.routes) {\n if (!r.fullName) continue\n const list = this.byName.get(r.fullName) ?? []\n list.push(r)\n this.byName.set(r.fullName, list)\n }\n }\n\n /** All namespaced names (for debugging / tooling). */\n get names(): string[] {\n return [...this.byName.keys()]\n }\n\n /** All routes matching `path` (in order). */\n matchAll(path: string): ResolverMatch[] {\n const p = path.replace(/^\\//, '')\n const out: ResolverMatch[] = []\n for (const r of this.routes) {\n const m = r.regex.exec(p)\n if (!m) continue\n const groups: Record<string, string | undefined> = {}\n for (const [k, v] of Object.entries(m.groups ?? {})) groups[k] = v === undefined ? undefined : decode(v)\n out.push(buildMatch(r, groups))\n }\n return out\n }\n\n /** First match for `path` (and `method`, if given), or null. */\n match(path: string, method?: string): ResolverMatch | null {\n const m = method?.toUpperCase() === 'HEAD' ? 'GET' : method?.toUpperCase()\n for (const r of this.matchAll(path)) {\n if (!m || !r.methods || r.methods.includes(m) || (m === 'GET' && r.methods.includes('HEAD'))) return r\n }\n return null\n }\n\n /** Django's `resolve()`: throws Resolver404 if nothing matches. */\n resolve(path: string): ResolverMatch {\n const m = this.match(path)\n if (!m) throw new Resolver404(`No URL pattern matches '${path}'.`)\n return m\n }\n\n isValidPath(path: string): boolean {\n return this.match(path) !== null\n }\n\n reverse(\n name: string,\n params: Record<string, unknown> | unknown[] = {},\n opts: { query?: Record<string, unknown> | URLSearchParams | string } = {},\n ): string {\n const candidates = this.byName.get(name)\n if (!candidates?.length) {\n throw new NoReverseMatch(\n `Reverse for '${name}' not found. '${name}' is not a valid view function or pattern name.`,\n )\n }\n for (const route of candidates) {\n const url = UrlResolver.tryReverse(route, params)\n if (url !== null) return url + queryString(opts.query)\n }\n const given = Array.isArray(params)\n ? `arguments ${JSON.stringify(params)}`\n : `keyword arguments ${JSON.stringify(params)}`\n throw new NoReverseMatch(\n `Reverse for '${name}' with ${given} not found. ${candidates.length} pattern(s) tried: ${candidates\n .map((c) => `'${c.pattern}'`)\n .join(', ')}`,\n )\n }\n\n private static tryReverse(\n route: CompiledRoute,\n params: Record<string, unknown> | unknown[],\n ): string | null {\n if (!route.tokens) return null\n const paramTokens = route.tokens.filter((t): t is Extract<Token, { param: string }> => 'param' in t)\n let values: Record<string, unknown>\n if (Array.isArray(params)) {\n if (params.length !== paramTokens.length) return null\n values = Object.fromEntries(paramTokens.map((t, i) => [t.param, params[i]]))\n } else {\n const keys = Object.keys(params).filter((k) => params[k] !== undefined)\n const expected = new Set(paramTokens.map((t) => t.param))\n for (const k of keys) {\n if (!expected.has(k) && !(k in route.extraKwargs && route.extraKwargs[k] === params[k])) return null\n }\n for (const k of expected) if (!keys.includes(k)) return null\n values = params\n }\n let out = ''\n for (const t of route.tokens) {\n if ('lit' in t) {\n out += t.lit\n continue\n }\n const text = t.converter.toUrl(values[t.param])\n if (!new RegExp(`^(?:${t.regex})$`).test(text)) return null\n out += encodePathValue(text)\n }\n return `/${out}`\n }\n\n /** Register every route on a Hono app (in order: first match wins, like Django). */\n mount(hono: HonoApp): void {\n for (const route of this.routes) {\n if (route.kind === 'app') {\n hono.route(route.honoPath!, route.app!)\n continue\n }\n const handler = makeRouteHandler(route)\n if (route.honoPath === null) {\n hono.all('*', handler)\n } else if (route.methods) {\n hono.on(route.methods, route.honoPath, handler)\n } else {\n hono.all(route.honoPath, handler)\n }\n }\n }\n}\n\nfunction queryString(q: Record<string, unknown> | URLSearchParams | string | undefined): string {\n if (q === undefined) return ''\n if (typeof q === 'string') return q ? (q.startsWith('?') ? q : `?${q}`) : ''\n const sp = q instanceof URLSearchParams ? q : new URLSearchParams()\n if (!(q instanceof URLSearchParams)) {\n for (const [k, v] of Object.entries(q)) {\n if (v === undefined || v === null) continue\n if (Array.isArray(v)) for (const x of v) sp.append(k, String(x))\n else sp.append(k, String(v))\n }\n }\n const s = sp.toString()\n return s ? `?${s}` : ''\n}\n\n// ---------------------------------------------------------------------------------------------\n// Request-time helpers\n// ---------------------------------------------------------------------------------------------\n\nconst MATCHES = new WeakMap<object, ResolverMatch>()\n/** Marker set on views by `csrfExempt()`. */\nexport const CSRF_EXEMPT_MARKER: symbol = Symbol.for('ghuri.csrfExempt')\nconst CSRF_EXEMPT = CSRF_EXEMPT_MARKER\n\nfunction makeRouteHandler(route: CompiledRoute) {\n const handler = async (c: Context, next: Next): Promise<Response | void> => {\n let match: ResolverMatch\n if (route.honoPath === null) {\n if (route.methods) {\n const method = c.req.method === 'HEAD' ? 'GET' : c.req.method\n if (!route.methods.includes(method)) return next()\n }\n const m = route.regex.exec(c.req.path.replace(/^\\//, ''))\n if (!m) return next()\n const groups: Record<string, string | undefined> = {}\n for (const [k, v] of Object.entries(m.groups ?? {})) groups[k] = v === undefined ? undefined : decode(v)\n match = buildMatch(route, groups)\n } else {\n match = buildMatch(route, c.req.param() as Record<string, string>)\n }\n MATCHES.set(c, match)\n let res: Response | undefined\n try {\n res = await route.view!(c)\n } catch (err) {\n if (err instanceof Response) return err\n throw err\n }\n if (!(res instanceof Response)) {\n throw new ImproperlyConfigured(\n `The view for '${route.pattern}' didn't return a Response. It returned ${res === undefined ? 'undefined' : typeof res} instead.`,\n )\n }\n return res\n }\n if ((route.view as any)?.[CSRF_EXEMPT] && route.honoPath !== null) (handler as any)[CSRF_EXEMPT] = true\n return handler\n}\n\nfunction buildMatch(route: CompiledRoute, groups: Record<string, string | undefined>): ResolverMatch {\n const kwargs: Record<string, any> = { ...route.extraKwargs }\n for (const p of route.params) {\n const raw = groups[p.name]\n if (raw !== undefined) kwargs[p.name] = p.converter.toJs(raw)\n }\n return {\n route: route.pattern,\n urlName: route.name,\n namespace: route.namespaces.join(':'),\n namespaces: route.namespaces,\n viewName: route.fullName,\n kwargs,\n view: route.view,\n app: route.app,\n methods: route.methods,\n compiled: route,\n }\n}\n\n/** The ResolverMatch of the current request (Django's `request.resolver_match`). */\nexport function resolverMatch(c: Context): ResolverMatch | undefined {\n return MATCHES.get(c)\n}\n\n/**\n * URL parameters of the current request, converted by their converters (`<int:id>` → number), plus any\n * extra `kwargs` given to `path()`.\n */\nexport function kwargs<T extends Record<string, any> = Record<string, any>>(c: Context): T {\n const m = MATCHES.get(c)\n if (m) return m.kwargs as T\n return { ...(c.req.param() as Record<string, string>) } as unknown as T\n}\n\nconst URLCONFS = new WeakMap<object, UrlResolver>()\n\n/** Compiled resolver for a urlconf (cached per patterns array). */\nexport function getResolver(patterns?: UrlPatterns): UrlResolver {\n const pats = patterns ?? (tryGetContext()?.settings.ROOT_URLCONF as UrlPatterns | undefined)\n if (!pats) {\n throw new ImproperlyConfigured(\n 'No urlconf: pass one explicitly or call reverse()/resolve() inside a Ghuri context.',\n )\n }\n let r = URLCONFS.get(pats)\n if (!r) {\n r = new UrlResolver(pats)\n URLCONFS.set(pats, r)\n }\n return r\n}\n\nexport interface ReverseOptions {\n urlconf?: UrlPatterns\n query?: Record<string, unknown> | URLSearchParams | string\n}\n\n/**\n * Django's `reverse()`: `reverse('blog:post-detail', { id: 3 })` → `/blog/posts/3/`.\n * Positional params (`reverse('x', [3])`) also work.\n */\nexport function reverse(\n name: string,\n params?: Record<string, unknown> | unknown[],\n opts: ReverseOptions = {},\n): string {\n return getResolver(opts.urlconf).reverse(name, params, opts)\n}\n\n/** Django's `resolve()`. */\nexport function resolve(pathname: string, opts: { urlconf?: UrlPatterns } = {}): ResolverMatch {\n return getResolver(opts.urlconf).resolve(pathname)\n}\n","import type { Context } from 'hono'\nimport { HTTPException } from 'hono/http-exception'\nimport { tryGetContext } from './context'\nimport { Http404, HttpError, MethodNotAllowed, ObjectDoesNotExist, ValidationError } from './errors'\nimport type { ErrorView, GhuriSettings } from './settings'\nimport type { UrlResolver } from './urls'\nimport { getResolver, Resolver404, resolverMatch } from './urls'\n\n// ---------------------------------------------------------------------------------------------\n// Pluggable exception handlers (other packages map their own errors, e.g. rest's APIException)\n// ---------------------------------------------------------------------------------------------\n\nexport type ExceptionHandler = (\n err: any,\n c: Context,\n) => Response | undefined | null | void | Promise<Response | undefined | null | void>\n\ntype Matcher = ((err: unknown) => boolean) | (abstract new (...args: any[]) => unknown)\n\ninterface Registered {\n match: (err: unknown) => boolean\n handler: ExceptionHandler\n}\n\nconst HANDLERS_KEY = Symbol.for('ghuri.core.exceptionHandlers')\nconst registered: Registered[] = ((globalThis as any)[HANDLERS_KEY] ??= [])\n\nfunction isClass(m: Matcher): m is abstract new (...args: any[]) => unknown {\n if (typeof m !== 'function' || m.prototype === undefined) return false\n return (\n m === Error || m.prototype instanceof Error || /^class[\\s{]/.test(Function.prototype.toString.call(m))\n )\n}\n\n/**\n * Map an error class (or predicate) to a response. Handlers registered later win. Return `undefined` to\n * fall through to the next handler / the default mapping.\n *\n * ```ts\n * registerExceptionHandler(APIException, (err, c) => c.json(err.detail, err.status))\n * ```\n */\nexport function registerExceptionHandler(matcher: Matcher, handler: ExceptionHandler): () => void {\n const entry: Registered = {\n match: isClass(matcher)\n ? (err) => err instanceof (matcher as any)\n : (matcher as (err: unknown) => boolean),\n handler,\n }\n registered.unshift(entry)\n return () => {\n const i = registered.indexOf(entry)\n if (i >= 0) registered.splice(i, 1)\n }\n}\n\n// ---------------------------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------------------------\n\nconst STATUS_TEXT: Record<number, string> = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 403: 'Forbidden',\n 404: 'Not Found',\n 405: 'Method Not Allowed',\n 406: 'Not Acceptable',\n 409: 'Conflict',\n 410: 'Gone',\n 413: 'Payload Too Large',\n 415: 'Unsupported Media Type',\n 422: 'Unprocessable Entity',\n 429: 'Too Many Requests',\n 500: 'Server Error',\n 502: 'Bad Gateway',\n 503: 'Service Unavailable',\n}\n\nexport function statusText(status: number): string {\n return STATUS_TEXT[status] ?? (status >= 500 ? 'Server Error' : 'Error')\n}\n\nexport function escapeHtml(value: unknown): string {\n return String(value)\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;')\n}\n\n/** Settings of the request (works even if the error happened outside the context scope). */\nexport function settingsFor(c?: Context): GhuriSettings | undefined {\n let fromHono: GhuriSettings | undefined\n try {\n fromHono = c?.get('ghuri')?.settings\n } catch {\n fromHono = undefined\n }\n return fromHono ?? tryGetContext()?.settings\n}\n\n/**\n * Should errors for this request be rendered as JSON? True for API paths (`/api…`), clients that\n * accept JSON but not HTML, JSON request bodies and XHR requests.\n */\nexport function wantsJson(c: Context): boolean {\n const accept = c.req.header('accept') ?? ''\n const settings = settingsFor(c)\n const prefixes = (settings?.API_PATH_PREFIXES as string[] | undefined) ?? ['/api']\n const path = c.req.path\n if (prefixes.some((p) => path === p || path.startsWith(p.endsWith('/') ? p : `${p}/`))) return true\n if (accept.includes('text/html')) return false\n if (accept.includes('application/json') || accept.includes('+json')) return true\n if ((c.req.header('content-type') ?? '').includes('application/json')) return true\n if (c.req.header('x-requested-with') === 'XMLHttpRequest') return true\n return false\n}\n\nconst SENSITIVE = /API|KEY|PASS|SECRET|SIGNATURE|TOKEN|CREDENTIAL|PRIVATE/i\n\nfunction repr(value: unknown, depth = 0): string {\n if (value === null || value === undefined) return String(value)\n if (typeof value === 'string') return JSON.stringify(value)\n if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint')\n return String(value)\n if (typeof value === 'function') return (value as any).name ? `<${(value as any).name}>` : '<function>'\n if (depth > 2) return Array.isArray(value) ? '[…]' : '{…}'\n if (Array.isArray(value))\n return `[${value\n .slice(0, 20)\n .map((v) => repr(v, depth + 1))\n .join(', ')}${value.length > 20 ? ', …' : ''}]`\n if (typeof value === 'object') {\n const ctor = (value as any).constructor?.name\n if (ctor && ctor !== 'Object') return `<${ctor}>`\n const entries = Object.entries(value as Record<string, unknown>).slice(0, 20)\n return `{ ${entries.map(([k, v]) => `${k}: ${SENSITIVE.test(k) ? '••••••' : repr(v, depth + 1)}`).join(', ')} }`\n }\n return String(value)\n}\n\n/** Settings with secrets masked (debug pages). */\nexport function cleansedSettings(settings: GhuriSettings | undefined): Array<[string, string]> {\n if (!settings) return []\n return Object.keys(settings)\n .sort()\n .map((k) => [k, SENSITIVE.test(k) ? '••••••••••••••••••••' : repr(settings[k])])\n}\n\nconst PAGE_CSS = `\n *{box-sizing:border-box} body{margin:0;font:14px/1.5 system-ui,-apple-system,Segoe UI,Roboto,sans-serif;color:#1f2328;background:#fff}\n header{padding:18px 24px;background:#ffc;border-bottom:1px solid #ddd} header.err{background:#fde8e8}\n h1{margin:0 0 4px;font-size:22px;font-weight:600} h2{font-size:16px;margin:24px 0 8px}\n main{padding:8px 24px 32px} code,pre{font:12.5px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace}\n pre{background:#f6f8fa;padding:12px;border-radius:6px;overflow:auto;white-space:pre-wrap}\n table{border-collapse:collapse;width:100%} td,th{text-align:left;vertical-align:top;padding:4px 8px;border-bottom:1px solid #eee}\n th{width:220px;font-weight:600;color:#555} .muted{color:#666} ol li{margin:2px 0} .name{color:#666;margin-left:8px}\n @media (prefers-color-scheme:dark){body{background:#0d1117;color:#e6edf3} header{background:#3a3200;border-color:#333}\n header.err{background:#3d1416} pre{background:#161b22} td,th{border-color:#222} th,.muted,.name{color:#9aa4ae}}\n`\n\nfunction page(title: string, header: string, body: string, error = false): string {\n return `<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"robots\" content=\"noindex,nofollow\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>${escapeHtml(title)}</title><style>${PAGE_CSS}</style></head><body><header${error ? ' class=\"err\"' : ''}>${header}</header><main>${body}</main></body></html>`\n}\n\nfunction simplePage(status: number, message: string): string {\n const title = `${status} ${statusText(status)}`\n return `<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>${escapeHtml(title)}</title><style>body{font:16px/1.5 system-ui,sans-serif;margin:0;padding:48px 24px;color:#1f2328}h1{font-size:28px;font-weight:600;margin:0 0 8px}p{color:#555}@media (prefers-color-scheme:dark){body{background:#0d1117;color:#e6edf3}p{color:#9aa4ae}}</style></head><body><h1>${escapeHtml(title)}</h1>${message ? `<p>${escapeHtml(message)}</p>` : ''}</body></html>`\n}\n\nfunction requestTable(c: Context): string {\n const rows: Array<[string, string]> = [\n ['Request Method', c.req.method],\n ['Request URL', c.req.url],\n ]\n const match = resolverMatch(c)\n if (match)\n rows.push(['Matched route', `${match.route}${match.viewName ? ` [name='${match.viewName}']` : ''}`])\n for (const [k, v] of c.req.raw.headers) {\n rows.push([`Header ${k}`, /cookie|authorization/i.test(k) ? '••••••••' : v])\n }\n return `<table>${rows.map(([k, v]) => `<tr><th>${escapeHtml(k)}</th><td><code>${escapeHtml(v)}</code></td></tr>`).join('')}</table>`\n}\n\nfunction technical500(err: unknown, c: Context, settings: GhuriSettings | undefined): string {\n const e = err instanceof Error ? err : new Error(String(err))\n const causes: string[] = []\n let cause = (e as any).cause\n while (cause && causes.length < 5) {\n causes.push(cause instanceof Error ? (cause.stack ?? String(cause)) : String(cause))\n cause = cause instanceof Error ? (cause as any).cause : undefined\n }\n const header = `<h1>${escapeHtml(e.name)} at ${escapeHtml(c.req.path)}</h1><div class=\"muted\">${escapeHtml(e.message)}</div>`\n const body = `\n <h2>Traceback</h2><pre>${escapeHtml(e.stack ?? String(e))}</pre>\n ${causes.map((s) => `<h2>Caused by</h2><pre>${escapeHtml(s)}</pre>`).join('')}\n <h2>Request</h2>${requestTable(c)}\n <h2>Settings</h2><table>${cleansedSettings(settings)\n .map(([k, v]) => `<tr><th>${escapeHtml(k)}</th><td><code>${escapeHtml(v)}</code></td></tr>`)\n .join('')}</table>\n <p class=\"muted\">You're seeing this error because you have <code>DEBUG = true</code> in your Ghuri settings. Change that to <code>false</code>, and Ghuri will display a standard page.</p>`\n return page(`${e.name} at ${c.req.path}`, header, body, true)\n}\n\nfunction patternList(urlconf: UrlResolver | undefined): string {\n if (!urlconf) return ''\n return `<ol>${urlconf.routes\n .map(\n (r) =>\n `<li><code>${escapeHtml(r.pattern || '(empty path)')}${r.kind === 'app' ? ' [Hono app]' : ''}</code>${\n r.fullName ? `<span class=\"name\">[name='${escapeHtml(r.fullName)}']</span>` : ''\n }${r.methods ? `<span class=\"name\">${escapeHtml(r.methods.join(', '))}</span>` : ''}</li>`,\n )\n .join('')}</ol>`\n}\n\nfunction technical404(\n c: Context,\n message: string,\n urlconf: UrlResolver | undefined,\n raisedInView: boolean,\n): string {\n const path = c.req.path.replace(/^\\//, '')\n const header = `<h1>Page not found <span class=\"muted\">(404)</span></h1><table><tr><th>Request Method:</th><td>${escapeHtml(\n c.req.method,\n )}</td></tr><tr><th>Request URL:</th><td>${escapeHtml(c.req.url)}</td></tr>${\n raisedInView\n ? `<tr><th>Raised by:</th><td>${escapeHtml(resolverMatch(c)?.viewName ?? resolverMatch(c)?.route ?? '')}</td></tr>`\n : ''\n }</table>`\n let body: string\n if (raisedInView) {\n body = `<p>${escapeHtml(message)}</p>`\n } else {\n body = `<p>Using the URLconf defined in <code>ROOT_URLCONF</code>, Ghuri tried these URL patterns, in this order:</p>${patternList(\n urlconf,\n )}<p>The current path, <code>${escapeHtml(path)}</code>, didn't match any of these.</p>`\n if (\n !c.req.path.endsWith('/') &&\n !['GET', 'HEAD'].includes(c.req.method) &&\n urlconf?.isValidPath(`${c.req.path}/`)\n ) {\n body += `<p><strong>Note:</strong> You called this URL via ${escapeHtml(c.req.method)}, but the URL doesn't end in a slash and you have APPEND_SLASH set. Ghuri can't redirect to the slash URL while maintaining ${escapeHtml(c.req.method)} data. Change your form/request to point to <code>${escapeHtml(c.req.path)}/</code> (note the trailing slash).</p>`\n }\n }\n body += `<p class=\"muted\">You're seeing this error because you have <code>DEBUG = true</code> in your Ghuri settings. Change that to <code>false</code>, and Ghuri will display a standard 404 page.</p>`\n return page('Page not found', header, body)\n}\n\nfunction currentResolver(settings: GhuriSettings | undefined): UrlResolver | undefined {\n try {\n return settings ? getResolver(settings.ROOT_URLCONF as any) : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Run the project's `HANDLER_404` / `HANDLER_500` view, if set and `DEBUG` is off (with `DEBUG` on,\n * Django shows its technical pages instead). Returns undefined when there is no view, or when it throws\n * or returns something that is not a Response, so the caller renders the default page.\n */\nasync function renderErrorView(\n name: 'HANDLER_404' | 'HANDLER_500',\n c: Context,\n exception: unknown,\n settings: GhuriSettings | undefined,\n): Promise<Response | undefined> {\n if (!hasErrorView(name, settings)) return undefined\n try {\n const res = await (settings![name] as ErrorView)(c, exception)\n if (res instanceof Response) return res\n console.error(`${name} did not return a Response; using the default error page.`)\n } catch (err) {\n console.error(`${name} raised an error; using the default error page:`, err)\n }\n return undefined\n}\n\nfunction hasErrorView(name: 'HANDLER_404' | 'HANDLER_500', settings: GhuriSettings | undefined): boolean {\n return typeof settings?.[name] === 'function' && !settings?.DEBUG\n}\n\n// ---------------------------------------------------------------------------------------------\n// Main entry points\n// ---------------------------------------------------------------------------------------------\n\nfunction errorBody(\n c: Context,\n status: number,\n payload: Record<string, unknown>,\n html: string,\n headers?: HeadersInit,\n): Response {\n const res = wantsJson(c)\n ? new Response(JSON.stringify(payload), {\n status,\n headers: { 'content-type': 'application/json; charset=UTF-8' },\n })\n : new Response(html, { status, headers: { 'content-type': 'text/html; charset=UTF-8' } })\n if (headers) for (const [k, v] of new Headers(headers)) res.headers.set(k, v)\n return res\n}\n\n/**\n * The built-in 404 for a path no pattern matched (DEBUG lists the URL patterns, like Django). It never\n * calls `HANDLER_404`, so a custom handler can return it, e.g. for JSON clients.\n */\nexport function notFoundResponse(\n c: Context,\n message = 'The requested resource was not found on this server.',\n): Response {\n const settings = settingsFor(c)\n const debug = !!settings?.DEBUG\n const urlconf = debug ? currentResolver(settings) : undefined\n const payload: Record<string, unknown> = { detail: 'Not found.' }\n if (debug) {\n payload.path = c.req.path\n payload.tried =\n urlconf?.routes.map((r) => (r.fullName ? `${r.pattern} [name='${r.fullName}']` : r.pattern)) ?? []\n }\n return errorBody(\n c,\n 404,\n payload,\n debug ? technical404(c, message, urlconf, false) : simplePage(404, message),\n )\n}\n\n/**\n * Turn any thrown value into a Response: registered handlers first, then `HttpError` subclasses,\n * `ValidationError` (400), `ObjectDoesNotExist` (404), Hono's `HTTPException`, and finally 500.\n * With `DEBUG` off, 404s go through `HANDLER_404` and uncaught errors through `HANDLER_500` when set.\n */\nexport async function handleException(err: unknown, c: Context): Promise<Response> {\n if (err instanceof Response) return err\n for (const r of [...registered]) {\n if (!r.match(err)) continue\n const res = await r.handler(err, c)\n if (res instanceof Response) return res\n }\n const settings = settingsFor(c)\n const debug = !!settings?.DEBUG\n\n if (err instanceof HTTPException) {\n if ((err as any).res) return err.getResponse()\n const status = err.status\n if (status >= 500) console.error(err)\n return errorBody(\n c,\n status,\n { detail: err.message || statusText(status) },\n simplePage(status, err.message),\n )\n }\n if (err instanceof ValidationError) {\n const payload = {\n detail: err.messages.length === 1 && !err.hasFieldErrors ? err.messages[0] : 'Invalid input.',\n errors: err.toDict(),\n }\n const list = Object.entries(err.toDict())\n .map(([k, msgs]) => `${k === '__all__' ? '' : `${k}: `}${msgs.join(' ')}`)\n .join('; ')\n return errorBody(c, 400, payload, simplePage(400, list))\n }\n if (err instanceof Http404 || err instanceof ObjectDoesNotExist) {\n const message = err.message || 'Not found.'\n if (debug) {\n if (err instanceof Resolver404) return notFoundResponse(c, message)\n return errorBody(\n c,\n 404,\n { detail: message, exception: err.name },\n technical404(c, message, currentResolver(settings), true),\n )\n }\n const custom = await renderErrorView('HANDLER_404', c, err, settings)\n if (custom) return custom\n return errorBody(c, 404, { detail: err instanceof Http404 ? message : 'Not found.' }, simplePage(404, ''))\n }\n if (err instanceof MethodNotAllowed) {\n return errorBody(c, 405, { detail: err.message }, simplePage(405, err.message), {\n Allow: err.allowed.join(', '),\n })\n }\n if (err instanceof HttpError) {\n const status = err.status\n if (status >= 500) console.error(err)\n return errorBody(\n c,\n status,\n { detail: err.message },\n simplePage(status, status >= 500 && !debug ? '' : err.message),\n )\n }\n\n console.error(err)\n const custom = await renderErrorView('HANDLER_500', c, err, settings)\n if (custom) return custom\n if (debug) {\n const e = err instanceof Error ? err : new Error(String(err))\n return errorBody(\n c,\n 500,\n { detail: e.message, exception: e.name, stack: (e.stack ?? '').split('\\n').map((l) => l.trim()) },\n technical500(err, c, settings),\n )\n }\n return errorBody(c, 500, { detail: 'Internal Server Error' }, simplePage(500, ''))\n}\n\n/** Hono `onError` handler. */\nexport const errorHandler = (err: Error, c: Context): Promise<Response> => handleException(err, c)\n\n/** Redirect `/x` → `/x/` (301) when APPEND_SLASH applies (GET/HEAD, path unmatched, slashed path matches). */\nexport function appendSlashRedirect(c: Context, urlconf?: UrlResolver): Response | null {\n const path = c.req.path\n if (path.endsWith('/')) return null\n if (c.req.method !== 'GET' && c.req.method !== 'HEAD') return null\n const resolver = urlconf ?? currentResolver(settingsFor(c))\n if (!resolver) return null\n if (resolver.isValidPath(path) || !resolver.isValidPath(`${path}/`)) return null\n const url = new URL(c.req.url)\n return new Response(null, { status: 301, headers: { Location: `${path}/${url.search}` } })\n}\n\n/**\n * Hono `notFound` handler: APPEND_SLASH, 405 for method-restricted routes, then 404 (the project's\n * `HANDLER_404` when set and `DEBUG` is off). It runs at the end of the middleware chain, so the request\n * context and values set by MIDDLEWARE are available to `HANDLER_404`.\n */\nexport function notFoundHandler(urlconf?: UrlResolver) {\n return (c: Context): Response | Promise<Response> => {\n const settings = settingsFor(c)\n const resolver = urlconf ?? currentResolver(settings)\n if (settings?.APPEND_SLASH !== false) {\n const redirect = appendSlashRedirect(c, resolver)\n if (redirect) return redirect\n }\n if (resolver) {\n const matches = resolver.matchAll(c.req.path).filter((m) => m.compiled.kind === 'view')\n if (matches.length && matches.every((m) => m.methods)) {\n const allowed = new Set<string>()\n for (const m of matches) for (const x of m.methods!) allowed.add(x)\n if (allowed.has('GET')) allowed.add('HEAD')\n return handleException(new MethodNotAllowed(c.req.method, [...allowed]), c)\n }\n }\n if (hasErrorView('HANDLER_404', settings)) {\n const exception = new Resolver404(`No URL pattern matches '${c.req.path}'.`)\n return renderErrorView('HANDLER_404', c, exception, settings).then((res) => res ?? notFoundResponse(c))\n }\n return notFoundResponse(c)\n }\n}\n","import type { Context } from 'hono'\nimport { getCookie, setCookie } from 'hono/cookie'\nimport { matchedRoutes } from 'hono/route'\nimport { PermissionDenied } from './errors'\nimport { settingsFor } from './exceptions'\nimport type { GhuriSettings } from './settings'\nimport { CSRF_EXEMPT_MARKER, getResolver, type ViewFunction } from './urls'\n\n// Django-compatible token format: a 32-char secret stored in the cookie, 64-char masked tokens in forms.\nconst CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'\nexport const CSRF_SECRET_LENGTH = 32\nexport const CSRF_TOKEN_LENGTH = 2 * CSRF_SECRET_LENGTH\nconst SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'TRACE'])\n\n/** 403 raised when CSRF verification fails. `reason` says why. */\nexport class CsrfFailure extends PermissionDenied {\n constructor(readonly reason: string) {\n super(`CSRF verification failed. Request aborted. ${reason}`)\n }\n}\n\nfunction randomString(length: number): string {\n const bytes = new Uint8Array(length)\n crypto.getRandomValues(bytes)\n let out = ''\n // 62 chars: reject bytes >= 248 to avoid modulo bias\n for (let i = 0; out.length < length; i++) {\n if (i >= bytes.length) {\n crypto.getRandomValues(bytes)\n i = 0\n }\n if (bytes[i] < 248) out += CHARS[bytes[i] % 62]\n }\n return out\n}\n\n/** A new random CSRF secret (what the cookie stores). */\nexport function generateCsrfSecret(): string {\n return randomString(CSRF_SECRET_LENGTH)\n}\n\nexport function maskCsrfSecret(secret: string): string {\n const mask = randomString(CSRF_SECRET_LENGTH)\n let cipher = ''\n for (let i = 0; i < CSRF_SECRET_LENGTH; i++) {\n cipher += CHARS[(CHARS.indexOf(secret[i]) + CHARS.indexOf(mask[i])) % 62]\n }\n return mask + cipher\n}\n\nexport function unmaskCsrfToken(token: string): string {\n const mask = token.slice(0, CSRF_SECRET_LENGTH)\n const cipher = token.slice(CSRF_SECRET_LENGTH)\n let secret = ''\n for (let i = 0; i < CSRF_SECRET_LENGTH; i++) {\n secret += CHARS[(CHARS.indexOf(cipher[i]) - CHARS.indexOf(mask[i]) + 62) % 62]\n }\n return secret\n}\n\nfunction wellFormed(token: string | undefined): token is string {\n return (\n !!token &&\n (token.length === CSRF_SECRET_LENGTH || token.length === CSRF_TOKEN_LENGTH) &&\n /^[a-zA-Z0-9]+$/.test(token)\n )\n}\n\nfunction constantTimeEquals(a: string, b: string): boolean {\n if (a.length !== b.length) return false\n let diff = 0\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return diff === 0\n}\n\ninterface CsrfState {\n secret?: string\n /** The secret must be (re)sent in a Set-Cookie header. */\n needsUpdate: boolean\n}\n\nconst STATES = new WeakMap<Context, CsrfState>()\n\nfunction csrfSettings(c: Context) {\n const s = (settingsFor(c) ?? {}) as GhuriSettings\n return {\n cookieName: (s.CSRF_COOKIE_NAME as string | undefined) ?? 'csrftoken',\n headerName: (s.CSRF_HEADER_NAME as string | undefined) ?? 'X-CSRFToken',\n cookieAge: (s.CSRF_COOKIE_AGE as number | null | undefined) ?? 31449600,\n cookieDomain: s.CSRF_COOKIE_DOMAIN as string | undefined,\n cookiePath: (s.CSRF_COOKIE_PATH as string | undefined) ?? '/',\n cookieSecure: !!s.CSRF_COOKIE_SECURE,\n cookieHttpOnly: !!s.CSRF_COOKIE_HTTPONLY,\n cookieSameSite: (s.CSRF_COOKIE_SAMESITE as 'Lax' | 'Strict' | 'None' | false | undefined) ?? 'Lax',\n trustedOrigins: s.CSRF_TRUSTED_ORIGINS ?? [],\n }\n}\n\nfunction state(c: Context): CsrfState {\n let st = STATES.get(c)\n if (!st) {\n const raw = getCookie(c, csrfSettings(c).cookieName)\n let secret: string | undefined\n if (wellFormed(raw)) secret = raw.length === CSRF_TOKEN_LENGTH ? unmaskCsrfToken(raw) : raw\n st = { secret, needsUpdate: false }\n STATES.set(c, st)\n }\n return st\n}\n\n/**\n * The CSRF token for forms/JS (`<input type=\"hidden\" name=\"csrfmiddlewaretoken\" value={getCsrfToken(c)} />`).\n * A new masked value is returned each call; `CsrfMiddleware` sends the cookie when it was just created.\n */\nexport function getCsrfToken(c: Context): string {\n const st = state(c)\n if (!st.secret) {\n st.secret = generateCsrfSecret()\n st.needsUpdate = true\n }\n return maskCsrfSecret(st.secret)\n}\n\n/** Change the CSRF secret (call on login, like Django's `rotate_token`). */\nexport function rotateCsrfToken(c: Context): void {\n const st = state(c)\n st.secret = generateCsrfSecret()\n st.needsUpdate = true\n}\n\n/** Mark a view (or a mounted Hono app) as exempt from `CsrfMiddleware`. */\nexport function csrfExempt<T extends object>(view: T): T {\n ;(view as any)[CSRF_EXEMPT_MARKER] = true\n return view\n}\n\n/** Make sure the CSRF cookie is set on this view's response (Django's `ensure_csrf_cookie`). */\nexport function ensureCsrfCookie(view: ViewFunction): ViewFunction {\n const wrapped: ViewFunction = (c) => {\n getCsrfToken(c)\n return view(c)\n }\n if ((view as any)[CSRF_EXEMPT_MARKER]) (wrapped as any)[CSRF_EXEMPT_MARKER] = true\n return wrapped\n}\n\n/** Is the request's view exempt from CSRF checks? */\nexport function isCsrfExempt(c: Context): boolean {\n try {\n for (const r of matchedRoutes(c)) if ((r.handler as any)?.[CSRF_EXEMPT_MARKER]) return true\n } catch {\n // no route information\n }\n const settings = settingsFor(c)\n if (!settings) return false\n try {\n const m = getResolver(settings.ROOT_URLCONF as any).match(c.req.path, c.req.method)\n if (!m) return false\n return !!((m.view as any)?.[CSRF_EXEMPT_MARKER] || (m.app as any)?.[CSRF_EXEMPT_MARKER])\n } catch {\n return false\n }\n}\n\n/** `https` request? Honors `SECURE_PROXY_SSL_HEADER = ['X-Forwarded-Proto', 'https']`. */\nexport function isSecure(c: Context): boolean {\n const s = settingsFor(c)\n const proxy = s?.SECURE_PROXY_SSL_HEADER as [string, string] | undefined\n if (proxy) {\n const v = c.req.header(proxy[0])\n if (v !== undefined) return v.split(',')[0].trim() === proxy[1]\n }\n return new URL(c.req.url).protocol === 'https:'\n}\n\n/** Request host (with port, from the request URL), honoring `USE_X_FORWARDED_HOST`. */\nexport function getHost(c: Context): string {\n const s = settingsFor(c)\n if (s?.USE_X_FORWARDED_HOST) {\n const fwd = c.req.header('x-forwarded-host')\n if (fwd) return fwd.split(',')[0].trim()\n }\n // The request URL's host is derived from the Host header by Workers and @hono/node-server alike, and is\n // what dev proxies (wrangler/Miniflare) preserve.\n return new URL(c.req.url).host || c.req.header('host') || ''\n}\n\nfunction originMatches(origin: string, pattern: string): boolean {\n if (pattern === origin) return true\n const m = /^([a-z][a-z0-9+.-]*):\\/\\/\\*\\.(.+)$/i.exec(pattern)\n if (!m) return false\n try {\n const u = new URL(origin)\n return u.protocol === `${m[1].toLowerCase()}:` && (u.host === m[2] || u.host.endsWith(`.${m[2]}`))\n } catch {\n return false\n }\n}\n\nfunction hostMatches(host: string, pattern: string): boolean {\n const p = pattern.toLowerCase()\n const h = host.toLowerCase()\n if (p.startsWith('.')) return h === p.slice(1) || h.endsWith(p)\n if (p.startsWith('*.')) return h.endsWith(p.slice(1))\n return h === p\n}\n\n/**\n * Run the CSRF checks for an unsafe request. Returns the failure reason, or `null` when the request passes.\n * Used by `CsrfMiddleware` and by REST session authentication.\n */\nexport async function checkCsrf(c: Context): Promise<string | null> {\n const cfg = csrfSettings(c)\n const secure = isSecure(c)\n const host = getHost(c)\n const origin = c.req.header('origin')\n if (origin !== undefined) {\n const good = `${secure ? 'https' : 'http'}://${host}`\n if (origin === 'null' || !(origin === good || cfg.trustedOrigins.some((t) => originMatches(origin, t)))) {\n return `Origin checking failed - ${origin} does not match any trusted origins.`\n }\n } else if (secure) {\n const referer = c.req.header('referer')\n if (!referer) return 'Referer checking failed - no Referer.'\n let ref: URL\n try {\n ref = new URL(referer)\n } catch {\n return 'Referer checking failed - Referer is malformed.'\n }\n if (ref.protocol !== 'https:')\n return 'Referer checking failed - Referer is insecure while host is secure.'\n const trustedHosts = cfg.trustedOrigins.map((t) => t.replace(/^[a-z][a-z0-9+.-]*:\\/\\//i, ''))\n const goodHost = cfg.cookieDomain ? [cfg.cookieDomain] : [host]\n if (![...goodHost, ...trustedHosts].some((p) => hostMatches(ref.host, p))) {\n return `Referer checking failed - ${referer} does not match any trusted origins.`\n }\n }\n\n const st = state(c)\n if (!st.secret) return 'CSRF cookie not set.'\n\n let token = c.req.header(cfg.headerName)\n let source = `'${cfg.headerName}' header`\n if (!token && c.req.method === 'POST') {\n const ct = c.req.header('content-type') ?? ''\n if (ct.startsWith('application/x-www-form-urlencoded') || ct.startsWith('multipart/form-data')) {\n try {\n const body = await c.req.parseBody()\n const v = body.csrfmiddlewaretoken\n if (typeof v === 'string') token = v\n } catch {\n // unreadable body → token missing\n }\n source = 'POST'\n }\n }\n if (!token) return 'CSRF token missing.'\n if (token.length !== CSRF_SECRET_LENGTH && token.length !== CSRF_TOKEN_LENGTH) {\n return `CSRF token from ${source} has incorrect length.`\n }\n if (!/^[a-zA-Z0-9]+$/.test(token)) return `CSRF token from ${source} has invalid characters.`\n const secret = token.length === CSRF_TOKEN_LENGTH ? unmaskCsrfToken(token) : token\n if (!constantTimeEquals(secret, st.secret)) return `CSRF token from ${source} incorrect.`\n return null\n}\n\n/** Throw `CsrfFailure` (403) unless the request passes the CSRF checks. Safe methods always pass. */\nexport async function enforceCsrf(c: Context): Promise<void> {\n if (SAFE_METHODS.has(c.req.method)) return\n const reason = await checkCsrf(c)\n if (reason) throw new CsrfFailure(reason)\n}\n\n/** Send the CSRF cookie if the token was created or rotated during this request. */\nexport function setCsrfCookieIfNeeded(c: Context): void {\n const st = STATES.get(c)\n if (!st?.needsUpdate || !st.secret) return\n const cfg = csrfSettings(c)\n setCookie(c, cfg.cookieName, st.secret, {\n path: cfg.cookiePath,\n domain: cfg.cookieDomain,\n maxAge: cfg.cookieAge ?? undefined,\n secure: cfg.cookieSecure,\n httpOnly: cfg.cookieHttpOnly,\n sameSite: cfg.cookieSameSite === false ? undefined : cfg.cookieSameSite,\n })\n st.needsUpdate = false\n}\n\nexport { hostMatches, SAFE_METHODS as CSRF_SAFE_METHODS }\n"],"mappings":";AACO,IAAM,aAAN,cAAyB,MAAM;AAAA,EACpC,YAAY,SAAkB,SAA+B;AAC3D,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO,WAAW;AAAA,EACzB;AACF;AAGO,IAAM,uBAAN,cAAmC,WAAW;AAAC;AAG/C,IAAM,sBAAN,cAAkC,WAAW;AAAC;AAE9C,IAAM,qBAAN,cAAiC,WAAW;AAAC;AAC7C,IAAM,0BAAN,cAAsC,WAAW;AAAC;AAGlD,IAAM,YAAN,cAAwB,WAAW;AAAA,EACxC,SAAS;AACX;AACO,IAAM,UAAN,cAAsB,UAAU;AAAA,EAC5B,SAAS;AAAA,EAClB,YAAY,UAAU,cAAc;AAClC,UAAM,OAAO;AAAA,EACf;AACF;AACO,IAAM,mBAAN,cAA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S,MAAM,WAAW,oBAAoB,gBAAgB,KAAK,IAAI;AAC7E,MAAI,CAAC,mBAAmB,QAAQ,GAAG,MAAM,EAAG,QAAO,mBAAmB,MAAM;AAC5E,SAAO;AACT;AAGA,eAAsB,YAAY,GAA2B;AAC3D,MAAI,aAAa,IAAI,EAAE,IAAI,MAAM,EAAG;AACpC,QAAM,SAAS,MAAM,UAAU,CAAC;AAChC,MAAI,OAAQ,OAAM,IAAI,YAAY,MAAM;AAC1C;AAGO,SAAS,sBAAsB,GAAkB;AACtD,QAAM,KAAK,OAAO,IAAI,CAAC;AACvB,MAAI,CAAC,IAAI,eAAe,CAAC,GAAG,OAAQ;AACpC,QAAM,MAAM,aAAa,CAAC;AAC1B,YAAU,GAAG,IAAI,YAAY,GAAG,QAAQ;AAAA,IACtC,MAAM,IAAI;AAAA,IACV,QAAQ,IAAI;AAAA,IACZ,QAAQ,IAAI,aAAa;AAAA,IACzB,QAAQ,IAAI;AAAA,IACZ,UAAU,IAAI;AAAA,IACd,UAAU,IAAI,mBAAmB,QAAQ,SAAY,IAAI;AAAA,EAC3D,CAAC;AACD,KAAG,cAAc;AACnB;","names":["state","path","kwargs","path","custom"]}
@@ -488,6 +488,11 @@ type UrlPatternsLike = UrlPatterns;
488
488
  type MiddlewareLike = (new () => {
489
489
  handle(c: any, next: () => Promise<void>): Promise<Response | void>;
490
490
  }) | Middleware | MiddlewareHandler;
491
+ /**
492
+ * A custom error view (Django's `handler404` / `handler500`): receives the request context and the
493
+ * exception, returns the response.
494
+ */
495
+ type ErrorView<E = unknown> = (c: Context<any, any, any>, exception: E) => Response | Promise<Response>;
491
496
  /**
492
497
  * Project settings. Other packages add keys with declaration merging:
493
498
  *
@@ -503,6 +508,17 @@ interface GhuriSettings {
503
508
  MIDDLEWARE?: MiddlewareLike[];
504
509
  ROOT_URLCONF: UrlPatternsLike;
505
510
  APPEND_SLASH?: boolean;
511
+ /**
512
+ * Custom 404 view (Django's `handler404`). Called with `DEBUG` off for unmatched paths (after the
513
+ * `APPEND_SLASH` redirect and 405 checks) and for `Http404` / `ObjectDoesNotExist` raised by views
514
+ * or middleware. If it throws, the default 404 page is used.
515
+ */
516
+ HANDLER_404?: ErrorView<Http404 | ObjectDoesNotExist>;
517
+ /**
518
+ * Custom 500 view (Django's `handler500`). Called with `DEBUG` off for uncaught exceptions (errors
519
+ * not mapped to an HTTP status). If it throws, the default 500 page is used.
520
+ */
521
+ HANDLER_500?: ErrorView<unknown>;
506
522
  TIME_ZONE?: string;
507
523
  USE_TZ?: boolean;
508
524
  CACHES?: Record<string, CacheConfig>;
@@ -570,4 +586,4 @@ declare function createContext(init: Omit<GhuriContext, 'state'> & {
570
586
  state?: GhuriContext['state'];
571
587
  }): GhuriContext;
572
588
 
573
- export { ValidationError as $, AppConfig as A, BadRequest as B, CSRF_EXEMPT_MARKER as C, DisallowedHost as D, type Env as E, type PathOptions as F, type GhuriSettings as G, type HonoApp as H, ImproperlyConfigured as I, type PathTarget as J, type ResolverMatch as K, LookupError as L, MethodNotAllowed as M, NoReverseMatch as N, ObjectDoesNotExist as O, PermissionDenied as P, type ReverseOptions as Q, Resolver404 as R, type SettingsFactory as S, SecurityMiddleware as T, UrlResolver as U, type ViewFunction as V, SuspiciousOperation as W, type UrlEntry as X, type UrlInclude as Y, type UrlPatterns as Z, type UrlPatternsLike as _, type GhuriContext as a, type ValidationMessages as a0, type ViewClassLike as a1, XFrameOptionsMiddleware as a2, apps as a3, cache as a4, caches as a5, cfCache as a6, converters as a7, createContext as a8, defineSettings as a9, ensureAppsReady as aa, getContext as ab, getEnv as ac, getResolver as ad, getSettings as ae, include as af, isAllowedHost as ag, isSettingsFactory as ah, kvCache as ai, kwargs as aj, memoryCache as ak, path as al, rePath as am, registerConverter as an, resolve as ao, resolverMatch as ap, reverse as aq, runWithContext as ar, setGlobalContext as as, setting as at, toHonoMiddleware as au, tryGetContext as av, urlpatterns as aw, validateHost as ax, type ExecutionContextLike as b, GhuriError as c, type AppConfigClass as d, AppRegistry as e, AppRegistryNotReady as f, Cache as g, type CacheBackend as h, type CacheConfig as i, type CacheOptions as j, type CommandClassLike as k, CommonMiddleware as l, type CompiledRoute as m, type Converter as n, CorsMiddleware as o, type CorsOptions as p, CsrfMiddleware as q, GZipMiddleware as r, Http404 as s, HttpError as t, type Includable as u, Middleware as v, type MiddlewareClass as w, type MiddlewareEntry as x, type MiddlewareLike as y, MultipleObjectsReturned as z };
589
+ export { type UrlPatternsLike as $, AppConfig as A, BadRequest as B, CSRF_EXEMPT_MARKER as C, DisallowedHost as D, type Env as E, MultipleObjectsReturned as F, type GhuriSettings as G, type HonoApp as H, ImproperlyConfigured as I, type PathOptions as J, type PathTarget as K, LookupError as L, MethodNotAllowed as M, NoReverseMatch as N, ObjectDoesNotExist as O, PermissionDenied as P, type ResolverMatch as Q, Resolver404 as R, type SettingsFactory as S, type ReverseOptions as T, UrlResolver as U, type ViewFunction as V, SecurityMiddleware as W, SuspiciousOperation as X, type UrlEntry as Y, type UrlInclude as Z, type UrlPatterns as _, type GhuriContext as a, ValidationError as a0, type ValidationMessages as a1, type ViewClassLike as a2, XFrameOptionsMiddleware as a3, apps as a4, cache as a5, caches as a6, cfCache as a7, converters as a8, createContext as a9, defineSettings as aa, ensureAppsReady as ab, getContext as ac, getEnv as ad, getResolver as ae, getSettings as af, include as ag, isAllowedHost as ah, isSettingsFactory as ai, kvCache as aj, kwargs as ak, memoryCache as al, path as am, rePath as an, registerConverter as ao, resolve as ap, resolverMatch as aq, reverse as ar, runWithContext as as, setGlobalContext as at, setting as au, toHonoMiddleware as av, tryGetContext as aw, urlpatterns as ax, validateHost as ay, type ExecutionContextLike as b, GhuriError as c, type AppConfigClass as d, AppRegistry as e, AppRegistryNotReady as f, Cache as g, type CacheBackend as h, type CacheConfig as i, type CacheOptions as j, type CommandClassLike as k, CommonMiddleware as l, type CompiledRoute as m, type Converter as n, CorsMiddleware as o, type CorsOptions as p, CsrfMiddleware as q, type ErrorView as r, GZipMiddleware as s, Http404 as t, HttpError as u, type Includable as v, Middleware as w, type MiddlewareClass as x, type MiddlewareEntry as y, type MiddlewareLike as z };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Context, Hono, HonoRequest } from 'hono';
2
- import { U as UrlResolver, G as GhuriSettings, a as GhuriContext, E as Env, b as ExecutionContextLike, S as SettingsFactory, A as AppConfig, c as GhuriError, P as PermissionDenied, V as ViewFunction } from './context-Du2IsGtO.js';
3
- export { d as AppConfigClass, e as AppRegistry, f as AppRegistryNotReady, B as BadRequest, C as CSRF_EXEMPT_MARKER, g as Cache, h as CacheBackend, i as CacheConfig, j as CacheOptions, k as CommandClassLike, l as CommonMiddleware, m as CompiledRoute, n as Converter, o as CorsMiddleware, p as CorsOptions, q as CsrfMiddleware, D as DisallowedHost, r as GZipMiddleware, H as HonoApp, s as Http404, t as HttpError, I as ImproperlyConfigured, u as Includable, L as LookupError, M as MethodNotAllowed, v as Middleware, w as MiddlewareClass, x as MiddlewareEntry, y as MiddlewareLike, z as MultipleObjectsReturned, N as NoReverseMatch, O as ObjectDoesNotExist, F as PathOptions, J as PathTarget, R as Resolver404, K as ResolverMatch, Q as ReverseOptions, T as SecurityMiddleware, W as SuspiciousOperation, X as UrlEntry, Y as UrlInclude, Z as UrlPatterns, _ as UrlPatternsLike, $ as ValidationError, a0 as ValidationMessages, a1 as ViewClassLike, a2 as XFrameOptionsMiddleware, a3 as apps, a4 as cache, a5 as caches, a6 as cfCache, a7 as converters, a8 as createContext, a9 as defineSettings, aa as ensureAppsReady, ab as getContext, ac as getEnv, ad as getResolver, ae as getSettings, af as include, ag as isAllowedHost, ah as isSettingsFactory, ai as kvCache, aj as kwargs, ak as memoryCache, al as path, am as rePath, an as registerConverter, ao as resolve, ap as resolverMatch, aq as reverse, ar as runWithContext, as as setGlobalContext, at as setting, au as toHonoMiddleware, av as tryGetContext, aw as urlpatterns, ax as validateHost } from './context-Du2IsGtO.js';
2
+ import { U as UrlResolver, G as GhuriSettings, a as GhuriContext, E as Env, b as ExecutionContextLike, S as SettingsFactory, A as AppConfig, c as GhuriError, P as PermissionDenied, V as ViewFunction } from './context-BP7meNmA.js';
3
+ export { d as AppConfigClass, e as AppRegistry, f as AppRegistryNotReady, B as BadRequest, C as CSRF_EXEMPT_MARKER, g as Cache, h as CacheBackend, i as CacheConfig, j as CacheOptions, k as CommandClassLike, l as CommonMiddleware, m as CompiledRoute, n as Converter, o as CorsMiddleware, p as CorsOptions, q as CsrfMiddleware, D as DisallowedHost, r as ErrorView, s as GZipMiddleware, H as HonoApp, t as Http404, u as HttpError, I as ImproperlyConfigured, v as Includable, L as LookupError, M as MethodNotAllowed, w as Middleware, x as MiddlewareClass, y as MiddlewareEntry, z as MiddlewareLike, F as MultipleObjectsReturned, N as NoReverseMatch, O as ObjectDoesNotExist, J as PathOptions, K as PathTarget, R as Resolver404, Q as ResolverMatch, T as ReverseOptions, W as SecurityMiddleware, X as SuspiciousOperation, Y as UrlEntry, Z as UrlInclude, _ as UrlPatterns, $ as UrlPatternsLike, a0 as ValidationError, a1 as ValidationMessages, a2 as ViewClassLike, a3 as XFrameOptionsMiddleware, a4 as apps, a5 as cache, a6 as caches, a7 as cfCache, a8 as converters, a9 as createContext, aa as defineSettings, ab as ensureAppsReady, ac as getContext, ad as getEnv, ae as getResolver, af as getSettings, ag as include, ah as isAllowedHost, ai as isSettingsFactory, aj as kvCache, ak as kwargs, al as memoryCache, am as path, an as rePath, ao as registerConverter, ap as resolve, aq as resolverMatch, ar as reverse, as as runWithContext, at as setGlobalContext, au as setting, av as toHonoMiddleware, aw as tryGetContext, ax as urlpatterns, ay as validateHost } from './context-BP7meNmA.js';
4
4
 
5
5
  type ExceptionHandler = (err: any, c: Context) => Response | undefined | null | void | Promise<Response | undefined | null | void>;
6
6
  type Matcher = ((err: unknown) => boolean) | (abstract new (...args: any[]) => unknown);
@@ -24,18 +24,26 @@ declare function settingsFor(c?: Context): GhuriSettings | undefined;
24
24
  declare function wantsJson(c: Context): boolean;
25
25
  /** Settings with secrets masked (debug pages). */
26
26
  declare function cleansedSettings(settings: GhuriSettings | undefined): Array<[string, string]>;
27
- /** Render a 404 for a path no pattern matched (DEBUG lists the URL patterns, like Django). */
27
+ /**
28
+ * The built-in 404 for a path no pattern matched (DEBUG lists the URL patterns, like Django). It never
29
+ * calls `HANDLER_404`, so a custom handler can return it, e.g. for JSON clients.
30
+ */
28
31
  declare function notFoundResponse(c: Context, message?: string): Response;
29
32
  /**
30
33
  * Turn any thrown value into a Response: registered handlers first, then `HttpError` subclasses,
31
34
  * `ValidationError` (400), `ObjectDoesNotExist` (404), Hono's `HTTPException`, and finally 500.
35
+ * With `DEBUG` off, 404s go through `HANDLER_404` and uncaught errors through `HANDLER_500` when set.
32
36
  */
33
37
  declare function handleException(err: unknown, c: Context): Promise<Response>;
34
38
  /** Hono `onError` handler. */
35
39
  declare const errorHandler: (err: Error, c: Context) => Promise<Response>;
36
40
  /** Redirect `/x` → `/x/` (301) when APPEND_SLASH applies (GET/HEAD, path unmatched, slashed path matches). */
37
41
  declare function appendSlashRedirect(c: Context, urlconf?: UrlResolver): Response | null;
38
- /** Hono `notFound` handler: APPEND_SLASH, 405 for method-restricted routes, then 404. */
42
+ /**
43
+ * Hono `notFound` handler: APPEND_SLASH, 405 for method-restricted routes, then 404 (the project's
44
+ * `HANDLER_404` when set and `DEBUG` is off). It runs at the end of the middleware chain, so the request
45
+ * context and values set by MIDDLEWARE are available to `HANDLER_404`.
46
+ */
39
47
  declare function notFoundHandler(urlconf?: UrlResolver): (c: Context) => Response | Promise<Response>;
40
48
 
41
49
  /** Cloudflare `ScheduledController` (structural). */
package/dist/index.js CHANGED
@@ -62,7 +62,7 @@ import {
62
62
  unmaskCsrfToken,
63
63
  urlpatterns,
64
64
  wantsJson
65
- } from "./chunk-BQBV57DI.js";
65
+ } from "./chunk-LDWLVUKY.js";
66
66
 
67
67
  // src/app.ts
68
68
  import { Hono } from "hono";
@@ -655,6 +655,11 @@ function validateSettings(s) {
655
655
  if (!Array.isArray(s.INSTALLED_APPS)) throw new ImproperlyConfigured("INSTALLED_APPS must be an array.");
656
656
  if (!Array.isArray(s.ROOT_URLCONF))
657
657
  throw new ImproperlyConfigured("ROOT_URLCONF must be an array of url patterns.");
658
+ for (const key of ["HANDLER_404", "HANDLER_500"]) {
659
+ if (s[key] !== void 0 && s[key] !== null && typeof s[key] !== "function") {
660
+ throw new ImproperlyConfigured(`${key} must be a view function (c, exception) => Response.`);
661
+ }
662
+ }
658
663
  }
659
664
  function getSettings() {
660
665
  return getContext().settings;