@guren/server 2.23.2 → 2.24.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.
- package/dist/DailyFileChannel-CTTPA0EF.js +114 -0
- package/dist/{DocsViewerServiceProvider-DWnlXx_y.js → DocsViewerServiceProvider-CIRNHQ2I.js} +2 -2
- package/dist/{authorization-0mCGUFoI.js → Gate-Cn1E6JnO.js} +3 -217
- package/dist/{Job-BVvaY-7p.js → Job-BVRCYuVY.js} +4 -10
- package/dist/McpServiceProvider-B-LioPSz.js +43 -0
- package/dist/Resource-BJhY4aF8.js +1035 -0
- package/dist/{loopback-guard-DT9gHF0F.js → ServiceProvider-DDW3MqQJ.js} +10 -68
- package/dist/agent/audit-file.d.ts +3 -0
- package/dist/agent/audit-sink.d.ts +16 -0
- package/dist/agent/call-budget.d.ts +22 -0
- package/dist/agent/events.d.ts +6 -6
- package/dist/api-token-BbgDEd6j.js +298 -0
- package/dist/audit-file-DocumbCr.js +29 -0
- package/dist/auth/index.js +2 -1
- package/dist/auth/oauth/index.d.ts +7 -0
- package/dist/{auth-D_W1cJp3.js → auth-vFeem6uM.js} +14 -300
- package/dist/authorization/index.js +2 -1
- package/dist/authorization-BsMTG8P1.js +217 -0
- package/dist/broadcasting/index.js +1 -1
- package/dist/{broadcasting-DVfG2vgN.js → broadcasting-6o_CCfF0.js} +2 -1
- package/dist/config/define.d.ts +50 -0
- package/dist/config/env-reads.d.ts +12 -0
- package/dist/config/env.d.ts +122 -0
- package/dist/container/Container.d.ts +13 -2
- package/dist/container/ServiceProvider.d.ts +7 -0
- package/dist/container/bindings.d.ts +8 -0
- package/dist/{default-application-Chbrul_m.js → default-application-CMuAAsdf.js} +20 -31
- package/dist/deprecate-rL8jNpKX.js +31 -0
- package/dist/encryption/index.js +1 -1
- package/dist/{encryption-BRjZnshr.js → encryption-_GiNb0Ol.js} +2 -1
- package/dist/{endpoint-BXipU2Jj.js → endpoint-CTIzcagh.js} +1 -1
- package/dist/{endpoint-Dsw3Acvq.js → endpoint-Coq0K_6I.js} +1 -1
- package/dist/events/index.js +1 -1
- package/dist/{events-CaJKZ2qk.js → events-swsyfCzt.js} +1 -1
- package/dist/http/Application.d.ts +22 -0
- package/dist/http/vite-manifest.d.ts +5 -1
- package/dist/i18n/index.js +1 -1
- package/dist/i18n/injected-translations.d.ts +8 -0
- package/dist/i18n/loaders/JsonLoader.d.ts +3 -2
- package/dist/{i18n-DRo1g0AN.js → i18n-0bOJqFpX.js} +5 -3
- package/dist/index.d.ts +11 -0
- package/dist/index.js +526 -1075
- package/dist/inertia-defaults-BjrcT7za.js +30 -0
- package/dist/internal/request.d.ts +4 -3
- package/dist/internal/request.js +2 -1
- package/dist/internal/testing.d.ts +17 -0
- package/dist/internal/testing.js +6 -0
- package/dist/lambda/index.js +1 -1
- package/dist/logging/index.js +2 -1
- package/dist/{logging-CXotojgW.js → logging-DshkpIkj.js} +4 -113
- package/dist/loopback-guard-CG8xB4v0.js +68 -0
- package/dist/mail/index.js +1 -1
- package/dist/{mail-zMjQimaJ.js → mail-CQlxrjYp.js} +4 -2
- package/dist/mcp/McpServiceProvider.d.ts +21 -4
- package/dist/mcp/create-mcp-server.d.ts +6 -0
- package/dist/mcp/index.js +434 -1
- package/dist/mvc/Controller.d.ts +11 -1
- package/dist/mvc/Router.d.ts +6 -0
- package/dist/mvc/inertia/InertiaEngine.d.ts +2 -0
- package/dist/mvc/validated-input.d.ts +55 -0
- package/dist/notifications/index.js +1 -1
- package/dist/{notifications-BLid0Y6M.js → notifications-DmyJZGM2.js} +3 -2
- package/dist/providers/ConfigServiceProvider.d.ts +19 -0
- package/dist/queue/index.js +2 -2
- package/dist/{queue-IdJjqbyJ.js → queue-CdwHlFXE.js} +1 -1
- package/dist/resolve-optional-ax6gPWTp.js +9 -0
- package/dist/runtime/index.js +2 -1
- package/dist/support/redirect-target.d.ts +5 -1
- package/dist/validated-input-D84J8wcC.js +25 -0
- package/dist/{vite-manifest-2p0IRIcy.js → vite-manifest-DAqhhZZ9.js} +7 -32
- package/package.json +6 -2
- package/dist/McpServiceProvider-BvJRcDOm.js +0 -458
|
@@ -0,0 +1,1035 @@
|
|
|
1
|
+
import { i as parseRequestBody, n as flattenRequestQueries, o as parseRequestUploads, t as asRecord } from "./request-CLOYytGP.js";
|
|
2
|
+
import { n as getValidatedInput, r as readValidatedInput } from "./validated-input-D84J8wcC.js";
|
|
3
|
+
import { n as ValidationException } from "./errors-JpkcCjjn.js";
|
|
4
|
+
import { n as parseImportMap, t as DEFAULT_DEV_STYLES_ENTRY } from "./inertia-defaults-BjrcT7za.js";
|
|
5
|
+
import { t as resolveOptional } from "./resolve-optional-ax6gPWTp.js";
|
|
6
|
+
import { n as warnDeprecatedGetter, r as warnDeprecatedSetter } from "./deprecate-rL8jNpKX.js";
|
|
7
|
+
import { n as ServiceProvider } from "./ServiceProvider-DDW3MqQJ.js";
|
|
8
|
+
import { r as getAuthContext } from "./context-af2n5abO.js";
|
|
9
|
+
import { o as getApiTokenOrFail } from "./api-token-BbgDEd6j.js";
|
|
10
|
+
import { a as resolveI18n } from "./i18n-0bOJqFpX.js";
|
|
11
|
+
import { d as resolveGate, g as tryGetRequestContainer } from "./Gate-Cn1E6JnO.js";
|
|
12
|
+
import { t as jsx_runtime_exports } from "./jsx-runtime.js";
|
|
13
|
+
import { getCookie } from "hono/cookie";
|
|
14
|
+
import { isAbsolute, resolve } from "node:path";
|
|
15
|
+
import { pathToFileURL } from "node:url";
|
|
16
|
+
import { createMiddleware } from "hono/factory";
|
|
17
|
+
import { parseAccept } from "hono/utils/accept";
|
|
18
|
+
//#region src/support/error-polyfill.ts
|
|
19
|
+
let patched = false;
|
|
20
|
+
/**
|
|
21
|
+
* Bun 1.x throws from Error.captureStackTrace unless the first argument is a
|
|
22
|
+
* real Error. Packages that pass plain objects (notably follow-redirects, which
|
|
23
|
+
* Node tolerates) then crash SSR boot before Inertia can import the SSR entry.
|
|
24
|
+
* This mirrors Node by copying a real Error's stack onto whatever it is given.
|
|
25
|
+
*/
|
|
26
|
+
function ensureErrorStackTracePolyfill() {
|
|
27
|
+
if (patched) return;
|
|
28
|
+
const capture = Error.captureStackTrace;
|
|
29
|
+
if (typeof capture !== "function") {
|
|
30
|
+
Error.captureStackTrace = (target) => copyStackFromNewError(target);
|
|
31
|
+
patched = true;
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
Error.captureStackTrace = (target, constructorOpt) => {
|
|
35
|
+
if (target instanceof Error) try {
|
|
36
|
+
return capture(target, constructorOpt);
|
|
37
|
+
} catch {}
|
|
38
|
+
const placeholder = /* @__PURE__ */ new Error();
|
|
39
|
+
capture(placeholder, constructorOpt);
|
|
40
|
+
copyStackFromError(target, placeholder);
|
|
41
|
+
return target;
|
|
42
|
+
};
|
|
43
|
+
patched = true;
|
|
44
|
+
}
|
|
45
|
+
function copyStackFromNewError(target) {
|
|
46
|
+
copyStackFromError(target, /* @__PURE__ */ new Error());
|
|
47
|
+
}
|
|
48
|
+
function copyStackFromError(target, source) {
|
|
49
|
+
if (!target || typeof target !== "object") return;
|
|
50
|
+
if (source.stack) Object.defineProperty(target, "stack", {
|
|
51
|
+
configurable: true,
|
|
52
|
+
enumerable: false,
|
|
53
|
+
writable: true,
|
|
54
|
+
value: source.stack
|
|
55
|
+
});
|
|
56
|
+
if (source.name && !("name" in target)) Object.defineProperty(target, "name", {
|
|
57
|
+
configurable: true,
|
|
58
|
+
enumerable: false,
|
|
59
|
+
writable: true,
|
|
60
|
+
value: source.name
|
|
61
|
+
});
|
|
62
|
+
if (source.message && !("message" in target)) Object.defineProperty(target, "message", {
|
|
63
|
+
configurable: true,
|
|
64
|
+
enumerable: false,
|
|
65
|
+
writable: true,
|
|
66
|
+
value: source.message
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
//#endregion
|
|
70
|
+
//#region src/mvc/inertia/InertiaEngine.ts
|
|
71
|
+
ensureErrorStackTracePolyfill();
|
|
72
|
+
let documentOptions;
|
|
73
|
+
/**
|
|
74
|
+
* Register app-wide document defaults for server-rendered Inertia responses.
|
|
75
|
+
* Process-wide, not request-scoped: calling it mid-flight leaks the policy into
|
|
76
|
+
* in-flight requests — use the {@link InertiaOptions} fields per response.
|
|
77
|
+
* Values are emitted verbatim, so never pass user input. `undefined` clears.
|
|
78
|
+
*
|
|
79
|
+
* @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Pass
|
|
80
|
+
* `createApp({ inertia: { document } })`, which binds it on the app rather than
|
|
81
|
+
* the process. The slot stays the engine's second read.
|
|
82
|
+
*/
|
|
83
|
+
function setInertiaDocument(options) {
|
|
84
|
+
warnDeprecatedSetter("setInertiaDocument");
|
|
85
|
+
documentOptions = options;
|
|
86
|
+
}
|
|
87
|
+
let defaultSsrRenderer;
|
|
88
|
+
/**
|
|
89
|
+
* Register a process-wide default SSR renderer, for adapters whose bundler
|
|
90
|
+
* cannot resolve a runtime path (Workers has no filesystem for
|
|
91
|
+
* `GUREN_INERTIA_SSR_ENTRY`'s dynamic import). Per-call `ssr.render` still
|
|
92
|
+
* wins; `undefined` clears (test isolation).
|
|
93
|
+
*
|
|
94
|
+
* @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Pass
|
|
95
|
+
* `createApp({ inertia: { ssrRenderer } })`, or bind `inertia.ssrRenderer` on
|
|
96
|
+
* the app when the renderer only exists after `createApp()` has run.
|
|
97
|
+
*/
|
|
98
|
+
function setInertiaSsrRenderer(renderer) {
|
|
99
|
+
warnDeprecatedSetter("setInertiaSsrRenderer");
|
|
100
|
+
defaultSsrRenderer = renderer;
|
|
101
|
+
}
|
|
102
|
+
const DEFAULT_TITLE = "Guren";
|
|
103
|
+
const DEV_FALLBACK_IMPORT_MAP = {
|
|
104
|
+
react: "https://esm.sh/react@19.0.0?dev",
|
|
105
|
+
"react/jsx-runtime": "https://esm.sh/react@19.0.0/jsx-runtime?dev",
|
|
106
|
+
"react/jsx-dev-runtime": "https://esm.sh/react@19.0.0/jsx-dev-runtime?dev",
|
|
107
|
+
"react-dom/client": "https://esm.sh/react-dom@19.0.0/client?dev",
|
|
108
|
+
"@guren/inertia-client": "/vendor/inertia-client.tsx",
|
|
109
|
+
"@inertiajs/react": "https://esm.sh/@inertiajs/react@2.2.15?dev&external=react,react-dom/client"
|
|
110
|
+
};
|
|
111
|
+
async function inertia(component, props, options = {}) {
|
|
112
|
+
const resolvedVersion = options.version ?? process.env.GUREN_INERTIA_VERSION ?? void 0;
|
|
113
|
+
const page = {
|
|
114
|
+
component,
|
|
115
|
+
props,
|
|
116
|
+
url: options.url ?? inertiaPageUrl(options.request) ?? "",
|
|
117
|
+
version: resolvedVersion
|
|
118
|
+
};
|
|
119
|
+
const request = options.request;
|
|
120
|
+
const isInertiaVisit = Boolean(request?.headers.get("X-Inertia"));
|
|
121
|
+
const prefersJson = request ? acceptsJson(request) : false;
|
|
122
|
+
const versionHeader = resolvedVersion ? { "X-Inertia-Version": resolvedVersion } : {};
|
|
123
|
+
if (request && resolvedVersion && isInertiaVisit && request.method === "GET") {
|
|
124
|
+
if (request.headers.get("X-Inertia-Version") !== resolvedVersion) return new Response(null, {
|
|
125
|
+
status: 409,
|
|
126
|
+
headers: {
|
|
127
|
+
"X-Inertia-Location": options.url ?? request.url,
|
|
128
|
+
Vary: "Accept"
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
if (isInertiaVisit || prefersJson) return new Response(serializePage(page), {
|
|
133
|
+
status: options.status ?? 200,
|
|
134
|
+
headers: {
|
|
135
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
136
|
+
"X-Inertia": "true",
|
|
137
|
+
Vary: "Accept",
|
|
138
|
+
...versionHeader,
|
|
139
|
+
...options.headers
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
const html = await renderDocument$1(page, options);
|
|
143
|
+
return new Response(html, {
|
|
144
|
+
status: options.status ?? 200,
|
|
145
|
+
headers: {
|
|
146
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
147
|
+
"X-Inertia": "true",
|
|
148
|
+
Vary: "Accept",
|
|
149
|
+
...versionHeader,
|
|
150
|
+
...options.headers
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* The Inertia protocol's page `url` is the request path plus query string, kept
|
|
156
|
+
* relative. Derived from the request when the caller does not override it.
|
|
157
|
+
*/
|
|
158
|
+
function inertiaPageUrl(request) {
|
|
159
|
+
if (!request) return;
|
|
160
|
+
const { pathname, search } = new URL(request.url);
|
|
161
|
+
return `${pathname}${search}`;
|
|
162
|
+
}
|
|
163
|
+
async function renderDocument$1(page, options) {
|
|
164
|
+
const defaultEntry = process.env.GUREN_INERTIA_ENTRY || "/resources/js/app.tsx";
|
|
165
|
+
const entry = options.entry ?? defaultEntry;
|
|
166
|
+
const title = escapeHtml(options.title ?? DEFAULT_TITLE);
|
|
167
|
+
const isProduction = process.env.NODE_ENV === "production";
|
|
168
|
+
const configuredStyles = options.styles ?? parseStylesEnv(process.env.GUREN_INERTIA_STYLES);
|
|
169
|
+
const styles = !isProduction && options.styles === void 0 && isDevServerEntry(entry) ? configuredStyles.filter((href) => href !== DEFAULT_DEV_STYLES_ENTRY) : configuredStyles;
|
|
170
|
+
const envImportMap = parseImportMap(process.env.GUREN_INERTIA_IMPORT_MAP, { context: "GUREN_INERTIA_IMPORT_MAP" });
|
|
171
|
+
const importMapEntries = {
|
|
172
|
+
...isProduction ? {} : DEV_FALLBACK_IMPORT_MAP,
|
|
173
|
+
...envImportMap,
|
|
174
|
+
...options.importMap
|
|
175
|
+
};
|
|
176
|
+
const importMap = JSON.stringify({ imports: importMapEntries }, null, 2);
|
|
177
|
+
const stylesheetLinks = renderStyles(styles);
|
|
178
|
+
const criticalCss = resolveDocumentValue("criticalCss", options, page.component);
|
|
179
|
+
const prepaintScript = resolveDocumentValue("prepaintScript", options, page.component);
|
|
180
|
+
const headMarkup = resolveDocumentValue("head", options, page.component);
|
|
181
|
+
const ssrResult = await tryRenderSsr(page, options);
|
|
182
|
+
const headElements = (ssrResult?.head ?? []).map(normalizeHeadElement);
|
|
183
|
+
const hasCustomTitle = headElements.some((element) => /<title\b[^>]*>/iu.test(element));
|
|
184
|
+
const appMarkup = ssrResult === void 0 ? `${pagePayloadElement(page)}<div id="app"></div>` : ssrResult.pageEmbedded ? ssrResult.body : `${ssrResult.body}${pagePayloadElement(page)}`;
|
|
185
|
+
const headSegments = [
|
|
186
|
+
"<meta charset=\"utf-8\" />",
|
|
187
|
+
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />",
|
|
188
|
+
hasCustomTitle ? "" : `<title>${title}</title>`,
|
|
189
|
+
headMarkup ?? "",
|
|
190
|
+
criticalCss ? `<style id="guren-critical">${criticalCss}</style>` : "",
|
|
191
|
+
prepaintScript ? `<script>${prepaintScript}<\/script>` : "",
|
|
192
|
+
stylesheetLinks,
|
|
193
|
+
...headElements,
|
|
194
|
+
Object.keys(importMapEntries).length > 0 ? `<script type="importmap">${importMap}<\/script>` : ""
|
|
195
|
+
].filter((segment) => segment && segment.length > 0);
|
|
196
|
+
const bodyClass = resolveDocumentValue("bodyClass", options, page.component);
|
|
197
|
+
const bodyAttributes = bodyClass ? ` class="${escapeAttribute(bodyClass)}"` : "";
|
|
198
|
+
return `<!DOCTYPE html>
|
|
199
|
+
<html lang="${escapeAttribute(options.lang ?? "en")}">
|
|
200
|
+
<head>
|
|
201
|
+
${headSegments.join("\n ")}
|
|
202
|
+
</head>
|
|
203
|
+
<body${bodyAttributes}>
|
|
204
|
+
${appMarkup}${PAGE_GLOBAL_FROM_ELEMENT}
|
|
205
|
+
<script type="module" src="${entry}"><\/script>
|
|
206
|
+
</body>
|
|
207
|
+
</html>`;
|
|
208
|
+
}
|
|
209
|
+
function pagePayloadElement(page) {
|
|
210
|
+
return `<script data-page="app" type="application/json">${serializePage(page)}<\/script>`;
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* `window.__INERTIA_PAGE__` for readers other than the client. Same selector
|
|
214
|
+
* and guards as the client's `getInitialPage` (@guren/inertia-client), so a
|
|
215
|
+
* container carrying a non-payload `data-page` is ignored rather than mounted.
|
|
216
|
+
* A classic inline script, so it has run before the module entry does.
|
|
217
|
+
*/
|
|
218
|
+
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>";
|
|
219
|
+
async function tryRenderSsr(page, options) {
|
|
220
|
+
const ssrOptions = options.ssr;
|
|
221
|
+
if (ssrOptions?.enabled === false) return;
|
|
222
|
+
const manifest = (ssrOptions?.manifest ?? process.env.GUREN_INERTIA_SSR_MANIFEST)?.trim() || void 0;
|
|
223
|
+
const renderer = ssrOptions?.render ?? resolveOptional(options.container, "inertia.ssrRenderer") ?? defaultSsrRenderer ?? await loadSsrRenderer(ssrOptions?.entry ?? process.env.GUREN_INERTIA_SSR_ENTRY);
|
|
224
|
+
if (!renderer) return;
|
|
225
|
+
try {
|
|
226
|
+
const result = await renderer({
|
|
227
|
+
page,
|
|
228
|
+
request: options.request,
|
|
229
|
+
manifest
|
|
230
|
+
});
|
|
231
|
+
if (!result || typeof result.body !== "string") return;
|
|
232
|
+
return {
|
|
233
|
+
body: result.body,
|
|
234
|
+
head: Array.isArray(result.head) ? result.head : [],
|
|
235
|
+
pageEmbedded: result.pageEmbedded === true
|
|
236
|
+
};
|
|
237
|
+
} catch (error) {
|
|
238
|
+
console.error("Inertia SSR renderer failed; falling back to client rendering.", error);
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
async function loadSsrRenderer(entry) {
|
|
243
|
+
const specifier = entry?.trim();
|
|
244
|
+
if (!specifier) return;
|
|
245
|
+
const normalized = normalizeSsrSpecifier(specifier);
|
|
246
|
+
try {
|
|
247
|
+
const renderCandidate = extractSsrRenderer(await import(normalized));
|
|
248
|
+
if (!renderCandidate) {
|
|
249
|
+
console.warn(`Inertia SSR entry "${specifier}" does not export a renderer. Expected a default export or a named "render" function.`);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
return renderCandidate;
|
|
253
|
+
} catch (error) {
|
|
254
|
+
console.error(`Failed to import Inertia SSR entry "${specifier}".`, error);
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
function extractSsrRenderer(module) {
|
|
259
|
+
if (!module || typeof module !== "object") return;
|
|
260
|
+
const candidate = typeof module.render === "function" ? module.render : typeof module.default === "function" ? module.default : void 0;
|
|
261
|
+
if (!candidate) return;
|
|
262
|
+
return (context) => Promise.resolve(candidate(context));
|
|
263
|
+
}
|
|
264
|
+
function normalizeSsrSpecifier(specifier) {
|
|
265
|
+
if (specifier.startsWith("file://") || isUrlLike(specifier)) return specifier;
|
|
266
|
+
if (specifier.startsWith("./") || specifier.startsWith("../")) {
|
|
267
|
+
const absolute = resolve(process.cwd(), specifier);
|
|
268
|
+
return pathToFileURL(absolute).href;
|
|
269
|
+
}
|
|
270
|
+
if (isAbsolute(specifier)) return pathToFileURL(specifier).href;
|
|
271
|
+
return specifier;
|
|
272
|
+
}
|
|
273
|
+
function isUrlLike(specifier) {
|
|
274
|
+
return /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(specifier);
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* An absolute http(s) entry means an asset dev server (Vite) is serving the
|
|
278
|
+
* module graph; a same-origin path means source files are served directly,
|
|
279
|
+
* where the raw stylesheet link is the only styling.
|
|
280
|
+
*/
|
|
281
|
+
function isDevServerEntry(entry) {
|
|
282
|
+
return /^https?:\/\//iu.test(entry);
|
|
283
|
+
}
|
|
284
|
+
function renderStyles(styles) {
|
|
285
|
+
if (!styles.length) return "";
|
|
286
|
+
return styles.map((href) => `<link rel="stylesheet" href="${escapeAttribute(href)}" />`).join("\n ");
|
|
287
|
+
}
|
|
288
|
+
function normalizeHeadElement(element) {
|
|
289
|
+
return (typeof element === "string" ? element : String(element ?? "")).replace(/href="\/(?!public\/)([^"?]+\.(?:js|css))(\?[^"']*)?"/g, (_match, file, query = "") => `href="/public/assets/${file}${query}"`);
|
|
290
|
+
}
|
|
291
|
+
/** One document field: per-response override, then app-wide default, then "". */
|
|
292
|
+
function resolveDocumentValue(key, options, componentName) {
|
|
293
|
+
const override = options[key];
|
|
294
|
+
if (override !== void 0) return override;
|
|
295
|
+
const value = (resolveOptional(options.container, "inertia.document") ?? documentOptions)?.[key];
|
|
296
|
+
return (typeof value === "function" ? value({ component: componentName }) : value) ?? "";
|
|
297
|
+
}
|
|
298
|
+
function serializePage(page) {
|
|
299
|
+
return JSON.stringify(page).replace(/[<\u2028\u2029]/gu, (char) => {
|
|
300
|
+
switch (char) {
|
|
301
|
+
case "<": return "\\u003c";
|
|
302
|
+
case "\u2028": return "\\u2028";
|
|
303
|
+
case "\u2029": return "\\u2029";
|
|
304
|
+
default: return char;
|
|
305
|
+
}
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
function acceptsJson(request) {
|
|
309
|
+
const accept = request.headers.get("accept")?.toLowerCase() ?? "";
|
|
310
|
+
if (!accept || accept === "*/*") return false;
|
|
311
|
+
if (accept.includes("text/html")) return false;
|
|
312
|
+
return accept.includes("application/json") || accept.includes("json");
|
|
313
|
+
}
|
|
314
|
+
function escapeHtml(value) {
|
|
315
|
+
return value.replace(/[&<>"']/gu, (char) => {
|
|
316
|
+
switch (char) {
|
|
317
|
+
case "&": return "&";
|
|
318
|
+
case "<": return "<";
|
|
319
|
+
case ">": return ">";
|
|
320
|
+
case "\"": return """;
|
|
321
|
+
case "'": return "'";
|
|
322
|
+
default: return char;
|
|
323
|
+
}
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
function escapeAttribute(value) {
|
|
327
|
+
return value.replace(/[&"]/gu, (char) => {
|
|
328
|
+
if (char === "&") return "&";
|
|
329
|
+
return """;
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
function parseStylesEnv(value) {
|
|
333
|
+
if (!value) return [];
|
|
334
|
+
return value.split(",").map((item) => item.trim()).filter((item) => item.length > 0);
|
|
335
|
+
}
|
|
336
|
+
//#endregion
|
|
337
|
+
//#region src/mvc/inertia/shared.ts
|
|
338
|
+
/** Container binding key for the scoped {@link SharedInertiaPropsRegistry}. */
|
|
339
|
+
const INERTIA_SHARED_PROPS_BINDING = "inertia.sharedProps";
|
|
340
|
+
/**
|
|
341
|
+
* Registrations are numbered from one process-wide counter so that props keep
|
|
342
|
+
* resolving in registration order — later registrations win on conflicting
|
|
343
|
+
* keys — no matter which registry each one landed in.
|
|
344
|
+
*/
|
|
345
|
+
let registrationSequence = 0;
|
|
346
|
+
/**
|
|
347
|
+
* Holds the shared-props resolvers for one scope: either a single
|
|
348
|
+
* Application's container or the module-global fallback for bare-Hono apps.
|
|
349
|
+
*/
|
|
350
|
+
var SharedInertiaPropsRegistry = class {
|
|
351
|
+
resolvers = [];
|
|
352
|
+
/** Replace every resolver registered in this scope. */
|
|
353
|
+
set(resolverFn) {
|
|
354
|
+
this.resolvers = resolverFn ? [orderedResolver(resolverFn)] : [];
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Register additional shared props without replacing resolvers registered
|
|
358
|
+
* earlier — the new resolver's props are merged over the previous ones.
|
|
359
|
+
*/
|
|
360
|
+
share(resolverFn) {
|
|
361
|
+
this.resolvers.push(orderedResolver(resolverFn));
|
|
362
|
+
}
|
|
363
|
+
/** The resolvers registered in this scope, ordered by registration. */
|
|
364
|
+
entries() {
|
|
365
|
+
return this.resolvers;
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* The scope's registrations composed into one resolver, or null when empty.
|
|
369
|
+
* The composition is a snapshot: resolvers registered later are not picked up.
|
|
370
|
+
*/
|
|
371
|
+
get() {
|
|
372
|
+
if (this.resolvers.length === 0) return null;
|
|
373
|
+
if (this.resolvers.length === 1) return this.resolvers[0].resolve;
|
|
374
|
+
const snapshot = [...this.resolvers];
|
|
375
|
+
return (ctx) => applyResolvers(snapshot, ctx);
|
|
376
|
+
}
|
|
377
|
+
async resolve(ctx) {
|
|
378
|
+
return applyResolvers(this.resolvers, ctx);
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
function orderedResolver(resolverFn) {
|
|
382
|
+
return {
|
|
383
|
+
seq: registrationSequence++,
|
|
384
|
+
resolve: resolverFn
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
async function applyResolvers(entries, ctx) {
|
|
388
|
+
const merged = {};
|
|
389
|
+
for (const entry of entries) {
|
|
390
|
+
const props = await entry.resolve(ctx);
|
|
391
|
+
if (props && typeof props === "object") Object.assign(merged, props);
|
|
392
|
+
}
|
|
393
|
+
return merged;
|
|
394
|
+
}
|
|
395
|
+
const globalRegistry = new SharedInertiaPropsRegistry();
|
|
396
|
+
/** The registry bound to `container`, or null when it owns none yet. */
|
|
397
|
+
function scopedRegistry(container) {
|
|
398
|
+
if (!container?.has?.("inertia.sharedProps")) return null;
|
|
399
|
+
return container.make(INERTIA_SHARED_PROPS_BINDING);
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* The shared-props registry scoped to `container`, binding a fresh one on
|
|
403
|
+
* first use.
|
|
404
|
+
*/
|
|
405
|
+
function ensureSharedInertiaPropsRegistry(container) {
|
|
406
|
+
const existing = scopedRegistry(container);
|
|
407
|
+
if (existing) return existing;
|
|
408
|
+
const registry = new SharedInertiaPropsRegistry();
|
|
409
|
+
container.instance(INERTIA_SHARED_PROPS_BINDING, registry);
|
|
410
|
+
return registry;
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Replace the module-global shared props resolver. Props registered on an
|
|
414
|
+
* application's container (see {@link shareInertiaProps}) are unaffected.
|
|
415
|
+
* @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Use
|
|
416
|
+
* `shareInertiaProps(fn, container)`, which scopes the registration to one app.
|
|
417
|
+
* It composes rather than replaces, so a wholesale reset becomes one
|
|
418
|
+
* registration on a fresh container.
|
|
419
|
+
*/
|
|
420
|
+
function setInertiaSharedProps(resolverFn) {
|
|
421
|
+
warnDeprecatedSetter("setInertiaSharedProps");
|
|
422
|
+
globalRegistry.set(resolverFn);
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* The module-global registrations composed into one resolver, for manual
|
|
426
|
+
* composition. Container-scoped props are not included — get those from
|
|
427
|
+
* `ensureSharedInertiaPropsRegistry(container).get()`.
|
|
428
|
+
* @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Use
|
|
429
|
+
* `ensureSharedInertiaPropsRegistry(container).get()` on the container that owns
|
|
430
|
+
* the call.
|
|
431
|
+
*/
|
|
432
|
+
function getInertiaSharedPropsResolver() {
|
|
433
|
+
warnDeprecatedGetter("getInertiaSharedPropsResolver");
|
|
434
|
+
return globalRegistry.get();
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Register additional shared props without replacing earlier resolvers, so
|
|
438
|
+
* several providers can each contribute (`setInertiaSharedProps` replaces
|
|
439
|
+
* wholesale). Pass the provider's `this.container` to scope them; without it
|
|
440
|
+
* they are module-global and a second Application in the process shares them.
|
|
441
|
+
*/
|
|
442
|
+
function shareInertiaProps(resolverFn, container) {
|
|
443
|
+
(container ? ensureSharedInertiaPropsRegistry(container) : globalRegistry).share(resolverFn);
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Resolve shared props for a request, merging the module-global registrations
|
|
447
|
+
* with those scoped to `container` in registration order.
|
|
448
|
+
*/
|
|
449
|
+
async function resolveSharedInertiaProps(ctx, container) {
|
|
450
|
+
const scoped = scopedRegistry(container);
|
|
451
|
+
if (!scoped) return globalRegistry.resolve(ctx);
|
|
452
|
+
const globalEntries = globalRegistry.entries();
|
|
453
|
+
if (globalEntries.length === 0) return scoped.resolve(ctx);
|
|
454
|
+
return applyResolvers([...globalEntries, ...scoped.entries()].sort((a, b) => a.seq - b.seq), ctx);
|
|
455
|
+
}
|
|
456
|
+
//#endregion
|
|
457
|
+
//#region src/container/definePlugin.ts
|
|
458
|
+
/**
|
|
459
|
+
* Define a configurable Guren plugin without ServiceProvider boilerplate. Each
|
|
460
|
+
* factory call returns a fresh provider class, so the same plugin can be
|
|
461
|
+
* registered twice with different configurations.
|
|
462
|
+
*/
|
|
463
|
+
function definePlugin(definition) {
|
|
464
|
+
const className = `${definition.name}PluginProvider`;
|
|
465
|
+
return (config) => {
|
|
466
|
+
class ConfiguredPluginProvider extends ServiceProvider {
|
|
467
|
+
static deferred = definition.deferred ?? false;
|
|
468
|
+
static provides = definition.provides ?? [];
|
|
469
|
+
register() {
|
|
470
|
+
return definition.register(this.container, config);
|
|
471
|
+
}
|
|
472
|
+
boot() {
|
|
473
|
+
return definition.boot?.(this.container, config);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
Object.defineProperty(ConfiguredPluginProvider, "name", { value: className });
|
|
477
|
+
return ConfiguredPluginProvider;
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
//#endregion
|
|
481
|
+
//#region src/container/defineModule.ts
|
|
482
|
+
/** Define a Guren application module without boilerplate. */
|
|
483
|
+
function defineModule(definition) {
|
|
484
|
+
return {
|
|
485
|
+
name: definition.name,
|
|
486
|
+
prefix: definition.prefix,
|
|
487
|
+
routes: definition.routes,
|
|
488
|
+
providers: definition.providers ?? [],
|
|
489
|
+
commands: definition.commands ?? []
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
/**
|
|
493
|
+
* Runs a module's route registrar, applying its `prefix` via `router.group()`.
|
|
494
|
+
* Shared by `Application.mountRoutes()` and the CLI's route loader, so both see
|
|
495
|
+
* the same route set. `router.group()`'s callback is synchronous (prefix
|
|
496
|
+
* pushed, callback run, prefix popped), so route calls made after an `await`
|
|
497
|
+
* inside an async prefixed registrar run with the prefix already popped.
|
|
498
|
+
*/
|
|
499
|
+
async function mountModuleRoutes(router, gurenModule) {
|
|
500
|
+
const registrar = gurenModule.routes;
|
|
501
|
+
if (!registrar) return;
|
|
502
|
+
if (!gurenModule.prefix) {
|
|
503
|
+
await registrar(router);
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
let pending = void 0;
|
|
507
|
+
router.group(gurenModule.prefix, (grouped) => {
|
|
508
|
+
pending = registrar(grouped);
|
|
509
|
+
});
|
|
510
|
+
await pending;
|
|
511
|
+
}
|
|
512
|
+
//#endregion
|
|
513
|
+
//#region src/http/middleware/detect-locale.ts
|
|
514
|
+
/** Context key for the resolved request locale (read by Inertia for `<html lang>`). */
|
|
515
|
+
const LOCALE_CONTEXT_KEY = "locale";
|
|
516
|
+
/** Reads the `locale` context variable, whoever set it. */
|
|
517
|
+
function getRequestLocale(c) {
|
|
518
|
+
const locale = c.var?.[LOCALE_CONTEXT_KEY];
|
|
519
|
+
return typeof locale === "string" && locale.length > 0 ? locale : void 0;
|
|
520
|
+
}
|
|
521
|
+
/** The request-scoped translator bound by {@link detectLocaleMiddleware}. */
|
|
522
|
+
function getRequestTranslator(c) {
|
|
523
|
+
const vars = c.var;
|
|
524
|
+
const t = vars?.["t"];
|
|
525
|
+
const tc = vars?.["tc"];
|
|
526
|
+
return typeof t === "function" && typeof tc === "function" ? {
|
|
527
|
+
t,
|
|
528
|
+
tc
|
|
529
|
+
} : void 0;
|
|
530
|
+
}
|
|
531
|
+
const DEFAULT_SOURCES = [
|
|
532
|
+
"query",
|
|
533
|
+
"cookie",
|
|
534
|
+
"header"
|
|
535
|
+
];
|
|
536
|
+
/**
|
|
537
|
+
* Resolves the request locale from the query string, a cookie, or
|
|
538
|
+
* `Accept-Language`, restricted to the `supported` allowlist, and stores it as
|
|
539
|
+
* the `locale` context variable that Inertia reads for `<html lang>`.
|
|
540
|
+
*/
|
|
541
|
+
function detectLocaleMiddleware(options) {
|
|
542
|
+
const supported = options.supported.map((locale) => locale.trim()).filter(Boolean);
|
|
543
|
+
if (supported.length === 0) throw new Error("detectLocaleMiddleware requires at least one supported locale.");
|
|
544
|
+
const fallback = options.fallback ?? supported[0];
|
|
545
|
+
const sources = options.sources ?? DEFAULT_SOURCES;
|
|
546
|
+
const queryParam = options.queryParam ?? "locale";
|
|
547
|
+
const cookieName = options.cookieName ?? "locale";
|
|
548
|
+
const byLowerCase = new Map(supported.map((locale) => [locale.toLowerCase(), locale]));
|
|
549
|
+
const match = (candidate) => {
|
|
550
|
+
const value = candidate?.trim().toLowerCase();
|
|
551
|
+
if (!value) return;
|
|
552
|
+
return byLowerCase.get(value) ?? byLowerCase.get(value.split("-")[0]);
|
|
553
|
+
};
|
|
554
|
+
const matchHeader = (header) => {
|
|
555
|
+
if (!header) return;
|
|
556
|
+
for (const accept of parseAccept(header)) {
|
|
557
|
+
if (accept.type === "*" || accept.q <= 0) continue;
|
|
558
|
+
const matched = match(accept.type);
|
|
559
|
+
if (matched) return matched;
|
|
560
|
+
}
|
|
561
|
+
};
|
|
562
|
+
const translators = /* @__PURE__ */ new Map();
|
|
563
|
+
const supportedSet = new Set(supported);
|
|
564
|
+
const bindingFor = (locale, i18n) => {
|
|
565
|
+
const cached = translators.get(locale);
|
|
566
|
+
if (cached) return cached;
|
|
567
|
+
const translator = i18n.forLocale(locale);
|
|
568
|
+
const binding = {
|
|
569
|
+
t: translator.t.bind(translator),
|
|
570
|
+
tc: translator.tc.bind(translator)
|
|
571
|
+
};
|
|
572
|
+
if (supportedSet.has(locale) && i18n.isLocaleLoaded(locale)) translators.set(locale, binding);
|
|
573
|
+
return binding;
|
|
574
|
+
};
|
|
575
|
+
return createMiddleware(async (c, next) => {
|
|
576
|
+
const readers = {
|
|
577
|
+
query: () => match(c.req.query(queryParam)),
|
|
578
|
+
cookie: () => match(getCookie(c, cookieName)),
|
|
579
|
+
header: () => matchHeader(c.req.header("Accept-Language"))
|
|
580
|
+
};
|
|
581
|
+
let resolved = fallback;
|
|
582
|
+
for (const source of sources) {
|
|
583
|
+
const matched = readers[source]();
|
|
584
|
+
if (matched) {
|
|
585
|
+
resolved = matched;
|
|
586
|
+
break;
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
c.set(LOCALE_CONTEXT_KEY, resolved);
|
|
590
|
+
const i18n = options.i18n === false ? void 0 : options.i18n ?? tryGetRequestContainer(c)?.makeOptional("i18n") ?? resolveI18n();
|
|
591
|
+
if (i18n) {
|
|
592
|
+
await i18n.loadLocale(resolved).catch(() => {});
|
|
593
|
+
const current = () => bindingFor(getRequestLocale(c) ?? resolved, i18n);
|
|
594
|
+
c.set("t", (key, replacements) => current().t(key, replacements));
|
|
595
|
+
c.set("tc", (key, count, replacements) => current().tc(key, count, replacements));
|
|
596
|
+
}
|
|
597
|
+
await next();
|
|
598
|
+
});
|
|
599
|
+
}
|
|
600
|
+
//#endregion
|
|
601
|
+
//#region src/mvc/view.ts
|
|
602
|
+
/**
|
|
603
|
+
* Does the output begin with an `<html>` root, allowing leading whitespace and
|
|
604
|
+
* complete comments? A linear scan rather than a regex: the equivalent pattern
|
|
605
|
+
* backtracks exponentially on adversarial comment runs (CodeQL js/redos), and
|
|
606
|
+
* the scanned body can embed user-influenced raw markup.
|
|
607
|
+
*/
|
|
608
|
+
function startsWithHtmlRoot(body) {
|
|
609
|
+
let i = 0;
|
|
610
|
+
while (i < body.length) {
|
|
611
|
+
const ch = body.charCodeAt(i);
|
|
612
|
+
if (ch === 32 || ch >= 9 && ch <= 13) {
|
|
613
|
+
i++;
|
|
614
|
+
continue;
|
|
615
|
+
}
|
|
616
|
+
if (body.startsWith("<!--", i)) {
|
|
617
|
+
const end = body.indexOf("-->", i + 4);
|
|
618
|
+
if (end === -1) return false;
|
|
619
|
+
i = end + 3;
|
|
620
|
+
continue;
|
|
621
|
+
}
|
|
622
|
+
break;
|
|
623
|
+
}
|
|
624
|
+
if (body.slice(i, i + 5).toLowerCase() !== "<html") return false;
|
|
625
|
+
const next = body.charCodeAt(i + 5);
|
|
626
|
+
return next === 62 || next === 32 || next >= 9 && next <= 13;
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* Render a `hono/jsx` component to a plain server-rendered HTML `Response` —
|
|
630
|
+
* the engine behind `Controller.view()` (RFC 0014).
|
|
631
|
+
*/
|
|
632
|
+
async function renderDocument(component, props, options = {}) {
|
|
633
|
+
const body = String(await (0, jsx_runtime_exports.jsx)(component, props, void 0).toString());
|
|
634
|
+
if (options.doctype !== false && !startsWithHtmlRoot(body)) {
|
|
635
|
+
const name = component.displayName ?? component.name ?? "component";
|
|
636
|
+
throw new Error(`view(): ${name} rendered a fragment, not a document. Wrap the page in your Layout (an <html> root), or pass { doctype: false } for an intentional fragment response. Without <html>/<head>, <title> and <meta> tags are not hoisted and the page ships unstyled.`);
|
|
637
|
+
}
|
|
638
|
+
const { doctype, headers: headersInit, ...init } = options;
|
|
639
|
+
const headers = new Headers(headersInit);
|
|
640
|
+
if (!headers.has("content-type")) headers.set("content-type", "text/html; charset=utf-8");
|
|
641
|
+
return new Response((doctype === false ? "" : "<!doctype html>") + body, {
|
|
642
|
+
...init,
|
|
643
|
+
headers
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
//#endregion
|
|
647
|
+
//#region src/mvc/Controller.ts
|
|
648
|
+
/**
|
|
649
|
+
* Base controller inspired by Laravel's expressive API. Subclasses reach the
|
|
650
|
+
* Hono context through the protected `ctx` getter. Dependencies are declared
|
|
651
|
+
* with `static inject = ['cache'] as const` and passed to the constructor.
|
|
652
|
+
*/
|
|
653
|
+
var Controller = class {
|
|
654
|
+
/** Services to resolve from the container and pass to the constructor. */
|
|
655
|
+
static inject;
|
|
656
|
+
context;
|
|
657
|
+
parsedBody;
|
|
658
|
+
resolvedModels;
|
|
659
|
+
_container;
|
|
660
|
+
setContext(context) {
|
|
661
|
+
this.context = context;
|
|
662
|
+
}
|
|
663
|
+
/** @internal Called by the router to inject the DI container. */
|
|
664
|
+
setContainer(container) {
|
|
665
|
+
this._container = container;
|
|
666
|
+
}
|
|
667
|
+
/** @internal Called by the router to store a route-bound model instance. */
|
|
668
|
+
setResolvedModel(modelClass, instance) {
|
|
669
|
+
if (!this.resolvedModels) this.resolvedModels = /* @__PURE__ */ new Map();
|
|
670
|
+
this.resolvedModels.set(modelClass, instance);
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* Retrieve a model instance resolved via route model binding — a per-route
|
|
674
|
+
* `bind` option or a router-level `router.bind(param, Model)`. The class
|
|
675
|
+
* alone looks up by primary key, a `[Model, column]` tuple by that column.
|
|
676
|
+
*/
|
|
677
|
+
model(modelClass) {
|
|
678
|
+
const instance = this.resolvedModels?.get(modelClass);
|
|
679
|
+
if (instance === void 0) throw new Error(`No model binding found for ${modelClass.name ?? "unknown"}. Ensure the route has a matching bind option in RouteContractOptions, or the router a bind(param, Model) call.`);
|
|
680
|
+
return instance;
|
|
681
|
+
}
|
|
682
|
+
get ctx() {
|
|
683
|
+
if (!this.context) throw new Error("Controller context has not been set.");
|
|
684
|
+
return this.context;
|
|
685
|
+
}
|
|
686
|
+
get request() {
|
|
687
|
+
return this.ctx.req;
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* Get an uploaded file from a multipart request. Returns null when the field
|
|
691
|
+
* is missing, is not a file, or the upload is empty. Hono caches the parsed
|
|
692
|
+
* body, so this composes with other body reads in the same request.
|
|
693
|
+
*/
|
|
694
|
+
async file(name) {
|
|
695
|
+
const value = (await parseRequestUploads(this.ctx))[name];
|
|
696
|
+
const candidate = Array.isArray(value) ? value[0] : value;
|
|
697
|
+
return candidate instanceof File && candidate.size > 0 ? candidate : null;
|
|
698
|
+
}
|
|
699
|
+
/**
|
|
700
|
+
* Get all uploaded files for a multipart field (e.g. `<input multiple>`).
|
|
701
|
+
* Returns an empty array when none were uploaded.
|
|
702
|
+
*/
|
|
703
|
+
async files(name) {
|
|
704
|
+
const value = (await parseRequestUploads(this.ctx))[name];
|
|
705
|
+
return (Array.isArray(value) ? value : value !== void 0 ? [value] : []).filter((item) => item instanceof File && item.size > 0);
|
|
706
|
+
}
|
|
707
|
+
get auth() {
|
|
708
|
+
const auth = getAuthContext(this.ctx);
|
|
709
|
+
if (!auth) throw new Error("Controller auth helper requires the auth middleware. Make sure AuthServiceProvider is registered.");
|
|
710
|
+
return auth;
|
|
711
|
+
}
|
|
712
|
+
make(key) {
|
|
713
|
+
if (!this._container) throw new Error("Controller.make() requires a DI container. Ensure the app is booted with a Container.");
|
|
714
|
+
return this._container.make(key);
|
|
715
|
+
}
|
|
716
|
+
/** Get the authenticated API token, or throw AuthenticationException. */
|
|
717
|
+
apiToken() {
|
|
718
|
+
return getApiTokenOrFail(this.ctx);
|
|
719
|
+
}
|
|
720
|
+
/** Get the authenticated user ID from the API token. */
|
|
721
|
+
apiTokenUserId() {
|
|
722
|
+
return this.apiToken().userId;
|
|
723
|
+
}
|
|
724
|
+
/**
|
|
725
|
+
* Authorize the current user (or guest) for an ability; throws
|
|
726
|
+
* AuthorizationException (403) when denied. ORM records are plain objects
|
|
727
|
+
* with no constructor information, so pass the model class alongside the
|
|
728
|
+
* record: `await this.authorize('update', [Post, post])`.
|
|
729
|
+
*/
|
|
730
|
+
async authorize(ability, ...args) {
|
|
731
|
+
await this.#resolveGate().forUser(await this.gateUser()).authorize(ability, ...args);
|
|
732
|
+
}
|
|
733
|
+
/** Check an ability without throwing: `await this.can('update', [Post, post])`. */
|
|
734
|
+
async can(ability, ...args) {
|
|
735
|
+
return this.#resolveGate().forUser(await this.gateUser()).allows(ability, ...args);
|
|
736
|
+
}
|
|
737
|
+
/** This app's `gate` (RFC 0023 §2); the ambient one only off a container, as on a bare Hono app. */
|
|
738
|
+
#resolveGate() {
|
|
739
|
+
return resolveOptional(this._container, "gate") ?? resolveGate();
|
|
740
|
+
}
|
|
741
|
+
async gateUser() {
|
|
742
|
+
const auth = getAuthContext(this.ctx);
|
|
743
|
+
if (!auth) return null;
|
|
744
|
+
return await auth.user();
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* Render a `hono/jsx` component to a plain server-rendered HTML response —
|
|
748
|
+
* the non-hydrating counterpart to {@link inertia} (RFC 0014). Escaping
|
|
749
|
+
* covers markup only, not URL schemes: a `javascript:` href built from user
|
|
750
|
+
* data is emitted verbatim, so sanitize user-supplied URLs upstream.
|
|
751
|
+
*/
|
|
752
|
+
view(component, props, options) {
|
|
753
|
+
return renderDocument(component, props, options);
|
|
754
|
+
}
|
|
755
|
+
async inertia(componentOrPage, props, options = {}) {
|
|
756
|
+
const ctx = this.ctx;
|
|
757
|
+
const component = typeof componentOrPage === "string" ? componentOrPage : componentOrPage.component ?? componentOrPage.id;
|
|
758
|
+
const propsWithShared = {
|
|
759
|
+
...await resolveSharedInertiaProps(ctx, this._container),
|
|
760
|
+
...props
|
|
761
|
+
};
|
|
762
|
+
const response = await inertia(component, propsWithShared, {
|
|
763
|
+
...options,
|
|
764
|
+
lang: options.lang ?? this.#resolveLocale(),
|
|
765
|
+
request: ctx.req.raw,
|
|
766
|
+
container: this._container
|
|
767
|
+
});
|
|
768
|
+
response.__gurenInertia = {
|
|
769
|
+
component,
|
|
770
|
+
props: propsWithShared
|
|
771
|
+
};
|
|
772
|
+
return response;
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* Locale for the current request: the request-scoped `locale` context
|
|
776
|
+
* variable wins over the app-wide i18n locale. Falls back to `'en'`.
|
|
777
|
+
*/
|
|
778
|
+
get locale() {
|
|
779
|
+
return this.#resolveLocale() ?? "en";
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* Translate a key for the current request locale, using the request-scoped
|
|
783
|
+
* translator the locale middleware bound, else one scoped to `this.locale`.
|
|
784
|
+
*/
|
|
785
|
+
t(key, replacements) {
|
|
786
|
+
return this.#requestTranslator().t(key, replacements);
|
|
787
|
+
}
|
|
788
|
+
/**
|
|
789
|
+
* Translate a key with a count for pluralization, using the same locale
|
|
790
|
+
* resolution as {@link Controller.t}.
|
|
791
|
+
*/
|
|
792
|
+
tc(key, count, replacements) {
|
|
793
|
+
return this.#requestTranslator().tc(key, count, replacements);
|
|
794
|
+
}
|
|
795
|
+
#requestTranslator() {
|
|
796
|
+
const bound = getRequestTranslator(this.ctx);
|
|
797
|
+
if (bound) return bound;
|
|
798
|
+
const i18n = this.#resolveI18n();
|
|
799
|
+
if (!i18n) throw new Error("Controller i18n helpers require i18n to be configured. Pass createApp({ i18n }) or register an I18nManager.");
|
|
800
|
+
const locale = getRequestLocale(this.ctx);
|
|
801
|
+
return locale && locale !== i18n.getLocale() ? i18n.forLocale(locale) : i18n;
|
|
802
|
+
}
|
|
803
|
+
#resolveLocale() {
|
|
804
|
+
const requestLocale = getRequestLocale(this.ctx);
|
|
805
|
+
if (requestLocale) return requestLocale;
|
|
806
|
+
const locale = this.#resolveI18n()?.getLocale();
|
|
807
|
+
return typeof locale === "string" && locale.length > 0 ? locale : void 0;
|
|
808
|
+
}
|
|
809
|
+
#resolveI18n() {
|
|
810
|
+
return resolveOptional(this._container, "i18n") ?? resolveI18n();
|
|
811
|
+
}
|
|
812
|
+
json(data, init = {}) {
|
|
813
|
+
return new Response(JSON.stringify(data), {
|
|
814
|
+
...init,
|
|
815
|
+
headers: {
|
|
816
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
817
|
+
...init.headers
|
|
818
|
+
}
|
|
819
|
+
});
|
|
820
|
+
}
|
|
821
|
+
text(body, init = {}) {
|
|
822
|
+
return new Response(body, {
|
|
823
|
+
...init,
|
|
824
|
+
headers: {
|
|
825
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
826
|
+
...init.headers
|
|
827
|
+
}
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
redirect(url, options = {}) {
|
|
831
|
+
const requestMethod = this.request.method?.toUpperCase?.();
|
|
832
|
+
const defaultStatus = requestMethod && requestMethod !== "GET" ? 303 : 302;
|
|
833
|
+
const { status = defaultStatus, headers } = options;
|
|
834
|
+
return new Response(null, {
|
|
835
|
+
status,
|
|
836
|
+
headers: {
|
|
837
|
+
Location: url,
|
|
838
|
+
...headers
|
|
839
|
+
}
|
|
840
|
+
});
|
|
841
|
+
}
|
|
842
|
+
noContent() {
|
|
843
|
+
return new Response(null, { status: 204 });
|
|
844
|
+
}
|
|
845
|
+
created(data, init = {}) {
|
|
846
|
+
return this.jsonStatus(201, data, init);
|
|
847
|
+
}
|
|
848
|
+
accepted(data, init = {}) {
|
|
849
|
+
return this.jsonStatus(202, data, init);
|
|
850
|
+
}
|
|
851
|
+
jsonStatus(status, data, init = {}) {
|
|
852
|
+
if (data === void 0) return new Response(null, {
|
|
853
|
+
status,
|
|
854
|
+
...init
|
|
855
|
+
});
|
|
856
|
+
return new Response(JSON.stringify(data), {
|
|
857
|
+
status,
|
|
858
|
+
...init,
|
|
859
|
+
headers: {
|
|
860
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
861
|
+
...init.headers
|
|
862
|
+
}
|
|
863
|
+
});
|
|
864
|
+
}
|
|
865
|
+
/** Get an input value; body values take precedence over query parameters. */
|
|
866
|
+
async input(key, defaultValue) {
|
|
867
|
+
const body = await this.getBody();
|
|
868
|
+
if (key in body) return body[key];
|
|
869
|
+
const queryValue = this.ctx.req.query(key);
|
|
870
|
+
if (queryValue !== void 0) return queryValue;
|
|
871
|
+
return defaultValue;
|
|
872
|
+
}
|
|
873
|
+
query(key, defaultValue) {
|
|
874
|
+
return this.ctx.req.query(key) ?? defaultValue;
|
|
875
|
+
}
|
|
876
|
+
/** Get only the specified keys from the request body. */
|
|
877
|
+
async only(...keys) {
|
|
878
|
+
const body = await this.getBody();
|
|
879
|
+
const result = {};
|
|
880
|
+
for (const key of keys) if (key in body) result[key] = body[key];
|
|
881
|
+
return result;
|
|
882
|
+
}
|
|
883
|
+
/** Get all request body values except the specified keys. */
|
|
884
|
+
async except(...keys) {
|
|
885
|
+
const body = await this.getBody();
|
|
886
|
+
const excluded = new Set(keys);
|
|
887
|
+
const result = {};
|
|
888
|
+
for (const [key, value] of Object.entries(body)) if (!excluded.has(key)) result[key] = value;
|
|
889
|
+
return result;
|
|
890
|
+
}
|
|
891
|
+
/** Check if a key exists in the request body. */
|
|
892
|
+
async has(key) {
|
|
893
|
+
return key in await this.getBody();
|
|
894
|
+
}
|
|
895
|
+
/** Flatten query string arrays to scalar values for cleaner schema usage. */
|
|
896
|
+
flattenQueries() {
|
|
897
|
+
return flattenRequestQueries(this.ctx);
|
|
898
|
+
}
|
|
899
|
+
validated(route) {
|
|
900
|
+
return readValidatedInput(this.ctx, route);
|
|
901
|
+
}
|
|
902
|
+
/** Validate the request body; throws ValidationException on failure. */
|
|
903
|
+
async validateBody(schema) {
|
|
904
|
+
return this.runValidation(schema, await this.getRawBody());
|
|
905
|
+
}
|
|
906
|
+
/** Validate query parameters; throws ValidationException on failure. */
|
|
907
|
+
validateQuery(schema) {
|
|
908
|
+
return this.runValidation(schema, this.flattenQueries());
|
|
909
|
+
}
|
|
910
|
+
/** Validate route parameters; throws ValidationException on failure. */
|
|
911
|
+
validateParams(schema) {
|
|
912
|
+
const params = this.ctx.req.param();
|
|
913
|
+
return this.runValidation(schema, params);
|
|
914
|
+
}
|
|
915
|
+
/** Validate the request body without throwing; returns data or field errors. */
|
|
916
|
+
async validateBodySafe(schema) {
|
|
917
|
+
return this.runValidationSafe(schema, await this.getRawBody());
|
|
918
|
+
}
|
|
919
|
+
/** Validate query parameters without throwing; returns data or field errors. */
|
|
920
|
+
validateQuerySafe(schema) {
|
|
921
|
+
return this.runValidationSafe(schema, this.flattenQueries());
|
|
922
|
+
}
|
|
923
|
+
/** Validate route parameters without throwing; returns data or field errors. */
|
|
924
|
+
validateParamsSafe(schema) {
|
|
925
|
+
const params = this.ctx.req.param();
|
|
926
|
+
return this.runValidationSafe(schema, params);
|
|
927
|
+
}
|
|
928
|
+
runValidation(schema, data) {
|
|
929
|
+
const result = schema.safeParse(data);
|
|
930
|
+
if (result.success) return result.data;
|
|
931
|
+
throw ValidationException.fromZodError(result.error);
|
|
932
|
+
}
|
|
933
|
+
runValidationSafe(schema, data) {
|
|
934
|
+
const result = schema.safeParse(data);
|
|
935
|
+
if (result.success) return {
|
|
936
|
+
success: true,
|
|
937
|
+
data: result.data
|
|
938
|
+
};
|
|
939
|
+
const errors = {};
|
|
940
|
+
for (const issue of result.error.issues) {
|
|
941
|
+
const field = issue.path.join(".") || issue.message;
|
|
942
|
+
if (!errors[field]) errors[field] = issue.message;
|
|
943
|
+
}
|
|
944
|
+
return {
|
|
945
|
+
success: false,
|
|
946
|
+
errors
|
|
947
|
+
};
|
|
948
|
+
}
|
|
949
|
+
/**
|
|
950
|
+
* The parsed body as sent: an array stays an array, so a non-object contract
|
|
951
|
+
* stays reachable. Boxed rather than memoized by truthiness — `null`, `''`,
|
|
952
|
+
* `0` and `false` are parsed bodies, and re-reading would find the stream
|
|
953
|
+
* consumed. No fallback here: {@link parseRequestBody} already yields `{}`.
|
|
954
|
+
*/
|
|
955
|
+
async getRawBody() {
|
|
956
|
+
if (this.parsedBody) return this.parsedBody.value;
|
|
957
|
+
this.parsedBody = getValidatedInput(this.ctx)?.rawBody ?? { value: await parseRequestBody(this.ctx) };
|
|
958
|
+
return this.parsedBody.value;
|
|
959
|
+
}
|
|
960
|
+
/** The record view of {@link getRawBody}; a non-object body reads as `{}`. */
|
|
961
|
+
async getBody() {
|
|
962
|
+
return asRecord(await this.getRawBody());
|
|
963
|
+
}
|
|
964
|
+
};
|
|
965
|
+
//#endregion
|
|
966
|
+
//#region src/http/resources/Resource.ts
|
|
967
|
+
/**
|
|
968
|
+
* Abstract base class for API resources: transforms model data into an API
|
|
969
|
+
* response payload. `TData` names what `toArray()` builds, so `toJSON()` reports
|
|
970
|
+
* it too; it defaults to `ResourceData` so `Resource<T>` and narrowing overrides
|
|
971
|
+
* keep compiling. `TData` is a claim about `toArray()` only — `additional()` is
|
|
972
|
+
* spread *after* the payload, so a colliding key overwrites a typed field.
|
|
973
|
+
*/
|
|
974
|
+
var Resource = class {
|
|
975
|
+
resource;
|
|
976
|
+
additionalData = {};
|
|
977
|
+
constructor(resource) {
|
|
978
|
+
this.resource = resource;
|
|
979
|
+
}
|
|
980
|
+
toJSON() {
|
|
981
|
+
return {
|
|
982
|
+
...this.toArray(),
|
|
983
|
+
...this.additionalData
|
|
984
|
+
};
|
|
985
|
+
}
|
|
986
|
+
/** Keys merged beside the payload, overriding colliding `toArray()` keys. */
|
|
987
|
+
additional(data) {
|
|
988
|
+
this.additionalData = {
|
|
989
|
+
...this.additionalData,
|
|
990
|
+
...data
|
|
991
|
+
};
|
|
992
|
+
return this;
|
|
993
|
+
}
|
|
994
|
+
when(condition, value) {
|
|
995
|
+
if (!condition) return;
|
|
996
|
+
return typeof value === "function" ? value() : value;
|
|
997
|
+
}
|
|
998
|
+
whenOr(condition, value, defaultValue) {
|
|
999
|
+
if (!condition) return defaultValue;
|
|
1000
|
+
return typeof value === "function" ? value() : value;
|
|
1001
|
+
}
|
|
1002
|
+
/** Loaded means the relation key is present and not `undefined`. */
|
|
1003
|
+
whenLoaded(relation, value, defaultValue) {
|
|
1004
|
+
const resource = this.resource;
|
|
1005
|
+
if (!(relation in resource && resource[relation] !== void 0)) return defaultValue;
|
|
1006
|
+
return typeof value === "function" ? value() : value;
|
|
1007
|
+
}
|
|
1008
|
+
whenNotNull(value) {
|
|
1009
|
+
return value ?? void 0;
|
|
1010
|
+
}
|
|
1011
|
+
merge(data) {
|
|
1012
|
+
return {
|
|
1013
|
+
...this.toArray(),
|
|
1014
|
+
...data
|
|
1015
|
+
};
|
|
1016
|
+
}
|
|
1017
|
+
static make(resource) {
|
|
1018
|
+
return new this(resource);
|
|
1019
|
+
}
|
|
1020
|
+
static collection(resources) {
|
|
1021
|
+
return resources.map((resource) => new this(resource).toJSON());
|
|
1022
|
+
}
|
|
1023
|
+
};
|
|
1024
|
+
/** Create a resource collection from a resource class. */
|
|
1025
|
+
function collect(resources, resourceClass) {
|
|
1026
|
+
return resources.map((resource) => new resourceClass(resource).toJSON());
|
|
1027
|
+
}
|
|
1028
|
+
/** Simple resource wrapper for objects that need no transformation. */
|
|
1029
|
+
var JsonResource = class extends Resource {
|
|
1030
|
+
toArray() {
|
|
1031
|
+
return { ...this.resource };
|
|
1032
|
+
}
|
|
1033
|
+
};
|
|
1034
|
+
//#endregion
|
|
1035
|
+
export { ensureErrorStackTracePolyfill as S, acceptsJson as _, renderDocument as a, setInertiaDocument as b, getRequestLocale as c, mountModuleRoutes as d, definePlugin as f, shareInertiaProps as g, setInertiaSharedProps as h, Controller as i, getRequestTranslator as l, resolveSharedInertiaProps as m, Resource as n, LOCALE_CONTEXT_KEY as o, getInertiaSharedPropsResolver as p, collect as r, detectLocaleMiddleware as s, JsonResource as t, defineModule as u, inertia as v, setInertiaSsrRenderer as x, serializePage as y };
|