@guren/server 2.20.0 → 2.22.0

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.
Files changed (36) hide show
  1. package/dist/{Logger-DFifRAtc.js → Logger-DWXdtLSJ.js} +62 -2
  2. package/dist/agent/approval-status.d.ts +1 -1
  3. package/dist/agent/approval.d.ts +2 -2
  4. package/dist/agent/audit-emitter.d.ts +11 -1
  5. package/dist/agent/gate.d.ts +10 -8
  6. package/dist/agent/meta-tools.d.ts +13 -5
  7. package/dist/agent/pipeline.d.ts +10 -9
  8. package/dist/auth/index.js +1 -1
  9. package/dist/auth/password/DefaultHasher.d.ts +1 -0
  10. package/dist/{auth-BXcHQwHf.js → auth-CjE2oO50.js} +21 -2
  11. package/dist/cache/index.js +1 -1
  12. package/dist/{cache-DUhlolkJ.js → cache-DikxP7Bk.js} +2 -2
  13. package/dist/container/bindings.d.ts +4 -4
  14. package/dist/http/Application.d.ts +15 -0
  15. package/dist/http/middleware/index.d.ts +1 -1
  16. package/dist/http/middleware/session-manager.d.ts +7 -0
  17. package/dist/i18n/index.js +1 -1
  18. package/dist/index.d.ts +5 -3
  19. package/dist/index.js +628 -413
  20. package/dist/lambda/index.js +1 -1
  21. package/dist/logging/index.js +2 -2
  22. package/dist/{logging-DXmqqUl4.js → logging-Dmzdb6mL.js} +1 -1
  23. package/dist/mvc/Router.d.ts +18 -15
  24. package/dist/mvc/inertia/InertiaEngine.d.ts +6 -0
  25. package/dist/mvc/prototype.d.ts +105 -0
  26. package/dist/runtime/index.js +2 -2
  27. package/dist/storage/index.js +1 -1
  28. package/dist/support/keep-alive.d.ts +26 -0
  29. package/dist/support/request-deferrer.d.ts +10 -0
  30. package/dist/vite/index.js +147 -0
  31. package/dist/vite/plugin.d.ts +39 -0
  32. package/dist/{vite-manifest-BZQ-75hf.js → vite-manifest-D295_7-_.js} +1 -1
  33. package/package.json +5 -4
  34. package/dist/{DocsViewerServiceProvider-D2cuVgtN.js → DocsViewerServiceProvider-DWnlXx_y.js} +1 -1
  35. package/dist/{i18n-Cg1aajRP.js → i18n-BZ2VrSud.js} +1 -1
  36. package/dist/{storage-BB59f07j.js → storage-D_yNe54O.js} +1 -1
package/dist/index.js CHANGED
@@ -5,20 +5,20 @@ import { _ as setGate, a as withAuthorization, b as mergeCapabilities, c as Gate
5
5
  import { a as mapToolResponse, i as describeBuildFailure, n as advertisesStructuredOutput, r as buildToolRequest, s as AGENT_PREFLIGHT_VERDICT_HEADER, t as PREFLIGHT_ARGUMENT } from "./dispatch-BAwzftws.js";
6
6
  import { t as trimSlashes } from "./trim-slashes-BLY9hKAa.js";
7
7
  import { PATH_PARAM_PATTERN, extractPathParamNames } from "./internal/route-path.js";
8
- import { a as getRegisteredJobs, c as setQueueDriver, d as getContainer, f as resolve, i as getQueueDriver, l as Container, n as clearJobRegistry, o as registerJob, p as setContainer, r as getJob, s as resolveJobName, t as Job, u as createContainer } from "./Job-CvDwk2Gj.js";
9
- import { n as ProviderManager, r as ServiceProvider } from "./loopback-guard-DT9gHF0F.js";
10
8
  import { a as generateAppKey, c as parseAppKey, i as encodeDerivedKey, l as parsePreviousAppKeys, n as deriveAppKey, o as getAppKeyringFromEnv, r as deriveAppKeyring, s as normalizeAppKey, t as MessageSigner } from "./MessageSigner-Bd25ZJAV.js";
11
9
  import { n as detectServerlessRuntime, t as SERVERLESS_RUNTIME_LABELS } from "./serverless-D96rJb6x.js";
12
- import { A as verifyOAuthState, B as getApiToken, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, F as TokenGuard, G as readBearerToken, H as getUserApiTokens, I as API_TOKEN_KEY, J as tokenCan, K as revokeAllApiTokens, L as MemoryApiTokenStore, M as isAppRelativePath, N as normalizeRedirectTarget, O as parseOAuthRedirectUrl, P as AuthManager, Q as SessionGuard, R as createApiToken, S as createGitHubOAuthProviderConfig, T as createOAuthState, U as hasBearerHeader, V as getApiTokenOrFail, W as parseApiToken, X as tokenCanAny, Y as tokenCanAll, Z as verifyApiToken, _ as OAUTH_SESSION_BINDING_KEY, _t as getSessionFromContext, a as isEmailVerified, b as buildOAuthRedirectUrl, c as verifyEmailToken, ct as NodeHasher, d as completePasswordReset, dt as BaseUserProvider, f as createPasswordResetToken, ft as installAgentPrincipal, g as MemoryOAuthStateStore, gt as defaultCookieSecure, h as AuthenticatableModel, ht as createSessionMiddleware, i as createEmailVerificationToken, j as hostMatchesAllowlist, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, lt as ScryptHasher, m as verifyPasswordResetToken, mt as MemorySessionStore, n as buildVerificationUrl, o as parseVerificationUrl, ot as ModelUserProvider, p as parsePasswordResetUrl, pt as readAgentPrincipal, q as revokeApiToken, r as completeEmailVerification, s as requireVerifiedEmail, st as DefaultHasher, t as MemoryEmailVerificationStore, u as buildPasswordResetUrl, ut as AuthenticationException, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createBearerTokenMiddleware } from "./auth-BXcHQwHf.js";
10
+ import { A as verifyOAuthState, B as getApiToken, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, F as TokenGuard, G as readBearerToken, H as getUserApiTokens, I as API_TOKEN_KEY, J as tokenCan, K as revokeAllApiTokens, L as MemoryApiTokenStore, M as isAppRelativePath, N as normalizeRedirectTarget, O as parseOAuthRedirectUrl, P as AuthManager, Q as SessionGuard, R as createApiToken, S as createGitHubOAuthProviderConfig, T as createOAuthState, U as hasBearerHeader, V as getApiTokenOrFail, W as parseApiToken, X as tokenCanAny, Y as tokenCanAll, Z as verifyApiToken, _ as OAUTH_SESSION_BINDING_KEY, _t as getSessionFromContext, a as isEmailVerified, b as buildOAuthRedirectUrl, c as verifyEmailToken, ct as NodeHasher, d as completePasswordReset, dt as BaseUserProvider, f as createPasswordResetToken, ft as installAgentPrincipal, g as MemoryOAuthStateStore, gt as defaultCookieSecure, h as AuthenticatableModel, ht as createSessionMiddleware, i as createEmailVerificationToken, j as hostMatchesAllowlist, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, lt as ScryptHasher, m as verifyPasswordResetToken, mt as MemorySessionStore, n as buildVerificationUrl, o as parseVerificationUrl, ot as ModelUserProvider, p as parsePasswordResetUrl, pt as readAgentPrincipal, q as revokeApiToken, r as completeEmailVerification, s as requireVerifiedEmail, st as DefaultHasher, t as MemoryEmailVerificationStore, u as buildPasswordResetUrl, ut as AuthenticationException, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createBearerTokenMiddleware } from "./auth-CjE2oO50.js";
11
+ import { _ as parseImportMap, c as isViteProduction, d as startViteDevServer, g as DEFAULT_DEV_STYLES_ENTRY, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, m as isWildcardHost, n as INJECTED_CLIENT_MANIFEST_SOURCE, o as getManifestFile, p as formatHostPort, r as PUBLIC_ASSETS_URL_PREFIX, s as injectedClientManifest, u as normalizeDevServerUrl } from "./vite-manifest-D295_7-_.js";
12
+ import { a as getRegisteredJobs, c as setQueueDriver, d as getContainer, f as resolve, i as getQueueDriver, l as Container, n as clearJobRegistry, o as registerJob, p as setContainer, r as getJob, s as resolveJobName, t as Job, u as createContainer } from "./Job-CvDwk2Gj.js";
13
+ import { n as ProviderManager, r as ServiceProvider } from "./loopback-guard-DT9gHF0F.js";
13
14
  import { a as md5, c as sha256, d as verifyPassword, i as hmac, l as sha512, n as hash, o as needsRehash, r as hashPassword, s as secureCompare, t as check, u as verifyHmac } from "./Hash-D2DFd8xX.js";
14
15
  import { n as getAuthContext, t as AUTH_CONTEXT_KEY } from "./context-CXk_umpT.js";
15
- import { n as filterSensitiveData, t as Logger } from "./Logger-DFifRAtc.js";
16
- import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, s as resolveLazyRedisClient, t as CacheManager } from "./cache-DUhlolkJ.js";
16
+ import { a as runInRequestScope, i as keepAlive, n as filterSensitiveData, t as Logger } from "./Logger-DWXdtLSJ.js";
17
+ import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, s as resolveLazyRedisClient, t as CacheManager } from "./cache-DikxP7Bk.js";
17
18
  import { n as createRedisClient, r as RedisSessionStore } from "./client-C5Wj9P9o.js";
18
19
  import { r as isMcpEndpointEnabled } from "./endpoint-Dsw3Acvq.js";
19
20
  import { n as isHotReloadRuntime, r as matchingOpenParen, t as claimHotDisposable } from "./hot-disposables-B5BXqaIH.js";
20
- import { a as setI18n, c as tryGetI18n, d as getPluralizationRule, f as pluralizationRules, i as getI18n, l as JsonLoader, n as I18nManager, o as t, p as selectPluralForm, r as createI18n, s as tc, t as MemoryLoader, u as Translator } from "./i18n-Cg1aajRP.js";
21
- import { _ as parseImportMap, c as isViteProduction, d as startViteDevServer, g as DEFAULT_DEV_STYLES_ENTRY, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, m as isWildcardHost, n as INJECTED_CLIENT_MANIFEST_SOURCE, o as getManifestFile, p as formatHostPort, r as PUBLIC_ASSETS_URL_PREFIX, s as injectedClientManifest, u as normalizeDevServerUrl } from "./vite-manifest-BZQ-75hf.js";
21
+ import { a as setI18n, c as tryGetI18n, d as getPluralizationRule, f as pluralizationRules, i as getI18n, l as JsonLoader, n as I18nManager, o as t, p as selectPluralForm, r as createI18n, s as tc, t as MemoryLoader, u as Translator } from "./i18n-BZ2VrSud.js";
22
22
  import { r as isDocsViewerEnabled } from "./endpoint-BXipU2Jj.js";
23
23
  import { t as jsx_runtime_exports } from "./jsx-runtime.js";
24
24
  import { readObjectSchema, toJsonSchema } from "./internal/zod-json-schema.js";
