@ngrok/app-server 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +659 -70
  2. package/dist/build-id-C6sYO9Yp.js +126 -0
  3. package/dist/build-id-C6sYO9Yp.js.map +1 -0
  4. package/dist/build-manifest-UDNk81Ce.js +63 -0
  5. package/dist/build-manifest-UDNk81Ce.js.map +1 -0
  6. package/dist/{bun-DCGnDEPn.js → bun-BCz6K_Xv.js} +12 -8
  7. package/dist/bun-BCz6K_Xv.js.map +1 -0
  8. package/dist/cli.js +47 -27
  9. package/dist/cli.js.map +1 -1
  10. package/dist/client.d.ts +141 -0
  11. package/dist/client.js +326 -0
  12. package/dist/client.js.map +1 -0
  13. package/dist/compression-7_gToa8R.js +97 -0
  14. package/dist/compression-7_gToa8R.js.map +1 -0
  15. package/dist/create-server-iE1-s6Bi.js +1409 -0
  16. package/dist/create-server-iE1-s6Bi.js.map +1 -0
  17. package/dist/{deno-BnMfk2n1.js → deno-aqhikNMG.js} +5 -5
  18. package/dist/deno-aqhikNMG.js.map +1 -0
  19. package/dist/entry-DZ3qo7qF.js +116 -0
  20. package/dist/entry-DZ3qo7qF.js.map +1 -0
  21. package/dist/entry-DmJEqVfd.d.ts +622 -0
  22. package/dist/gzip-Doi4wqjX.js +294 -0
  23. package/dist/gzip-Doi4wqjX.js.map +1 -0
  24. package/dist/header-hook-Vzw9J9BY.js +159 -0
  25. package/dist/header-hook-Vzw9J9BY.js.map +1 -0
  26. package/dist/index-Bo5G9LuQ.d.ts +127 -0
  27. package/dist/index.d.ts +110 -95
  28. package/dist/index.js +56 -57
  29. package/dist/index.js.map +1 -1
  30. package/dist/{listen-options-DHWmSWGi.js → listen-options-7TaXjyrk.js} +2 -2
  31. package/dist/listen-options-7TaXjyrk.js.map +1 -0
  32. package/dist/load-entry-AfYS_zS9.js +37 -0
  33. package/dist/load-entry-AfYS_zS9.js.map +1 -0
  34. package/dist/log-BP6xXXZl.js +122 -0
  35. package/dist/log-BP6xXXZl.js.map +1 -0
  36. package/dist/node-BFH82eeL.js +333 -0
  37. package/dist/node-BFH82eeL.js.map +1 -0
  38. package/dist/node-tBVQPjQv.js +41 -0
  39. package/dist/node-tBVQPjQv.js.map +1 -0
  40. package/dist/node-vite.d.ts +11 -0
  41. package/dist/node-vite.js +3 -0
  42. package/dist/node.d.ts +86 -0
  43. package/dist/node.js +4 -0
  44. package/dist/react-router-vite.d.ts +10 -0
  45. package/dist/react-router-vite.js +3 -0
  46. package/dist/react-router.d.ts +11 -24
  47. package/dist/react-router.js +21 -30
  48. package/dist/react-router.js.map +1 -1
  49. package/dist/request-context-BtQ87VYb.js +40 -0
  50. package/dist/request-context-BtQ87VYb.js.map +1 -0
  51. package/dist/response-edge-Bc1-C_Cx.js +327 -0
  52. package/dist/response-edge-Bc1-C_Cx.js.map +1 -0
  53. package/dist/response-writer-B7FoJjEE.js +289 -0
  54. package/dist/response-writer-B7FoJjEE.js.map +1 -0
  55. package/dist/script-hashes-hqUk6kG7.js +53 -0
  56. package/dist/script-hashes-hqUk6kG7.js.map +1 -0
  57. package/dist/serve-CDNgThjk.js +29 -0
  58. package/dist/serve-CDNgThjk.js.map +1 -0
  59. package/dist/{start-BVMb8Pyt.js → start-TLIprD74.js} +96 -81
  60. package/dist/start-TLIprD74.js.map +1 -0
  61. package/dist/static-files-Beju9riB.js +302 -0
  62. package/dist/static-files-Beju9riB.js.map +1 -0
  63. package/dist/tanstack-start-vite.d.ts +12 -0
  64. package/dist/tanstack-start-vite.js +3 -0
  65. package/dist/tanstack-start.d.ts +34 -0
  66. package/dist/tanstack-start.js +41 -0
  67. package/dist/tanstack-start.js.map +1 -0
  68. package/dist/{tcp-Dau_IONd.js → tcp-Dd1Mt6sN.js} +8 -7
  69. package/dist/tcp-Dd1Mt6sN.js.map +1 -0
  70. package/dist/trailing-slash-DX7NB88H.d.ts +36 -0
  71. package/dist/types-DLYxYS6M.d.ts +392 -0
  72. package/dist/vercel-vite.d.ts +35 -0
  73. package/dist/vercel-vite.js +142 -0
  74. package/dist/vercel-vite.js.map +1 -0
  75. package/dist/vercel.d.ts +35 -0
  76. package/dist/vercel.js +89 -0
  77. package/dist/vercel.js.map +1 -0
  78. package/dist/vite-B-GfswoH.js +22 -0
  79. package/dist/vite-B-GfswoH.js.map +1 -0
  80. package/dist/vite-D4hfj3ph.js +19 -0
  81. package/dist/vite-D4hfj3ph.js.map +1 -0
  82. package/dist/vite-DyrhyKEr.js +25 -0
  83. package/dist/vite-DyrhyKEr.js.map +1 -0
  84. package/dist/vite-iioAoxSt.js +752 -0
  85. package/dist/vite-iioAoxSt.js.map +1 -0
  86. package/dist/vite.d.ts +2 -27
  87. package/dist/vite.js +2 -2
  88. package/package.json +50 -4
  89. package/dist/bun-DCGnDEPn.js.map +0 -1
  90. package/dist/captured-headers-ewL_t3MQ.js +0 -48
  91. package/dist/captured-headers-ewL_t3MQ.js.map +0 -1
  92. package/dist/deno-BnMfk2n1.js.map +0 -1
  93. package/dist/entry-CIpwaayZ.d.ts +0 -293
  94. package/dist/entry-ChjmFwX5.js +0 -755
  95. package/dist/entry-ChjmFwX5.js.map +0 -1
  96. package/dist/listen-options-DHWmSWGi.js.map +0 -1
  97. package/dist/node-2wWBMFeO.js +0 -3
  98. package/dist/node-79my3Uix.js +0 -58
  99. package/dist/node-79my3Uix.js.map +0 -1
  100. package/dist/serve-ByeedcRB.js +0 -16
  101. package/dist/serve-ByeedcRB.js.map +0 -1
  102. package/dist/start-BVMb8Pyt.js.map +0 -1
  103. package/dist/tcp-Dau_IONd.js.map +0 -1
  104. package/dist/vite-CrNqpoeK.js +0 -102
  105. package/dist/vite-CrNqpoeK.js.map +0 -1
