@guren/server 2.10.0 → 2.11.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 (91) hide show
  1. package/dist/DocsViewerServiceProvider-qFCaeiUv.js +77 -0
  2. package/dist/Hash-CzrwKeDp.js +133 -0
  3. package/dist/HttpException-BkS3euNG.js +161 -0
  4. package/dist/Job-BVT813DO.js +441 -0
  5. package/dist/McpServiceProvider-BoAN-UcD.js +367 -0
  6. package/dist/MessageSigner-Bd25ZJAV.js +93 -0
  7. package/dist/Random-DbIJ22KQ.js +191 -0
  8. package/dist/address-D0Iq-XIH.js +20 -0
  9. package/dist/auth/index.js +2 -122
  10. package/dist/auth-C7sVmYgc.js +1954 -0
  11. package/dist/authorization/index.js +2 -38
  12. package/dist/authorization-Dbcuc5ZK.js +610 -0
  13. package/dist/broadcasting/index.js +2 -26
  14. package/dist/broadcasting-Dw-FhyjN.js +1055 -0
  15. package/dist/cache/index.js +2 -17
  16. package/dist/cache/types.d.ts +4 -4
  17. package/dist/cache-BYnZf2FR.js +812 -0
  18. package/dist/client-Dd7vLcqp.js +27 -0
  19. package/dist/console/Output.d.ts +18 -18
  20. package/dist/encryption/index.js +5 -96
  21. package/dist/encryption-fOWQaKqX.js +250 -0
  22. package/dist/endpoint-D-20PiHY.js +46 -0
  23. package/dist/endpoint-D6GIqOpe.js +31 -0
  24. package/dist/errors-quJOkkCn.js +81 -0
  25. package/dist/events/index.js +2 -28
  26. package/dist/events-aIH_bWRx.js +410 -0
  27. package/dist/health/index.js +2 -24
  28. package/dist/health-VWdWXRwh.js +345 -0
  29. package/dist/hot-disposables-WsTX2ySN.js +281 -0
  30. package/dist/hot-reload/testing.d.ts +1 -1
  31. package/dist/http/resources/Resource.d.ts +23 -3
  32. package/dist/i18n/index.js +2 -30
  33. package/dist/i18n-mcWi7LCd.js +617 -0
  34. package/dist/index.js +7515 -7276
  35. package/dist/lambda/index.js +114 -71
  36. package/dist/logging/index.js +2 -24
  37. package/dist/logging-CPaRMuPP.js +518 -0
  38. package/dist/loopback-guard-D0Kc7-xc.js +224 -0
  39. package/dist/mail/index.js +2 -27
  40. package/dist/mail-DfEfSQEr.js +699 -0
  41. package/dist/mcp/index.js +2 -10
  42. package/dist/notifications/index.js +2 -33
  43. package/dist/notifications-BGqmUNZ8.js +759 -0
  44. package/dist/queue/index.js +3 -42
  45. package/dist/queue-CXrRK85G.js +948 -0
  46. package/dist/redis/index.js +672 -642
  47. package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
  48. package/dist/runtime/index.js +472 -616
  49. package/dist/scheduling/index.js +2 -29
  50. package/dist/scheduling-CPiEdtQd.js +839 -0
  51. package/dist/storage/index.js +2 -15
  52. package/dist/storage-tWHMv2H_.js +841 -0
  53. package/dist/support/expiry.js +69 -12
  54. package/dist/trim-slashes-ZJ_VsY5s.js +25 -0
  55. package/dist/vite/index.js +118 -181
  56. package/dist/vite/plugin.d.ts +1 -1
  57. package/dist/vite-dev-server-BSJkduhZ.js +131 -0
  58. package/package.json +6 -5
  59. package/dist/DocsViewerServiceProvider-RUYDFBMW.js +0 -75
  60. package/dist/McpServiceProvider-SL7DUZ4G.js +0 -8
  61. package/dist/chunk-2SC566CD.js +0 -376
  62. package/dist/chunk-2V3YID4H.js +0 -20
  63. package/dist/chunk-3KV5X2FL.js +0 -31
  64. package/dist/chunk-63SKW5PS.js +0 -457
  65. package/dist/chunk-6J6B5KOB.js +0 -425
  66. package/dist/chunk-A5JJ7XTH.js +0 -24
  67. package/dist/chunk-AZOYI43J.js +0 -18
  68. package/dist/chunk-B5E5VBDI.js +0 -115
  69. package/dist/chunk-DAQKYKLH.js +0 -182
  70. package/dist/chunk-DRNPVBAA.js +0 -1002
  71. package/dist/chunk-EI5GYMAT.js +0 -853
  72. package/dist/chunk-H3B23O6T.js +0 -271
  73. package/dist/chunk-HPET6XY5.js +0 -853
  74. package/dist/chunk-HR2KZ3WL.js +0 -616
  75. package/dist/chunk-IOTWFHZU.js +0 -558
  76. package/dist/chunk-K6CUBJX6.js +0 -642
  77. package/dist/chunk-KTNJG7R7.js +0 -911
  78. package/dist/chunk-LAJQCSSF.js +0 -355
  79. package/dist/chunk-LHR6OHI7.js +0 -189
  80. package/dist/chunk-N7PLD7MB.js +0 -729
  81. package/dist/chunk-Q2P6YLRR.js +0 -24
  82. package/dist/chunk-QQKTH5KX.js +0 -114
  83. package/dist/chunk-SFQP6O52.js +0 -126
  84. package/dist/chunk-SQR7277M.js +0 -911
  85. package/dist/chunk-T2FFUU6J.js +0 -484
  86. package/dist/chunk-TVV5YNEC.js +0 -1842
  87. package/dist/chunk-UY3AZSYL.js +0 -14
  88. package/dist/chunk-V4DNC2ER.js +0 -114
  89. package/dist/chunk-VSA3QY5Q.js +0 -274
  90. package/dist/chunk-YSOJKAAU.js +0 -427
  91. package/dist/errors-PUNHAFL2.js +0 -34
@@ -1,678 +1,534 @@
1
- import {
2
- DEFAULT_DEV_STYLES_ENTRY,
3
- GUREN_ASCII_ART,
4
- logDevServerBanner,
5
- parseImportMap,
6
- startViteDevServer
7
- } from "../chunk-VSA3QY5Q.js";
8
- import {
9
- trimTrailingSlashes
10
- } from "../chunk-AZOYI43J.js";
11
- import {
12
- hash
13
- } from "../chunk-QQKTH5KX.js";
14
-
15
- // src/http/dev-assets.ts
1
+ import { n as trimTrailingSlashes } from "../trim-slashes-ZJ_VsY5s.js";
2
+ import { n as hash } from "../Hash-CzrwKeDp.js";
3
+ import { a as logDevServerBanner, n as GUREN_ASCII_ART, s as parseImportMap, t as startViteDevServer } from "../vite-dev-server-BSJkduhZ.js";
4
+ import { createRequire } from "node:module";
5
+ import { realpath } from "node:fs/promises";
6
+ import { dirname, extname, join, resolve, sep } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { readFileSync } from "node:fs";
16
9
  import { serveStatic } from "hono/bun";
17
- import { dirname, extname as extname2, join, resolve as resolve2 } from "path";
18
- import { fileURLToPath } from "url";
19
- import { createRequire } from "module";
20
-
21
- // src/http/public-assets.ts
22
- import { extname, resolve } from "path";
23
-
24
- // src/support/contained-path.ts
25
- import { realpath } from "fs/promises";
26
- import { sep } from "path";
10
+ //#region src/support/contained-path.ts
11
+ /**
12
+ * Is `candidate` a path strictly below `root`, judged lexically?
13
+ *
14
+ * The trailing separator is what keeps out a sibling directory whose name
15
+ * merely extends the root's (`…/inertia` vs `…/inertia-secrets`), and what
16
+ * rejects an absolute `candidate` — which `resolve()` returns verbatim when a
17
+ * doubled slash in the request path left the relative part rooted.
18
+ *
19
+ * Cheap, but not sufficient on its own: `resolve()` collapses `..` without
20
+ * following symlinks. Use {@link isRealPathWithin} before reading the file.
21
+ */
27
22
  function isPathWithin(root, candidate) {
28
- return candidate.startsWith(root.endsWith(sep) ? root : root + sep);
23
+ return candidate.startsWith(root.endsWith(sep) ? root : root + sep);
29
24
  }
