@stratal/inertia 0.0.21 → 0.0.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,392 @@
1
+ import { t as __decorate } from "./decorate-B7nr7eBl.mjs";
2
+ import { n as runTypeGeneration, t as findPagesDir } from "./type-generator-DFpha_Fp.mjs";
3
+ import { Module } from "stratal/module";
4
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
5
+ import { dirname, join, relative } from "node:path";
6
+ import { spawn } from "node:child_process";
7
+ import { Command } from "stratal/quarry";
8
+ import { watch } from "node:fs/promises";
9
+ //#region src/vite/create-client-vite-config.ts
10
+ /**
11
+ * Emits a standalone Vite config for building the Inertia browser bundle.
12
+ *
13
+ * This runs as a separate `vite build` invocation BEFORE the worker build so
14
+ * the worker's `stratal:inertia-inject-manifest` plugin has a finished
15
+ * `<outDir>/.vite/manifest.json` to read. `@cloudflare/vite-plugin` builds its
16
+ * environments in parallel, which made a single-config build racy — splitting
17
+ * the two phases removes the race entirely and keeps each build minimal.
18
+ */
19
+ function writeTempClientViteConfig(options) {
20
+ const configPath = join(join(options.cwd, "node_modules", ".stratal"), "vite.client.config.mjs");
21
+ mkdirSync(dirname(configPath), { recursive: true });
22
+ const entry = (options.entry ?? "src/inertia/app.tsx").replace(/\\/g, "/");
23
+ const outDir = (options.outDir ?? "dist/client").replace(/\\/g, "/");
24
+ const hasUserConfig = existsSync(join(options.cwd, "vite.config.ts"));
25
+ writeFileSync(configPath, `
26
+ import { mergeConfig } from 'vite'
27
+
28
+ const baseConfig = {
29
+ publicDir: '${join(options.cwd, "src", "inertia", "public").replace(/\\/g, "/")}',
30
+ build: {
31
+ outDir: '${outDir}',
32
+ manifest: true,
33
+ emptyOutDir: true,
34
+ rollupOptions: {
35
+ input: { app: '${entry}' },
36
+ },
37
+ },
38
+ }
39
+
40
+ ${hasUserConfig ? `const userModule = await import('${join(options.cwd, "vite.config.ts").replace(/\\/g, "/")}')
41
+ const userConfig = userModule.default ?? userModule
42
+ export default mergeConfig(userConfig, baseConfig)` : "export default baseConfig"}
43
+ `, "utf-8");
44
+ return configPath;
45
+ }
46
+ //#endregion
47
+ //#region src/vite/create-vite-config.ts
48
+ function writeTempViteConfig(options) {
49
+ const configPath = join(join(options.cwd, "node_modules", ".stratal"), "vite.config.mjs");
50
+ mkdirSync(dirname(configPath), { recursive: true });
51
+ const hasUserConfig = existsSync(join(options.cwd, "vite.config.ts"));
52
+ const serverConfig = options.server ? `server: { port: ${options.server.port}, host: ${options.server.host ? "true" : "undefined"} },` : "";
53
+ const outDirConfig = options.outDir ? `outDir: '${options.outDir}',` : "";
54
+ writeFileSync(configPath, `
55
+ import { mergeConfig } from 'vite'
56
+ import { cloudflare } from '@cloudflare/vite-plugin'
57
+ import { stratalInertia } from '@stratal/inertia/vite'
58
+
59
+ let inertiaPlugin = null
60
+ try {
61
+ const mod = await import('@inertiajs/vite')
62
+ const inertia = mod.default ?? mod
63
+ inertiaPlugin = inertia()
64
+ } catch {}
65
+
66
+ const baseConfig = {
67
+ publicDir: 'src/inertia/public',
68
+ plugins: [
69
+ cloudflare(${options.persistTo ? `{ persistState: { path: ${JSON.stringify(options.persistTo)} } }` : ""}),
70
+ ...(inertiaPlugin ? [inertiaPlugin] : []),
71
+ ...stratalInertia(${options.clientManifestPath ? `{ clientManifestPath: ${JSON.stringify(options.clientManifestPath)} }` : ""}),
72
+ ],
73
+ build: {
74
+ ${outDirConfig}
75
+ },
76
+ ${serverConfig}
77
+ }
78
+
79
+ ${hasUserConfig ? `const userModule = await import('${join(options.cwd, "vite.config.ts").replace(/\\/g, "/")}')
80
+ const userConfig = userModule.default ?? userModule
81
+ export default mergeConfig(baseConfig, userConfig)` : "export default baseConfig"}
82
+ `, "utf-8");
83
+ return configPath;
84
+ }
85
+ //#endregion
86
+ //#region src/commands/inertia-build.command.ts
87
+ var InertiaBuildCommand = class extends Command {
88
+ static command = "inertia:build {--outDir=dist : Output directory} {--ssr : Also build SSR bundle}";
89
+ static description = "Build Inertia.js frontend for production";
90
+ async handle() {
91
+ const outDir = this.string("outDir") || "dist";
92
+ const shouldBuildSsr = this.boolean("ssr");
93
+ const cwd = process.cwd();
94
+ const entryPath = "src/inertia/app.tsx";
95
+ if (!existsSync(join(cwd, entryPath))) {
96
+ this.fail("src/inertia/app.tsx not found. Run `quarry inertia:install` first.");
97
+ return 1;
98
+ }
99
+ const clientOutDir = join(outDir, "client").replace(/\\/g, "/");
100
+ const clientConfigPath = writeTempClientViteConfig({
101
+ cwd,
102
+ entry: entryPath,
103
+ outDir: clientOutDir
104
+ });
105
+ this.info("Building Inertia.js browser bundle...");
106
+ const browserCode = await this.spawnVite(cwd, clientConfigPath, ["build"]);
107
+ if (browserCode !== 0) {
108
+ this.fail("Browser bundle build failed.");
109
+ return browserCode;
110
+ }
111
+ this.success(`Browser bundle written to ${clientOutDir}/`);
112
+ const configPath = writeTempViteConfig({
113
+ cwd,
114
+ outDir,
115
+ clientManifestPath: join(clientOutDir, ".vite", "manifest.json").replace(/\\/g, "/")
116
+ });
117
+ this.info("Building Cloudflare worker bundle...");
118
+ const workerCode = await this.spawnVite(cwd, configPath, ["build"]);
119
+ if (workerCode !== 0) {
120
+ this.fail("Worker build failed.");
121
+ return workerCode;
122
+ }
123
+ this.success("Worker build complete!");
124
+ if (shouldBuildSsr) {
125
+ this.info("Building SSR bundle...");
126
+ const ssrCode = await this.spawnVite(cwd, configPath, ["build", "--ssr"]);
127
+ if (ssrCode !== 0) {
128
+ this.fail("SSR build failed.");
129
+ return ssrCode;
130
+ }
131
+ this.success("SSR build complete!");
132
+ }
133
+ this.success(`Output in ${outDir}/`);
134
+ this.info("Deploy with: npx wrangler deploy");
135
+ return 0;
136
+ }
137
+ spawnVite(cwd, configPath, args) {
138
+ return new Promise((resolve) => {
139
+ const child = spawn("npx", [
140
+ "vite",
141
+ "--config",
142
+ configPath,
143
+ ...args
144
+ ], {
145
+ cwd,
146
+ stdio: "inherit",
147
+ shell: true
148
+ });
149
+ child.on("error", (err) => {
150
+ this.fail(`Vite process error: ${err.message}`);
151
+ resolve(1);
152
+ });
153
+ child.on("close", (code) => {
154
+ resolve(code ?? 0);
155
+ });
156
+ });
157
+ }
158
+ };
159
+ //#endregion
160
+ //#region src/commands/inertia-dev.command.ts
161
+ var InertiaDevCommand = class extends Command {
162
+ static command = "inertia:dev {--port= : Dev server port} {--host : Expose to network} {--persist-to= : Shared persist directory for @cloudflare/vite-plugin (relative to cwd; the plugin appends /v3). Use to share R2/KV/cache emulator state across multiple workers in dev.}";
163
+ static description = "Start Inertia.js Vite development server";
164
+ async handle() {
165
+ const port = this.number("port");
166
+ const host = this.boolean("host");
167
+ const persistTo = this.string("persist-to");
168
+ const cwd = process.cwd();
169
+ if (!existsSync(join(cwd, "src/inertia/app.tsx"))) {
170
+ this.fail("src/inertia/app.tsx not found. Run `quarry inertia:install` first.");
171
+ return 1;
172
+ }
173
+ const configPath = writeTempViteConfig({
174
+ cwd,
175
+ server: {
176
+ port,
177
+ host
178
+ },
179
+ persistTo
180
+ });
181
+ this.info("Starting Vite dev server...");
182
+ const args = [
183
+ "vite",
184
+ "dev",
185
+ "--config",
186
+ configPath
187
+ ];
188
+ if (host) args.push("--host");
189
+ return new Promise((resolve) => {
190
+ const child = spawn("npx", args, {
191
+ cwd,
192
+ stdio: "inherit",
193
+ shell: true
194
+ });
195
+ child.on("error", (err) => {
196
+ this.fail(`Failed to start dev server: ${err.message}`);
197
+ resolve(1);
198
+ });
199
+ child.on("close", (code) => {
200
+ resolve(code ?? 0);
201
+ });
202
+ });
203
+ }
204
+ };
205
+ //#endregion
206
+ //#region src/commands/inertia-install.command.ts
207
+ const ROOT_HTML = `<!DOCTYPE html>
208
+ <html lang="en">
209
+ <head>
210
+ <meta charset="utf-8" />
211
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
212
+ @viteHead
213
+ @inertiaHead
214
+ </head>
215
+ <body>
216
+ @inertia
217
+ @viteScripts
218
+ </body>
219
+ </html>`;
220
+ const APP_TSX = `import { createInertiaApp } from '@inertiajs/react'
221
+
222
+ createInertiaApp({
223
+ resolve: async (name) => {
224
+ const pages = import.meta.glob('./pages/**/*.tsx')
225
+ const page = await pages[\`./pages/\${name}.tsx\`]?.()
226
+ if (!page) throw new Error(\`Page not found: \${name}\`)
227
+ return page
228
+ },
229
+ })`;
230
+ const HOME_TSX = `export default function Home({ message }: { message: string }) {
231
+ return (
232
+ <div>
233
+ <h1>{message}</h1>
234
+ <p>This page is rendered with Inertia.js and Stratal.</p>
235
+ </div>
236
+ )
237
+ }`;
238
+ var InertiaInstallCommand = class extends Command {
239
+ static command = "inertia:install {--skip-deps : Skip installing npm dependencies}";
240
+ static description = "Scaffold Inertia.js files for a Stratal project";
241
+ async handle() {
242
+ const skipDeps = this.boolean("skip-deps");
243
+ const cwd = process.cwd();
244
+ const inertiaDir = join(cwd, "src", "inertia");
245
+ const pagesDir = join(inertiaDir, "pages");
246
+ this.info("Creating src/inertia/ directory...");
247
+ mkdirSync(pagesDir, { recursive: true });
248
+ const publicDir = join(inertiaDir, "public");
249
+ mkdirSync(publicDir, { recursive: true });
250
+ const gitkeepPath = join(publicDir, ".gitkeep");
251
+ if (!existsSync(gitkeepPath)) writeFileSync(gitkeepPath, "", "utf-8");
252
+ this.success("Created src/inertia/public/");
253
+ const files = [
254
+ {
255
+ path: join(inertiaDir, "root.html"),
256
+ content: ROOT_HTML,
257
+ name: "root.html"
258
+ },
259
+ {
260
+ path: join(inertiaDir, "app.tsx"),
261
+ content: APP_TSX,
262
+ name: "app.tsx"
263
+ },
264
+ {
265
+ path: join(pagesDir, "Home.tsx"),
266
+ content: HOME_TSX,
267
+ name: "pages/Home.tsx"
268
+ }
269
+ ];
270
+ for (const file of files) if (existsSync(file.path)) this.warn(`Skipping ${file.name} (already exists)`);
271
+ else {
272
+ writeFileSync(file.path, file.content, "utf-8");
273
+ this.success(`Created src/inertia/${file.name}`);
274
+ }
275
+ const appModulePath = join(cwd, "src", "app.module.ts");
276
+ if (existsSync(appModulePath)) {
277
+ this.info("Updating src/app.module.ts...");
278
+ try {
279
+ if (await this.updateAppModule(appModulePath)) this.success("Updated src/app.module.ts with InertiaModule");
280
+ else this.info("InertiaModule already configured in app.module.ts");
281
+ } catch (err) {
282
+ this.warn(`Could not auto-update app.module.ts: ${err.message}`);
283
+ this.info("Please manually add InertiaModule.forRoot() to your module imports");
284
+ }
285
+ } else this.info("No src/app.module.ts found — please manually configure InertiaModule");
286
+ try {
287
+ const { outputPath, pageCount } = await runTypeGeneration(cwd);
288
+ const relPath = relative(cwd, outputPath);
289
+ this.success(`Generated ${relPath} (${pageCount} page${pageCount !== 1 ? "s" : ""})`);
290
+ } catch {
291
+ this.warn("Could not generate initial type definitions. Run `quarry inertia:types` manually.");
292
+ }
293
+ if (!skipDeps) {
294
+ this.newLine();
295
+ this.info("Install the following dependencies:");
296
+ this.line(" npm install @stratal/inertia @inertiajs/react @inertiajs/vite react react-dom");
297
+ this.line(" npm install -D @types/react @types/react-dom vite @cloudflare/vite-plugin");
298
+ }
299
+ this.newLine();
300
+ this.success("Inertia.js scaffolding complete!");
301
+ this.info("Run `quarry inertia:dev` to start the dev server");
302
+ return 0;
303
+ }
304
+ async updateAppModule(modulePath) {
305
+ const { Project, SyntaxKind } = await import("ts-morph");
306
+ const sourceFile = new Project({ useInMemoryFileSystem: false }).addSourceFileAtPath(modulePath);
307
+ if (sourceFile.getImportDeclaration((decl) => decl.getModuleSpecifierValue() === "@stratal/inertia")) return false;
308
+ sourceFile.addImportDeclaration({
309
+ defaultImport: "rootView",
310
+ moduleSpecifier: "./inertia/root.html?raw"
311
+ });
312
+ sourceFile.addImportDeclaration({
313
+ namedImports: ["InertiaModule"],
314
+ moduleSpecifier: "@stratal/inertia"
315
+ });
316
+ const classes = sourceFile.getClasses();
317
+ for (const cls of classes) {
318
+ const moduleDecorator = cls.getDecorator("Module");
319
+ if (!moduleDecorator) continue;
320
+ const args = moduleDecorator.getArguments();
321
+ if (args.length === 0) continue;
322
+ const objLiteral = args[0].asKind(SyntaxKind.ObjectLiteralExpression);
323
+ if (!objLiteral) continue;
324
+ const importsProp = objLiteral.getProperty("imports");
325
+ if (importsProp) {
326
+ const arrayLiteral = (importsProp.asKind(SyntaxKind.PropertyAssignment)?.getInitializer())?.asKind(SyntaxKind.ArrayLiteralExpression);
327
+ if (arrayLiteral) arrayLiteral.addElement(`InertiaModule.forRoot({\n rootView,\n })`);
328
+ } else objLiteral.addPropertyAssignment({
329
+ name: "imports",
330
+ initializer: `[\n InertiaModule.forRoot({\n rootView,\n }),\n ]`
331
+ });
332
+ break;
333
+ }
334
+ await sourceFile.save();
335
+ return true;
336
+ }
337
+ };
338
+ //#endregion
339
+ //#region src/commands/inertia-types.command.ts
340
+ var InertiaTypesCommand = class extends Command {
341
+ static command = "inertia:types {--watch : Watch for changes and regenerate}";
342
+ static description = "Generate Inertia.js page type definitions";
343
+ async handle() {
344
+ const cwd = process.cwd();
345
+ if (!existsSync(findPagesDir(cwd))) {
346
+ this.fail("src/inertia/pages/ not found. Run `quarry inertia:install` first.");
347
+ return 1;
348
+ }
349
+ if (!await this.generate(cwd)) return 1;
350
+ if (this.boolean("watch")) {
351
+ this.info("Watching for changes...");
352
+ await this.watchForChanges(cwd);
353
+ }
354
+ return 0;
355
+ }
356
+ async generate(cwd) {
357
+ try {
358
+ const { outputPath, pageCount } = await runTypeGeneration(cwd);
359
+ const relPath = relative(cwd, outputPath);
360
+ this.success(`Generated ${relPath} (${pageCount} page${pageCount !== 1 ? "s" : ""})`);
361
+ return true;
362
+ } catch (err) {
363
+ this.fail(`Type generation failed: ${err.message}`);
364
+ return false;
365
+ }
366
+ }
367
+ async watchForChanges(cwd) {
368
+ const srcDir = join(cwd, "src");
369
+ try {
370
+ const watcher = watch(srcDir, { recursive: true });
371
+ for await (const event of watcher) if (event.filename && /\.(tsx|ts)$/.test(event.filename)) {
372
+ this.info(`Change detected: ${event.filename}`);
373
+ await this.generate(cwd);
374
+ }
375
+ } catch (err) {
376
+ this.fail(`Watch failed: ${err.message}`);
377
+ }
378
+ }
379
+ };
380
+ //#endregion
381
+ //#region src/quarry.ts
382
+ let InertiaQuarryModule = class InertiaQuarryModule {};
383
+ InertiaQuarryModule = __decorate([Module({ providers: [
384
+ InertiaInstallCommand,
385
+ InertiaTypesCommand,
386
+ InertiaDevCommand,
387
+ InertiaBuildCommand
388
+ ] })], InertiaQuarryModule);
389
+ //#endregion
390
+ export { InertiaBuildCommand, InertiaDevCommand, InertiaInstallCommand, InertiaQuarryModule, InertiaTypesCommand, runTypeGeneration };
391
+
392
+ //# sourceMappingURL=quarry.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"quarry.mjs","names":[],"sources":["../src/vite/create-client-vite-config.ts","../src/vite/create-vite-config.ts","../src/commands/inertia-build.command.ts","../src/commands/inertia-dev.command.ts","../src/commands/inertia-install.command.ts","../src/commands/inertia-types.command.ts","../src/quarry.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nexport interface TempClientViteConfigOptions {\n cwd: string\n entry?: string\n outDir?: string\n}\n\n/**\n * Emits a standalone Vite config for building the Inertia browser bundle.\n *\n * This runs as a separate `vite build` invocation BEFORE the worker build so\n * the worker's `stratal:inertia-inject-manifest` plugin has a finished\n * `<outDir>/.vite/manifest.json` to read. `@cloudflare/vite-plugin` builds its\n * environments in parallel, which made a single-config build racy — splitting\n * the two phases removes the race entirely and keeps each build minimal.\n */\nexport function writeTempClientViteConfig(options: TempClientViteConfigOptions): string {\n const configDir = join(options.cwd, 'node_modules', '.stratal')\n const configPath = join(configDir, 'vite.client.config.mjs')\n mkdirSync(dirname(configPath), { recursive: true })\n\n const entry = (options.entry ?? 'src/inertia/app.tsx').replace(/\\\\/g, '/')\n const outDir = (options.outDir ?? 'dist/client').replace(/\\\\/g, '/')\n const hasUserConfig = existsSync(join(options.cwd, 'vite.config.ts'))\n const publicDir = join(options.cwd, 'src', 'inertia', 'public').replace(/\\\\/g, '/')\n\n const content = `\nimport { mergeConfig } from 'vite'\n\nconst baseConfig = {\n publicDir: '${publicDir}',\n build: {\n outDir: '${outDir}',\n manifest: true,\n emptyOutDir: true,\n rollupOptions: {\n input: { app: '${entry}' },\n },\n },\n}\n\n${hasUserConfig\n ? `const userModule = await import('${join(options.cwd, 'vite.config.ts').replace(/\\\\/g, '/')}')\nconst userConfig = userModule.default ?? userModule\nexport default mergeConfig(userConfig, baseConfig)`\n : 'export default baseConfig'\n }\n`\n\n writeFileSync(configPath, content, 'utf-8')\n return configPath\n}\n","import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nexport interface TempViteConfigOptions {\n cwd: string\n server?: { port?: number; host?: boolean }\n outDir?: string\n persistTo?: string\n /**\n * Path (relative to `cwd`) to the Vite client manifest the worker bundle\n * should inline. Defaults to `dist/client/.vite/manifest.json`, matching\n * what `quarry inertia:build` emits in phase 1.\n */\n clientManifestPath?: string\n}\n\nexport function writeTempViteConfig(options: TempViteConfigOptions): string {\n const configDir = join(options.cwd, 'node_modules', '.stratal')\n const configPath = join(configDir, 'vite.config.mjs')\n mkdirSync(dirname(configPath), { recursive: true })\n\n const hasUserConfig = existsSync(join(options.cwd, 'vite.config.ts'))\n\n const serverConfig = options.server\n ? `server: { port: ${options.server.port}, host: ${options.server.host ? 'true' : 'undefined'} },`\n : ''\n\n const outDirConfig = options.outDir\n ? `outDir: '${options.outDir}',`\n : ''\n\n const cloudflareArgs = options.persistTo\n ? `{ persistState: { path: ${JSON.stringify(options.persistTo)} } }`\n : ''\n\n const stratalArgs = options.clientManifestPath\n ? `{ clientManifestPath: ${JSON.stringify(options.clientManifestPath)} }`\n : ''\n\n const content = `\nimport { mergeConfig } from 'vite'\nimport { cloudflare } from '@cloudflare/vite-plugin'\nimport { stratalInertia } from '@stratal/inertia/vite'\n\nlet inertiaPlugin = null\ntry {\n const mod = await import('@inertiajs/vite')\n const inertia = mod.default ?? mod\n inertiaPlugin = inertia()\n} catch {}\n\nconst baseConfig = {\n publicDir: 'src/inertia/public',\n plugins: [\n cloudflare(${cloudflareArgs}),\n ...(inertiaPlugin ? [inertiaPlugin] : []),\n ...stratalInertia(${stratalArgs}),\n ],\n build: {\n ${outDirConfig}\n },\n ${serverConfig}\n}\n\n${hasUserConfig\n ? `const userModule = await import('${join(options.cwd, 'vite.config.ts').replace(/\\\\/g, '/')}')\nconst userConfig = userModule.default ?? userModule\nexport default mergeConfig(baseConfig, userConfig)`\n : 'export default baseConfig'\n }\n`\n\n writeFileSync(configPath, content, 'utf-8')\n return configPath\n}\n","import { spawn } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { Command } from 'stratal/quarry'\nimport { writeTempClientViteConfig } from '../vite/create-client-vite-config'\nimport { writeTempViteConfig } from '../vite/create-vite-config'\n\nexport class InertiaBuildCommand extends Command {\n static command = 'inertia:build {--outDir=dist : Output directory} {--ssr : Also build SSR bundle}'\n static description = 'Build Inertia.js frontend for production'\n\n async handle(): Promise<number | undefined> {\n const outDir = this.string('outDir') || 'dist'\n const shouldBuildSsr = this.boolean('ssr')\n const cwd = process.cwd()\n\n const entryPath = 'src/inertia/app.tsx'\n if (!existsSync(join(cwd, entryPath))) {\n this.fail('src/inertia/app.tsx not found. Run `quarry inertia:install` first.')\n return 1\n }\n\n // Phase 1: standalone browser-bundle build. Runs without the Cloudflare\n // vite-plugin so it isn't subject to its parallel env orchestration. The\n // resulting `<clientOutDir>/.vite/manifest.json` is what the worker build\n // (phase 2) inlines into the worker entry via `stratal:inertia-inject-manifest`.\n const clientOutDir = join(outDir, 'client').replace(/\\\\/g, '/')\n const clientConfigPath = writeTempClientViteConfig({\n cwd,\n entry: entryPath,\n outDir: clientOutDir,\n })\n\n this.info('Building Inertia.js browser bundle...')\n const browserCode = await this.spawnVite(cwd, clientConfigPath, ['build'])\n if (browserCode !== 0) {\n this.fail('Browser bundle build failed.')\n return browserCode\n }\n this.success(`Browser bundle written to ${clientOutDir}/`)\n\n // Phase 2: worker build (Cloudflare vite-plugin). The injector plugin\n // reads the manifest produced in phase 1 and inlines it onto the worker\n // entry chunk.\n const configPath = writeTempViteConfig({\n cwd,\n outDir,\n clientManifestPath: join(clientOutDir, '.vite', 'manifest.json').replace(/\\\\/g, '/'),\n })\n\n this.info('Building Cloudflare worker bundle...')\n const workerCode = await this.spawnVite(cwd, configPath, ['build'])\n if (workerCode !== 0) {\n this.fail('Worker build failed.')\n return workerCode\n }\n this.success('Worker build complete!')\n\n if (shouldBuildSsr) {\n this.info('Building SSR bundle...')\n const ssrCode = await this.spawnVite(cwd, configPath, ['build', '--ssr'])\n if (ssrCode !== 0) {\n this.fail('SSR build failed.')\n return ssrCode\n }\n this.success('SSR build complete!')\n }\n\n this.success(`Output in ${outDir}/`)\n this.info('Deploy with: npx wrangler deploy')\n return 0\n }\n\n private spawnVite(cwd: string, configPath: string, args: string[]): Promise<number> {\n return new Promise((resolve) => {\n const child = spawn('npx', ['vite', '--config', configPath, ...args], {\n cwd,\n stdio: 'inherit',\n shell: true,\n })\n\n child.on('error', (err) => {\n this.fail(`Vite process error: ${err.message}`)\n resolve(1)\n })\n\n child.on('close', (code) => {\n resolve(code ?? 0)\n })\n })\n }\n}\n","import { spawn } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { Command } from 'stratal/quarry'\nimport { writeTempViteConfig } from '../vite/create-vite-config'\n\nexport class InertiaDevCommand extends Command {\n static command = 'inertia:dev {--port= : Dev server port} {--host : Expose to network} {--persist-to= : Shared persist directory for @cloudflare/vite-plugin (relative to cwd; the plugin appends /v3). Use to share R2/KV/cache emulator state across multiple workers in dev.}'\n static description = 'Start Inertia.js Vite development server'\n\n async handle(): Promise<number | undefined> {\n const port = this.number('port')\n const host = this.boolean('host')\n const persistTo = this.string('persist-to')\n const cwd = process.cwd()\n\n const entryPath = 'src/inertia/app.tsx'\n if (!existsSync(join(cwd, entryPath))) {\n this.fail('src/inertia/app.tsx not found. Run `quarry inertia:install` first.')\n return 1\n }\n\n const configPath = writeTempViteConfig({\n cwd,\n server: { port, host },\n persistTo,\n })\n\n this.info('Starting Vite dev server...')\n\n const args = ['vite', 'dev', '--config', configPath]\n if (host) args.push('--host')\n\n return new Promise<number>((resolve) => {\n const child = spawn('npx', args, {\n cwd,\n stdio: 'inherit',\n shell: true,\n })\n\n child.on('error', (err) => {\n this.fail(`Failed to start dev server: ${err.message}`)\n resolve(1)\n })\n\n child.on('close', (code) => {\n resolve(code ?? 0)\n })\n })\n }\n}\n","import { existsSync, mkdirSync, writeFileSync } from 'node:fs'\nimport { join, relative } from 'node:path'\nimport { Command } from 'stratal/quarry'\nimport { runTypeGeneration } from '../generator/type-generator'\n\nconst ROOT_HTML = `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n @viteHead\n @inertiaHead\n</head>\n<body>\n @inertia\n @viteScripts\n</body>\n</html>`\n\nconst APP_TSX = `import { createInertiaApp } from '@inertiajs/react'\n\ncreateInertiaApp({\n resolve: async (name) => {\n const pages = import.meta.glob('./pages/**/*.tsx')\n const page = await pages[\\`./pages/\\${name}.tsx\\`]?.()\n if (!page) throw new Error(\\`Page not found: \\${name}\\`)\n return page\n },\n})`\n\nconst HOME_TSX = `export default function Home({ message }: { message: string }) {\n return (\n <div>\n <h1>{message}</h1>\n <p>This page is rendered with Inertia.js and Stratal.</p>\n </div>\n )\n}`\n\nexport class InertiaInstallCommand extends Command {\n static command = 'inertia:install {--skip-deps : Skip installing npm dependencies}'\n static description = 'Scaffold Inertia.js files for a Stratal project'\n\n async handle(): Promise<number | undefined> {\n const skipDeps = this.boolean('skip-deps')\n const cwd = process.cwd()\n const inertiaDir = join(cwd, 'src', 'inertia')\n const pagesDir = join(inertiaDir, 'pages')\n\n // Create directories\n this.info('Creating src/inertia/ directory...')\n mkdirSync(pagesDir, { recursive: true })\n\n const publicDir = join(inertiaDir, 'public')\n mkdirSync(publicDir, { recursive: true })\n const gitkeepPath = join(publicDir, '.gitkeep')\n if (!existsSync(gitkeepPath)) {\n writeFileSync(gitkeepPath, '', 'utf-8')\n }\n this.success('Created src/inertia/public/')\n\n // Write template files\n const files = [\n { path: join(inertiaDir, 'root.html'), content: ROOT_HTML, name: 'root.html' },\n { path: join(inertiaDir, 'app.tsx'), content: APP_TSX, name: 'app.tsx' },\n { path: join(pagesDir, 'Home.tsx'), content: HOME_TSX, name: 'pages/Home.tsx' },\n ]\n\n for (const file of files) {\n if (existsSync(file.path)) {\n this.warn(`Skipping ${file.name} (already exists)`)\n } else {\n writeFileSync(file.path, file.content, 'utf-8')\n this.success(`Created src/inertia/${file.name}`)\n }\n }\n\n // Modify app.module.ts\n const appModulePath = join(cwd, 'src', 'app.module.ts')\n if (existsSync(appModulePath)) {\n this.info('Updating src/app.module.ts...')\n try {\n const updated = await this.updateAppModule(appModulePath)\n if (updated) {\n this.success('Updated src/app.module.ts with InertiaModule')\n } else {\n this.info('InertiaModule already configured in app.module.ts')\n }\n } catch (err) {\n this.warn(`Could not auto-update app.module.ts: ${(err as Error).message}`)\n this.info('Please manually add InertiaModule.forRoot() to your module imports')\n }\n } else {\n this.info('No src/app.module.ts found — please manually configure InertiaModule')\n }\n\n // Generate initial type definitions\n try {\n const { outputPath, pageCount } = await runTypeGeneration(cwd)\n const relPath = relative(cwd, outputPath)\n this.success(`Generated ${relPath} (${pageCount} page${pageCount !== 1 ? 's' : ''})`)\n } catch {\n this.warn('Could not generate initial type definitions. Run `quarry inertia:types` manually.')\n }\n\n if (!skipDeps) {\n this.newLine()\n this.info('Install the following dependencies:')\n this.line(' npm install @stratal/inertia @inertiajs/react @inertiajs/vite react react-dom')\n this.line(' npm install -D @types/react @types/react-dom vite @cloudflare/vite-plugin')\n }\n\n this.newLine()\n this.success('Inertia.js scaffolding complete!')\n this.info('Run `quarry inertia:dev` to start the dev server')\n\n return 0\n }\n\n private async updateAppModule(modulePath: string): Promise<boolean> {\n const { Project, SyntaxKind } = await import('ts-morph')\n\n const project = new Project({ useInMemoryFileSystem: false })\n const sourceFile = project.addSourceFileAtPath(modulePath)\n\n // Check if InertiaModule is already imported\n const existingImport = sourceFile.getImportDeclaration((decl) =>\n decl.getModuleSpecifierValue() === '@stratal/inertia',\n )\n if (existingImport) {\n return false\n }\n\n // Add rootView import\n sourceFile.addImportDeclaration({\n defaultImport: 'rootView',\n moduleSpecifier: './inertia/root.html?raw',\n })\n\n // Add InertiaModule import\n sourceFile.addImportDeclaration({\n namedImports: ['InertiaModule'],\n moduleSpecifier: '@stratal/inertia',\n })\n\n // Find the @Module decorator and add InertiaModule to imports\n const classes = sourceFile.getClasses()\n for (const cls of classes) {\n const moduleDecorator = cls.getDecorator('Module')\n if (!moduleDecorator) continue\n\n const args = moduleDecorator.getArguments()\n if (args.length === 0) continue\n\n const objLiteral = args[0].asKind(SyntaxKind.ObjectLiteralExpression)\n if (!objLiteral) continue\n\n const importsProp = objLiteral.getProperty('imports')\n if (importsProp) {\n // Add to existing imports array\n const initializer = importsProp.asKind(SyntaxKind.PropertyAssignment)?.getInitializer()\n const arrayLiteral = initializer?.asKind(SyntaxKind.ArrayLiteralExpression)\n if (arrayLiteral) {\n arrayLiteral.addElement(`InertiaModule.forRoot({\\n rootView,\\n })`)\n }\n } else {\n // Add imports property\n objLiteral.addPropertyAssignment({\n name: 'imports',\n initializer: `[\\n InertiaModule.forRoot({\\n rootView,\\n }),\\n ]`,\n })\n }\n\n break\n }\n\n await sourceFile.save()\n return true\n }\n}\n","import { existsSync } from 'node:fs'\nimport { watch } from 'node:fs/promises'\nimport { join, relative } from 'node:path'\nimport { Command } from 'stratal/quarry'\nimport { findPagesDir, runTypeGeneration } from '../generator/type-generator'\n\nexport class InertiaTypesCommand extends Command {\n static command = 'inertia:types {--watch : Watch for changes and regenerate}'\n static description = 'Generate Inertia.js page type definitions'\n\n async handle(): Promise<number | undefined> {\n const cwd = process.cwd()\n const pagesDir = findPagesDir(cwd)\n\n if (!existsSync(pagesDir)) {\n this.fail('src/inertia/pages/ not found. Run `quarry inertia:install` first.')\n return 1\n }\n\n const result = await this.generate(cwd)\n if (!result) return 1\n\n if (this.boolean('watch')) {\n this.info('Watching for changes...')\n await this.watchForChanges(cwd)\n }\n\n return 0\n }\n\n private async generate(cwd: string): Promise<boolean> {\n try {\n const { outputPath, pageCount } = await runTypeGeneration(cwd)\n const relPath = relative(cwd, outputPath)\n this.success(`Generated ${relPath} (${pageCount} page${pageCount !== 1 ? 's' : ''})`)\n return true\n } catch (err) {\n this.fail(`Type generation failed: ${(err as Error).message}`)\n return false\n }\n }\n\n private async watchForChanges(cwd: string): Promise<void> {\n const srcDir = join(cwd, 'src')\n\n try {\n const watcher = watch(srcDir, { recursive: true })\n for await (const event of watcher) {\n if (event.filename && /\\.(tsx|ts)$/.test(event.filename)) {\n this.info(`Change detected: ${event.filename}`)\n await this.generate(cwd)\n }\n }\n } catch (err) {\n this.fail(`Watch failed: ${(err as Error).message}`)\n }\n }\n}\n","import { Module } from 'stratal/module'\nimport { InertiaBuildCommand } from './commands/inertia-build.command'\nimport { InertiaDevCommand } from './commands/inertia-dev.command'\nimport { InertiaInstallCommand } from './commands/inertia-install.command'\nimport { InertiaTypesCommand } from './commands/inertia-types.command'\n\n@Module({\n providers: [\n InertiaInstallCommand,\n InertiaTypesCommand,\n InertiaDevCommand,\n InertiaBuildCommand,\n ],\n})\nexport class InertiaQuarryModule {}\n\nexport { InertiaBuildCommand } from './commands/inertia-build.command'\nexport { InertiaDevCommand } from './commands/inertia-dev.command'\nexport { InertiaInstallCommand } from './commands/inertia-install.command'\nexport { InertiaTypesCommand } from './commands/inertia-types.command'\nexport { runTypeGeneration } from './generator/type-generator'\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,SAAgB,0BAA0B,SAA8C;CAEtF,MAAM,aAAa,KADD,KAAK,QAAQ,KAAK,gBAAgB,UACpB,GAAG,wBAAwB;CAC3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EJ,SAAS,KAAK;GACZ,KAAK,KAAK,iBAAkB,IAAc,SAAS;EACrD;CACF;AACF;;;AC3CO,IAAA,sBAAA,MAAM,oBAAoB,CAAC;kCARjC,OAAO,EACN,WAAW;CACT;CACA;CACA;CACA;AACF,EACF,CAAC,CAAA,GAAA,mBAAA"}
package/dist/react.d.mts CHANGED
@@ -1,40 +1,21 @@
1
1
  /// <reference path="../global.d.ts" />