@@ -26,21 +26,21 @@ import { a as RequestFinished, c as UserLoggedOut, d as createEventManager, f as
26
26
  import { a as NotificationManager, c as setNotificationManager, d as getNotification, f as registerNotification, i as MailChannel, l as resolveNotifiableType, n as SlackChannel, o as createNotificationManager, p as Notification, r as DatabaseChannel, s as getNotificationManager, t as MemoryChannel, u as clearNotificationRegistry } from "./notifications-D0VXkFLF.js";
27
27
  import { a as processJob, c as RedisDriver$1, i as Worker, l as SyncDriver, n as createQueueManager, o as SqsDriver, r as FailedJobReporter, s as createSqsAdapter, t as QueueManager, u as MemoryDriver$1 } from "./queue-zPPYZdif.js";
28
28
  import { a as MailManager, c as MemoryTransport, i as setMailManager, l as ResendTransport, n as getMailManager, o as createMailManager, r as mail, s as LogTransport, t as Mail, u as SmtpTransport } from "./mail-9CrvJyBZ.js";
29
- import { a as DailyFileChannel, c as matchDailyFileDate, d as LOG_LEVEL_PRIORITY, i as setLogManager, l as FileChannel, n as createLogManager, o as dailyFileDateStamp, r as getLogManager, s as dailyFilePath, t as LogManager, u as ConsoleChannel } from "./logging-DXmqqUl4.js";
29
+ import { a as DailyFileChannel, c as matchDailyFileDate, d as LOG_LEVEL_PRIORITY, i as setLogManager, l as FileChannel, n as createLogManager, o as dailyFileDateStamp, r as getLogManager, s as dailyFilePath, t as LogManager, u as ConsoleChannel } from "./logging-Dmzdb6mL.js";
30
30
  import { a as setBroadcastManager, c as PresenceChannel, i as getBroadcastManager, l as PrivateChannel, n as BroadcastManager, o as RedisDriver, r as createBroadcastManager, s as MemoryDriver, t as createTypedBroadcaster, u as Channel } from "./broadcasting-B5RzB0A2.js";
31
31
  import { a as random, c as randomHex, d as sample, f as shuffle, i as pick, l as randomInt, m as uuid, n as generatePassword, o as randomBase64, p as urlSafeToken, r as generateSlug, s as randomBase64Url, t as generateOtp, u as randomString } from "./Random-S0OvCuR8.js";
32
32
  import { a as decrypt, c as getEncrypter, i as createEncrypter, l as setEncrypter, n as verifySignedUrl, o as encrypt, r as Encrypter, s as generateKey, t as signUrl } from "./encryption-uwP3Di4D.js";
33
- import { a as LocalDriver, i as S3Driver, n as createStorageManager, o as warnOnce, r as MemoryDriver$2, t as StorageManager } from "./storage-BB59f07j.js";
33
+ import { a as LocalDriver, i as S3Driver, n as createStorageManager, o as warnOnce, r as MemoryDriver$2, t as StorageManager } from "./storage-D_yNe54O.js";
34
34
  import { a as CacheCheck, c as HealthManager, i as StorageCheck, l as createHealthManager, n as customCheck, o as RedisCheck, r as MemoryCheck, s as DatabaseCheck, t as CustomCheck, u as HealthCheck } from "./health-DQSvUplL.js";
35
35
  import { a as ScheduledTask, c as isDue, d as parseCron, f as toTimezone, i as Schedule, l as isDueInTimezone, n as createScheduler, o as getNextOccurrence, r as PendingSchedule, s as getNextOccurrences, t as Scheduler, u as matchesCron } from "./scheduling-C6tcOtUl.js";
36
36
  import { Hono } from "hono";
37
37
  import { deleteCookie, getCookie } from "hono/cookie";
38
38
  import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
39
+ import { isAbsolute, join, resolve as resolve$1 } from "node:path";
40
+ import { pathToFileURL } from "node:url";
39
41
  import { cors } from "hono/cors";
40
42
  import { createMiddleware } from "hono/factory";
41
43
  import { parseAccept } from "hono/utils/accept";
42
- import { isAbsolute, join, resolve as resolve$1 } from "node:path";
43
- import { pathToFileURL } from "node:url";
44
44
  import { serialize } from "hono/utils/cookie";
45
45
  import { existsSync } from "node:fs";
46
46
  import * as readline from "readline";
@@ -106,6 +106,516 @@ function mountRoute(app, method, path, ...handlers) {
106
106
  app.on(method, path, ...handlers);
107
107
  }
108
108
  //#endregion
109
+ //#region src/mvc/inertia/InertiaEngine.ts
110
+ ensureErrorStackTracePolyfill();
111
+ let documentOptions;
112
+ /**
113
+ * Register app-wide document defaults for server-rendered Inertia responses;
114
+ * call it at module scope in the app entry so every runtime picks it up.
115
+ * Process-wide, not request-scoped: calling it mid-flight leaks the policy into
116
+ * in-flight requests — use the {@link InertiaOptions} fields per response.
117
+ * Values are emitted verbatim, so never pass user input. `undefined` clears.
118
+ */
119
+ function setInertiaDocument(options) {
120
+ documentOptions = options;
121
+ }
122
+ let defaultSsrRenderer;
123
+ /**
124
+ * Register a process-wide default SSR renderer, for adapters whose bundler
125
+ * cannot resolve a runtime path (Workers has no filesystem for
126
+ * `GUREN_INERTIA_SSR_ENTRY`'s dynamic import). Per-call `ssr.render` still
127
+ * wins; `undefined` clears (test isolation).
128
+ */
129
+ function setInertiaSsrRenderer(renderer) {
130
+ defaultSsrRenderer = renderer;
131
+ }
132
+ const DEFAULT_TITLE = "Guren";
133
+ const DEV_FALLBACK_IMPORT_MAP = {
134
+ react: "https://esm.sh/react@19.0.0?dev",
135
+ "react/jsx-runtime": "https://esm.sh/react@19.0.0/jsx-runtime?dev",
136
+ "react/jsx-dev-runtime": "https://esm.sh/react@19.0.0/jsx-dev-runtime?dev",
137
+ "react-dom/client": "https://esm.sh/react-dom@19.0.0/client?dev",
138
+ "@guren/inertia-client": "/vendor/inertia-client.tsx",
139
+ "@inertiajs/react": "https://esm.sh/@inertiajs/react@2.2.15?dev&external=react,react-dom/client"
140
+ };
141
+ async function inertia(component, props, options = {}) {
142
+ const resolvedVersion = options.version ?? process.env.GUREN_INERTIA_VERSION ?? void 0;
143
+ const page = {
144
+ component,
145
+ props,
146
+ url: options.url ?? inertiaPageUrl(options.request) ?? "",
147
+ version: resolvedVersion
148
+ };
149
+ const request = options.request;
150
+ const isInertiaVisit = Boolean(request?.headers.get("X-Inertia"));
151
+ const prefersJson = request ? acceptsJson(request) : false;
152
+ const versionHeader = resolvedVersion ? { "X-Inertia-Version": resolvedVersion } : {};
153
+ if (request && resolvedVersion && isInertiaVisit && request.method === "GET") {
154
+ if (request.headers.get("X-Inertia-Version") !== resolvedVersion) return new Response(null, {
155
+ status: 409,
156
+ headers: {
157
+ "X-Inertia-Location": options.url ?? request.url,
158
+ Vary: "Accept"
159
+ }
160
+ });
161
+ }
162
+ if (isInertiaVisit || prefersJson) return new Response(serializePage(page), {
163
+ status: options.status ?? 200,
164
+ headers: {
165
+ "Content-Type": "application/json; charset=utf-8",
166
+ "X-Inertia": "true",
167
+ Vary: "Accept",
168
+ ...versionHeader,
169
+ ...options.headers
170
+ }
171
+ });
172
+ const html = await renderDocument$1(page, options);
173
+ return new Response(html, {
174
+ status: options.status ?? 200,
175
+ headers: {
176
+ "Content-Type": "text/html; charset=utf-8",
177
+ "X-Inertia": "true",
178
+ Vary: "Accept",
179
+ ...versionHeader,
180
+ ...options.headers
181
+ }
182
+ });
183
+ }
184
+ /**
185
+ * The Inertia protocol's page `url` is the request path plus query string, kept
186
+ * relative. Derived from the request when the caller does not override it.
187
+ */
188
+ function inertiaPageUrl(request) {
189
+ if (!request) return;
190
+ const { pathname, search } = new URL(request.url);
191
+ return `${pathname}${search}`;
192
+ }
193
+ async function renderDocument$1(page, options) {
194
+ const defaultEntry = process.env.GUREN_INERTIA_ENTRY || "/resources/js/app.tsx";
195
+ const entry = options.entry ?? defaultEntry;
196
+ const title = escapeHtml$2(options.title ?? DEFAULT_TITLE);
197
+ const isProduction = process.env.NODE_ENV === "production";
198
+ const configuredStyles = options.styles ?? parseStylesEnv(process.env.GUREN_INERTIA_STYLES);
199
+ const styles = !isProduction && options.styles === void 0 && isDevServerEntry(entry) ? configuredStyles.filter((href) => href !== DEFAULT_DEV_STYLES_ENTRY) : configuredStyles;
200
+ const envImportMap = parseImportMap(process.env.GUREN_INERTIA_IMPORT_MAP, { context: "GUREN_INERTIA_IMPORT_MAP" });
201
+ const importMapEntries = {
202
+ ...isProduction ? {} : DEV_FALLBACK_IMPORT_MAP,
203
+ ...envImportMap,
204
+ ...options.importMap
205
+ };
206
+ const importMap = JSON.stringify({ imports: importMapEntries }, null, 2);
207
+ const stylesheetLinks = renderStyles(styles);
208
+ const criticalCss = resolveDocumentValue("criticalCss", options, page.component);
209
+ const prepaintScript = resolveDocumentValue("prepaintScript", options, page.component);
210
+ const headMarkup = resolveDocumentValue("head", options, page.component);
211
+ const ssrResult = await tryRenderSsr(page, options);
212
+ const headElements = (ssrResult?.head ?? []).map(normalizeHeadElement);
213
+ const hasCustomTitle = headElements.some((element) => /<title\b[^>]*>/iu.test(element));
214
+ const appMarkup = ssrResult === void 0 ? `${pagePayloadElement(page)}<div id="app"></div>` : ssrResult.pageEmbedded ? ssrResult.body : `${ssrResult.body}${pagePayloadElement(page)}`;
215
+ const headSegments = [
216
+ "<meta charset=\"utf-8\" />",
217
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />",
218
+ hasCustomTitle ? "" : `<title>${title}</title>`,
219
+ headMarkup ?? "",
220
+ criticalCss ? `<style id="guren-critical">${criticalCss}</style>` : "",
221
+ prepaintScript ? `<script>${prepaintScript}<\/script>` : "",
222
+ stylesheetLinks,
223
+ ...headElements,
224
+ Object.keys(importMapEntries).length > 0 ? `<script type="importmap">${importMap}<\/script>` : ""
225
+ ].filter((segment) => segment && segment.length > 0);
226
+ const bodyClass = resolveDocumentValue("bodyClass", options, page.component);
227
+ const bodyAttributes = bodyClass ? ` class="${escapeAttribute(bodyClass)}"` : "";
228
+ return `<!DOCTYPE html>
229
+ <html lang="${escapeAttribute(options.lang ?? "en")}">
230
+ <head>
231
+ ${headSegments.join("\n ")}
232
+ </head>
233
+ <body${bodyAttributes}>
234
+ ${appMarkup}${PAGE_GLOBAL_FROM_ELEMENT}
235
+ <script type="module" src="${entry}"><\/script>
236
+ </body>
237
+ </html>`;
238
+ }
239
+ function pagePayloadElement(page) {
240
+ return `<script data-page="app" type="application/json">${serializePage(page)}<\/script>`;
241
+ }
242
+ /**
243
+ * `window.__INERTIA_PAGE__` for readers other than the client. Same selector
244
+ * and guards as the client's `getInitialPage` (@guren/inertia-client), so a
245
+ * container carrying a non-payload `data-page` is ignored rather than mounted.
246
+ * A classic inline script, so it has run before the module entry does.
247
+ */
248
+ const PAGE_GLOBAL_FROM_ELEMENT = "<script>try{var e=document.querySelector('script[data-page=\"app\"][type=\"application/json\"]')||document.getElementById(\"app\"),p=JSON.parse(e.tagName===\"SCRIPT\"?e.textContent:e.getAttribute(\"data-page\"));if(p&&p.component)window.__INERTIA_PAGE__=p}catch(_){}<\/script>";
249
+ async function tryRenderSsr(page, options) {
250
+ const ssrOptions = options.ssr;
251
+ if (ssrOptions?.enabled === false) return;
252
+ const manifest = (ssrOptions?.manifest ?? process.env.GUREN_INERTIA_SSR_MANIFEST)?.trim() || void 0;
253
+ const renderer = ssrOptions?.render ?? defaultSsrRenderer ?? await loadSsrRenderer(ssrOptions?.entry ?? process.env.GUREN_INERTIA_SSR_ENTRY);
254
+ if (!renderer) return;
255
+ try {
256
+ const result = await renderer({
257
+ page,
258
+ request: options.request,
259
+ manifest
260
+ });
261
+ if (!result || typeof result.body !== "string") return;
262
+ return {
263
+ body: result.body,
264
+ head: Array.isArray(result.head) ? result.head : [],
265
+ pageEmbedded: result.pageEmbedded === true
266
+ };
267
+ } catch (error) {
268
+ console.error("Inertia SSR renderer failed; falling back to client rendering.", error);
269
+ return;
270
+ }
271
+ }
272
+ async function loadSsrRenderer(entry) {
273
+ const specifier = entry?.trim();
274
+ if (!specifier) return;
275
+ const normalized = normalizeSsrSpecifier(specifier);
276
+ try {
277
+ const renderCandidate = extractSsrRenderer(await import(normalized));
278
+ if (!renderCandidate) {
279
+ console.warn(`Inertia SSR entry "${specifier}" does not export a renderer. Expected a default export or a named "render" function.`);
280
+ return;
281
+ }
282
+ return renderCandidate;
283
+ } catch (error) {
284
+ console.error(`Failed to import Inertia SSR entry "${specifier}".`, error);
285
+ return;
286
+ }
287
+ }
288
+ function extractSsrRenderer(module) {
289
+ if (!module || typeof module !== "object") return;
290
+ const candidate = typeof module.render === "function" ? module.render : typeof module.default === "function" ? module.default : void 0;
291
+ if (!candidate) return;
292
+ return (context) => Promise.resolve(candidate(context));
293
+ }
294
+ function normalizeSsrSpecifier(specifier) {
295
+ if (specifier.startsWith("file://") || isUrlLike(specifier)) return specifier;
296
+ if (specifier.startsWith("./") || specifier.startsWith("../")) {
297
+ const absolute = resolve$1(process.cwd(), specifier);
298
+ return pathToFileURL(absolute).href;
299
+ }
300
+ if (isAbsolute(specifier)) return pathToFileURL(specifier).href;
301
+ return specifier;
302
+ }
303
+ function isUrlLike(specifier) {
304
+ return /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(specifier);
305
+ }
306
+ /**
307
+ * An absolute http(s) entry means an asset dev server (Vite) is serving the
308
+ * module graph; a same-origin path means source files are served directly,
309
+ * where the raw stylesheet link is the only styling.
310
+ */
311
+ function isDevServerEntry(entry) {
312
+ return /^https?:\/\//iu.test(entry);
313
+ }
314
+ function renderStyles(styles) {
315
+ if (!styles.length) return "";
316
+ return styles.map((href) => `<link rel="stylesheet" href="${escapeAttribute(href)}" />`).join("\n ");
317
+ }
318
+ function normalizeHeadElement(element) {
319
+ return (typeof element === "string" ? element : String(element ?? "")).replace(/href="\/(?!public\/)([^"?]+\.(?:js|css))(\?[^"']*)?"/g, (_match, file, query = "") => `href="/public/assets/${file}${query}"`);
320
+ }
321
+ /** One document field: per-response override, then app-wide default, then "". */
322
+ function resolveDocumentValue(key, options, componentName) {
323
+ const override = options[key];
324
+ if (override !== void 0) return override;
325
+ const value = documentOptions?.[key];
326
+ return (typeof value === "function" ? value({ component: componentName }) : value) ?? "";
327
+ }
328
+ function serializePage(page) {
329
+ return JSON.stringify(page).replace(/[<\u2028\u2029]/gu, (char) => {
330
+ switch (char) {
331
+ case "<": return "\\u003c";
332
+ case "\u2028": return "\\u2028";
333
+ case "\u2029": return "\\u2029";
334
+ default: return char;
335
+ }
336
+ });
337
+ }
338
+ function acceptsJson(request) {
339
+ const accept = request.headers.get("accept")?.toLowerCase() ?? "";
340
+ if (!accept || accept === "*/*") return false;
341
+ if (accept.includes("text/html")) return false;
342
+ return accept.includes("application/json") || accept.includes("json");
343
+ }
344
+ function escapeHtml$2(value) {
345
+ return value.replace(/[&<>"']/gu, (char) => {
346
+ switch (char) {
347
+ case "&": return "&amp;";
348
+ case "<": return "&lt;";
349
+ case ">": return "&gt;";
350
+ case "\"": return "&quot;";
351
+ case "'": return "&#39;";
352
+ default: return char;
353
+ }
354
+ });
355
+ }
356
+ function escapeAttribute(value) {
357
+ return value.replace(/[&"]/gu, (char) => {
358
+ if (char === "&") return "&amp;";
359
+ return "&quot;";
360
+ });
361
+ }
362
+ function parseStylesEnv(value) {
363
+ if (!value) return [];
364
+ return value.split(",").map((item) => item.trim()).filter((item) => item.length > 0);
365
+ }
366
+ //#endregion
367
+ //#region src/mvc/inertia/shared.ts
368
+ /** Container binding key for the scoped {@link SharedInertiaPropsRegistry}. */
369
+ const INERTIA_SHARED_PROPS_BINDING = "inertia.sharedProps";
370
+ /**
371
+ * Registrations are numbered from one process-wide counter so that props keep
372
+ * resolving in registration order — later registrations win on conflicting
373
+ * keys — no matter which registry each one landed in.
374
+ */
375
+ let registrationSequence = 0;
376
+ /**
377
+ * Holds the shared-props resolvers for one scope: either a single
378
+ * Application's container or the module-global fallback for bare-Hono apps.
379
+ */
380
+ var SharedInertiaPropsRegistry = class {
381
+ resolvers = [];
382
+ /** Replace every resolver registered in this scope. */
383
+ set(resolverFn) {
384
+ this.resolvers = resolverFn ? [orderedResolver(resolverFn)] : [];
385
+ }
386
+ /**
387
+ * Register additional shared props without replacing resolvers registered
388
+ * earlier — the new resolver's props are merged over the previous ones.
389
+ */
390
+ share(resolverFn) {
391
+ this.resolvers.push(orderedResolver(resolverFn));
392
+ }
393
+ /** The resolvers registered in this scope, ordered by registration. */
394
+ entries() {
395
+ return this.resolvers;
396
+ }
397
+ /**
398
+ * The scope's registrations composed into one resolver, or null when empty.
399
+ * The composition is a snapshot: resolvers registered later are not picked up.
400
+ */
401
+ get() {
402
+ if (this.resolvers.length === 0) return null;
403
+ if (this.resolvers.length === 1) return this.resolvers[0].resolve;
404
+ const snapshot = [...this.resolvers];
405
+ return (ctx) => applyResolvers(snapshot, ctx);
406
+ }
407
+ async resolve(ctx) {
408
+ return applyResolvers(this.resolvers, ctx);
409
+ }
410
+ };
411
+ function orderedResolver(resolverFn) {
412
+ return {
413
+ seq: registrationSequence++,
414
+ resolve: resolverFn
415
+ };
416
+ }
417
+ async function applyResolvers(entries, ctx) {
418
+ const merged = {};
419
+ for (const entry of entries) {
420
+ const props = await entry.resolve(ctx);
421
+ if (props && typeof props === "object") Object.assign(merged, props);
422
+ }
423
+ return merged;
424
+ }
425
+ const globalRegistry = new SharedInertiaPropsRegistry();
426
+ /** The registry bound to `container`, or null when it owns none yet. */
427
+ function scopedRegistry(container) {
428
+ if (!container?.has?.("inertia.sharedProps")) return null;
429
+ return container.make(INERTIA_SHARED_PROPS_BINDING);
430
+ }
431
+ /**
432
+ * The shared-props registry scoped to `container`, binding a fresh one on
433
+ * first use.
434
+ */
435
+ function ensureSharedInertiaPropsRegistry(container) {
436
+ const existing = scopedRegistry(container);
437
+ if (existing) return existing;
438
+ const registry = new SharedInertiaPropsRegistry();
439
+ container.instance(INERTIA_SHARED_PROPS_BINDING, registry);
440
+ return registry;
441
+ }
442
+ /**
443
+ * Replace the module-global shared props resolver. Props registered on an
444
+ * application's container (see {@link shareInertiaProps}) are unaffected.
445
+ */
446
+ function setInertiaSharedProps(resolverFn) {
447
+ globalRegistry.set(resolverFn);
448
+ }
449
+ /**
450
+ * The module-global registrations composed into one resolver, for manual
451
+ * composition. Container-scoped props are not included — get those from
452
+ * `ensureSharedInertiaPropsRegistry(container).get()`.
453
+ */
454
+ function getInertiaSharedPropsResolver() {
455
+ return globalRegistry.get();
456
+ }
457
+ /**
458
+ * Register additional shared props without replacing earlier resolvers, so
459
+ * several providers can each contribute (`setInertiaSharedProps` replaces
460
+ * wholesale). Pass the provider's `this.container` to scope them; without it
461
+ * they are module-global and a second Application in the process shares them.
462
+ */
463
+ function shareInertiaProps(resolverFn, container) {
464
+ (container ? ensureSharedInertiaPropsRegistry(container) : globalRegistry).share(resolverFn);
465
+ }
466
+ /**
467
+ * Resolve shared props for a request, merging the module-global registrations
468
+ * with those scoped to `container` in registration order.
469
+ */
470
+ async function resolveSharedInertiaProps(ctx, container) {
471
+ const scoped = scopedRegistry(container);
472
+ if (!scoped) return globalRegistry.resolve(ctx);
473
+ const globalEntries = globalRegistry.entries();
474
+ if (globalEntries.length === 0) return scoped.resolve(ctx);
475
+ return applyResolvers([...globalEntries, ...scoped.entries()].sort((a, b) => a.seq - b.seq), ctx);
476
+ }
477
+ //#endregion
478
+ //#region src/mvc/prototype.ts
479
+ const PROTOTYPE_HANDLER = Symbol.for("guren.prototype.handler");
480
+ const prototype = Object.freeze({ [PROTOTYPE_HANDLER]: true });
481
+ function isPrototypeHandler(value) {
482
+ return typeof value === "object" && value !== null && value[PROTOTYPE_HANDLER] === true;
483
+ }
484
+ /** Container key the loaded fixture is bound under once `Application` has validated the prototype routes. */
485
+ const PROTOTYPE_FIXTURE_BINDING = "prototype.fixture";
486
+ function isFixture(value) {
487
+ return typeof value === "object" && value !== null && typeof value.routes === "object" && value.routes !== null;
488
+ }
489
+ async function loadPrototypeFixture(loader) {
490
+ const loaded = await loader();
491
+ const fixture = isFixture(loaded) ? loaded : loaded.default;
492
+ if (!isFixture(fixture)) throw new Error("createApp({ prototype }) loaded a module that does not export a definePrototype() result as its default export.");
493
+ return fixture;
494
+ }
495
+ /** One `state()` per fixture per process: shared by every request, reset by a restart. */
496
+ const processState = /* @__PURE__ */ new WeakMap();
497
+ function stateOf(fixture) {
498
+ if (!processState.has(fixture)) processState.set(fixture, fixture.state?.() ?? {});
499
+ return processState.get(fixture);
500
+ }
501
+ function enforce(schema, data) {
502
+ if (!schema) return;
503
+ const result = schema.safeParse(data);
504
+ if (!result.success) throw ValidationException.withMessages(formatValidationErrors(result.error));
505
+ }
506
+ const BODYLESS_METHODS = /* @__PURE__ */ new Set([
507
+ "GET",
508
+ "HEAD",
509
+ "OPTIONS"
510
+ ]);
511
+ /**
512
+ * The route's handler: the fixture entry for the route name, run against the
513
+ * same context shape the browser client builds. The route contract is enforced
514
+ * first (`params`, `query`, `body`; not `output`, which only a response has), so `guren
515
+ * audit`'s "runtime-enforced" verdict stays true here.
516
+ */
517
+ function createPrototypeRouteHandler(route, deps) {
518
+ return async (c) => {
519
+ const fixture = resolveFixture(deps.container);
520
+ const name = route.name;
521
+ const handler = name ? fixture.routes[name] : void 0;
522
+ if (!name || !handler) throw new Error(`Prototype route ${route.method} ${route.path} has no fixture entry${name ? ` for "${name}"` : ""}.`);
523
+ const params = c.req.param();
524
+ const query = flattenRequestQueries(c);
525
+ enforce(route.schemas?.params, params);
526
+ enforce(route.schemas?.query, query);
527
+ const method = c.req.method.toUpperCase();
528
+ const body = BODYLESS_METHODS.has(method) ? void 0 : await parseRequestBody(c);
529
+ enforce(route.schemas?.body, body);
530
+ const session = getSessionFromContext(c);
531
+ const shared = {
532
+ ...fixture.shared,
533
+ ...await resolveSharedInertiaProps(c, deps.container)
534
+ };
535
+ const url = new URL(c.req.url);
536
+ const result = await handler({
537
+ method,
538
+ url: `${url.pathname}${url.search}`,
539
+ params,
540
+ query,
541
+ body,
542
+ state: stateOf(fixture),
543
+ shared,
544
+ page: (contract, props) => ({
545
+ kind: "page",
546
+ component: componentOf(contract),
547
+ props
548
+ }),
549
+ redirect: (to, redirectParams) => ({
550
+ kind: "redirect",
551
+ to,
552
+ params: redirectParams
553
+ }),
554
+ location: (target) => ({
555
+ kind: "location",
556
+ url: target
557
+ }),
558
+ errors: (errors) => ({
559
+ kind: "errors",
560
+ errors
561
+ }),
562
+ notFound: () => ({ kind: "not-found" }),
563
+ flash: (key, value) => session?.flash(key, value)
564
+ });
565
+ if (!isResult(result)) throw new Error(`Prototype entry "${name}" returned something other than page()/redirect()/errors()/location()/notFound().`);
566
+ return answer(result, c, fixture, shared, deps);
567
+ };
568
+ }
569
+ const RESULT_KINDS = /* @__PURE__ */ new Set([
570
+ "page",
571
+ "redirect",
572
+ "location",
573
+ "errors",
574
+ "not-found"
575
+ ]);
576
+ function componentOf(contract) {
577
+ return contract.component ?? contract.id;
578
+ }
579
+ function isResult(value) {
580
+ return typeof value === "object" && value !== null && RESULT_KINDS.has(String(value.kind));
581
+ }
582
+ function resolveFixture(container) {
583
+ let fixture;
584
+ try {
585
+ fixture = container?.make(PROTOTYPE_FIXTURE_BINDING);
586
+ } catch {
587
+ fixture = void 0;
588
+ }
589
+ if (!isFixture(fixture)) throw new Error("A prototype route was dispatched before its fixture was loaded. Pass `prototype: () => import(...)` to createApp() and mount routes through the application, which validates and loads it at boot.");
590
+ return fixture;
591
+ }
592
+ async function answer(result, c, fixture, shared, deps) {
593
+ switch (result.kind) {
594
+ case "page": return inertia(result.component, {
595
+ ...shared,
596
+ ...result.props
597
+ }, { request: c.req.raw });
598
+ case "redirect": return c.redirect(deps.routeUrl(result.to, result.params), 303);
599
+ case "location":
600
+ if (c.req.header("X-Inertia")) return new Response(null, {
601
+ status: 409,
602
+ headers: { "X-Inertia-Location": result.url }
603
+ });
604
+ return c.redirect(result.url, 302);
605
+ case "errors": throw ValidationException.withMessages(result.errors);
606
+ case "not-found":
607
+ if (fixture.notFoundPage) return inertia(componentOf(fixture.notFoundPage), {
608
+ ...shared,
609
+ status: 404,
610
+ message: "Not Found"
611
+ }, {
612
+ request: c.req.raw,
613
+ status: 404
614
+ });
615
+ throw HttpException.notFound();
616
+ }
617
+ }
618
+ //#endregion
109
619
  //#region src/mvc/Router.ts
110
620
  function normalizeModelBinding(binding) {
111
621
  if (Array.isArray(binding)) {
@@ -287,7 +797,10 @@ var Router = class {
287
797
  mount(app, options = {}) {
288
798
  for (const route of this.registry) {
289
799
  const resolvedMiddlewares = this.resolveMiddlewareNames(route.routeMiddlewareNames);
290
- const handler = resolveHandler(route.handler, this.modelBindings, options.container, route.bindings, route.path);
800
+ const handler = isPrototypeHandler(route.handler) ? createPrototypeRouteHandler(route, {
801
+ container: options.container,
802
+ routeUrl: (name, params) => this.route(name, params)
803
+ }) : resolveHandler(route.handler, this.modelBindings, options.container, route.bindings, route.path);
291
804
  const contractMiddleware = createContractValidationMiddleware(route);
292
805
  const inlineMiddlewares = [...route.scopedMiddlewares, ...route.middlewares];
293
806
  const preflightMiddleware = createAgentPreflightMiddleware(route, () => this.aggregateCapabilities(route.routeMiddlewareNames, inlineMiddlewares));
@@ -310,11 +823,12 @@ var Router = class {
310
823
  this.modelBindings.clear();
311
824
  }
312
825
  definitions() {
313
- return this.registry.map(({ method, path, name, schemas, resource, openapi, routeMiddlewareNames, middlewares, scopedMiddlewares, handler, bindings, agent }) => ({
826
+ return this.registry.map(({ method, path, name, schemas, resource, openapi, routeMiddlewareNames, middlewares, scopedMiddlewares, handler, bindings, agent, prototype }) => ({
314
827
  method,
315
828
  path,
316
829
  name,
317
830
  schemas,
831
+ prototype,
318
832
  resource: serializeResourceHint(resource),
319
833
  agent: agent ? cloneAgentMetadata(agent) : void 0,
320
834
  middlewareNames: [...routeMiddlewareNames],
@@ -347,6 +861,13 @@ var Router = class {
347
861
  applyRouteContract(route, options);
348
862
  return builder;
349
863
  }
864
+ if (isPrototypeHandler(handlerOrAction)) {
865
+ const builder = this.add(method, path, handlerOrAction, options.middlewares ?? []);
866
+ if (options.name) builder.name(options.name);
867
+ const route = this.registry[this.registry.length - 1];
868
+ applyRouteContract(route, options);
869
+ return builder;
870
+ }
350
871
  const contractHandler = handlerOrAction;
351
872
  if (typeof contractHandler !== "function") throw new Error(`Router.${method.toLowerCase()} requires a handler function when route contract options are provided.`);
352
873
  const wrappedHandler = createContractHandler(path, options, contractHandler);
@@ -369,6 +890,7 @@ var Router = class {
369
890
  scopedMiddlewares: scope.handlers,
370
891
  routeMiddlewareNames: scope.names
371
892
  };
893
+ if (isPrototypeHandler(handler)) route.prototype = true;
372
894
  this.registry.push(route);
373
895
  return createRouteBuilder(route, this.namedRoutes);
374
896
  }
@@ -916,6 +1438,18 @@ var CookieSessionStore = class {
916
1438
  /** The store `SessionConfig.default` names when it names none, and the one driver that shares no state between requests. */
917
1439
  const DEFAULT_SESSION_STORE_NAME = "memory";
918
1440
  const PER_PROCESS_SESSION_DRIVERS = /* @__PURE__ */ new Set([DEFAULT_SESSION_STORE_NAME]);
1441
+ /**
1442
+ * Every driver the framework itself registers, and whether it survives a
1443
+ * runtime that shares no memory between requests. Read by static checks that
1444
+ * cannot boot the app; a plugin's driver is declared in its `gurenPlugin`
1445
+ * manifest instead, and a name in neither is unverifiable, not absent.
1446
+ */
1447
+ const BUILT_IN_SESSION_DRIVERS = /* @__PURE__ */ new Map([
1448
+ ["memory", false],
1449
+ ["cookie", true],
1450
+ ["database", true],
1451
+ ["redis", true]
1452
+ ]);
919
1453
  function isPrunable(store) {
920
1454
  return typeof store.deleteExpired === "function";
921
1455
  }
@@ -2016,7 +2550,7 @@ function createDefaultGuardFactory(providerName) {
2016
2550
  }
2017
2551
  //#endregion
2018
2552
  //#region src/errors/error-page.ts
2019
- function escapeHtml$2(value) {
2553
+ function escapeHtml$1(value) {
2020
2554
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2021
2555
  }
2022
2556
  /** Production error page: no stack traces or internal details are exposed. */
@@ -2055,7 +2589,7 @@ function renderErrorPage(statusCode, message) {
2055
2589
  <div class="container">
2056
2590
  <div class="status">${statusCode}</div>
2057
2591
  <h1 class="title">${title}</h1>
2058
- <p class="description">${escapeHtml$2(message ?? STATUS_DESCRIPTIONS[statusCode] ?? "An unexpected error occurred.")}</p>
2592
+ <p class="description">${escapeHtml$1(message ?? STATUS_DESCRIPTIONS[statusCode] ?? "An unexpected error occurred.")}</p>
2059
2593
  <a href="/" class="home-link">Go Home</a>
2060
2594
  </div>
2061
2595
  </body>
@@ -2280,118 +2814,7 @@ var ErrorServiceProvider = class extends ServiceProvider {
2280
2814
  const handler = this.container.make("exception.handler");
2281
2815
  hono.onError((error, ctx) => handler.handle(error, ctx));
2282
2816
  }
2283
- };
2284
- //#endregion
2285
- //#region src/mvc/inertia/shared.ts
2286
- /** Container binding key for the scoped {@link SharedInertiaPropsRegistry}. */
2287
- const INERTIA_SHARED_PROPS_BINDING = "inertia.sharedProps";
2288
- /**
2289
- * Registrations are numbered from one process-wide counter so that props keep
2290
- * resolving in registration order — later registrations win on conflicting
2291
- * keys — no matter which registry each one landed in.
2292
- */
2293
- let registrationSequence = 0;
2294
- /**
2295
- * Holds the shared-props resolvers for one scope: either a single
2296
- * Application's container or the module-global fallback for bare-Hono apps.
2297
- */
2298
- var SharedInertiaPropsRegistry = class {
2299
- resolvers = [];
2300
- /** Replace every resolver registered in this scope. */
2301
- set(resolverFn) {
2302
- this.resolvers = resolverFn ? [orderedResolver(resolverFn)] : [];
2303
- }
2304
- /**
2305
- * Register additional shared props without replacing resolvers registered
2306
- * earlier — the new resolver's props are merged over the previous ones.
2307
- */
2308
- share(resolverFn) {
2309
- this.resolvers.push(orderedResolver(resolverFn));
2310
- }
2311
- /** The resolvers registered in this scope, ordered by registration. */
2312
- entries() {
2313
- return this.resolvers;
2314
- }
2315
- /**
2316
- * The scope's registrations composed into one resolver, or null when empty.
2317
- * The composition is a snapshot: resolvers registered later are not picked up.
2318
- */
2319
- get() {
2320
- if (this.resolvers.length === 0) return null;
2321
- if (this.resolvers.length === 1) return this.resolvers[0].resolve;
2322
- const snapshot = [...this.resolvers];
2323
- return (ctx) => applyResolvers(snapshot, ctx);
2324
- }
2325
- async resolve(ctx) {
2326
- return applyResolvers(this.resolvers, ctx);
2327
- }
2328
- };
2329
- function orderedResolver(resolverFn) {
2330
- return {
2331
- seq: registrationSequence++,
2332
- resolve: resolverFn
2333
- };
2334
- }
2335
- async function applyResolvers(entries, ctx) {
2336
- const merged = {};
2337
- for (const entry of entries) {
2338
- const props = await entry.resolve(ctx);
2339
- if (props && typeof props === "object") Object.assign(merged, props);
2340
- }
2341
- return merged;
2342
- }
2343
- const globalRegistry = new SharedInertiaPropsRegistry();
2344
- /** The registry bound to `container`, or null when it owns none yet. */
2345
- function scopedRegistry(container) {
2346
- if (!container?.has?.("inertia.sharedProps")) return null;
2347
- return container.make(INERTIA_SHARED_PROPS_BINDING);
2348
- }
2349
- /**
2350
- * The shared-props registry scoped to `container`, binding a fresh one on
2351
- * first use.
2352
- */
2353
- function ensureSharedInertiaPropsRegistry(container) {
2354
- const existing = scopedRegistry(container);
2355
- if (existing) return existing;
2356
- const registry = new SharedInertiaPropsRegistry();
2357
- container.instance(INERTIA_SHARED_PROPS_BINDING, registry);
2358
- return registry;
2359
- }
2360
- /**
2361
- * Replace the module-global shared props resolver. Props registered on an
2362
- * application's container (see {@link shareInertiaProps}) are unaffected.
2363
- */
2364
- function setInertiaSharedProps(resolverFn) {
2365
- globalRegistry.set(resolverFn);
2366
- }
2367
- /**
2368
- * The module-global registrations composed into one resolver, for manual
2369
- * composition. Container-scoped props are not included — get those from
2370
- * `ensureSharedInertiaPropsRegistry(container).get()`.
2371
- */
2372
- function getInertiaSharedPropsResolver() {
2373
- return globalRegistry.get();
2374
- }
2375
- /**
2376
- * Register additional shared props without replacing earlier resolvers, so
2377
- * several providers can each contribute (`setInertiaSharedProps` replaces
2378
- * wholesale). Pass the provider's `this.container` to scope them; without it
2379
- * they are module-global and a second Application in the process shares them.
2380
- */
2381
- function shareInertiaProps(resolverFn, container) {
2382
- (container ? ensureSharedInertiaPropsRegistry(container) : globalRegistry).share(resolverFn);
2383
- }
2384
- /**
2385
- * Resolve shared props for a request, merging the module-global registrations
2386
- * with those scoped to `container` in registration order.
2387
- */
2388
- async function resolveSharedInertiaProps(ctx, container) {
2389
- const scoped = scopedRegistry(container);
2390
- if (!scoped) return globalRegistry.resolve(ctx);
2391
- const globalEntries = globalRegistry.entries();
2392
- if (globalEntries.length === 0) return scoped.resolve(ctx);
2393
- return applyResolvers([...globalEntries, ...scoped.entries()].sort((a, b) => a.seq - b.seq), ctx);
2394
- }
2817
+ };
2395
2818
  //#endregion
2396
2819
  //#region src/providers/I18nServiceProvider.ts
2397
2820
  /**
@@ -2459,254 +2882,6 @@ var I18nServiceProvider = class extends ServiceProvider {
2459
2882
  }
2460
2883
  };
2461
2884
  //#endregion
2462
- //#region src/mvc/inertia/InertiaEngine.ts
2463
- ensureErrorStackTracePolyfill();
2464
- let documentOptions;
2465
- /**
2466
- * Register app-wide document defaults for server-rendered Inertia responses;
2467
- * call it at module scope in the app entry so every runtime picks it up.
2468
- * Process-wide, not request-scoped: calling it mid-flight leaks the policy into
2469
- * in-flight requests — use the {@link InertiaOptions} fields per response.
2470
- * Values are emitted verbatim, so never pass user input. `undefined` clears.
2471
- */
2472
- function setInertiaDocument(options) {
2473
- documentOptions = options;
2474
- }
2475
- let defaultSsrRenderer;
2476
- /**
2477
- * Register a process-wide default SSR renderer, for adapters whose bundler
2478
- * cannot resolve a runtime path (Workers has no filesystem for
2479
- * `GUREN_INERTIA_SSR_ENTRY`'s dynamic import). Per-call `ssr.render` still
2480
- * wins; `undefined` clears (test isolation).
2481
- */
2482
- function setInertiaSsrRenderer(renderer) {
2483
- defaultSsrRenderer = renderer;
2484
- }
2485
- const DEFAULT_TITLE = "Guren";
2486
- const DEV_FALLBACK_IMPORT_MAP = {
2487
- react: "https://esm.sh/react@19.0.0?dev",
2488
- "react/jsx-runtime": "https://esm.sh/react@19.0.0/jsx-runtime?dev",
2489
- "react/jsx-dev-runtime": "https://esm.sh/react@19.0.0/jsx-dev-runtime?dev",
2490
- "react-dom/client": "https://esm.sh/react-dom@19.0.0/client?dev",
2491
- "@guren/inertia-client": "/vendor/inertia-client.tsx",
2492
- "@inertiajs/react": "https://esm.sh/@inertiajs/react@2.2.15?dev&external=react,react-dom/client"
2493
- };
2494
- async function inertia(component, props, options = {}) {
2495
- const resolvedVersion = options.version ?? process.env.GUREN_INERTIA_VERSION ?? void 0;
2496
- const page = {
2497
- component,
2498
- props,
2499
- url: options.url ?? inertiaPageUrl(options.request) ?? "",
2500
- version: resolvedVersion
2501
- };
2502
- const request = options.request;
2503
- const isInertiaVisit = Boolean(request?.headers.get("X-Inertia"));
2504
- const prefersJson = request ? acceptsJson(request) : false;
2505
- const versionHeader = resolvedVersion ? { "X-Inertia-Version": resolvedVersion } : {};
2506
- if (request && resolvedVersion && isInertiaVisit && request.method === "GET") {
2507
- if (request.headers.get("X-Inertia-Version") !== resolvedVersion) return new Response(null, {
2508
- status: 409,
2509
- headers: {
2510
- "X-Inertia-Location": options.url ?? request.url,
2511
- Vary: "Accept"
2512
- }
2513
- });
2514
- }
2515
- if (isInertiaVisit || prefersJson) return new Response(serializePage(page), {
2516
- status: options.status ?? 200,
2517
- headers: {
2518
- "Content-Type": "application/json; charset=utf-8",
2519
- "X-Inertia": "true",
2520
- Vary: "Accept",
2521
- ...versionHeader,
2522
- ...options.headers
2523
- }
2524
- });
2525
- const html = await renderDocument$1(page, options);
2526
- return new Response(html, {
2527
- status: options.status ?? 200,
2528
- headers: {
2529
- "Content-Type": "text/html; charset=utf-8",
2530
- "X-Inertia": "true",
2531
- Vary: "Accept",
2532
- ...versionHeader,
2533
- ...options.headers
2534
- }
2535
- });
2536
- }
2537
- /**
2538
- * The Inertia protocol's page `url` is the request path plus query string, kept
2539
- * relative. Derived from the request when the caller does not override it.
2540
- */
2541
- function inertiaPageUrl(request) {
2542
- if (!request) return;
2543
- const { pathname, search } = new URL(request.url);
2544
- return `${pathname}${search}`;
2545
- }
2546
- async function renderDocument$1(page, options) {
2547
- const defaultEntry = process.env.GUREN_INERTIA_ENTRY || "/resources/js/app.tsx";
2548
- const entry = options.entry ?? defaultEntry;
2549
- const title = escapeHtml$1(options.title ?? DEFAULT_TITLE);
2550
- const isProduction = process.env.NODE_ENV === "production";
2551
- const configuredStyles = options.styles ?? parseStylesEnv(process.env.GUREN_INERTIA_STYLES);
2552
- const styles = !isProduction && options.styles === void 0 && isDevServerEntry(entry) ? configuredStyles.filter((href) => href !== DEFAULT_DEV_STYLES_ENTRY) : configuredStyles;
2553
- const envImportMap = parseImportMap(process.env.GUREN_INERTIA_IMPORT_MAP, { context: "GUREN_INERTIA_IMPORT_MAP" });
2554
- const importMapEntries = {
2555
- ...isProduction ? {} : DEV_FALLBACK_IMPORT_MAP,
2556
- ...envImportMap,
2557
- ...options.importMap
2558
- };
2559
- const importMap = JSON.stringify({ imports: importMapEntries }, null, 2);
2560
- const serializedPage = serializePage(page);
2561
- const stylesheetLinks = renderStyles(styles);
2562
- const criticalCss = resolveDocumentValue("criticalCss", options, page.component);
2563
- const prepaintScript = resolveDocumentValue("prepaintScript", options, page.component);
2564
- const headMarkup = resolveDocumentValue("head", options, page.component);
2565
- const ssrResult = await tryRenderSsr(page, options);
2566
- const headElements = (ssrResult?.head ?? []).map(normalizeHeadElement);
2567
- const headSegments = [
2568
- "<meta charset=\"utf-8\" />",
2569
- "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />",
2570
- headElements.some((element) => /<title\b[^>]*>/iu.test(element)) ? "" : `<title>${title}</title>`,
2571
- headMarkup ?? "",
2572
- criticalCss ? `<style id="guren-critical">${criticalCss}</style>` : "",
2573
- prepaintScript ? `<script>${prepaintScript}<\/script>` : "",
2574
- stylesheetLinks,
2575
- ...headElements,
2576
- Object.keys(importMapEntries).length > 0 ? `<script type="importmap">${importMap}<\/script>` : "",
2577
- `<script>window.__INERTIA_PAGE__ = ${serializedPage};<\/script>`
2578
- ].filter((segment) => segment && segment.length > 0);
2579
- const appMarkup = ssrResult?.body ?? `<script data-page="app" type="application/json">${serializedPage}<\/script><div id="app"></div>`;
2580
- const bodyClass = resolveDocumentValue("bodyClass", options, page.component);
2581
- const bodyAttributes = bodyClass ? ` class="${escapeAttribute(bodyClass)}"` : "";
2582
- return `<!DOCTYPE html>
2583
- <html lang="${escapeAttribute(options.lang ?? "en")}">
2584
- <head>
2585
- ${headSegments.join("\n ")}
2586
- </head>
2587
- <body${bodyAttributes}>
2588
- ${appMarkup}
2589
- <script type="module" src="${entry}"><\/script>
2590
- </body>
2591
- </html>`;
2592
- }
2593
- async function tryRenderSsr(page, options) {
2594
- const ssrOptions = options.ssr;
2595
- if (ssrOptions?.enabled === false) return;
2596
- const manifest = (ssrOptions?.manifest ?? process.env.GUREN_INERTIA_SSR_MANIFEST)?.trim() || void 0;
2597
- const renderer = ssrOptions?.render ?? defaultSsrRenderer ?? await loadSsrRenderer(ssrOptions?.entry ?? process.env.GUREN_INERTIA_SSR_ENTRY);
2598
- if (!renderer) return;
2599
- try {
2600
- const result = await renderer({
2601
- page,
2602
- request: options.request,
2603
- manifest
2604
- });
2605
- if (!result || typeof result.body !== "string") return;
2606
- return {
2607
- body: result.body,
2608
- head: Array.isArray(result.head) ? result.head : []
2609
- };
2610
- } catch (error) {
2611
- console.error("Inertia SSR renderer failed; falling back to client rendering.", error);
2612
- return;
2613
- }
2614
- }
2615
- async function loadSsrRenderer(entry) {
2616
- const specifier = entry?.trim();
2617
- if (!specifier) return;
2618
- const normalized = normalizeSsrSpecifier(specifier);
2619
- try {
2620
- const renderCandidate = extractSsrRenderer(await import(normalized));
2621
- if (!renderCandidate) {
2622
- console.warn(`Inertia SSR entry "${specifier}" does not export a renderer. Expected a default export or a named "render" function.`);
2623
- return;
2624
- }
2625
- return renderCandidate;
2626
- } catch (error) {
2627
- console.error(`Failed to import Inertia SSR entry "${specifier}".`, error);
2628
- return;
2629
- }
2630
- }
2631
- function extractSsrRenderer(module) {
2632
- if (!module || typeof module !== "object") return;
2633
- const candidate = typeof module.render === "function" ? module.render : typeof module.default === "function" ? module.default : void 0;
2634
- if (!candidate) return;
2635
- return (context) => Promise.resolve(candidate(context));
2636
- }
2637
- function normalizeSsrSpecifier(specifier) {
2638
- if (specifier.startsWith("file://") || isUrlLike(specifier)) return specifier;
2639
- if (specifier.startsWith("./") || specifier.startsWith("../")) {
2640
- const absolute = resolve$1(process.cwd(), specifier);
2641
- return pathToFileURL(absolute).href;
2642
- }
2643
- if (isAbsolute(specifier)) return pathToFileURL(specifier).href;
2644
- return specifier;
2645
- }
2646
- function isUrlLike(specifier) {
2647
- return /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(specifier);
2648
- }
2649
- /**
2650
- * An absolute http(s) entry means an asset dev server (Vite) is serving the
2651
- * module graph; a same-origin path means source files are served directly,
2652
- * where the raw stylesheet link is the only styling.
2653
- */
2654
- function isDevServerEntry(entry) {
2655
- return /^https?:\/\//iu.test(entry);
2656
- }
2657
- function renderStyles(styles) {
2658
- if (!styles.length) return "";
2659
- return styles.map((href) => `<link rel="stylesheet" href="${escapeAttribute(href)}" />`).join("\n ");
2660
- }
2661
- function normalizeHeadElement(element) {
2662
- return (typeof element === "string" ? element : String(element ?? "")).replace(/href="\/(?!public\/)([^"?]+\.(?:js|css))(\?[^"']*)?"/g, (_match, file, query = "") => `href="/public/assets/${file}${query}"`);
2663
- }
2664
- /** One document field: per-response override, then app-wide default, then "". */
2665
- function resolveDocumentValue(key, options, componentName) {
2666
- const override = options[key];
2667
- if (override !== void 0) return override;
2668
- const value = documentOptions?.[key];
2669
- return (typeof value === "function" ? value({ component: componentName }) : value) ?? "";
2670
- }
2671
- function serializePage(page) {
2672
- return JSON.stringify(page).replace(/[<\u2028\u2029]/gu, (char) => {
2673
- switch (char) {
2674
- case "<": return "\\u003c";
2675
- case "\u2028": return "\\u2028";
2676
- case "\u2029": return "\\u2029";
2677
- default: return char;
2678
- }
2679
- });
2680
- }
2681
- function acceptsJson(request) {
2682
- const accept = request.headers.get("accept")?.toLowerCase() ?? "";
2683
- if (!accept || accept === "*/*") return false;
2684
- if (accept.includes("text/html")) return false;
2685
- return accept.includes("application/json") || accept.includes("json");
2686
- }
2687
- function escapeHtml$1(value) {
2688
- return value.replace(/[&<>"']/gu, (char) => {
2689
- switch (char) {
2690
- case "&": return "&amp;";
2691
- case "<": return "&lt;";
2692
- case ">": return "&gt;";
2693
- case "\"": return "&quot;";
2694
- case "'": return "&#39;";
2695
- default: return char;
2696
- }
2697
- });
2698
- }
2699
- function escapeAttribute(value) {
2700
- return value.replace(/[&"]/gu, (char) => {
2701
- if (char === "&") return "&amp;";
2702
- return "&quot;";
2703
- });
2704
- }
2705
- function parseStylesEnv(value) {
2706
- if (!value) return [];
2707
- return value.split(",").map((item) => item.trim()).filter((item) => item.length > 0);
2708
- }
2709
- //#endregion
2710
2885
  //#region src/mvc/ViewEngine.ts
2711
2886
  /**
2712
2887
  * Registry for view renderers. Engines are typically registered via service
@@ -3183,8 +3358,30 @@ var Application = class {
3183
3358
  for (const gurenModule of this.options.modules ?? []) await mountModuleRoutes(this.router, gurenModule);
3184
3359
  this.routesRegistered = true;
3185
3360
  }
3361
+ await this.preparePrototypeRoutes();
3186
3362
  this.router.mount(this.hono, { container: this.container });
3187
3363
  }
3364
+ /**
3365
+ * Every failure here is one a request would otherwise surface as a 500:
3366
+ * an unnamed prototype route cannot be looked up, a named one the fixture
3367
+ * does not answer, no loader to answer from at all. Process-shared fixture
3368
+ * state is a developer's own `bun run dev`, not a deployment, hence the
3369
+ * production refusal; `GUREN_PROTOTYPE_ROUTES=1` overrides it deliberately.
3370
+ */
3371
+ async preparePrototypeRoutes() {
3372
+ if (this.container.has("prototype.fixture")) return;
3373
+ const routes = this.router.definitions().filter((route) => route.prototype);
3374
+ if (routes.length === 0) return;
3375
+ const describe = (route) => `${route.method} ${route.path}${route.name ? ` (${route.name})` : ""}`;
3376
+ const unnamed = routes.find((route) => !route.name);
3377
+ if (unnamed) throw new Error(`Route ${describe(unnamed)} uses the prototype handler but has no name; the fixture is keyed by route name. Chain .name() on it or pass { name } in its options.`);
3378
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "production" && process.env.GUREN_PROTOTYPE_ROUTES !== "1") throw new Error(`${routes.length} route(s) still answer from the prototype fixture (${routes.map(describe).join(", ")}), whose state is shared by every request of this process. Replace them with controllers before deploying, or set GUREN_PROTOTYPE_ROUTES=1 to run a deliberately fixture-backed server.`);
3379
+ if (!this.options.prototype) throw new Error(`Route ${describe(routes[0])} uses the prototype handler, but createApp() has no \`prototype\` option. Pass \`prototype: () => import('../resources/js/prototype/index.js')\`.`);
3380
+ const fixture = await loadPrototypeFixture(this.options.prototype);
3381
+ const missing = routes.filter((route) => typeof fixture.routes[route.name] !== "function");
3382
+ if (missing.length > 0) throw new Error(`The prototype fixture has no entry for ${missing.map(describe).join(", ")}. Add the route name to \`routes\` in resources/js/prototype/index.ts, or replace the handler with a controller.`);
3383
+ this.container.instance(PROTOTYPE_FIXTURE_BINDING, fixture);
3384
+ }
3188
3385
  use(path, ...middleware) {
3189
3386
  this.hono.use(path, ...middleware);
3190
3387
  }
@@ -3218,7 +3415,7 @@ var Application = class {
3218
3415
  await this.options.boot?.(this.hono);
3219
3416
  await this.mountRoutes();
3220
3417
  await this.mountDevEndpoint(isMcpEndpointEnabled(), async () => (await import("./McpServiceProvider-BvJRcDOm.js").then((n) => n.n)).McpServiceProvider, "GUREN_MCP=1 but the MCP endpoint could not load — is @modelcontextprotocol/sdk installed?");
3221
- await this.mountDevEndpoint(isDocsViewerEnabled(), async () => (await import("./DocsViewerServiceProvider-D2cuVgtN.js")).DocsViewerServiceProvider, "GUREN_DOCS=1 but the docs viewer could not load — is @guren/cli resolvable from this app?");
3418
+ await this.mountDevEndpoint(isDocsViewerEnabled(), async () => (await import("./DocsViewerServiceProvider-DWnlXx_y.js")).DocsViewerServiceProvider, "GUREN_DOCS=1 but the docs viewer could not load — is @guren/cli resolvable from this app?");
3222
3419
  await this.providerManager.bootAll();
3223
3420
  }
3224
3421
  /** Called once, from the constructor — see the note there for why. */
@@ -3250,7 +3447,7 @@ var Application = class {
3250
3447
  await provider.boot?.();
3251
3448
  }
3252
3449
  async fetch(request, env, executionCtx) {
3253
- return this.hono.fetch(request, env, executionCtx);
3450
+ return runInRequestScope(executionCtx, () => this.hono.fetch(request, env, executionCtx));
3254
3451
  }
3255
3452
  async listen(options = {}) {
3256
3453
  if (!Bun) throw new Error("Bun runtime is required to call Application.listen");
@@ -3855,6 +4052,10 @@ function deriveAgentTools(definitions) {
3855
4052
  if (!agent) continue;
3856
4053
  const method = definition.method.toUpperCase();
3857
4054
  const where = `${method} ${definition.path}`;
4055
+ if (definition.prototype) {
4056
+ warnings.push(`${where}: declares agent metadata while still on its prototype fixture, so it is not exposed as a tool.`);
4057
+ continue;
4058
+ }
3858
4059
  if (!definition.name) {
3859
4060
  warnings.push(`${where}: declares agent metadata but has no route name, so it is not exposed as a tool. Chain .name() on the route — the tool name is its identity.`);
3860
4061
  continue;
@@ -3995,21 +4196,29 @@ function deriveAuthorization(definition, method) {
3995
4196
  /**
3996
4197
  * The names a protocol adapter may add to an application's tool catalogue on
3997
4198
  * its own, and which an application route therefore may not claim (RFC 0016
3998
- * §5.4). One rule, two readers: `@guren/plugin-mcp` adds `guren.preflight` to
4199
+ * §5.4). One rule, two readers: `@guren/plugin-mcp` adds `guren_preflight` to
3999
4200
  * the catalogue it serves, `guren check` fails a route whose tool name
4000
4201
  * collides; the CLI cannot import the plugin, hence beside the derivation. A
4001
4202
  * `tools/list` carrying two tools with one name is rejected wholesale by an MCP
4002
- * client, so a collision costs the *entire* catalogue. The `guren.` prefix is
4203
+ * client, so a collision costs the *entire* catalogue. The `guren_` prefix is
4003
4204
  * not reserved wholesale: that would fail routes over collisions that do not exist.
4004
4205
  */
4005
4206
  /**
4207
+ * The grammar every known client accepts: a strict subset of MCP's own
4208
+ * (`AGENT_TOOL_NAME_PATTERN`, which admits `.` and 128 characters). The Claude and
4209
+ * OpenAI tool APIs enforce it; Claude Managed Agents silently skips an MCP tool
4210
+ * outside it (#787). Meta-tools have no `toolName` escape hatch, so the names
4211
+ * below must match; `guren check` warns on a route name that does not.
4212
+ */
4213
+ const PORTABLE_AGENT_TOOL_NAME_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
4214
+ /**
4006
4215
  * The preflight companion tool (RFC 0016 §5.4). Preflight cannot be an
4007
4216
  * *argument* of the tool being checked: a tool advertising an `outputSchema`
4008
4217
  * must answer with conforming `structuredContent` unless the result is an
4009
4218
  * error, and a verdict conforms to no route's output. One meta-tool for the
4010
4219
  * whole catalogue, not one companion per tool (§5.5).
4011
4220
  */
4012
- const PREFLIGHT_TOOL_NAME = "guren.preflight";
4221
+ const PREFLIGHT_TOOL_NAME = "guren_preflight";
4013
4222
  /**
4014
4223
  * The approval-status companion tool (RFC 0016 §5.4 item 4). A caller handed a
4015
4224
  * request id needs something that can say what became of it, and the gated tool
@@ -4017,12 +4226,12 @@ const PREFLIGHT_TOOL_NAME = "guren.preflight";
4017
4226
  * mode of the first, so neither output schema is the union of two unrelated
4018
4227
  * shapes.
4019
4228
  */
4020
- const APPROVAL_STATUS_TOOL_NAME = "guren.approval_status";
4229
+ const APPROVAL_STATUS_TOOL_NAME = "guren_approval_status";
4021
4230
  /** Every meta-tool name an adapter may occupy. */
4022
4231
  const RESERVED_AGENT_TOOL_NAMES = [PREFLIGHT_TOOL_NAME, APPROVAL_STATUS_TOOL_NAME];
4023
4232
  /**
4024
4233
  * Whether a tool name belongs to the framework rather than the application.
4025
- * Case-sensitive: MCP tool names are matched literally, so `Guren.Preflight` is
4234
+ * Case-sensitive: MCP tool names are matched literally, so `Guren_Preflight` is
4026
4235
  * a different tool and reserving it would take a name away for nothing.
4027
4236
  */
4028
4237
  function isReservedAgentToolName(name) {
@@ -4470,18 +4679,24 @@ const AGENT_AUDIT_BINDING = "agent.audit";
4470
4679
  * emitted for genuine listeners (RFC 0016 §5.2). Neither half may fail the call
4471
4680
  * it records: both are caught, the sink's failure warned rather than swallowed.
4472
4681
  */
4473
- function createAuditEmitter(sink, events, now = () => /* @__PURE__ */ new Date()) {
4682
+ function createAuditEmitter(sink, events, now = () => /* @__PURE__ */ new Date(), options = {}) {
4474
4683
  return (event) => {
4475
- if (sink) try {
4476
- Promise.resolve(sink(toAuditRecord(event, now()))).catch(warnSinkFailure);
4477
- } catch (error) {
4478
- warnSinkFailure(error);
4479
- }
4480
- events?.emit(event).catch((error) => {
4481
- console.warn(`[guren] audit event listener failed: ${String(error)}`);
4482
- });
4684
+ if (sink) keepAlive({
4685
+ run: () => sink(toAuditRecord(event, now())),
4686
+ onFailure: warnSinkFailure,
4687
+ label: LABEL
4688
+ }, options.defer);
4689
+ if (events) keepAlive({
4690
+ run: () => events.emit(event),
4691
+ onFailure: warnListenerFailure,
4692
+ label: LABEL
4693
+ }, options.defer);
4483
4694
  };
4484
4695
  }
4696
+ const LABEL = "agent audit work";
4697
+ function warnListenerFailure(error) {
4698
+ console.warn(`[guren] audit event listener failed: ${String(error)}`);
4699
+ }
4485
4700
  function warnSinkFailure(error) {
4486
4701
  console.warn(`[guren] agent audit sink failed, record dropped: ${String(error)}`);
4487
4702
  }
@@ -4606,7 +4821,7 @@ function agentApprovalUsableAt(request, now) {
4606
4821
  }
4607
4822
  /**
4608
4823
  * Whether `principal` may be told anything at all about `request` — the scope
4609
- * rule of `guren.approval_status` (RFC 0016 §5.4): a caller reads only the
4824
+ * rule of `guren_approval_status` (RFC 0016 §5.4): a caller reads only the
4610
4825
  * status of a request it created, or an agent could walk ids and enumerate
4611
4826
  * other principals' pending actions. A `false` here must be answered *exactly*
4612
4827
  * as an unknown id is: any difference in message, shape or timing reintroduces it.
@@ -4700,19 +4915,19 @@ const DEFAULT_APPROVAL_CONFIGURE_HINT = "an approval queue on the invocation pip
4700
4915
  */
4701
4916
  const DEFAULT_SCOPE_SUBJECT = "The caller's scopes";
4702
4917
  /**
4703
- * Wrap the application's `notify` so a failure can neither fail the tool call nor
4704
- * lose the record: it is already persisted when this runs, so a dead channel costs
4705
- * an approver an email, not a request. The failure is warned about with the request
4706
- * id, which is what finds the record sitting there unannounced. Both shapes are
4707
- * caught — a synchronous throw and a rejected promise.
4918
+ * A failure may neither fail the tool call nor lose the record: it is persisted
4919
+ * before this runs, so a dead channel costs an approver an email. The warning
4920
+ * carries the request id, which is what finds the record sitting there
4921
+ * unannounced. Everything else about invoking a best-effort channel — which
4922
+ * failures are caught, and when `defer` runs — is {@link keepAlive}'s.
4708
4923
  */
4709
- function notifyApprovers(notify) {
4924
+ function notifyApprovers(notify, defer) {
4710
4925
  return (request) => {
4711
- try {
4712
- Promise.resolve(notify(request)).catch((error) => warnNotifyFailure(request, error));
4713
- } catch (error) {
4714
- warnNotifyFailure(request, error);
4715
- }
4926
+ keepAlive({
4927
+ run: () => notify(request),
4928
+ onFailure: (error) => warnNotifyFailure(request, error),
4929
+ label: `approval notification for request ${request.id}`
4930
+ }, defer);
4716
4931
  };
4717
4932
  }
4718
4933
  function warnNotifyFailure(request, error) {
@@ -4819,7 +5034,7 @@ function spentVerdict(tool, request) {
4819
5034
  return approvalRefusal("spent", `The tool "${tool.toolName}" requires approval, and the approval for this exact call was already used by another call. Nothing was executed. Ask again to request a new one.`, request);
4820
5035
  }
4821
5036
  /**
4822
- * The scope half alone — what `guren.preflight` checks before rehearsing a call
5037
+ * The scope half alone — what `guren_preflight` checks before rehearsing a call
4823
5038
  * (RFC 0016 §5.4). Checking requires the *same* scope as calling, or the
4824
5039
  * companion becomes a probe of tools the token cannot call. Approval is not
4825
5040
  * applied: a rehearsal executes nothing, and approval gates an ability rather
@@ -4843,13 +5058,13 @@ function scopedShape(tool) {
4843
5058
  //#endregion
4844
5059
  //#region src/agent/pipeline.ts
4845
5060
  /**
4846
- * Build {@link AgentInvocationOptions.approvals} for one caller.
4847
- *
4848
- * The TTL default, the redaction rules and the `notify` wrapping are invariants
4849
- * of an approval record rather than of a protocol. Per caller, because an
4850
- * approval binds to the principal that asked; `undefined` means no queue.
5061
+ * Build {@link AgentInvocationOptions.approvals} for one caller — an approval binds
5062
+ * to the principal that asked; `undefined` means no queue. The TTL default, the
5063
+ * redaction rules and the `notify` wrapping are invariants of an approval record
5064
+ * rather than of a protocol, which is why `defer` arrives here: a `notify` the
5065
+ * pipeline received already wrapped cannot be given a deferrer afterwards.
4851
5066
  */
4852
- function createAgentApprovalContext(config, principal) {
5067
+ function createAgentApprovalContext(config, principal, defer) {
4853
5068
  if (!config) return void 0;
4854
5069
  return {
4855
5070
  store: config.store,
@@ -4857,7 +5072,7 @@ function createAgentApprovalContext(config, principal) {
4857
5072
  now: () => /* @__PURE__ */ new Date(),
4858
5073
  ttlMs: config.ttlMs ?? 36e5,
4859
5074
  redact: (tool, args) => redactAgentArguments(args, tool.redact),
4860
- notify: notifyApprovers(config.notify)
5075
+ notify: notifyApprovers(config.notify, defer)
4861
5076
  };
4862
5077
  }
4863
5078
  /**
@@ -5001,7 +5216,7 @@ function elapsed(startedAt) {
5001
5216
  * clock, no protocol.
5002
5217
  *
5003
5218
  * Here rather than in an adapter because two surfaces answer this question —
5004
- * `guren.approval_status` over MCP and a durable agent's own status check
5219
+ * `guren_approval_status` over MCP and a durable agent's own status check
5005
5220
  * (RFC 0017 §5) — and a record one of them calls "approved" must not be one
5006
5221
  * the other hides.
5007
5222
  */
@@ -7716,4 +7931,4 @@ function renderEnvironmentSection() {
7716
7931
  //#region src/index.ts
7717
7932
  ensureErrorStackTracePolyfill();
7718
7933
  //#endregion
7719
- export { AGENT_APPROVAL_CONFIG_KEY, AGENT_AUDIT_BINDING, AGENT_REDACTED, AGENT_TOOL_NAME_PATTERN, API_TOKEN_KEY, APPROVAL_STATUS_TOOL_NAME, AUTH_CONTEXT_KEY, AgentApprovalRequested, AgentToolDenied, AgentToolInvoked, Application, ApplicationShutdown, ApplicationStarted, AuthManager, Response$1 as AuthResponse, AuthServiceProvider, AuthenticatableModel, AuthenticationException, AuthorizationException, AuthorizationServiceProvider, AutoDiscovery, BaseFactory, BaseFactory as Factory, BaseSeeder, BaseSeeder as Seeder, BaseUserProvider, BroadcastManager, BroadcastServiceProvider, BufferedOutput, CSP_NONCE_KEY, CSRF_FORM_FIELD, CSRF_HEADER_NAME, CSRF_TOKEN_KEY, CacheCheck, CacheManager, CacheServiceProvider, Channel, Command, ConsoleChannel, ConsoleKernel, Container, Controller, CookieSessionStore, CursorPaginator, CustomCheck, DEFAULT_AGENT_APPROVAL_TTL_MS, DEFAULT_AGENT_AUDIT_PATH, DEFAULT_APPROVAL_CONFIGURE_HINT, DEFAULT_SCOPE_SUBJECT, DEFAULT_SESSION_STORE_NAME, DailyFileChannel, DatabaseChannel, DatabaseCheck, DefaultHasher, DefaultHasher as Hash, Encrypter, EncryptionServiceProvider, ErrorServiceProvider, Event, EventManager, EventServiceProvider, ExceptionHandler, FailedJobReporter, FieldValidator, FileStore as FileCacheStore, FileChannel, FormRequest, Gate, HealthCheck, HealthManager, HealthServiceProvider, HttpException, I18nManager, I18nServiceProvider, InertiaServiceProvider, Input, Job, JobFailed, JobProcessed, JsonLoader, JsonResource, LOCALE_CONTEXT_KEY, LOG_LEVEL_PRIORITY, Listener, LocalDriver as LocalStorageDriver, LogManager, LogServiceProvider, LogTransport, Logger, Mail, MailChannel, MailManager, MailServiceProvider, MemoryApiTokenStore, MemoryDriver as MemoryBroadcastDriver, MemoryStore as MemoryCacheStore, MemoryChannel, MemoryCheck, MemoryDriver$1 as MemoryDriver, MemoryDriver$1 as MemoryQueueDriver, MemoryEmailVerificationStore, MemoryLoader, MemoryOAuthStateStore, MemoryPasswordResetStore, MemoryRateLimitStore, MemorySessionStore, MemoryDriver$2 as MemoryStorageDriver, MemoryTransport, MessageSigner, MethodNotAllowedException, ModelUserProvider, NodeHasher, NotFoundHttpException, Notification, NotificationManager, NotificationServiceProvider, OAUTH_SESSION_BINDING_KEY, OAuthManager, OAuthServiceProvider, Output, PER_PROCESS_SESSION_DRIVERS, PREFLIGHT_ARGUMENT, PREFLIGHT_TOOL_NAME, Paginator, PendingSchedule, Policy, PresenceChannel, PrivateChannel, ProviderManager, QueueManager, QueueServiceProvider, RESERVED_AGENT_TOOL_NAMES, RedisDriver as RedisBroadcastDriver, RedisStore as RedisCacheStore, RedisCheck, RedisDriver$1 as RedisDriver, RedisDriver$1 as RedisQueueDriver, RequestFinished, RequestReceived, ResendTransport, Resource, ResourceCollection, Router, S3Driver, SERVERLESS_RUNTIME_LABELS, Schedule, ScheduledTask, Scheduler, SchedulingServiceProvider, ScryptHasher, SeederRunner, ServiceProvider, SessionGuard, SessionManager, SlackChannel, SlidingWindowRateLimitStore, SmtpTransport, SqsDriver, StorageCheck, StorageManager, StorageServiceProvider, SyncDriver, SyncDriver as SyncQueueDriver, TaggedCache, TokenGuard, Translator, UserAuthenticated, UserLoggedOut, VALIDATED_DATA_KEY, ValidationException, Validator, ViewEngine, Worker, abort, abortIf, abortUnless, advertisesStructuredOutput, after, afterOrEqual, agentApprovalExpiredAt, agentApprovalFingerprint, agentApprovalPrincipalKey, agentApprovalStatusAt, agentApprovalUsableAt, agentApprovalVisibleTo, alpha, alphaDash, alphaNum, approvalStatusNotFoundMessage, array as arrayRule, attachAuthContext, authorize as authorizeAbility, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, before, beforeOrEqual, between, boolean as booleanRule, buildAgentApprovalRequest, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildToolRequest, buildVerificationUrl, can, cannot, canonicalizeAgentApprovalInput, check as checkHash, classifyRegistrationScope, clearJobRegistry, clearNotificationRegistry, collect, completeEmailVerification, completePasswordReset, confirmed, createAgentApprovalContext, createAgentAuditRecorder, createAgentInvocationPipeline, createApiToken, createApp, createAuditEmitter, createBearerTokenMiddleware, createBroadcastManager, createCacheManager, createConsoleKernel, createContainer, createCorsMiddleware, createCspMiddleware, createCsrfMiddleware, createDiscordOAuthProviderConfig, createEmailVerificationToken, createEncrypter, createEventManager, createExceptionHandler, createFacade, createFacades, createForceHttpsMiddleware, createGate, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createHealthManager, createHostAuthorizationMiddleware, createI18n, createLogManager, createMailManager, createNotificationManager, createOAuthManager, createOAuthState, createPasswordResetToken, createQueueManager, createRateLimitMiddleware, createRedirectSafetyMiddleware, createRedisClient, createScheduler, createSecurityHeaders, createSeederRunner, createSessionMiddleware, createSqsAdapter, createStorageManager, createTypedBroadcaster, createValidator, csrfField, cursorPaginate, custom, customCheck, dailyFileDateStamp, dailyFilePath, dateFormat, date as dateRule, debugErrorMiddleware, decodeCursor, decrypt, defineFactory, defineGate, defineMiddleware, defineModule, definePlugin, definePolicy, deriveAgentTools, deriveAppKey, deriveAppKeyring, describeBuildFailure, detectLocaleMiddleware, detectServerlessRuntime, different, email as emailRule, encodeCursor, encrypt, endsWith, exchangeOAuthCode, exists, expandToolScopes, fetchOAuthUserProfile, file as fileRule, filterSensitiveData, formatValidationErrors, gateApproval, gatePreflight, gateToolCall, generateAppKey, generateKey, generateOtp, generatePassword, generateSlug, getApiToken, getApiTokenOrFail, getAppKeyringFromEnv, getBroadcastManager, getContainer, getCspNonce, getCsrfToken, getEncrypter, getExceptionHandler, getGate, getI18n, getInertiaSharedPropsResolver, getJob, getLogManager, getMailManager, getNextOccurrence, getNextOccurrences, getNotification, getNotificationManager, getPluralizationRule, getQueueDriver, getRateLimitInfo, getRegisteredJobs, getRequestLocale, getRequestTranslator, getSessionFromContext, getUserApiTokens, getValidatedData, hash, hashPassword, hmac, image as imageRule, inValues, inertia, integer, ip, ipv4, ipv6, isDue, isDueInTimezone, isEmailVerified, isReservedAgentToolName, isSafeRedirectUrl, jsonResponse, json as jsonRule, mail, mapToolResponse, matchDailyFileDate, matchesCron, max, maxFileSize, md5, mimes, min, minFileSize, mountModuleRoutes, needsRehash, normalizeAppKey, notIn, notifyApprovers, nullable, numeric, object as objectRule, paginate, parseApiToken, parseAppKey, parseAuditRecord, parseCron, parseOAuthRedirectUrl, parsePasswordResetUrl, parsePreviousAppKeys, parseRequestPayload, parseSignature, parseToolScope, parseVerificationUrl, pick, pluralizationRules, processJob, quickValidate, quickValidateOrThrow, random, randomBase64, randomBase64Url, randomHex, randomInt, randomString, readBearerToken, redactAgentArguments, regex, registerJob, registerNotification, renderDebugPage, renderDocument, renderErrorPage, requestIdMiddleware, requestLoggingMiddleware, requireAuthenticated, requireGuest, requireVerifiedEmail, required, requiredIf, requiredUnless, requiredWith, requiredWithout, resetCalledSeeders, resetRateLimit, resolve, resolveJobName, resolveNotifiableType, revokeAllApiTokens, revokeApiToken, same, sample, sanitizeOAuthRedirect, scopedShape, scopesAllowTool, secureCompare, selectPluralForm, setBroadcastManager, setContainer, setEncrypter, setExceptionHandler, setGate, setI18n, setInertiaDocument, setInertiaSharedProps, setInertiaSsrRenderer, setLogManager, setMailManager, setNotificationManager, setQueueDriver, sha256, sha512, shareInertiaProps, shuffle, signUrl, size, startsWith, string as stringRule, t, tc, toApprovalStatusReport, toAuditRecord, toTimezone, tokenCan, tokenCanAll, tokenCanAny, tryGetI18n, unique, url as urlRule, urlSafeToken, uuid, uuid$1 as uuidRule, validate, validateRequest, validateRequestWith, validateSafe, verifyApiToken, verifyCsrfToken, verifyEmailToken, verifyHmac, verifyOAuthState, verifyPassword, verifyPasswordResetToken, verifySignedUrl, viteAsset, withAuthorization };
7934
+ export { AGENT_APPROVAL_CONFIG_KEY, AGENT_AUDIT_BINDING, AGENT_REDACTED, AGENT_TOOL_NAME_PATTERN, API_TOKEN_KEY, APPROVAL_STATUS_TOOL_NAME, AUTH_CONTEXT_KEY, AgentApprovalRequested, AgentToolDenied, AgentToolInvoked, Application, ApplicationShutdown, ApplicationStarted, AuthManager, Response$1 as AuthResponse, AuthServiceProvider, AuthenticatableModel, AuthenticationException, AuthorizationException, AuthorizationServiceProvider, AutoDiscovery, BUILT_IN_SESSION_DRIVERS, BaseFactory, BaseFactory as Factory, BaseSeeder, BaseSeeder as Seeder, BaseUserProvider, BroadcastManager, BroadcastServiceProvider, BufferedOutput, CSP_NONCE_KEY, CSRF_FORM_FIELD, CSRF_HEADER_NAME, CSRF_TOKEN_KEY, CacheCheck, CacheManager, CacheServiceProvider, Channel, Command, ConsoleChannel, ConsoleKernel, Container, Controller, CookieSessionStore, CursorPaginator, CustomCheck, DEFAULT_AGENT_APPROVAL_TTL_MS, DEFAULT_AGENT_AUDIT_PATH, DEFAULT_APPROVAL_CONFIGURE_HINT, DEFAULT_SCOPE_SUBJECT, DEFAULT_SESSION_STORE_NAME, DailyFileChannel, DatabaseChannel, DatabaseCheck, DefaultHasher, DefaultHasher as Hash, Encrypter, EncryptionServiceProvider, ErrorServiceProvider, Event, EventManager, EventServiceProvider, ExceptionHandler, FailedJobReporter, FieldValidator, FileStore as FileCacheStore, FileChannel, FormRequest, Gate, HealthCheck, HealthManager, HealthServiceProvider, HttpException, I18nManager, I18nServiceProvider, InertiaServiceProvider, Input, Job, JobFailed, JobProcessed, JsonLoader, JsonResource, LOCALE_CONTEXT_KEY, LOG_LEVEL_PRIORITY, Listener, LocalDriver as LocalStorageDriver, LogManager, LogServiceProvider, LogTransport, Logger, Mail, MailChannel, MailManager, MailServiceProvider, MemoryApiTokenStore, MemoryDriver as MemoryBroadcastDriver, MemoryStore as MemoryCacheStore, MemoryChannel, MemoryCheck, MemoryDriver$1 as MemoryDriver, MemoryDriver$1 as MemoryQueueDriver, MemoryEmailVerificationStore, MemoryLoader, MemoryOAuthStateStore, MemoryPasswordResetStore, MemoryRateLimitStore, MemorySessionStore, MemoryDriver$2 as MemoryStorageDriver, MemoryTransport, MessageSigner, MethodNotAllowedException, ModelUserProvider, NodeHasher, NotFoundHttpException, Notification, NotificationManager, NotificationServiceProvider, OAUTH_SESSION_BINDING_KEY, OAuthManager, OAuthServiceProvider, Output, PER_PROCESS_SESSION_DRIVERS, PORTABLE_AGENT_TOOL_NAME_PATTERN, PREFLIGHT_ARGUMENT, PREFLIGHT_TOOL_NAME, Paginator, PendingSchedule, Policy, PresenceChannel, PrivateChannel, ProviderManager, QueueManager, QueueServiceProvider, RESERVED_AGENT_TOOL_NAMES, RedisDriver as RedisBroadcastDriver, RedisStore as RedisCacheStore, RedisCheck, RedisDriver$1 as RedisDriver, RedisDriver$1 as RedisQueueDriver, RequestFinished, RequestReceived, ResendTransport, Resource, ResourceCollection, Router, S3Driver, SERVERLESS_RUNTIME_LABELS, Schedule, ScheduledTask, Scheduler, SchedulingServiceProvider, ScryptHasher, SeederRunner, ServiceProvider, SessionGuard, SessionManager, SlackChannel, SlidingWindowRateLimitStore, SmtpTransport, SqsDriver, StorageCheck, StorageManager, StorageServiceProvider, SyncDriver, SyncDriver as SyncQueueDriver, TaggedCache, TokenGuard, Translator, UserAuthenticated, UserLoggedOut, VALIDATED_DATA_KEY, ValidationException, Validator, ViewEngine, Worker, abort, abortIf, abortUnless, advertisesStructuredOutput, after, afterOrEqual, agentApprovalExpiredAt, agentApprovalFingerprint, agentApprovalPrincipalKey, agentApprovalStatusAt, agentApprovalUsableAt, agentApprovalVisibleTo, alpha, alphaDash, alphaNum, approvalStatusNotFoundMessage, array as arrayRule, attachAuthContext, authorize as authorizeAbility, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, before, beforeOrEqual, between, boolean as booleanRule, buildAgentApprovalRequest, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildToolRequest, buildVerificationUrl, can, cannot, canonicalizeAgentApprovalInput, check as checkHash, classifyRegistrationScope, clearJobRegistry, clearNotificationRegistry, collect, completeEmailVerification, completePasswordReset, confirmed, createAgentApprovalContext, createAgentAuditRecorder, createAgentInvocationPipeline, createApiToken, createApp, createAuditEmitter, createBearerTokenMiddleware, createBroadcastManager, createCacheManager, createConsoleKernel, createContainer, createCorsMiddleware, createCspMiddleware, createCsrfMiddleware, createDiscordOAuthProviderConfig, createEmailVerificationToken, createEncrypter, createEventManager, createExceptionHandler, createFacade, createFacades, createForceHttpsMiddleware, createGate, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createHealthManager, createHostAuthorizationMiddleware, createI18n, createLogManager, createMailManager, createNotificationManager, createOAuthManager, createOAuthState, createPasswordResetToken, createQueueManager, createRateLimitMiddleware, createRedirectSafetyMiddleware, createRedisClient, createScheduler, createSecurityHeaders, createSeederRunner, createSessionMiddleware, createSqsAdapter, createStorageManager, createTypedBroadcaster, createValidator, csrfField, cursorPaginate, custom, customCheck, dailyFileDateStamp, dailyFilePath, dateFormat, date as dateRule, debugErrorMiddleware, decodeCursor, decrypt, defineFactory, defineGate, defineMiddleware, defineModule, definePlugin, definePolicy, deriveAgentTools, deriveAppKey, deriveAppKeyring, describeBuildFailure, detectLocaleMiddleware, detectServerlessRuntime, different, email as emailRule, encodeCursor, encrypt, endsWith, exchangeOAuthCode, exists, expandToolScopes, fetchOAuthUserProfile, file as fileRule, filterSensitiveData, formatValidationErrors, gateApproval, gatePreflight, gateToolCall, generateAppKey, generateKey, generateOtp, generatePassword, generateSlug, getApiToken, getApiTokenOrFail, getAppKeyringFromEnv, getBroadcastManager, getContainer, getCspNonce, getCsrfToken, getEncrypter, getExceptionHandler, getGate, getI18n, getInertiaSharedPropsResolver, getJob, getLogManager, getMailManager, getNextOccurrence, getNextOccurrences, getNotification, getNotificationManager, getPluralizationRule, getQueueDriver, getRateLimitInfo, getRegisteredJobs, getRequestLocale, getRequestTranslator, getSessionFromContext, getUserApiTokens, getValidatedData, hash, hashPassword, hmac, image as imageRule, inValues, inertia, integer, ip, ipv4, ipv6, isDue, isDueInTimezone, isEmailVerified, isReservedAgentToolName, isSafeRedirectUrl, jsonResponse, json as jsonRule, mail, mapToolResponse, matchDailyFileDate, matchesCron, max, maxFileSize, md5, mimes, min, minFileSize, mountModuleRoutes, needsRehash, normalizeAppKey, notIn, notifyApprovers, nullable, numeric, object as objectRule, paginate, parseApiToken, parseAppKey, parseAuditRecord, parseCron, parseOAuthRedirectUrl, parsePasswordResetUrl, parsePreviousAppKeys, parseRequestPayload, parseSignature, parseToolScope, parseVerificationUrl, pick, pluralizationRules, processJob, prototype, quickValidate, quickValidateOrThrow, random, randomBase64, randomBase64Url, randomHex, randomInt, randomString, readBearerToken, redactAgentArguments, regex, registerJob, registerNotification, renderDebugPage, renderDocument, renderErrorPage, requestIdMiddleware, requestLoggingMiddleware, requireAuthenticated, requireGuest, requireVerifiedEmail, required, requiredIf, requiredUnless, requiredWith, requiredWithout, resetCalledSeeders, resetRateLimit, resolve, resolveJobName, resolveNotifiableType, revokeAllApiTokens, revokeApiToken, same, sample, sanitizeOAuthRedirect, scopedShape, scopesAllowTool, secureCompare, selectPluralForm, setBroadcastManager, setContainer, setEncrypter, setExceptionHandler, setGate, setI18n, setInertiaDocument, setInertiaSharedProps, setInertiaSsrRenderer, setLogManager, setMailManager, setNotificationManager, setQueueDriver, sha256, sha512, shareInertiaProps, shuffle, signUrl, size, startsWith, string as stringRule, t, tc, toApprovalStatusReport, toAuditRecord, toTimezone, tokenCan, tokenCanAll, tokenCanAny, tryGetI18n, unique, url as urlRule, urlSafeToken, uuid, uuid$1 as uuidRule, validate, validateRequest, validateRequestWith, validateSafe, verifyApiToken, verifyCsrfToken, verifyEmailToken, verifyHmac, verifyOAuthState, verifyPassword, verifyPasswordResetToken, verifySignedUrl, viteAsset, withAuthorization };