25
+ /**
26
+ * Is `candidate` a path strictly below `root` once both are canonicalized?
27
+ *
28
+ * Every reader downstream of these checks (`Bun.file().text()`,
29
+ * `.arrayBuffer()`, `new Response(file)`) follows symlinks, so a lexical check
30
+ * alone accepts `<root>/link/secret` where `link` points out of the tree.
31
+ * *Both* sides are canonicalized: a root reached through a symlink itself is
32
+ * routine (workspace and pnpm layouts, macOS `/var` → `/private/var`), and
33
+ * canonicalizing only the candidate would 404 every asset such an app serves.
34
+ *
35
+ * Call this on a path already known to exist — a path that does not exist
36
+ * cannot be read, and `realpath` rejects it, so either way this fails closed.
37
+ */
30
38
  async function isRealPathWithin(root, candidate) {
31
- if (!isPathWithin(root, candidate)) {
32
- return false;
33
- }
34
- const [realRoot, realCandidate] = await Promise.all([canonicalize(root), canonicalize(candidate)]);
35
- if (!realRoot || !realCandidate) {
36
- return false;
37
- }
38
- return isPathWithin(realRoot, realCandidate);
39
+ if (!isPathWithin(root, candidate)) return false;
40
+ const [realRoot, realCandidate] = await Promise.all([canonicalize(root), canonicalize(candidate)]);
41
+ if (!realRoot || !realCandidate) return false;
42
+ return isPathWithin(realRoot, realCandidate);
39
43
  }
40
44
  async function canonicalize(path) {
41
- try {
42
- return await realpath(path);
43
- } catch {
44
- return void 0;
45
- }
45
+ try {
46
+ return await realpath(path);
47
+ } catch {
48
+ return;
49
+ }
46
50
  }