package/dist/node.d.ts ADDED
@@ -0,0 +1,86 @@
1
+ import { T as StaticFiles, c as HostRuntime, d as ListenerBindings, t as AppServerEnv, u as Listener } from "./types-DLYxYS6M.js";
2
+ import { MiddlewareHandler } from "hono";
3
+ import { IncomingMessage, ServerResponse } from "node:http";
4
+ /** A Connect middleware, such as `vite.middlewares`. */
5
+ type NodeMiddleware = (request: IncomingMessage, response: ServerResponse, next: (error?: unknown) => void) => void;
6
+ /** What a `node:http` listener passes to the app with each request. */
7
+ type NodeBindings = ListenerBindings & {
8
+ /** Node's request. */
9
+ incoming?: IncomingMessage;
10
+ /** Node's response. */
11
+ outgoing?: ServerResponse;
12
+ };
13
+ /** Options for {@link devServerStage}. */
14
+ type DevServerStageOptions = {
15
+ /**
16
+ * The directory that the middleware serves as it is, and the URL base that
17
+ * it serves the directory at, such as Vite's `publicDir` and `base`. An HTML
18
+ * file from it gets the `contentSecurityPolicy` with the hashes of its
19
+ * inline scripts, as it does in production. Why a function: a Vite restart
20
+ * can change both.
21
+ */
22
+ publicFiles?: () => {
23
+ directory: string;
24
+ base: string;
25
+ };
26
+ };
27
+ /**
28
+ * Runs a Connect middleware, such as Vite's, inside the pipeline. The
29
+ * middleware answers or calls `next`. A request with no Node request and
30
+ * response goes on.
31
+ *
32
+ * @example
33
+ * entry.fetchDev(request, bindings, devServerStage(viteServer.middlewares, {
34
+ * publicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),
35
+ * }));
36
+ */
37
+ export declare function devServerStage(middleware: NodeMiddleware, { publicFiles }?: DevServerStageOptions): MiddlewareHandler<AppServerEnv>;
38
+ /**
39
+ * The client build on the file system. A relative `clientDirectory` is
40
+ * relative to the working directory.
41
+ *
42
+ * Its `snapshot` reads each file and directory once. It throws for an error
43
+ * that does not mean a missing file, so the server does not start.
44
+ *
45
+ * @example
46
+ * nodeFiles("build/client").stat("/llms.txt");
47
+ */
48
+ export declare function nodeFiles(clientDirectory: string): StaticFiles;
49
+ /** Options for {@link tcp}. */
50
+ type TcpOptions = {
51
+ /** @default the `PORT` environment variable, else 3000 */
52
+ port?: number;
53
+ /** @default the `HOST` environment variable, else every interface */
54
+ host?: string;
55
+ /** @default 95000 */
56
+ idleTimeoutMs?: number;
57
+ };
58
+ /**
59
+ * Reads a port number. A value that is not an integer from 0 to 65535 throws,
60
+ * so a bad `PORT` stops startup.
61
+ *
62
+ * @example
63
+ * parsePort("8080"); // => 8080
64
+ */
65
+ export declare function parsePort(value: string): number;
66
+ /**
67
+ * The default listener: a TCP port, served by the runtime's own HTTP server
68
+ * (`node:http` on Node, `Bun.serve` on Bun, `Deno.serve` on Deno). It reads
69
+ * `PORT` and `HOST` when it starts.
70
+ *
71
+ * @example
72
+ * createServer({ listeners: [tcp({ port: 8080 })] });
73
+ */
74
+ export declare function tcp({ port, host, idleTimeoutMs }?: TcpOptions): Listener;
75
+ /**
76
+ * The node host: one long-lived process on Node, Bun, or Deno, such as a
77
+ * Docker image. It listens with `tcp()`, reads the client build from the file
78
+ * system, and keeps `requestContext()` in `AsyncLocalStorage`. On `SIGTERM` or
79
+ * `SIGINT`, it shuts down, then exits the process.
80
+ *
81
+ * @example
82
+ * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });
83
+ */
84
+ declare const host$1: HostRuntime;
85
+ export { type DevServerStageOptions, type NodeBindings, type NodeMiddleware, type TcpOptions, host$1 as host };
86
+ //# sourceMappingURL=node.d.ts.map
package/dist/node.js ADDED
@@ -0,0 +1,4 @@
1
+ import { n as tcp, t as parsePort } from "./tcp-Dd1Mt6sN.js";
2
+ import { n as devServerStage, r as nodeFiles, t as host } from "./node-BFH82eeL.js";
3
+
4
+ export { devServerStage, host, nodeFiles, parsePort, tcp };
@@ -0,0 +1,10 @@
1
+ import { n as FrameworkBuild } from "./index-Bo5G9LuQ.js";
2
+ /**
3
+ * The build side of the React Router adapter. `appServer` uses it when the
4
+ * Vite config has the React Router plugin, so pass it only to override that.
5
+ *
6
+ * @example
7
+ * appServer({ framework: reactRouterAdapter() });
8
+ */
9
+ export declare function reactRouterAdapter(): FrameworkBuild;
10
+ //# sourceMappingURL=react-router-vite.d.ts.map
@@ -0,0 +1,3 @@
1
+ import { t as reactRouterAdapter } from "./vite-B-GfswoH.js";
2
+
3
+ export { reactRouterAdapter };
@@ -1,23 +1,19 @@
1
- import { D as SetupInfo, T as RequestLogger, r as AppServer, t as AppServerEntry, v as FrameworkAdapter } from "./entry-CIpwaayZ.js";
1
+ import { _ as RequestContext, a as FrameworkRuntime, h as Mode } from "./types-DLYxYS6M.js";
2
2
  import { ServerBuild } from "react-router";