2
- import { MessageKeys, MessageParams } from "stratal/i18n";
2
+ import { g as InertiaTranslationKeys, x as SeoData } from "./types--_iJ04lT.mjs";
3
3
  import { CurrentRoute, RouteMatcher, RouteName, RouteParams } from "stratal/router";
4
+ import { MessageParams } from "stratal/i18n";
4
5
 
5
- //#region src/react/use-i18n.d.ts
6
+ //#region src/react/seo.d.ts
6
7
  /**
7
- * Hook that provides i18n translation capabilities in React components.
8
- *
9
- * Consumes `locale` and `translations` from Inertia shared props and returns
10
- * a `t()` function that translates message keys with optional interpolation.
11
- *
12
- * Requires the `i18n` option to be set on `InertiaModule.forRoot()` to inject
13
- * the shared props.
14
- *
15
- * @returns An object with:
16
- * - `t` — Translation function accepting a message key and optional params
17
- * - `locale` — The current locale string
18
- *
19
- * @example
20
- * ```tsx
21
- * import { useI18n } from '@stratal/inertia/react'
8
+ * Returns the resolved SEO data shared by the backend for the current page.
22
9
  *
23
- * export default function Header() {
24
- * const { t, locale } = useI18n()
25
- *
26
- * return (
27
- * <header>
28
- * <h1>{t('common.title')}</h1>
29
- * <p>{t('common.greeting', { name: 'World' })}</p>
30
- * <span>Locale: {locale}</span>
31
- * </header>
32
- * )
33
- * }
34
- * ```
10
+ * The document head is kept in sync automatically (server injection on the
11
+ * initial paint + the auto-injected client runtime on navigation); use this
12
+ * hook only when you want to read the metadata inside a component.
35
13
  */
