@ngrok/app-server 0.3.6 → 0.4.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/README.md +40 -9
- package/dist/cli.js +3 -3
- package/dist/client.js +1 -1
- package/dist/{create-server-C_90R50y.js → create-server-C63luLkn.js} +71 -30
- package/dist/create-server-C63luLkn.js.map +1 -0
- package/dist/{create-server-kxyhCdhv.d.ts → create-server-DKJ0wASH.d.ts} +33 -13
- package/dist/{entry-65IESBSA.js → entry-BSbsQ_kq.js} +13 -5
- package/dist/entry-BSbsQ_kq.js.map +1 -0
- package/dist/{entry-CNL4OsEn.d.ts → entry-C9bBcYeP.d.ts} +3 -3
- package/dist/index.d.ts +18 -5
- package/dist/index.js +6 -6
- package/dist/{load-entry-BftQ3qlz.js → load-entry-DgZyPtoD.js} +4 -4
- package/dist/{load-entry-BftQ3qlz.js.map → load-entry-DgZyPtoD.js.map} +1 -1
- package/dist/log-CW_g1pWk.js +304 -0
- package/dist/log-CW_g1pWk.js.map +1 -0
- package/dist/{node-Fo6EodEV.js → node-DBwgrye_.js} +2 -2
- package/dist/{node-Fo6EodEV.js.map → node-DBwgrye_.js.map} +1 -1
- package/dist/{node-CA7t-s6D.js → node-DiMwdTOC.js} +3 -3
- package/dist/{node-CA7t-s6D.js.map → node-DiMwdTOC.js.map} +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +2 -2
- package/dist/react-router.d.ts +2 -2
- package/dist/react-router.js +3 -4
- package/dist/react-router.js.map +1 -1
- package/dist/request-context-BdAH1D-2.js +80 -0
- package/dist/request-context-BdAH1D-2.js.map +1 -0
- package/dist/{response-edge-D3CAjukJ.js → response-edge-7eUl2ewl.js} +3 -3
- package/dist/response-edge-7eUl2ewl.js.map +1 -0
- package/dist/{response-writer-BUyOW4n2.js → response-writer-CLtCseu5.js} +2 -2
- package/dist/{response-writer-BUyOW4n2.js.map → response-writer-CLtCseu5.js.map} +1 -1
- package/dist/{serve-CEecObwD.js → serve-DCaIBTM-.js} +2 -2
- package/dist/{serve-CEecObwD.js.map → serve-DCaIBTM-.js.map} +1 -1
- package/dist/{start-CDnHKNca.js → start-D2IVWkow.js} +29 -13
- package/dist/start-D2IVWkow.js.map +1 -0
- package/dist/tanstack-start.d.ts +2 -2
- package/dist/tanstack-start.js +1 -1
- package/dist/{tcp-BPeUZaNg.js → tcp-B8aFGQRB.js} +2 -2
- package/dist/{tcp-BPeUZaNg.js.map → tcp-B8aFGQRB.js.map} +1 -1
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +4 -4
- package/dist/{trailing-slash-DeOUxMYo.d.ts → trailing-slash-D_52DJaQ.d.ts} +2 -2
- package/dist/{types-BKJxtIuj.d.ts → types-C_I3i62n.d.ts} +32 -4
- package/dist/vercel.d.ts +2 -2
- package/dist/vercel.js +4 -4
- package/package.json +1 -1
- package/dist/create-server-C_90R50y.js.map +0 -1
- package/dist/entry-65IESBSA.js.map +0 -1
- package/dist/log-C8LGQ23s.js +0 -149
- package/dist/log-C8LGQ23s.js.map +0 -1
- package/dist/request-context-BtQ87VYb.js +0 -40
- package/dist/request-context-BtQ87VYb.js.map +0 -1
- package/dist/response-edge-D3CAjukJ.js.map +0 -1
- package/dist/start-CDnHKNca.js.map +0 -1
package/README.md
CHANGED
|
@@ -403,7 +403,7 @@ In development, `app-server start` sends the same policy. A rendered page gets a
|
|
|
403
403
|
createServer({
|
|
404
404
|
plugins: defaultPlugins({
|
|
405
405
|
contentSecurityPolicy: {
|
|
406
|
-
policy: (scriptSrc) => `script-src ${scriptSrc}; object-src 'none'; base-uri 'none'`,
|
|
406
|
+
policy: ({ scriptSrc }) => `script-src ${scriptSrc}; object-src 'none'; base-uri 'none'`,
|
|
407
407
|
},
|
|
408
408
|
}),
|
|
409
409
|
});
|
|
@@ -682,7 +682,9 @@ The default twin is the path with no trailing slash plus `.md`, and `/index.md`
|
|
|
682
682
|
A different mapping goes in `twinOf`. Its path follows the same rules as a request path, and it can give a twin to a request that `rewrite` changes:
|
|
683
683
|
|
|
684
684
|
```ts
|
|
685
|
-
prerendered({
|
|
685
|
+
prerendered({
|
|
686
|
+
markdownTwins: { twinOf: ({ path }) => (path === "/" ? "/llms.md" : `${path}.md`) },
|
|
687
|
+
});
|
|
686
688
|
```
|
|
687
689
|
|
|
688
690
|
`twinOf` also gets the request's Hono context, the same as `rewrite`. If it gives `undefined`, the request gets no twin, and the answer gets no `Vary: Accept` and no `Link`.
|
|
@@ -753,20 +755,48 @@ Pass a sink to use your own format. Attribute names are flat and dotted:
|
|
|
753
755
|
```ts
|
|
754
756
|
createServer({
|
|
755
757
|
logger: {
|
|
756
|
-
log: (level, message, attributes) => mySlogger[level](message, attributes),
|
|
758
|
+
log: ({ level, message, attributes }) => mySlogger[level](message, attributes),
|
|
757
759
|
},
|
|
758
760
|
});
|
|
759
761
|
```
|
|
760
762
|
|
|
761
|
-
The default is `jsonSink()`: one JSON object per line on standard output (stdout). It writes the lines of one event-loop turn in one write, at the end of the turn. Each line still reaches stdout before the process exits, and before the vercel handler returns.
|
|
763
|
+
The default is `jsonSink()`: one JSON object per line on standard output (stdout). It writes the lines of one event-loop turn in one write, at the end of the turn. Each line still reaches stdout before the process exits, and before the vercel handler returns. `jsonSink()` writes a bigint as a string, such as `"1n"`, and a cycle as `"[Circular]"`. A line whose attributes have no JSON, such as a value whose `toJSON` throws, goes out with `log.error` in place of its attributes, so `jsonSink()` never throws for its attributes. Like `JSON.stringify`, it writes a `Map` or a `Set` as `{}`, so convert it first, such as with `Object.fromEntries(map)`.
|
|
764
|
+
|
|
765
|
+
In server code, `logger()` gives the logger of the request that runs. Its lines carry the request ID, method, and path, and these fields win over a field of the same name that you give. Outside a request, such as at module load or in a prerender pass, `logger()` writes to the sink and hooks of the last `createServer` call, else to `jsonSink()`:
|
|
766
|
+
|
|
767
|
+
```ts
|
|
768
|
+
import { logger } from "@ngrok/app-server";
|
|
769
|
+
|
|
770
|
+
export async function loader() {
|
|
771
|
+
logger().info("loading", { "usr.id": userId });
|
|
772
|
+
}
|
|
773
|
+
```
|
|
774
|
+
|
|
775
|
+
An attribute whose value is an `Error` becomes dotted fields under its name: `kind`, `message`, `stack`, each own field, such as `code`, and the `cause` chain as `<name>.cause.*`. An `AggregateError` adds its members as `<name>.errors`. An error with `toJSON` gives its own fields from it. The server's own error lines, such as `unhandled error`, use the same fields:
|
|
776
|
+
|
|
777
|
+
```ts
|
|
778
|
+
logger().error("payment failed", { error });
|
|
779
|
+
// {"message":"payment failed","error.kind":"TypeError","error.message":"…","error.stack":"…","error.cause.kind":"Error","error.cause.code":"ECONNRESET",…}
|
|
780
|
+
```
|
|
781
|
+
|
|
782
|
+
The `log` option changes each line of the server and of `logger()` before it goes to the sink. `attributes` gets the attributes after the server flattens each error. `error` gets each error, its attribute name, and its default fields, and gives the fields to write:
|
|
783
|
+
|
|
784
|
+
```ts
|
|
785
|
+
createServer({
|
|
786
|
+
log: {
|
|
787
|
+
attributes: ({ attributes }) => ({ ...attributes, "usr.email": undefined }),
|
|
788
|
+
error: ({ prefix, fields }) => ({ ...fields, [`${prefix}.stack`]: undefined }),
|
|
789
|
+
},
|
|
790
|
+
});
|
|
791
|
+
```
|
|
762
792
|
|
|
763
|
-
|
|
793
|
+
`requestContext()` gives the request ID, the logger, the CSP nonce, and the client address of the request that runs. It works with each framework. It gives `undefined` outside a server request:
|
|
764
794
|
|
|
765
795
|
```ts
|
|
766
796
|
import { requestContext } from "@ngrok/app-server";
|
|
767
797
|
|
|
768
798
|
export async function loader() {
|
|
769
|
-
requestContext()?.
|
|
799
|
+
const requestId = requestContext()?.requestId;
|
|
770
800
|
}
|
|
771
801
|
```
|
|
772
802
|
|
|
@@ -782,14 +812,14 @@ export async function loader({ context }: Route.LoaderArgs) {
|
|
|
782
812
|
|
|
783
813
|
A request with a valid W3C `traceparent` header logs `trace_id` and `span_id` on each line. `requestId({ datadogTraceIds: true })` also logs `dd.trace_id` and `dd.span_id`, the lower 64 bits in decimal, so Datadog connects each line to its trace.
|
|
784
814
|
|
|
785
|
-
`accessLog({ attributes })` adds the app's own attributes to each request line. The callback runs when the line goes out. It gets the context and what went out
|
|
815
|
+
`accessLog({ attributes })` adds the app's own attributes to each request line. The callback runs when the line goes out. It gets `{ context, sent }`: the request's context, and what went out as `status`, `headers`, `bytes`, and `aborted`. Read a response header from `sent.headers`, not from `context.res`: `sent.headers` has the headers that went out on each runtime, after the header hooks, and `context.res` can lack them. On Node.js and Vercel, `sent.headers` also has the headers that the listener adds, such as `Content-Length`. `accessLog({ serverTiming: true })` sets `Server-Timing: app;dur=<ms>` on each HTML document: the time until the response headers were ready.
|
|
786
816
|
|
|
787
817
|
```ts
|
|
788
818
|
defaultPlugins({
|
|
789
819
|
requestId: { datadogTraceIds: true },
|
|
790
820
|
accessLog: {
|
|
791
|
-
attributes: (
|
|
792
|
-
"usr.id":
|
|
821
|
+
attributes: ({ context, sent }) => ({
|
|
822
|
+
"usr.id": context.get("userId"),
|
|
793
823
|
"http.response.cache_control": sent.headers.get("Cache-Control"),
|
|
794
824
|
}),
|
|
795
825
|
},
|
|
@@ -907,6 +937,7 @@ A framework adapter or a host adapter is two small objects. A third-party adapte
|
|
|
907
937
|
|
|
908
938
|
- `plugins`: default `defaultPlugins()`.
|
|
909
939
|
- `logger`: default `jsonSink()`.
|
|
940
|
+
- `log`: hooks that change each log line: `attributes` and `error`. See [Logs](#logs).
|
|
910
941
|
- `listeners`: default the host's listeners. A listener decides how connections arrive. On the node host, the default is `[tcp()]` from `@ngrok/app-server/node`. `tcp()` uses `node:http`, `Bun.serve`, or `Deno.serve`.
|
|
911
942
|
- `trustForwardedProto`: read the scheme from `X-Forwarded-Proto`. Set it only behind a proxy that overwrites the header. Default `false`. The server passes it to each listener as `start(fetch, { trustForwardedProto })`, so the node listener on Node.js builds each request with that scheme and copies none. For a listener that ignores it, the server copies each request to change its scheme. For a build with no `server.ts`, set `TRUST_FORWARDED_PROTO=1`. TanStack Start compares a server function call's `Origin` with the request URL when the browser sends no `Sec-Fetch-Site`, so set this option behind a proxy that ends TLS.
|
|
912
943
|
- `trustedProxyHops`: how many proxies in front of the server add to `X-Forwarded-For`, such as `1` behind the ngrok edge. With N, the client address is the Nth address from the right of that header. The access log and `requestContext()?.clientAddress` use it. Default `0`, the address of the socket. Set it only to the number of proxies that you run, else a client can spoof its address. For a build with no `server.ts`, set `TRUSTED_PROXY_HOPS`.
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { t as parsePort } from "./tcp-
|
|
2
|
+
import { t as parsePort } from "./tcp-B8aFGQRB.js";
|
|
3
3
|
import process from "node:process";
|
|
4
4
|
import { parseArgs } from "node:util";
|
|
5
5
|
|
|
@@ -42,12 +42,12 @@ try {
|
|
|
42
42
|
if (args?.help === true) process.stdout.write(`${USAGE}\n`);
|
|
43
43
|
else if (args?.command === "start") {
|
|
44
44
|
process.env.NODE_ENV ??= "development";
|
|
45
|
-
const { start } = await import("./start-
|
|
45
|
+
const { start } = await import("./start-D2IVWkow.js");
|
|
46
46
|
await start();
|
|
47
47
|
} else if (args?.command === "serve") {
|
|
48
48
|
process.env.NODE_ENV ??= "production";
|
|
49
49
|
if (typeof process.setSourceMapsEnabled === "function") process.setSourceMapsEnabled(true);
|
|
50
|
-
const { serve } = await import("./serve-
|
|
50
|
+
const { serve } = await import("./serve-DCaIBTM-.js");
|
|
51
51
|
await serve({ buildPath: args.buildPath });
|
|
52
52
|
} else if (args != null) fail(args.command == null ? "Give a command." : `Unknown command: ${args.command}.`);
|
|
53
53
|
|
package/dist/client.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { r as requestContext } from "./request-context-BdAH1D-2.js";
|
|
2
2
|
import { n as staleBuildTanStack, r as documentNonce, t as staleBuildReactRouter } from "./stale-build-navigation-rg5xxmTr.js";
|
|
3
3
|
|
|
4
4
|
// src/client/csp-nonce.ts
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { r as
|
|
1
|
+
import { a as requestLogger, i as jsonSink, r as hookSink, t as asError } from "./log-CW_g1pWk.js";
|
|
2
|
+
import { a as setProcessSink, o as withRequestContext } from "./request-context-BdAH1D-2.js";
|
|
2
3
|
import { a as replaceResponse, o as withHeaderHook, r as hookedHeaders, s as writableHeaders } from "./header-hook-Vzw9J9BY.js";
|
|
3
4
|
import { c as presenceHeaders, l as presenceHeadersOf, o as checkOptionPlugins, r as buildId, s as optionPlugin } from "./build-id-B0448vZH.js";
|
|
4
|
-
import {
|
|
5
|
-
import { n as finishResponse, r as onResponseSent } from "./response-edge-D3CAjukJ.js";
|
|
5
|
+
import { n as finishResponse, r as onResponseSent } from "./response-edge-7eUl2ewl.js";
|
|
6
6
|
import { r as manifestKey } from "./build-manifest-DBMWe3Lx.js";
|
|
7
7
|
import { a as isCompressible, i as forbidsTransform, n as MIN_COMPRESS_BYTES, o as preferredEncoding, s as readIfQueued } from "./compression-CT2mWlKM.js";
|
|
8
8
|
import { i as isFilePath$1, n as findStaticFile, o as staticResponse, s as withVary, t as contentType } from "./static-files-C2ea8KQ6.js";
|
|
@@ -323,7 +323,10 @@ function linkToTwin(context, twinPath) {
|
|
|
323
323
|
function developmentTwins(twinOf, { rewrite, skip }, prerenderedPaths) {
|
|
324
324
|
return async (context, next) => {
|
|
325
325
|
const { method, path } = context.req;
|
|
326
|
-
const twinPath = (method === "GET" || method === "HEAD") && skip?.(path) !== true && prefersMarkdown(context.req.raw) ? twinOf(path, rewrite?.(
|
|
326
|
+
const twinPath = (method === "GET" || method === "HEAD") && skip?.(path) !== true && prefersMarkdown(context.req.raw) ? twinOf(path, rewrite?.({
|
|
327
|
+
path,
|
|
328
|
+
context
|
|
329
|
+
}) ?? path, context) : void 0;
|
|
327
330
|
if (twinPath == null || prerenderedPaths != null && !prerenderedPaths.has(twinPath) || !isFilePath$1(twinPath)) return next();
|
|
328
331
|
const url = new URL(context.req.url);
|
|
329
332
|
url.pathname = urlPath(twinPath);
|
|
@@ -349,7 +352,10 @@ function twinOfOption(markdownTwins) {
|
|
|
349
352
|
if (markdownTwins === true) return defaultTwinOf;
|
|
350
353
|
if (markdownTwins == null || markdownTwins === false) return;
|
|
351
354
|
const { twinOf } = markdownTwins;
|
|
352
|
-
return (path, _rewritten, context) => twinOf(
|
|
355
|
+
return (path, _rewritten, context) => twinOf({
|
|
356
|
+
path,
|
|
357
|
+
context
|
|
358
|
+
});
|
|
353
359
|
}
|
|
354
360
|
/**
|
|
355
361
|
* Serves the client build: prerendered pages at their own URL with a 200,
|
|
@@ -365,7 +371,7 @@ function twinOfOption(markdownTwins) {
|
|
|
365
371
|
*
|
|
366
372
|
* @example
|
|
367
373
|
* prerendered({
|
|
368
|
-
* headers: (path) => (path.startsWith("/api/") ? { "Access-Control-Allow-Origin": "*" } : undefined),
|
|
374
|
+
* headers: ({ path }) => (path.startsWith("/api/") ? { "Access-Control-Allow-Origin": "*" } : undefined),
|
|
369
375
|
* });
|
|
370
376
|
*/
|
|
371
377
|
function prerendered(options = {}) {
|
|
@@ -382,7 +388,11 @@ function prerendered(options = {}) {
|
|
|
382
388
|
const { files, contentTypes, capturedHeaders } = info;
|
|
383
389
|
const missing = [];
|
|
384
390
|
for (const path of info.prerenderedPaths) if (await findStaticFile(files, path) == null) missing.push(path);
|
|
385
|
-
if (missing.length > 0) info.logger.log(
|
|
391
|
+
if (missing.length > 0) info.logger.log({
|
|
392
|
+
level: "warn",
|
|
393
|
+
message: "prerendered paths with no file",
|
|
394
|
+
attributes: { "app_server.missing_paths": missing }
|
|
395
|
+
});
|
|
386
396
|
const cacheControl = options.cacheControl ?? ((path) => {
|
|
387
397
|
const type = contentType(path, contentTypes);
|
|
388
398
|
return type.startsWith("text/html") || type.startsWith("text/markdown") || info.isDataRequest(path) ? REVALIDATE : ONE_HOUR;
|
|
@@ -391,7 +401,10 @@ function prerendered(options = {}) {
|
|
|
391
401
|
context.env.onServedFile?.(file.path);
|
|
392
402
|
const value = cacheControl(file.path);
|
|
393
403
|
const headers = new Headers(value == null ? void 0 : { "Cache-Control": value });
|
|
394
|
-
for (const layer of [capturedHeaders.get(manifestKey(path)), options.headers?.(
|
|
404
|
+
for (const layer of [capturedHeaders.get(manifestKey(path)), options.headers?.({
|
|
405
|
+
path,
|
|
406
|
+
context
|
|
407
|
+
})]) for (const [name, layerValue] of Object.entries(layer ?? {})) headers.set(name, layerValue);
|
|
395
408
|
return staticResponse(context, {
|
|
396
409
|
files,
|
|
397
410
|
file,
|
|
@@ -402,7 +415,10 @@ function prerendered(options = {}) {
|
|
|
402
415
|
stage = async (context, next) => {
|
|
403
416
|
const { method } = context.req;
|
|
404
417
|
if (method !== "GET" && method !== "HEAD" || options.skip?.(context.req.path) === true) return next();
|
|
405
|
-
const rewritten = options.rewrite?.(
|
|
418
|
+
const rewritten = options.rewrite?.({
|
|
419
|
+
path: context.req.path,
|
|
420
|
+
context
|
|
421
|
+
}) ?? context.req.path;
|
|
406
422
|
const twin = await findTwin(files, context, {
|
|
407
423
|
twinOf,
|
|
408
424
|
rewritten
|
|
@@ -470,13 +486,16 @@ function accessLog({ redactQuery = true, attributes, serverTiming = false } = {}
|
|
|
470
486
|
try {
|
|
471
487
|
context.get("logger")[sent.status >= 500 ? "error" : "info"]("request", attributes == null ? line : {
|
|
472
488
|
...line,
|
|
473
|
-
...attributes(
|
|
489
|
+
...attributes({
|
|
490
|
+
context,
|
|
491
|
+
sent
|
|
492
|
+
})
|
|
474
493
|
});
|
|
475
494
|
} catch (error) {
|
|
476
495
|
try {
|
|
477
496
|
context.get("logger").error("access log attributes failed", {
|
|
478
497
|
...line,
|
|
479
|
-
|
|
498
|
+
error: asError(error)
|
|
480
499
|
});
|
|
481
500
|
} catch {}
|
|
482
501
|
}
|
|
@@ -651,7 +670,7 @@ function health({ livePath = "/livez", readyPath = "/readyz", ready } = {}) {
|
|
|
651
670
|
try {
|
|
652
671
|
passed = await ready();
|
|
653
672
|
} catch (error) {
|
|
654
|
-
failure =
|
|
673
|
+
failure = { error: asError(error) };
|
|
655
674
|
}
|
|
656
675
|
if (!passed && !appFailing) logger.warn("readiness check failed", failure);
|
|
657
676
|
else if (passed && appFailing) logger.info("readiness check passed");
|
|
@@ -957,7 +976,7 @@ function randomNonce() {
|
|
|
957
976
|
* @example
|
|
958
977
|
* defaultPlugins({
|
|
959
978
|
* contentSecurityPolicy: {
|
|
960
|
-
* policy: (scriptSrc) => `script-src ${scriptSrc}; object-src 'none'; base-uri 'none'`,
|
|
979
|
+
* policy: ({ scriptSrc }) => `script-src ${scriptSrc}; object-src 'none'; base-uri 'none'`,
|
|
961
980
|
* },
|
|
962
981
|
* });
|
|
963
982
|
*/
|
|
@@ -976,7 +995,10 @@ function contentSecurityPolicy({ policy }) {
|
|
|
976
995
|
const hashes = context.get("documentScriptHashes") ?? (file == null ? void 0 : scriptHashes.get(file) ?? []);
|
|
977
996
|
if (headers.has("Content-Security-Policy") || hashes == null && !(headers.get("Content-Type")?.startsWith("text/html") ?? false)) return;
|
|
978
997
|
const scriptSrc = hashes == null ? `'nonce-${nonce}' 'strict-dynamic'` : ["'self'", ...hashes.map((hash) => `'sha256-${hash}'`)].join(" ");
|
|
979
|
-
headers.set("Content-Security-Policy", oneLine(policy(
|
|
998
|
+
headers.set("Content-Security-Policy", oneLine(policy({
|
|
999
|
+
scriptSrc,
|
|
1000
|
+
context
|
|
1001
|
+
})));
|
|
980
1002
|
});
|
|
981
1003
|
}
|
|
982
1004
|
});
|
|
@@ -1237,7 +1259,7 @@ function answerError(error, context) {
|
|
|
1237
1259
|
const response = error.getResponse();
|
|
1238
1260
|
if (response instanceof Response) return response;
|
|
1239
1261
|
}
|
|
1240
|
-
context.get("logger").error("unhandled error",
|
|
1262
|
+
context.get("logger").error("unhandled error", { error });
|
|
1241
1263
|
return context.text("Internal Server Error", 500);
|
|
1242
1264
|
}
|
|
1243
1265
|
const appInternals = /* @__PURE__ */ new WeakMap();
|
|
@@ -1310,13 +1332,6 @@ function withForwardedProto(request) {
|
|
|
1310
1332
|
if (copy.method !== request.method) Object.defineProperty(copy, "method", { value: request.method });
|
|
1311
1333
|
return copy;
|
|
1312
1334
|
}
|
|
1313
|
-
/**
|
|
1314
|
-
* A thrown value as an `Error`. Hono sends only an `Error` to `onError`, and
|
|
1315
|
-
* rethrows any other value.
|
|
1316
|
-
*/
|
|
1317
|
-
function asError(error) {
|
|
1318
|
-
return error instanceof Error ? error : new Error(`A non-Error value was thrown: ${String(error)}`, { cause: error });
|
|
1319
|
-
}
|
|
1320
1335
|
/** Whether `work` settles before `ms` pass. */
|
|
1321
1336
|
async function settlesWithin(work, ms) {
|
|
1322
1337
|
let timer;
|
|
@@ -1340,11 +1355,13 @@ async function settlesWithin(work, ms) {
|
|
|
1340
1355
|
* app.get("/api/status", (c) => c.json({ ok: true }));
|
|
1341
1356
|
* export default app;
|
|
1342
1357
|
*/
|
|
1343
|
-
function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listeners, trustForwardedProto = false, trustedProxyHops = 0, shutdownDelayMs = 0, shutdownDeadlineMs = 1e4 } = {}) {
|
|
1358
|
+
function createServer({ plugins = defaultPlugins(), logger: sink = jsonSink(), log, listeners, trustForwardedProto = false, trustedProxyHops = 0, shutdownDelayMs = 0, shutdownDeadlineMs = 1e4 } = {}) {
|
|
1344
1359
|
checkOptionPlugins(plugins);
|
|
1345
1360
|
checkCount("trustedProxyHops", trustedProxyHops);
|
|
1346
1361
|
checkCount("shutdownDelayMs", shutdownDelayMs, MAX_TIMER_MS);
|
|
1347
1362
|
checkCount("shutdownDeadlineMs", shutdownDeadlineMs, MAX_TIMER_MS);
|
|
1363
|
+
const logger = hookSink(sink, log);
|
|
1364
|
+
setProcessSink(logger);
|
|
1348
1365
|
const app = new Hono();
|
|
1349
1366
|
let onError = answerError;
|
|
1350
1367
|
const setOnError = app.onError.bind(app);
|
|
@@ -1439,7 +1456,11 @@ function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listene
|
|
|
1439
1456
|
throw failed.reason;
|
|
1440
1457
|
}
|
|
1441
1458
|
const urls = started.map((listener) => listener.url);
|
|
1442
|
-
logger.log(
|
|
1459
|
+
logger.log({
|
|
1460
|
+
level: "info",
|
|
1461
|
+
message: "listening",
|
|
1462
|
+
attributes: { "app_server.urls": urls }
|
|
1463
|
+
});
|
|
1443
1464
|
let stopping;
|
|
1444
1465
|
running = {
|
|
1445
1466
|
urls,
|
|
@@ -1447,12 +1468,20 @@ function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listene
|
|
|
1447
1468
|
stopping ??= (async () => {
|
|
1448
1469
|
markStopping();
|
|
1449
1470
|
if (shutdownDelayMs > 0) {
|
|
1450
|
-
logger.log(
|
|
1471
|
+
logger.log({
|
|
1472
|
+
level: "info",
|
|
1473
|
+
message: "waiting before the drain",
|
|
1474
|
+
attributes: { "app_server.delay_ms": shutdownDelayMs }
|
|
1475
|
+
});
|
|
1451
1476
|
await new Promise((resolve) => {
|
|
1452
1477
|
setTimeout(resolve, shutdownDelayMs);
|
|
1453
1478
|
});
|
|
1454
1479
|
}
|
|
1455
|
-
logger.log(
|
|
1480
|
+
logger.log({
|
|
1481
|
+
level: "info",
|
|
1482
|
+
message: "draining",
|
|
1483
|
+
attributes: { "app_server.deadline_ms": shutdownDeadlineMs }
|
|
1484
|
+
});
|
|
1456
1485
|
abortShutdownSignal();
|
|
1457
1486
|
const deadline = setTimeout(() => {
|
|
1458
1487
|
deadlinePassed = true;
|
|
@@ -1461,7 +1490,11 @@ function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listene
|
|
|
1461
1490
|
clearTimeout(deadline);
|
|
1462
1491
|
const rejected = results.find((result) => result.status === "rejected");
|
|
1463
1492
|
if (rejected != null) throw rejected.reason;
|
|
1464
|
-
logger.log(
|
|
1493
|
+
logger.log({
|
|
1494
|
+
level: "info",
|
|
1495
|
+
message: "stopped",
|
|
1496
|
+
attributes: {}
|
|
1497
|
+
});
|
|
1465
1498
|
})();
|
|
1466
1499
|
return stopping;
|
|
1467
1500
|
}
|
|
@@ -1472,8 +1505,16 @@ function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listene
|
|
|
1472
1505
|
stoppingPlugins ??= (async () => {
|
|
1473
1506
|
if (!await settlesWithin((async () => {
|
|
1474
1507
|
const results = await Promise.allSettled(plugins.map(async (plugin) => plugin.onShutdown?.()));
|
|
1475
|
-
for (const result of results) if (result.status === "rejected") logger.log(
|
|
1476
|
-
|
|
1508
|
+
for (const result of results) if (result.status === "rejected") logger.log({
|
|
1509
|
+
level: "error",
|
|
1510
|
+
message: "plugin shutdown failed",
|
|
1511
|
+
attributes: { error: asError(result.reason) }
|
|
1512
|
+
});
|
|
1513
|
+
})(), shutdownDeadlineMs)) logger.log({
|
|
1514
|
+
level: "warn",
|
|
1515
|
+
message: "plugin shutdown passed the deadline",
|
|
1516
|
+
attributes: { "app_server.deadline_ms": shutdownDeadlineMs }
|
|
1517
|
+
});
|
|
1477
1518
|
})();
|
|
1478
1519
|
return stoppingPlugins;
|
|
1479
1520
|
}
|
|
@@ -1487,4 +1528,4 @@ function serverInternals(app) {
|
|
|
1487
1528
|
}
|
|
1488
1529
|
|
|
1489
1530
|
export { assets as _, streamingCompress as a, prefersMarkdown as b, securityHeaders as c, noindex as d, health as f, accessLog as g, bodyLimit as h, withForwardedProto as i, redirects as l, shutdownSignal as m, defaultPlugins as n, requestId as o, abortShutdownSignal as p, serverInternals as r, contentSecurityPolicy as s, createServer as t, privateDocuments as u, prerendered as v, trailingSlash as y };
|
|
1490
|
-
//# sourceMappingURL=create-server-
|
|
1531
|
+
//# sourceMappingURL=create-server-C63luLkn.js.map
|