3
3
  /** What the server puts in React Router's context for each request. */
4
- export type AppServerContext = {
5
- /** The request ID, when the `requestId` plugin runs. */
6
- requestId: string | undefined;
7
- /** The request's logger. Its lines carry the request ID. */
8
- logger: RequestLogger;
9
- };
4
+ export type AppServerContext = RequestContext;
10
5
  /**
11
6
  * The React Router context key for {@link AppServerContext}. Outside a server
12
7
  * request, such as in React Router's prerender pass, it holds no request ID
13
- * and a logger that writes to `jsonSink()`.
8
+ * and a logger that writes to `jsonSink()`. `requestContext()` from
9
+ * `@ngrok/app-server` gives the same values.
14
10
  *
15
11
  * @example
16
12
  * export async function loader({ context }: Route.LoaderArgs) {
17
13
  * context.get(appServerContext).logger.info("loading the dashboard");
18
14
  * }
19
15
  */
20
- export declare const appServerContext: import("react-router").RouterContext<AppServerContext>;
16
+ export declare const appServerContext: import("react-router").RouterContext<RequestContext>;
21
17
  /**
22
18
  * Whether a module is a React Router server build.
23
19
  *
@@ -26,22 +22,13 @@ export declare const appServerContext: import("react-router").RouterContext<AppS
26
22
  */
27
23
  export declare function isServerBuild(value: unknown): value is ServerBuild;
28
24
  /**
29
- * The framework adapter for a React Router server build. Each request gets a
30
- * `RouterContextProvider` that holds {@link appServerContext}.
25
+ * The run side of the React Router adapter, for a server build. Each request
26
+ * gets a `RouterContextProvider` that holds {@link appServerContext}.
31
27
  *
32
28
  * @example
33
- * const framework = createAdapter(build, { mode: "production" });
29
+ * const framework = runtime(build, { mode: "production" });
34
30
  */
35
- export declare function createAdapter(build: ServerBuild, { mode }: {
36
- mode: SetupInfo["mode"];
37
- }): FrameworkAdapter;
38
- /**
39
- * The `appServer` export of a React Router server build. The `serverEntry`
40
- * Vite plugin adds it, so the copy of this package in the build runs the
41
- * server. With no `app`, the server has the default plugins.
42
- *
43
- * @example
44
- * export const appServer = appServerEntry(build, app);
45
- */
46
- export declare function appServerEntry(build: ServerBuild, app?: AppServer): AppServerEntry;
31
+ export declare function runtime(build: unknown, { mode }: {
32
+ mode: Mode;
33
+ }): FrameworkRuntime;
47
34
  //# sourceMappingURL=react-router.d.ts.map
@@ -1,12 +1,13 @@
1
- import { f as jsonSink, p as sinkLogger, r as createServer, t as createEntry } from "./entry-ChjmFwX5.js";
2
- import { resolve } from "node:path";
1
+ import { a as sinkLogger, r as jsonSink } from "./log-BP6xXXZl.js";
2
+ import { n as requestContextValues } from "./request-context-BtQ87VYb.js";
3
3
  import { RouterContextProvider, createContext, createRequestHandler } from "react-router";
4
4
 
5
- // src/react-router.ts
5
+ // src/react-router/index.ts
6
6
  /**
7
7
  * The React Router context key for {@link AppServerContext}. Outside a server
8
8
  * request, such as in React Router's prerender pass, it holds no request ID
9
- * and a logger that writes to `jsonSink()`.
9
+ * and a logger that writes to `jsonSink()`. `requestContext()` from
10
+ * `@ngrok/app-server` gives the same values.
10
11
  *
11
12
  * @example
12
13
  * export async function loader({ context }: Route.LoaderArgs) {
@@ -15,7 +16,9 @@ import { RouterContextProvider, createContext, createRequestHandler } from "reac
15
16
  */
16
17
  const appServerContext = createContext({
17
18
  requestId: void 0,
18
- logger: sinkLogger(jsonSink())
19
+ logger: sinkLogger(jsonSink()),
20
+ cspNonce: void 0,
21
+ clientAddress: void 0
19
22
  });
20
23
  /**
21
24
  * Whether a module is a React Router server build.
@@ -27,42 +30,30 @@ function isServerBuild(value) {
27
30
  return typeof value === "object" && value != null && "routes" in value && "entry" in value && "assetsBuildDirectory" in value && typeof value.assetsBuildDirectory === "string";
28
31
  }
29
32
  /**
30
- * The framework adapter for a React Router server build. Each request gets a
31
- * `RouterContextProvider` that holds {@link appServerContext}.
33
+ * The run side of the React Router adapter, for a server build. Each request
34
+ * gets a `RouterContextProvider` that holds {@link appServerContext}.
32
35
  *
33
36
  * @example
34
- * const framework = createAdapter(build, { mode: "production" });
37
+ * const framework = runtime(build, { mode: "production" });
35
38
  */