14
+ declare function useSeo(): SeoData;
15
+ //#endregion
16
+ //#region src/react/use-i18n.d.ts
36
17
  declare function useI18n(): {
37
- t: (key: MessageKeys, params?: MessageParams) => string;
18
+ t: (key: InertiaTranslationKeys, params?: MessageParams) => string;
38
19
  locale: string;
39
20
  };
40
21
  //#endregion
@@ -86,5 +67,5 @@ declare function useRoute(): {
86
67
  params: Record<string, string>;
87
68
  };
88
69
  //#endregion
89
- export { useI18n, useRoute };
70
+ export { useI18n, useRoute, useSeo };
90
71
  //# sourceMappingURL=react.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"react.d.mts","names":[],"sources":["../src/react/use-i18n.ts","../src/react/use-route.ts"],"mappings":";;;;;;;;;;;;;ACkOA;;;;;;;;;;;;;;;;;;;;;iBDzKgB,OAAA,CAAA;WAcA,WAAA,EAAW,MAAA,GAAW,aAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBC2JtB,QAAA,CAAA;oBAKK,SAAA,EAAS,IAAA,EAAQ,CAAA,EAAC,MAAA,GAAW,WAAA,CAAY,CAAA;;QAOvC,SAAA;IAAA,OACG,YAAA;EAAA"}
