@ngrok/app-server 0.3.0 → 0.3.1
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 +47 -6
- package/dist/cli.js +2 -2
- package/dist/client-browser.d.ts +12 -0
- package/dist/client-browser.js +3 -0
- package/dist/client.d.ts +14 -134
- package/dist/client.js +17 -316
- package/dist/client.js.map +1 -1
- package/dist/{create-server-iE1-s6Bi.js → create-server-DkTeIJ8L.js} +7 -7
- package/dist/create-server-DkTeIJ8L.js.map +1 -0
- package/dist/{entry-DmJEqVfd.d.ts → entry-CM6Ma-Tv.d.ts} +7 -3
- package/dist/{entry-DZ3qo7qF.js → entry-CenmvESk.js} +2 -2
- package/dist/{entry-DZ3qo7qF.js.map → entry-CenmvESk.js.map} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3 -3
- package/dist/{load-entry-AfYS_zS9.js → load-entry-CmkdlmDX.js} +3 -3
- package/dist/{load-entry-AfYS_zS9.js.map → load-entry-CmkdlmDX.js.map} +1 -1
- package/dist/react-router.js +1 -1
- package/dist/{serve-CDNgThjk.js → serve-Cc-ADdhZ.js} +2 -2
- package/dist/{serve-CDNgThjk.js.map → serve-Cc-ADdhZ.js.map} +1 -1
- package/dist/stale-build-navigation-PnMLtTF8.js +339 -0
- package/dist/stale-build-navigation-PnMLtTF8.js.map +1 -0
- package/dist/stale-build-navigation-ypV7Ow4o.d.ts +141 -0
- package/dist/{start-TLIprD74.js → start-Cb3kknlF.js} +2 -2
- package/dist/{start-TLIprD74.js.map → start-Cb3kknlF.js.map} +1 -1
- package/dist/vercel.d.ts +1 -1
- package/dist/vercel.js +1 -1
- package/package.json +2 -1
- package/dist/create-server-iE1-s6Bi.js.map +0 -1
package/README.md
CHANGED
|
@@ -162,7 +162,7 @@ After the build and after the prerender pass, `appServer` writes a gzip copy (`.
|
|
|
162
162
|
|
|
163
163
|
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.
|
|
164
164
|
|
|
165
|
-
A React Router app with no Vite plugin also works: `app-server serve build/server/index.js` reads a plain React Router build and runs it with the CLI's copy, the node host, and the default plugins. In that build, a route that calls `shutdownSignal()`, `eventStream()`, or `
|
|
165
|
+
A React Router app with no Vite plugin also works: `app-server serve build/server/index.js` reads a plain React Router build and runs it with the CLI's copy, the node host, and the default plugins. In that build, a route that calls `shutdownSignal()`, `eventStream()`, `requestContext()`, or `cspNonce()` must import the CLI's copy, so do not bundle `@ngrok/app-server` into it.
|
|
166
166
|
|
|
167
167
|
## Commands
|
|
168
168
|
|
|
@@ -381,21 +381,51 @@ createServer({
|
|
|
381
381
|
});
|
|
382
382
|
```
|
|
383
383
|
|
|
384
|
-
Give the nonce to the framework's render
|
|
384
|
+
Give the nonce to the framework's render with `cspNonce()` from `@ngrok/app-server/client`. On the server, it gives the nonce of the request. In the browser, it reads the nonce from the document, so the hydration matches. It gives `undefined` when the page has no nonce. A bundler that resolves the `browser` export condition, such as Vite for the client build, gets a `cspNonce()` with no server code.
|
|
385
|
+
|
|
386
|
+
In React Router, give it to the render in `app/entry.server.tsx`:
|
|
385
387
|
|
|
386
388
|
```tsx
|
|
387
|
-
|
|
389
|
+
import { cspNonce } from "@ngrok/app-server/client";
|
|
390
|
+
|
|
391
|
+
const nonce = cspNonce();
|
|
388
392
|
const { pipe } = renderToPipeableStream(
|
|
389
393
|
<ServerRouter context={routerContext} url={request.url} nonce={nonce} />,
|
|
390
394
|
{ nonce /* , … */ },
|
|
391
395
|
);
|
|
392
396
|
```
|
|
393
397
|
|
|
394
|
-
|
|
398
|
+
`<HydratedRouter>` takes no nonce, so in the browser `<Links>`, `<ScrollRestoration>`, and `<Scripts>` render no nonce, and React warns that the hydration does not match. Give them the nonce in the root `Layout`. Give it also to each inline script of the app, such as a theme script:
|
|
399
|
+
|
|
400
|
+
```tsx
|
|
401
|
+
// app/root.tsx
|
|
402
|
+
import { cspNonce } from "@ngrok/app-server/client";
|
|
403
|
+
|
|
404
|
+
export function Layout({ children }: { children: React.ReactNode }) {
|
|
405
|
+
const nonce = cspNonce();
|
|
406
|
+
return (
|
|
407
|
+
<html lang="en">
|
|
408
|
+
<head>
|
|
409
|
+
<Meta />
|
|
410
|
+
<Links nonce={nonce} />
|
|
411
|
+
</head>
|
|
412
|
+
<body>
|
|
413
|
+
{children}
|
|
414
|
+
<ScrollRestoration nonce={nonce} />
|
|
415
|
+
<Scripts nonce={nonce} />
|
|
416
|
+
</body>
|
|
417
|
+
</html>
|
|
418
|
+
);
|
|
419
|
+
}
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
In TanStack Start, give it to the router. `getRouter` runs on the server and in the browser:
|
|
395
423
|
|
|
396
424
|
```ts
|
|
425
|
+
import { cspNonce } from "@ngrok/app-server/client";
|
|
426
|
+
|
|
397
427
|
export function getRouter() {
|
|
398
|
-
return createRouter({ routeTree, ssr: { nonce:
|
|
428
|
+
return createRouter({ routeTree, ssr: { nonce: cspNonce() } });
|
|
399
429
|
}
|
|
400
430
|
```
|
|
401
431
|
|
|
@@ -617,6 +647,17 @@ The default twin is the path with no trailing slash plus `.md`, and `/index.md`
|
|
|
617
647
|
prerendered({ markdownTwins: { twinOf: (path) => (path === "/" ? "/llms.md" : `${path}.md`) } });
|
|
618
648
|
```
|
|
619
649
|
|
|
650
|
+
`twinOf` also gets the request's Hono context, the same as `rewrite`. If it gives `undefined`, the request gets no twin, `rewrite` runs, and the answer gets no `Vary: Accept` and no `Link`. For example, when the framework renders a page for each query, keep a request with a query off the prerendered twin:
|
|
651
|
+
|
|
652
|
+
```ts
|
|
653
|
+
prerendered({
|
|
654
|
+
markdownTwins: {
|
|
655
|
+
twinOf: (path, c) =>
|
|
656
|
+
new URL(c.req.url).search === "" ? `${path === "/" ? "/index" : path}.md` : undefined,
|
|
657
|
+
},
|
|
658
|
+
});
|
|
659
|
+
```
|
|
660
|
+
|
|
620
661
|
The framework makes the twins. In React Router, one splat resource route can answer every twin. Prerender each twin URL, and point `twinOf` at the route. `markdownFor` stands for the app's own lookup:
|
|
621
662
|
|
|
622
663
|
```ts
|
|
@@ -642,7 +683,7 @@ createServer({ plugins: defaultPlugins({ prerendered: { markdownTwins: { twinOf
|
|
|
642
683
|
|
|
643
684
|
The same route answers the twins in development.
|
|
644
685
|
|
|
645
|
-
For other negotiation, `rewrite` maps a request path to the file to serve. It does not run for a request that gets the twin. When its answer depends on a request header, add a `Vary` for that header in a plugin.
|
|
686
|
+
For other negotiation, `rewrite` maps a request path to the file to serve. It does not run for a request that gets the twin. To keep a request off the twin, give `undefined` from `twinOf`. When its answer depends on a request header, add a `Vary` for that header in a plugin.
|
|
646
687
|
|
|
647
688
|
### A rendered page
|
|
648
689
|
|
package/dist/cli.js
CHANGED
|
@@ -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-Cb3kknlF.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-Cc-ADdhZ.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
|
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { a as staleBuildReactRouter, o as staleBuildTanStack } from "./stale-build-navigation-ypV7Ow4o.js";
|
|
2
|
+
/**
|
|
3
|
+
* The CSP nonce of the document's first element with a nonce, or `undefined`
|
|
4
|
+
* when it has none. The browser build of `@ngrok/app-server/client` exports it
|
|
5
|
+
* as `cspNonce()`, so the browser bundle holds no server code.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* documentNonce(); // => "d2hhdCBhIG5vbmNl"
|
|
9
|
+
*/
|
|
10
|
+
declare function documentNonce(): string | undefined;
|
|
11
|
+
export { documentNonce as cspNonce, staleBuildReactRouter, staleBuildTanStack };
|
|
12
|
+
//# sourceMappingURL=client-browser.d.ts.map
|
package/dist/client.d.ts
CHANGED
|
@@ -1,141 +1,21 @@
|
|
|
1
|
-
|
|
2
|
-
type StaleBuildOptions = {
|
|
3
|
-
/**
|
|
4
|
-
* The header that `buildId()` sets on data responses.
|
|
5
|
-
* @default "X-Build-Id"
|
|
6
|
-
*/
|
|
7
|
-
header?: string;
|
|
8
|
-
/**
|
|
9
|
-
* The build that this document runs. Set it only when the server does not
|
|
10
|
-
* send it.
|
|
11
|
-
* @default the `build` metric of the document's `Server-Timing`, which `buildId()` sends
|
|
12
|
-
*/
|
|
13
|
-
build?: string;
|
|
14
|
-
/**
|
|
15
|
-
* Runs once, when the tab first sees a response from another build. Use
|
|
16
|
-
* it to count stale tabs in the app's RUM tool.
|
|
17
|
-
*/
|
|
18
|
-
onNewBuild?: (served: string) => void;
|
|
19
|
-
};
|
|
20
|
-
/** The context that React Router gives `unstable_fetch` with each request. */
|
|
21
|
-
type RouterFetchContext = {
|
|
22
|
-
/** `"navigation"` for the data request of a navigation that the router started. */
|
|
23
|
-
type: string;
|
|
24
|
-
/** `"PUSH"`, `"REPLACE"`, or `"POP"` for a navigation. */
|
|
25
|
-
navigationType?: string | null;
|
|
26
|
-
/** The fetcher that sends the request, also in a navigation that revalidates it. */
|
|
27
|
-
fetcherKey?: string | null;
|
|
28
|
-
};
|
|
29
|
-
/** The location in a TanStack Router event. */
|
|
30
|
-
type EventLocation = {
|
|
31
|
-
pathname: string;
|
|
32
|
-
searchStr: string;
|
|
33
|
-
};
|
|
34
|
-
/** The part of a TanStack Router that {@link staleBuildTanStack} reads. */
|
|
35
|
-
type NavigationEvents = {
|
|
36
|
-
history: {
|
|
37
|
-
flush: () => void;
|
|
38
|
-
};
|
|
39
|
-
clearCache: () => void;
|
|
40
|
-
subscribe: (type: "onBeforeNavigate" | "onResolved", listener: (event: {
|
|
41
|
-
fromLocation?: EventLocation;
|
|
42
|
-
toLocation: EventLocation;
|
|
43
|
-
}) => void) => () => void;
|
|
44
|
-
};
|
|
45
|
-
/** The `navigate` call of a React Router instrumentation. */
|
|
46
|
-
type NavigateInfo = {
|
|
47
|
-
to: string | number;
|
|
48
|
-
formMethod?: string;
|
|
49
|
-
};
|
|
50
|
-
/** The router instrumentations that {@link staleBuildReactRouter} adds. */
|
|
51
|
-
type RouterInstrumentations = {
|
|
52
|
-
navigate: (handler: () => Promise<unknown>, info: NavigateInfo) => Promise<void>;
|
|
53
|
-
};
|
|
54
|
-
/** The hooks that {@link staleBuildReactRouter} gives to React Router. */
|
|
55
|
-
type StaleBuildReactRouter = {
|
|
56
|
-
/** Give it to `HydratedRouter` as `unstable_fetch`. */
|
|
57
|
-
fetch: (request: Request, context: RouterFetchContext) => Promise<Response>;
|
|
58
|
-
/** Give it to `HydratedRouter` in `instrumentations`. */
|
|
59
|
-
instrumentation: {
|
|
60
|
-
router: (router: {
|
|
61
|
-
instrument: (instrumentations: RouterInstrumentations) => void;
|
|
62
|
-
}) => void;
|
|
63
|
-
};
|
|
64
|
-
/** Export it from `app/root.tsx` in `clientMiddleware`. */
|
|
65
|
-
middleware: <Result>(args: {
|
|
66
|
-
request: Request;
|
|
67
|
-
}, next: () => Promise<Result>) => Promise<Result>;
|
|
68
|
-
};
|
|
1
|
+
import { a as staleBuildReactRouter, i as StaleBuildReactRouter, n as RouterFetchContext, o as staleBuildTanStack, r as StaleBuildOptions, t as NavigationEvents } from "./stale-build-navigation-ypV7Ow4o.js";
|
|
69
2
|
/**
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
* visitor reads never reloads. Create it in a module that the client entry
|
|
73
|
-
* and `app/root.tsx` both import. It reads no browser state until React
|
|
74
|
-
* Router calls it, so the server can import it.
|
|
3
|
+
* The CSP nonce of the document, for the framework's render. It gives the
|
|
4
|
+
* same value on the server and in the browser, so the hydration matches.
|
|
75
5
|
*
|
|
76
|
-
* -
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
* or sends a data request. The root middleware does this also for a route
|
|
81
|
-
* with no loader.
|
|
82
|
-
* - A revalidation, a fetcher, an action, and the loaders after an action
|
|
83
|
-
* get their response. They only mark the tab, so the page that the visitor
|
|
84
|
-
* reads never reloads.
|
|
85
|
-
* - The router's blockers run first, and a canceled navigation never loads
|
|
86
|
-
* its target.
|
|
6
|
+
* - On the server, the nonce of the request that runs, from `requestContext()`.
|
|
7
|
+
* - In the browser, the nonce of the document's first element with a nonce.
|
|
8
|
+
* Why: React Router's `<HydratedRouter>` takes no nonce, so the app reads it
|
|
9
|
+
* from the document.
|
|
87
10
|
*
|
|
88
|
-
* It
|
|
89
|
-
*
|
|
11
|
+
* It gives `undefined` when the page has no nonce: with no
|
|
12
|
+
* `contentSecurityPolicy` plugin, during a prerender, and on a prerendered page.
|
|
13
|
+
* A bundler that resolves the `browser` condition, such as Vite for the
|
|
14
|
+
* client, gets a build with no server code.
|
|
90
15
|
*
|
|
91
16
|
* @example
|
|
92
|
-
*
|
|
93
|
-
* export const staleBuild = staleBuildReactRouter();
|
|
94
|
-
*
|
|
95
|
-
* // app/root.tsx
|
|
96
|
-
* export const clientMiddleware = [staleBuild.middleware];
|
|
97
|
-
*
|
|
98
|
-
* // app/entry.client.tsx
|
|
99
|
-
* startTransition(() => {
|
|
100
|
-
* hydrateRoot(
|
|
101
|
-
* document,
|
|
102
|
-
* <HydratedRouter
|
|
103
|
-
* unstable_fetch={staleBuild.fetch}
|
|
104
|
-
* instrumentations={[staleBuild.instrumentation]}
|
|
105
|
-
* />,
|
|
106
|
-
* );
|
|
107
|
-
* });
|
|
108
|
-
*/
|
|
109
|
-
export declare function staleBuildReactRouter(options?: StaleBuildOptions): StaleBuildReactRouter;
|
|
110
|
-
/**
|
|
111
|
-
* Moves an open TanStack Router tab to a new build at a navigation, so the
|
|
112
|
-
* old client code never renders data from the new server, and the page that
|
|
113
|
-
* the visitor reads never reloads. Call it with the router on the client.
|
|
114
|
-
*
|
|
115
|
-
* - A navigation runs from `onBeforeNavigate` to `onResolved`. The router
|
|
116
|
-
* moves history and runs its blockers before it.
|
|
117
|
-
* - When a GET response from a new build comes back while a navigation
|
|
118
|
-
* runs, such as from a server function in a loader, the browser loads the
|
|
119
|
-
* page as a document.
|
|
120
|
-
* - When the tab already knows of a new build, a navigation to a new path or
|
|
121
|
-
* query clears the router cache and loads the page as a document.
|
|
122
|
-
* - A request outside a navigation gets its response, and only marks the tab.
|
|
123
|
-
*
|
|
124
|
-
* It sends no request of its own and adds no wait. It needs `buildId()` in
|
|
125
|
-
* the server's pipeline, and it does nothing on a document with no build.
|
|
126
|
-
* It returns a function that stops it and gives back `fetch`. If the app
|
|
127
|
-
* wrapped `fetch` after it, the wrapper stays, and each request passes on.
|
|
128
|
-
*
|
|
129
|
-
* @example
|
|
130
|
-
* // src/router.tsx
|
|
131
|
-
* export function getRouter() {
|
|
132
|
-
* const router = createRouter({ routeTree });
|
|
133
|
-
* if (!router.isServer) {
|
|
134
|
-
* staleBuildTanStack(router);
|
|
135
|
-
* }
|
|
136
|
-
* return router;
|
|
137
|
-
* }
|
|
17
|
+
* <Scripts nonce={cspNonce()} />
|
|
138
18
|
*/
|
|
139
|
-
export declare function
|
|
140
|
-
export type
|
|
19
|
+
export declare function cspNonce(): string | undefined;
|
|
20
|
+
export { type NavigationEvents, type RouterFetchContext, type StaleBuildOptions, type StaleBuildReactRouter, staleBuildReactRouter, staleBuildTanStack };
|
|
141
21
|
//# sourceMappingURL=client.d.ts.map
|
package/dist/client.js
CHANGED
|
@@ -1,326 +1,27 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { t as requestContext } from "./request-context-BtQ87VYb.js";
|
|
2
|
+
import { n as staleBuildTanStack, r as documentNonce, t as staleBuildReactRouter } from "./stale-build-navigation-PnMLtTF8.js";
|
|
2
3
|
|
|
3
|
-
// src/client/
|
|
4
|
-
/** Whether `url` is on the origin of this page. */
|
|
5
|
-
function isOwn(url) {
|
|
6
|
-
return new URL(url, location.href).origin === location.origin;
|
|
7
|
-
}
|
|
8
|
-
/** The build in the `Server-Timing` of the first of `entries` that has one, from this origin only. */
|
|
9
|
-
function timingBuild(entries) {
|
|
10
|
-
return entries.filter((entry) => "serverTiming" in entry && isOwn(entry.name)).filter((entry) => entry.entryType !== "resource" || entry.redirectStart === 0).flatMap((entry) => entry.serverTiming).find((metric) => metric.name === BUILD_ID_METRIC)?.description;
|
|
11
|
-
}
|
|
12
|
-
/** The build in a `Server-Timing` header, as `buildId()` writes it. */
|
|
13
|
-
function headerBuild(header) {
|
|
14
|
-
const { quoted, token } = serverTimingMetrics(header).find((metric) => isBuildMetric(metric))?.match(/;\s*desc\s*=\s*(?:"(?<quoted>(?:[^"\\]|\\.)*)"|(?<token>[^;\s]*))/iu)?.groups ?? {};
|
|
15
|
-
return quoted?.replaceAll(/\\(?<char>.)/gu, "$<char>") ?? token;
|
|
16
|
-
}
|
|
17
|
-
/** The page of `url`: the router renders a new route for a new path or query, not for a new fragment. */
|
|
18
|
-
function pageOf(url) {
|
|
19
|
-
const { origin, pathname, search } = new URL(url, location.href);
|
|
20
|
-
return `${origin}${pathname}${search}`;
|
|
21
|
-
}
|
|
22
|
-
/** The page of a TanStack Router location, as {@link pageOf} reads a URL. */
|
|
23
|
-
function eventPage({ pathname, searchStr }) {
|
|
24
|
-
return `${pathname}${searchStr}`;
|
|
25
|
-
}
|
|
26
|
-
/** The URL of a `fetch` call. */
|
|
27
|
-
function urlOf(input) {
|
|
28
|
-
return input instanceof Request ? input.url : String(input);
|
|
29
|
-
}
|
|
30
|
-
/** The method of a `fetch` call. */
|
|
31
|
-
function methodOf(input, init) {
|
|
32
|
-
return (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
|
|
33
|
-
}
|
|
34
|
-
/** The page that a React Router data request loads: `/a.data` loads `/a`, and `/a/_.data` loads `/a/`. */
|
|
35
|
-
function targetOf(request) {
|
|
36
|
-
const url = new URL(request.url);
|
|
37
|
-
url.pathname = url.pathname.replace(/\/_\.data$/u, "/").replace(/\.data$/u, "");
|
|
38
|
-
url.searchParams.delete("_routes");
|
|
39
|
-
return url.href;
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* Reloads a document that the back/forward cache shows again. Why: Back can
|
|
43
|
-
* show the document that {@link loadDocument} left, with its router still in a
|
|
44
|
-
* navigation that never ends. Why one function: the browser adds it once.
|
|
45
|
-
*/
|
|
46
|
-
function reloadIfRestored(event) {
|
|
47
|
-
if (event.persisted) location.reload();
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
50
|
-
* Loads `target` as a document, so the old code never gets the new build's
|
|
51
|
-
* data. It returns a promise that never settles, because the page unloads.
|
|
52
|
-
*/
|
|
53
|
-
async function loadDocument(target, { response, navigationType } = {}) {
|
|
54
|
-
response?.body?.cancel().catch(() => void 0);
|
|
55
|
-
const isSamePage = pageOf(target) === pageOf(location.href);
|
|
56
|
-
const removesFragment = new URL(target, location.href).hash === "" && location.hash !== "";
|
|
57
|
-
addEventListener("pageshow", reloadIfRestored, { once: true });
|
|
58
|
-
if (navigationType === "POP" || isSamePage && !removesFragment) location.reload();
|
|
59
|
-
else if (navigationType === "REPLACE") location.replace(target);
|
|
60
|
-
else location.assign(target);
|
|
61
|
-
return new Promise(() => {});
|
|
62
|
-
}
|
|
63
|
-
/**
|
|
64
|
-
* Runs `clear` when `signal` aborts. Why: the router aborts a navigation when a
|
|
65
|
-
* newer one starts, such as after the visitor stays on the page at a leave prompt.
|
|
66
|
-
*/
|
|
67
|
-
function onAbort(signal, clear) {
|
|
68
|
-
signal.addEventListener("abort", clear, { once: true });
|
|
69
|
-
}
|
|
70
|
-
/** Reads the build of each response, and tells when the server runs a new build. */
|
|
71
|
-
function watchBuild({ header = BUILD_ID_HEADER, build, onNewBuild }) {
|
|
72
|
-
if (typeof document === "undefined") return null;
|
|
73
|
-
const current = build ?? timingBuild(performance.getEntriesByType("navigation"));
|
|
74
|
-
if (current == null) return null;
|
|
75
|
-
let stale = false;
|
|
76
|
-
const see = (served) => {
|
|
77
|
-
if (served == null || served === current || stale) return;
|
|
78
|
-
stale = true;
|
|
79
|
-
try {
|
|
80
|
-
onNewBuild?.(served);
|
|
81
|
-
} catch (error) {
|
|
82
|
-
reportError(error);
|
|
83
|
-
}
|
|
84
|
-
};
|
|
85
|
-
const observer = typeof PerformanceObserver === "function" ? new PerformanceObserver((list) => {
|
|
86
|
-
for (const entry of list.getEntries()) see(timingBuild([entry]));
|
|
87
|
-
}) : void 0;
|
|
88
|
-
observer?.observe({
|
|
89
|
-
type: "resource",
|
|
90
|
-
buffered: true
|
|
91
|
-
});
|
|
92
|
-
return {
|
|
93
|
-
isStale: () => stale,
|
|
94
|
-
/** Whether `response` comes from a new build of this origin. `url` is the URL of the request. */
|
|
95
|
-
isNew: (response, url) => {
|
|
96
|
-
const served = isOwn(response.url === "" ? url : response.url) ? response.headers.get(header) ?? headerBuild(response.headers.get("Server-Timing")) : null;
|
|
97
|
-
see(served);
|
|
98
|
-
return served != null && served !== current;
|
|
99
|
-
},
|
|
100
|
-
stop: () => observer?.disconnect()
|
|
101
|
-
};
|
|
102
|
-
}
|
|
103
|
-
/** The fragment of a `navigate` target, such as `#usage`, or `""`. */
|
|
104
|
-
function hashOf(to) {
|
|
105
|
-
return typeof to === "string" && to.includes("#") ? to.slice(to.indexOf("#")) : "";
|
|
106
|
-
}
|
|
107
|
-
/**
|
|
108
|
-
* Moves an open React Router tab to a new build at a navigation, so the old
|
|
109
|
-
* client code never renders data from the new server, and the page that the
|
|
110
|
-
* visitor reads never reloads. Create it in a module that the client entry
|
|
111
|
-
* and `app/root.tsx` both import. It reads no browser state until React
|
|
112
|
-
* Router calls it, so the server can import it.
|
|
113
|
-
*
|
|
114
|
-
* - When the data request of a navigation gets a response from a new build,
|
|
115
|
-
* the browser loads the target URL as a document.
|
|
116
|
-
* - When the tab already knows of a new build, a `navigate` call, such as a
|
|
117
|
-
* link click, loads its target as a document before the router renders it
|
|
118
|
-
* or sends a data request. The root middleware does this also for a route
|
|
119
|
-
* with no loader.
|
|
120
|
-
* - A revalidation, a fetcher, an action, and the loaders after an action
|
|
121
|
-
* get their response. They only mark the tab, so the page that the visitor
|
|
122
|
-
* reads never reloads.
|
|
123
|
-
* - The router's blockers run first, and a canceled navigation never loads
|
|
124
|
-
* its target.
|
|
125
|
-
*
|
|
126
|
-
* It sends no request of its own and adds no wait. It needs `buildId()` in
|
|
127
|
-
* the server's pipeline, and it does nothing on a document with no build.
|
|
128
|
-
*
|
|
129
|
-
* @example
|
|
130
|
-
* // app/stale-build.ts
|
|
131
|
-
* export const staleBuild = staleBuildReactRouter();
|
|
132
|
-
*
|
|
133
|
-
* // app/root.tsx
|
|
134
|
-
* export const clientMiddleware = [staleBuild.middleware];
|
|
135
|
-
*
|
|
136
|
-
* // app/entry.client.tsx
|
|
137
|
-
* startTransition(() => {
|
|
138
|
-
* hydrateRoot(
|
|
139
|
-
* document,
|
|
140
|
-
* <HydratedRouter
|
|
141
|
-
* unstable_fetch={staleBuild.fetch}
|
|
142
|
-
* instrumentations={[staleBuild.instrumentation]}
|
|
143
|
-
* />,
|
|
144
|
-
* );
|
|
145
|
-
* });
|
|
146
|
-
*/
|
|
147
|
-
function staleBuildReactRouter(options = {}) {
|
|
148
|
-
let watched;
|
|
149
|
-
const watch = () => {
|
|
150
|
-
watched ??= { watch: watchBuild(options) };
|
|
151
|
-
return watched.watch;
|
|
152
|
-
};
|
|
153
|
-
/**
|
|
154
|
-
* The path of the last action of a navigation, until its loaders run. The
|
|
155
|
-
* router revalidates the page with one or more loader requests after it.
|
|
156
|
-
* `loading` is true while they run.
|
|
157
|
-
*/
|
|
158
|
-
let action;
|
|
159
|
-
/** The target that the tab loads as a document now. */
|
|
160
|
-
let leaving;
|
|
161
|
-
/**
|
|
162
|
-
* The last `navigate` call. `claimed` is true when its first middleware call
|
|
163
|
-
* already ran, or when it is not a page load. `page` is the target page of
|
|
164
|
-
* that first call.
|
|
165
|
-
*/
|
|
166
|
-
let navigating;
|
|
167
|
-
const load = async (request, target, { response, navigationType } = {}) => {
|
|
168
|
-
if (leaving === target) {
|
|
169
|
-
response?.body?.cancel().catch(() => void 0);
|
|
170
|
-
return new Promise(() => {});
|
|
171
|
-
}
|
|
172
|
-
leaving = target;
|
|
173
|
-
onAbort(request.signal, () => {
|
|
174
|
-
if (leaving === target) leaving = void 0;
|
|
175
|
-
});
|
|
176
|
-
return loadDocument(target, {
|
|
177
|
-
response,
|
|
178
|
-
navigationType
|
|
179
|
-
});
|
|
180
|
-
};
|
|
181
|
-
return {
|
|
182
|
-
fetch: async (request, context) => {
|
|
183
|
-
const navigationType = context.type === "navigation" && context.fetcherKey == null ? context.navigationType : void 0;
|
|
184
|
-
const send = async () => {
|
|
185
|
-
const response = await globalThis.fetch(request);
|
|
186
|
-
return {
|
|
187
|
-
response,
|
|
188
|
-
isNew: watch()?.isNew(response, request.url) === true
|
|
189
|
-
};
|
|
190
|
-
};
|
|
191
|
-
if (watch() == null || navigationType == null) return (await send()).response;
|
|
192
|
-
const page = targetOf(request);
|
|
193
|
-
const target = page + (navigationType !== "POP" && navigating?.page === pageOf(page) ? navigating.hash : "");
|
|
194
|
-
const path = new URL(target).pathname;
|
|
195
|
-
const isAfterAction = request.method === "GET" && action?.path === path;
|
|
196
|
-
const isNavigation = () => request.method === "GET" && !isAfterAction && !request.signal.aborted;
|
|
197
|
-
if (isNavigation() && watch()?.isStale() === true) return load(request, target, { navigationType });
|
|
198
|
-
const { response, isNew } = await send();
|
|
199
|
-
if (!isNew || !isNavigation()) return response;
|
|
200
|
-
return load(request, target, {
|
|
201
|
-
response,
|
|
202
|
-
navigationType
|
|
203
|
-
});
|
|
204
|
-
},
|
|
205
|
-
instrumentation: { router: ({ instrument }) => {
|
|
206
|
-
watch();
|
|
207
|
-
instrument({ navigate: async (handler, { to, formMethod }) => {
|
|
208
|
-
const current = {
|
|
209
|
-
hash: hashOf(to),
|
|
210
|
-
claimed: typeof to === "number" || (formMethod ?? "GET").toUpperCase() !== "GET"
|
|
211
|
-
};
|
|
212
|
-
navigating = current;
|
|
213
|
-
await handler();
|
|
214
|
-
if (navigating === current && current.claimed) navigating = void 0;
|
|
215
|
-
} });
|
|
216
|
-
} },
|
|
217
|
-
middleware: async (args, next) => {
|
|
218
|
-
const { request, unstable_initiator: initiator, unstable_navigationType: navigationType } = args;
|
|
219
|
-
const current = navigating;
|
|
220
|
-
if (initiator === "navigation") {
|
|
221
|
-
const path = new URL(request.url).pathname;
|
|
222
|
-
const mark = action;
|
|
223
|
-
if (navigationType === "POP") action = void 0;
|
|
224
|
-
else if (request.method !== "GET") {
|
|
225
|
-
const started = {
|
|
226
|
-
path,
|
|
227
|
-
loading: false
|
|
228
|
-
};
|
|
229
|
-
action = started;
|
|
230
|
-
onAbort(request.signal, () => {
|
|
231
|
-
if (action === started) action = void 0;
|
|
232
|
-
});
|
|
233
|
-
return next();
|
|
234
|
-
} else if (mark?.path === path) {
|
|
235
|
-
mark.loading = true;
|
|
236
|
-
try {
|
|
237
|
-
return await next();
|
|
238
|
-
} finally {
|
|
239
|
-
if (action === mark) action = void 0;
|
|
240
|
-
}
|
|
241
|
-
} else if (mark?.loading === false) action = void 0;
|
|
242
|
-
}
|
|
243
|
-
if (initiator !== "navigation" || navigationType == null || navigationType === "POP" || current == null || current.claimed) return next();
|
|
244
|
-
current.claimed = true;
|
|
245
|
-
current.page = pageOf(request.url);
|
|
246
|
-
if (request.signal.aborted || watch()?.isStale() !== true || pageOf(request.url) === pageOf(location.href)) return next();
|
|
247
|
-
return load(request, request.url + current.hash, { navigationType });
|
|
248
|
-
}
|
|
249
|
-
};
|
|
250
|
-
}
|
|
4
|
+
// src/client/csp-nonce.ts
|
|
251
5
|
/**
|
|
252
|
-
*
|
|
253
|
-
*
|
|
254
|
-
* the visitor reads never reloads. Call it with the router on the client.
|
|
6
|
+
* The CSP nonce of the document, for the framework's render. It gives the
|
|
7
|
+
* same value on the server and in the browser, so the hydration matches.
|
|
255
8
|
*
|
|
256
|
-
* -
|
|
257
|
-
*
|
|
258
|
-
*
|
|
259
|
-
*
|
|
260
|
-
* page as a document.
|
|
261
|
-
* - When the tab already knows of a new build, a navigation to a new path or
|
|
262
|
-
* query clears the router cache and loads the page as a document.
|
|
263
|
-
* - A request outside a navigation gets its response, and only marks the tab.
|
|
9
|
+
* - On the server, the nonce of the request that runs, from `requestContext()`.
|
|
10
|
+
* - In the browser, the nonce of the document's first element with a nonce.
|
|
11
|
+
* Why: React Router's `<HydratedRouter>` takes no nonce, so the app reads it
|
|
12
|
+
* from the document.
|
|
264
13
|
*
|
|
265
|
-
* It
|
|
266
|
-
*
|
|
267
|
-
*
|
|
268
|
-
*
|
|
14
|
+
* It gives `undefined` when the page has no nonce: with no
|
|
15
|
+
* `contentSecurityPolicy` plugin, during a prerender, and on a prerendered page.
|
|
16
|
+
* A bundler that resolves the `browser` condition, such as Vite for the
|
|
17
|
+
* client, gets a build with no server code.
|
|
269
18
|
*
|
|
270
19
|
* @example
|
|
271
|
-
*
|
|
272
|
-
* export function getRouter() {
|
|
273
|
-
* const router = createRouter({ routeTree });
|
|
274
|
-
* if (!router.isServer) {
|
|
275
|
-
* staleBuildTanStack(router);
|
|
276
|
-
* }
|
|
277
|
-
* return router;
|
|
278
|
-
* }
|
|
20
|
+
* <Scripts nonce={cspNonce()} />
|
|
279
21
|
*/
|
|
280
|
-
function
|
|
281
|
-
|
|
282
|
-
if (watch == null) return () => {};
|
|
283
|
-
/** The navigation that runs now. `leaving` is true when it already loads its page as a document. */
|
|
284
|
-
let navigation;
|
|
285
|
-
const reload = async (current, response) => {
|
|
286
|
-
if (current.leaving) {
|
|
287
|
-
response?.body?.cancel().catch(() => void 0);
|
|
288
|
-
return new Promise(() => {});
|
|
289
|
-
}
|
|
290
|
-
current.leaving = true;
|
|
291
|
-
router.history.flush();
|
|
292
|
-
return loadDocument(location.href, { response });
|
|
293
|
-
};
|
|
294
|
-
const unsubscribe = [router.subscribe("onBeforeNavigate", ({ fromLocation, toLocation }) => {
|
|
295
|
-
navigation = void 0;
|
|
296
|
-
if (fromLocation == null || eventPage(fromLocation) === eventPage(toLocation)) return;
|
|
297
|
-
navigation = { leaving: false };
|
|
298
|
-
if (watch.isStale()) {
|
|
299
|
-
router.clearCache();
|
|
300
|
-
reload(navigation);
|
|
301
|
-
}
|
|
302
|
-
}), router.subscribe("onResolved", () => {
|
|
303
|
-
navigation = void 0;
|
|
304
|
-
})];
|
|
305
|
-
const send = globalThis.fetch;
|
|
306
|
-
let isStopped = false;
|
|
307
|
-
const patched = async (input, init) => {
|
|
308
|
-
if (isStopped) return send.call(globalThis, input, init);
|
|
309
|
-
const isGet = methodOf(input, init) === "GET";
|
|
310
|
-
if (isGet && navigation != null && watch.isStale()) return reload(navigation);
|
|
311
|
-
const response = await send.call(globalThis, input, init);
|
|
312
|
-
if (!watch.isNew(response, urlOf(input)) || !isGet || navigation == null) return response;
|
|
313
|
-
return reload(navigation, response);
|
|
314
|
-
};
|
|
315
|
-
globalThis.fetch = patched;
|
|
316
|
-
return () => {
|
|
317
|
-
for (const stop of unsubscribe) stop();
|
|
318
|
-
watch.stop();
|
|
319
|
-
isStopped = true;
|
|
320
|
-
navigation = void 0;
|
|
321
|
-
if (globalThis.fetch === patched) globalThis.fetch = send;
|
|
322
|
-
};
|
|
22
|
+
function cspNonce() {
|
|
23
|
+
return typeof document === "undefined" ? requestContext()?.cspNonce : documentNonce();
|
|
323
24
|
}
|
|
324
25
|
|
|
325
|
-
export { staleBuildReactRouter, staleBuildTanStack };
|
|
26
|
+
export { cspNonce, staleBuildReactRouter, staleBuildTanStack };
|
|
326
27
|
//# sourceMappingURL=client.js.map
|