36
- function createAdapter(build, { mode }) {
39
+ function runtime(build, { mode }) {
40
+ if (!isServerBuild(build)) throw new Error("The server module is not a React Router server build.");
37
41
  if (build.publicPath !== "/") throw new Error(`@ngrok/app-server serves a build at "/" only, and this build has the publicPath "${build.publicPath}".`);
38
42
  const handler = createRequestHandler(build, mode);
43
+ const manifestPath = build.routeDiscovery.mode === "lazy" ? [build.basename ?? "", build.routeDiscovery.manifestPath || "/__manifest"].join("/").replaceAll(/\/+/gu, "/") : void 0;
39
44
  return {
40
- clientDirectory: resolve(build.assetsBuildDirectory),
45
+ name: "react-router",
46
+ clientDirectory: build.assetsBuildDirectory,
41
47
  prerenderedPaths: build.prerender,
42
- fetch: (request, context) => {
48
+ isDataRequest: (path) => path.endsWith(".data") || path === manifestPath,
49
+ contentTypes: { ".data": "text/x-script" },
50
+ fetch: async (request, context) => {
43
51
  const routerContext = new RouterContextProvider();
44
- routerContext.set(appServerContext, {
45
- requestId: context.var.requestId,
46
- logger: context.var.logger
47
- });
52
+ routerContext.set(appServerContext, requestContextValues(context));
48
53
  return handler(request, routerContext);
49
54
  }
50
55
  };
51
56
  }
52
- /**
53
- * The `appServer` export of a React Router server build. The `serverEntry`
54
- * Vite plugin adds it, so the copy of this package in the build runs the
55
- * server. With no `app`, the server has the default plugins.
56
- *
57
- * @example
58
- * export const appServer = appServerEntry(build, app);
59
- */
60
- function appServerEntry(build, app = createServer({ trustForwardedProto: process.env.TRUST_FORWARDED_PROTO === "1" })) {
61
- return createEntry({
62
- app,
63
- framework: (mode) => createAdapter(build, { mode })
64
- });
65
- }
66
57
 
67
- export { appServerContext, appServerEntry, createAdapter, isServerBuild };
58
+ export { appServerContext, isServerBuild, runtime };
68
59
  //# sourceMappingURL=react-router.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"react-router.js","names":[],"sources":["../src/react-router.ts"],"sourcesContent":["import { resolve } from \"node:path\";\nimport {\n\t//,\n\tcreateContext,\n\tcreateRequestHandler,\n\tRouterContextProvider,\n\ttype ServerBuild,\n} from \"react-router\";\nimport { createServer, type AppServer } from \"./create-server.js\";\nimport { createEntry, type AppServerEntry } from \"./entry.js\";\nimport { jsonSink, sinkLogger } from \"./log.js\";\nimport type { FrameworkAdapter, RequestLogger, SetupInfo } from \"./types.js\";\n\n/** What the server puts in React Router's context for each request. */\nexport type AppServerContext = {\n\t/** The request ID, when the `requestId` plugin runs. */\n\trequestId: string | undefined;\n\t/** The request's logger. Its lines carry the request ID. */\n\tlogger: RequestLogger;\n};\n\n/**\n * The React Router context key for {@link AppServerContext}. Outside a server\n * request, such as in React Router's prerender pass, it holds no request ID\n * and a logger that writes to `jsonSink()`.\n *\n * @example\n * export async function loader({ context }: Route.LoaderArgs) {\n * \tcontext.get(appServerContext).logger.info(\"loading the dashboard\");\n * }\n */\nexport const appServerContext = createContext<AppServerContext>({\n\trequestId: undefined,\n\tlogger: sinkLogger(jsonSink()),\n});\n\n/**\n * Whether a module is a React Router server build.\n *\n * @example\n * isServerBuild(await import(\"./build/server/index.js\")); // => true\n */\nexport function isServerBuild(value: unknown): value is ServerBuild {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t\"routes\" in value &&\n\t\t\"entry\" in value &&\n\t\t\"assetsBuildDirectory\" in value &&\n\t\ttypeof value.assetsBuildDirectory === \"string\"\n\t);\n}\n\n/**\n * The framework adapter for a React Router server build. Each request gets a\n * `RouterContextProvider` that holds {@link appServerContext}.\n *\n * @example\n * const framework = createAdapter(build, { mode: \"production\" });\n */\nexport function createAdapter(\n\tbuild: ServerBuild,\n\t{ mode }: { mode: SetupInfo[\"mode\"] },\n): FrameworkAdapter {\n\tif (build.publicPath !== \"/\") {\n\t\tthrow new Error(\n\t\t\t`@ngrok/app-server serves a build at \"/\" only, and this build has the publicPath \"${build.publicPath}\".`,\n\t\t);\n\t}\n\tconst handler = createRequestHandler(build, mode);\n\treturn {\n\t\tclientDirectory: resolve(build.assetsBuildDirectory),\n\t\tprerenderedPaths: build.prerender,\n\t\tfetch: (request, context) => {\n\t\t\tconst routerContext = new RouterContextProvider();\n\t\t\trouterContext.set(appServerContext, {\n\t\t\t\trequestId: context.var.requestId,\n\t\t\t\tlogger: context.var.logger,\n\t\t\t});\n\t\t\treturn handler(request, routerContext);\n\t\t},\n\t};\n}\n\n/**\n * The `appServer` export of a React Router server build. The `serverEntry`\n * Vite plugin adds it, so the copy of this package in the build runs the\n * server. With no `app`, the server has the default plugins.\n *\n * @example\n * export const appServer = appServerEntry(build, app);\n */\nexport function appServerEntry(\n\tbuild: ServerBuild,\n\tapp: AppServer = createServer({ trustForwardedProto: process.env.TRUST_FORWARDED_PROTO === \"1\" }),\n): AppServerEntry {\n\treturn createEntry({ app, framework: (mode) => createAdapter(build, { mode }) });\n}\n"],"mappings":";;;;;;;;;;;;;;;AA+BA,MAAa,mBAAmB,cAAgC;CAC/D,WAAW;CACX,QAAQ,WAAW,SAAS,CAAC;AAC9B,CAAC;;;;;;;AAQD,SAAgB,cAAc,OAAsC;CACnE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,YAAY,SACZ,WAAW,SACX,0BAA0B,SAC1B,OAAO,MAAM,yBAAyB;AAExC;;;;;;;;AASA,SAAgB,cACf,OACA,EAAE,QACiB;CACnB,IAAI,MAAM,eAAe,KACxB,MAAM,IAAI,MACT,oFAAoF,MAAM,WAAW,GACtG;CAED,MAAM,UAAU,qBAAqB,OAAO,IAAI;CAChD,OAAO;EACN,iBAAiB,QAAQ,MAAM,oBAAoB;EACnD,kBAAkB,MAAM;EACxB,QAAQ,SAAS,YAAY;GAC5B,MAAM,gBAAgB,IAAI,sBAAsB;GAChD,cAAc,IAAI,kBAAkB;IACnC,WAAW,QAAQ,IAAI;IACvB,QAAQ,QAAQ,IAAI;GACrB,CAAC;GACD,OAAO,QAAQ,SAAS,aAAa;EACtC;CACD;AACD;;;;;;;;;AAUA,SAAgB,eACf,OACA,MAAiB,aAAa,EAAE,qBAAqB,QAAQ,IAAI,0BAA0B,IAAI,CAAC,GAC/E;CACjB,OAAO,YAAY;EAAE;EAAK,YAAY,SAAS,cAAc,OAAO,EAAE,KAAK,CAAC;CAAE,CAAC;AAChF"}
1
+ {"version":3,"file":"react-router.js","names":[],"sources":["../src/react-router/index.ts"],"sourcesContent":["import { createContext, createRequestHandler, RouterContextProvider } from \"react-router\";\nimport type { ServerBuild } from \"react-router\";\nimport { jsonSink, sinkLogger } from \"../core/log.js\";\nimport { requestContextValues } from \"../core/request-context.js\";\nimport type { FrameworkRuntime, Mode, RequestContext } from \"../core/types.js\";\n\n/** What the server puts in React Router's context for each request. */\nexport type AppServerContext = RequestContext;\n\n/**\n * The React Router context key for {@link AppServerContext}. Outside a server\n * request, such as in React Router's prerender pass, it holds no request ID\n * and a logger that writes to `jsonSink()`. `requestContext()` from\n * `@ngrok/app-server` gives the same values.\n *\n * @example\n * export async function loader({ context }: Route.LoaderArgs) {\n * \tcontext.get(appServerContext).logger.info(\"loading the dashboard\");\n * }\n */\nexport const appServerContext = createContext<AppServerContext>({\n\trequestId: undefined,\n\tlogger: sinkLogger(jsonSink()),\n\tcspNonce: undefined,\n\tclientAddress: undefined,\n});\n\n/**\n * Whether a module is a React Router server build.\n *\n * @example\n * isServerBuild(await import(\"./build/server/index.js\")); // => true\n */\nexport function isServerBuild(value: unknown): value is ServerBuild {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t\"routes\" in value &&\n\t\t\"entry\" in value &&\n\t\t\"assetsBuildDirectory\" in value &&\n\t\ttypeof value.assetsBuildDirectory === \"string\"\n\t);\n}\n\n/**\n * The run side of the React Router adapter, for a server build. Each request\n * gets a `RouterContextProvider` that holds {@link appServerContext}.\n *\n * @example\n * const framework = runtime(build, { mode: \"production\" });\n */\nexport function runtime(build: unknown, { mode }: { mode: Mode }): FrameworkRuntime {\n\tif (!isServerBuild(build)) {\n\t\tthrow new Error(\"The server module is not a React Router server build.\");\n\t}\n\t// Why also here: the Vite plugin checks the base, but a plain build skips the plugin.\n\tif (build.publicPath !== \"/\") {\n\t\tthrow new Error(\n\t\t\t`@ngrok/app-server serves a build at \"/\" only, and this build has the publicPath \"${build.publicPath}\".`,\n\t\t);\n\t}\n\tconst handler = createRequestHandler(build, mode);\n\t// Why: lazy route discovery fetches this exact path, so a redirect breaks it.\n\tconst manifestPath =\n\t\tbuild.routeDiscovery.mode === \"lazy\"\n\t\t\t? [build.basename ?? \"\", build.routeDiscovery.manifestPath || \"/__manifest\"]\n\t\t\t\t\t.join(\"/\")\n\t\t\t\t\t.replaceAll(/\\/+/gu, \"/\")\n\t\t\t: undefined;\n\treturn {\n\t\tname: \"react-router\",\n\t\tclientDirectory: build.assetsBuildDirectory,\n\t\tprerenderedPaths: build.prerender,\n\t\tisDataRequest: (path) => path.endsWith(\".data\") || path === manifestPath,\n\t\tcontentTypes: { \".data\": \"text/x-script\" },\n\t\tfetch: async (request, context) => {\n\t\t\tconst routerContext = new RouterContextProvider();\n\t\t\trouterContext.set(appServerContext, requestContextValues(context));\n\t\t\treturn handler(request, routerContext);\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoBA,MAAa,mBAAmB,cAAgC;CAC/D,WAAW;CACX,QAAQ,WAAW,SAAS,CAAC;CAC7B,UAAU;CACV,eAAe;AAChB,CAAC;;;;;;;AAQD,SAAgB,cAAc,OAAsC;CACnE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,YAAY,SACZ,WAAW,SACX,0BAA0B,SAC1B,OAAO,MAAM,yBAAyB;AAExC;;;;;;;;AASA,SAAgB,QAAQ,OAAgB,EAAE,QAA0C;CACnF,IAAI,CAAC,cAAc,KAAK,GACvB,MAAM,IAAI,MAAM,uDAAuD;CAGxE,IAAI,MAAM,eAAe,KACxB,MAAM,IAAI,MACT,oFAAoF,MAAM,WAAW,GACtG;CAED,MAAM,UAAU,qBAAqB,OAAO,IAAI;CAEhD,MAAM,eACL,MAAM,eAAe,SAAS,SAC3B,CAAC,MAAM,YAAY,IAAI,MAAM,eAAe,gBAAgB,aAAa,CAAC,CACzE,KAAK,GAAG,CAAC,CACT,WAAW,SAAS,GAAG,IACxB;CACJ,OAAO;EACN,MAAM;EACN,iBAAiB,MAAM;EACvB,kBAAkB,MAAM;EACxB,gBAAgB,SAAS,KAAK,SAAS,OAAO,KAAK,SAAS;EAC5D,cAAc,EAAE,SAAS,gBAAgB;EACzC,OAAO,OAAO,SAAS,YAAY;GAClC,MAAM,gBAAgB,IAAI,sBAAsB;GAChD,cAAc,IAAI,kBAAkB,qBAAqB,OAAO,CAAC;GACjE,OAAO,QAAQ,SAAS,aAAa;EACtC;CACD;AACD"}
@@ -0,0 +1,40 @@
1
+ // src/core/request-context.ts
2
+ /**
3
+ * Each store that a request ran in. Why a set: two entries in one process can
4
+ * have two hosts, and each request uses the store of its own app.
5
+ */
6
+ const stores = /* @__PURE__ */ new Set();
7
+ /** The {@link RequestContext} values of a request. */
8
+ function requestContextValues(context) {
9
+ return {
10
+ requestId: context.get("requestId"),
11
+ logger: context.get("logger"),
12
+ cspNonce: context.get("cspNonce"),
13
+ clientAddress: context.get("clientAddress")
14
+ };
15
+ }
16
+ /** Runs `work` in `store` with `context` as the request that {@link requestContext} reads. */
17
+ async function withRequestContext(store, context, work) {
18
+ if (store == null) return work();
19
+ stores.add(store);
20
+ return store.run(context, work);
21
+ }
22
+ /**
23
+ * The request ID, logger, and CSP nonce of the request that runs. It gives `undefined`
24
+ * outside a server request, such as in a prerender pass, or on a host with no
25
+ * request storage.
26
+ *
27
+ * @example
28
+ * export async function loader() {
29
+ * requestContext()?.logger.info("loading the dashboard");
30
+ * }
31
+ */
32
+ function requestContext() {
33
+ for (const store of stores) {
34
+ const context = store.get();
35
+ if (context != null) return requestContextValues(context);
36
+ }
37
+ }
38
+
39
+ export { requestContextValues as n, withRequestContext as r, requestContext as t };
40
+ //# sourceMappingURL=request-context-BtQ87VYb.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-context-BtQ87VYb.js","names":[],"sources":["../src/core/request-context.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { AppServerEnv, RequestContext, RequestStore } from \"./types.js\";\n\n/**\n * Each store that a request ran in. Why a set: two entries in one process can\n * have two hosts, and each request uses the store of its own app.\n */\nconst stores = new Set<RequestStore>();\n\n/** The {@link RequestContext} values of a request. */\nexport function requestContextValues(context: Context<AppServerEnv>): RequestContext {\n\treturn {\n\t\trequestId: context.get(\"requestId\"),\n\t\tlogger: context.get(\"logger\"),\n\t\tcspNonce: context.get(\"cspNonce\"),\n\t\tclientAddress: context.get(\"clientAddress\"),\n\t};\n}\n\n/** Runs `work` in `store` with `context` as the request that {@link requestContext} reads. */\nexport async function withRequestContext(\n\tstore: RequestStore | undefined,\n\tcontext: Context<AppServerEnv>,\n\twork: () => Promise<void>,\n): Promise<void> {\n\tif (store == null) {\n\t\treturn work();\n\t}\n\tstores.add(store);\n\treturn store.run(context, work);\n}\n\n/**\n * The request ID, logger, and CSP nonce of the request that runs. It gives `undefined`\n * outside a server request, such as in a prerender pass, or on a host with no\n * request storage.\n *\n * @example\n * export async function loader() {\n * \trequestContext()?.logger.info(\"loading the dashboard\");\n * }\n */\nexport function requestContext(): RequestContext | undefined {\n\tfor (const store of stores) {\n\t\tconst context = store.get();\n\t\tif (context != null) {\n\t\t\treturn requestContextValues(context);\n\t\t}\n\t}\n\treturn undefined;\n}\n"],"mappings":";;;;;AAOA,MAAM,yBAAS,IAAI,IAAkB;;AAGrC,SAAgB,qBAAqB,SAAgD;CACpF,OAAO;EACN,WAAW,QAAQ,IAAI,WAAW;EAClC,QAAQ,QAAQ,IAAI,QAAQ;EAC5B,UAAU,QAAQ,IAAI,UAAU;EAChC,eAAe,QAAQ,IAAI,eAAe;CAC3C;AACD;;AAGA,eAAsB,mBACrB,OACA,SACA,MACgB;CAChB,IAAI,SAAS,MACZ,OAAO,KAAK;CAEb,OAAO,IAAI,KAAK;CAChB,OAAO,MAAM,IAAI,SAAS,IAAI;AAC/B;;;;;;;;;;;AAYA,SAAgB,iBAA6C;CAC5D,KAAK,MAAM,SAAS,QAAQ;EAC3B,MAAM,UAAU,MAAM,IAAI;EAC1B,IAAI,WAAW,MACd,OAAO,qBAAqB,OAAO;CAErC;AAED"}
@@ -0,0 +1,327 @@
1
+ import { a as replaceResponse, i as listView, n as headerList, t as headerIndex } from "./header-hook-Vzw9J9BY.js";
2
+ import { t as errorAttributes } from "./log-BP6xXXZl.js";
3
+
4
+ // src/core/response-edge.ts
5
+ function ignore() {}
6
+ /** Calls `report` with `sent`, and drops a throw from it. */
7
+ function callReport(report, sent) {
8
+ try {
9
+ report(sent);
10
+ } catch {}
11
+ }
12
+ /** The `Set-Cookie` values of a flat header list, one on each line. */
13
+ function cookiesOf(head) {
14
+ let cookies = "";
15
+ for (let index = 0; index < head.length; index += 2) if (head[index] === "set-cookie") cookies += `${head[index + 1] ?? ""}\n`;
16
+ return cookies;
17
+ }
18
+ /** The value of the lowercase `name` in a flat header list with one entry for each name, or `undefined`. */
19
+ function valueOf(head, name) {
20
+ const index = headerIndex(head, name);
21
+ return index === -1 ? void 0 : head[index + 1];
22
+ }
23
+ /** Whether two flat header lists are the same. */
24
+ function sameHead(first, second) {
25
+ if (first.length !== second.length) return false;
26
+ for (let index = 0; index < first.length; index += 1) if (first[index] !== second[index]) return false;
27
+ return true;
28
+ }
29
+ /** `head` with the changes from `base` to `live`, two lists of the headers of the response before the hooks. */
30
+ function withChanges(head, base, live) {
31
+ const changed = [...head];
32
+ const view = listView(changed);
33
+ for (let index = 0; index < base.length; index += 2) {
34
+ const name = base[index] ?? "";
35
+ if (headerIndex(live, name) === -1) view.delete(name);
36
+ }
37
+ if (cookiesOf(base) !== cookiesOf(live)) {
38
+ view.delete("set-cookie");
39
+ for (let index = 0; index < live.length; index += 2) if (live[index] === "set-cookie") view.append("set-cookie", live[index + 1] ?? "");
40
+ }
41
+ for (let index = 0; index < live.length; index += 2) {
42
+ const name = live[index] ?? "";
43
+ const value = live[index + 1] ?? "";
44
+ if (name !== "set-cookie" && valueOf(base, name) !== value) view.set(name, value);
45
+ }
46
+ return changed;
47
+ }
48
+ /**
49
+ * What the server and a listener that writes each response itself share for
50
+ * one request. The listener makes one for each request and gives it as the
51
+ * `edge` binding. The server then runs the header hooks on a list of the
52
+ * headers, so it copies no response for them. The listener:
53
+ *
54
+ * - writes {@link ResponseEdge.headersFor} in place of the headers of the response
55
+ * - adds each body byte that it writes to {@link ResponseEdge.bytes}
56
+ * - gives an error that stops the response to {@link ResponseEdge.fail}
57
+ * - calls {@link ResponseEdge.close} once, when the response ends or its client goes away
58
+ *
59
+ * @example
60
+ * const edge = new ResponseEdge();
61
+ * const response = await fetch(request, { remoteAddress, edge });
62
+ * outgoing.writeHead(response.status, edge.headersFor(response) ?? [...response.headers].flat());
63
+ */
64
+ var ResponseEdge = class {
65
+ /** The body bytes that the listener gave to its socket. */
66
+ bytes = 0;
67
+ #logger = void 0;
68
+ #base = void 0;
69
+ #headers = void 0;
70
+ #reports = [];
71
+ #sent = void 0;
72
+ /**
73
+ * Gives the edge to the request of `logger`, and gives `true`, the first
74
+ * time only. The server calls it when a request starts. Why once: a
75
+ * request that the app sends through itself again with the same bindings
76
+ * must change its own response.
77
+ */
78
+ claim(logger) {
79
+ if (this.#logger != null) return false;
80
+ this.#logger = logger;
81
+ return true;
82
+ }
83
+ /**
84
+ * Keeps `headers`, the headers of the response after each header hook, and
85
+ * `base`, its headers before the hooks. The server calls it.
86
+ */
87
+ useHeaders(base, headers) {
88
+ this.#base = base;
89
+ this.#headers = headers;
90
+ }
91
+ /**
92
+ * The headers to write for `response`: lowercase names and their values in
93
+ * turn, as Node's `writeHead` takes them. They are the headers after the
94
+ * hooks, with each change that the headers of `response` have from the
95
+ * response that the hooks ran on. Why: Hono answers HEAD with a copy that
96
+ * has no body, and a wrapper of the app's `fetch` can change the headers or
97
+ * return a copy. It gives `undefined` when the server kept no headers.
98
+ */
99
+ headersFor(response) {
100
+ const base = this.#base;
101
+ const headers = this.#headers;
102
+ if (base == null || headers == null) return headers;
103
+ const live = headerList(response.headers);
104
+ return sameHead(base, live) ? headers : withChanges(headers, base, live);
105
+ }
106
+ /**
107
+ * Calls `report` once, when the response ends or its client goes away. It
108
+ * calls it at once when that happened already. A throw from `report` never
109
+ * reaches the listener.
110
+ */
111
+ onSent(report) {
112
+ if (this.#sent == null) this.#reports.push(report);
113
+ else callReport(report, this.#sent);
114
+ }
115
+ /** Logs `error`, which stopped the response, with the logger of the request. */
116
+ fail(error) {
117
+ try {
118
+ if (this.#logger != null) {
119
+ this.#logger.error("unhandled error", errorAttributes(error));
120
+ return;
121
+ }
122
+ } catch {}
123
+ console.error(error);
124
+ }
125
+ /**
126
+ * Reports what went out, once: the status and the headers that the
127
+ * listener sent, the bytes, and whether the body stopped before its end.
128
+ * `head` is the flat list that the listener gave `writeHead`.
129
+ */
130
+ close(status, aborted, head) {
131
+ if (this.#sent != null) return;
132
+ this.#sent = {
133
+ status,
134
+ headers: listView(head),
135
+ bytes: this.bytes,
136
+ aborted
137
+ };
138
+ for (const report of this.#reports) callReport(report, this.#sent);
139
+ }
140
+ };
141
+ /**
142
+ * `body` again, with a count of its bytes for `report`. `report` runs once:
143
+ * at the end of the body, at a failure, or at a cancel.
144
+ */
145
+ function countedBody(body, report) {
146
+ const reader = body.getReader();
147
+ let bytes = 0;
148
+ return new ReadableStream({
149
+ async pull(controller) {
150
+ let result;
151
+ try {
152
+ result = await reader.read();
153
+ } catch (error) {
154
+ report(bytes, true);
155
+ throw error;
156
+ }
157
+ if (result.done) {
158
+ controller.close();
159
+ report(bytes, false);
160
+ return;
161
+ }
162
+ bytes += result.value.byteLength;
163
+ controller.enqueue(result.value);
164
+ },
165
+ async cancel(reason) {
166
+ try {
167
+ report(bytes, true);
168
+ } finally {
169
+ await reader.cancel(reason);
170
+ }
171
+ }
172
+ }, { highWaterMark: 0 });
173
+ }
174
+ /**
175
+ * The body of `context.res` with a count for `report`, or `undefined` when
176
+ * `report` ran at once: a HEAD response and a response with no body send no
177
+ * body bytes. `headers` are the headers that go out with the response.
178
+ */
179
+ function reportedBody(context, headers, report) {
180
+ const { status, body } = context.res;
181
+ if (context.req.method === "HEAD") {
182
+ callReport(report, {
183
+ status,
184
+ headers,
185
+ bytes: 0,
186
+ aborted: false
187
+ });
188
+ return;
189
+ }
190
+ if (body == null) {
191
+ callReport(report, {
192
+ status,
193
+ headers,
194
+ bytes: Number(headers.get("Content-Length") ?? 0),
195
+ aborted: false
196
+ });
197
+ return;
198
+ }
199
+ return countedBody(body, (bytes, aborted) => {
200
+ callReport(report, {
201
+ status,
202
+ headers,
203
+ bytes,
204
+ aborted
205
+ });
206
+ });
207
+ }
208
+ /**
209
+ * Calls `report` once, when the response of the request ends or its client
210
+ * goes away: with the status and the headers that went out, the body bytes,
211
+ * and whether the body stopped before its end. In an app server, it reports the response that
212
+ * the server returns, after each stage and header hook. A listener with an
213
+ * `edge` counts the bytes as it writes them; else the server counts them with
214
+ * a stream around the body.
215
+ *
216
+ * @example
217
+ * middleware: async (c, next) => {
218
+ * await next();
219
+ * onResponseSent(c, ({ status, bytes }) => c.get("logger").info("sent", { status, bytes }));
220
+ * },
221
+ */
222
+ function onResponseSent(context, report) {
223
+ const reports = context.get("sentReports");
224
+ if (reports != null) {
225
+ reports.push(report);
226
+ return;
227
+ }
228
+ const response = context.res;
229
+ const body = reportedBody(context, response.headers, report);
230
+ if (body != null) replaceResponse(context, new Response(body, response));
231
+ }
232
+ /**
233
+ * Puts the response that `fail` gives for `error` in place of the response of
234
+ * the request, and cancels the body that no one reads now.
235
+ */
236
+ async function useErrorResponse(context, fail, error) {
237
+ const { body } = context.res;
238
+ context.res = void 0;
239
+ context.res = await fail(error, context);
240
+ body?.cancel().catch(ignore);
241
+ }
242
+ /**
243
+ * Gives `reports` the response of the request. With no edge, it makes one new
244
+ * response with `headers`, when the hooks made them, and a body that counts
245
+ * its bytes.
246
+ */
247
+ function reportResponse(context, reports, headers) {
248
+ const response = context.res;
249
+ const [only] = reports;
250
+ const report = reports.length > 1 ? (sent) => {
251
+ for (const each of reports) callReport(each, sent);
252
+ } : only;
253
+ const body = report == null ? void 0 : reportedBody(context, headers ?? response.headers, report);
254
+ if (headers == null && body == null) return;
255
+ context.res = void 0;
256
+ context.res = new Response(body ?? response.body, {
257
+ status: response.status,
258
+ statusText: response.statusText,
259
+ headers: headers ?? response.headers
260
+ });
261
+ }
262
+ /** Puts the error response for `error` in place, then runs the hooks from `from` on it. */
263
+ async function finishAfterError(context, finish, { error, from }) {
264
+ await useErrorResponse(context, finish.fail, error);
265
+ await finishFrom(context, finish, from);
266
+ }
267
+ /** Puts the error response for `error` in place, and gives it to the reports. */
268
+ async function reportErrorResponse(context, finish, error) {
269
+ await useErrorResponse(context, finish.fail, error);
270
+ reportResponse(context, finish.reports, void 0);
271
+ }
272
+ /** {@link finishResponse} from the hook at `from`, down to the first one. */
273
+ function finishFrom(context, finish, from) {
274
+ const { hooks, reports, edge } = finish;
275
+ const base = headerList(context.res.headers);
276
+ const head = edge == null ? base : [...base];
277
+ const view = listView(head);
278
+ for (let index = from; index >= 0; index -= 1) try {
279
+ hooks[index]?.(view);
280
+ } catch (error) {
281
+ return finishAfterError(context, finish, {
282
+ error,
283
+ from: index - 1
284
+ });
285
+ }
286
+ if (edge != null) {
287
+ edge.useHeaders(base, head);
288
+ for (const report of reports) edge.onSent(report);
289
+ return;
290
+ }
291
+ if (hooks.length === 0) {
292
+ reportResponse(context, reports, void 0);
293
+ return;
294
+ }
295
+ const headers = new Headers();
296
+ try {
297
+ for (let index = 0; index < head.length; index += 2) headers.append(head[index] ?? "", head[index + 1] ?? "");
298
+ } catch (error) {
299
+ return reportErrorResponse(context, finish, error);
300
+ }
301
+ reportResponse(context, reports, headers);
302
+ }
303
+ /**
304
+ * Finishes the response of the request, after each stage. The server calls it
305
+ * once, in the request's `requestContext()`.
306
+ *
307
+ * - It runs `hooks` on the head, in reverse order, so the hook of an inner
308
+ * stage runs first and an outer stage has the last word. When a hook
309
+ * throws, `fail` gives the response that takes the place of this one, and
310
+ * the hooks of the outer stages run on it, as when a stage throws.
311
+ * - It gives `reports` the response, so each one runs when it ends.
312
+ *
313
+ * With `edge`, the head stays a list that the listener writes, so the server
314
+ * copies no response. Else the server makes one new response with the head
315
+ * and a body that counts its bytes. It gives a promise only when a hook
316
+ * throws, so a response with no error waits for no microtask.
317
+ *
318
+ * @example
319
+ * await next();
320
+ * await finishResponse(context, { hooks, reports, edge, fail: (error, c) => onError(error, c) });
321
+ */
322
+ function finishResponse(context, finish) {
323
+ return finishFrom(context, finish, finish.hooks.length - 1);
324
+ }
325
+
326
+ export { finishResponse as n, onResponseSent as r, ResponseEdge as t };
327
+ //# sourceMappingURL=response-edge-Bc1-C_Cx.js.map