1
+ {"version":3,"file":"react.d.mts","names":[],"sources":["../src/react/seo.ts","../src/react/use-i18n.ts","../src/react/use-route.ts"],"mappings":";;;;;;;;;AAeA;;;iBAAgB,MAAA,IAAU,OAAO;;;iBCHjB,OAAA;WAUC,sBAAA,EAAsB,MAAA,GAAW,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBCmN/C,QAAA;oBAKK,SAAA,EAAS,IAAA,EAAQ,CAAA,EAAC,MAAA,GAAW,WAAA,CAAY,CAAA;;QAOvC,SAAA;IAAA,OACG,YAAA;EAAA"}
package/dist/react.mjs CHANGED
@@ -1,51 +1,31 @@
1
1
  import { usePage } from "@inertiajs/react";
2
- import { compile, createCoreContext, registerMessageCompiler, translate } from "@intlify/core-base";
2
+ import IntlMessageFormat from "intl-messageformat";
3
3
  import { useMemo } from "react";
4
- //#region src/react/use-i18n.ts
5
- registerMessageCompiler(compile);
4
+ //#region src/react/seo.ts
6
5
  /**
7
- * Hook that provides i18n translation capabilities in React components.
8
- *
9
- * Consumes `locale` and `translations` from Inertia shared props and returns
10
- * a `t()` function that translates message keys with optional interpolation.
11
- *
12
- * Requires the `i18n` option to be set on `InertiaModule.forRoot()` to inject
13
- * the shared props.
14
- *
15
- * @returns An object with:
16
- * - `t` — Translation function accepting a message key and optional params
17
- * - `locale` — The current locale string
18
- *
19
- * @example
20
- * ```tsx
21
- * import { useI18n } from '@stratal/inertia/react'
22
- *
23
- * export default function Header() {
24
- * const { t, locale } = useI18n()
6
+ * Returns the resolved SEO data shared by the backend for the current page.
25
7
  *
26
- * return (
27
- * <header>
28
- * <h1>{t('common.title')}</h1>
29
- * <p>{t('common.greeting', { name: 'World' })}</p>
30
- * <span>Locale: {locale}</span>
31
- * </header>
32
- * )
33
- * }
34
- * ```
8
+ * The document head is kept in sync automatically (server injection on the
9
+ * initial paint + the auto-injected client runtime on navigation); use this
10
+ * hook only when you want to read the metadata inside a component.
35
11
  */
