@rshono/core 1.0.0-rc.2 → 1.0.0-rc.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +348 -158
- package/bin/rshono.mjs +3 -4
- package/dist/builder/env-shadow-loader.cjs +123 -8
- package/dist/builder/page-entry-loader.cjs +28 -1
- package/dist/builder/page-files.d.ts +0 -1
- package/dist/builder/page-files.js +7 -3
- package/dist/builder/page-files.js.map +1 -1
- package/dist/builder/public-env.d.ts +7 -1
- package/dist/builder/public-env.js +7 -0
- package/dist/builder/public-env.js.map +1 -1
- package/dist/builder/react-versions.d.ts +12 -0
- package/dist/builder/react-versions.js +74 -0
- package/dist/builder/react-versions.js.map +1 -0
- package/dist/builder/rspack-config.d.ts +13 -4
- package/dist/builder/rspack-config.js +136 -53
- package/dist/builder/rspack-config.js.map +1 -1
- package/dist/builder/server-only-imports.d.ts +32 -0
- package/dist/builder/server-only-imports.js +51 -0
- package/dist/builder/server-only-imports.js.map +1 -0
- package/dist/cli/build.d.ts +2 -3
- package/dist/cli/build.js +51 -13
- package/dist/cli/build.js.map +1 -1
- package/dist/cli/dev.d.ts +2 -3
- package/dist/cli/dev.js +149 -45
- package/dist/cli/dev.js.map +1 -1
- package/dist/cli/exit.d.ts +12 -0
- package/dist/cli/exit.js +16 -0
- package/dist/cli/exit.js.map +1 -0
- package/dist/cli/index.d.ts +0 -1
- package/dist/cli/index.js +91 -30
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/start.d.ts +0 -1
- package/dist/cli/start.js +15 -18
- package/dist/cli/start.js.map +1 -1
- package/dist/config.d.ts +72 -78
- package/dist/config.js +17 -1
- package/dist/config.js.map +1 -1
- package/dist/deploy/aws-lambda/runtime.d.ts +4 -7
- package/dist/deploy/aws-lambda/runtime.js +5 -8
- package/dist/deploy/aws-lambda/runtime.js.map +1 -1
- package/dist/deploy/build-marker.d.ts +9 -6
- package/dist/deploy/build-marker.js +8 -4
- package/dist/deploy/build-marker.js.map +1 -1
- package/dist/deploy/cloudflare/build.d.ts +0 -1
- package/dist/deploy/cloudflare/build.js +17 -13
- package/dist/deploy/cloudflare/build.js.map +1 -1
- package/dist/deploy/cloudflare/runtime.d.ts +2 -6
- package/dist/deploy/cloudflare/runtime.js +73 -68
- package/dist/deploy/cloudflare/runtime.js.map +1 -1
- package/dist/deploy/contract.d.ts +57 -41
- package/dist/deploy/contract.js.map +1 -1
- package/dist/deploy/filesystem.d.ts +3 -6
- package/dist/deploy/filesystem.js +23 -20
- package/dist/deploy/filesystem.js.map +1 -1
- package/dist/deploy/node/runtime.d.ts +5 -3
- package/dist/deploy/node/runtime.js +23 -9
- package/dist/deploy/node/runtime.js.map +1 -1
- package/dist/deploy/presets.d.ts +34 -30
- package/dist/deploy/presets.js +56 -44
- package/dist/deploy/presets.js.map +1 -1
- package/dist/deploy/public-paths.d.ts +42 -0
- package/dist/deploy/public-paths.js +66 -0
- package/dist/deploy/public-paths.js.map +1 -0
- package/dist/deploy/vercel/build.d.ts +0 -1
- package/dist/deploy/vercel/build.js +25 -16
- package/dist/deploy/vercel/build.js.map +1 -1
- package/dist/deploy/vercel/runtime.d.ts +10 -7
- package/dist/deploy/vercel/runtime.js +48 -11
- package/dist/deploy/vercel/runtime.js.map +1 -1
- package/dist/index.d.ts +19 -17
- package/dist/index.js +20 -10
- package/dist/index.js.map +1 -1
- package/dist/router.d.ts +212 -120
- package/dist/router.js +3 -8
- package/dist/router.js.map +1 -1
- package/dist/runtime/boundaries.d.ts +62 -48
- package/dist/runtime/boundaries.js +32 -34
- package/dist/runtime/boundaries.js.map +1 -1
- package/dist/runtime/client.d.ts +20 -11
- package/dist/runtime/client.js +20 -10
- package/dist/runtime/client.js.map +1 -1
- package/dist/runtime/context.d.ts +304 -123
- package/dist/runtime/context.js +377 -149
- package/dist/runtime/context.js.map +1 -1
- package/dist/runtime/control.d.ts +15 -1
- package/dist/runtime/control.js +24 -0
- package/dist/runtime/control.js.map +1 -1
- package/dist/runtime/dev-protocol.d.ts +4 -9
- package/dist/runtime/dev-protocol.js.map +1 -1
- package/dist/runtime/empty-server-app.d.ts +0 -1
- package/dist/runtime/entry.client.d.ts +4 -1
- package/dist/runtime/entry.client.js +455 -313
- package/dist/runtime/entry.client.js.map +1 -1
- package/dist/runtime/entry.rsc.d.ts +15 -7
- package/dist/runtime/entry.rsc.js +811 -252
- package/dist/runtime/entry.rsc.js.map +1 -1
- package/dist/runtime/entry.ssr.d.ts +27 -10
- package/dist/runtime/entry.ssr.js +30 -48
- package/dist/runtime/entry.ssr.js.map +1 -1
- package/dist/runtime/failure-document.d.ts +11 -0
- package/dist/runtime/failure-document.js +35 -0
- package/dist/runtime/failure-document.js.map +1 -0
- package/dist/runtime/flight-inject.d.ts +23 -0
- package/dist/runtime/flight-inject.js +403 -0
- package/dist/runtime/flight-inject.js.map +1 -0
- package/dist/runtime/hot-update.d.ts +44 -0
- package/dist/runtime/hot-update.js +44 -0
- package/dist/runtime/hot-update.js.map +1 -0
- package/dist/runtime/navigation.d.ts +46 -54
- package/dist/runtime/navigation.js +22 -63
- package/dist/runtime/navigation.js.map +1 -1
- package/dist/runtime/request.d.ts +42 -8
- package/dist/runtime/request.js +84 -7
- package/dist/runtime/request.js.map +1 -1
- package/dist/runtime/server.d.ts +20 -18
- package/dist/runtime/server.js +22 -17
- package/dist/runtime/server.js.map +1 -1
- package/dist/runtime/validate-entries.d.ts +77 -0
- package/dist/runtime/validate-entries.js +405 -0
- package/dist/runtime/validate-entries.js.map +1 -0
- package/dist/server/headers.d.ts +41 -15
- package/dist/server/headers.js +53 -24
- package/dist/server/headers.js.map +1 -1
- package/dist/server/load-config.d.ts +4 -5
- package/dist/server/load-config.js +22 -14
- package/dist/server/load-config.js.map +1 -1
- package/dist/server/load-env.d.ts +0 -1
- package/dist/server/prerendered.d.ts +88 -34
- package/dist/server/prerendered.js +184 -24
- package/dist/server/prerendered.js.map +1 -1
- package/dist/server/server-config.d.ts +35 -50
- package/dist/server/server-config.js +27 -74
- package/dist/server/server-config.js.map +1 -1
- package/dist/server/shutdown.d.ts +5 -4
- package/dist/server/shutdown.js +5 -3
- package/dist/server/shutdown.js.map +1 -1
- package/dist/server/ssg.d.ts +9 -7
- package/dist/server/ssg.js +209 -65
- package/dist/server/ssg.js.map +1 -1
- package/dist/server/static.d.ts +0 -1
- package/dist/server/static.js +7 -1
- package/dist/server/static.js.map +1 -1
- package/package.json +21 -23
- package/dist/builder/page-files.d.ts.map +0 -1
- package/dist/builder/public-env.d.ts.map +0 -1
- package/dist/builder/rspack-config.d.ts.map +0 -1
- package/dist/cli/build.d.ts.map +0 -1
- package/dist/cli/dev.d.ts.map +0 -1
- package/dist/cli/index.d.ts.map +0 -1
- package/dist/cli/start.d.ts.map +0 -1
- package/dist/config.d.ts.map +0 -1
- package/dist/deploy/aws-lambda/runtime.d.ts.map +0 -1
- package/dist/deploy/build-marker.d.ts.map +0 -1
- package/dist/deploy/bun/runtime.d.ts +0 -11
- package/dist/deploy/bun/runtime.d.ts.map +0 -1
- package/dist/deploy/bun/runtime.js +0 -22
- package/dist/deploy/bun/runtime.js.map +0 -1
- package/dist/deploy/cloudflare/build.d.ts.map +0 -1
- package/dist/deploy/cloudflare/runtime.d.ts.map +0 -1
- package/dist/deploy/contract.d.ts.map +0 -1
- package/dist/deploy/deno/runtime.d.ts +0 -11
- package/dist/deploy/deno/runtime.d.ts.map +0 -1
- package/dist/deploy/deno/runtime.js +0 -16
- package/dist/deploy/deno/runtime.js.map +0 -1
- package/dist/deploy/filesystem.d.ts.map +0 -1
- package/dist/deploy/listen.d.ts +0 -20
- package/dist/deploy/listen.d.ts.map +0 -1
- package/dist/deploy/listen.js +0 -24
- package/dist/deploy/listen.js.map +0 -1
- package/dist/deploy/netlify/build.d.ts +0 -8
- package/dist/deploy/netlify/build.d.ts.map +0 -1
- package/dist/deploy/netlify/build.js +0 -52
- package/dist/deploy/netlify/build.js.map +0 -1
- package/dist/deploy/netlify/runtime.d.ts +0 -13
- package/dist/deploy/netlify/runtime.d.ts.map +0 -1
- package/dist/deploy/netlify/runtime.js +0 -24
- package/dist/deploy/netlify/runtime.js.map +0 -1
- package/dist/deploy/node/runtime.d.ts.map +0 -1
- package/dist/deploy/presets.d.ts.map +0 -1
- package/dist/deploy/vercel/build.d.ts.map +0 -1
- package/dist/deploy/vercel/runtime.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/router.d.ts.map +0 -1
- package/dist/runtime/boundaries.d.ts.map +0 -1
- package/dist/runtime/client.d.ts.map +0 -1
- package/dist/runtime/context.d.ts.map +0 -1
- package/dist/runtime/control.d.ts.map +0 -1
- package/dist/runtime/dev-protocol.d.ts.map +0 -1
- package/dist/runtime/empty-server-app.d.ts.map +0 -1
- package/dist/runtime/entry.client.d.ts.map +0 -1
- package/dist/runtime/entry.rsc.d.ts.map +0 -1
- package/dist/runtime/entry.ssr.d.ts.map +0 -1
- package/dist/runtime/navigation.d.ts.map +0 -1
- package/dist/runtime/request.d.ts.map +0 -1
- package/dist/runtime/server.d.ts.map +0 -1
- package/dist/server/compress.d.ts +0 -15
- package/dist/server/compress.d.ts.map +0 -1
- package/dist/server/compress.js +0 -76
- package/dist/server/compress.js.map +0 -1
- package/dist/server/headers.d.ts.map +0 -1
- package/dist/server/load-config.d.ts.map +0 -1
- package/dist/server/load-env.d.ts.map +0 -1
- package/dist/server/prerendered.d.ts.map +0 -1
- package/dist/server/server-config.d.ts.map +0 -1
- package/dist/server/shutdown.d.ts.map +0 -1
- package/dist/server/ssg.d.ts.map +0 -1
- package/dist/server/static.d.ts.map +0 -1
package/dist/cli/build.js
CHANGED
|
@@ -3,12 +3,16 @@ import { cpSync, existsSync } from 'node:fs';
|
|
|
3
3
|
import { rm } from 'node:fs/promises';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { pathToFileURL } from 'node:url';
|
|
6
|
-
import { createConfigs } from '../builder/rspack-config.js';
|
|
6
|
+
import { BUILD_OUT_DIR, createConfigs } from '../builder/rspack-config.js';
|
|
7
7
|
import { writeBuildMarker } from '../deploy/build-marker.js';
|
|
8
8
|
import { prerenderStaticRoutes } from '../server/ssg.js';
|
|
9
|
+
import { exit } from './exit.js';
|
|
10
|
+
function importServerBundle(distDir) {
|
|
11
|
+
return import(pathToFileURL(join(distDir, 'server', 'main.mjs')).href);
|
|
12
|
+
}
|
|
9
13
|
export async function buildCommand(options) {
|
|
10
14
|
const { rootDir, config, preset } = options;
|
|
11
|
-
const distDir = join(rootDir,
|
|
15
|
+
const distDir = join(rootDir, BUILD_OUT_DIR);
|
|
12
16
|
console.log(' • building client + server bundles…');
|
|
13
17
|
const configs = createConfigs({ rootDir, isDev: false, config, preset });
|
|
14
18
|
const compiler = rspack(configs);
|
|
@@ -24,41 +28,75 @@ export async function buildCommand(options) {
|
|
|
24
28
|
});
|
|
25
29
|
if (stats.hasErrors()) {
|
|
26
30
|
console.error(stats.toString({ preset: 'errors-warnings', colors: true }));
|
|
27
|
-
|
|
31
|
+
return exit(1);
|
|
28
32
|
}
|
|
33
|
+
// Printed rather than left to the summary below, which counts warnings without saying what they are —
|
|
34
|
+
// and one of them is the env shadow reporting a read it cannot cover. See `env-shadow-loader.cjs`.
|
|
35
|
+
if (stats.hasWarnings())
|
|
36
|
+
console.warn(stats.toString({ preset: 'errors-warnings', colors: true }));
|
|
29
37
|
console.log(stats.toString({ preset: 'summary', colors: true }));
|
|
30
38
|
const publicDir = join(rootDir, 'public');
|
|
31
|
-
|
|
39
|
+
// From scratch, and unconditionally, like every other directory this build assembles. `cpSync` only
|
|
40
|
+
// adds, so a file deleted from `public/` used to survive in `dist/public` and go on being served by
|
|
41
|
+
// `rshono start` for good — and deleting `public/` outright left the whole of the old tree there, since
|
|
42
|
+
// the copy below is the only thing that touches it. The two CDN presets clear their own output but read
|
|
43
|
+
// *this* directory, so a stale file propagated into their assets as well, past a comment promising it
|
|
44
|
+
// could not.
|
|
45
|
+
const distPublicDir = join(distDir, 'public');
|
|
46
|
+
await rm(distPublicDir, { recursive: true, force: true });
|
|
47
|
+
let servedPublicDir = null;
|
|
32
48
|
if (existsSync(publicDir)) {
|
|
33
|
-
|
|
49
|
+
servedPublicDir = distPublicDir;
|
|
34
50
|
cpSync(publicDir, distPublicDir, { recursive: true });
|
|
35
51
|
console.log(' • copied public/ into dist/public (served at /)');
|
|
36
52
|
}
|
|
37
53
|
const ssgDir = join(distDir, 'ssg');
|
|
38
54
|
await rm(ssgDir, { recursive: true, force: true });
|
|
39
55
|
process.env.RSHONO_PRERENDER = '1';
|
|
40
|
-
|
|
41
|
-
|
|
56
|
+
// The bundle's module scope is where `src/routes.ts` and `src/server.ts` are validated.
|
|
57
|
+
//
|
|
58
|
+
// This and the two stages below are what the *app* can fail — the two entry modules here, each route's own
|
|
59
|
+
// module next, and a page that throws while prerendering after that. Each raises a `[rshono]` message
|
|
60
|
+
// written for whoever is running the build, and `main().catch` in `cli/index.ts` is what prints it as the
|
|
61
|
+
// one line it is. These used to be wrapped in a `phase()` helper that did the same thing three times and
|
|
62
|
+
// nowhere else, which left `createConfigs` above — where a missing `src/routes.ts` is found — printing a
|
|
63
|
+
// raw `Error` object with framework frames in it.
|
|
64
|
+
const bundle = await importServerBundle(distDir);
|
|
65
|
+
// Before anything is rendered: the checks here are the ones a route fails on *every* request, so a build
|
|
66
|
+
// that skipped them would spend the prerender pass on a route it is about to refuse anyway. Without this
|
|
67
|
+
// they ran on first request instead, which meant a page that could never work shipped behind a green build.
|
|
68
|
+
await bundle.checkAppModules();
|
|
69
|
+
const { written, skipped, flightOnly } = await prerenderStaticRoutes({
|
|
42
70
|
routes: bundle.routes,
|
|
43
71
|
fetch: (request) => bundle.app.fetch(request),
|
|
44
72
|
ssgDir,
|
|
45
73
|
siteUrl: config.siteUrl,
|
|
46
74
|
});
|
|
47
|
-
if (written.length > 0)
|
|
48
|
-
|
|
75
|
+
if (written.length > 0) {
|
|
76
|
+
// Marked per page rather than counted separately, so the line answers the question a reader has about
|
|
77
|
+
// each name in it: is this page served from disk? A page under a CSP nonce is half of one — its flight
|
|
78
|
+
// payload is, its document is re-rendered per request — and saying "prerendered" alone would claim more
|
|
79
|
+
// than the build did. The warning above says why, once.
|
|
80
|
+
const nonced = new Set(flightOnly);
|
|
81
|
+
const label = (path) => (nonced.has(path) ? `${path} (flight only)` : path);
|
|
82
|
+
console.log(` • prerendered ${written.length} static page(s): ${written.map(label).join(', ')}`);
|
|
83
|
+
}
|
|
49
84
|
if (skipped.length > 0)
|
|
50
85
|
console.log(` • skipped ${skipped.length} (will SSR per request)`);
|
|
51
|
-
//
|
|
86
|
+
// Before `finalize`, so a preset that copies `dist/` into a platform layout takes it along.
|
|
52
87
|
writeBuildMarker(distDir, preset.name);
|
|
53
|
-
// Last, so a preset arranging its output finds every piece of the build
|
|
88
|
+
// Last, so a preset arranging its output finds every piece of the build on disk.
|
|
54
89
|
await preset.finalize?.({
|
|
55
90
|
rootDir,
|
|
56
91
|
distDir,
|
|
57
92
|
staticDir: join(distDir, 'static'),
|
|
58
|
-
publicDir:
|
|
93
|
+
publicDir: servedPublicDir,
|
|
59
94
|
ssgDir,
|
|
95
|
+
routes: bundle.routes,
|
|
60
96
|
});
|
|
61
97
|
console.log(` ✓ build complete — ${preset.deployHint}`);
|
|
62
|
-
|
|
98
|
+
// Rspack's worker pool can keep the loop alive after `close()`, so the exit is explicit. {@link exit}
|
|
99
|
+
// drains first: in CI the tail is the lines saying what was built and where it went.
|
|
100
|
+
await exit(0);
|
|
63
101
|
}
|
|
64
102
|
//# sourceMappingURL=build.js.map
|
package/dist/cli/build.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.js","sourceRoot":"","sources":["../../src/cli/build.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAmB,MAAM,cAAc,CAAC;AAEvD,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAC7C,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAk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AAG,CAAC,mBAAmB,OAAO,CAAC,MAAM,oBAAoB,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC/G,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,CAAC,GAAG,CAAC,eAAe,OAAO,CAAC,MAAM,yBAAyB,CAAC,CAAC;IAE5F,oGAAoG;IACpG,gBAAgB,CAAC,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAEvC,yFAAyF;IACzF,MAAM,MAAM,CAAC,QAAQ,EAAE,CAAC;QACtB,OAAO;QACP,OAAO;QACP,SAAS,EAAE,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC;QAClC,SAAS,EAAE,aAAa;QACxB,MAAM;KACP,CAAC,CAAC;IAEH,OAAO,CAAC,GAAG,CAAC,wBAAwB,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC;IACzD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC","sourcesContent":["import { rspack, type MultiStats } from '@rspack/core';\nimport type { Hono } from 'hono';\nimport { cpSync, existsSync } from 'node:fs';\nimport { rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { createConfigs } from '../builder/rspack-config.js';\nimport type { RSHonoConfig } from '../config.js';\nimport { writeBuildMarker } from '../deploy/build-marker.js';\nimport type { DeployPreset } from '../deploy/presets.js';\nimport type { Route } from '../router.js';\nimport { prerenderStaticRoutes } from '../server/ssg.js';\n\ninterface BuildOptions {\n rootDir: string;\n config: RSHonoConfig;\n /** The platform to build for, already resolved from the flag, the environment and the config. */\n preset: DeployPreset;\n}\n\nexport async function buildCommand(options: BuildOptions): Promise<void> {\n const { rootDir, config, preset } = options;\n const distDir = join(rootDir, 'dist');\n\n console.log(' • building client + server bundles…');\n const configs = createConfigs({ rootDir, isDev: false, config, preset });\n const compiler = rspack(configs);\n\n const stats = await new Promise<MultiStats>((resolve, reject) => {\n compiler.run((err, result) => {\n compiler.close(() => {\n if (err) reject(err);\n else resolve(result!);\n });\n });\n });\n\n if (stats.hasErrors()) {\n console.error(stats.toString({ preset: 'errors-warnings', colors: true }));\n process.exit(1);\n }\n console.log(stats.toString({ preset: 'summary', colors: true }));\n\n const publicDir = join(rootDir, 'public');\n let distPublicDir: string | null = null;\n if (existsSync(publicDir)) {\n distPublicDir = join(distDir, 'public');\n cpSync(publicDir, distPublicDir, { recursive: true });\n console.log(' • copied public/ into dist/public (served at /)');\n }\n\n const ssgDir = join(distDir, 'ssg');\n await rm(ssgDir, { recursive: true, force: true });\n process.env.RSHONO_PRERENDER = '1';\n const bundle = (await import(pathToFileURL(join(distDir, 'server', 'main.mjs')).href)) as {\n app: Hono;\n routes: readonly Route[];\n };\n const { written, skipped } = await prerenderStaticRoutes({\n routes: bundle.routes,\n fetch: (request) => bundle.app.fetch(request),\n ssgDir,\n siteUrl: config.siteUrl,\n });\n if (written.length > 0) console.log(` • prerendered ${written.length} static page(s): ${written.join(', ')}`);\n if (skipped.length > 0) console.log(` • skipped ${skipped.length} (will SSR per request)`);\n\n // Written before `finalize`, so a preset that copies `dist/` into a platform layout takes it along.\n writeBuildMarker(distDir, preset.name);\n\n // Last, so a preset arranging its output finds every piece of the build already written.\n await preset.finalize?.({\n rootDir,\n distDir,\n staticDir: join(distDir, 'static'),\n publicDir: distPublicDir,\n ssgDir,\n });\n\n console.log(` ✓ build complete — ${preset.deployHint}`);\n process.exit(0);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"build.js","sourceRoot":"","sources":["../../src/cli/build.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAmB,MAAM,cAAc,CAAC;AAEvD,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAC7C,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AACtC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE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AC,CAAC;IAE5F,4FAA4F;IAC5F,gBAAgB,CAAC,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAEvC,iFAAiF;IACjF,MAAM,MAAM,CAAC,QAAQ,EAAE,CAAC;QACtB,OAAO;QACP,OAAO;QACP,SAAS,EAAE,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC;QAClC,SAAS,EAAE,eAAe;QAC1B,MAAM;QACN,MAAM,EAAE,MAAM,CAAC,MAAM;KACtB,CAAC,CAAC;IAEH,OAAO,CAAC,GAAG,CAAC,wBAAwB,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC;IAEzD,sGAAsG;IACtG,qFAAqF;IACrF,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC;AAChB,CAAC","sourcesContent":["import { rspack, type MultiStats } from '@rspack/core';\nimport type { Hono } from 'hono';\nimport { cpSync, existsSync } from 'node:fs';\nimport { rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { BUILD_OUT_DIR, createConfigs } from '../builder/rspack-config.js';\nimport type { RshonoConfig } from '../config.js';\nimport { writeBuildMarker } from '../deploy/build-marker.js';\nimport type { DeployPreset } from '../deploy/presets.js';\nimport type { Route } from '../router.js';\nimport { prerenderStaticRoutes } from '../server/ssg.js';\nimport { exit } from './exit.js';\n\ninterface BuildOptions {\n rootDir: string;\n config: RshonoConfig;\n /** The platform to build for, already resolved from the flag, the environment and the config. */\n preset: DeployPreset;\n}\n\n/** What `rshono build` uses the app's own server bundle for, once it has compiled it. */\ninterface ServerBundle {\n app: Hono;\n routes: readonly Route[];\n /** Resolves every route's own module, and the app's server actions, and checks them — see `checkAppModules`. */\n checkAppModules: () => Promise<void>;\n}\n\nfunction importServerBundle(distDir: string): Promise<ServerBundle> {\n return import(pathToFileURL(join(distDir, 'server', 'main.mjs')).href) as Promise<ServerBundle>;\n}\n\nexport async function buildCommand(options: BuildOptions): Promise<void> {\n const { rootDir, config, preset } = options;\n const distDir = join(rootDir, BUILD_OUT_DIR);\n\n console.log(' • building client + server bundles…');\n const configs = createConfigs({ rootDir, isDev: false, config, preset });\n const compiler = rspack(configs);\n\n const stats = await new Promise<MultiStats>((resolve, reject) => {\n compiler.run((err, result) => {\n compiler.close(() => {\n if (err) reject(err);\n else resolve(result!);\n });\n });\n });\n\n if (stats.hasErrors()) {\n console.error(stats.toString({ preset: 'errors-warnings', colors: true }));\n return exit(1);\n }\n // Printed rather than left to the summary below, which counts warnings without saying what they are —\n // and one of them is the env shadow reporting a read it cannot cover. See `env-shadow-loader.cjs`.\n if (stats.hasWarnings()) console.warn(stats.toString({ preset: 'errors-warnings', colors: true }));\n console.log(stats.toString({ preset: 'summary', colors: true }));\n\n const publicDir = join(rootDir, 'public');\n // From scratch, and unconditionally, like every other directory this build assembles. `cpSync` only\n // adds, so a file deleted from `public/` used to survive in `dist/public` and go on being served by\n // `rshono start` for good — and deleting `public/` outright left the whole of the old tree there, since\n // the copy below is the only thing that touches it. The two CDN presets clear their own output but read\n // *this* directory, so a stale file propagated into their assets as well, past a comment promising it\n // could not.\n const distPublicDir = join(distDir, 'public');\n await rm(distPublicDir, { recursive: true, force: true });\n let servedPublicDir: string | null = null;\n if (existsSync(publicDir)) {\n servedPublicDir = distPublicDir;\n cpSync(publicDir, distPublicDir, { recursive: true });\n console.log(' • copied public/ into dist/public (served at /)');\n }\n\n const ssgDir = join(distDir, 'ssg');\n await rm(ssgDir, { recursive: true, force: true });\n process.env.RSHONO_PRERENDER = '1';\n // The bundle's module scope is where `src/routes.ts` and `src/server.ts` are validated.\n //\n // This and the two stages below are what the *app* can fail — the two entry modules here, each route's own\n // module next, and a page that throws while prerendering after that. Each raises a `[rshono]` message\n // written for whoever is running the build, and `main().catch` in `cli/index.ts` is what prints it as the\n // one line it is. These used to be wrapped in a `phase()` helper that did the same thing three times and\n // nowhere else, which left `createConfigs` above — where a missing `src/routes.ts` is found — printing a\n // raw `Error` object with framework frames in it.\n const bundle = await importServerBundle(distDir);\n\n // Before anything is rendered: the checks here are the ones a route fails on *every* request, so a build\n // that skipped them would spend the prerender pass on a route it is about to refuse anyway. Without this\n // they ran on first request instead, which meant a page that could never work shipped behind a green build.\n await bundle.checkAppModules();\n\n const { written, skipped, flightOnly } = await prerenderStaticRoutes({\n routes: bundle.routes,\n fetch: (request) => bundle.app.fetch(request),\n ssgDir,\n siteUrl: config.siteUrl,\n });\n if (written.length > 0) {\n // Marked per page rather than counted separately, so the line answers the question a reader has about\n // each name in it: is this page served from disk? A page under a CSP nonce is half of one — its flight\n // payload is, its document is re-rendered per request — and saying \"prerendered\" alone would claim more\n // than the build did. The warning above says why, once.\n const nonced = new Set(flightOnly);\n const label = (path: string) => (nonced.has(path) ? `${path} (flight only)` : path);\n console.log(` • prerendered ${written.length} static page(s): ${written.map(label).join(', ')}`);\n }\n if (skipped.length > 0) console.log(` • skipped ${skipped.length} (will SSR per request)`);\n\n // Before `finalize`, so a preset that copies `dist/` into a platform layout takes it along.\n writeBuildMarker(distDir, preset.name);\n\n // Last, so a preset arranging its output finds every piece of the build on disk.\n await preset.finalize?.({\n rootDir,\n distDir,\n staticDir: join(distDir, 'static'),\n publicDir: servedPublicDir,\n ssgDir,\n routes: bundle.routes,\n });\n\n console.log(` ✓ build complete — ${preset.deployHint}`);\n\n // Rspack's worker pool can keep the loop alive after `close()`, so the exit is explicit. {@link exit}\n // drains first: in CI the tail is the lines saying what was built and where it went.\n await exit(0);\n}\n"]}
|
package/dist/cli/dev.d.ts
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { RshonoConfig } from '../config.js';
|
|
2
2
|
interface DevOptions {
|
|
3
3
|
rootDir: string;
|
|
4
4
|
port?: number;
|
|
5
|
-
config:
|
|
5
|
+
config: RshonoConfig;
|
|
6
6
|
}
|
|
7
7
|
export declare function devCommand(options: DevOptions): Promise<void>;
|
|
8
8
|
export {};
|
|
9
|
-
//# sourceMappingURL=dev.d.ts.map
|
package/dist/cli/dev.js
CHANGED
|
@@ -1,26 +1,99 @@
|
|
|
1
1
|
import { serve } from '@hono/node-server';
|
|
2
2
|
import { rspack } from '@rspack/core';
|
|
3
3
|
import { Hono } from 'hono';
|
|
4
|
+
import { proxy } from 'hono/proxy';
|
|
5
|
+
import { watch } from 'node:fs';
|
|
4
6
|
import { mkdir, rm } from 'node:fs/promises';
|
|
7
|
+
import { createServer } from 'node:net';
|
|
5
8
|
import { join } from 'node:path';
|
|
6
9
|
import { Worker } from 'node:worker_threads';
|
|
7
|
-
import { createConfigs } from '../builder/rspack-config.js';
|
|
10
|
+
import { DEV_OUT_DIR, createConfigs } from '../builder/rspack-config.js';
|
|
8
11
|
import { NODE_PRESET } from '../deploy/presets.js';
|
|
9
12
|
import { SERVER_DEFAULTS } from '../server/server-config.js';
|
|
10
13
|
import { createStaticAssetsApp } from '../server/static.js';
|
|
14
|
+
import { exit } from './exit.js';
|
|
11
15
|
const WORKER_READY_TIMEOUT_MS = 15_000;
|
|
16
|
+
/**
|
|
17
|
+
* Files whose contents are *compiled into* a build rather than read per request, so no rebuild picks a change
|
|
18
|
+
* to them up: `.env` because the `PUBLIC_` view of it is baked into the client bundle by DefinePlugin and into
|
|
19
|
+
* the SSR layer by the env-shadow prelude, and `rshono.config.ts` because `ServerConfig` is a DefinePlugin
|
|
20
|
+
* literal too. `.env` is worse than the config, which the docs at least describe as build-time: a page that
|
|
21
|
+
* reads `process.env` rebuilds, serves, and shows the old value.
|
|
22
|
+
*/
|
|
23
|
+
const BAKED_IN_FILES = ['.env.local', '.env', 'rshono.config.ts', 'rshono.config.js', 'rshono.config.mjs'];
|
|
24
|
+
/**
|
|
25
|
+
* Watches those files, only to say that a restart is needed.
|
|
26
|
+
*
|
|
27
|
+
* Reloading them for real means re-exec'ing this process: `process.loadEnvFile` does not override a variable
|
|
28
|
+
* that is already set, so the copy this process took at startup would survive an in-place reload — and the
|
|
29
|
+
* worker is spawned with `env: process.env`, so it would inherit the stale value too. Choreographing that
|
|
30
|
+
* against a bound port and a live SSE connection is a great deal of machinery to save one Ctrl-C; a line
|
|
31
|
+
* saying which key to press costs nothing and loses nobody an afternoon.
|
|
32
|
+
*
|
|
33
|
+
* The directory is watched rather than each file, so a file that does not exist yet is still covered — and
|
|
34
|
+
* because an editor's atomic save replaces the file, which a watch on the file itself does not survive. An
|
|
35
|
+
* explicit `--config` outside the project root is not covered: this is a convenience, not a contract.
|
|
36
|
+
*/
|
|
37
|
+
function warnOnBakedInFileChanges(rootDir) {
|
|
38
|
+
const warnedAt = new Map();
|
|
39
|
+
try {
|
|
40
|
+
// `persistent: false`: the dev server is kept alive by its listener, and a watcher that outlived it
|
|
41
|
+
// would hold the process open with nothing left to report to.
|
|
42
|
+
watch(rootDir, { persistent: false }, (_event, filename) => {
|
|
43
|
+
if (!filename || !BAKED_IN_FILES.includes(filename))
|
|
44
|
+
return;
|
|
45
|
+
// One save fires several events — a write, a rename, an attribute change — and they are all the same
|
|
46
|
+
// save. The window is short enough that a second real edit still gets its own line.
|
|
47
|
+
const now = Date.now();
|
|
48
|
+
if (now - (warnedAt.get(filename) ?? 0) < 250)
|
|
49
|
+
return;
|
|
50
|
+
warnedAt.set(filename, now);
|
|
51
|
+
console.warn(` ⚠ ${filename} changed — restart \`rshono dev\` to pick it up. It is compiled into the build, not read per request.`);
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
// No watcher available: a filesystem that cannot, or a platform limit reached. Rebuilding still works,
|
|
56
|
+
// so the dev server goes on without the reminder rather than refusing to start over one.
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** An error as the dev server shows it in the browser: the stack where there is one, since this is dev. */
|
|
60
|
+
function describe(error) {
|
|
61
|
+
return error instanceof Error ? (error.stack ?? error.message) : String(error);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Whether nothing is listening on the port yet — checked before the output directory is emptied, because a
|
|
65
|
+
* second `rshono dev` would otherwise wipe the chunks the running one is still importing and only then exit
|
|
66
|
+
* on EADDRINUSE.
|
|
67
|
+
*/
|
|
68
|
+
function portAvailable(port, hostname) {
|
|
69
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
70
|
+
const probe = createServer();
|
|
71
|
+
probe.once('error', () => resolve(false));
|
|
72
|
+
probe.listen(port, hostname, () => probe.close(() => resolve(true)));
|
|
73
|
+
return promise;
|
|
74
|
+
}
|
|
12
75
|
export async function devCommand(options) {
|
|
13
76
|
const { rootDir, config } = options;
|
|
14
77
|
const port = options.port ?? SERVER_DEFAULTS.port;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
78
|
+
// Its own directory, never `dist/`: a `rshono build` in another terminal must not be able to delete the
|
|
79
|
+
// chunks this server is still importing.
|
|
80
|
+
const outDir = join(rootDir, DEV_OUT_DIR);
|
|
81
|
+
// Before the `rm` below, not at `serve` where the bind happens — see {@link portAvailable}.
|
|
82
|
+
if (!(await portAvailable(port, '127.0.0.1'))) {
|
|
83
|
+
console.error(` ✗ port ${port} is already in use`);
|
|
84
|
+
return exit(1);
|
|
85
|
+
}
|
|
86
|
+
await rm(outDir, { recursive: true, force: true });
|
|
87
|
+
await mkdir(join(outDir, 'static'), { recursive: true });
|
|
18
88
|
const encoder = new TextEncoder();
|
|
19
89
|
const sseClients = new Set();
|
|
20
90
|
let clientHash;
|
|
21
91
|
const sseChunk = (data) => encoder.encode(`data: ${JSON.stringify(data)}\n\n`);
|
|
22
|
-
|
|
23
|
-
|
|
92
|
+
/**
|
|
93
|
+
* Writes one already-encoded SSE frame to every open client. A failed write is what retires a client:
|
|
94
|
+
* `cancel` is not always reached first when a browser navigates away.
|
|
95
|
+
*/
|
|
96
|
+
function sendToAll(chunk) {
|
|
24
97
|
for (const controller of sseClients) {
|
|
25
98
|
try {
|
|
26
99
|
controller.enqueue(chunk);
|
|
@@ -30,13 +103,16 @@ export async function devCommand(options) {
|
|
|
30
103
|
}
|
|
31
104
|
}
|
|
32
105
|
}
|
|
106
|
+
function broadcast(message) {
|
|
107
|
+
sendToAll(sseChunk(message));
|
|
108
|
+
}
|
|
33
109
|
let serverComponentsChanged = false;
|
|
34
110
|
const [clientConfig, serverConfig] = createConfigs({
|
|
35
111
|
rootDir,
|
|
36
112
|
isDev: true,
|
|
37
113
|
config,
|
|
38
|
-
// Always Node, whatever `deploy` says:
|
|
39
|
-
//
|
|
114
|
+
// Always Node, whatever `deploy` says: that is a property of `build` output, and the dev server runs the
|
|
115
|
+
// bundle in a worker thread of this process.
|
|
40
116
|
preset: NODE_PRESET,
|
|
41
117
|
onServerComponentChanges: () => {
|
|
42
118
|
serverComponentsChanged = true;
|
|
@@ -54,22 +130,32 @@ export async function devCommand(options) {
|
|
|
54
130
|
}
|
|
55
131
|
function spawnWorker() {
|
|
56
132
|
return new Promise((resolve, reject) => {
|
|
57
|
-
const worker = new Worker(join(
|
|
133
|
+
const worker = new Worker(join(outDir, 'server', 'main.mjs'), {
|
|
58
134
|
workerData: { port: 0, hostname: '127.0.0.1' },
|
|
59
135
|
execArgv: ['--enable-source-maps'],
|
|
60
136
|
env: process.env,
|
|
61
137
|
});
|
|
62
138
|
const timeout = setTimeout(() => {
|
|
63
|
-
worker
|
|
139
|
+
// Nothing waits on the termination: the promise below is already being rejected, and a worker that
|
|
140
|
+
// never reported ready has no state left worth draining.
|
|
141
|
+
void worker.terminate();
|
|
64
142
|
reject(new Error(`server worker did not become ready within ${WORKER_READY_TIMEOUT_MS / 1000}s`));
|
|
65
143
|
}, WORKER_READY_TIMEOUT_MS);
|
|
144
|
+
let ready = false;
|
|
66
145
|
worker.once('message', (message) => {
|
|
67
146
|
if (message?.type === 'ready' && typeof message.port === 'number') {
|
|
147
|
+
ready = true;
|
|
68
148
|
clearTimeout(timeout);
|
|
69
149
|
resolve({ worker, port: message.port });
|
|
70
150
|
}
|
|
71
151
|
});
|
|
72
|
-
|
|
152
|
+
// `on`, not `once`: an error after the worker is ready has no pending promise left to reject, and a
|
|
153
|
+
// consumed `once` would leave it unlistened — which Node turns into an uncaught exception here.
|
|
154
|
+
worker.on('error', (error) => {
|
|
155
|
+
if (ready) {
|
|
156
|
+
console.error(' ✗ server worker crashed:', error);
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
73
159
|
clearTimeout(timeout);
|
|
74
160
|
reject(error);
|
|
75
161
|
});
|
|
@@ -77,7 +163,10 @@ export async function devCommand(options) {
|
|
|
77
163
|
if (worker === currentWorker && code !== 0) {
|
|
78
164
|
console.error(` ✗ server worker exited with code ${code} — waiting for the next rebuild`);
|
|
79
165
|
currentWorker = null;
|
|
166
|
+
// Opened with the reason rather than left closed, so a request arriving before the next rebuild sees
|
|
167
|
+
// it instead of hanging. `hooks.invalid` installs a fresh closed gate as soon as a file changes.
|
|
80
168
|
workerGate = createGate();
|
|
169
|
+
workerGate.open({ error: `The server worker exited with code ${code}. See the terminal for the error it crashed with.` });
|
|
81
170
|
}
|
|
82
171
|
});
|
|
83
172
|
});
|
|
@@ -110,9 +199,15 @@ export async function devCommand(options) {
|
|
|
110
199
|
}
|
|
111
200
|
catch (error) {
|
|
112
201
|
console.error(' ✗ failed to start server worker:', error);
|
|
113
|
-
gate.open({ error:
|
|
202
|
+
gate.open({ error: describe(error) });
|
|
114
203
|
}
|
|
115
204
|
});
|
|
205
|
+
// No link in this queue may be left rejected: `.then` on a rejected promise short-circuits, and from there
|
|
206
|
+
// no worker is spawned and no gate is opened again.
|
|
207
|
+
restartChain = restartChain.catch((error) => {
|
|
208
|
+
console.error(' ✗ dev server restart failed:', error);
|
|
209
|
+
gate.open({ error: describe(error) });
|
|
210
|
+
});
|
|
116
211
|
await restartChain;
|
|
117
212
|
});
|
|
118
213
|
clientCompiler.hooks.done.tap('rshono/hmr', (stats) => {
|
|
@@ -131,14 +226,31 @@ export async function devCommand(options) {
|
|
|
131
226
|
return;
|
|
132
227
|
}
|
|
133
228
|
if (multiStats && !multiStats.hasErrors()) {
|
|
229
|
+
// Errors print themselves through the per-compiler `done` hooks; a warning has nowhere else to go, and
|
|
230
|
+
// the env shadow reports what it cannot cover that way. See `env-shadow-loader.cjs`.
|
|
231
|
+
if (multiStats.hasWarnings())
|
|
232
|
+
console.warn(multiStats.toString({ preset: 'errors-warnings', colors: true }));
|
|
134
233
|
const seconds = Math.max(...multiStats.stats.map((s) => (s.endTime ?? 0) - (s.startTime ?? 0))) / 1000;
|
|
135
234
|
console.log(` ${firstBuild ? '✓ built' : '✓ rebuilt'} in ${seconds.toFixed(1)}s`);
|
|
136
235
|
firstBuild = false;
|
|
137
236
|
}
|
|
138
237
|
});
|
|
139
238
|
const front = new Hono();
|
|
140
|
-
|
|
141
|
-
|
|
239
|
+
// **Answered here, not proxied — so the app's own middleware does not see an asset request in dev.**
|
|
240
|
+
// That is a divergence from a build, where `/_static` is mounted *inside* the app so an asset carries
|
|
241
|
+
// HSTS, the app's CSP and anything else its middleware sets (`prod-config.test.mjs` asserts it). It is
|
|
242
|
+
// kept deliberately, and the reason is the gate below: every request the front-end proxies first awaits
|
|
243
|
+
// `workerGate.promise`. The client bundle is built by a compiler that finishes independently of the
|
|
244
|
+
// server one, so proxying assets would park the browser's JS and CSS behind the *server* rebuild — a save
|
|
245
|
+
// touching one server component would stall the whole page's assets, and a server bundle that failed to
|
|
246
|
+
// build would take them down with it. A worse dev experience than the divergence.
|
|
247
|
+
//
|
|
248
|
+
// What it costs is real and worth knowing: a CSP is developed against a policy that does not apply to the
|
|
249
|
+
// files it is most likely to break, so the first time it does is in a build. If this ever has to go, the
|
|
250
|
+
// shape that keeps both properties is narrower than a plain move — proxy `/_static` only while a worker
|
|
251
|
+
// is live, and answer locally while the gate is closed.
|
|
252
|
+
front.route('/_static', createStaticAssetsApp({ root: join(outDir, 'static'), isDev: true }));
|
|
253
|
+
front.get('/_rshono/hmr', () => {
|
|
142
254
|
let ctrl;
|
|
143
255
|
const stream = new ReadableStream({
|
|
144
256
|
start(controller) {
|
|
@@ -159,16 +271,10 @@ export async function devCommand(options) {
|
|
|
159
271
|
},
|
|
160
272
|
});
|
|
161
273
|
});
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
}
|
|
167
|
-
catch {
|
|
168
|
-
sseClients.delete(controller);
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
}, 15_000).unref();
|
|
274
|
+
// An SSE comment, not a message: it keeps an idle connection off a proxy's timeout without the client
|
|
275
|
+
// having to know a frame type that means nothing.
|
|
276
|
+
const ping = encoder.encode(': ping\n\n');
|
|
277
|
+
setInterval(() => sendToAll(ping), 15_000).unref();
|
|
172
278
|
front.all('*', async (c) => {
|
|
173
279
|
const { error } = await workerGate.promise;
|
|
174
280
|
if (error || workerPort === null) {
|
|
@@ -176,33 +282,31 @@ export async function devCommand(options) {
|
|
|
176
282
|
}
|
|
177
283
|
const incoming = new URL(c.req.url);
|
|
178
284
|
const target = `http://127.0.0.1:${workerPort}${incoming.pathname}${incoming.search}`;
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
headers
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
method: c.req.method,
|
|
186
|
-
headers,
|
|
187
|
-
body: hasBody ? c.req.raw.body : undefined,
|
|
285
|
+
// Hono's proxy helper rather than a hand-rolled `fetch`: it carries the method, the streamed body (with
|
|
286
|
+
// the `duplex` Node requires) and the client's abort signal, and strips the hop-by-hop headers on the way
|
|
287
|
+
// back. `headers` replaces the set wholesale, so the request's own are spread back in first.
|
|
288
|
+
const response = await proxy(target, {
|
|
289
|
+
raw: c.req.raw,
|
|
290
|
+
// The worker's redirects are the app's answer to this request, to be rewritten below and passed on.
|
|
188
291
|
redirect: 'manual',
|
|
189
|
-
|
|
190
|
-
|
|
292
|
+
headers: {
|
|
293
|
+
...c.req.header(),
|
|
294
|
+
// This front-end *is* the proxy the app sits behind, which is why `trustProxy` is forced on in dev:
|
|
295
|
+
// without these the app resolves every URL against the worker's random 127.0.0.1 port.
|
|
296
|
+
'x-forwarded-host': incoming.host,
|
|
297
|
+
'x-forwarded-proto': incoming.protocol.replace(':', ''),
|
|
298
|
+
},
|
|
191
299
|
});
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
const location = responseHeaders.get('location');
|
|
300
|
+
// A redirect to the worker's own address has to become a relative one, or the browser leaves the dev
|
|
301
|
+
// server for a random port only this process knows about.
|
|
302
|
+
const location = response.headers.get('location');
|
|
196
303
|
const loc = location ? URL.parse(location, target) : null;
|
|
197
304
|
if (loc && loc.host === `127.0.0.1:${workerPort}`) {
|
|
198
|
-
|
|
305
|
+
response.headers.set('location', `${loc.pathname}${loc.search}${loc.hash}`);
|
|
199
306
|
}
|
|
200
|
-
return
|
|
201
|
-
status: response.status,
|
|
202
|
-
statusText: response.statusText,
|
|
203
|
-
headers: responseHeaders,
|
|
204
|
-
});
|
|
307
|
+
return response;
|
|
205
308
|
});
|
|
309
|
+
warnOnBakedInFileChanges(rootDir);
|
|
206
310
|
serve({ fetch: front.fetch, port, hostname: '127.0.0.1' }, (info) => {
|
|
207
311
|
console.log(` ➜ rshono dev server: http://localhost:${info.port}`);
|
|
208
312
|
});
|
package/dist/cli/dev.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev.js","sourceRoot":"","sources":["../../src/cli/dev.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,MAAM,EAAc,MAAM,cAAc,CAAC;AAClD,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAE5D,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAEnD,OAAO,EAAE,eAA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nimport { Hono } from 'hono';\nimport { mkdir, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { Worker } from 'node:worker_threads';\nimport { createConfigs } from '../builder/rspack-config.js';\nimport type { RSHonoConfig } from '../config.js';\nimport { NODE_PRESET } from '../deploy/presets.js';\nimport type { DevMessage } from '../runtime/dev-protocol.js';\nimport { SERVER_DEFAULTS } from '../server/server-config.js';\nimport { createStaticAssetsApp } from '../server/static.js';\n\nconst WORKER_READY_TIMEOUT_MS = 15_000;\n\ninterface DevOptions {\n rootDir: string;\n port?: number;\n config: RSHonoConfig;\n}\n\nexport async function devCommand(options: DevOptions): Promise<void> {\n const { rootDir, config } = options;\n const port = options.port ?? SERVER_DEFAULTS.port;\n const distDir = join(rootDir, 'dist');\n\n await rm(distDir, { recursive: true, force: true });\n await mkdir(join(distDir, 'static'), { recursive: true });\n\n const encoder = new TextEncoder();\n const sseClients = new Set<ReadableStreamDefaultController<Uint8Array>>();\n let clientHash: string | undefined;\n\n const sseChunk = (data: unknown) => encoder.encode(`data: ${JSON.stringify(data)}\\n\\n`);\n function broadcast(message: DevMessage): void {\n const chunk = sseChunk(message);\n for (const controller of sseClients) {\n try {\n controller.enqueue(chunk);\n } catch {\n sseClients.delete(controller);\n }\n }\n }\n\n let serverComponentsChanged = false;\n const [clientConfig, serverConfig] = createConfigs({\n rootDir,\n isDev: true,\n config,\n // Always Node, whatever `deploy` says: the dev server runs the bundle in a worker thread of this\n // process and fronts it on one port. `deploy` is a property of `build` output, not of developing.\n preset: NODE_PRESET,\n onServerComponentChanges: () => {\n serverComponentsChanged = true;\n },\n });\n const compiler = rspack([clientConfig, serverConfig]);\n const [clientCompiler, serverCompiler] = compiler.compilers;\n\n let currentWorker: Worker | null = null;\n let workerPort: number | null = null;\n let workerGate = createGate();\n let restartChain: Promise<void> = Promise.resolve();\n\n function createGate() {\n const { promise, resolve } = Promise.withResolvers<{ error?: string }>();\n return { promise, open: resolve };\n }\n\n function spawnWorker(): Promise<{ worker: Worker; port: number }> {\n return new Promise((resolve, reject) => {\n const worker = new Worker(join(distDir, 'server', 'main.mjs'), {\n workerData: { port: 0, hostname: '127.0.0.1' },\n execArgv: ['--enable-source-maps'],\n env: process.env as Record<string, string>,\n });\n const timeout = setTimeout(() => {\n worker.terminate();\n reject(new Error(`server worker did not become ready within ${WORKER_READY_TIMEOUT_MS / 1000}s`));\n }, WORKER_READY_TIMEOUT_MS);\n\n worker.once('message', (message: { type?: string; port?: number }) => {\n if (message?.type === 'ready' && typeof message.port === 'number') {\n clearTimeout(timeout);\n resolve({ worker, port: message.port });\n }\n });\n worker.once('error', (error) => {\n clearTimeout(timeout);\n reject(error);\n });\n worker.on('exit', (code) => {\n if (worker === currentWorker && code !== 0) {\n console.error(` ✗ server worker exited with code ${code} — waiting for the next rebuild`);\n currentWorker = null;\n workerGate = createGate();\n }\n });\n });\n }\n\n serverCompiler.hooks.invalid.tap('rshono/gate', () => {\n workerGate = createGate();\n });\n\n serverCompiler.hooks.done.tapPromise('rshono/worker', async (stats: Stats) => {\n const gate = workerGate;\n restartChain = restartChain.then(async () => {\n if (stats.hasErrors()) {\n console.error(stats.toString({ preset: 'errors-warnings', colors: true }));\n gate.open({ error: stats.toString({ preset: 'errors-only', colors: false }) });\n return;\n }\n try {\n if (currentWorker) {\n const old = currentWorker;\n currentWorker = null;\n await old.terminate();\n }\n const { worker, port: newPort } = await spawnWorker();\n currentWorker = worker;\n workerPort = newPort;\n gate.open({});\n if (serverComponentsChanged) {\n serverComponentsChanged = false;\n broadcast({ type: 'rsc-update' });\n }\n } catch (error) {\n console.error(' ✗ failed to start server worker:', error);\n gate.open({ error: error instanceof Error ? (error.stack ?? error.message) : String(error) });\n }\n });\n await restartChain;\n });\n\n clientCompiler.hooks.done.tap('rshono/hmr', (stats: Stats) => {\n if (stats.hasErrors()) {\n console.error(stats.toString({ preset: 'errors-warnings', colors: true }));\n return;\n }\n clientHash = stats.hash ?? undefined;\n if (clientHash) broadcast({ type: 'client-built', hash: clientHash });\n });\n\n let firstBuild = true;\n compiler.watch([{}, {}] as never, (err, multiStats) => {\n if (err) {\n console.error(' ✗ build failed:', err);\n return;\n }\n if (multiStats && !multiStats.hasErrors()) {\n const seconds = Math.max(...multiStats.stats.map((s) => (s.endTime ?? 0) - (s.startTime ?? 0))) / 1000;\n console.log(` ${firstBuild ? '✓ built' : '✓ rebuilt'} in ${seconds.toFixed(1)}s`);\n firstBuild = false;\n }\n });\n\n const front = new Hono();\n\n front.route('/_static', createStaticAssetsApp({ root: join(distDir, 'static'), isDev: true }));\n\n front.get('/_rshono/hmr', (c) => {\n let ctrl: ReadableStreamDefaultController<Uint8Array>;\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n ctrl = controller;\n sseClients.add(controller);\n controller.enqueue(encoder.encode('retry: 500\\n\\n'));\n controller.enqueue(sseChunk({ type: 'hello', hash: clientHash } satisfies DevMessage));\n },\n cancel() {\n sseClients.delete(ctrl);\n },\n });\n return new Response(stream, {\n headers: {\n 'content-type': 'text/event-stream',\n 'cache-control': 'no-cache',\n connection: 'keep-alive',\n },\n });\n });\n\n setInterval(() => {\n for (const controller of sseClients) {\n try {\n controller.enqueue(encoder.encode(': ping\\n\\n'));\n } catch {\n sseClients.delete(controller);\n }\n }\n }, 15_000).unref();\n\n front.all('*', async (c) => {\n const { error } = await workerGate.promise;\n if (error || workerPort === null) {\n return c.text(`Build failed:\\n\\n${error ?? 'server not running'}`, 500);\n }\n\n const incoming = new URL(c.req.url);\n const target = `http://127.0.0.1:${workerPort}${incoming.pathname}${incoming.search}`;\n\n const headers = new Headers(c.req.raw.headers);\n headers.delete('accept-encoding');\n headers.set('x-forwarded-host', incoming.host);\n headers.set('x-forwarded-proto', incoming.protocol.replace(':', ''));\n\n const hasBody = c.req.method !== 'GET' && c.req.method !== 'HEAD';\n const response = await fetch(target, {\n method: c.req.method,\n headers,\n body: hasBody ? c.req.raw.body : undefined,\n redirect: 'manual',\n // @ts-expect-error — Node fetch requires duplex for streamed bodies\n duplex: hasBody ? 'half' : undefined,\n });\n\n const responseHeaders = new Headers(response.headers);\n responseHeaders.delete('content-encoding');\n responseHeaders.delete('content-length');\n const location = responseHeaders.get('location');\n const loc = location ? URL.parse(location, target) : null;\n if (loc && loc.host === `127.0.0.1:${workerPort}`) {\n responseHeaders.set('location', `${loc.pathname}${loc.search}${loc.hash}`);\n }\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n });\n });\n\n serve({ fetch: front.fetch, port, hostname: '127.0.0.1' }, (info) => {\n console.log(` ➜ rshono dev server: http://localhost:${info.port}`);\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"dev.js","sourceRoot":"","sources":["../../src/cli/dev.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,MAAM,EAAc,MAAM,cAAc,CAAC;AAClD,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAEzE,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAEnD,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,MAAM,uBAAuB,GAAG,MAAM,CAAC;AAEvC;;;;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AK,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QAC1D,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,aAAa,UAAU,EAAE,EAAE,CAAC;YAClD,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,GAAG,GAAG,CAAC,QAAQ,GAAG,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;QAC9E,CAAC;QACD,OAAO,QAAQ,CAAC;IAClB,CAAC,CAAC,CAAC;IAEH,wBAAwB,CAAC,OAAO,CAAC,CAAC;IAElC,KAAK,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,EAAE,CAAC,IAAI,EAAE,EAAE;QAClE,OAAO,CAAC,GAAG,CAAC,2CAA2C,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;IACtE,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { serve } from '@hono/node-server';\nimport { rspack, type Stats } from '@rspack/core';\nimport { Hono } from 'hono';\nimport { proxy } from 'hono/proxy';\nimport { watch } from 'node:fs';\nimport { mkdir, rm } from 'node:fs/promises';\nimport { createServer } from 'node:net';\nimport { join } from 'node:path';\nimport { Worker } from 'node:worker_threads';\nimport { DEV_OUT_DIR, createConfigs } from '../builder/rspack-config.js';\nimport type { RshonoConfig } from '../config.js';\nimport { NODE_PRESET } from '../deploy/presets.js';\nimport type { DevMessage } from '../runtime/dev-protocol.js';\nimport { SERVER_DEFAULTS } from '../server/server-config.js';\nimport { createStaticAssetsApp } from '../server/static.js';\nimport { exit } from './exit.js';\n\nconst WORKER_READY_TIMEOUT_MS = 15_000;\n\n/**\n * Files whose contents are *compiled into* a build rather than read per request, so no rebuild picks a change\n * to them up: `.env` because the `PUBLIC_` view of it is baked into the client bundle by DefinePlugin and into\n * the SSR layer by the env-shadow prelude, and `rshono.config.ts` because `ServerConfig` is a DefinePlugin\n * literal too. `.env` is worse than the config, which the docs at least describe as build-time: a page that\n * reads `process.env` rebuilds, serves, and shows the old value.\n */\nconst BAKED_IN_FILES = ['.env.local', '.env', 'rshono.config.ts', 'rshono.config.js', 'rshono.config.mjs'];\n\n/**\n * Watches those files, only to say that a restart is needed.\n *\n * Reloading them for real means re-exec'ing this process: `process.loadEnvFile` does not override a variable\n * that is already set, so the copy this process took at startup would survive an in-place reload — and the\n * worker is spawned with `env: process.env`, so it would inherit the stale value too. Choreographing that\n * against a bound port and a live SSE connection is a great deal of machinery to save one Ctrl-C; a line\n * saying which key to press costs nothing and loses nobody an afternoon.\n *\n * The directory is watched rather than each file, so a file that does not exist yet is still covered — and\n * because an editor's atomic save replaces the file, which a watch on the file itself does not survive. An\n * explicit `--config` outside the project root is not covered: this is a convenience, not a contract.\n */\nfunction warnOnBakedInFileChanges(rootDir: string): void {\n const warnedAt = new Map<string, number>();\n try {\n // `persistent: false`: the dev server is kept alive by its listener, and a watcher that outlived it\n // would hold the process open with nothing left to report to.\n watch(rootDir, { persistent: false }, (_event, filename) => {\n if (!filename || !BAKED_IN_FILES.includes(filename)) return;\n // One save fires several events — a write, a rename, an attribute change — and they are all the same\n // save. The window is short enough that a second real edit still gets its own line.\n const now = Date.now();\n if (now - (warnedAt.get(filename) ?? 0) < 250) return;\n warnedAt.set(filename, now);\n console.warn(` ⚠ ${filename} changed — restart \\`rshono dev\\` to pick it up. It is compiled into the build, not read per request.`);\n });\n } catch {\n // No watcher available: a filesystem that cannot, or a platform limit reached. Rebuilding still works,\n // so the dev server goes on without the reminder rather than refusing to start over one.\n }\n}\n\n/** An error as the dev server shows it in the browser: the stack where there is one, since this is dev. */\nfunction describe(error: unknown): string {\n return error instanceof Error ? (error.stack ?? error.message) : String(error);\n}\n\n/**\n * Whether nothing is listening on the port yet — checked before the output directory is emptied, because a\n * second `rshono dev` would otherwise wipe the chunks the running one is still importing and only then exit\n * on EADDRINUSE.\n */\nfunction portAvailable(port: number, hostname: string): Promise<boolean> {\n const { promise, resolve } = Promise.withResolvers<boolean>();\n const probe = createServer();\n probe.once('error', () => resolve(false));\n probe.listen(port, hostname, () => probe.close(() => resolve(true)));\n return promise;\n}\n\ninterface DevOptions {\n rootDir: string;\n port?: number;\n config: RshonoConfig;\n}\n\nexport async function devCommand(options: DevOptions): Promise<void> {\n const { rootDir, config } = options;\n const port = options.port ?? SERVER_DEFAULTS.port;\n // Its own directory, never `dist/`: a `rshono build` in another terminal must not be able to delete the\n // chunks this server is still importing.\n const outDir = join(rootDir, DEV_OUT_DIR);\n\n // Before the `rm` below, not at `serve` where the bind happens — see {@link portAvailable}.\n if (!(await portAvailable(port, '127.0.0.1'))) {\n console.error(` ✗ port ${port} is already in use`);\n return exit(1);\n }\n\n await rm(outDir, { recursive: true, force: true });\n await mkdir(join(outDir, 'static'), { recursive: true });\n\n const encoder = new TextEncoder();\n const sseClients = new Set<ReadableStreamDefaultController<Uint8Array>>();\n let clientHash: string | undefined;\n\n const sseChunk = (data: unknown) => encoder.encode(`data: ${JSON.stringify(data)}\\n\\n`);\n\n /**\n * Writes one already-encoded SSE frame to every open client. A failed write is what retires a client:\n * `cancel` is not always reached first when a browser navigates away.\n */\n function sendToAll(chunk: Uint8Array): void {\n for (const controller of sseClients) {\n try {\n controller.enqueue(chunk);\n } catch {\n sseClients.delete(controller);\n }\n }\n }\n\n function broadcast(message: DevMessage): void {\n sendToAll(sseChunk(message));\n }\n\n let serverComponentsChanged = false;\n const [clientConfig, serverConfig] = createConfigs({\n rootDir,\n isDev: true,\n config,\n // Always Node, whatever `deploy` says: that is a property of `build` output, and the dev server runs the\n // bundle in a worker thread of this process.\n preset: NODE_PRESET,\n onServerComponentChanges: () => {\n serverComponentsChanged = true;\n },\n });\n const compiler = rspack([clientConfig, serverConfig]);\n const [clientCompiler, serverCompiler] = compiler.compilers;\n\n let currentWorker: Worker | null = null;\n let workerPort: number | null = null;\n let workerGate = createGate();\n let restartChain: Promise<void> = Promise.resolve();\n\n function createGate() {\n const { promise, resolve } = Promise.withResolvers<{ error?: string }>();\n return { promise, open: resolve };\n }\n\n function spawnWorker(): Promise<{ worker: Worker; port: number }> {\n return new Promise((resolve, reject) => {\n const worker = new Worker(join(outDir, 'server', 'main.mjs'), {\n workerData: { port: 0, hostname: '127.0.0.1' },\n execArgv: ['--enable-source-maps'],\n env: process.env as Record<string, string>,\n });\n const timeout = setTimeout(() => {\n // Nothing waits on the termination: the promise below is already being rejected, and a worker that\n // never reported ready has no state left worth draining.\n void worker.terminate();\n reject(new Error(`server worker did not become ready within ${WORKER_READY_TIMEOUT_MS / 1000}s`));\n }, WORKER_READY_TIMEOUT_MS);\n\n let ready = false;\n worker.once('message', (message: { type?: string; port?: number }) => {\n if (message?.type === 'ready' && typeof message.port === 'number') {\n ready = true;\n clearTimeout(timeout);\n resolve({ worker, port: message.port });\n }\n });\n // `on`, not `once`: an error after the worker is ready has no pending promise left to reject, and a\n // consumed `once` would leave it unlistened — which Node turns into an uncaught exception here.\n worker.on('error', (error: Error) => {\n if (ready) {\n console.error(' ✗ server worker crashed:', error);\n return;\n }\n clearTimeout(timeout);\n reject(error);\n });\n worker.on('exit', (code) => {\n if (worker === currentWorker && code !== 0) {\n console.error(` ✗ server worker exited with code ${code} — waiting for the next rebuild`);\n currentWorker = null;\n // Opened with the reason rather than left closed, so a request arriving before the next rebuild sees\n // it instead of hanging. `hooks.invalid` installs a fresh closed gate as soon as a file changes.\n workerGate = createGate();\n workerGate.open({ error: `The server worker exited with code ${code}. See the terminal for the error it crashed with.` });\n }\n });\n });\n }\n\n serverCompiler.hooks.invalid.tap('rshono/gate', () => {\n workerGate = createGate();\n });\n\n serverCompiler.hooks.done.tapPromise('rshono/worker', async (stats: Stats) => {\n const gate = workerGate;\n restartChain = restartChain.then(async () => {\n if (stats.hasErrors()) {\n console.error(stats.toString({ preset: 'errors-warnings', colors: true }));\n gate.open({ error: stats.toString({ preset: 'errors-only', colors: false }) });\n return;\n }\n try {\n if (currentWorker) {\n const old = currentWorker;\n currentWorker = null;\n await old.terminate();\n }\n const { worker, port: newPort } = await spawnWorker();\n currentWorker = worker;\n workerPort = newPort;\n gate.open({});\n if (serverComponentsChanged) {\n serverComponentsChanged = false;\n broadcast({ type: 'rsc-update' });\n }\n } catch (error) {\n console.error(' ✗ failed to start server worker:', error);\n gate.open({ error: describe(error) });\n }\n });\n // No link in this queue may be left rejected: `.then` on a rejected promise short-circuits, and from there\n // no worker is spawned and no gate is opened again.\n restartChain = restartChain.catch((error) => {\n console.error(' ✗ dev server restart failed:', error);\n gate.open({ error: describe(error) });\n });\n await restartChain;\n });\n\n clientCompiler.hooks.done.tap('rshono/hmr', (stats: Stats) => {\n if (stats.hasErrors()) {\n console.error(stats.toString({ preset: 'errors-warnings', colors: true }));\n return;\n }\n clientHash = stats.hash ?? undefined;\n if (clientHash) broadcast({ type: 'client-built', hash: clientHash });\n });\n\n let firstBuild = true;\n compiler.watch([{}, {}] as never, (err, multiStats) => {\n if (err) {\n console.error(' ✗ build failed:', err);\n return;\n }\n if (multiStats && !multiStats.hasErrors()) {\n // Errors print themselves through the per-compiler `done` hooks; a warning has nowhere else to go, and\n // the env shadow reports what it cannot cover that way. See `env-shadow-loader.cjs`.\n if (multiStats.hasWarnings()) console.warn(multiStats.toString({ preset: 'errors-warnings', colors: true }));\n const seconds = Math.max(...multiStats.stats.map((s) => (s.endTime ?? 0) - (s.startTime ?? 0))) / 1000;\n console.log(` ${firstBuild ? '✓ built' : '✓ rebuilt'} in ${seconds.toFixed(1)}s`);\n firstBuild = false;\n }\n });\n\n const front = new Hono();\n\n // **Answered here, not proxied — so the app's own middleware does not see an asset request in dev.**\n // That is a divergence from a build, where `/_static` is mounted *inside* the app so an asset carries\n // HSTS, the app's CSP and anything else its middleware sets (`prod-config.test.mjs` asserts it). It is\n // kept deliberately, and the reason is the gate below: every request the front-end proxies first awaits\n // `workerGate.promise`. The client bundle is built by a compiler that finishes independently of the\n // server one, so proxying assets would park the browser's JS and CSS behind the *server* rebuild — a save\n // touching one server component would stall the whole page's assets, and a server bundle that failed to\n // build would take them down with it. A worse dev experience than the divergence.\n //\n // What it costs is real and worth knowing: a CSP is developed against a policy that does not apply to the\n // files it is most likely to break, so the first time it does is in a build. If this ever has to go, the\n // shape that keeps both properties is narrower than a plain move — proxy `/_static` only while a worker\n // is live, and answer locally while the gate is closed.\n front.route('/_static', createStaticAssetsApp({ root: join(outDir, 'static'), isDev: true }));\n\n front.get('/_rshono/hmr', () => {\n let ctrl: ReadableStreamDefaultController<Uint8Array>;\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n ctrl = controller;\n sseClients.add(controller);\n controller.enqueue(encoder.encode('retry: 500\\n\\n'));\n controller.enqueue(sseChunk({ type: 'hello', hash: clientHash } satisfies DevMessage));\n },\n cancel() {\n sseClients.delete(ctrl);\n },\n });\n return new Response(stream, {\n headers: {\n 'content-type': 'text/event-stream',\n 'cache-control': 'no-cache',\n connection: 'keep-alive',\n },\n });\n });\n\n // An SSE comment, not a message: it keeps an idle connection off a proxy's timeout without the client\n // having to know a frame type that means nothing.\n const ping = encoder.encode(': ping\\n\\n');\n setInterval(() => sendToAll(ping), 15_000).unref();\n\n front.all('*', async (c) => {\n const { error } = await workerGate.promise;\n if (error || workerPort === null) {\n return c.text(`Build failed:\\n\\n${error ?? 'server not running'}`, 500);\n }\n\n const incoming = new URL(c.req.url);\n const target = `http://127.0.0.1:${workerPort}${incoming.pathname}${incoming.search}`;\n\n // Hono's proxy helper rather than a hand-rolled `fetch`: it carries the method, the streamed body (with\n // the `duplex` Node requires) and the client's abort signal, and strips the hop-by-hop headers on the way\n // back. `headers` replaces the set wholesale, so the request's own are spread back in first.\n const response = await proxy(target, {\n raw: c.req.raw,\n // The worker's redirects are the app's answer to this request, to be rewritten below and passed on.\n redirect: 'manual',\n headers: {\n ...c.req.header(),\n // This front-end *is* the proxy the app sits behind, which is why `trustProxy` is forced on in dev:\n // without these the app resolves every URL against the worker's random 127.0.0.1 port.\n 'x-forwarded-host': incoming.host,\n 'x-forwarded-proto': incoming.protocol.replace(':', ''),\n },\n });\n\n // A redirect to the worker's own address has to become a relative one, or the browser leaves the dev\n // server for a random port only this process knows about.\n const location = response.headers.get('location');\n const loc = location ? URL.parse(location, target) : null;\n if (loc && loc.host === `127.0.0.1:${workerPort}`) {\n response.headers.set('location', `${loc.pathname}${loc.search}${loc.hash}`);\n }\n return response;\n });\n\n warnOnBakedInFileChanges(rootDir);\n\n serve({ fetch: front.fetch, port, hostname: '127.0.0.1' }, (info) => {\n console.log(` ➜ rshono dev server: http://localhost:${info.port}`);\n });\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `process.exit`, once both output streams have drained.
|
|
3
|
+
*
|
|
4
|
+
* A piped stdout/stderr — every CI job, and any `rshono build | tee` — is asynchronous on POSIX, and exiting
|
|
5
|
+
* drops whatever has not left the pipe buffer (64 KiB on Linux and macOS; a pipe write on Windows is
|
|
6
|
+
* synchronous, so there the drain is a no-op). On the failure paths that is the report saying *why* the build
|
|
7
|
+
* failed, cut mid-error. A zero-length write's callback fires behind the real ones, so awaiting one per stream
|
|
8
|
+
* is enough.
|
|
9
|
+
*
|
|
10
|
+
* `Promise<never>`, so a caller can `return exit(1)` and keep the branch terminal for control-flow analysis.
|
|
11
|
+
*/
|
|
12
|
+
export declare function exit(code: number): Promise<never>;
|
package/dist/cli/exit.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `process.exit`, once both output streams have drained.
|
|
3
|
+
*
|
|
4
|
+
* A piped stdout/stderr — every CI job, and any `rshono build | tee` — is asynchronous on POSIX, and exiting
|
|
5
|
+
* drops whatever has not left the pipe buffer (64 KiB on Linux and macOS; a pipe write on Windows is
|
|
6
|
+
* synchronous, so there the drain is a no-op). On the failure paths that is the report saying *why* the build
|
|
7
|
+
* failed, cut mid-error. A zero-length write's callback fires behind the real ones, so awaiting one per stream
|
|
8
|
+
* is enough.
|
|
9
|
+
*
|
|
10
|
+
* `Promise<never>`, so a caller can `return exit(1)` and keep the branch terminal for control-flow analysis.
|
|
11
|
+
*/
|
|
12
|
+
export async function exit(code) {
|
|
13
|
+
await Promise.all([process.stdout, process.stderr].map((stream) => new Promise((resolve) => stream.write('', () => resolve()))));
|
|
14
|
+
process.exit(code);
|
|
15
|
+
}
|
|
16
|
+
//# sourceMappingURL=exit.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"exit.js","sourceRoot":"","sources":["../../src/cli/exit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,IAAI,CAAC,IAAY;IACrC,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IACvI,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACrB,CAAC","sourcesContent":["/**\n * `process.exit`, once both output streams have drained.\n *\n * A piped stdout/stderr — every CI job, and any `rshono build | tee` — is asynchronous on POSIX, and exiting\n * drops whatever has not left the pipe buffer (64 KiB on Linux and macOS; a pipe write on Windows is\n * synchronous, so there the drain is a no-op). On the failure paths that is the report saying *why* the build\n * failed, cut mid-error. A zero-length write's callback fires behind the real ones, so awaiting one per stream\n * is enough.\n *\n * `Promise<never>`, so a caller can `return exit(1)` and keep the branch terminal for control-flow analysis.\n */\nexport async function exit(code: number): Promise<never> {\n await Promise.all([process.stdout, process.stderr].map((stream) => new Promise<void>((resolve) => stream.write('', () => resolve()))));\n process.exit(code);\n}\n"]}
|
package/dist/cli/index.d.ts
CHANGED