@ngrok/app-server 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +236 -2
- package/dist/bun-DCGnDEPn.js +27 -0
- package/dist/bun-DCGnDEPn.js.map +1 -0
- package/dist/captured-headers-ewL_t3MQ.js +48 -0
- package/dist/captured-headers-ewL_t3MQ.js.map +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +33 -0
- package/dist/cli.js.map +1 -0
- package/dist/deno-BnMfk2n1.js +74 -0
- package/dist/deno-BnMfk2n1.js.map +1 -0
- package/dist/dev-DCytOhpM.js +132 -0
- package/dist/dev-DCytOhpM.js.map +1 -0
- package/dist/entry-2XXp2Ukh.js +793 -0
- package/dist/entry-2XXp2Ukh.js.map +1 -0
- package/dist/entry-CIpwaayZ.d.ts +293 -0
- package/dist/index.d.ts +176 -0
- package/dist/index.js +201 -0
- package/dist/index.js.map +1 -0
- package/dist/listen-options-DHWmSWGi.js +15 -0
- package/dist/listen-options-DHWmSWGi.js.map +1 -0
- package/dist/node-2wWBMFeO.js +3 -0
- package/dist/node-79my3Uix.js +58 -0
- package/dist/node-79my3Uix.js.map +1 -0
- package/dist/react-router.d.ts +47 -0
- package/dist/react-router.js +68 -0
- package/dist/react-router.js.map +1 -0
- package/dist/start-kxw_NM4q.js +16 -0
- package/dist/start-kxw_NM4q.js.map +1 -0
- package/dist/vite-CrNqpoeK.js +102 -0
- package/dist/vite-CrNqpoeK.js.map +1 -0
- package/dist/vite.d.ts +27 -0
- package/dist/vite.js +3 -0
- package/package.json +83 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) ngrok
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,237 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @ngrok/app-server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A composable [Hono](https://hono.dev) app server for [React Router](https://reactrouter.com) framework apps. It replaces `@react-router/serve`, and it runs the same request pipeline in development and production, on Node, Bun, and Deno.
|
|
4
|
+
|
|
5
|
+
What it fixes in `@react-router/serve`:
|
|
6
|
+
|
|
7
|
+
- A prerendered page answers at its own URL with a 200, not a 301 to a trailing slash.
|
|
8
|
+
- A prerendered resource route (`llms.txt`, `sitemap.xml`, a JSON API file) and each `.data` file keep the headers their loader sent: `Content-Type`, `Cache-Control`, CORS.
|
|
9
|
+
- A streamed page under gzip reaches the client chunk by chunk.
|
|
10
|
+
- Each request gets one JSON log line in your format, static files included, and an `X-Request-Id`.
|
|
11
|
+
- Shutdown drains open requests with a deadline, and the keep-alive timeout outlasts the proxy's idle pool.
|
|
12
|
+
|
|
13
|
+
## Requirements
|
|
14
|
+
|
|
15
|
+
- Node.js 24+, Bun 1.3+, or Deno 2.9+
|
|
16
|
+
- React Router 8.5+ and Vite 8.3+
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
pnpm add -E @ngrok/app-server hono
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Set up
|
|
25
|
+
|
|
26
|
+
Add the Vite plugin next to `reactRouter()`:
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
// vite.config.ts
|
|
30
|
+
import { serverEntry } from "@ngrok/app-server/vite";
|
|
31
|
+
import { reactRouter } from "@react-router/dev/vite";
|
|
32
|
+
import { defineConfig } from "vite";
|
|
33
|
+
|
|
34
|
+
export default defineConfig({
|
|
35
|
+
plugins: [reactRouter(), serverEntry("./server.ts")],
|
|
36
|
+
});
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Write the server. Its default export is the app:
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
// server.ts
|
|
43
|
+
import { createServer, defaultPlugins } from "@ngrok/app-server";
|
|
44
|
+
|
|
45
|
+
const app = createServer({ plugins: defaultPlugins() });
|
|
46
|
+
app.get("/livez", (c) => c.text("ok"));
|
|
47
|
+
export default app;
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Run it:
|
|
51
|
+
|
|
52
|
+
```json
|
|
53
|
+
{
|
|
54
|
+
"scripts": {
|
|
55
|
+
"start": "app-server dev",
|
|
56
|
+
"serve": "app-server start"
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`serverEntry` bundles `server.ts` into `build/server/index.js` with the rest of the app, so the server gets its path aliases and the app's one copy of `react-router`. The file stays a valid React Router server build. `serverEntry()` with no argument uses the default plugins.
|
|
62
|
+
|
|
63
|
+
The build exports `appServer`, and the CLI calls it. So the copy of this package in the build runs the server, and the CLI's copy runs nothing. The CLI refuses a build from a version of this package with another entry protocol.
|
|
64
|
+
|
|
65
|
+
An app with no `serverEntry` also works: `app-server start` reads a plain React Router build and runs it with the CLI's copy and the default plugins. In that build, a route that calls `shutdownSignal()` or `eventStream()` must import the CLI's copy, so do not bundle `@ngrok/app-server` into it.
|
|
66
|
+
|
|
67
|
+
## Commands
|
|
68
|
+
|
|
69
|
+
- `app-server dev`: Vite in middleware mode inside the pipeline, with HMR on the same port. Each request loads the latest server build, so an edit to a route or to `server.ts` applies at once. The port is `PORT`, else Vite's `server.port`. The host is `HOST`, else Vite's `server.host`.
|
|
70
|
+
- `app-server start [build/server/index.js]`: production. Reads `PORT` (default 3000) and `HOST` (default every interface). Stops on `SIGTERM` or `SIGINT`.
|
|
71
|
+
|
|
72
|
+
On Bun, run `bun node_modules/@ngrok/app-server/dist/cli.js start`. On Deno, run `deno run --allow-net --allow-env --allow-read --allow-sys node_modules/@ngrok/app-server/dist/cli.js start`.
|
|
73
|
+
|
|
74
|
+
## The pipeline
|
|
75
|
+
|
|
76
|
+
`createServer` runs the plugins in list order, then the app's own Hono routes, then React Router. `defaultPlugins()` returns this order:
|
|
77
|
+
|
|
78
|
+
1. `requestId()`: reuses a valid incoming `X-Request-Id`, else makes a UUID, and echoes it.
|
|
79
|
+
2. `accessLog({ redactQuery })`: one line per request when the body ends, with Datadog standard attributes (`http.status_code`, `network.bytes_written`, `duration` in nanoseconds). Query values are `REDACTED` by default.
|
|
80
|
+
3. `streamingCompress()`: gzip that flushes after each chunk. It skips encoded, partial, and `no-transform` responses.
|
|
81
|
+
4. The `beforeStatic` plugins: they see every response, prerendered pages included. `runtimeEnv` and `buildId` go here.
|
|
82
|
+
5. `assets()`: `/assets/*` with a one-year immutable cache. A missing asset gets a plain 404. In development, Vite serves here.
|
|
83
|
+
6. `prerendered({ headers, rewrite })`: every file in `build/client`, with an ETag and a 304 for a matching `If-None-Match`. A directory answers with its `index.html`. Each file has one URL: `/a//b`, `/a/index.html`, and `/a%2Fb` go on to React Router. Dotfiles stay private, except `/.well-known/`. A path with no file goes on to React Router.
|
|
84
|
+
|
|
85
|
+
`defaultPlugins()` is a plain array, so you can filter it or splice into it. A plugin is Hono middleware plus optional hooks:
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
import type { Plugin } from "@ngrok/app-server";
|
|
89
|
+
|
|
90
|
+
const securityHeaders: Plugin = {
|
|
91
|
+
name: "security-headers",
|
|
92
|
+
middleware: async (c, next) => {
|
|
93
|
+
await next();
|
|
94
|
+
c.header("X-Frame-Options", "DENY"); // `c.header` also works on a response with immutable headers
|
|
95
|
+
},
|
|
96
|
+
setup: (info) => {}, // once, before the first request; a throw stops startup
|
|
97
|
+
onShutdown: async () => {}, // at shutdown, while the listeners drain, up to the deadline
|
|
98
|
+
};
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
A plugin that changes a response with a value it reads at run time, as `runtimeEnv` and `buildId` do, returns that value from `etagPart`. The server adds it to the ETag of each static file that the request reaches after the plugin, so a 304 never keeps a response made with an old value.
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
const version: Plugin = {
|
|
105
|
+
name: "version",
|
|
106
|
+
etagPart: () => process.env.APP_VERSION,
|
|
107
|
+
middleware: async (c, next) => {
|
|
108
|
+
await next();
|
|
109
|
+
c.header("X-App-Version", process.env.APP_VERSION);
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
## Content negotiation
|
|
115
|
+
|
|
116
|
+
`rewrite` maps a request path to the file to serve. A rewritten path follows the same rules as a request path. This serves a prerendered markdown twin, such as `/components/button.md` for `/components/button`, to a client that asks for markdown:
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
import { readdirSync } from "node:fs";
|
|
120
|
+
|
|
121
|
+
const markdownPaths = new Set(
|
|
122
|
+
readdirSync("build/client", { recursive: true, encoding: "utf8" })
|
|
123
|
+
.filter((file) => file.endsWith(".md"))
|
|
124
|
+
.map((file) => `/${file}`),
|
|
125
|
+
);
|
|
126
|
+
const twin = (path: string) => `${path.replace(/\/+$/, "") || "/index"}.md`;
|
|
127
|
+
|
|
128
|
+
// Why a plugin: one URL answers HTML or markdown, so a shared cache must key on `Accept`.
|
|
129
|
+
const varyOnAccept: Plugin = {
|
|
130
|
+
name: "vary-on-accept",
|
|
131
|
+
middleware: async (c, next) => {
|
|
132
|
+
await next();
|
|
133
|
+
if (markdownPaths.has(twin(c.req.path))) {
|
|
134
|
+
c.header("Vary", "Accept", { append: true });
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
createServer({
|
|
140
|
+
plugins: defaultPlugins({
|
|
141
|
+
beforeStatic: [varyOnAccept],
|
|
142
|
+
prerendered: {
|
|
143
|
+
rewrite: (path, c) =>
|
|
144
|
+
markdownPaths.has(twin(path)) && c.req.header("Accept")?.includes("text/markdown")
|
|
145
|
+
? twin(path)
|
|
146
|
+
: path,
|
|
147
|
+
},
|
|
148
|
+
}),
|
|
149
|
+
});
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Parse the `Accept` quality values when a client can send `text/markdown;q=0`.
|
|
153
|
+
|
|
154
|
+
## Prerendered headers
|
|
155
|
+
|
|
156
|
+
During React Router's prerender pass, `serverEntry` records the response headers of each prerendered file that is not an HTML document into `build/client/.headers.json`, and `prerendered()` replays them. It leaves out `Set-Cookie`, `Vary`, and the headers of one transfer, such as `Content-Length`.
|
|
157
|
+
|
|
158
|
+
A document's headers are not recorded, because `entry.server` sets them for each request (a CSP nonce, the host). Set the headers of a prerendered page with the `headers` option or a plugin. For its CSP, use a `script-src` with the hash of each inline script, not a nonce. The prerender writes one nonce into the file, and every visitor can read it, so it protects nothing.
|
|
159
|
+
|
|
160
|
+
## Logs
|
|
161
|
+
|
|
162
|
+
Pass a sink to use your own format. Attribute names are flat and dotted:
|
|
163
|
+
|
|
164
|
+
```ts
|
|
165
|
+
createServer({
|
|
166
|
+
logger: {
|
|
167
|
+
log: (level, message, attributes) => mySlogger[level](message, attributes),
|
|
168
|
+
},
|
|
169
|
+
});
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
The default is `jsonSink()`: one JSON object per line on stdout.
|
|
173
|
+
|
|
174
|
+
In a loader, read the request ID and a logger whose lines carry it:
|
|
175
|
+
|
|
176
|
+
```ts
|
|
177
|
+
import { appServerContext } from "@ngrok/app-server/react-router";
|
|
178
|
+
|
|
179
|
+
export async function loader({ context }: Route.LoaderArgs) {
|
|
180
|
+
context.get(appServerContext).logger.info("loading");
|
|
181
|
+
}
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
## Environment
|
|
185
|
+
|
|
186
|
+
`runtimeEnv(schema)` validates the environment once, at startup, with any [Standard Schema](https://standardschema.dev) (zod, valibot, arktype). A bad value stops the server with a message that names it.
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
import { createServer, defaultPlugins, runtimeEnv } from "@ngrok/app-server";
|
|
190
|
+
import { z } from "zod";
|
|
191
|
+
|
|
192
|
+
export const env = runtimeEnv(
|
|
193
|
+
z.object({ PUBLIC_API_URL: z.url(), SESSION_KEY: z.string().min(32) }),
|
|
194
|
+
);
|
|
195
|
+
|
|
196
|
+
export default createServer({ plugins: defaultPlugins({ beforeStatic: [env] }) });
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
The values whose names start with `PUBLIC_` go into each HTML document at serve time, prerendered pages included, so one build serves every environment. Read them in the browser:
|
|
200
|
+
|
|
201
|
+
```ts
|
|
202
|
+
const publicEnv = JSON.parse(document.getElementById("app-server-public-env")?.textContent ?? "{}");
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
## Long-lived responses
|
|
206
|
+
|
|
207
|
+
`eventStream()` makes a server-sent event response that sends a heartbeat every 15 s, stops when the client disconnects, and closes at shutdown so the drain does not wait for it:
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
import { eventStream } from "@ngrok/app-server";
|
|
211
|
+
|
|
212
|
+
export async function loader({ request }: Route.LoaderArgs) {
|
|
213
|
+
return eventStream({ signal: request.signal }, async ({ send, signal }) => {
|
|
214
|
+
for await (const update of watch({ signal })) {
|
|
215
|
+
send({ event: "update", data: JSON.stringify(update) });
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
For other long work, stop on `shutdownSignal()`.
|
|
222
|
+
|
|
223
|
+
## Options
|
|
224
|
+
|
|
225
|
+
`createServer` takes:
|
|
226
|
+
|
|
227
|
+
- `plugins`: default `defaultPlugins()`.
|
|
228
|
+
- `logger`: default `jsonSink()`.
|
|
229
|
+
- `listeners`: default `[tcp()]`. A listener decides how connections arrive. `tcp()` uses `node:http`, `Bun.serve`, or `Deno.serve`.
|
|
230
|
+
- `trustForwardedProto`: read the scheme from `X-Forwarded-Proto`. Set it only behind a proxy that overwrites the header. Default `false`. For a build with no `server.ts`, set `TRUST_FORWARDED_PROTO=1`.
|
|
231
|
+
- `shutdownDeadlineMs`: default `10000`.
|
|
232
|
+
|
|
233
|
+
## Limits
|
|
234
|
+
|
|
235
|
+
- The build must serve at `/` (React Router `publicPath`).
|
|
236
|
+
- `serverEntry` does not support React Router `serverBundles`.
|
|
237
|
+
- On Deno, `Deno.serve` logs a notice about its legacy `request.signal` behavior.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { t as listenerUrl } from "./listen-options-DHWmSWGi.js";
|
|
2
|
+
|
|
3
|
+
// src/runtimes/bun.ts
|
|
4
|
+
/** Bun's largest `idleTimeout`, in seconds. */
|
|
5
|
+
const BUN_MAX_IDLE_TIMEOUT_S = 255;
|
|
6
|
+
/** Listens with `Bun.serve`. */
|
|
7
|
+
async function listen(fetch, options) {
|
|
8
|
+
const server = Reflect.get(globalThis, "Bun").serve({
|
|
9
|
+
port: options.port,
|
|
10
|
+
...options.hostname == null ? {} : { hostname: options.hostname },
|
|
11
|
+
idleTimeout: Math.min(BUN_MAX_IDLE_TIMEOUT_S, Math.ceil(options.idleTimeoutMs / 1e3)),
|
|
12
|
+
fetch: (request, bunServer) => fetch(request, { remoteAddress: bunServer.requestIP(request)?.address })
|
|
13
|
+
});
|
|
14
|
+
return {
|
|
15
|
+
url: listenerUrl(options.hostname, server.port),
|
|
16
|
+
stop: async ({ deadlineMs }) => {
|
|
17
|
+
const deadline = setTimeout(() => {
|
|
18
|
+
server.stop(true);
|
|
19
|
+
}, deadlineMs);
|
|
20
|
+
await server.stop();
|
|
21
|
+
clearTimeout(deadline);
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export { listen };
|
|
27
|
+
//# sourceMappingURL=bun-DCGnDEPn.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bun-DCGnDEPn.js","names":[],"sources":["../src/runtimes/bun.ts"],"sourcesContent":["import type { FetchHandler, StartedListener } from \"../types.js\";\nimport { listenerUrl, type ListenOptions } from \"./listen-options.js\";\n\n/** The part of Bun's server that the listener uses. */\ntype BunServer = {\n\tport: number;\n\trequestIP: (request: Request) => { address: string } | null;\n\tstop: (closeActiveConnections?: boolean) => Promise<void>;\n};\n\n/** The part of the `Bun` global that the listener uses. */\ntype BunGlobal = {\n\tserve: (options: {\n\t\tport: number;\n\t\thostname?: string;\n\t\tidleTimeout: number;\n\t\tfetch: (request: Request, server: BunServer) => Response | Promise<Response>;\n\t}) => BunServer;\n};\n\n/** Bun's largest `idleTimeout`, in seconds. */\nconst BUN_MAX_IDLE_TIMEOUT_S = 255;\n\n/** Listens with `Bun.serve`. */\nexport async function listen(\n\tfetch: FetchHandler,\n\toptions: ListenOptions,\n): Promise<StartedListener> {\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- `Bun` is a runtime global with no types in this package.\n\tconst bun = Reflect.get(globalThis, \"Bun\") as BunGlobal;\n\tconst server = bun.serve({\n\t\tport: options.port,\n\t\t...(options.hostname == null ? {} : { hostname: options.hostname }),\n\t\t// Why: Bun's 10 s default also closes a quiet event stream.\n\t\tidleTimeout: Math.min(BUN_MAX_IDLE_TIMEOUT_S, Math.ceil(options.idleTimeoutMs / 1_000)),\n\t\tfetch: (request, bunServer) =>\n\t\t\tfetch(request, { remoteAddress: bunServer.requestIP(request)?.address }),\n\t});\n\treturn {\n\t\turl: listenerUrl(options.hostname, server.port),\n\t\tstop: async ({ deadlineMs }) => {\n\t\t\tconst deadline = setTimeout(() => {\n\t\t\t\tvoid server.stop(true);\n\t\t\t}, deadlineMs);\n\t\t\tawait server.stop();\n\t\t\tclearTimeout(deadline);\n\t\t},\n\t};\n}\n"],"mappings":";;;;AAqBA,MAAM,yBAAyB;;AAG/B,eAAsB,OACrB,OACA,SAC2B;CAG3B,MAAM,SADM,QAAQ,IAAI,YAAY,KACnB,CAAC,CAAC,MAAM;EACxB,MAAM,QAAQ;EACd,GAAI,QAAQ,YAAY,OAAO,CAAC,IAAI,EAAE,UAAU,QAAQ,SAAS;EAEjE,aAAa,KAAK,IAAI,wBAAwB,KAAK,KAAK,QAAQ,gBAAgB,GAAK,CAAC;EACtF,QAAQ,SAAS,cAChB,MAAM,SAAS,EAAE,eAAe,UAAU,UAAU,OAAO,CAAC,EAAE,QAAQ,CAAC;CACzE,CAAC;CACD,OAAO;EACN,KAAK,YAAY,QAAQ,UAAU,OAAO,IAAI;EAC9C,MAAM,OAAO,EAAE,iBAAiB;GAC/B,MAAM,WAAW,iBAAiB;IACjC,AAAK,OAAO,KAAK,IAAI;GACtB,GAAG,UAAU;GACb,MAAM,OAAO,KAAK;GAClB,aAAa,QAAQ;EACtB;CACD;AACD"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
// src/captured-headers.ts
|
|
5
|
+
/**
|
|
6
|
+
* The file under the client build that holds the headers each prerendered
|
|
7
|
+
* response had at build time. It is a dotfile, so the static stages never
|
|
8
|
+
* serve it.
|
|
9
|
+
*/
|
|
10
|
+
const CAPTURED_HEADERS_FILE = ".headers.json";
|
|
11
|
+
/**
|
|
12
|
+
* The key for a URL path in {@link CapturedHeaders}: the path with no
|
|
13
|
+
* trailing slash, so `/a/` and `/a` share headers. The root stays `/`.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* capturedHeadersKey("/components/button/"); // => "/components/button"
|
|
17
|
+
*/
|
|
18
|
+
function capturedHeadersKey(pathname) {
|
|
19
|
+
const trimmed = pathname.replace(/\/+$/, "");
|
|
20
|
+
return trimmed === "" ? "/" : trimmed;
|
|
21
|
+
}
|
|
22
|
+
function isStringRecord(value) {
|
|
23
|
+
return typeof value === "object" && value != null && !Array.isArray(value) && Object.values(value).every((entry) => typeof entry === "string");
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Reads the captured headers of a client build. A build with no file has
|
|
27
|
+
* none. A file in any other shape throws, so a bad build stops startup.
|
|
28
|
+
*/
|
|
29
|
+
async function readCapturedHeaders(clientDirectory) {
|
|
30
|
+
let text;
|
|
31
|
+
try {
|
|
32
|
+
text = await readFile(join(clientDirectory, CAPTURED_HEADERS_FILE), "utf8");
|
|
33
|
+
} catch (error) {
|
|
34
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") return /* @__PURE__ */ new Map();
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
const parsed = JSON.parse(text);
|
|
38
|
+
if (typeof parsed !== "object" || parsed == null || Array.isArray(parsed)) throw new Error(`${CAPTURED_HEADERS_FILE} must hold an object of header objects.`);
|
|
39
|
+
const captured = /* @__PURE__ */ new Map();
|
|
40
|
+
for (const [path, headers] of Object.entries(parsed)) {
|
|
41
|
+
if (!isStringRecord(headers)) throw new Error(`${CAPTURED_HEADERS_FILE}: the headers for ${path} must be strings.`);
|
|
42
|
+
captured.set(path, headers);
|
|
43
|
+
}
|
|
44
|
+
return captured;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export { capturedHeadersKey as n, readCapturedHeaders as r, CAPTURED_HEADERS_FILE as t };
|
|
48
|
+
//# sourceMappingURL=captured-headers-ewL_t3MQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"captured-headers-ewL_t3MQ.js","names":[],"sources":["../src/captured-headers.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\n/**\n * The file under the client build that holds the headers each prerendered\n * response had at build time. It is a dotfile, so the static stages never\n * serve it.\n */\nexport const CAPTURED_HEADERS_FILE = \".headers.json\";\n\n/** The headers of each prerendered URL path. */\nexport type CapturedHeaders = Record<string, Record<string, string>>;\n\n/**\n * The key for a URL path in {@link CapturedHeaders}: the path with no\n * trailing slash, so `/a/` and `/a` share headers. The root stays `/`.\n *\n * @example\n * capturedHeadersKey(\"/components/button/\"); // => \"/components/button\"\n */\nexport function capturedHeadersKey(pathname: string): string {\n\tconst trimmed = pathname.replace(/\\/+$/, \"\");\n\treturn trimmed === \"\" ? \"/\" : trimmed;\n}\n\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t!Array.isArray(value) &&\n\t\tObject.values(value).every((entry) => typeof entry === \"string\")\n\t);\n}\n\n/**\n * Reads the captured headers of a client build. A build with no file has\n * none. A file in any other shape throws, so a bad build stops startup.\n */\nexport async function readCapturedHeaders(\n\tclientDirectory: string,\n): Promise<ReadonlyMap<string, Record<string, string>>> {\n\tlet text: string;\n\ttry {\n\t\ttext = await readFile(join(clientDirectory, CAPTURED_HEADERS_FILE), \"utf8\");\n\t} catch (error) {\n\t\tif (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n\t\t\treturn new Map();\n\t\t}\n\t\tthrow error;\n\t}\n\tconst parsed: unknown = JSON.parse(text);\n\tif (typeof parsed !== \"object\" || parsed == null || Array.isArray(parsed)) {\n\t\tthrow new Error(`${CAPTURED_HEADERS_FILE} must hold an object of header objects.`);\n\t}\n\tconst captured = new Map<string, Record<string, string>>();\n\tfor (const [path, headers] of Object.entries(parsed)) {\n\t\tif (!isStringRecord(headers)) {\n\t\t\tthrow new Error(`${CAPTURED_HEADERS_FILE}: the headers for ${path} must be strings.`);\n\t\t}\n\t\tcaptured.set(path, headers);\n\t}\n\treturn captured;\n}\n"],"mappings":";;;;;;;;;AAQA,MAAa,wBAAwB;;;;;;;;AAYrC,SAAgB,mBAAmB,UAA0B;CAC5D,MAAM,UAAU,SAAS,QAAQ,QAAQ,EAAE;CAC3C,OAAO,YAAY,KAAK,MAAM;AAC/B;AAEA,SAAS,eAAe,OAAiD;CACxE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,CAAC,MAAM,QAAQ,KAAK,KACpB,OAAO,OAAO,KAAK,CAAC,CAAC,OAAO,UAAU,OAAO,UAAU,QAAQ;AAEjE;;;;;AAMA,eAAsB,oBACrB,iBACuD;CACvD,IAAI;CACJ,IAAI;EACH,OAAO,MAAM,SAAS,KAAK,iBAAiB,qBAAqB,GAAG,MAAM;CAC3E,SAAS,OAAO;EACf,IAAI,iBAAiB,SAAS,UAAU,SAAS,MAAM,SAAS,UAC/D,uBAAO,IAAI,IAAI;EAEhB,MAAM;CACP;CACA,MAAM,SAAkB,KAAK,MAAM,IAAI;CACvC,IAAI,OAAO,WAAW,YAAY,UAAU,QAAQ,MAAM,QAAQ,MAAM,GACvE,MAAM,IAAI,MAAM,GAAG,sBAAsB,wCAAwC;CAElF,MAAM,2BAAW,IAAI,IAAoC;CACzD,KAAK,MAAM,CAAC,MAAM,YAAY,OAAO,QAAQ,MAAM,GAAG;EACrD,IAAI,CAAC,eAAe,OAAO,GAC1B,MAAM,IAAI,MAAM,GAAG,sBAAsB,oBAAoB,KAAK,kBAAkB;EAErF,SAAS,IAAI,MAAM,OAAO;CAC3B;CACA,OAAO;AACR"}
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import process from "node:process";
|
|
3
|
+
import { parseArgs } from "node:util";
|
|
4
|
+
|
|
5
|
+
// src/cli.ts
|
|
6
|
+
const USAGE = "Usage: app-server dev | app-server start [build/server/index.js]";
|
|
7
|
+
const { positionals } = parseArgs({
|
|
8
|
+
allowPositionals: true,
|
|
9
|
+
strict: true,
|
|
10
|
+
options: {}
|
|
11
|
+
});
|
|
12
|
+
const [command, buildPath = "build/server/index.js"] = positionals;
|
|
13
|
+
switch (command) {
|
|
14
|
+
case "start": {
|
|
15
|
+
process.env.NODE_ENV ??= "production";
|
|
16
|
+
if (typeof process.setSourceMapsEnabled === "function") process.setSourceMapsEnabled(true);
|
|
17
|
+
const { start } = await import("./start-kxw_NM4q.js");
|
|
18
|
+
await start({ buildPath });
|
|
19
|
+
break;
|
|
20
|
+
}
|
|
21
|
+
case "dev": {
|
|
22
|
+
process.env.NODE_ENV ??= "development";
|
|
23
|
+
const { dev } = await import("./dev-DCytOhpM.js");
|
|
24
|
+
await dev();
|
|
25
|
+
break;
|
|
26
|
+
}
|
|
27
|
+
default:
|
|
28
|
+
process.stderr.write(`${USAGE}\n`);
|
|
29
|
+
process.exitCode = 1;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export { };
|
|
33
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n// The `app-server` command: `app-server dev` or `app-server start [build/server/index.js]`.\nimport process from \"node:process\";\nimport { parseArgs } from \"node:util\";\n\nconst USAGE = \"Usage: app-server dev | app-server start [build/server/index.js]\";\n\nconst { positionals } = parseArgs({ allowPositionals: true, strict: true, options: {} });\nconst [command, buildPath = \"build/server/index.js\"] = positionals;\n\n// Why dynamic imports: React reads `NODE_ENV` when it loads, and a static import runs first.\nswitch (command) {\n\tcase \"start\": {\n\t\tprocess.env.NODE_ENV ??= \"production\";\n\t\tif (typeof process.setSourceMapsEnabled === \"function\") {\n\t\t\tprocess.setSourceMapsEnabled(true);\n\t\t}\n\t\tconst { start } = await import(\"./start.js\");\n\t\tawait start({ buildPath });\n\t\tbreak;\n\t}\n\tcase \"dev\": {\n\t\tprocess.env.NODE_ENV ??= \"development\";\n\t\tconst { dev } = await import(\"./dev.js\");\n\t\tawait dev();\n\t\tbreak;\n\t}\n\tdefault: {\n\t\tprocess.stderr.write(`${USAGE}\\n`);\n\t\tprocess.exitCode = 1;\n\t}\n}\n"],"mappings":";;;;;AAKA,MAAM,QAAQ;AAEd,MAAM,EAAE,gBAAgB,UAAU;CAAE,kBAAkB;CAAM,QAAQ;CAAM,SAAS,CAAC;AAAE,CAAC;AACvF,MAAM,CAAC,SAAS,YAAY,2BAA2B;AAGvD,QAAQ,SAAR;CACC,KAAK,SAAS;EACb,QAAQ,IAAI,aAAa;EACzB,IAAI,OAAO,QAAQ,yBAAyB,YAC3C,QAAQ,qBAAqB,IAAI;EAElC,MAAM,EAAE,UAAU,MAAM,OAAO;EAC/B,MAAM,MAAM,EAAE,UAAU,CAAC;EACzB;CACD;CACA,KAAK,OAAO;EACX,QAAQ,IAAI,aAAa;EACzB,MAAM,EAAE,QAAQ,MAAM,OAAO;EAC7B,MAAM,IAAI;EACV;CACD;CACA;EACC,QAAQ,OAAO,MAAM,GAAG,MAAM,GAAG;EACjC,QAAQ,WAAW;AAErB"}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { t as listenerUrl } from "./listen-options-DHWmSWGi.js";
|
|
2
|
+
|
|
3
|
+
// src/runtimes/deno.ts
|
|
4
|
+
/** Wraps a response body so the listener can end it at the deadline. `open` holds its closer while the body is open. */
|
|
5
|
+
function closableResponse(response, open) {
|
|
6
|
+
if (response.body == null) return response;
|
|
7
|
+
const reader = response.body.getReader();
|
|
8
|
+
let force;
|
|
9
|
+
const body = new ReadableStream({
|
|
10
|
+
start(controller) {
|
|
11
|
+
force = () => {
|
|
12
|
+
open.delete(force);
|
|
13
|
+
controller.error(/* @__PURE__ */ new Error("The shutdown deadline passed."));
|
|
14
|
+
reader.cancel();
|
|
15
|
+
};
|
|
16
|
+
open.add(force);
|
|
17
|
+
},
|
|
18
|
+
async pull(controller) {
|
|
19
|
+
try {
|
|
20
|
+
const { done, value } = await reader.read();
|
|
21
|
+
if (done) {
|
|
22
|
+
open.delete(force);
|
|
23
|
+
controller.close();
|
|
24
|
+
} else controller.enqueue(value);
|
|
25
|
+
} catch (error) {
|
|
26
|
+
open.delete(force);
|
|
27
|
+
throw error;
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
cancel(reason) {
|
|
31
|
+
open.delete(force);
|
|
32
|
+
return reader.cancel(reason);
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
return new Response(body, response);
|
|
36
|
+
}
|
|
37
|
+
/** Listens with `Deno.serve`. */
|
|
38
|
+
async function listen(fetch, options) {
|
|
39
|
+
const deno = Reflect.get(globalThis, "Deno");
|
|
40
|
+
const open = /* @__PURE__ */ new Set();
|
|
41
|
+
const server = deno.serve({
|
|
42
|
+
port: options.port,
|
|
43
|
+
...options.hostname == null ? {} : { hostname: options.hostname },
|
|
44
|
+
onListen: () => {}
|
|
45
|
+
}, async (request, info) => {
|
|
46
|
+
const forced = Promise.withResolvers();
|
|
47
|
+
const force = () => {
|
|
48
|
+
open.delete(force);
|
|
49
|
+
forced.resolve(new Response(null, { status: 503 }));
|
|
50
|
+
};
|
|
51
|
+
open.add(force);
|
|
52
|
+
const answer = (async () => {
|
|
53
|
+
try {
|
|
54
|
+
return closableResponse(await fetch(request, { remoteAddress: info.remoteAddr.hostname }), open);
|
|
55
|
+
} finally {
|
|
56
|
+
open.delete(force);
|
|
57
|
+
}
|
|
58
|
+
})();
|
|
59
|
+
return Promise.race([answer, forced.promise]);
|
|
60
|
+
});
|
|
61
|
+
return {
|
|
62
|
+
url: listenerUrl(options.hostname, server.addr.port),
|
|
63
|
+
stop: async ({ deadlineMs }) => {
|
|
64
|
+
const deadline = setTimeout(() => {
|
|
65
|
+
for (const force of open) force();
|
|
66
|
+
}, deadlineMs);
|
|
67
|
+
await server.shutdown();
|
|
68
|
+
clearTimeout(deadline);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export { listen };
|
|
74
|
+
//# sourceMappingURL=deno-BnMfk2n1.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deno-BnMfk2n1.js","names":[],"sources":["../src/runtimes/deno.ts"],"sourcesContent":["import type { FetchHandler, StartedListener } from \"../types.js\";\nimport { listenerUrl, type ListenOptions } from \"./listen-options.js\";\n\n/** The part of Deno's server that the listener uses. */\ntype DenoServer = {\n\taddr: { port: number };\n\tshutdown: () => Promise<void>;\n};\n\n/** The part of the `Deno` global that the listener uses. */\ntype DenoGlobal = {\n\tserve: (\n\t\toptions: { port: number; hostname?: string; onListen: () => void },\n\t\thandler: (\n\t\t\trequest: Request,\n\t\t\tinfo: { remoteAddr: { hostname: string } },\n\t\t) => Response | Promise<Response>,\n\t) => DenoServer;\n};\n\n/** Wraps a response body so the listener can end it at the deadline. `open` holds its closer while the body is open. */\nfunction closableResponse(response: Response, open: Set<() => void>): Response {\n\tif (response.body == null) {\n\t\treturn response;\n\t}\n\tconst reader = response.body.getReader();\n\tlet force: () => void;\n\tconst body = new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tforce = () => {\n\t\t\t\topen.delete(force);\n\t\t\t\tcontroller.error(new Error(\"The shutdown deadline passed.\"));\n\t\t\t\tvoid reader.cancel();\n\t\t\t};\n\t\t\topen.add(force);\n\t\t},\n\t\tasync pull(controller) {\n\t\t\ttry {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) {\n\t\t\t\t\topen.delete(force);\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} else {\n\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\topen.delete(force);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\tcancel(reason) {\n\t\t\topen.delete(force);\n\t\t\treturn reader.cancel(reason);\n\t\t},\n\t});\n\treturn new Response(body, response);\n}\n\n/** Listens with `Deno.serve`. */\nexport async function listen(\n\tfetch: FetchHandler,\n\toptions: ListenOptions,\n): Promise<StartedListener> {\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- `Deno` is a runtime global with no types in this package.\n\tconst deno = Reflect.get(globalThis, \"Deno\") as DenoGlobal;\n\t// Why: Deno has no forced close, and `shutdown()` waits for each open request. At the\n\t// deadline, the listener answers each pending request with a 503 and ends each open body.\n\tconst open = new Set<() => void>();\n\tconst server = deno.serve(\n\t\t{\n\t\t\tport: options.port,\n\t\t\t...(options.hostname == null ? {} : { hostname: options.hostname }),\n\t\t\t// Why a no-op: the server logs its own startup line.\n\t\t\tonListen: () => {},\n\t\t},\n\t\tasync (request, info) => {\n\t\t\tconst forced = Promise.withResolvers<Response>();\n\t\t\tconst force = () => {\n\t\t\t\topen.delete(force);\n\t\t\t\tforced.resolve(new Response(null, { status: 503 }));\n\t\t\t};\n\t\t\topen.add(force);\n\t\t\tconst answer = (async () => {\n\t\t\t\ttry {\n\t\t\t\t\treturn closableResponse(\n\t\t\t\t\t\tawait fetch(request, { remoteAddress: info.remoteAddr.hostname }),\n\t\t\t\t\t\topen,\n\t\t\t\t\t);\n\t\t\t\t} finally {\n\t\t\t\t\topen.delete(force);\n\t\t\t\t}\n\t\t\t})();\n\t\t\treturn Promise.race([answer, forced.promise]);\n\t\t},\n\t);\n\treturn {\n\t\turl: listenerUrl(options.hostname, server.addr.port),\n\t\tstop: async ({ deadlineMs }) => {\n\t\t\tconst deadline = setTimeout(() => {\n\t\t\t\tfor (const force of open) {\n\t\t\t\t\tforce();\n\t\t\t\t}\n\t\t\t}, deadlineMs);\n\t\t\tawait server.shutdown();\n\t\t\tclearTimeout(deadline);\n\t\t},\n\t};\n}\n"],"mappings":";;;;AAqBA,SAAS,iBAAiB,UAAoB,MAAiC;CAC9E,IAAI,SAAS,QAAQ,MACpB,OAAO;CAER,MAAM,SAAS,SAAS,KAAK,UAAU;CACvC,IAAI;CACJ,MAAM,OAAO,IAAI,eAA2B;EAC3C,MAAM,YAAY;GACjB,cAAc;IACb,KAAK,OAAO,KAAK;IACjB,WAAW,sBAAM,IAAI,MAAM,+BAA+B,CAAC;IAC3D,AAAK,OAAO,OAAO;GACpB;GACA,KAAK,IAAI,KAAK;EACf;EACA,MAAM,KAAK,YAAY;GACtB,IAAI;IACH,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;IAC1C,IAAI,MAAM;KACT,KAAK,OAAO,KAAK;KACjB,WAAW,MAAM;IAClB,OACC,WAAW,QAAQ,KAAK;GAE1B,SAAS,OAAO;IACf,KAAK,OAAO,KAAK;IACjB,MAAM;GACP;EACD;EACA,OAAO,QAAQ;GACd,KAAK,OAAO,KAAK;GACjB,OAAO,OAAO,OAAO,MAAM;EAC5B;CACD,CAAC;CACD,OAAO,IAAI,SAAS,MAAM,QAAQ;AACnC;;AAGA,eAAsB,OACrB,OACA,SAC2B;CAE3B,MAAM,OAAO,QAAQ,IAAI,YAAY,MAAM;CAG3C,MAAM,uBAAO,IAAI,IAAgB;CACjC,MAAM,SAAS,KAAK,MACnB;EACC,MAAM,QAAQ;EACd,GAAI,QAAQ,YAAY,OAAO,CAAC,IAAI,EAAE,UAAU,QAAQ,SAAS;EAEjE,gBAAgB,CAAC;CAClB,GACA,OAAO,SAAS,SAAS;EACxB,MAAM,SAAS,QAAQ,cAAwB;EAC/C,MAAM,cAAc;GACnB,KAAK,OAAO,KAAK;GACjB,OAAO,QAAQ,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC,CAAC;EACnD;EACA,KAAK,IAAI,KAAK;EACd,MAAM,UAAU,YAAY;GAC3B,IAAI;IACH,OAAO,iBACN,MAAM,MAAM,SAAS,EAAE,eAAe,KAAK,WAAW,SAAS,CAAC,GAChE,IACD;GACD,UAAU;IACT,KAAK,OAAO,KAAK;GAClB;EACD,EAAC,CAAE;EACH,OAAO,QAAQ,KAAK,CAAC,QAAQ,OAAO,OAAO,CAAC;CAC7C,CACD;CACA,OAAO;EACN,KAAK,YAAY,QAAQ,UAAU,OAAO,KAAK,IAAI;EACnD,MAAM,OAAO,EAAE,iBAAiB;GAC/B,MAAM,WAAW,iBAAiB;IACjC,KAAK,MAAM,SAAS,MACnB,MAAM;GAER,GAAG,UAAU;GACb,MAAM,OAAO,SAAS;GACtB,aAAa,QAAQ;EACtB;CACD;AACD"}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { a as parsePort, m as jsonSink, n as loadEntry, p as errorAttributes } from "./entry-2XXp2Ukh.js";
|
|
2
|
+
import { t as SERVER_ENTRY_ID } from "./vite-CrNqpoeK.js";
|
|
3
|
+
import { t as listenerUrl } from "./listen-options-DHWmSWGi.js";
|
|
4
|
+
import { t as cancelIfClosed } from "./node-79my3Uix.js";
|
|
5
|
+
import { IncomingMessage, ServerResponse, createServer } from "node:http";
|
|
6
|
+
import { getRequestListener } from "@hono/node-server";
|
|
7
|
+
|
|
8
|
+
// src/served-apps.ts
|
|
9
|
+
/**
|
|
10
|
+
* Tracks the apps that `app-server dev` serves. An edit to `server.ts` makes a
|
|
11
|
+
* new app, and the old app's plugins still hold what their `setup` opened.
|
|
12
|
+
* When the last request that the old app took returns, its `onShutdown` hooks
|
|
13
|
+
* run, and the tracker lets go of it. A route edit makes a new entry with the
|
|
14
|
+
* same app, which keeps its plugins.
|
|
15
|
+
*/
|
|
16
|
+
function servedApps() {
|
|
17
|
+
let current;
|
|
18
|
+
const served = /* @__PURE__ */ new Set();
|
|
19
|
+
const retire = (app) => {
|
|
20
|
+
served.delete(app);
|
|
21
|
+
app.entry.stopPlugins();
|
|
22
|
+
};
|
|
23
|
+
return {
|
|
24
|
+
/** Runs `handle` for a request that `entry` serves. */
|
|
25
|
+
serve: async (entry, handle) => {
|
|
26
|
+
if (current?.entry.app === entry.app) current.entry = entry;
|
|
27
|
+
else {
|
|
28
|
+
if (current != null) {
|
|
29
|
+
current.replaced = true;
|
|
30
|
+
if (current.pending === 0) retire(current);
|
|
31
|
+
}
|
|
32
|
+
current = {
|
|
33
|
+
entry,
|
|
34
|
+
pending: 0,
|
|
35
|
+
replaced: false
|
|
36
|
+
};
|
|
37
|
+
served.add(current);
|
|
38
|
+
}
|
|
39
|
+
const app = current;
|
|
40
|
+
app.pending += 1;
|
|
41
|
+
try {
|
|
42
|
+
return await handle(entry);
|
|
43
|
+
} finally {
|
|
44
|
+
app.pending -= 1;
|
|
45
|
+
if (app.replaced && app.pending === 0) retire(app);
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
/** At exit: aborts `shutdownSignal()` and runs the `onShutdown` hooks of each app still held. */
|
|
49
|
+
stopAll: () => {
|
|
50
|
+
for (const app of served) {
|
|
51
|
+
app.entry.abortShutdownSignal();
|
|
52
|
+
retire(app);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// src/dev.ts
|
|
59
|
+
/**
|
|
60
|
+
* Runs the app in development: the same pipeline as production, with Vite in
|
|
61
|
+
* middleware mode inside it. Each request loads the server entry through
|
|
62
|
+
* Vite's SSR runner, so an edit to a route or to the app's `server.ts` applies
|
|
63
|
+
* at once. HMR shares the port.
|
|
64
|
+
*
|
|
65
|
+
* The port is `PORT`, else Vite's `server.port`. The host is `HOST`, else
|
|
66
|
+
* Vite's `server.host`.
|
|
67
|
+
*/
|
|
68
|
+
async function dev() {
|
|
69
|
+
const vite = await import("vite");
|
|
70
|
+
const httpServer = createServer();
|
|
71
|
+
const viteServer = await vite.createServer({
|
|
72
|
+
server: {
|
|
73
|
+
middlewareMode: true,
|
|
74
|
+
ws: { server: httpServer }
|
|
75
|
+
},
|
|
76
|
+
appType: "custom"
|
|
77
|
+
});
|
|
78
|
+
const ssrRunner = () => {
|
|
79
|
+
const ssr = viteServer.environments.ssr;
|
|
80
|
+
if (ssr == null || !vite.isRunnableDevEnvironment(ssr)) throw new Error("Vite's SSR environment cannot run modules.");
|
|
81
|
+
return ssr.runner;
|
|
82
|
+
};
|
|
83
|
+
ssrRunner();
|
|
84
|
+
const entryId = viteServer.config.plugins.some((plugin) => plugin.name === "@ngrok/app-server") ? SERVER_ENTRY_ID : "virtual:react-router/server-build";
|
|
85
|
+
const sink = jsonSink();
|
|
86
|
+
const apps = servedApps();
|
|
87
|
+
const listener = getRequestListener(async (request, { incoming, outgoing }) => {
|
|
88
|
+
try {
|
|
89
|
+
const response = await apps.serve(await loadEntry(await ssrRunner().import(entryId)), (entry) => entry.fetchDev(request, {
|
|
90
|
+
remoteAddress: incoming.socket.remoteAddress,
|
|
91
|
+
...incoming instanceof IncomingMessage && outgoing instanceof ServerResponse ? {
|
|
92
|
+
incoming,
|
|
93
|
+
outgoing
|
|
94
|
+
} : {}
|
|
95
|
+
}, viteServer.middlewares));
|
|
96
|
+
return await cancelIfClosed(response, outgoing);
|
|
97
|
+
} catch (error) {
|
|
98
|
+
if (error instanceof Error) viteServer.ssrFixStacktrace(error);
|
|
99
|
+
sink.log("error", "dev request failed", errorAttributes(error));
|
|
100
|
+
return new Response(error instanceof Error ? error.stack ?? error.message : String(error), {
|
|
101
|
+
status: 500,
|
|
102
|
+
headers: { "Content-Type": "text/plain; charset=utf-8" }
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
httpServer.on("request", (request, response) => {
|
|
107
|
+
listener(request, response);
|
|
108
|
+
});
|
|
109
|
+
const port = process.env.PORT == null ? viteServer.config.server.port : parsePort(process.env.PORT);
|
|
110
|
+
const configuredHost = viteServer.config.server.host;
|
|
111
|
+
const hostname = process.env.HOST || (configuredHost === true ? void 0 : configuredHost || "localhost");
|
|
112
|
+
await new Promise((resolve, reject) => {
|
|
113
|
+
httpServer.once("error", reject);
|
|
114
|
+
httpServer.listen(port, hostname, () => {
|
|
115
|
+
httpServer.off("error", reject);
|
|
116
|
+
resolve();
|
|
117
|
+
});
|
|
118
|
+
});
|
|
119
|
+
sink.log("info", "listening", { "app_server.urls": [listenerUrl(hostname, port)] });
|
|
120
|
+
for (const signal of ["SIGTERM", "SIGINT"]) process.once(signal, () => {
|
|
121
|
+
apps.stopAll();
|
|
122
|
+
httpServer.closeAllConnections();
|
|
123
|
+
httpServer.close();
|
|
124
|
+
viteServer.close().catch((error) => {
|
|
125
|
+
sink.log("error", "Vite close failed", errorAttributes(error));
|
|
126
|
+
process.exitCode = 1;
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export { dev };
|
|
132
|
+
//# sourceMappingURL=dev-DCytOhpM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dev-DCytOhpM.js","names":["createHttpServer"],"sources":["../src/served-apps.ts","../src/dev.ts"],"sourcesContent":["import type { AppServerEntry } from \"./entry.js\";\n\ntype ServedApp = { entry: AppServerEntry; pending: number; replaced: boolean };\n\n/**\n * Tracks the apps that `app-server dev` serves. An edit to `server.ts` makes a\n * new app, and the old app's plugins still hold what their `setup` opened.\n * When the last request that the old app took returns, its `onShutdown` hooks\n * run, and the tracker lets go of it. A route edit makes a new entry with the\n * same app, which keeps its plugins.\n */\nexport function servedApps() {\n\tlet current: ServedApp | undefined;\n\tconst served = new Set<ServedApp>();\n\tconst retire = (app: ServedApp) => {\n\t\tserved.delete(app);\n\t\tvoid app.entry.stopPlugins();\n\t};\n\treturn {\n\t\t/** Runs `handle` for a request that `entry` serves. */\n\t\tserve: async <Result>(\n\t\t\tentry: AppServerEntry,\n\t\t\thandle: (entry: AppServerEntry) => Promise<Result>,\n\t\t): Promise<Result> => {\n\t\t\tif (current?.entry.app === entry.app) {\n\t\t\t\tcurrent.entry = entry;\n\t\t\t} else {\n\t\t\t\tif (current != null) {\n\t\t\t\t\tcurrent.replaced = true;\n\t\t\t\t\tif (current.pending === 0) {\n\t\t\t\t\t\tretire(current);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent = { entry, pending: 0, replaced: false };\n\t\t\t\tserved.add(current);\n\t\t\t}\n\t\t\tconst app = current;\n\t\t\tapp.pending += 1;\n\t\t\ttry {\n\t\t\t\treturn await handle(entry);\n\t\t\t} finally {\n\t\t\t\tapp.pending -= 1;\n\t\t\t\tif (app.replaced && app.pending === 0) {\n\t\t\t\t\tretire(app);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t/** At exit: aborts `shutdownSignal()` and runs the `onShutdown` hooks of each app still held. */\n\t\tstopAll: () => {\n\t\t\tfor (const app of served) {\n\t\t\t\tapp.entry.abortShutdownSignal();\n\t\t\t\tretire(app);\n\t\t\t}\n\t\t},\n\t};\n}\n","import { createServer as createHttpServer, IncomingMessage, ServerResponse } from \"node:http\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport { loadEntry } from \"./entry.js\";\nimport { errorAttributes, jsonSink } from \"./log.js\";\nimport { listenerUrl } from \"./runtimes/listen-options.js\";\nimport { cancelIfClosed } from \"./runtimes/node.js\";\nimport { servedApps } from \"./served-apps.js\";\nimport { parsePort } from \"./tcp.js\";\nimport { SERVER_ENTRY_ID } from \"./vite.js\";\n\n/**\n * Runs the app in development: the same pipeline as production, with Vite in\n * middleware mode inside it. Each request loads the server entry through\n * Vite's SSR runner, so an edit to a route or to the app's `server.ts` applies\n * at once. HMR shares the port.\n *\n * The port is `PORT`, else Vite's `server.port`. The host is `HOST`, else\n * Vite's `server.host`.\n */\nexport async function dev(): Promise<void> {\n\tconst vite = await import(\"vite\");\n\tconst httpServer = createHttpServer();\n\tconst viteServer = await vite.createServer({\n\t\tserver: { middlewareMode: true, ws: { server: httpServer } },\n\t\tappType: \"custom\",\n\t});\n\t// Why read it for each request: a Vite restart, such as after a config edit, replaces the environments.\n\tconst ssrRunner = () => {\n\t\tconst ssr = viteServer.environments.ssr;\n\t\tif (ssr == null || !vite.isRunnableDevEnvironment(ssr)) {\n\t\t\tthrow new Error(\"Vite's SSR environment cannot run modules.\");\n\t\t}\n\t\treturn ssr.runner;\n\t};\n\tssrRunner();\n\tconst entryId = viteServer.config.plugins.some((plugin) => plugin.name === \"@ngrok/app-server\")\n\t\t? SERVER_ENTRY_ID\n\t\t: \"virtual:react-router/server-build\";\n\tconst sink = jsonSink();\n\tconst apps = servedApps();\n\n\tconst listener = getRequestListener(async (request, { incoming, outgoing }) => {\n\t\ttry {\n\t\t\tconst response = await apps.serve(\n\t\t\t\tawait loadEntry(await ssrRunner().import(entryId)),\n\t\t\t\t(entry) =>\n\t\t\t\t\tentry.fetchDev(\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tremoteAddress: incoming.socket.remoteAddress,\n\t\t\t\t\t\t\t// Why the check: the listener is plain `node:http`, so these are always HTTP/1 objects.\n\t\t\t\t\t\t\t...(incoming instanceof IncomingMessage && outgoing instanceof ServerResponse\n\t\t\t\t\t\t\t\t? { incoming, outgoing }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tviteServer.middlewares,\n\t\t\t\t\t),\n\t\t\t);\n\t\t\treturn await cancelIfClosed(response, outgoing);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tviteServer.ssrFixStacktrace(error);\n\t\t\t}\n\t\t\tsink.log(\"error\", \"dev request failed\", errorAttributes(error));\n\t\t\treturn new Response(error instanceof Error ? (error.stack ?? error.message) : String(error), {\n\t\t\t\tstatus: 500,\n\t\t\t\theaders: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n\t\t\t});\n\t\t}\n\t});\n\thttpServer.on(\"request\", (request, response) => {\n\t\tvoid listener(request, response);\n\t});\n\n\tconst port =\n\t\tprocess.env.PORT == null ? viteServer.config.server.port : parsePort(process.env.PORT);\n\tconst configuredHost = viteServer.config.server.host;\n\tconst hostname =\n\t\tprocess.env.HOST || (configuredHost === true ? undefined : configuredHost || \"localhost\");\n\tawait new Promise<void>((resolve, reject) => {\n\t\thttpServer.once(\"error\", reject);\n\t\thttpServer.listen(port, hostname, () => {\n\t\t\thttpServer.off(\"error\", reject);\n\t\t\tresolve();\n\t\t});\n\t});\n\tsink.log(\"info\", \"listening\", { \"app_server.urls\": [listenerUrl(hostname, port)] });\n\n\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\tprocess.once(signal, () => {\n\t\t\tapps.stopAll();\n\t\t\thttpServer.closeAllConnections();\n\t\t\thttpServer.close();\n\t\t\tviteServer.close().catch((error: unknown) => {\n\t\t\t\tsink.log(\"error\", \"Vite close failed\", errorAttributes(error));\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t});\n\t\t});\n\t}\n}\n"],"mappings":"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"}
|