12
+ function useSeo() {
13
+ return usePage().props.seo ?? {};
14
+ }
15
+ //#endregion
16
+ //#region src/react/use-i18n.ts
36
17
  function useI18n() {
37
18
  const { locale, translations } = usePage().props;
38
- const context = useMemo(() => createCoreContext({
39
- locale,
40
- messages: { [locale]: translations },
41
- missingWarn: !import.meta.env.PROD,
42
- fallbackWarn: !import.meta.env.PROD
43
- }), [locale, translations]);
44
19
  return {
45
- t: useMemo(() => (key, params) => {
46
- const result = params !== void 0 ? translate(context, key, params) : translate(context, key);
47
- return typeof result === "string" ? result : key;
48
- }, [context]),
20
+ t: useMemo(() => {
21
+ const compiled = /* @__PURE__ */ new Map();
22
+ for (const [key, value] of Object.entries(translations)) compiled.set(key, new IntlMessageFormat(value, locale));
23
+ return (key, params) => {
24
+ const msg = compiled.get(key);
25
+ if (!msg) return key;
26
+ return String(msg.format(params));
27
+ };
28
+ }, [locale, translations]),
49
29
  locale
50
30
  };
51
31
  }
@@ -91,12 +71,12 @@ function encodePathParam(value) {
91
71
  * Mirrors `buildRouteUrl()` from `stratal/router` (pure reimplementation to
92
72
  * avoid pulling server-side dependencies into the browser bundle).
93
73
  */
94
- function buildUrl(route, name, params) {
74
+ function buildUrl(route, name, params, localeConfig) {
95
75
  const allParams = { ...params };
96
76
  const consumedKeys = /* @__PURE__ */ new Set();
97
77
  let url = route.path;
98
78
  if (allParams.locale && route.localePaths?.length) {
99
- url = `/${allParams.locale}${url === "/" ? "" : url}`;
79
+ if (!localeConfig || localeConfig.prefixDefaultLocale === true || allParams.locale !== localeConfig.defaultLocale) url = `/${allParams.locale}${url === "/" ? "" : url}`;
100
80
  consumedKeys.add("locale");
101
81
  }
102
82
  for (const paramName of route.paramNames) {
@@ -143,14 +123,14 @@ function filterCarryover(carryover, route) {
143
123
  * Merges params in order (last wins): sticky `defaults`, current-route
144
124
  * carryover (filtered to the target's declared params), explicit params.
145
125
  */
146
- function resolveUrl(name, explicitParams, routes, currentRoute, trailingSlash = "ignore") {
126
+ function resolveUrl(name, explicitParams, routes, currentRoute, trailingSlash = "ignore", localeConfig) {
147
127
  const target = routes[name];
148
128
  if (!target) throw new Error(`Route "${name}" not found.`);
149
129
  return applyTrailingSlash(buildUrl(target, name, {
150
130
  ...currentRoute.defaults,
151
131
  ...filterCarryover(currentRoute.params, target),
152
132
  ...explicitParams
153
- }), trailingSlash);
133
+ }, localeConfig), trailingSlash);
154
134
  }
155
135
  function matchCurrent(currentRoute, name) {
156
136
  if (name === void 0) return currentRoute.name;
@@ -199,12 +179,13 @@ function matchCurrent(currentRoute, name) {
199
179
  * ```
200
180
  */
201
181
  function useRoute() {
202
- const { routes, trailingSlash = "ignore", route: currentRoute } = usePage().props;
182
+ const { routes, trailingSlash = "ignore", route: currentRoute, localeConfig } = usePage().props;
203
183
  return {
204
- route: useMemo(() => (name, params) => resolveUrl(name, params, routes, currentRoute, trailingSlash), [
184
+ route: useMemo(() => (name, params) => resolveUrl(name, params, routes, currentRoute, trailingSlash, localeConfig), [
205
185
  routes,
206
186
  trailingSlash,
207
- currentRoute
187
+ currentRoute,
188
+ localeConfig
208
189
  ]),
209
190
  current: useMemo(() => {
210
191
  function impl(name) {
@@ -217,6 +198,6 @@ function useRoute() {
217
198
  };
218
199
  }
219
200
  //#endregion
220
- export { useI18n, useRoute };
201
+ export { useI18n, useRoute, useSeo };
221
202
 
222
203
  //# sourceMappingURL=react.mjs.map