47
-
48
- // src/http/public-assets.ts
49
- var DEFAULT_CACHE_CONTROL = "public, max-age=31536000, immutable";
50
- var DEFAULT_EXTENSIONS = [".svg", ".png", ".jpg", ".jpeg", ".gif", ".ico", ".webp", ".avif", ".webmanifest", ".txt"];
51
- var DEFAULT_CONTENT_TYPES = {
52
- ".svg": "image/svg+xml",
53
- ".png": "image/png",
54
- ".jpg": "image/jpeg",
55
- ".jpeg": "image/jpeg",
56
- ".gif": "image/gif",
57
- ".ico": "image/x-icon",
58
- ".webp": "image/webp",
59
- ".avif": "image/avif",
60
- ".webmanifest": "application/manifest+json",
61
- ".txt": "text/plain; charset=utf-8"
51
+ //#endregion
52
+ //#region src/http/public-assets.ts
53
+ const DEFAULT_CACHE_CONTROL = "public, max-age=31536000, immutable";
54
+ const DEFAULT_EXTENSIONS = [
55
+ ".svg",
56
+ ".png",
57
+ ".jpg",
58
+ ".jpeg",
59
+ ".gif",
60
+ ".ico",
61
+ ".webp",
62
+ ".avif",
63
+ ".webmanifest",
64
+ ".txt"
65
+ ];
66
+ const DEFAULT_CONTENT_TYPES = {
67
+ ".svg": "image/svg+xml",
68
+ ".png": "image/png",
69
+ ".jpg": "image/jpeg",
70
+ ".jpeg": "image/jpeg",
71
+ ".gif": "image/gif",
72
+ ".ico": "image/x-icon",
73
+ ".webp": "image/webp",
74
+ ".avif": "image/avif",
75
+ ".webmanifest": "application/manifest+json",
76
+ ".txt": "text/plain; charset=utf-8"
62
77
  };
63
78
  function registerRootPublicAssets(app, publicDir, config) {
64
- const normalized = normalizeConfig(config);
65
- if (!normalized) {
66
- return;
67
- }
68
- if (typeof Bun === "undefined") {
69
- console.warn("Root public asset serving is only available when running on Bun; skipping registration.");
70
- return;
71
- }
72
- const { extensions, cacheControlHeader, routePrefix, contentTypeMap } = normalized;
73
- const normalizedPrefix = routePrefix ? trimTrailingSlashes(routePrefix) || "/" : void 0;
74
- app.hono.use(async (ctx, next) => {
75
- const path = ctx.req.path;
76
- if (!path || path === "/" || path.startsWith("/public/")) {
77
- return next();
78
- }
79
- if (normalizedPrefix && !path.startsWith(normalizedPrefix)) {
80
- return next();
81
- }
82
- const extension = extname(path).toLowerCase();
83
- if (!extensions.has(extension)) {
84
- return next();
85
- }
86
- const relativePath = path.replace(/^\/+/, "");
87
- if (!relativePath) {
88
- return next();
89
- }
90
- const candidatePath = resolve(publicDir, relativePath);
91
- if (!isPathWithin(publicDir, candidatePath) && candidatePath !== publicDir) {
92
- return next();
93
- }
94
- const file = Bun.file(candidatePath);
95
- if (!await file.exists()) {
96
- return next();
97
- }
98
- if (!await isRealPathWithin(publicDir, candidatePath)) {
99
- return next();
100
- }
101
- const headers = new Headers({
102
- "Cache-Control": cacheControlHeader,
103
- "Content-Type": contentTypeMap?.[extension] ?? DEFAULT_CONTENT_TYPES[extension] ?? "application/octet-stream"
104
- });
105
- return new Response(file, { headers });
106
- });
79
+ const normalized = normalizeConfig(config);
80
+ if (!normalized) return;
81
+ if (typeof Bun === "undefined") {
82
+ console.warn("Root public asset serving is only available when running on Bun; skipping registration.");
83
+ return;
84
+ }
85
+ const { extensions, cacheControlHeader, routePrefix, contentTypeMap } = normalized;
86
+ const normalizedPrefix = routePrefix ? trimTrailingSlashes(routePrefix) || "/" : void 0;
87
+ app.hono.use(async (ctx, next) => {
88
+ const path = ctx.req.path;
89
+ if (!path || path === "/" || path.startsWith("/public/")) return next();
90
+ if (normalizedPrefix && !path.startsWith(normalizedPrefix)) return next();
91
+ const extension = extname(path).toLowerCase();
92
+ if (!extensions.has(extension)) return next();
93
+ const relativePath = path.replace(/^\/+/, "");
94
+ if (!relativePath) return next();
95
+ const candidatePath = resolve(publicDir, relativePath);
96
+ if (!isPathWithin(publicDir, candidatePath) && candidatePath !== publicDir) return next();
97
+ const file = Bun.file(candidatePath);
98
+ if (!await file.exists()) return next();
99
+ if (!await isRealPathWithin(publicDir, candidatePath)) return next();
100
+ const headers = new Headers({
101
+ "Cache-Control": cacheControlHeader,
102
+ "Content-Type": contentTypeMap?.[extension] ?? DEFAULT_CONTENT_TYPES[extension] ?? "application/octet-stream"
103
+ });
104
+ return new Response(file, { headers });
105
+ });
107
106
  }
108
107
  function normalizeConfig(config) {
109
- if (config === false) {
110
- return void 0;
111
- }
112
- if (config === void 0 || config === true) {
113
- return {
114
- extensions: new Set(DEFAULT_EXTENSIONS),
115
- cacheControlHeader: DEFAULT_CACHE_CONTROL
116
- };
117
- }
118
- const enabled = config.enabled ?? true;
119
- if (!enabled) {
120
- return void 0;
121
- }
122
- const extensions = new Set(
123
- (config.extensions && config.extensions.length > 0 ? config.extensions : DEFAULT_EXTENSIONS).map(
124
- (ext) => normalizeExtension(ext)
125
- )
126
- );
127
- return {
128
- extensions,
129
- cacheControlHeader: config.cacheControlHeader ?? DEFAULT_CACHE_CONTROL,
130
- routePrefix: config.routePrefix,
131
- contentTypeMap: config.contentTypeMap
132
- };
108
+ if (config === false) return;
109
+ if (config === void 0 || config === true) return {
110
+ extensions: new Set(DEFAULT_EXTENSIONS),
111
+ cacheControlHeader: DEFAULT_CACHE_CONTROL
112
+ };
113
+ if (!(config.enabled ?? true)) return;
114
+ return {
115
+ extensions: new Set((config.extensions && config.extensions.length > 0 ? config.extensions : DEFAULT_EXTENSIONS).map((ext) => normalizeExtension(ext))),
116
+ cacheControlHeader: config.cacheControlHeader ?? DEFAULT_CACHE_CONTROL,
117
+ routePrefix: config.routePrefix,
118
+ contentTypeMap: config.contentTypeMap
119
+ };
133
120
  }
134
121
  function normalizeExtension(value) {
135
- if (!value) {
136
- return value;
137
- }
138
- return value.startsWith(".") ? value.toLowerCase() : `.${value.toLowerCase()}`;
122
+ if (!value) return value;
123
+ return value.startsWith(".") ? value.toLowerCase() : `.${value.toLowerCase()}`;
139
124
  }
140
-
141
- // src/http/dev-assets.ts
142
- var DEFAULT_PREFIX = "/resources/js";
143
- var DEFAULT_VENDOR_PATH = "/vendor/inertia-client.tsx";
144
- var DEFAULT_JSX_RUNTIME = "https://esm.sh/react@19.0.0/jsx-dev-runtime?dev";
145
- var REACT_IMPORT_PATTERN = /from\s+['"]react['"]/u;
125
+ //#endregion
126
+ //#region src/http/dev-assets.ts
127
+ const DEFAULT_PREFIX = "/resources/js";
128
+ const DEFAULT_VENDOR_PATH = "/vendor/inertia-client.tsx";
129
+ const DEFAULT_JSX_RUNTIME = "https://esm.sh/react@19.0.0/jsx-dev-runtime?dev";
130
+ const REACT_IMPORT_PATTERN = /from\s+['"]react['"]/u;
131
+ /**
132
+ * Derive the mount point for the vendored Inertia client from its public
133
+ * path: the containing directory (always slash-terminated), the Hono route
134
+ * pattern for it, and the file's path relative to that base.
135
+ */
146
136
  function resolveInertiaClientRoute(inertiaClientPath) {
147
- const base = inertiaClientPath.slice(0, inertiaClientPath.lastIndexOf("/") + 1) || "/";
148
- return {
149
- base,
150
- pattern: `${base}*`,
151
- requestPath: inertiaClientPath.slice(base.length)
152
- };
137
+ const base = inertiaClientPath.slice(0, inertiaClientPath.lastIndexOf("/") + 1) || "/";
138
+ return {
139
+ base,
140
+ pattern: `${base}*`,
141
+ requestPath: inertiaClientPath.slice(base.length)
142
+ };
153
143
  }
154
- var require2 = createRequire(import.meta.url);
144
+ const require = createRequire(import.meta.url);
155
145
  function resolveGurenInertiaClient() {
156
- return require2.resolve("@guren/inertia-client/app");
146
+ return require.resolve("@guren/inertia-client/app");
157
147
  }
148
+ /**
149
+ * Absolute path to `@guren/inertia-client`'s build output, the directory
150
+ * production serves the vendored client and its chunks from.
151
+ *
152
+ * Unlike {@link resolveGurenInertiaClient}, this must not follow a tsconfig
153
+ * `paths` mapping to the package's TypeScript sources — production serves
154
+ * files, it cannot transpile them. So it anchors on `./package.json`, a
155
+ * subpath such a mapping misses (there is no `src/package.json`) and real
156
+ * package resolution answers with the package root.
157
+ */
158
158
  function resolveInertiaClientDir() {
159
- return join(dirname(require2.resolve("@guren/inertia-client/package.json")), "dist");
159
+ return join(dirname(require.resolve("@guren/inertia-client/package.json")), "dist");
160
160
  }
161
+ /**
162
+ * Registers development asset serving middleware.
163
+ * @param app
164
+ * @param options
165
+ */
161
166
  function registerDevAssets(app, options) {
162
- if (typeof Bun === "undefined") {
163
- throw new Error("Bun runtime is required for dev asset serving.");
164
- }
165
- const moduleDir = options.importMeta ? dirname(fileURLToPath(options.importMeta.url)) : void 0;
166
- const resourcesDir = options.resourcesDir ?? (moduleDir ? resolve2(moduleDir, options.resourcesPath ?? "../resources") : void 0);
167
- if (!resourcesDir) {
168
- throw new Error("registerDevAssets requires either `resourcesDir` or `importMeta`.");
169
- }
170
- const prefix = options.prefix ?? DEFAULT_PREFIX;
171
- const cssDir = options.cssDir ?? resolve2(resourcesDir, "css");
172
- const cssRoute = options.cssRoute ?? deriveCssRoute(prefix);
173
- const inertiaClientPath = options.inertiaClientPath ?? DEFAULT_VENDOR_PATH;
174
- const inertiaClientSource = options.inertiaClientSource ?? resolveGurenInertiaClient();
175
- const jsxRuntimeUrl = options.jsxRuntimeUrl ?? DEFAULT_JSX_RUNTIME;
176
- const resourcesJsDir = resolve2(resourcesDir, "js");
177
- const transpilerOptions = {
178
- target: "browser",
179
- jsx: "transform",
180
- jsxFactory: "React.createElement",
181
- jsxFragment: "React.Fragment",
182
- define: {
183
- "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV ?? "development")
184
- }
185
- };
186
- const transpile = {
187
- tsx: new Bun.Transpiler({ loader: "tsx", ...transpilerOptions }),
188
- ts: new Bun.Transpiler({ loader: "ts", ...transpilerOptions }),
189
- jsxRuntimeUrl
190
- };
191
- app.hono.get(`${prefix}/*`, (ctx) => handleTranspileRequest(ctx, resourcesJsDir, prefix, transpile));
192
- if (cssDir) {
193
- const cssRewrite = createStaticRewrite(cssRoute);
194
- app.use(
195
- cssRoute,
196
- serveStatic({
197
- root: cssDir,
198
- rewriteRequestPath: cssRewrite
199
- })
200
- );
201
- }
202
- if (options.inertiaClient !== false) {
203
- const inertiaClientDir = dirname(inertiaClientSource);
204
- const {
205
- base: inertiaClientBase,
206
- pattern: inertiaClientPattern,
207
- requestPath: inertiaClientRequestPath
208
- } = resolveInertiaClientRoute(inertiaClientPath);
209
- app.hono.get(inertiaClientPattern, (ctx) => {
210
- const relativeRequest = ctx.req.path.slice(inertiaClientBase.length) || inertiaClientRequestPath;
211
- if (relativeRequest === inertiaClientRequestPath) {
212
- return transpileFile(inertiaClientSource, transpile);
213
- }
214
- const candidatePath = resolve2(inertiaClientDir, relativeRequest);
215
- if (!isPathWithin(inertiaClientDir, candidatePath)) {
216
- return ctx.notFound();
217
- }
218
- return transpileFile(candidatePath, transpile, inertiaClientDir);
219
- });
220
- }
221
- const publicPathOption = options.publicPath === void 0 ? "../public" : options.publicPath;
222
- const publicDir = options.publicDir ?? (moduleDir && publicPathOption ? resolve2(moduleDir, publicPathOption) : void 0);
223
- const shouldServePublic = publicDir && publicPathOption !== false;
224
- if (shouldServePublic) {
225
- const publicRoute = options.publicRoute ?? "/public/*";
226
- const rewriteRequestPath = createStaticRewrite(publicRoute);
227
- app.use(
228
- publicRoute,
229
- serveStatic({
230
- root: publicDir,
231
- rewriteRequestPath
232
- })
233
- );
234
- if (options.favicon !== false) {
235
- app.hono.get("/favicon.ico", () => new Response(null, { status: 204 }));
236
- }
237
- registerRootPublicAssets(app, publicDir, options.rootPublicAssets);
238
- }
167
+ if (typeof Bun === "undefined") throw new Error("Bun runtime is required for dev asset serving.");
168
+ const moduleDir = options.importMeta ? dirname(fileURLToPath(options.importMeta.url)) : void 0;
169
+ const resourcesDir = options.resourcesDir ?? (moduleDir ? resolve(moduleDir, options.resourcesPath ?? "../resources") : void 0);
170
+ if (!resourcesDir) throw new Error("registerDevAssets requires either `resourcesDir` or `importMeta`.");
171
+ const prefix = options.prefix ?? DEFAULT_PREFIX;
172
+ const cssDir = options.cssDir ?? resolve(resourcesDir, "css");
173
+ const cssRoute = options.cssRoute ?? deriveCssRoute(prefix);
174
+ const inertiaClientPath = options.inertiaClientPath ?? DEFAULT_VENDOR_PATH;
175
+ const inertiaClientSource = options.inertiaClientSource ?? resolveGurenInertiaClient();
176
+ const jsxRuntimeUrl = options.jsxRuntimeUrl ?? DEFAULT_JSX_RUNTIME;
177
+ const resourcesJsDir = resolve(resourcesDir, "js");
178
+ const transpilerOptions = {
179
+ target: "browser",
180
+ jsx: "transform",
181
+ jsxFactory: "React.createElement",
182
+ jsxFragment: "React.Fragment",
183
+ define: { "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV ?? "development") }
184
+ };
185
+ const transpile = {
186
+ tsx: new Bun.Transpiler({
187
+ loader: "tsx",
188
+ ...transpilerOptions
189
+ }),
190
+ ts: new Bun.Transpiler({
191
+ loader: "ts",
192
+ ...transpilerOptions
193
+ }),
194
+ jsxRuntimeUrl
195
+ };
196
+ app.hono.get(`${prefix}/*`, (ctx) => handleTranspileRequest(ctx, resourcesJsDir, prefix, transpile));
197
+ if (cssDir) {
198
+ const cssRewrite = createStaticRewrite(cssRoute);
199
+ app.use(cssRoute, serveStatic({
200
+ root: cssDir,
201
+ rewriteRequestPath: cssRewrite
202
+ }));
203
+ }
204
+ if (options.inertiaClient !== false) {
205
+ const inertiaClientDir = dirname(inertiaClientSource);
206
+ const { base: inertiaClientBase, pattern: inertiaClientPattern, requestPath: inertiaClientRequestPath } = resolveInertiaClientRoute(inertiaClientPath);
207
+ app.hono.get(inertiaClientPattern, (ctx) => {
208
+ const relativeRequest = ctx.req.path.slice(inertiaClientBase.length) || inertiaClientRequestPath;
209
+ if (relativeRequest === inertiaClientRequestPath) return transpileFile(inertiaClientSource, transpile);
210
+ const candidatePath = resolve(inertiaClientDir, relativeRequest);
211
+ if (!isPathWithin(inertiaClientDir, candidatePath)) return ctx.notFound();
212
+ return transpileFile(candidatePath, transpile, inertiaClientDir);
213
+ });
214
+ }
215
+ const publicPathOption = options.publicPath === void 0 ? "../public" : options.publicPath;
216
+ const publicDir = options.publicDir ?? (moduleDir && publicPathOption ? resolve(moduleDir, publicPathOption) : void 0);
217
+ if (publicDir && publicPathOption !== false) {
218
+ const publicRoute = options.publicRoute ?? "/public/*";
219
+ const rewriteRequestPath = createStaticRewrite(publicRoute);
220
+ app.use(publicRoute, serveStatic({
221
+ root: publicDir,
222
+ rewriteRequestPath
223
+ }));
224
+ if (options.favicon !== false) app.hono.get("/favicon.ico", () => new Response(null, { status: 204 }));
225
+ registerRootPublicAssets(app, publicDir, options.rootPublicAssets);
226
+ }
239
227
  }
240
228
  function createStaticRewrite(route) {
241
- const wildcardIndex = route.indexOf("*");
242
- const base = wildcardIndex >= 0 ? route.slice(0, wildcardIndex) : route;
243
- const normalizedBase = base.endsWith("/") ? base.slice(0, -1) : base;
244
- if (!normalizedBase) {
245
- return (path) => path || "/";
246
- }
247
- return (path) => {
248
- if (!path.startsWith(normalizedBase)) {
249
- return path || "/";
250
- }
251
- const remainder = path.slice(normalizedBase.length);
252
- if (!remainder) {
253
- return "/";
254
- }
255
- return remainder.startsWith("/") ? remainder : `/${remainder}`;
256
- };
229
+ const wildcardIndex = route.indexOf("*");
230
+ const base = wildcardIndex >= 0 ? route.slice(0, wildcardIndex) : route;
231
+ const normalizedBase = base.endsWith("/") ? base.slice(0, -1) : base;
232
+ if (!normalizedBase) return (path) => path || "/";
233
+ return (path) => {
234
+ if (!path.startsWith(normalizedBase)) return path || "/";
235
+ const remainder = path.slice(normalizedBase.length);
236
+ if (!remainder) return "/";
237
+ return remainder.startsWith("/") ? remainder : `/${remainder}`;
238
+ };
257
239
  }
240
+ /**
241
+ * Handles a request to transpile a JavaScript or TypeScript file.
242
+ * @param ctx The request context.
243
+ * @param resourcesJsDir The directory containing the resource files.
244
+ * @param prefix The URL prefix for the request.
245
+ * @param transpile The transpilers and JSX runtime to use.
246
+ * @returns A Promise that resolves to a Response object.
247
+ */
258
248
  async function handleTranspileRequest(ctx, resourcesJsDir, prefix, transpile) {
259
- const relative = ctx.req.path.slice(prefix.length + 1);
260
- const fsPath = resolve2(resourcesJsDir, relative);
261
- if (!isPathWithin(resourcesJsDir, fsPath)) {
262
- return ctx.notFound();
263
- }
264
- return transpileFile(fsPath, transpile, resourcesJsDir);
249
+ const relative = ctx.req.path.slice(prefix.length + 1);
250
+ const fsPath = resolve(resourcesJsDir, relative);
251
+ if (!isPathWithin(resourcesJsDir, fsPath)) return ctx.notFound();
252
+ return transpileFile(fsPath, transpile, resourcesJsDir);
265
253
  }
254
+ /**
255
+ * Transpiles a file if it's a TSX or TS file, otherwise serves it as a static asset.
256
+ * @param fsPath The file system path to the file.
257
+ * @param transpile The transpilers and JSX runtime to use.
258
+ * @param containmentRoot Directory the resolved file must really live under. Omit for configured (non request-derived) paths.
259
+ * @returns A Promise that resolves to a Response object.
260
+ */
266
261
  async function transpileFile(fsPath, transpile, containmentRoot) {
267
- const candidates = buildCandidatePaths(fsPath);
268
- let filePath;
269
- let file;
270
- for (const candidate of candidates) {
271
- const bunFile = Bun.file(candidate);
272
- if (await bunFile.exists()) {
273
- filePath = candidate;
274
- file = bunFile;
275
- break;
276
- }
277
- }
278
- if (!file || !filePath) {
279
- return new Response("Not Found", { status: 404 });
280
- }
281
- if (containmentRoot && !await isRealPathWithin(containmentRoot, filePath)) {
282
- return new Response("Not Found", { status: 404 });
283
- }
284
- const ext = extname2(filePath);
285
- let source = await file.text();
286
- if (ext === ".tsx" && !REACT_IMPORT_PATTERN.test(source)) {
287
- source = "import React from 'react'\n" + source;
288
- }
289
- if (ext === ".tsx" || ext === ".ts") {
290
- const loader = ext === ".tsx" ? "tsx" : "ts";
291
- const transpiled = transpile[loader].transformSync(source, {
292
- loader,
293
- sourceMap: isDev() ? "inline" : false,
294
- filename: filePath
295
- });
296
- const helpers = collectJsxHelpers(transpiled);
297
- const runtimeShim = helpers.size ? createJsxRuntimeShim(helpers, transpile.jsxRuntimeUrl) : "";
298
- return new Response(runtimeShim + transpiled, {
299
- headers: {
300
- "Content-Type": "application/javascript; charset=utf-8",
301
- "Cache-Control": isDev() ? "no-cache" : "public, max-age=31536000"
302
- }
303
- });
304
- }
305
- const body = await file.arrayBuffer();
306
- return new Response(body, {
307
- headers: {
308
- "Content-Type": file.type || "application/octet-stream",
309
- "Cache-Control": isDev() ? "no-cache" : "public, max-age=31536000"
310
- }
311
- });
262
+ const candidates = buildCandidatePaths(fsPath);
263
+ let filePath;
264
+ let file;
265
+ for (const candidate of candidates) {
266
+ const bunFile = Bun.file(candidate);
267
+ if (await bunFile.exists()) {
268
+ filePath = candidate;
269
+ file = bunFile;
270
+ break;
271
+ }
272
+ }
273
+ if (!file || !filePath) return new Response("Not Found", { status: 404 });
274
+ if (containmentRoot && !await isRealPathWithin(containmentRoot, filePath)) return new Response("Not Found", { status: 404 });
275
+ const ext = extname(filePath);
276
+ let source = await file.text();
277
+ if (ext === ".tsx" && !REACT_IMPORT_PATTERN.test(source)) source = "import React from 'react'\n" + source;
278
+ if (ext === ".tsx" || ext === ".ts") {
279
+ const loader = ext === ".tsx" ? "tsx" : "ts";
280
+ const transpiled = transpile[loader].transformSync(source, {
281
+ loader,
282
+ sourceMap: isDev() ? "inline" : false,
283
+ filename: filePath
284
+ });
285
+ const helpers = collectJsxHelpers(transpiled);
286
+ const runtimeShim = helpers.size ? createJsxRuntimeShim(helpers, transpile.jsxRuntimeUrl) : "";
287
+ return new Response(runtimeShim + transpiled, { headers: {
288
+ "Content-Type": "application/javascript; charset=utf-8",
289
+ "Cache-Control": isDev() ? "no-cache" : "public, max-age=31536000"
290
+ } });
291
+ }
292
+ const body = await file.arrayBuffer();
293
+ return new Response(body, { headers: {
294
+ "Content-Type": file.type || "application/octet-stream",
295
+ "Cache-Control": isDev() ? "no-cache" : "public, max-age=31536000"
296
+ } });
312
297
  }
313
298
  function buildCandidatePaths(fsPath) {
314
- const ext = extname2(fsPath);
315
- if (ext) {
316
- return [fsPath];
317
- }
318
- return [
319
- `${fsPath}.tsx`,
320
- `${fsPath}.ts`,
321
- `${fsPath}.jsx`,
322
- `${fsPath}.js`
323
- ];
299
+ if (extname(fsPath)) return [fsPath];
300
+ return [
301
+ `${fsPath}.tsx`,
302
+ `${fsPath}.ts`,
303
+ `${fsPath}.jsx`,
304
+ `${fsPath}.js`
305
+ ];
324
306
  }
325
307
  function collectJsxHelpers(code) {
326
- const helpers = /* @__PURE__ */ new Set();
327
- const pattern = /(jsxDEV|jsx|jsxs|Fragment)_[0-9a-z]+/gu;
328
- for (const match of code.matchAll(pattern)) {
329
- helpers.add(match[0]);
330
- }
331
- return helpers;
308
+ const helpers = /* @__PURE__ */ new Set();
309
+ for (const match of code.matchAll(/(jsxDEV|jsx|jsxs|Fragment)_[0-9a-z]+/gu)) helpers.add(match[0]);
310
+ return helpers;
332
311
  }
333
312
  function createJsxRuntimeShim(helpers, runtimeUrl) {
334
- const assignments = Array.from(helpers).map((helper) => {
335
- const base = helper.split("_")[0];
336
- return `const ${helper} = __jsxRuntime.${base};`;
337
- });
338
- return `import * as __jsxRuntime from "${runtimeUrl}";
339
- ${assignments.join("\n")}
340
- `;
313
+ return `import * as __jsxRuntime from "${runtimeUrl}";\n${Array.from(helpers).map((helper) => {
314
+ return `const ${helper} = __jsxRuntime.${helper.split("_")[0]};`;
315
+ }).join("\n")}\n`;
341
316
  }
342
317
  function isDev() {
343
- return (process.env.NODE_ENV ?? "development") !== "production";
318
+ return (process.env.NODE_ENV ?? "development") !== "production";
344
319
  }
345
320
  function deriveCssRoute(prefix) {
346
- const base = prefix.endsWith("/js") ? prefix.slice(0, -3) : prefix;
347
- const normalizedBase = base.endsWith("/") ? base.slice(0, -1) : base;
348
- const resolvedBase = normalizedBase.startsWith("/") ? normalizedBase : `/${normalizedBase}`;
349
- return `${resolvedBase}/css/*`;
321
+ const base = prefix.endsWith("/js") ? prefix.slice(0, -3) : prefix;
322
+ const normalizedBase = base.endsWith("/") ? base.slice(0, -1) : base;
323
+ return `${normalizedBase.startsWith("/") ? normalizedBase : `/${normalizedBase}`}/css/*`;
350
324
  }
351
-
352
- // src/http/inertia-assets.ts
353
- import { serveStatic as serveStatic2 } from "hono/bun";
354
- import { dirname as dirname2, resolve as resolve3, join as join2 } from "path";
355
- import { fileURLToPath as fileURLToPath2 } from "url";
356
- import { readFileSync } from "fs";
357
- var DEFAULT_STYLES_ENTRY = "/public/assets/app.css";
358
- var DEFAULT_SCRIPT_ENTRY = "/assets/app.js";
359
- var DEFAULT_VENDOR_CLIENT_PATH = "/vendor/inertia-client.tsx";
325
+ //#endregion
326
+ //#region src/http/inertia-assets.ts
327
+ const DEFAULT_STYLES_ENTRY = "/public/assets/app.css";
328
+ const DEFAULT_SCRIPT_ENTRY = "/assets/app.js";
329
+ const DEFAULT_VENDOR_CLIENT_PATH = "/vendor/inertia-client.tsx";
360
330
  function configureInertiaAssets(app, options) {
361
- const stylesEntry = options.stylesEntry ?? DEFAULT_STYLES_ENTRY;
362
- process.env.GUREN_INERTIA_STYLES = process.env.GUREN_INERTIA_STYLES ?? stylesEntry;
363
- const providedSsrEntry = options.ssrEntry;
364
- const providedSsrManifest = options.ssrManifest;
365
- const isProduction = process.env.NODE_ENV === "production";
366
- if (!isProduction) {
367
- const devSsrEntry = resolveDevSsrEntry(options);
368
- if (!process.env.GUREN_INERTIA_SSR_ENTRY && devSsrEntry) {
369
- process.env.GUREN_INERTIA_SSR_ENTRY = devSsrEntry;
370
- }
371
- if (!process.env.GUREN_INERTIA_SSR_MANIFEST) {
372
- process.env.GUREN_INERTIA_SSR_MANIFEST = providedSsrManifest ?? "";
373
- }
374
- registerDevAssets(app, options);
375
- return;
376
- }
377
- const scriptEntry = options.scriptEntry ?? DEFAULT_SCRIPT_ENTRY;
378
- process.env.GUREN_INERTIA_ENTRY = process.env.GUREN_INERTIA_ENTRY ?? scriptEntry;
379
- if (!process.env.GUREN_INERTIA_SSR_ENTRY && providedSsrEntry) {
380
- process.env.GUREN_INERTIA_SSR_ENTRY = providedSsrEntry;
381
- }
382
- if (!process.env.GUREN_INERTIA_SSR_MANIFEST && providedSsrManifest) {
383
- process.env.GUREN_INERTIA_SSR_MANIFEST = providedSsrManifest;
384
- }
385
- const moduleDir = options.importMeta ? dirname2(fileURLToPath2(options.importMeta.url)) : void 0;
386
- const publicPathOption = options.publicPath === void 0 ? "../public" : options.publicPath;
387
- const publicDir = options.publicDir ?? (moduleDir && publicPathOption ? resolve3(moduleDir, publicPathOption) : void 0);
388
- if (!publicDir || publicPathOption === false) {
389
- return;
390
- }
391
- const publicRoute = options.publicRoute ?? "/public/*";
392
- const rewriteRequestPath = createStaticRewrite(publicRoute);
393
- const hashedAssetsPrefix = `${publicRouteBase(publicRoute)}/assets/`;
394
- app.use(
395
- publicRoute,
396
- serveStatic2({
397
- root: publicDir,
398
- rewriteRequestPath,
399
- // Vite writes content-hashed filenames under `assets/`, so those
400
- // responses can be cached forever. Files elsewhere in public/ keep
401
- // stable names and must stay revalidatable.
402
- onFound: (_path, ctx) => {
403
- if (ctx.req.path.startsWith(hashedAssetsPrefix)) {
404
- ctx.header("Cache-Control", "public, max-age=31536000, immutable");
405
- }
406
- }
407
- })
408
- );
409
- if (options.favicon !== false) {
410
- app.hono.get("/favicon.ico", () => new Response(null, { status: 204 }));
411
- }
412
- registerRootPublicAssets(app, publicDir, options.rootPublicAssets);
413
- if (options.inertiaClient !== false) {
414
- try {
415
- registerBuiltInertiaClient(
416
- app,
417
- resolveInertiaClientDir(),
418
- options.inertiaClientPath ?? DEFAULT_VENDOR_CLIENT_PATH
419
- );
420
- } catch (error) {
421
- console.warn("Unable to resolve @guren/inertia-client for production serving.", error);
422
- }
423
- }
331
+ const stylesEntry = options.stylesEntry ?? DEFAULT_STYLES_ENTRY;
332
+ process.env.GUREN_INERTIA_STYLES = process.env.GUREN_INERTIA_STYLES ?? stylesEntry;
333
+ const providedSsrEntry = options.ssrEntry;
334
+ const providedSsrManifest = options.ssrManifest;
335
+ if (!(process.env.NODE_ENV === "production")) {
336
+ const devSsrEntry = resolveDevSsrEntry(options);
337
+ if (!process.env.GUREN_INERTIA_SSR_ENTRY && devSsrEntry) process.env.GUREN_INERTIA_SSR_ENTRY = devSsrEntry;
338
+ if (!process.env.GUREN_INERTIA_SSR_MANIFEST) process.env.GUREN_INERTIA_SSR_MANIFEST = providedSsrManifest ?? "";
339
+ registerDevAssets(app, options);
340
+ return;
341
+ }
342
+ const scriptEntry = options.scriptEntry ?? DEFAULT_SCRIPT_ENTRY;
343
+ process.env.GUREN_INERTIA_ENTRY = process.env.GUREN_INERTIA_ENTRY ?? scriptEntry;
344
+ if (!process.env.GUREN_INERTIA_SSR_ENTRY && providedSsrEntry) process.env.GUREN_INERTIA_SSR_ENTRY = providedSsrEntry;
345
+ if (!process.env.GUREN_INERTIA_SSR_MANIFEST && providedSsrManifest) process.env.GUREN_INERTIA_SSR_MANIFEST = providedSsrManifest;
346
+ const moduleDir = options.importMeta ? dirname(fileURLToPath(options.importMeta.url)) : void 0;
347
+ const publicPathOption = options.publicPath === void 0 ? "../public" : options.publicPath;
348
+ const publicDir = options.publicDir ?? (moduleDir && publicPathOption ? resolve(moduleDir, publicPathOption) : void 0);
349
+ if (!publicDir || publicPathOption === false) return;
350
+ const publicRoute = options.publicRoute ?? "/public/*";
351
+ const rewriteRequestPath = createStaticRewrite(publicRoute);
352
+ const hashedAssetsPrefix = `${publicRouteBase(publicRoute)}/assets/`;
353
+ app.use(publicRoute, serveStatic({
354
+ root: publicDir,
355
+ rewriteRequestPath,
356
+ onFound: (_path, ctx) => {
357
+ if (ctx.req.path.startsWith(hashedAssetsPrefix)) ctx.header("Cache-Control", "public, max-age=31536000, immutable");
358
+ }
359
+ }));
360
+ if (options.favicon !== false) app.hono.get("/favicon.ico", () => new Response(null, { status: 204 }));
361
+ registerRootPublicAssets(app, publicDir, options.rootPublicAssets);
362
+ if (options.inertiaClient !== false) try {
363
+ registerBuiltInertiaClient(app, resolveInertiaClientDir(), options.inertiaClientPath ?? DEFAULT_VENDOR_CLIENT_PATH);
364
+ } catch (error) {
365
+ console.warn("Unable to resolve @guren/inertia-client for production serving.", error);
366
+ }
424
367
  }
368
+ /** The route base ahead of the wildcard, as {@link createStaticRewrite} sees it. */
425
369
  function publicRouteBase(route) {
426
- const wildcardIndex = route.indexOf("*");
427
- const base = wildcardIndex >= 0 ? route.slice(0, wildcardIndex) : route;
428
- return trimTrailingSlashes(base);
370
+ const wildcardIndex = route.indexOf("*");
371
+ const base = wildcardIndex >= 0 ? route.slice(0, wildcardIndex) : route;
372
+ return trimTrailingSlashes(base);
429
373
  }
374
+ /**
375
+ * Serves the built Inertia client and the chunks it imports out of the
376
+ * resolved package directory.
377
+ *
378
+ * Split out of {@link configureInertiaAssets} so it can be pointed at a
379
+ * directory: the caller derives `inertiaClientDir` from `import.meta.resolve`,
380
+ * which no test can redirect at a fixture.
381
+ */
430
382
  function registerBuiltInertiaClient(app, inertiaClientDir, inertiaClientPath) {
431
- const {
432
- base: inertiaClientBase,
433
- pattern: inertiaClientPattern,
434
- requestPath: inertiaClientRequestPath
435
- } = resolveInertiaClientRoute(inertiaClientPath);
436
- app.hono.get(inertiaClientPattern, async (ctx) => {
437
- const relativeRequest = ctx.req.path.slice(inertiaClientBase.length) || inertiaClientRequestPath;
438
- let targetPath;
439
- let containmentRoot;
440
- if (relativeRequest === inertiaClientRequestPath) {
441
- targetPath = join2(inertiaClientDir, "app.js");
442
- } else {
443
- targetPath = resolve3(inertiaClientDir, relativeRequest);
444
- containmentRoot = inertiaClientDir;
445
- if (!isPathWithin(containmentRoot, targetPath)) {
446
- return ctx.notFound();
447
- }
448
- }
449
- const file = Bun.file(targetPath);
450
- if (!await file.exists()) {
451
- return ctx.notFound();
452
- }
453
- if (containmentRoot && !await isRealPathWithin(containmentRoot, targetPath)) {
454
- return ctx.notFound();
455
- }
456
- const contentType = file.type || "application/javascript; charset=utf-8";
457
- return new Response(file, {
458
- headers: {
459
- "Content-Type": contentType,
460
- "Cache-Control": "public, max-age=31536000"
461
- }
462
- });
463
- });
383
+ const { base: inertiaClientBase, pattern: inertiaClientPattern, requestPath: inertiaClientRequestPath } = resolveInertiaClientRoute(inertiaClientPath);
384
+ app.hono.get(inertiaClientPattern, async (ctx) => {
385
+ const relativeRequest = ctx.req.path.slice(inertiaClientBase.length) || inertiaClientRequestPath;
386
+ let targetPath;
387
+ let containmentRoot;
388
+ if (relativeRequest === inertiaClientRequestPath) targetPath = join(inertiaClientDir, "app.js");
389
+ else {
390
+ targetPath = resolve(inertiaClientDir, relativeRequest);
391
+ containmentRoot = inertiaClientDir;
392
+ if (!isPathWithin(containmentRoot, targetPath)) return ctx.notFound();
393
+ }
394
+ const file = Bun.file(targetPath);
395
+ if (!await file.exists()) return ctx.notFound();
396
+ if (containmentRoot && !await isRealPathWithin(containmentRoot, targetPath)) return ctx.notFound();
397
+ const contentType = file.type || "application/javascript; charset=utf-8";
398
+ return new Response(file, { headers: {
399
+ "Content-Type": contentType,
400
+ "Cache-Control": "public, max-age=31536000"
401
+ } });
402
+ });
464
403
  }
465
404
  function autoConfigureInertiaAssets(app, options) {
466
- const providedEnv = captureInertiaEnvFlags();
467
- configureInertiaAssets(app, options);
468
- const moduleDir = options.importMeta ? dirname2(fileURLToPath2(options.importMeta.url)) : void 0;
469
- const resourcesDir = resolveResourcesDir(options, moduleDir);
470
- const ssrOutDir = options.ssrOutDir ?? ".guren/ssr";
471
- const importMapEntries = parseImportMap(process.env.GUREN_INERTIA_IMPORT_MAP, {
472
- context: "GUREN_INERTIA_IMPORT_MAP from environment"
473
- });
474
- const ssrEnabled = options.enableSsr ?? true;
475
- const setEnvIfUserDidNotProvide = (key, value) => {
476
- if (providedEnv[key]) {
477
- return;
478
- }
479
- process.env[key] = value;
480
- };
481
- if (!moduleDir) {
482
- return;
483
- }
484
- const isProduction = (process.env.NODE_ENV ?? "development") === "production" && typeof process.env.VITE_DEV_SERVER_URL !== "string";
485
- if (!isProduction) {
486
- const devServerUrl = options.devServerUrl ?? process.env.VITE_DEV_SERVER_URL ?? "http://localhost:5173";
487
- const normalizedDevServerUrl = normalizeDevServerUrl(devServerUrl);
488
- setEnvIfUserDidNotProvide("GUREN_INERTIA_ENTRY", `${normalizedDevServerUrl}/resources/js/dev-entry.ts`);
489
- setEnvIfUserDidNotProvide("GUREN_INERTIA_STYLES", options.stylesEntry ?? DEFAULT_DEV_STYLES_ENTRY);
490
- importMapEntries["@guren/inertia-client"] = DEFAULT_VENDOR_CLIENT_PATH;
491
- if (ssrEnabled) {
492
- const ssrEntryPath = options.ssrEntry ?? (resourcesDir ? resolve3(resourcesDir, "js/ssr.tsx") : void 0);
493
- if (ssrEntryPath) {
494
- setEnvIfUserDidNotProvide("GUREN_INERTIA_SSR_ENTRY", ssrEntryPath);
495
- }
496
- setEnvIfUserDidNotProvide("GUREN_INERTIA_SSR_MANIFEST", "");
497
- } else {
498
- setEnvIfUserDidNotProvide("GUREN_INERTIA_SSR_ENTRY", "");
499
- setEnvIfUserDidNotProvide("GUREN_INERTIA_SSR_MANIFEST", "");
500
- }
501
- process.env.GUREN_INERTIA_IMPORT_MAP = JSON.stringify(importMapEntries);
502
- return;
503
- }
504
- const clientManifest = loadViteManifest(
505
- [
506
- resolve3(moduleDir, "../public/assets/manifest.json"),
507
- resolve3(moduleDir, "../public/assets/.vite/manifest.json")
508
- ],
509
- "client"
510
- );
511
- const clientEntry = clientManifest?.["resources/js/app.tsx"];
512
- const clientEntryFile = getManifestFile(clientEntry);
513
- const clientCssFiles = getManifestCss(clientEntry);
514
- if (clientManifest?.__raw__) {
515
- setEnvIfUserDidNotProvide(
516
- "GUREN_INERTIA_VERSION",
517
- hash(clientManifest.__raw__, "sha1").slice(0, 12)
518
- );
519
- }
520
- if (clientEntryFile) {
521
- setEnvIfUserDidNotProvide("GUREN_INERTIA_ENTRY", `/public/assets/${clientEntryFile.replace(/^\//u, "")}`);
522
- }
523
- if (clientCssFiles?.length) {
524
- setEnvIfUserDidNotProvide(
525
- "GUREN_INERTIA_STYLES",
526
- clientCssFiles.map((href) => `/public/assets/${href.replace(/^\//u, "")}`).join(",")
527
- );
528
- }
529
- importMapEntries["@guren/inertia-client"] = DEFAULT_VENDOR_CLIENT_PATH;
530
- if (!ssrEnabled) {
531
- if (Object.keys(importMapEntries).length > 0) {
532
- process.env.GUREN_INERTIA_IMPORT_MAP = JSON.stringify(importMapEntries);
533
- }
534
- setEnvIfUserDidNotProvide("GUREN_INERTIA_SSR_ENTRY", "");
535
- setEnvIfUserDidNotProvide("GUREN_INERTIA_SSR_MANIFEST", "");
536
- return;
537
- }
538
- const ssrManifestPaths = [
539
- options.ssrManifest,
540
- resolve3(moduleDir, `../${ssrOutDir}/manifest.json`),
541
- resolve3(moduleDir, `../${ssrOutDir}/.vite/manifest.json`),
542
- resolve3(moduleDir, `../${ssrOutDir}/ssr-manifest.json`),
543
- resolve3(moduleDir, "../build/ssr/manifest.json"),
544
- resolve3(moduleDir, "../build/ssr/.vite/manifest.json"),
545
- resolve3(moduleDir, "../build/ssr/ssr-manifest.json"),
546
- resolve3(moduleDir, "../public/assets/.ssr/manifest.json"),
547
- resolve3(moduleDir, "../public/assets/.ssr/.vite/manifest.json"),
548
- resolve3(moduleDir, "../public/assets/.ssr/ssr-manifest.json"),
549
- resolve3(moduleDir, "../public/assets/.vite/ssr-manifest.json")
550
- ].filter((value) => Boolean(value));
551
- const ssrManifest = loadViteManifest(ssrManifestPaths, "SSR");
552
- const ssrEntry = ssrManifest?.["resources/js/ssr.tsx"];
553
- const ssrEntryFile = getManifestFile(ssrEntry);
554
- const ssrEntryRoot = deriveAssetRoot(ssrManifest, resolve3(moduleDir, `../${ssrOutDir}`));
555
- if (ssrEntryFile && ssrEntryRoot) {
556
- setEnvIfUserDidNotProvide(
557
- "GUREN_INERTIA_SSR_ENTRY",
558
- resolve3(ssrEntryRoot, ssrEntryFile.replace(/^\//u, ""))
559
- );
560
- }
561
- if (Object.keys(importMapEntries).length > 0) {
562
- process.env.GUREN_INERTIA_IMPORT_MAP = JSON.stringify(importMapEntries);
563
- }
564
- if (ssrManifest?.__path__) {
565
- setEnvIfUserDidNotProvide("GUREN_INERTIA_SSR_MANIFEST", ssrManifest.__path__);
566
- }
405
+ const providedEnv = captureInertiaEnvFlags();
406
+ configureInertiaAssets(app, options);
407
+ const moduleDir = options.importMeta ? dirname(fileURLToPath(options.importMeta.url)) : void 0;
408
+ const resourcesDir = resolveResourcesDir(options, moduleDir);
409
+ const ssrOutDir = options.ssrOutDir ?? ".guren/ssr";
410
+ const importMapEntries = parseImportMap(process.env.GUREN_INERTIA_IMPORT_MAP, { context: "GUREN_INERTIA_IMPORT_MAP from environment" });
411
+ const ssrEnabled = options.enableSsr ?? true;
412
+ const setEnvIfUserDidNotProvide = (key, value) => {
413
+ if (providedEnv[key]) return;
414
+ process.env[key] = value;
415
+ };
416
+ if (!moduleDir) return;
417
+ if (!((process.env.NODE_ENV ?? "development") === "production" && typeof process.env.VITE_DEV_SERVER_URL !== "string")) {
418
+ setEnvIfUserDidNotProvide("GUREN_INERTIA_ENTRY", `${normalizeDevServerUrl(options.devServerUrl ?? process.env.VITE_DEV_SERVER_URL ?? "http://localhost:5173")}/resources/js/dev-entry.ts`);
419
+ setEnvIfUserDidNotProvide("GUREN_INERTIA_STYLES", options.stylesEntry ?? "/resources/css/app.css");
420
+ importMapEntries["@guren/inertia-client"] = DEFAULT_VENDOR_CLIENT_PATH;
421
+ if (ssrEnabled) {
422
+ const ssrEntryPath = options.ssrEntry ?? (resourcesDir ? resolve(resourcesDir, "js/ssr.tsx") : void 0);
423
+ if (ssrEntryPath) setEnvIfUserDidNotProvide("GUREN_INERTIA_SSR_ENTRY", ssrEntryPath);
424
+ setEnvIfUserDidNotProvide("GUREN_INERTIA_SSR_MANIFEST", "");
425
+ } else {
426
+ setEnvIfUserDidNotProvide("GUREN_INERTIA_SSR_ENTRY", "");
427
+ setEnvIfUserDidNotProvide("GUREN_INERTIA_SSR_MANIFEST", "");
428
+ }
429
+ process.env.GUREN_INERTIA_IMPORT_MAP = JSON.stringify(importMapEntries);
430
+ return;
431
+ }
432
+ const clientManifest = loadViteManifest([resolve(moduleDir, "../public/assets/manifest.json"), resolve(moduleDir, "../public/assets/.vite/manifest.json")], "client");
433
+ const clientEntry = clientManifest?.["resources/js/app.tsx"];
434
+ const clientEntryFile = getManifestFile(clientEntry);
435
+ const clientCssFiles = getManifestCss(clientEntry);
436
+ if (clientManifest?.__raw__) setEnvIfUserDidNotProvide("GUREN_INERTIA_VERSION", hash(clientManifest.__raw__, "sha1").slice(0, 12));
437
+ if (clientEntryFile) setEnvIfUserDidNotProvide("GUREN_INERTIA_ENTRY", `/public/assets/${clientEntryFile.replace(/^\//u, "")}`);
438
+ if (clientCssFiles?.length) setEnvIfUserDidNotProvide("GUREN_INERTIA_STYLES", clientCssFiles.map((href) => `/public/assets/${href.replace(/^\//u, "")}`).join(","));
439
+ importMapEntries["@guren/inertia-client"] = DEFAULT_VENDOR_CLIENT_PATH;
440
+ if (!ssrEnabled) {
441
+ if (Object.keys(importMapEntries).length > 0) process.env.GUREN_INERTIA_IMPORT_MAP = JSON.stringify(importMapEntries);
442
+ setEnvIfUserDidNotProvide("GUREN_INERTIA_SSR_ENTRY", "");
443
+ setEnvIfUserDidNotProvide("GUREN_INERTIA_SSR_MANIFEST", "");
444
+ return;
445
+ }
446
+ const ssrManifest = loadViteManifest([
447
+ options.ssrManifest,
448
+ resolve(moduleDir, `../${ssrOutDir}/manifest.json`),
449
+ resolve(moduleDir, `../${ssrOutDir}/.vite/manifest.json`),
450
+ resolve(moduleDir, `../${ssrOutDir}/ssr-manifest.json`),
451
+ resolve(moduleDir, "../build/ssr/manifest.json"),
452
+ resolve(moduleDir, "../build/ssr/.vite/manifest.json"),
453
+ resolve(moduleDir, "../build/ssr/ssr-manifest.json"),
454
+ resolve(moduleDir, "../public/assets/.ssr/manifest.json"),
455
+ resolve(moduleDir, "../public/assets/.ssr/.vite/manifest.json"),
456
+ resolve(moduleDir, "../public/assets/.ssr/ssr-manifest.json"),
457
+ resolve(moduleDir, "../public/assets/.vite/ssr-manifest.json")
458
+ ].filter((value) => Boolean(value)), "SSR");
459
+ const ssrEntry = ssrManifest?.["resources/js/ssr.tsx"];
460
+ const ssrEntryFile = getManifestFile(ssrEntry);
461
+ const ssrEntryRoot = deriveAssetRoot(ssrManifest, resolve(moduleDir, `../${ssrOutDir}`));
462
+ if (ssrEntryFile && ssrEntryRoot) setEnvIfUserDidNotProvide("GUREN_INERTIA_SSR_ENTRY", resolve(ssrEntryRoot, ssrEntryFile.replace(/^\//u, "")));
463
+ if (Object.keys(importMapEntries).length > 0) process.env.GUREN_INERTIA_IMPORT_MAP = JSON.stringify(importMapEntries);
464
+ if (ssrManifest?.__path__) setEnvIfUserDidNotProvide("GUREN_INERTIA_SSR_MANIFEST", ssrManifest.__path__);
567
465
  }
568
466
  function captureInertiaEnvFlags() {
569
- return {
570
- GUREN_INERTIA_ENTRY: process.env.GUREN_INERTIA_ENTRY !== void 0,
571
- GUREN_INERTIA_STYLES: process.env.GUREN_INERTIA_STYLES !== void 0,
572
- GUREN_INERTIA_SSR_ENTRY: process.env.GUREN_INERTIA_SSR_ENTRY !== void 0,
573
- GUREN_INERTIA_SSR_MANIFEST: process.env.GUREN_INERTIA_SSR_MANIFEST !== void 0,
574
- GUREN_INERTIA_VERSION: process.env.GUREN_INERTIA_VERSION !== void 0
575
- };
467
+ return {
468
+ GUREN_INERTIA_ENTRY: process.env.GUREN_INERTIA_ENTRY !== void 0,
469
+ GUREN_INERTIA_STYLES: process.env.GUREN_INERTIA_STYLES !== void 0,
470
+ GUREN_INERTIA_SSR_ENTRY: process.env.GUREN_INERTIA_SSR_ENTRY !== void 0,
471
+ GUREN_INERTIA_SSR_MANIFEST: process.env.GUREN_INERTIA_SSR_MANIFEST !== void 0,
472
+ GUREN_INERTIA_VERSION: process.env.GUREN_INERTIA_VERSION !== void 0
473
+ };
576
474
  }
577
475
  function resolveDevSsrEntry(options) {
578
- if (options.ssrEntry) {
579
- return options.ssrEntry;
580
- }
581
- if (options.resourcesDir) {
582
- return resolve3(options.resourcesDir, "js/ssr.tsx");
583
- }
584
- const moduleDir = options.importMeta ? dirname2(fileURLToPath2(options.importMeta.url)) : void 0;
585
- if (!moduleDir) {
586
- return void 0;
587
- }
588
- const resourcesPath = options.resourcesPath ?? "../resources";
589
- const resourcesDir = resolve3(moduleDir, resourcesPath);
590
- return resolve3(resourcesDir, "js/ssr.tsx");
476
+ if (options.ssrEntry) return options.ssrEntry;
477
+ if (options.resourcesDir) return resolve(options.resourcesDir, "js/ssr.tsx");
478
+ const moduleDir = options.importMeta ? dirname(fileURLToPath(options.importMeta.url)) : void 0;
479
+ if (!moduleDir) return;
480
+ const resourcesPath = options.resourcesPath ?? "../resources";
481
+ const resourcesDir = resolve(moduleDir, resourcesPath);
482
+ return resolve(resourcesDir, "js/ssr.tsx");
591
483
  }
592
484
  function normalizeDevServerUrl(value) {
593
- if (!value) {
594
- return value;
595
- }
596
- const trimmed = value.trim();
597
- if (!trimmed) {
598
- return trimmed;
599
- }
600
- const stripped = trimTrailingSlashes(trimmed);
601
- return stripped.length > 0 ? stripped : "/";
485
+ if (!value) return value;
486
+ const trimmed = value.trim();
487
+ if (!trimmed) return trimmed;
488
+ const stripped = trimTrailingSlashes(trimmed);
489
+ return stripped.length > 0 ? stripped : "/";
602
490
  }
603
491
  function loadViteManifest(candidatePaths, label) {
604
- const command = label === "SSR" ? "bunx vite build --ssr" : "bunx vite build";
605
- for (const manifestPath of candidatePaths) {
606
- try {
607
- const raw = readFileSync(manifestPath, "utf8");
608
- const manifest = JSON.parse(raw);
609
- Object.defineProperty(manifest, "__path__", {
610
- value: manifestPath,
611
- enumerable: false
612
- });
613
- Object.defineProperty(manifest, "__raw__", {
614
- value: raw,
615
- enumerable: false
616
- });
617
- return manifest;
618
- } catch (error) {
619
- if (error.code !== "ENOENT") {
620
- console.warn(`Unable to load ${label} Vite manifest at ${manifestPath}.`, error);
621
- return void 0;
622
- }
623
- }
624
- }
625
- if (candidatePaths.length) {
626
- console.warn(
627
- `Unable to load ${label} Vite manifest. Checked paths:
628
- ${candidatePaths.map((p) => ` - ${p}`).join("\n")}
629
- Run \`${command}\` before starting in production.`
630
- );
631
- }
632
- return void 0;
492
+ const command = label === "SSR" ? "bunx vite build --ssr" : "bunx vite build";
493
+ for (const manifestPath of candidatePaths) try {
494
+ const raw = readFileSync(manifestPath, "utf8");
495
+ const manifest = JSON.parse(raw);
496
+ Object.defineProperty(manifest, "__path__", {
497
+ value: manifestPath,
498
+ enumerable: false
499
+ });
500
+ Object.defineProperty(manifest, "__raw__", {
501
+ value: raw,
502
+ enumerable: false
503
+ });
504
+ return manifest;
505
+ } catch (error) {
506
+ if (error.code !== "ENOENT") {
507
+ console.warn(`Unable to load ${label} Vite manifest at ${manifestPath}.`, error);
508
+ return;
509
+ }
510
+ }
511
+ if (candidatePaths.length) console.warn(`Unable to load ${label} Vite manifest. Checked paths:\n${candidatePaths.map((p) => ` - ${p}`).join("\n")}\nRun \`${command}\` before starting in production.`);
633
512
  }
634
513
  function deriveAssetRoot(manifest, fallback) {
635
- if (!manifest?.__path__) {
636
- return fallback;
637
- }
638
- return resolve3(dirname2(manifest.__path__), "..");
514
+ if (!manifest?.__path__) return fallback;
515
+ return resolve(dirname(manifest.__path__), "..");
639
516
  }
640
517
  function getManifestFile(entry) {
641
- if (!entry) {
642
- return void 0;
643
- }
644
- if (Array.isArray(entry)) {
645
- return entry[0];
646
- }
647
- if (typeof entry === "string") {
648
- return entry;
649
- }
650
- if ("file" in entry && typeof entry.file === "string") {
651
- return entry.file;
652
- }
653
- return void 0;
518
+ if (!entry) return;
519
+ if (Array.isArray(entry)) return entry[0];
520
+ if (typeof entry === "string") return entry;
521
+ if ("file" in entry && typeof entry.file === "string") return entry.file;
654
522
  }
655
523
  function getManifestCss(entry) {
656
- if (!entry || Array.isArray(entry) || typeof entry === "string") {
657
- return void 0;
658
- }
659
- return entry.css;
524
+ if (!entry || Array.isArray(entry) || typeof entry === "string") return;
525
+ return entry.css;
660
526
  }
661
527
  function resolveResourcesDir(options, moduleDir) {
662
- if (options.resourcesDir) {
663
- return options.resourcesDir;
664
- }
665
- if (!moduleDir) {
666
- return void 0;
667
- }
668
- const resourcesPath = options.resourcesPath ?? "../resources";
669
- return resolve3(moduleDir, resourcesPath);
528
+ if (options.resourcesDir) return options.resourcesDir;
529
+ if (!moduleDir) return;
530
+ const resourcesPath = options.resourcesPath ?? "../resources";
531
+ return resolve(moduleDir, resourcesPath);
670
532
  }
671
- export {
672
- GUREN_ASCII_ART,
673
- autoConfigureInertiaAssets,
674
- configureInertiaAssets,
675
- logDevServerBanner,
676
- registerDevAssets,
677
- startViteDevServer
678
- };
533
+ //#endregion
534
+ export { GUREN_ASCII_ART, autoConfigureInertiaAssets, configureInertiaAssets, logDevServerBanner, registerDevAssets, startViteDevServer };