@ghuri/core 0.1.0-alpha.3 → 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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tasks.ts","../src/cron.ts","../src/remote.ts"],"sourcesContent":["import type { GhuriContext } from './context'\n\n/** Cloudflare `ScheduledController` (structural). */\nexport interface ScheduledEventLike {\n cron: string\n scheduledTime: number\n type?: string\n noRetry?(): void\n}\n\n/** Cloudflare Queues message (structural). */\nexport interface QueueMessageLike<T = unknown> {\n id: string\n timestamp: Date\n body: T\n attempts?: number\n ack(): void\n retry(opts?: { delaySeconds?: number }): void\n}\n\n/** Cloudflare Queues `MessageBatch` (structural). */\nexport interface MessageBatchLike<T = unknown> {\n queue: string\n messages: readonly QueueMessageLike<T>[]\n ackAll(): void\n retryAll(opts?: { delaySeconds?: number }): void\n}\n\nexport type ScheduledHandler = (event: ScheduledEventLike, ctx: GhuriContext) => void | Promise<void>\nexport type QueueHandler<T = any> = (batch: MessageBatchLike<T>, ctx: GhuriContext) => void | Promise<void>\n\ninterface Registry {\n schedules: Array<{ cron: string; handler: ScheduledHandler }>\n queues: Array<{ queue: string; handler: QueueHandler }>\n}\n\nconst KEY = Symbol.for('ghuri.core.tasks')\nconst registry: Registry = ((globalThis as any)[KEY] ??= { schedules: [], queues: [] })\n\n/**\n * Run `handler` for Cron Triggers matching `cron` (the exact expression from wrangler.jsonc, or `'*'` for\n * every trigger). Typically called from an AppConfig's `ready()`. Returns an unregister function.\n */\nexport function onSchedule(cron: string, handler: ScheduledHandler): () => void {\n const entry = { cron, handler }\n registry.schedules.push(entry)\n return () => {\n registry.schedules = registry.schedules.filter((e) => e !== entry)\n }\n}\n\n/** Consume batches of the queue named `queue` (or `'*'` for all queues). Returns an unregister function. */\nexport function onQueue<T = any>(queue: string, handler: QueueHandler<T>): () => void {\n const entry = { queue, handler: handler as QueueHandler }\n registry.queues.push(entry)\n return () => {\n registry.queues = registry.queues.filter((e) => e !== entry)\n }\n}\n\n/** Introspection / test helpers for the cron & queue handler registry. */\nexport const taskHandlers = {\n schedulesFor(cron: string): ScheduledHandler[] {\n return registry.schedules.filter((e) => e.cron === cron || e.cron === '*').map((e) => e.handler)\n },\n /** Every cron expression registered with `onSchedule()` (without `'*'`), in registration order. */\n crons(): string[] {\n return [...new Set(registry.schedules.map((e) => e.cron).filter((c) => c !== '*'))]\n },\n queuesFor(queue: string): QueueHandler[] {\n return registry.queues.filter((e) => e.queue === queue || e.queue === '*').map((e) => e.handler)\n },\n clear(): void {\n registry.schedules = []\n registry.queues = []\n },\n}\n","// Cron expressions with Cloudflare Cron Triggers semantics, so a schedule fires at the same minutes on Workers and\n// on Node (`startScheduler()` in `@ghuri/core/node`). Five fields, evaluated in UTC:\n//\n// minute 0-59 · hour 0-23 · day of month 1-31 · month 1-12 or JAN-DEC · day of week 1-7 or SUN-SAT (1 = Sunday)\n//\n// Every field takes `*`, lists (`,`), ranges (`-`) and steps (`/`). Day of month also takes `L` (last day), `LW`\n// (last weekday) and `<n>W` (weekday nearest the n-th); day of week takes `<d>L` (last <d> of the month) and\n// `<d>#<n>` (n-th <d> of the month). Note that day of week is NOT Unix numbering (0 = Sunday).\n// When both day fields are restricted, a day matches if either matches (as in Vixie cron).\n\nimport { ImproperlyConfigured } from './errors'\n\nconst MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']\nconst DAYS = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT']\n\ntype DayRule =\n | { kind: 'last' } // L (day of month)\n | { kind: 'lastWeekday' } // LW\n | { kind: 'nearestWeekday'; day: number } // 15W\n | { kind: 'lastDow'; dow: number } // 6L (day of week, 1-7)\n | { kind: 'nthDow'; dow: number; nth: number } // 6#3\n\ninterface CronField {\n values: Set<number>\n rules: DayRule[]\n any: boolean\n}\n\n/** A parsed cron expression. */\nexport interface CronExpression {\n readonly source: string\n /** Does the expression fire at this minute (UTC; seconds are ignored)? */\n matches(date: Date): boolean\n /** The first minute strictly after `after` at which the expression fires (searches up to 5 years ahead). */\n next(after?: Date): Date | null\n}\n\nfunction invalid(source: string, why: string): never {\n throw new ImproperlyConfigured(`Invalid cron expression '${source}': ${why}.`)\n}\n\nfunction parseValue(token: string, names: string[] | null, offset: number, source: string): number {\n const upper = token.toUpperCase()\n if (names) {\n const i = names.indexOf(upper)\n if (i >= 0) return i + offset\n }\n if (!/^\\d+$/.test(token)) invalid(source, `'${token}' is not a number`)\n return Number(token)\n}\n\nfunction parseField(\n text: string,\n min: number,\n max: number,\n names: string[] | null,\n nameOffset: number,\n source: string,\n kind: 'plain' | 'dom' | 'dow',\n): CronField {\n const field: CronField = { values: new Set(), rules: [], any: false }\n if (text === '*' || text === '?') {\n field.any = true\n for (let v = min; v <= max; v++) field.values.add(v)\n return field\n }\n for (const part of text.split(',')) {\n if (!part) invalid(source, 'empty list item')\n const upper = part.toUpperCase()\n if (kind === 'dom') {\n if (upper === 'L') {\n field.rules.push({ kind: 'last' })\n continue\n }\n if (upper === 'LW') {\n field.rules.push({ kind: 'lastWeekday' })\n continue\n }\n const w = /^(\\d+)W$/.exec(upper)\n if (w) {\n const day = Number(w[1])\n if (day < 1 || day > 31) invalid(source, `day '${w[1]}' out of range 1-31`)\n field.rules.push({ kind: 'nearestWeekday', day })\n continue\n }\n }\n if (kind === 'dow') {\n if (upper === 'L') {\n field.values.add(7) // Quartz: L alone is the last day of the week, Saturday\n continue\n }\n const last = /^([A-Z]{3}|\\d)L$/.exec(upper)\n if (last) {\n field.rules.push({ kind: 'lastDow', dow: checkRange(parseValue(last[1], names, nameOffset, source)) })\n continue\n }\n const nth = /^([A-Z]{3}|\\d)#([1-5])$/.exec(upper)\n if (nth) {\n field.rules.push({\n kind: 'nthDow',\n dow: checkRange(parseValue(nth[1], names, nameOffset, source)),\n nth: Number(nth[2]),\n })\n continue\n }\n }\n const [range, stepText] = part.split('/')\n if (part.split('/').length > 2) invalid(source, `'${part}' has more than one '/'`)\n const step = stepText === undefined ? 1 : Number(stepText)\n if (!Number.isInteger(step) || step < 1) invalid(source, `step '${stepText}' must be a positive integer`)\n let lo: number\n let hi: number\n if (range === '*') {\n lo = min\n hi = max\n } else if (range.includes('-')) {\n const [a, b] = range.split('-')\n lo = checkRange(parseValue(a, names, nameOffset, source))\n hi = checkRange(parseValue(b, names, nameOffset, source))\n if (lo > hi) invalid(source, `range '${range}' runs backwards`)\n } else {\n lo = checkRange(parseValue(range, names, nameOffset, source))\n hi = stepText === undefined ? lo : max\n }\n for (let v = lo; v <= hi; v += step) field.values.add(v)\n }\n return field\n\n function checkRange(v: number): number {\n if (v < min || v > max) invalid(source, `${v} is out of range ${min}-${max}`)\n return v\n }\n}\n\nfunction daysInMonth(year: number, month0: number): number {\n return new Date(Date.UTC(year, month0 + 1, 0)).getUTCDate()\n}\n\nfunction isWeekday(year: number, month0: number, day: number): boolean {\n const dow = new Date(Date.UTC(year, month0, day)).getUTCDay()\n return dow !== 0 && dow !== 6\n}\n\nfunction nearestWeekday(year: number, month0: number, day: number): number {\n const last = daysInMonth(year, month0)\n const d = Math.min(day, last)\n const dow = new Date(Date.UTC(year, month0, d)).getUTCDay()\n if (dow === 6) return d === 1 ? 3 : d - 1 // Saturday → Friday (or Monday the 3rd)\n if (dow === 0) return d === last ? d - 2 : d + 1 // Sunday → Monday (or Friday before the last day)\n return d\n}\n\nfunction domMatches(field: CronField, date: Date): boolean {\n const y = date.getUTCFullYear()\n const m = date.getUTCMonth()\n const d = date.getUTCDate()\n if (field.values.has(d)) return true\n const last = daysInMonth(y, m)\n for (const rule of field.rules) {\n if (rule.kind === 'last' && d === last) return true\n if (rule.kind === 'lastWeekday') {\n let lw = last\n while (!isWeekday(y, m, lw)) lw--\n if (d === lw) return true\n }\n if (rule.kind === 'nearestWeekday' && d === nearestWeekday(y, m, rule.day)) return true\n }\n return false\n}\n\nfunction dowMatches(field: CronField, date: Date): boolean {\n const dow = date.getUTCDay() + 1 // Cloudflare: 1 = Sunday … 7 = Saturday\n if (field.values.has(dow)) return true\n const d = date.getUTCDate()\n const last = daysInMonth(date.getUTCFullYear(), date.getUTCMonth())\n for (const rule of field.rules) {\n if (rule.kind === 'lastDow' && rule.dow === dow && d + 7 > last) return true\n if (rule.kind === 'nthDow' && rule.dow === dow && Math.ceil(d / 7) === rule.nth) return true\n }\n return false\n}\n\n/** Parse a Cloudflare-style cron expression. Throws `ImproperlyConfigured` when it is invalid. */\nexport function parseCron(source: string): CronExpression {\n const parts = source.trim().split(/\\s+/)\n if (parts.length !== 5) invalid(source, `expected 5 fields, got ${parts.length}`)\n const minute = parseField(parts[0], 0, 59, null, 0, source, 'plain')\n const hour = parseField(parts[1], 0, 23, null, 0, source, 'plain')\n const dom = parseField(parts[2], 1, 31, null, 0, source, 'dom')\n const month = parseField(parts[3], 1, 12, MONTHS, 1, source, 'plain')\n const dow = parseField(parts[4], 1, 7, DAYS, 1, source, 'dow')\n\n function dayMatches(date: Date): boolean {\n if (dom.any && dow.any) return true\n if (dom.any) return dowMatches(dow, date)\n if (dow.any) return domMatches(dom, date)\n return domMatches(dom, date) || dowMatches(dow, date)\n }\n\n function matches(date: Date): boolean {\n return (\n minute.values.has(date.getUTCMinutes()) &&\n hour.values.has(date.getUTCHours()) &&\n month.values.has(date.getUTCMonth() + 1) &&\n dayMatches(date)\n )\n }\n\n function next(after: Date = new Date()): Date | null {\n const t = new Date(Math.floor(after.getTime() / 60_000) * 60_000 + 60_000)\n const limit = after.getTime() + 5 * 366 * 24 * 3600_000\n while (t.getTime() <= limit) {\n if (!month.values.has(t.getUTCMonth() + 1)) {\n t.setUTCMonth(t.getUTCMonth() + 1, 1)\n t.setUTCHours(0, 0, 0, 0)\n continue\n }\n if (!dayMatches(t)) {\n t.setUTCDate(t.getUTCDate() + 1)\n t.setUTCHours(0, 0, 0, 0)\n continue\n }\n if (!hour.values.has(t.getUTCHours())) {\n t.setUTCHours(t.getUTCHours() + 1, 0, 0, 0)\n continue\n }\n if (!minute.values.has(t.getUTCMinutes())) {\n t.setUTCMinutes(t.getUTCMinutes() + 1, 0, 0)\n continue\n }\n return new Date(t)\n }\n return null\n }\n\n return { source, matches, next }\n}\n\n/** Is `source` a valid cron expression? */\nexport function isValidCron(source: string): boolean {\n try {\n parseCron(source)\n return true\n } catch {\n return false\n }\n}\n","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":";;;;;AAoCA,IAAM,MAAM,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A,IACnB;AACA,WAAO;AAAA,EACT;AAEA,SAAO,EAAE,QAAQ,SAAS,KAAK;AACjC;AAGO,SAAS,YAAY,QAAyB;AACnD,MAAI;AACF,cAAU,MAAM;AAChB,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;;;ACnPA,IAAMA,OAAM,uBAAO,IAAI,kBAAkB;AACzC,IAAM,QAAoC,WAAmBA,IAAG,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":["KEY"]}
@@ -0,0 +1,104 @@
1
+ // src/errors.ts
2
+ var GhuriError = class extends Error {
3
+ constructor(message, options) {
4
+ super(message, options);
5
+ this.name = new.target.name;
6
+ }
7
+ };
8
+ var ImproperlyConfigured = class extends GhuriError {
9
+ };
10
+ var AppRegistryNotReady = class extends GhuriError {
11
+ };
12
+ var ObjectDoesNotExist = class extends GhuriError {
13
+ };
14
+ var MultipleObjectsReturned = class extends GhuriError {
15
+ };
16
+ var HttpError = class extends GhuriError {
17
+ status = 500;
18
+ };
19
+ var Http404 = class extends HttpError {
20
+ status = 404;
21
+ constructor(message = "Not found.") {
22
+ super(message);
23
+ }
24
+ };
25
+ var PermissionDenied = class extends HttpError {
26
+ status = 403;
27
+ constructor(message = "Permission denied.") {
28
+ super(message);
29
+ }
30
+ };
31
+ var BadRequest = class extends HttpError {
32
+ status = 400;
33
+ constructor(message = "Bad request.") {
34
+ super(message);
35
+ }
36
+ };
37
+ var SuspiciousOperation = class extends HttpError {
38
+ status = 400;
39
+ constructor(message = "Suspicious operation.") {
40
+ super(message);
41
+ }
42
+ };
43
+ var ValidationError = class _ValidationError extends GhuriError {
44
+ messages;
45
+ messageDict;
46
+ code;
47
+ constructor(message, options) {
48
+ const normalized = _ValidationError.normalize(message);
49
+ super(Array.isArray(normalized) ? normalized.join(" ") : JSON.stringify(normalized));
50
+ this.code = options?.code;
51
+ if (Array.isArray(normalized)) {
52
+ this.messages = normalized;
53
+ } else {
54
+ this.messageDict = normalized;
55
+ this.messages = Object.values(normalized).flat();
56
+ }
57
+ }
58
+ get hasFieldErrors() {
59
+ return this.messageDict !== void 0;
60
+ }
61
+ /** Merge into a field → messages dict; non-field errors go under `nonFieldKey`. */
62
+ toDict(nonFieldKey = "__all__") {
63
+ return this.messageDict ?? { [nonFieldKey]: this.messages };
64
+ }
65
+ static normalize(m) {
66
+ if (typeof m === "string") return [m];
67
+ if (Array.isArray(m)) return m;
68
+ const out = {};
69
+ for (const [k, v] of Object.entries(m)) out[k] = Array.isArray(v) ? v : [v];
70
+ return out;
71
+ }
72
+ };
73
+ var MethodNotAllowed = class extends HttpError {
74
+ constructor(method, allowed = [], message = `Method "${method.toUpperCase()}" not allowed.`) {
75
+ super(message);
76
+ this.method = method;
77
+ this.allowed = allowed;
78
+ }
79
+ method;
80
+ allowed;
81
+ status = 405;
82
+ };
83
+ var DisallowedHost = class extends SuspiciousOperation {
84
+ constructor(message = "Invalid HTTP_HOST header.") {
85
+ super(message);
86
+ }
87
+ };
88
+
89
+ export {
90
+ GhuriError,
91
+ ImproperlyConfigured,
92
+ AppRegistryNotReady,
93
+ ObjectDoesNotExist,
94
+ MultipleObjectsReturned,
95
+ HttpError,
96
+ Http404,
97
+ PermissionDenied,
98
+ BadRequest,
99
+ SuspiciousOperation,
100
+ ValidationError,
101
+ MethodNotAllowed,
102
+ DisallowedHost
103
+ };
104
+ //# sourceMappingURL=chunk-VBA235HC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.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"],"mappings":";AACO,IAAM,aAAN,cAAyB,MAAM;AAAA,EACpC,YAAY,SAAkB,SAA+B;AAC3D,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO,WAAW;AAAA,EACzB;AACF;AAGO,IAAM,uBAAN,cAAmC,WAAW;AAAC;AAG/C,IAAM,sBAAN,cAAkC,WAAW;AAAC;AAE9C,IAAM,qBAAN,cAAiC,WAAW;AAAC;AAC7C,IAAM,0BAAN,cAAsC,WAAW;AAAC;AAGlD,IAAM,YAAN,cAAwB,WAAW;AAAA,EACxC,SAAS;AACX;AACO,IAAM,UAAN,cAAsB,UAAU;AAAA,EAC5B,SAAS;AAAA,EAClB,YAAY,UAAU,cAAc;AAClC,UAAM,OAAO;AAAA,EACf;AACF;AACO,IAAM,mBAAN,cAA+B,UAAU;AAAA,EACrC,SAAS;AAAA,EAClB,YAAY,UAAU,sBAAsB;AAC1C,UAAM,OAAO;AAAA,EACf;AACF;AACO,IAAM,aA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AAM,OAAO;AAJJ;AACA;AAAA,EAIX;AAAA,EALW;AAAA,EACA;AAAA,EAHF,SAAS;AAQpB;AAGO,IAAM,iBAAN,cAA6B,oBAAoB;AAAA,EACtD,YAAY,UAAU,6BAA6B;AACjD,UAAM,OAAO;AAAA,EACf;AACF;","names":[]}
@@ -83,6 +83,8 @@ declare abstract class AppConfig {
83
83
  migrations?: Record<string, unknown>;
84
84
  /** `import * as admin from './admin'` — importing the module registers ModelAdmins. */
85
85
  admin?: unknown;
86
+ /** `import * as tasks from './tasks'` — background tasks (`@ghuri/tasks`), named `<app label>.<export name>`. */
87
+ tasks?: Record<string, unknown>;
86
88
  /** Agents, signals or any other module the app wants loaded at startup. */
87
89
  modules?: Record<string, unknown>;
88
90
  commands?: Record<string, CommandClassLike>;
@@ -591,4 +593,4 @@ declare function createContext(init: Omit<GhuriContext, 'state'> & {
591
593
  state?: GhuriContext['state'];
592
594
  }): GhuriContext;
593
595
 
594
- export { type UrlPatternsLike as $, AppConfig as A, BadRequest as B, CSRF_EXEMPT_MARKER as C, DisallowedHost as D, type Env as E, MultipleObjectsReturned as F, type GhuriSettings as G, type HonoApp as H, ImproperlyConfigured as I, type PathOptions as J, type PathTarget as K, LookupError as L, MethodNotAllowed as M, NoReverseMatch as N, ObjectDoesNotExist as O, PermissionDenied as P, type ResolverMatch as Q, Resolver404 as R, type SettingsFactory as S, type ReverseOptions as T, UrlResolver as U, type ViewFunction as V, SecurityMiddleware as W, SuspiciousOperation as X, type UrlEntry as Y, type UrlInclude as Z, type UrlPatterns as _, type GhuriContext as a, ValidationError as a0, type ValidationMessages as a1, type ViewClassLike as a2, XFRAME_OPTIONS_EXEMPT_MARKER as a3, XFrameOptionsMiddleware as a4, apps as a5, cache as a6, caches as a7, cfCache as a8, converters as a9, createContext as aa, defineSettings as ab, ensureAppsReady as ac, getContext as ad, getEnv as ae, getResolver as af, getSettings as ag, include as ah, isAllowedHost as ai, isSettingsFactory as aj, kvCache as ak, kwargs as al, memoryCache as am, path as an, rePath as ao, registerConverter as ap, resolve as aq, resolverMatch as ar, reverse as as, runWithContext as at, setGlobalContext as au, setting as av, toHonoMiddleware as aw, tryGetContext as ax, urlpatterns as ay, validateHost as az, type ExecutionContextLike as b, GhuriError as c, type AppConfigClass as d, AppRegistry as e, AppRegistryNotReady as f, Cache as g, type CacheBackend as h, type CacheConfig as i, type CacheOptions as j, type CommandClassLike as k, CommonMiddleware as l, type CompiledRoute as m, type Converter as n, CorsMiddleware as o, type CorsOptions as p, CsrfMiddleware as q, type ErrorView as r, GZipMiddleware as s, Http404 as t, HttpError as u, type Includable as v, Middleware as w, type MiddlewareClass as x, type MiddlewareEntry as y, type MiddlewareLike as z };
596
+ export { type UrlPatternsLike as $, AppConfig as A, BadRequest as B, CSRF_EXEMPT_MARKER as C, DisallowedHost as D, type Env as E, MultipleObjectsReturned as F, type GhuriSettings as G, type HonoApp as H, ImproperlyConfigured as I, type PathOptions as J, type PathTarget as K, LookupError as L, MethodNotAllowed as M, NoReverseMatch as N, ObjectDoesNotExist as O, PermissionDenied as P, type ResolverMatch as Q, Resolver404 as R, type SettingsFactory as S, type ReverseOptions as T, UrlResolver as U, type ViewFunction as V, SecurityMiddleware as W, SuspiciousOperation as X, type UrlEntry as Y, type UrlInclude as Z, type UrlPatterns as _, type ExecutionContextLike as a, ValidationError as a0, type ValidationMessages as a1, type ViewClassLike as a2, XFRAME_OPTIONS_EXEMPT_MARKER as a3, XFrameOptionsMiddleware as a4, apps as a5, cache as a6, caches as a7, cfCache as a8, converters as a9, createContext as aa, defineSettings as ab, ensureAppsReady as ac, getContext as ad, getEnv as ae, getResolver as af, getSettings as ag, include as ah, isAllowedHost as ai, isSettingsFactory as aj, kvCache as ak, kwargs as al, memoryCache as am, path as an, rePath as ao, registerConverter as ap, resolve as aq, resolverMatch as ar, reverse as as, runWithContext as at, setGlobalContext as au, setting as av, toHonoMiddleware as aw, tryGetContext as ax, urlpatterns as ay, validateHost as az, type GhuriContext as b, GhuriError as c, type AppConfigClass as d, AppRegistry as e, AppRegistryNotReady as f, Cache as g, type CacheBackend as h, type CacheConfig as i, type CacheOptions as j, type CommandClassLike as k, CommonMiddleware as l, type CompiledRoute as m, type Converter as n, CorsMiddleware as o, type CorsOptions as p, CsrfMiddleware as q, type ErrorView as r, GZipMiddleware as s, Http404 as t, HttpError as u, type Includable as v, Middleware as w, type MiddlewareClass as x, type MiddlewareEntry as y, type MiddlewareLike as z };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { Context, Hono, HonoRequest } from 'hono';
2
- import { U as UrlResolver, G as GhuriSettings, a as GhuriContext, E as Env, b as ExecutionContextLike, S as SettingsFactory, A as AppConfig, c as GhuriError, P as PermissionDenied, V as ViewFunction } from './context-mL1PriMt.js';
3
- export { d as AppConfigClass, e as AppRegistry, f as AppRegistryNotReady, B as BadRequest, C as CSRF_EXEMPT_MARKER, g as Cache, h as CacheBackend, i as CacheConfig, j as CacheOptions, k as CommandClassLike, l as CommonMiddleware, m as CompiledRoute, n as Converter, o as CorsMiddleware, p as CorsOptions, q as CsrfMiddleware, D as DisallowedHost, r as ErrorView, s as GZipMiddleware, H as HonoApp, t as Http404, u as HttpError, I as ImproperlyConfigured, v as Includable, L as LookupError, M as MethodNotAllowed, w as Middleware, x as MiddlewareClass, y as MiddlewareEntry, z as MiddlewareLike, F as MultipleObjectsReturned, N as NoReverseMatch, O as ObjectDoesNotExist, J as PathOptions, K as PathTarget, R as Resolver404, Q as ResolverMatch, T as ReverseOptions, W as SecurityMiddleware, X as SuspiciousOperation, Y as UrlEntry, Z as UrlInclude, _ as UrlPatterns, $ as UrlPatternsLike, a0 as ValidationError, a1 as ValidationMessages, a2 as ViewClassLike, a3 as XFRAME_OPTIONS_EXEMPT_MARKER, a4 as XFrameOptionsMiddleware, a5 as apps, a6 as cache, a7 as caches, a8 as cfCache, a9 as converters, aa as createContext, ab as defineSettings, ac as ensureAppsReady, ad as getContext, ae as getEnv, af as getResolver, ag as getSettings, ah as include, ai as isAllowedHost, aj as isSettingsFactory, ak as kvCache, al as kwargs, am as memoryCache, an as path, ao as rePath, ap as registerConverter, aq as resolve, ar as resolverMatch, as as reverse, at as runWithContext, au as setGlobalContext, av as setting, aw as toHonoMiddleware, ax as tryGetContext, ay as urlpatterns, az as validateHost } from './context-mL1PriMt.js';
2
+ import { U as UrlResolver, G as GhuriSettings, E as Env, a as ExecutionContextLike, b as GhuriContext, S as SettingsFactory, A as AppConfig, c as GhuriError, P as PermissionDenied, V as ViewFunction } from './context-BM17cFwp.js';
3
+ export { d as AppConfigClass, e as AppRegistry, f as AppRegistryNotReady, B as BadRequest, C as CSRF_EXEMPT_MARKER, g as Cache, h as CacheBackend, i as CacheConfig, j as CacheOptions, k as CommandClassLike, l as CommonMiddleware, m as CompiledRoute, n as Converter, o as CorsMiddleware, p as CorsOptions, q as CsrfMiddleware, D as DisallowedHost, r as ErrorView, s as GZipMiddleware, H as HonoApp, t as Http404, u as HttpError, I as ImproperlyConfigured, v as Includable, L as LookupError, M as MethodNotAllowed, w as Middleware, x as MiddlewareClass, y as MiddlewareEntry, z as MiddlewareLike, F as MultipleObjectsReturned, N as NoReverseMatch, O as ObjectDoesNotExist, J as PathOptions, K as PathTarget, R as Resolver404, Q as ResolverMatch, T as ReverseOptions, W as SecurityMiddleware, X as SuspiciousOperation, Y as UrlEntry, Z as UrlInclude, _ as UrlPatterns, $ as UrlPatternsLike, a0 as ValidationError, a1 as ValidationMessages, a2 as ViewClassLike, a3 as XFRAME_OPTIONS_EXEMPT_MARKER, a4 as XFrameOptionsMiddleware, a5 as apps, a6 as cache, a7 as caches, a8 as cfCache, a9 as converters, aa as createContext, ab as defineSettings, ac as ensureAppsReady, ad as getContext, ae as getEnv, af as getResolver, ag as getSettings, ah as include, ai as isAllowedHost, aj as isSettingsFactory, ak as kvCache, al as kwargs, am as memoryCache, an as path, ao as rePath, ap as registerConverter, aq as resolve, ar as resolverMatch, as as reverse, at as runWithContext, au as setGlobalContext, av as setting, aw as toHonoMiddleware, ax as tryGetContext, ay as urlpatterns, az as validateHost } from './context-BM17cFwp.js';
4
+ import { S as ScheduledEventLike, M as MessageBatchLike } from './tasks-BEaLcIUR.js';
5
+ export { Q as QueueHandler, a as QueueMessageLike, b as ScheduledHandler, o as onQueue, c as onSchedule, t as taskHandlers } from './tasks-BEaLcIUR.js';
4
6
 
5
7
  type ExceptionHandler = (err: any, c: Context) => Response | undefined | null | void | Promise<Response | undefined | null | void>;
6
8
  type Matcher = ((err: unknown) => boolean) | (abstract new (...args: any[]) => unknown);
@@ -46,49 +48,6 @@ declare function appendSlashRedirect(c: Context, urlconf?: UrlResolver): Respons
46
48
  */
47
49
  declare function notFoundHandler(urlconf?: UrlResolver): (c: Context) => Response | Promise<Response>;
48
50
 
49
- /** Cloudflare `ScheduledController` (structural). */
50
- interface ScheduledEventLike {
51
- cron: string;
52
- scheduledTime: number;
53
- type?: string;
54
- noRetry?(): void;
55
- }
56
- /** Cloudflare Queues message (structural). */
57
- interface QueueMessageLike<T = unknown> {
58
- id: string;
59
- timestamp: Date;
60
- body: T;
61
- attempts?: number;
62
- ack(): void;
63
- retry(opts?: {
64
- delaySeconds?: number;
65
- }): void;
66
- }
67
- /** Cloudflare Queues `MessageBatch` (structural). */
68
- interface MessageBatchLike<T = unknown> {
69
- queue: string;
70
- messages: readonly QueueMessageLike<T>[];
71
- ackAll(): void;
72
- retryAll(opts?: {
73
- delaySeconds?: number;
74
- }): void;
75
- }
76
- type ScheduledHandler = (event: ScheduledEventLike, ctx: GhuriContext) => void | Promise<void>;
77
- type QueueHandler<T = any> = (batch: MessageBatchLike<T>, ctx: GhuriContext) => void | Promise<void>;
78
- /**
79
- * Run `handler` for Cron Triggers matching `cron` (the exact expression from wrangler.jsonc, or `'*'` for
80
- * every trigger). Typically called from an AppConfig's `ready()`. Returns an unregister function.
81
- */
82
- declare function onSchedule(cron: string, handler: ScheduledHandler): () => void;
83
- /** Consume batches of the queue named `queue` (or `'*'` for all queues). Returns an unregister function. */
84
- declare function onQueue<T = any>(queue: string, handler: QueueHandler<T>): () => void;
85
- /** Introspection / test helpers for the cron & queue handler registry. */
86
- declare const taskHandlers: {
87
- schedulesFor(cron: string): ScheduledHandler[];
88
- queuesFor(queue: string): QueueHandler[];
89
- clear(): void;
90
- };
91
-
92
51
  interface CreateAppOptions {
93
52
  /** Customize the Hono app. Called after MIDDLEWARE is installed and before the URL patterns. */
94
53
  hono?: (app: Hono) => void;
@@ -121,6 +80,41 @@ interface GhuriApp {
121
80
  */
122
81
  declare function createApp(settingsInput: SettingsFactory | ((env: Env) => GhuriSettings) | GhuriSettings, options?: CreateAppOptions): GhuriApp;
123
82
 
83
+ /**
84
+ * Context carriers: request-scoped state (the current tenant, a locale…) that work leaving the request has to take
85
+ * along. A package registers a carrier once; code that hands work to a queue, another service or a background
86
+ * task calls `captureContext()` and later `restoreContext(captured, fn)`, without importing those packages.
87
+ *
88
+ * ```ts
89
+ * const ctx = captureContext() // { tenant: '42' } inside a tenant's request, {} otherwise
90
+ * await queue.send({ ...job, context: ctx })
91
+ * // consumer
92
+ * await restoreContext(job.context, () => runJob(job))
93
+ * ```
94
+ */
95
+ /** Captured values, keyed by carrier name. JSON-safe, so they can go into a queue message or HTTP headers. */
96
+ type CapturedContext = Record<string, string>;
97
+ interface ContextCarrier {
98
+ /** Unique key in the captured object (`'tenant'`). */
99
+ name: string;
100
+ /** The value of the current context as a string, or `undefined` when there is nothing to carry. */
101
+ capture(): string | undefined;
102
+ /** Run `fn` with `value` (from `capture()`) active again. */
103
+ restore<R>(value: string, fn: () => Promise<R>): Promise<R>;
104
+ }
105
+ /** Register (or replace) a carrier. Packages call this at import time. */
106
+ declare function registerContextCarrier(carrier: ContextCarrier): void;
107
+ declare function unregisterContextCarrier(name: string): boolean;
108
+ /** Names of the registered carriers. */
109
+ declare function getContextCarriers(): string[];
110
+ /** The values every registered carrier has in the current context (carriers with nothing to carry are left out). */
111
+ declare function captureContext(): CapturedContext;
112
+ /**
113
+ * Run `fn` with a captured context active again. Keys without a registered carrier are ignored, and an empty or
114
+ * missing `captured` runs `fn` as is, so messages written before a carrier existed keep working.
115
+ */
116
+ declare function restoreContext<R>(captured: CapturedContext | null | undefined, fn: () => Promise<R> | R): Promise<R>;
117
+
124
118
  /** Check levels (same numbers as Django). */
125
119
  declare const CheckLevel: {
126
120
  readonly DEBUG: 10;
@@ -274,6 +268,19 @@ declare function bufferIO(): CommandIO & {
274
268
  /** Run a command programmatically (Django's call_command). */
275
269
  declare function callCommand(nameOrClass: string | CommandClass, args?: Record<string, unknown>, io?: CommandIO): Promise<void | number>;
276
270
 
271
+ /** A parsed cron expression. */
272
+ interface CronExpression {
273
+ readonly source: string;
274
+ /** Does the expression fire at this minute (UTC; seconds are ignored)? */
275
+ matches(date: Date): boolean;
276
+ /** The first minute strictly after `after` at which the expression fires (searches up to 5 years ahead). */
277
+ next(after?: Date): Date | null;
278
+ }
279
+ /** Parse a Cloudflare-style cron expression. Throws `ImproperlyConfigured` when it is invalid. */
280
+ declare function parseCron(source: string): CronExpression;
281
+ /** Is `source` a valid cron expression? */
282
+ declare function isValidCron(source: string): boolean;
283
+
277
284
  declare const CSRF_SECRET_LENGTH = 32;
278
285
  declare const CSRF_TOKEN_LENGTH: number;
279
286
  declare const SAFE_METHODS: Set<string>;
@@ -523,4 +530,4 @@ declare function redirect(c: Context, to: string | {
523
530
  status?: number;
524
531
  }): Response;
525
532
 
526
- export { AnonymousUser, AppConfig, ArgumentParser, type ArgumentSpec, type AsViewFunction, BaseCommand, SAFE_METHODS as CSRF_SAFE_METHODS, CSRF_SECRET_LENGTH, CSRF_TOKEN_LENGTH, type CheckContext, type CheckFunction, CheckLevel, CheckMessage, type CommandClass, CommandError, type CommandIO, CommandRegistry, type CommandStyle, type CreateAppOptions, CsrfFailure, Env, type ExceptionHandler, ExecutionContextLike, type GhuriApp, GhuriContext, GhuriError, GhuriSettings, type HttpMethodName, type MessageBatchLike, type OptionSpec, PermissionDenied, type QueueHandler, type QueueMessageLike, type Receiver, RedirectView, type RenderOptions, type Renderable, type RequestUser, type RunChecksOptions, type ScheduledEventLike, type ScheduledHandler, SettingsFactory, Signal, type Template, TemplateView, UrlResolver, type UserLoader, View, ViewFunction, anonymousUser, appendSlashRedirect, bufferIO, callCommand, checkCsrf, checks, cleansedSettings, commandRegistry, createApp, csrfExempt, enforceCsrf, ensureCsrfCookie, errorHandler, escapeHtml, generateCsrfSecret, getCsrfToken, getHost, getRemoteAddr, getUser, handleException, hostMatches, isCloudflareRequest, isCsrfExempt, isSecure, isXFrameOptionsExempt, json, loadUser, maskCsrfSecret, notFoundHandler, notFoundResponse, onQueue, onSchedule, plainStyle, receiver, redirect, registerExceptionHandler, registerUserLoader, render, requestFinished, requestStarted, resolveUrl, rotateCsrfToken, runChecks, setCsrfCookieIfNeeded, setRemoteAddr, setUser, settingsFor, statusText, taskHandlers, toJson, unmaskCsrfToken, wantsJson, xframeOptionsExempt };
533
+ export { AnonymousUser, AppConfig, ArgumentParser, type ArgumentSpec, type AsViewFunction, BaseCommand, SAFE_METHODS as CSRF_SAFE_METHODS, CSRF_SECRET_LENGTH, CSRF_TOKEN_LENGTH, type CapturedContext, type CheckContext, type CheckFunction, CheckLevel, CheckMessage, type CommandClass, CommandError, type CommandIO, CommandRegistry, type CommandStyle, type ContextCarrier, type CreateAppOptions, type CronExpression, CsrfFailure, Env, type ExceptionHandler, ExecutionContextLike, type GhuriApp, GhuriContext, GhuriError, GhuriSettings, type HttpMethodName, MessageBatchLike, type OptionSpec, PermissionDenied, type Receiver, RedirectView, type RenderOptions, type Renderable, type RequestUser, type RunChecksOptions, ScheduledEventLike, SettingsFactory, Signal, type Template, TemplateView, UrlResolver, type UserLoader, View, ViewFunction, anonymousUser, appendSlashRedirect, bufferIO, callCommand, captureContext, checkCsrf, checks, cleansedSettings, commandRegistry, createApp, csrfExempt, enforceCsrf, ensureCsrfCookie, errorHandler, escapeHtml, generateCsrfSecret, getContextCarriers, getCsrfToken, getHost, getRemoteAddr, getUser, handleException, hostMatches, isCloudflareRequest, isCsrfExempt, isSecure, isValidCron, isXFrameOptionsExempt, json, loadUser, maskCsrfSecret, notFoundHandler, notFoundResponse, parseCron, plainStyle, receiver, redirect, registerContextCarrier, registerExceptionHandler, registerUserLoader, render, requestFinished, requestStarted, resolveUrl, restoreContext, rotateCsrfToken, runChecks, setCsrfCookieIfNeeded, setRemoteAddr, setUser, settingsFor, statusText, toJson, unmaskCsrfToken, unregisterContextCarrier, wantsJson, xframeOptionsExempt };
package/dist/index.js CHANGED
@@ -1,30 +1,22 @@
1
1
  import {
2
2
  getRemoteAddr,
3
3
  isCloudflareRequest,
4
- setRemoteAddr
5
- } from "./chunk-YJ7DTR2K.js";
4
+ isValidCron,
5
+ onQueue,
6
+ onSchedule,
7
+ parseCron,
8
+ setRemoteAddr,
9
+ taskHandlers
10
+ } from "./chunk-V2EUF5IH.js";
6
11
  import {
7
- AppRegistryNotReady,
8
- BadRequest,
9
12
  CSRF_EXEMPT_MARKER,
10
13
  CSRF_SECRET_LENGTH,
11
14
  CSRF_TOKEN_LENGTH,
12
15
  CsrfFailure,
13
- DisallowedHost,
14
- GhuriError,
15
- Http404,
16
- HttpError,
17
- ImproperlyConfigured,
18
- MethodNotAllowed,
19
- MultipleObjectsReturned,
20
16
  NoReverseMatch,
21
- ObjectDoesNotExist,
22
- PermissionDenied,
23
17
  Resolver404,
24
18
  SAFE_METHODS,
25
- SuspiciousOperation,
26
19
  UrlResolver,
27
- ValidationError,
28
20
  XFRAME_OPTIONS_EXEMPT_MARKER,
29
21
  appendSlashRedirect,
30
22
  checkCsrf,
@@ -69,7 +61,22 @@ import {
69
61
  urlpatterns,
70
62
  viewHasMarker,
71
63
  wantsJson
72
- } from "./chunk-54KUWCC4.js";
64
+ } from "./chunk-J3ORY46U.js";
65
+ import {
66
+ AppRegistryNotReady,
67
+ BadRequest,
68
+ DisallowedHost,
69
+ GhuriError,
70
+ Http404,
71
+ HttpError,
72
+ ImproperlyConfigured,
73
+ MethodNotAllowed,
74
+ MultipleObjectsReturned,
75
+ ObjectDoesNotExist,
76
+ PermissionDenied,
77
+ SuspiciousOperation,
78
+ ValidationError
79
+ } from "./chunk-VBA235HC.js";
73
80
 
74
81
  // src/app.ts
75
82
  import { Hono } from "hono";
@@ -142,6 +149,8 @@ var AppConfig = class {
142
149
  migrations;
143
150
  /** `import * as admin from './admin'` — importing the module registers ModelAdmins. */
144
151
  admin;
152
+ /** `import * as tasks from './tasks'` — background tasks (`@ghuri/tasks`), named `<app label>.<export name>`. */
153
+ tasks;
145
154
  /** Agents, signals or any other module the app wants loaded at startup. */
146
155
  modules;
147
156
  commands;
@@ -727,36 +736,6 @@ function receiver(signal, opts = {}) {
727
736
  var requestStarted = new Signal("requestStarted");
728
737
  var requestFinished = new Signal("requestFinished");
729
738
 
730
- // src/tasks.ts
731
- var KEY4 = /* @__PURE__ */ Symbol.for("ghuri.core.tasks");
732
- var registry = globalThis[KEY4] ??= { schedules: [], queues: [] };
733
- function onSchedule(cron, handler) {
734
- const entry = { cron, handler };
735
- registry.schedules.push(entry);
736
- return () => {
737
- registry.schedules = registry.schedules.filter((e) => e !== entry);
738
- };
739
- }
740
- function onQueue(queue, handler) {
741
- const entry = { queue, handler };
742
- registry.queues.push(entry);
743
- return () => {
744
- registry.queues = registry.queues.filter((e) => e !== entry);
745
- };
746
- }
747
- var taskHandlers = {
748
- schedulesFor(cron) {
749
- return registry.schedules.filter((e) => e.cron === cron || e.cron === "*").map((e) => e.handler);
750
- },
751
- queuesFor(queue) {
752
- return registry.queues.filter((e) => e.queue === queue || e.queue === "*").map((e) => e.handler);
753
- },
754
- clear() {
755
- registry.schedules = [];
756
- registry.queues = [];
757
- }
758
- };
759
-
760
739
  // src/app.ts
761
740
  var EMPTY_ENV = Object.freeze({});
762
741
  function toFactory(settings2) {
@@ -1156,6 +1135,38 @@ var cache = {
1156
1135
  clear: () => caches.get().clear()
1157
1136
  };
1158
1137
 
1138
+ // src/carriers.ts
1139
+ var KEY4 = /* @__PURE__ */ Symbol.for("ghuri.core.contextCarriers");
1140
+ var g = globalThis;
1141
+ var carriers = g[KEY4] ??= /* @__PURE__ */ new Map();
1142
+ function registerContextCarrier(carrier) {
1143
+ carriers.set(carrier.name, carrier);
1144
+ }
1145
+ function unregisterContextCarrier(name) {
1146
+ return carriers.delete(name);
1147
+ }
1148
+ function getContextCarriers() {
1149
+ return [...carriers.keys()];
1150
+ }
1151
+ function captureContext() {
1152
+ const out = {};
1153
+ for (const c of carriers.values()) {
1154
+ const v = c.capture();
1155
+ if (typeof v === "string" && v !== "") out[c.name] = v;
1156
+ }
1157
+ return out;
1158
+ }
1159
+ async function restoreContext(captured, fn) {
1160
+ const entries = Object.entries(captured ?? {}).filter(
1161
+ ([name, v]) => carriers.has(name) && typeof v === "string" && v !== ""
1162
+ );
1163
+ const run = entries.reduceRight(
1164
+ (next, [name, value]) => () => carriers.get(name).restore(value, next),
1165
+ async () => fn()
1166
+ );
1167
+ return run();
1168
+ }
1169
+
1159
1170
  // src/user.ts
1160
1171
  var AnonymousUser = class {
1161
1172
  pk = null;
@@ -1441,6 +1452,7 @@ export {
1441
1452
  cache,
1442
1453
  caches,
1443
1454
  callCommand,
1455
+ captureContext,
1444
1456
  cfCache,
1445
1457
  checkCsrf,
1446
1458
  checks,
@@ -1458,6 +1470,7 @@ export {
1458
1470
  escapeHtml,
1459
1471
  generateCsrfSecret,
1460
1472
  getContext,
1473
+ getContextCarriers,
1461
1474
  getCsrfToken,
1462
1475
  getEnv,
1463
1476
  getHost,
@@ -1473,6 +1486,7 @@ export {
1473
1486
  isCsrfExempt,
1474
1487
  isSecure,
1475
1488
  isSettingsFactory,
1489
+ isValidCron,
1476
1490
  isXFrameOptionsExempt,
1477
1491
  json,
1478
1492
  kvCache,
@@ -1484,11 +1498,13 @@ export {
1484
1498
  notFoundResponse,
1485
1499
  onQueue,
1486
1500
  onSchedule,
1501
+ parseCron,
1487
1502
  path,
1488
1503
  plainStyle,
1489
1504
  rePath,
1490
1505
  receiver,
1491
1506
  redirect,
1507
+ registerContextCarrier,
1492
1508
  registerConverter,
1493
1509
  registerExceptionHandler,
1494
1510
  registerUserLoader,
@@ -1498,6 +1514,7 @@ export {
1498
1514
  resolve,
1499
1515
  resolveUrl,
1500
1516
  resolverMatch,
1517
+ restoreContext,
1501
1518
  reverse,
1502
1519
  rotateCsrfToken,
1503
1520
  runChecks,
@@ -1514,6 +1531,7 @@ export {
1514
1531
  toJson,
1515
1532
  tryGetContext,
1516
1533
  unmaskCsrfToken,
1534
+ unregisterContextCarrier,
1517
1535
  urlpatterns,
1518
1536
  validateHost,
1519
1537
  wantsJson,