@ghuri/core 0.1.0-alpha.4 → 0.1.0-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-54KUWCC4.js → chunk-J3ORY46U.js} +11 -101
- package/dist/chunk-J3ORY46U.js.map +1 -0
- package/dist/chunk-V2EUF5IH.js +255 -0
- package/dist/chunk-V2EUF5IH.js.map +1 -0
- package/dist/chunk-VBA235HC.js +104 -0
- package/dist/chunk-VBA235HC.js.map +1 -0
- package/dist/{context-mL1PriMt.d.ts → context-BM17cFwp.d.ts} +3 -1
- package/dist/index.d.ts +18 -46
- package/dist/index.js +29 -48
- package/dist/index.js.map +1 -1
- package/dist/node.d.ts +35 -2
- package/dist/node.js +62 -3
- package/dist/node.js.map +1 -1
- package/dist/tasks-BEaLcIUR.d.ts +48 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +2 -1
- package/dist/testing.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-54KUWCC4.js.map +0 -1
- package/dist/chunk-YJ7DTR2K.js +0 -27
- package/dist/chunk-YJ7DTR2K.js.map +0 -1
package/dist/node.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
parseCron,
|
|
3
|
+
setRemoteAddr,
|
|
4
|
+
taskHandlers
|
|
5
|
+
} from "./chunk-V2EUF5IH.js";
|
|
6
|
+
import "./chunk-VBA235HC.js";
|
|
4
7
|
|
|
5
8
|
// src/node.ts
|
|
6
9
|
function createExecutionContext() {
|
|
@@ -42,8 +45,13 @@ async function serve(app, opts = {}) {
|
|
|
42
45
|
);
|
|
43
46
|
}
|
|
44
47
|
);
|
|
48
|
+
const scheduler = opts.scheduler && typeof app.scheduled === "function" ? await startScheduler(app, {
|
|
49
|
+
...typeof opts.scheduler === "object" ? opts.scheduler : {},
|
|
50
|
+
env
|
|
51
|
+
}) : null;
|
|
45
52
|
if (opts.handleSignals !== false) {
|
|
46
53
|
const shutdown = () => {
|
|
54
|
+
void scheduler?.stop();
|
|
47
55
|
server.close(() => {
|
|
48
56
|
execution.drain().finally(() => process.exit(0));
|
|
49
57
|
});
|
|
@@ -54,8 +62,59 @@ async function serve(app, opts = {}) {
|
|
|
54
62
|
}
|
|
55
63
|
return server;
|
|
56
64
|
}
|
|
65
|
+
async function startScheduler(app, opts = {}) {
|
|
66
|
+
const env = opts.env ?? process.env;
|
|
67
|
+
if (!opts.crons && typeof app.run === "function") await app.run(env, void 0, async () => void 0);
|
|
68
|
+
const crons = opts.crons ?? taskHandlers.crons();
|
|
69
|
+
const parsed = crons.map((c) => parseCron(c));
|
|
70
|
+
const execution = createExecutionContext();
|
|
71
|
+
const running = /* @__PURE__ */ new Set();
|
|
72
|
+
let timer;
|
|
73
|
+
let stopped = false;
|
|
74
|
+
let lastMinute = Math.floor(Date.now() / 6e4);
|
|
75
|
+
const fire = (minute) => {
|
|
76
|
+
const at = new Date(minute * 6e4);
|
|
77
|
+
for (const cron of parsed) {
|
|
78
|
+
if (!cron.matches(at)) continue;
|
|
79
|
+
const event = {
|
|
80
|
+
cron: cron.source,
|
|
81
|
+
scheduledTime: at.getTime(),
|
|
82
|
+
type: "scheduled",
|
|
83
|
+
noRetry() {
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
const p = app.scheduled(event, env, execution).catch(
|
|
87
|
+
(err) => opts.onError ? opts.onError(err, cron.source) : console.error(`Cron '${cron.source}' failed:`, err)
|
|
88
|
+
).finally(() => running.delete(p));
|
|
89
|
+
running.add(p);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
const tick = () => {
|
|
93
|
+
if (stopped) return;
|
|
94
|
+
const minute = Math.floor(Date.now() / 6e4);
|
|
95
|
+
for (let m = Math.max(lastMinute + 1, minute - 5); m <= minute; m++) fire(m);
|
|
96
|
+
lastMinute = Math.max(lastMinute, minute);
|
|
97
|
+
const delay = (minute + 1) * 6e4 - Date.now() + 50;
|
|
98
|
+
timer = setTimeout(tick, Math.max(delay, 50));
|
|
99
|
+
};
|
|
100
|
+
if (parsed.length) {
|
|
101
|
+
if (opts.onStart) opts.onStart(crons);
|
|
102
|
+
else console.log(`Ghuri scheduler: ${crons.map((c) => `'${c}'`).join(", ")} (UTC)`);
|
|
103
|
+
timer = setTimeout(tick, (lastMinute + 1) * 6e4 - Date.now() + 50);
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
crons,
|
|
107
|
+
async stop() {
|
|
108
|
+
stopped = true;
|
|
109
|
+
if (timer) clearTimeout(timer);
|
|
110
|
+
await Promise.all([...running]);
|
|
111
|
+
await execution.drain();
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
}
|
|
57
115
|
export {
|
|
58
116
|
createExecutionContext,
|
|
59
|
-
serve
|
|
117
|
+
serve,
|
|
118
|
+
startScheduler
|
|
60
119
|
};
|
|
61
120
|
//# sourceMappingURL=node.js.map
|
package/dist/node.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/node.ts"],"sourcesContent":["// @ghuri/core/node — run a Ghuri app on Node.js (VPS, containers, local dev without wrangler).\nimport type { Env, ExecutionContextLike } from './context'\nimport { setRemoteAddr } from './remote'\n\n/** Anything with a Workers-style `fetch(request, env, ctx)` — a GhuriApp or a Hono app. */\nexport interface FetchApp {\n fetch(request: Request, env?: Env, ctx?: ExecutionContextLike): Response | Promise<Response>\n}\n\nexport interface ServeOptions {\n /** Default: `process.env.PORT` or 8000. */\n port?: number\n /** Default: '0.0.0.0' (all interfaces) — use '127.0.0.1' for local only. */\n hostname?: string\n /** Passed to `app.fetch()` as `env` (settings read it). Default: `process.env`. */\n env?: Env\n /** Called once the server is listening. Default: logs the address. */\n onListen?(info: { address: string; port: number; family?: string }): void\n /** Close the server gracefully on SIGINT/SIGTERM (default true). */\n handleSignals?: boolean\n}\n\n/** A Workers-like ExecutionContext for Node: `waitUntil` promises are tracked and their errors logged. */\nexport function createExecutionContext(): ExecutionContextLike & {\n pending: Set<Promise<unknown>>\n drain(): Promise<void>\n} {\n const pending = new Set<Promise<unknown>>()\n return {\n pending,\n waitUntil(promise: Promise<unknown>) {\n const p = Promise.resolve(promise)\n .catch((err) => console.error('waitUntil task failed:', err))\n .finally(() => pending.delete(p))\n pending.add(p)\n },\n passThroughOnException() {},\n async drain() {\n while (pending.size) await Promise.all([...pending])\n },\n }\n}\n\n/**\n * Serve a Ghuri app with `@hono/node-server`:\n *\n * ```ts\n * import { serve } from '@ghuri/core/node'\n * serve(createApp(settings), { port: 8000, env: process.env })\n * ```\n */\nexport async function serve(app: FetchApp, opts: ServeOptions = {}) {\n const { serve: nodeServe } = await import('@hono/node-server')\n const env = opts.env ?? (process.env as Env)\n const port = opts.port ?? (process.env.PORT ? Number(process.env.PORT) : 8000)\n const hostname = opts.hostname ?? '0.0.0.0'\n const execution = createExecutionContext()\n const server = nodeServe(\n {\n fetch: (request: Request, bindings?: any) => {\n // env stays the settings env; the socket address is exposed through getRemoteAddr(c)\n const addr = bindings?.incoming?.socket?.remoteAddress\n if (typeof addr === 'string' && addr) setRemoteAddr(request, addr)\n return app.fetch(request, env, execution)\n },\n port,\n hostname,\n },\n (info) => {\n if (opts.onListen) opts.onListen(info)\n else\n console.log(\n `Ghuri server listening on http://${hostname === '0.0.0.0' ? 'localhost' : hostname}:${info.port}/`,\n )\n },\n )\n if (opts.handleSignals !== false) {\n const shutdown = () => {\n server.close(() => {\n execution.drain().finally(() => process.exit(0))\n })\n setTimeout(() => process.exit(0), 10_000).unref()\n }\n process.once('SIGINT', shutdown)\n process.once('SIGTERM', shutdown)\n }\n return server\n}\n"],"mappings":";;;;;AAuBO,SAAS,yBAGd;AACA,QAAM,UAAU,oBAAI,IAAsB;AAC1C,SAAO;AAAA,IACL;AAAA,IACA,UAAU,SAA2B;AACnC,YAAM,IAAI,QAAQ,QAAQ,OAAO,EAC9B,MAAM,CAAC,QAAQ,QAAQ,MAAM,0BAA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YAAQ,KAAK,WAAW,QAAQ;AAAA,EAClC;AACA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/node.ts"],"sourcesContent":["// @ghuri/core/node — run a Ghuri app on Node.js (VPS, containers, local dev without wrangler).\nimport type { Env, ExecutionContextLike } from './context'\nimport { type CronExpression, parseCron } from './cron'\nimport { setRemoteAddr } from './remote'\nimport { type ScheduledEventLike, taskHandlers } from './tasks'\n\n/** Anything with a Workers-style `fetch(request, env, ctx)` — a GhuriApp or a Hono app. */\nexport interface FetchApp {\n fetch(request: Request, env?: Env, ctx?: ExecutionContextLike): Response | Promise<Response>\n}\n\nexport interface ServeOptions {\n /** Default: `process.env.PORT` or 8000. */\n port?: number\n /** Default: '0.0.0.0' (all interfaces) — use '127.0.0.1' for local only. */\n hostname?: string\n /** Passed to `app.fetch()` as `env` (settings read it). Default: `process.env`. */\n env?: Env\n /** Called once the server is listening. Default: logs the address. */\n onListen?(info: { address: string; port: number; family?: string }): void\n /** Close the server gracefully on SIGINT/SIGTERM (default true). */\n handleSignals?: boolean\n /**\n * Also fire the app's Cron Triggers in this process (`startScheduler()`), like `wrangler dev` does with\n * `--test-scheduled` and Cloudflare does in production. Run the scheduler in exactly one process.\n */\n scheduler?: boolean | Omit<SchedulerOptions, 'env'>\n}\n\n/** A Workers-like ExecutionContext for Node: `waitUntil` promises are tracked and their errors logged. */\nexport function createExecutionContext(): ExecutionContextLike & {\n pending: Set<Promise<unknown>>\n drain(): Promise<void>\n} {\n const pending = new Set<Promise<unknown>>()\n return {\n pending,\n waitUntil(promise: Promise<unknown>) {\n const p = Promise.resolve(promise)\n .catch((err) => console.error('waitUntil task failed:', err))\n .finally(() => pending.delete(p))\n pending.add(p)\n },\n passThroughOnException() {},\n async drain() {\n while (pending.size) await Promise.all([...pending])\n },\n }\n}\n\n/**\n * Serve a Ghuri app with `@hono/node-server`:\n *\n * ```ts\n * import { serve } from '@ghuri/core/node'\n * serve(createApp(settings), { port: 8000, env: process.env })\n * ```\n */\nexport async function serve(app: FetchApp, opts: ServeOptions = {}) {\n const { serve: nodeServe } = await import('@hono/node-server')\n const env = opts.env ?? (process.env as Env)\n const port = opts.port ?? (process.env.PORT ? Number(process.env.PORT) : 8000)\n const hostname = opts.hostname ?? '0.0.0.0'\n const execution = createExecutionContext()\n const server = nodeServe(\n {\n fetch: (request: Request, bindings?: any) => {\n // env stays the settings env; the socket address is exposed through getRemoteAddr(c)\n const addr = bindings?.incoming?.socket?.remoteAddress\n if (typeof addr === 'string' && addr) setRemoteAddr(request, addr)\n return app.fetch(request, env, execution)\n },\n port,\n hostname,\n },\n (info) => {\n if (opts.onListen) opts.onListen(info)\n else\n console.log(\n `Ghuri server listening on http://${hostname === '0.0.0.0' ? 'localhost' : hostname}:${info.port}/`,\n )\n },\n )\n const scheduler =\n opts.scheduler && typeof (app as Partial<SchedulableApp>).scheduled === 'function'\n ? await startScheduler(app as unknown as SchedulableApp, {\n ...(typeof opts.scheduler === 'object' ? opts.scheduler : {}),\n env,\n })\n : null\n if (opts.handleSignals !== false) {\n const shutdown = () => {\n void scheduler?.stop()\n server.close(() => {\n execution.drain().finally(() => process.exit(0))\n })\n setTimeout(() => process.exit(0), 10_000).unref()\n }\n process.once('SIGINT', shutdown)\n process.once('SIGTERM', shutdown)\n }\n return server\n}\n\n/** An app with Workers' `scheduled()` handler (a `GhuriApp`). */\nexport interface SchedulableApp {\n scheduled(event: ScheduledEventLike, env?: Env, ctx?: ExecutionContextLike): Promise<void>\n /** Populates the app registry so `onSchedule()` handlers registered in `ready()` are known. */\n run?<T>(\n env: Env | undefined,\n ctx: ExecutionContextLike | undefined,\n fn: (ctx: any) => Promise<T>,\n ): Promise<T>\n}\n\nexport interface SchedulerOptions {\n /** Cron expressions to fire (default: every cron registered with `onSchedule()`, read after the apps load). */\n crons?: string[]\n /** Passed to `app.scheduled()` as `env`. Default: `process.env`. */\n env?: Env\n /** Called when a scheduled handler throws (default: logs it). The scheduler keeps running. */\n onError?(error: unknown, cron: string): void\n /** Called once with the crons being fired (default: logs them). */\n onStart?(crons: string[]): void\n}\n\nexport interface Scheduler {\n readonly crons: string[]\n /** Stop firing and wait for running handlers. */\n stop(): Promise<void>\n}\n\n/**\n * Fire a Ghuri app's Cron Triggers on Node with Cloudflare's semantics (UTC, 1 = Sunday; see `parseCron`): at\n * each matching minute, `app.scheduled({ cron, scheduledTime })` runs, so `onSchedule()` handlers and\n * `@ghuri/tasks` periodic tasks work outside Workers. Like Celery beat, run it in exactly one process.\n */\nexport async function startScheduler(app: SchedulableApp, opts: SchedulerOptions = {}): Promise<Scheduler> {\n const env = opts.env ?? (process.env as Env)\n if (!opts.crons && typeof app.run === 'function') await app.run(env, undefined, async () => undefined)\n const crons = opts.crons ?? taskHandlers.crons()\n const parsed: CronExpression[] = crons.map((c) => parseCron(c))\n const execution = createExecutionContext()\n const running = new Set<Promise<void>>()\n let timer: ReturnType<typeof setTimeout> | undefined\n let stopped = false\n let lastMinute = Math.floor(Date.now() / 60_000)\n\n const fire = (minute: number) => {\n const at = new Date(minute * 60_000)\n for (const cron of parsed) {\n if (!cron.matches(at)) continue\n const event: ScheduledEventLike = {\n cron: cron.source,\n scheduledTime: at.getTime(),\n type: 'scheduled',\n noRetry() {},\n }\n const p = app\n .scheduled(event, env, execution)\n .catch((err) =>\n opts.onError ? opts.onError(err, cron.source) : console.error(`Cron '${cron.source}' failed:`, err),\n )\n .finally(() => running.delete(p))\n running.add(p)\n }\n }\n\n const tick = () => {\n if (stopped) return\n const minute = Math.floor(Date.now() / 60_000)\n // Fire every minute boundary crossed since the last tick (at most a few after a sleep / clock jump).\n for (let m = Math.max(lastMinute + 1, minute - 5); m <= minute; m++) fire(m)\n lastMinute = Math.max(lastMinute, minute)\n const delay = (minute + 1) * 60_000 - Date.now() + 50\n timer = setTimeout(tick, Math.max(delay, 50))\n }\n\n if (parsed.length) {\n if (opts.onStart) opts.onStart(crons)\n else console.log(`Ghuri scheduler: ${crons.map((c) => `'${c}'`).join(', ')} (UTC)`)\n timer = setTimeout(tick, (lastMinute + 1) * 60_000 - Date.now() + 50)\n }\n\n return {\n crons,\n async stop() {\n stopped = true\n if (timer) clearTimeout(timer)\n await Promise.all([...running])\n await execution.drain()\n },\n }\n}\n"],"mappings":";;;;;;;;AA8BO,SAAS,yBAGd;AACA,QAAM,UAAU,oBAAI,IAAsB;AAC1C,SAAO;AAAA,IACL;AAAA,IACA,UAAU,SAA2B;AACnC,YAAM,IAAI,QAAQ,QAAQ,OAAO,EAC9B,MAAM,CAAC,QAAQ,QAAQ,MAAM,0BAA0B,GAAG,CAAC,EAC3D,QAAQ,MAAM,QAAQ,OAAO,CAAC,CAAC;AAClC,cAAQ,IAAI,CAAC;AAAA,IACf;AAAA,IACA,yBAAyB;AAAA,IAAC;AAAA,IAC1B,MAAM,QAAQ;AACZ,aAAO,QAAQ,KAAM,OAAM,QAAQ,IAAI,CAAC,GAAG,OAAO,CAAC;AAAA,IACrD;AAAA,EACF;AACF;AAUA,eAAsB,MAAM,KAAe,OAAqB,CAAC,GAAG;AAClE,QAAM,EAAE,OAAO,UAAU,IAAI,MAAM,OAAO,mBAAmB;AAC7D,QAAM,MAAM,KAAK,OAAQ,QAAQ;AACjC,QAAM,OAAO,KAAK,SAAS,QAAQ,IAAI,OAAO,OAAO,QAAQ,IAAI,IAAI,IAAI;AACzE,QAAM,WAAW,KAAK,YAAY;AAClC,QAAM,YAAY,uBAAuB;AACzC,QAAM,SAAS;AAAA,IACb;AAAA,MACE,OAAO,CAAC,SAAkB,aAAmB;AAE3C,cAAM,OAAO,UAAU,UAAU,QAAQ;AACzC,YAAI,OAAO,SAAS,YAAY,KAAM,eAAc,SAAS,IAAI;AACjE,eAAO,IAAI,MAAM,SAAS,KAAK,SAAS;AAAA,MAC1C;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA,CAAC,SAAS;AACR,UAAI,KAAK,SAAU,MAAK,SAAS,IAAI;AAAA;AAEnC,gBAAQ;AAAA,UACN,oCAAoC,aAA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
|
3
|
+
/** Cloudflare `ScheduledController` (structural). */
|
|
4
|
+
interface ScheduledEventLike {
|
|
5
|
+
cron: string;
|
|
6
|
+
scheduledTime: number;
|
|
7
|
+
type?: string;
|
|
8
|
+
noRetry?(): void;
|
|
9
|
+
}
|
|
10
|
+
/** Cloudflare Queues message (structural). */
|
|
11
|
+
interface QueueMessageLike<T = unknown> {
|
|
12
|
+
id: string;
|
|
13
|
+
timestamp: Date;
|
|
14
|
+
body: T;
|
|
15
|
+
attempts?: number;
|
|
16
|
+
ack(): void;
|
|
17
|
+
retry(opts?: {
|
|
18
|
+
delaySeconds?: number;
|
|
19
|
+
}): void;
|
|
20
|
+
}
|
|
21
|
+
/** Cloudflare Queues `MessageBatch` (structural). */
|
|
22
|
+
interface MessageBatchLike<T = unknown> {
|
|
23
|
+
queue: string;
|
|
24
|
+
messages: readonly QueueMessageLike<T>[];
|
|
25
|
+
ackAll(): void;
|
|
26
|
+
retryAll(opts?: {
|
|
27
|
+
delaySeconds?: number;
|
|
28
|
+
}): void;
|
|
29
|
+
}
|
|
30
|
+
type ScheduledHandler = (event: ScheduledEventLike, ctx: GhuriContext) => void | Promise<void>;
|
|
31
|
+
type QueueHandler<T = any> = (batch: MessageBatchLike<T>, ctx: GhuriContext) => void | Promise<void>;
|
|
32
|
+
/**
|
|
33
|
+
* Run `handler` for Cron Triggers matching `cron` (the exact expression from wrangler.jsonc, or `'*'` for
|
|
34
|
+
* every trigger). Typically called from an AppConfig's `ready()`. Returns an unregister function.
|
|
35
|
+
*/
|
|
36
|
+
declare function onSchedule(cron: string, handler: ScheduledHandler): () => void;
|
|
37
|
+
/** Consume batches of the queue named `queue` (or `'*'` for all queues). Returns an unregister function. */
|
|
38
|
+
declare function onQueue<T = any>(queue: string, handler: QueueHandler<T>): () => void;
|
|
39
|
+
/** Introspection / test helpers for the cron & queue handler registry. */
|
|
40
|
+
declare const taskHandlers: {
|
|
41
|
+
schedulesFor(cron: string): ScheduledHandler[];
|
|
42
|
+
/** Every cron expression registered with `onSchedule()` (without `'*'`), in registration order. */
|
|
43
|
+
crons(): string[];
|
|
44
|
+
queuesFor(queue: string): QueueHandler[];
|
|
45
|
+
clear(): void;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export { type MessageBatchLike as M, type QueueHandler as Q, type ScheduledEventLike as S, type QueueMessageLike as a, type ScheduledHandler as b, onSchedule as c, onQueue as o, taskHandlers as t };
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { E as Env,
|
|
1
|
+
import { E as Env, a as ExecutionContextLike, b as GhuriContext } from './context-BM17cFwp.js';
|
|
2
2
|
import 'hono';
|
|
3
3
|
|
|
4
4
|
/** Anything with a Workers-style `fetch` (a GhuriApp, a Hono app, …). */
|
package/dist/testing.js
CHANGED
package/dist/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/testing.ts"],"sourcesContent":["// @ghuri/core/testing — Django-style test client. Fetch-based: works on Node and inside Workers (vitest-pool-workers).\nimport { type Env, type ExecutionContextLike, type GhuriContext, runWithContext } from './context'\nimport { generateCsrfSecret } from './csrf'\n\n/** Anything with a Workers-style `fetch` (a GhuriApp, a Hono app, …). */\nexport interface TestableApp {\n fetch(request: Request, env?: Env, ctx?: ExecutionContextLike): Response | Promise<Response>\n setup?(env?: Env): Promise<GhuriContext>\n}\n\nexport interface TestClientOptions {\n env?: Env\n /** Base URL of requests (default `http://testserver`). */\n baseUrl?: string\n /** Default headers for every request. */\n headers?: Record<string, string>\n /**\n * Send the CSRF token automatically on unsafe requests (default true). The token comes from the\n * `csrftoken` cookie; if there is none yet, the client creates one (like a browser that loaded a form).\n * Set to false to test CSRF failures.\n */\n csrf?: boolean\n csrfCookieName?: string\n csrfHeaderName?: string\n}\n\nexport interface RequestOptions {\n /** JSON body (sets Content-Type: application/json). */\n json?: unknown\n /** Form body: urlencoded, or multipart when it contains a Blob/File or is a FormData. */\n form?: Record<string, unknown> | FormData\n /** Raw body. */\n body?: BodyInit | null\n headers?: Record<string, string>\n /** Query string parameters (arrays repeat the key). */\n query?: Record<string, unknown> | URLSearchParams\n /** Follow redirects (Django's `follow=True`), max 20 hops. */\n follow?: boolean\n /** Override `csrf` for this request. */\n csrf?: boolean\n}\n\nexport interface TestResponse extends Response {\n /** Redirects followed (`follow: true`): `[url, status][]`. */\n redirectChain: Array<[string, number]>\n /** The request that produced this response. */\n request: Request\n}\n\nexport interface Cookie {\n name: string\n value: string\n path?: string\n expires?: Date\n}\n\n/** Hook used by packages to extend the client (e.g. `@ghuri/auth` implements `forceLogin`). */\nexport type TestClientHook = (client: TestClient, ...args: any[]) => unknown | Promise<unknown>\n\nconst HOOKS_KEY = Symbol.for('ghuri.core.testClientHooks')\nconst hooks: Map<string, TestClientHook> = ((globalThis as any)[HOOKS_KEY] ??= new Map())\n\n/**\n * Register a test-client extension: `registerTestClientHook('forceLogin', async (client, user) => {...})`.\n * Built-in hook names used by `TestClient`: `forceLogin`, `login`, `logout`.\n */\nexport function registerTestClientHook(name: string, fn: TestClientHook): void {\n hooks.set(name, fn)\n}\n\nexport function getTestClientHook(name: string): TestClientHook | undefined {\n return hooks.get(name)\n}\n\nconst UNSAFE = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\nfunction parseSetCookie(header: string): Cookie & { delete: boolean } {\n const [pair, ...attrs] = header.split(';')\n const eq = pair.indexOf('=')\n const name = pair.slice(0, eq).trim()\n let value = pair.slice(eq + 1).trim()\n if (value.startsWith('\"') && value.endsWith('\"')) value = value.slice(1, -1)\n try {\n value = decodeURIComponent(value)\n } catch {\n // keep raw\n }\n const cookie: Cookie & { delete: boolean } = { name, value, delete: false }\n for (const attr of attrs) {\n const [k, ...rest] = attr.trim().split('=')\n const v = rest.join('=')\n const key = k.toLowerCase()\n if (key === 'max-age' && Number(v) <= 0) cookie.delete = true\n if (key === 'expires') {\n const d = new Date(v)\n cookie.expires = d\n if (!Number.isNaN(d.getTime()) && d.getTime() <= Date.now()) cookie.delete = true\n }\n if (key === 'path') cookie.path = v\n }\n return cookie\n}\n\nfunction appendQuery(url: URL, query: RequestOptions['query']): void {\n if (!query) return\n if (query instanceof URLSearchParams) {\n for (const [k, v] of query) url.searchParams.append(k, v)\n return\n }\n for (const [k, v] of Object.entries(query)) {\n if (v === undefined || v === null) continue\n if (Array.isArray(v)) for (const x of v) url.searchParams.append(k, String(x))\n else url.searchParams.append(k, String(v))\n }\n}\n\n/** Django's test `Client`, for Ghuri apps. */\nexport class TestClient {\n readonly env: Env\n readonly baseUrl: string\n readonly cookies = new Map<string, Cookie>()\n readonly defaultHeaders: Record<string, string>\n private pending: Promise<unknown>[] = []\n private readonly csrf: boolean\n private readonly csrfCookieName: string\n private readonly csrfHeaderName: string\n\n constructor(\n readonly app: TestableApp,\n opts: TestClientOptions = {},\n ) {\n this.env = opts.env ?? {}\n this.baseUrl = opts.baseUrl ?? 'http://testserver'\n this.defaultHeaders = { ...opts.headers }\n this.csrf = opts.csrf ?? true\n this.csrfCookieName = opts.csrfCookieName ?? 'csrftoken'\n this.csrfHeaderName = opts.csrfHeaderName ?? 'X-CSRFToken'\n }\n\n /** ExecutionContext handed to the app; `waitUntil` promises can be awaited with `waitForBackgroundTasks()`. */\n readonly executionCtx: ExecutionContextLike = {\n waitUntil: (p) => {\n this.pending.push(Promise.resolve(p).catch((err) => console.error('waitUntil task failed:', err)))\n },\n passThroughOnException: () => {},\n }\n\n async waitForBackgroundTasks(): Promise<void> {\n while (this.pending.length) {\n const batch = this.pending\n this.pending = []\n await Promise.all(batch)\n }\n }\n\n // ------------------------------------------------------------------ cookies\n getCookie(name: string): string | undefined {\n return this.cookies.get(name)?.value\n }\n\n setCookie(name: string, value: string, opts: Omit<Cookie, 'name' | 'value'> = {}): void {\n this.cookies.set(name, { name, value, ...opts })\n }\n\n deleteCookie(name: string): void {\n this.cookies.delete(name)\n }\n\n clearCookies(): void {\n this.cookies.clear()\n }\n\n private cookieHeader(): string | undefined {\n const now = Date.now()\n const parts: string[] = []\n for (const c of this.cookies.values()) {\n if (c.expires && c.expires.getTime() <= now) {\n this.cookies.delete(c.name)\n continue\n }\n parts.push(`${c.name}=${encodeURIComponent(c.value)}`)\n }\n return parts.length ? parts.join('; ') : undefined\n }\n\n private storeCookies(res: Response): void {\n const headers = res.headers as Headers & { getSetCookie?(): string[] }\n const list = headers.getSetCookie?.() ?? (headers.get('set-cookie') ? [headers.get('set-cookie')!] : [])\n for (const h of list) {\n const c = parseSetCookie(h)\n if (!c.name) continue\n if (c.delete) this.cookies.delete(c.name)\n else this.cookies.set(c.name, { name: c.name, value: c.value, path: c.path, expires: c.expires })\n }\n }\n\n // ------------------------------------------------------------------ requests\n /** Build the Request a call would send (without sending it). */\n buildRequest(method: string, path: string, opts: RequestOptions = {}): Request {\n const url = new URL(path, this.baseUrl)\n appendQuery(url, opts.query)\n const headers = new Headers(this.defaultHeaders)\n for (const [k, v] of Object.entries(opts.headers ?? {})) headers.set(k, v)\n let body: BodyInit | null | undefined = opts.body\n if (opts.json !== undefined) {\n body = JSON.stringify(opts.json)\n if (!headers.has('content-type')) headers.set('content-type', 'application/json')\n } else if (opts.form !== undefined) {\n const form = opts.form\n const multipart =\n form instanceof FormData ||\n Object.values(form).some(\n (v) => v instanceof Blob || (Array.isArray(v) && v.some((x) => x instanceof Blob)),\n )\n if (multipart) {\n let fd: FormData\n if (form instanceof FormData) {\n fd = form\n } else {\n fd = new FormData()\n for (const [k, v] of Object.entries(form)) {\n for (const x of Array.isArray(v) ? v : [v]) {\n if (x === undefined || x === null) continue\n fd.append(k, x instanceof Blob ? x : String(x))\n }\n }\n }\n body = fd\n } else {\n const sp = new URLSearchParams()\n for (const [k, v] of Object.entries(form as Record<string, unknown>)) {\n for (const x of Array.isArray(v) ? v : [v])\n if (x !== undefined && x !== null) sp.append(k, String(x))\n }\n body = sp.toString()\n if (!headers.has('content-type')) headers.set('content-type', 'application/x-www-form-urlencoded')\n }\n }\n const upper = method.toUpperCase()\n const csrf = opts.csrf ?? this.csrf\n if (csrf && UNSAFE.has(upper) && !headers.has(this.csrfHeaderName)) {\n let token = this.getCookie(this.csrfCookieName)\n if (!token) {\n token = generateCsrfSecret()\n this.setCookie(this.csrfCookieName, token)\n }\n headers.set(this.csrfHeaderName, token)\n }\n const cookie = this.cookieHeader()\n if (cookie && !headers.has('cookie')) headers.set('cookie', cookie)\n return new Request(url, {\n method: upper,\n headers,\n body: upper === 'GET' || upper === 'HEAD' ? undefined : body,\n })\n }\n\n /** Send a raw Request through the app (cookies are still recorded). */\n async fetch(request: Request): Promise<Response> {\n const res = await this.app.fetch(request, this.env, this.executionCtx)\n this.storeCookies(res)\n return res\n }\n\n async request(method: string, path: string, opts: RequestOptions = {}): Promise<TestResponse> {\n const chain: Array<[string, number]> = []\n let req = this.buildRequest(method, path, opts)\n let res = await this.fetch(req)\n if (opts.follow) {\n let hops = 0\n while (res.status >= 300 && res.status < 400 && res.headers.get('location') && hops++ < 20) {\n const location = new URL(res.headers.get('location')!, req.url)\n chain.push([location.pathname + location.search, res.status])\n const keepMethod = res.status === 307 || res.status === 308\n const nextMethod = keepMethod ? method : method.toUpperCase() === 'HEAD' ? 'HEAD' : 'GET'\n const nextOpts: RequestOptions = keepMethod\n ? { ...opts, query: undefined }\n : { headers: opts.headers }\n req = this.buildRequest(nextMethod, location.toString(), nextOpts)\n res = await this.fetch(req)\n }\n }\n return Object.assign(res, { redirectChain: chain, request: req }) as TestResponse\n }\n\n get(path: string, opts?: RequestOptions) {\n return this.request('GET', path, opts)\n }\n head(path: string, opts?: RequestOptions) {\n return this.request('HEAD', path, opts)\n }\n options(path: string, opts?: RequestOptions) {\n return this.request('OPTIONS', path, opts)\n }\n post(path: string, opts?: RequestOptions) {\n return this.request('POST', path, opts)\n }\n put(path: string, opts?: RequestOptions) {\n return this.request('PUT', path, opts)\n }\n patch(path: string, opts?: RequestOptions) {\n return this.request('PATCH', path, opts)\n }\n delete(path: string, opts?: RequestOptions) {\n return this.request('DELETE', path, opts)\n }\n\n // ------------------------------------------------------------------ context & hooks\n /** `app.setup(env)`: populate apps and install the global context (for DB access in tests). */\n async setup(): Promise<GhuriContext | undefined> {\n return this.app.setup?.(this.env)\n }\n\n /** Run `fn` inside a fresh Ghuri context for this client's env (e.g. to create fixtures). */\n async withContext<T>(fn: (ctx: GhuriContext) => T | Promise<T>): Promise<T> {\n if (!this.app.setup) throw new TypeError('withContext() needs a GhuriApp (with setup()).')\n const base = await this.app.setup(this.env)\n const ctx: GhuriContext = { ...base, state: new Map() }\n return runWithContext(ctx, () => fn(ctx))\n }\n\n /** Call a registered hook by name. */\n async callHook<T = unknown>(name: string, ...args: unknown[]): Promise<T> {\n const hook = hooks.get(name)\n if (!hook) {\n throw new Error(\n `No test client hook '${name}' is registered. Is the package that provides it (e.g. @ghuri/auth) imported?`,\n )\n }\n return (await hook(this, ...args)) as T\n }\n\n /** Log `user` in without credentials (provided by `@ghuri/auth`). */\n forceLogin(user: unknown, opts?: Record<string, unknown>): Promise<void> {\n return this.callHook('forceLogin', user, opts)\n }\n\n /** Log in with credentials (provided by `@ghuri/auth`). Resolves to true on success. */\n login(credentials: Record<string, unknown>): Promise<boolean> {\n return this.callHook('login', credentials)\n }\n\n /** Log out (uses the `logout` hook when registered, then clears all cookies). */\n async logout(): Promise<void> {\n if (hooks.has('logout')) await this.callHook('logout')\n this.clearCookies()\n }\n}\n\n/** Create a test client: `const client = createTestClient(app, { env })`. */\nexport function createTestClient(app: TestableApp, opts: TestClientOptions = {}): TestClient {\n return new TestClient(app, opts)\n}\n"],"mappings":";;;;;;AA2DA,IAAM,YAAY,uBAAO,IAAI,4BAA4B;AACzD,IAAM,QAAuC,WAAmB,SAAS,MAAM,oBAAI,IAAI;AAMhF,SAAS,uBAAuB,MAAc,IAA0B;AAC7E,QAAM,IAAI,MAAM,EAAE;AACpB;AAEO,SAAS,kBAAkB,MAA0C;AAC1E,SAAO,MAAM,IAAI,IAAI;AACvB;AAEA,IAAM,SAAS,oBAAI,IAAI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,eAAe,KAAK,MAAM,GAAG,GAAG,CAAC;AAAA,EAC1C;AAAA;AAAA,EAGA,MAAM,SAAsB,SAAiB,MAA6B;AACxE,UAAM,OAAO,MAAM,IAAI,IAAI;AAC3B,QAAI,CAAC,MAAM;AACT,YAAM,IAAI;AAAA,QACR,wBAAwB,IAAI;AAAA,MAC9B;AAAA,IACF;AACA,WAAQ,MAAM,KAAK,MAAM,GAAG,IAAI;AAAA,EAClC;AAAA;AAAA,EAGA,WAAW,MAAe,MAA+C;AACvE,WAAO,KAAK,SAAS,cAAc,MAAM,IAAI;AAAA,EAC/C;AAAA;AAAA,EAGA,MAAM,aAAwD;AAC5D,WAAO,KAAK,SAAS,SAAS,WAAW;AAAA,EAC3C;AAAA;AAAA,EAGA,MAAM,SAAwB;AAC5B,QAAI,MAAM,IAAI,QAAQ,EAAG,OAAM,KAAK,SAAS,QAAQ;AACrD,SAAK,aAAa;AAAA,EACpB;AACF;AAGO,SAAS,iBAAiB,KAAkB,OAA0B,CAAC,GAAe;AAC3F,SAAO,IAAI,WAAW,KAAK,IAAI;AACjC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/testing.ts"],"sourcesContent":["// @ghuri/core/testing — Django-style test client. Fetch-based: works on Node and inside Workers (vitest-pool-workers).\nimport { type Env, type ExecutionContextLike, type GhuriContext, runWithContext } from './context'\nimport { generateCsrfSecret } from './csrf'\n\n/** Anything with a Workers-style `fetch` (a GhuriApp, a Hono app, …). */\nexport interface TestableApp {\n fetch(request: Request, env?: Env, ctx?: ExecutionContextLike): Response | Promise<Response>\n setup?(env?: Env): Promise<GhuriContext>\n}\n\nexport interface TestClientOptions {\n env?: Env\n /** Base URL of requests (default `http://testserver`). */\n baseUrl?: string\n /** Default headers for every request. */\n headers?: Record<string, string>\n /**\n * Send the CSRF token automatically on unsafe requests (default true). The token comes from the\n * `csrftoken` cookie; if there is none yet, the client creates one (like a browser that loaded a form).\n * Set to false to test CSRF failures.\n */\n csrf?: boolean\n csrfCookieName?: string\n csrfHeaderName?: string\n}\n\nexport interface RequestOptions {\n /** JSON body (sets Content-Type: application/json). */\n json?: unknown\n /** Form body: urlencoded, or multipart when it contains a Blob/File or is a FormData. */\n form?: Record<string, unknown> | FormData\n /** Raw body. */\n body?: BodyInit | null\n headers?: Record<string, string>\n /** Query string parameters (arrays repeat the key). */\n query?: Record<string, unknown> | URLSearchParams\n /** Follow redirects (Django's `follow=True`), max 20 hops. */\n follow?: boolean\n /** Override `csrf` for this request. */\n csrf?: boolean\n}\n\nexport interface TestResponse extends Response {\n /** Redirects followed (`follow: true`): `[url, status][]`. */\n redirectChain: Array<[string, number]>\n /** The request that produced this response. */\n request: Request\n}\n\nexport interface Cookie {\n name: string\n value: string\n path?: string\n expires?: Date\n}\n\n/** Hook used by packages to extend the client (e.g. `@ghuri/auth` implements `forceLogin`). */\nexport type TestClientHook = (client: TestClient, ...args: any[]) => unknown | Promise<unknown>\n\nconst HOOKS_KEY = Symbol.for('ghuri.core.testClientHooks')\nconst hooks: Map<string, TestClientHook> = ((globalThis as any)[HOOKS_KEY] ??= new Map())\n\n/**\n * Register a test-client extension: `registerTestClientHook('forceLogin', async (client, user) => {...})`.\n * Built-in hook names used by `TestClient`: `forceLogin`, `login`, `logout`.\n */\nexport function registerTestClientHook(name: string, fn: TestClientHook): void {\n hooks.set(name, fn)\n}\n\nexport function getTestClientHook(name: string): TestClientHook | undefined {\n return hooks.get(name)\n}\n\nconst UNSAFE = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\nfunction parseSetCookie(header: string): Cookie & { delete: boolean } {\n const [pair, ...attrs] = header.split(';')\n const eq = pair.indexOf('=')\n const name = pair.slice(0, eq).trim()\n let value = pair.slice(eq + 1).trim()\n if (value.startsWith('\"') && value.endsWith('\"')) value = value.slice(1, -1)\n try {\n value = decodeURIComponent(value)\n } catch {\n // keep raw\n }\n const cookie: Cookie & { delete: boolean } = { name, value, delete: false }\n for (const attr of attrs) {\n const [k, ...rest] = attr.trim().split('=')\n const v = rest.join('=')\n const key = k.toLowerCase()\n if (key === 'max-age' && Number(v) <= 0) cookie.delete = true\n if (key === 'expires') {\n const d = new Date(v)\n cookie.expires = d\n if (!Number.isNaN(d.getTime()) && d.getTime() <= Date.now()) cookie.delete = true\n }\n if (key === 'path') cookie.path = v\n }\n return cookie\n}\n\nfunction appendQuery(url: URL, query: RequestOptions['query']): void {\n if (!query) return\n if (query instanceof URLSearchParams) {\n for (const [k, v] of query) url.searchParams.append(k, v)\n return\n }\n for (const [k, v] of Object.entries(query)) {\n if (v === undefined || v === null) continue\n if (Array.isArray(v)) for (const x of v) url.searchParams.append(k, String(x))\n else url.searchParams.append(k, String(v))\n }\n}\n\n/** Django's test `Client`, for Ghuri apps. */\nexport class TestClient {\n readonly env: Env\n readonly baseUrl: string\n readonly cookies = new Map<string, Cookie>()\n readonly defaultHeaders: Record<string, string>\n private pending: Promise<unknown>[] = []\n private readonly csrf: boolean\n private readonly csrfCookieName: string\n private readonly csrfHeaderName: string\n\n constructor(\n readonly app: TestableApp,\n opts: TestClientOptions = {},\n ) {\n this.env = opts.env ?? {}\n this.baseUrl = opts.baseUrl ?? 'http://testserver'\n this.defaultHeaders = { ...opts.headers }\n this.csrf = opts.csrf ?? true\n this.csrfCookieName = opts.csrfCookieName ?? 'csrftoken'\n this.csrfHeaderName = opts.csrfHeaderName ?? 'X-CSRFToken'\n }\n\n /** ExecutionContext handed to the app; `waitUntil` promises can be awaited with `waitForBackgroundTasks()`. */\n readonly executionCtx: ExecutionContextLike = {\n waitUntil: (p) => {\n this.pending.push(Promise.resolve(p).catch((err) => console.error('waitUntil task failed:', err)))\n },\n passThroughOnException: () => {},\n }\n\n async waitForBackgroundTasks(): Promise<void> {\n while (this.pending.length) {\n const batch = this.pending\n this.pending = []\n await Promise.all(batch)\n }\n }\n\n // ------------------------------------------------------------------ cookies\n getCookie(name: string): string | undefined {\n return this.cookies.get(name)?.value\n }\n\n setCookie(name: string, value: string, opts: Omit<Cookie, 'name' | 'value'> = {}): void {\n this.cookies.set(name, { name, value, ...opts })\n }\n\n deleteCookie(name: string): void {\n this.cookies.delete(name)\n }\n\n clearCookies(): void {\n this.cookies.clear()\n }\n\n private cookieHeader(): string | undefined {\n const now = Date.now()\n const parts: string[] = []\n for (const c of this.cookies.values()) {\n if (c.expires && c.expires.getTime() <= now) {\n this.cookies.delete(c.name)\n continue\n }\n parts.push(`${c.name}=${encodeURIComponent(c.value)}`)\n }\n return parts.length ? parts.join('; ') : undefined\n }\n\n private storeCookies(res: Response): void {\n const headers = res.headers as Headers & { getSetCookie?(): string[] }\n const list = headers.getSetCookie?.() ?? (headers.get('set-cookie') ? [headers.get('set-cookie')!] : [])\n for (const h of list) {\n const c = parseSetCookie(h)\n if (!c.name) continue\n if (c.delete) this.cookies.delete(c.name)\n else this.cookies.set(c.name, { name: c.name, value: c.value, path: c.path, expires: c.expires })\n }\n }\n\n // ------------------------------------------------------------------ requests\n /** Build the Request a call would send (without sending it). */\n buildRequest(method: string, path: string, opts: RequestOptions = {}): Request {\n const url = new URL(path, this.baseUrl)\n appendQuery(url, opts.query)\n const headers = new Headers(this.defaultHeaders)\n for (const [k, v] of Object.entries(opts.headers ?? {})) headers.set(k, v)\n let body: BodyInit | null | undefined = opts.body\n if (opts.json !== undefined) {\n body = JSON.stringify(opts.json)\n if (!headers.has('content-type')) headers.set('content-type', 'application/json')\n } else if (opts.form !== undefined) {\n const form = opts.form\n const multipart =\n form instanceof FormData ||\n Object.values(form).some(\n (v) => v instanceof Blob || (Array.isArray(v) && v.some((x) => x instanceof Blob)),\n )\n if (multipart) {\n let fd: FormData\n if (form instanceof FormData) {\n fd = form\n } else {\n fd = new FormData()\n for (const [k, v] of Object.entries(form)) {\n for (const x of Array.isArray(v) ? v : [v]) {\n if (x === undefined || x === null) continue\n fd.append(k, x instanceof Blob ? x : String(x))\n }\n }\n }\n body = fd\n } else {\n const sp = new URLSearchParams()\n for (const [k, v] of Object.entries(form as Record<string, unknown>)) {\n for (const x of Array.isArray(v) ? v : [v])\n if (x !== undefined && x !== null) sp.append(k, String(x))\n }\n body = sp.toString()\n if (!headers.has('content-type')) headers.set('content-type', 'application/x-www-form-urlencoded')\n }\n }\n const upper = method.toUpperCase()\n const csrf = opts.csrf ?? this.csrf\n if (csrf && UNSAFE.has(upper) && !headers.has(this.csrfHeaderName)) {\n let token = this.getCookie(this.csrfCookieName)\n if (!token) {\n token = generateCsrfSecret()\n this.setCookie(this.csrfCookieName, token)\n }\n headers.set(this.csrfHeaderName, token)\n }\n const cookie = this.cookieHeader()\n if (cookie && !headers.has('cookie')) headers.set('cookie', cookie)\n return new Request(url, {\n method: upper,\n headers,\n body: upper === 'GET' || upper === 'HEAD' ? undefined : body,\n })\n }\n\n /** Send a raw Request through the app (cookies are still recorded). */\n async fetch(request: Request): Promise<Response> {\n const res = await this.app.fetch(request, this.env, this.executionCtx)\n this.storeCookies(res)\n return res\n }\n\n async request(method: string, path: string, opts: RequestOptions = {}): Promise<TestResponse> {\n const chain: Array<[string, number]> = []\n let req = this.buildRequest(method, path, opts)\n let res = await this.fetch(req)\n if (opts.follow) {\n let hops = 0\n while (res.status >= 300 && res.status < 400 && res.headers.get('location') && hops++ < 20) {\n const location = new URL(res.headers.get('location')!, req.url)\n chain.push([location.pathname + location.search, res.status])\n const keepMethod = res.status === 307 || res.status === 308\n const nextMethod = keepMethod ? method : method.toUpperCase() === 'HEAD' ? 'HEAD' : 'GET'\n const nextOpts: RequestOptions = keepMethod\n ? { ...opts, query: undefined }\n : { headers: opts.headers }\n req = this.buildRequest(nextMethod, location.toString(), nextOpts)\n res = await this.fetch(req)\n }\n }\n return Object.assign(res, { redirectChain: chain, request: req }) as TestResponse\n }\n\n get(path: string, opts?: RequestOptions) {\n return this.request('GET', path, opts)\n }\n head(path: string, opts?: RequestOptions) {\n return this.request('HEAD', path, opts)\n }\n options(path: string, opts?: RequestOptions) {\n return this.request('OPTIONS', path, opts)\n }\n post(path: string, opts?: RequestOptions) {\n return this.request('POST', path, opts)\n }\n put(path: string, opts?: RequestOptions) {\n return this.request('PUT', path, opts)\n }\n patch(path: string, opts?: RequestOptions) {\n return this.request('PATCH', path, opts)\n }\n delete(path: string, opts?: RequestOptions) {\n return this.request('DELETE', path, opts)\n }\n\n // ------------------------------------------------------------------ context & hooks\n /** `app.setup(env)`: populate apps and install the global context (for DB access in tests). */\n async setup(): Promise<GhuriContext | undefined> {\n return this.app.setup?.(this.env)\n }\n\n /** Run `fn` inside a fresh Ghuri context for this client's env (e.g. to create fixtures). */\n async withContext<T>(fn: (ctx: GhuriContext) => T | Promise<T>): Promise<T> {\n if (!this.app.setup) throw new TypeError('withContext() needs a GhuriApp (with setup()).')\n const base = await this.app.setup(this.env)\n const ctx: GhuriContext = { ...base, state: new Map() }\n return runWithContext(ctx, () => fn(ctx))\n }\n\n /** Call a registered hook by name. */\n async callHook<T = unknown>(name: string, ...args: unknown[]): Promise<T> {\n const hook = hooks.get(name)\n if (!hook) {\n throw new Error(\n `No test client hook '${name}' is registered. Is the package that provides it (e.g. @ghuri/auth) imported?`,\n )\n }\n return (await hook(this, ...args)) as T\n }\n\n /** Log `user` in without credentials (provided by `@ghuri/auth`). */\n forceLogin(user: unknown, opts?: Record<string, unknown>): Promise<void> {\n return this.callHook('forceLogin', user, opts)\n }\n\n /** Log in with credentials (provided by `@ghuri/auth`). Resolves to true on success. */\n login(credentials: Record<string, unknown>): Promise<boolean> {\n return this.callHook('login', credentials)\n }\n\n /** Log out (uses the `logout` hook when registered, then clears all cookies). */\n async logout(): Promise<void> {\n if (hooks.has('logout')) await this.callHook('logout')\n this.clearCookies()\n }\n}\n\n/** Create a test client: `const client = createTestClient(app, { env })`. */\nexport function createTestClient(app: TestableApp, opts: TestClientOptions = {}): TestClient {\n return new TestClient(app, opts)\n}\n"],"mappings":";;;;;;;AA2DA,IAAM,YAAY,uBAAO,IAAI,4BAA4B;AACzD,IAAM,QAAuC,WAAmB,SAAS,MAAM,oBAAI,IAAI;AAMhF,SAAS,uBAAuB,MAAc,IA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gDAAgD;AACzF,UAAM,OAAO,MAAM,KAAK,IAAI,MAAM,KAAK,GAAG;AAC1C,UAAM,MAAoB,EAAE,GAAG,MAAM,OAAO,oBAAI,IAAI,EAAE;AACtD,WAAO,eAAe,KAAK,MAAM,GAAG,GAAG,CAAC;AAAA,EAC1C;AAAA;AAAA,EAGA,MAAM,SAAsB,SAAiB,MAA6B;AACxE,UAAM,OAAO,MAAM,IAAI,IAAI;AAC3B,QAAI,CAAC,MAAM;AACT,YAAM,IAAI;AAAA,QACR,wBAAwB,IAAI;AAAA,MAC9B;AAAA,IACF;AACA,WAAQ,MAAM,KAAK,MAAM,GAAG,IAAI;AAAA,EAClC;AAAA;AAAA,EAGA,WAAW,MAAe,MAA+C;AACvE,WAAO,KAAK,SAAS,cAAc,MAAM,IAAI;AAAA,EAC/C;AAAA;AAAA,EAGA,MAAM,aAAwD;AAC5D,WAAO,KAAK,SAAS,SAAS,WAAW;AAAA,EAC3C;AAAA;AAAA,EAGA,MAAM,SAAwB;AAC5B,QAAI,MAAM,IAAI,QAAQ,EAAG,OAAM,KAAK,SAAS,QAAQ;AACrD,SAAK,aAAa;AAAA,EACpB;AACF;AAGO,SAAS,iBAAiB,KAAkB,OAA0B,CAAC,GAAe;AAC3F,SAAO,IAAI,WAAW,KAAK,IAAI;AACjC;","names":[]}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/context.ts","../src/urls.ts","../src/exceptions.ts","../src/csrf.ts","../src/markers.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/** Marker set on views by `xframeOptionsExempt()`. */\nexport const XFRAME_OPTIONS_EXEMPT_MARKER: symbol = Symbol.for('ghuri.xframeOptionsExempt')\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.honoPath !== null) {\n for (const marker of [CSRF_EXEMPT, XFRAME_OPTIONS_EXEMPT_MARKER])\n if ((route.view as any)?.[marker]) (handler as any)[marker] = true\n }\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, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\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 { PermissionDenied } from './errors'\nimport { settingsFor } from './exceptions'\nimport { viewHasMarker } from './markers'\nimport type { GhuriSettings } from './settings'\nimport { CSRF_EXEMPT_MARKER, 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 return viewHasMarker(c, CSRF_EXEMPT_MARKER)\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","import type { Context } from 'hono'\nimport { matchedRoutes } from 'hono/route'\nimport { settingsFor } from './exceptions'\nimport { getResolver } from './urls'\n\n/** Does the request's view (or mounted Hono app) carry `marker`? Internal: used by the `*Exempt()` helpers. */\nexport function viewHasMarker(c: Context, marker: symbol): boolean {\n try {\n for (const r of matchedRoutes(c)) if ((r.handler as any)?.[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)?.[marker] || (m.app as any)?.[marker])\n } catch {\n return false\n }\n}\n"],"mappings":";AACO,IAAM,aAAN,cAAyB,MAAM;AAAA,EACpC,YAAY,SAAkB,SAA+B;AAC3D,UAAM,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Y,IAAI;AAAA,EAC3D,CAAC;AACD,KAAG,cAAc;AACnB;","names":["state","path","kwargs","path","custom"]}
|
package/dist/chunk-YJ7DTR2K.js
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
// src/remote.ts
|
|
2
|
-
var KEY = /* @__PURE__ */ Symbol.for("ghuri.remoteAddr");
|
|
3
|
-
var addrs = globalThis[KEY] ??= /* @__PURE__ */ new WeakMap();
|
|
4
|
-
function setRemoteAddr(request, addr) {
|
|
5
|
-
addrs.set(request, addr);
|
|
6
|
-
}
|
|
7
|
-
function isCloudflareRequest(c) {
|
|
8
|
-
if (globalThis.navigator?.userAgent === "Cloudflare-Workers") return true;
|
|
9
|
-
return c.req.raw?.cf != null;
|
|
10
|
-
}
|
|
11
|
-
function getRemoteAddr(c) {
|
|
12
|
-
if (isCloudflareRequest(c)) {
|
|
13
|
-
const ip = c.req.header("cf-connecting-ip");
|
|
14
|
-
if (ip) return ip;
|
|
15
|
-
}
|
|
16
|
-
const recorded = addrs.get(c.req.raw);
|
|
17
|
-
if (recorded) return recorded;
|
|
18
|
-
const socket = c.env?.incoming?.socket?.remoteAddress;
|
|
19
|
-
return typeof socket === "string" ? socket : "";
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export {
|
|
23
|
-
setRemoteAddr,
|
|
24
|
-
isCloudflareRequest,
|
|
25
|
-
getRemoteAddr
|
|
26
|
-
};
|
|
27
|
-
//# sourceMappingURL=chunk-YJ7DTR2K.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/remote.ts"],"sourcesContent":["import type { Context } from 'hono'\n\n// Kept on globalThis so the main entry and `@ghuri/core/node` share it even if bundled twice.\nconst KEY = Symbol.for('ghuri.remoteAddr')\nconst addrs: WeakMap<Request, string> = ((globalThis as any)[KEY] ??= new WeakMap<Request, string>())\n\n/**\n * Record the peer address of an incoming request (what `getRemoteAddr()` returns for it). `serve()` from\n * `@ghuri/core/node` calls this with the socket address; call it yourself from a custom server (Bun, Deno, …)\n * before passing the request to `app.fetch()`.\n */\nexport function setRemoteAddr(request: Request, addr: string): void {\n addrs.set(request, addr)\n}\n\n/** Is this request served by Cloudflare (Workers, or `wrangler dev`/Miniflare)? */\nexport function isCloudflareRequest(c: Context): boolean {\n if ((globalThis as any).navigator?.userAgent === 'Cloudflare-Workers') return true\n return (c.req.raw as any)?.cf != null\n}\n\n/**\n * The client's network address (Django's `request.META['REMOTE_ADDR']`), from sources a client cannot forge:\n * `CF-Connecting-IP` on Cloudflare (Cloudflare sets it and overwrites any client copy), else the socket\n * address recorded by `serve()` / `setRemoteAddr()`, else `c.env.incoming` when the app is served by\n * `@hono/node-server` directly, else `''`. `X-Forwarded-For` is never read here: behind a reverse proxy this\n * is the proxy's address (REST throttles read the header with `NUM_PROXIES`).\n */\nexport function getRemoteAddr(c: Context): string {\n if (isCloudflareRequest(c)) {\n const ip = c.req.header('cf-connecting-ip')\n if (ip) return ip\n }\n const recorded = addrs.get(c.req.raw)\n if (recorded) return recorded\n const socket = (c.env as any)?.incoming?.socket?.remoteAddress\n return typeof socket === 'string' ? socket : ''\n}\n"],"mappings":";AAGA,IAAM,MAAM,uBAAO,IAAI,kBAAkB;AACzC,IAAM,QAAoC,WAAmB,GAAG,MAAM,oBAAI,QAAyB;AAO5F,SAAS,cAAc,SAAkB,MAAoB;AAClE,QAAM,IAAI,SAAS,IAAI;AACzB;AAGO,SAAS,oBAAoB,GAAqB;AACvD,MAAK,WAAmB,WAAW,cAAc,qBAAsB,QAAO;AAC9E,SAAQ,EAAE,IAAI,KAAa,MAAM;AACnC;AASO,SAAS,cAAc,GAAoB;AAChD,MAAI,oBAAoB,CAAC,GAAG;AAC1B,UAAM,KAAK,EAAE,IAAI,OAAO,kBAAkB;AAC1C,QAAI,GAAI,QAAO;AAAA,EACjB;AACA,QAAM,WAAW,MAAM,IAAI,EAAE,IAAI,GAAG;AACpC,MAAI,SAAU,QAAO;AACrB,QAAM,SAAU,EAAE,KAAa,UAAU,QAAQ;AACjD,SAAO,OAAO,WAAW,WAAW,SAAS;AAC/C;","names":[]}
|