akanjs 3.2.0-rc.15 → 3.2.0-rc.16
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/CHANGELOG.md +32 -0
- package/package.json +1 -1
- package/server/assetHeaders.ts +6 -0
- package/server/gateway/gatewayHttpProxy.ts +3 -3
- package/server/hmr/devHmrController.ts +10 -1
- package/server/rscClient.tsx +77 -193
- package/server/rscClientCache.ts +165 -0
- package/server/rscClientChunks.ts +38 -0
- package/server/rscClientPatch.ts +50 -1
- package/server/rscHttp.ts +13 -0
- package/server/rscPrefetchCache.ts +5 -1
- package/server/rscWorker.tsx +1 -1
- package/server/webAssetRoutes.ts +2 -2
- package/server/webRouteContext.ts +8 -2
- package/service/predefinedAdaptor/websocket.adaptor.ts +22 -6
- package/types/server/assetHeaders.d.ts +1 -0
- package/types/server/rscClientCache.d.ts +34 -0
- package/types/server/rscClientChunks.d.ts +1 -0
- package/types/server/rscClientPatch.d.ts +10 -0
- package/types/server/rscHttp.d.ts +1 -0
package/CHANGELOG.md
CHANGED
|
@@ -396,6 +396,22 @@
|
|
|
396
396
|
- e143263: The optional `happy-dom` and `@happy-dom/global-registrator` peers now ask for `^21.0.4`. Versions 17.0.0 through 21.0.3 compile a `<script type="module">` import alias into code unchecked, so a page loaded into a happy-dom window could run code on the host (GHSA-834v-8h66-3h79). UI tests register one through `akanjs/test/registerDom`; run `bun update happy-dom @happy-dom/global-registrator` in a workspace that pins an older one.
|
|
397
397
|
- e4f7876: A hidden field declared `.optional()` (`field.hidden(String).optional()`) is optional again in a service's `create<Model>` and `create<Model>Many` input, and in the document type `by()` makes of an input model or a scalar. It was typed there as a required, non-null value, though the model's own document already typed it optional, so a create that left it out needed a cast. A hidden field without `.optional()` stays required. Code that read such a field off a scalar's document as always present now handles its absence, as it already did on the model's document.
|
|
398
398
|
- cb0fd5b: Reading the client address from a forwarded header no longer stalls the server on a crafted hop. `IpLiteral.parse` matched a bracketed IPv6 hop with a pattern that backtracked quadratically, so an `X-Forwarded-For` or `X-Real-IP` entry of `[` and a long run of colons kept the event loop busy for about 100 ms per 16 KB of header, on every request that carried it. The bracket is now matched in linear time and the colon checked apart; every address parses as before.
|
|
399
|
+
- 24dcb1e: A lazily loaded chunk the server no longer serves now reloads its page once, in Chromium and Firefox.
|
|
400
|
+
|
|
401
|
+
- **Before:** a chunk loaded through `import()` (`lazy` from `akanjs/webkit`, `React.lazy`, or a dynamic import in a client component) that a deploy had removed failed to fetch, and the page stayed on its error. This happens to a tab left open across a deploy, and during a rolling deploy when the chunk's request reaches a replica of the other build.
|
|
402
|
+
- **Now:** when such a failure reaches the React root or rejects an `import()` that nothing catches, the client asks the server for the chunk again with a `HEAD` request. Only a 404 reloads the address the tab shows. A network failure, a blocked request or a 5xx leaves the page as before. The check runs only when all of these hold:
|
|
403
|
+
- the error names a chunk under this origin's `/_akan/client/`. Chromium names it, and so does Firefox from 115. Safari and other WebKit browsers do not, so they keep the old behaviour;
|
|
404
|
+
- the browser is online;
|
|
405
|
+
- the tab is not on the path a reload loaded, whether the reload was this fallback's, the chunk fallback's, the user's or `Reconnect`'s. A refresh or a shallow update keeps the tab on that path; after a page navigation to another path, the check runs again;
|
|
406
|
+
- no navigation to another page is under way, and no other document load either;
|
|
407
|
+
- the error is not one the Flight client's chunk loader already handled.
|
|
408
|
+
- **The reload is skipped if anything happened while the request was out:**
|
|
409
|
+
- any client navigation, including a shallow update, a refresh (the token-refresh timer's too) or a back or forward move;
|
|
410
|
+
- a `beforeunload` or `pagehide`, which a document load the router never sees fires (a plain link, a form post, `location.assign`).
|
|
411
|
+
- **Unlike a link failure, this covers the document's own page too,** since a deploy removes the chunks of the build the tab was opened on.
|
|
412
|
+
- **At most one reload per chain of loads.** The reloaded document never reloads from here while it stays on that path, so chunks that keep answering 404 there show their error after one reload, however many there are and whether or not the tab's storage holds. A further reload needs a page navigation to another path. Each chunk is also recorded in the per-tab list the chunk fallback uses.
|
|
413
|
+
- This applies to `akan build` output only.
|
|
414
|
+
|
|
399
415
|
- 256b6e3: A lazily loaded chunk that fails to link during a rolling deploy now reloads its page as a document.
|
|
400
416
|
|
|
401
417
|
- **Before:** the chunk fallback covered only the chunks the Flight client loads. A chunk loaded through `import()` (`lazy` from `akanjs/webkit`, `React.lazy`, or a dynamic import in a client component) on a page from another build could fail to link against the document's import map. With no error boundary above it, the page went blank; with one, it showed that boundary's fallback. Nothing loaded the page again.
|
|
@@ -460,6 +476,11 @@
|
|
|
460
476
|
- `akan preview` keeps an unprefixed path unprefixed under `"as-needed"`, except with `--csr`. The value reaches bundles as `AKAN_PUBLIC_LOCALE_PREFIX`, and the image env carries it when it is `"as-needed"`. `LocalePath` (`akanjs/common`) and a fourth `localePrefix` argument to `getPathInfo` build the same URLs in app code.
|
|
461
477
|
|
|
462
478
|
- dfc3564: A server stopped while its log control socket was still starting no longer leaves that socket listening. `akan logs` then found a socket nothing owned, and it kept serving a closed log hub until the process exited. Starts and stops on one control socket path now take turns, so a start whose log hub was closed meanwhile binds nothing or closes what it bound before a restart's open looks, and the restarted server gets its own socket. A socket that fails after binding is closed before the error surfaces. Stopping a control socket that never bound no longer unlinks the live socket of another server in the same runtime folder.
|
|
479
|
+
- 24dcb1e: A missing file under `/_akan/client/`, `/_akan/styles/`, `/_akan/fonts/` or `/_akan/dict/` now answers its 404 with `Cache-Control: no-store` and the asset security headers.
|
|
480
|
+
|
|
481
|
+
- **Before:** the 404 named no cache policy. A CDN in front of the app may cache such a 404 (Cloudflare keeps one on a `.js` path for 3 minutes), so during a rolling deploy one replica's 404 for a chunk was served for the replicas that have it.
|
|
482
|
+
- **Now:** both the app server and the gateway send `no-store`, so a CDN that honours it asks the origin again. CloudFront may still keep an error response for its error caching minimum TTL (10 seconds by default); lower that on the distribution if it matters.
|
|
483
|
+
|
|
463
484
|
- d12f556: `akanjs/signal`, `akanjs/client`, `akanjs/server`, `akanjs/constant` and `akanjs/store` now list every export by name instead of re-exporting whole files with `export *`. They export exactly the names they did before. A new export in one of those facets' files is no longer exported from `akanjs/<facet>` until its facet's `index.ts` names it. Files under `server/` and `client/native/` stay importable by their own subpath, as before.
|
|
464
485
|
- 9b5bcee: Every SSR page now loads 72K less framework JavaScript (22K less after Brotli).
|
|
465
486
|
|
|
@@ -507,6 +528,11 @@
|
|
|
507
528
|
|
|
508
529
|
The `infra/app` chart's readiness probe calls a new `readinessPath` value, `/_akan/app/health` unless set, because an image built with an earlier akanjs answers `/_akan/app/ready` with 404 and its pod would never become Ready. Set `readinessPath: /_akan/app/ready` once every image the chart deploys carries this release. The repository's own values set it, since its pipeline builds the image from the same commit as the chart. The startup and liveness probes stay on `/_akan/app/health`.
|
|
509
530
|
|
|
531
|
+
- cf5eeff: On the Redis WebSocket adaptor:
|
|
532
|
+
|
|
533
|
+
- **A PUBLISH a Redis ACL refuses (`NOPERM`) is dropped, not retried.** It used to be retried on a timer, and every event queued behind it waited with it, so one refused channel delayed all cross-server events. A refusal is logged as an error that names the family of channels whose events are being dropped (`<prefix>ws:room`, `<prefix>ws:change` or `<prefix>ws:broadcast`), at most once a minute per family. Other error replies are still retried.
|
|
534
|
+
- **A shutdown no longer logs the publisher's and subscriber's disconnect warnings.** A link that drops while the server runs still warns, and a dropped publisher now warns once rather than on every failed reconnect attempt.
|
|
535
|
+
|
|
510
536
|
- 7f0de74: On the Redis WebSocket adaptor, each room's events and each live-synced model's changes now go out on channels of their own, and a server subscribes only to those of the rooms and models it holds. Both used to go to every server of the app on one channel, `<prefix>ws:broadcast`, which servers keep using for one more release so that a rolling deploy loses nothing (see the note on rolling deploys).
|
|
511
537
|
|
|
512
538
|
- **A room's events** go out on one of 16,384 channels, picked by a hash of the room id (`<prefix>ws:room:<shard>`). A server subscribes to a shard while it holds a room on it.
|
|
@@ -554,7 +580,13 @@
|
|
|
554
580
|
- `invalidConfig`: a `transformEnv` callback returns something other than the env object.
|
|
555
581
|
- `notRegistered`: no WebSocket adaptor is registered.
|
|
556
582
|
|
|
583
|
+
- f8de6a7: A page whose server render streamed an error after its first byte is no longer replayed from the browser's navigation cache. Before, going back to it or following a link to it showed the same "This page could not be loaded." notice (or a `Load.*` section's failure) again without asking the server, and only "Try again" refetched. Now the next visit, a hover prefetch included, asks the server for the page. This covers the page a document loaded with, a page a navigation fetched, and, with `AKAN_PUBLIC_RSC_PARTIAL_COMMIT=1`, a cached patch. A not-found or redirect raised in the stream still counts as the page's answer and replays as before. A failure that recurs on every visit, such as a `Load.*` read refused for this viewer, now costs a server render on each visit. The server already renders such a page anew each time, since it never caches a render with a refused `Load.*` read. In development, a render error whose message is empty now carries the digest `AKAN_RENDER_ERROR` instead of an empty one.
|
|
584
|
+
- 1ed9f6a: With `AKAN_PUBLIC_RSC_PARTIAL_COMMIT=1`, a page reached by a patch is replayed from the browser's cache under any `#fragment`, as a page in the full-page cache already is: `/docs/x#a` and `/docs/x#b` now share one cached patch, and a link to another fragment of a page the patch cache would replay is not prefetched. A page that refuses prefetching (`.config({ prefetch: false })`) is no longer asked again after each full navigation: its 204 is kept for the prefetch lifetime under any page on screen, for the same account, as it already was with the flag off.
|
|
557
585
|
- b0ccf6f: The browser's RSC client now throws coded errors instead of bare `Error`s, so a caller can branch on `error.code`. A route the server has no page for is `routeNotFound` (404), as a missing WebSocket route already is. A response with no RSC payload is `rscFetchFailed` (502). A patch missing its parts, or a full fallback that answers with a patch, is `invalidRscResponse`, the code `rscClientFetch` already throws for the latter. The redirect marker, which only a log line receives, is `rscRedirectStarted`. Each error keeps its `name` and its message, except the fallback's message, which is now `[rscClient] fallback is a patch`. The error-code reference lists the new codes.
|
|
586
|
+
- 7836476: In development, an edit to any framework module that the browser's RSC client runs now fully reloads the open tab. That is `rscClient.tsx` and the `server/` modules it loads, such as `rscClientCache.ts`, `rscClientPatch.ts`, `rscClientFetch.ts`, `rscNavigationState.ts` and `rscPrefetchCache.ts`. Only `rscClient.tsx` did before, so an edit to one of the others refreshed the page in place and the tab kept running the old client code.
|
|
587
|
+
|
|
588
|
+
The RSC client's caches move from `rscClient.tsx` into `rscClientCache.ts`, and its patch commit into `rscClientPatch.ts`, with no change in behaviour.
|
|
589
|
+
|
|
558
590
|
- 9055634: Partial RSC commit can now patch a real page, and it patches cleanly. It is still off by default behind `AKAN_PUBLIC_RSC_PARTIAL_COMMIT=1`. With the flag on:
|
|
559
591
|
|
|
560
592
|
- **Which pages render their head through `AkanRouteHead`.** Every page whose head is plain `title`, `meta` and `link` tags now renders it through a client component instead of plain head tags. That way any page can be the one a patch starts from. Patches still only land on pages that set `.config({ rscPatchHeadSafe: true })`.
|
package/package.json
CHANGED
package/server/assetHeaders.ts
CHANGED
|
@@ -36,3 +36,9 @@ export const assetHeaders = ({ contentType, cacheControl, anyOrigin }: AssetHead
|
|
|
36
36
|
if (anyOrigin) headers.set("Access-Control-Allow-Origin", "*");
|
|
37
37
|
return applySecurityHeaders(headers);
|
|
38
38
|
};
|
|
39
|
+
|
|
40
|
+
export const missingAssetResponse = (): Response =>
|
|
41
|
+
new Response("Not Found", {
|
|
42
|
+
status: 404,
|
|
43
|
+
headers: assetHeaders({ contentType: "text/plain; charset=utf-8", cacheControl: "no-store" }),
|
|
44
|
+
});
|
|
@@ -2,7 +2,7 @@ import path from "node:path";
|
|
|
2
2
|
import type { Logger } from "akanjs/common";
|
|
3
3
|
import { isTraceEnabled } from "../../signal/trace";
|
|
4
4
|
import { AKAN_CHILD_HOST, makeAkanChildProxyHeaders } from "../akanAppHeaders";
|
|
5
|
-
import { type AssetHeaderOptions, assetHeaders } from "../assetHeaders";
|
|
5
|
+
import { type AssetHeaderOptions, assetHeaders, missingAssetResponse } from "../assetHeaders";
|
|
6
6
|
import { compressResponse, compressStreamResponse, encodedFileResponse } from "../contentEncoding";
|
|
7
7
|
import { ServerLimits } from "../routing/serverLimits";
|
|
8
8
|
import { resolveStaticPath } from "../staticPath";
|
|
@@ -56,9 +56,9 @@ export class GatewayHttpProxy {
|
|
|
56
56
|
path.join(this.#config.artifactDir, artifact.root),
|
|
57
57
|
url.pathname.slice(artifact.strip),
|
|
58
58
|
);
|
|
59
|
-
if (!filePath) return
|
|
59
|
+
if (!filePath) return missingAssetResponse();
|
|
60
60
|
const file = Bun.file(filePath);
|
|
61
|
-
if (!(await file.exists())) return
|
|
61
|
+
if (!(await file.exists())) return missingAssetResponse();
|
|
62
62
|
return this.#fileResponse(req, filePath, {
|
|
63
63
|
contentType: file.type || artifact.type,
|
|
64
64
|
cacheControl: "public, max-age=31536000, immutable",
|
|
@@ -22,6 +22,10 @@ import { type ChangeKind, type HmrMessage, type HmrWsData, HmrWsHub } from "./ws
|
|
|
22
22
|
|
|
23
23
|
export { isAkanRuntimeMetadataFile };
|
|
24
24
|
|
|
25
|
+
const BROWSER_RSC_MODULE_RE =
|
|
26
|
+
/^(?:rscClient\w*|rscHeadPatch|rscHttp|rscInlineStream|rscNavigationState|rscParkedRedirect|rscPrefetchCache|rscScrollRestoration|routeState|flightRowReader)\.tsx?$/;
|
|
27
|
+
const FRAMEWORK_SERVER_DIR = `${path.sep}pkgs${path.sep}akanjs${path.sep}server`;
|
|
28
|
+
|
|
25
29
|
export function manifestClientEntriesForFiles(
|
|
26
30
|
files: string[],
|
|
27
31
|
clientManifest: ClientManifest,
|
|
@@ -597,14 +601,19 @@ export class DevHmrController {
|
|
|
597
601
|
return this.#seedIndex.globalLayoutFiles.some((file) => normalized.has(path.resolve(file)));
|
|
598
602
|
}
|
|
599
603
|
|
|
604
|
+
static #isBrowserRscModule(file: string): boolean {
|
|
605
|
+
const resolved = path.resolve(file);
|
|
606
|
+
return path.dirname(resolved).endsWith(FRAMEWORK_SERVER_DIR) && BROWSER_RSC_MODULE_RE.test(path.basename(resolved));
|
|
607
|
+
}
|
|
608
|
+
|
|
600
609
|
#shouldFullReloadForFiles(files: string[], routeIds: string[] | undefined): boolean {
|
|
601
610
|
if (files.length === 0) return false;
|
|
602
611
|
const runtimeRoots = [
|
|
603
612
|
`${path.sep}pkgs${path.sep}akanjs${path.sep}server${path.sep}hmr${path.sep}`,
|
|
604
|
-
`${path.sep}pkgs${path.sep}akanjs${path.sep}server${path.sep}rscClient.tsx`,
|
|
605
613
|
`${path.sep}pkgs${path.sep}akanjs${path.sep}server${path.sep}ssrFromRscRenderer.tsx`,
|
|
606
614
|
];
|
|
607
615
|
if (files.some((file) => runtimeRoots.some((needle) => path.resolve(file).includes(needle)))) return true;
|
|
616
|
+
if (files.some((file) => DevHmrController.#isBrowserRscModule(file))) return true;
|
|
608
617
|
if (files.some((file) => path.basename(file).endsWith(".signal.ts"))) return true;
|
|
609
618
|
|
|
610
619
|
return (
|
package/server/rscClient.tsx
CHANGED
|
@@ -5,21 +5,18 @@ import { AkanError } from "../base/akanError";
|
|
|
5
5
|
import { csrLocation } from "../client/csrLocation";
|
|
6
6
|
import { DictionaryAsset } from "../client/dictionaryAsset";
|
|
7
7
|
import type {} from "../client/rscNavigation";
|
|
8
|
-
import { isAuthTokenKey } from "../common/authCookie";
|
|
9
|
-
import { CookieJar } from "../common/cookieJar";
|
|
10
|
-
import { StaleReads } from "../fetch/staleReads";
|
|
11
8
|
import {
|
|
12
9
|
AKAN_RSC_DICTIONARY_HEADER,
|
|
13
|
-
type AkanHeadSnapshotV1,
|
|
14
10
|
type AkanRouterStateV1,
|
|
15
|
-
type AkanRscPatchMetadata,
|
|
16
11
|
decodeAkanRouterState,
|
|
17
12
|
isAkanRscPartialCommitEnabled,
|
|
18
13
|
readAkanRouterStateResponseHeader,
|
|
19
14
|
} from "./routeState";
|
|
15
|
+
import { normalizeHref, pageKeyOf, RscClientCache, withoutHash } from "./rscClientCache";
|
|
20
16
|
import {
|
|
21
17
|
type ChunkNavigation,
|
|
22
18
|
claimChunkReload,
|
|
19
|
+
ifLazyChunkGone,
|
|
23
20
|
isBuildBundle,
|
|
24
21
|
isLinkFailure,
|
|
25
22
|
lazyLinkFailureKeyOf,
|
|
@@ -28,34 +25,23 @@ import {
|
|
|
28
25
|
recordChunksOf,
|
|
29
26
|
reportingRootErrors,
|
|
30
27
|
} from "./rscClientChunks";
|
|
31
|
-
import { fetchRscNavigationResponse
|
|
32
|
-
import { validateRscPatchForGuardedCommit } from "./rscClientPatch";
|
|
33
|
-
import {
|
|
34
|
-
|
|
35
|
-
getAkanHeadSnapshotPatchFailureReason,
|
|
36
|
-
prepareAkanHeadSnapshotPatch,
|
|
37
|
-
rollbackPreparedAkanHeadSnapshotPatch,
|
|
38
|
-
} from "./rscHeadPatch";
|
|
39
|
-
import { getRscPayloadStream, guardRscRedirectRows, type RscRedirectRow } from "./rscHttp";
|
|
28
|
+
import { fetchRscNavigationResponse } from "./rscClientFetch";
|
|
29
|
+
import { commitRscPatch, type RscPatchedResult, validateRscPatchForGuardedCommit } from "./rscClientPatch";
|
|
30
|
+
import { getAkanHeadSnapshotPatchFailureReason } from "./rscHeadPatch";
|
|
31
|
+
import { getRscPayloadStream, guardRscRedirectRows, type RscRedirectRow, watchRscErrorRows } from "./rscHttp";
|
|
40
32
|
import { createInitialRscStream } from "./rscInlineStream";
|
|
41
33
|
import {
|
|
42
34
|
type AkanSegmentCacheNode,
|
|
43
35
|
commitLatestRscNavigation,
|
|
44
36
|
createAkanSegmentCacheTree,
|
|
45
37
|
createRscNavigationCacheNode,
|
|
46
|
-
createRscPatchNavigationCacheNode,
|
|
47
38
|
deleteRscCacheEntryIfCurrent,
|
|
48
|
-
forgetRscPatchesOfLostBases,
|
|
49
39
|
observeRscNavigationNode,
|
|
50
40
|
type RscNavigationCacheNode,
|
|
51
|
-
type RscPatchNavigationCacheNode,
|
|
52
|
-
rememberRscCacheNode,
|
|
53
|
-
resolveCachedRscPatchNavigation,
|
|
54
41
|
} from "./rscNavigationState";
|
|
55
42
|
import { RscParkedRedirect } from "./rscParkedRedirect";
|
|
56
|
-
import { RscPrefetchCache } from "./rscPrefetchCache";
|
|
57
43
|
import { RscScrollRestoration } from "./rscScrollRestoration";
|
|
58
|
-
import {
|
|
44
|
+
import { resetAkanSegmentOutletPatches } from "./rscSegmentOutlet";
|
|
59
45
|
|
|
60
46
|
declare global {
|
|
61
47
|
var __AKAN_RSC_INITIAL_STATE__: string | undefined;
|
|
@@ -70,19 +56,16 @@ type RscThenable = Promise<ReactNode> & {
|
|
|
70
56
|
};
|
|
71
57
|
type RscCacheNode = RscNavigationCacheNode<RscThenable>;
|
|
72
58
|
type RscSegmentCacheNode = AkanSegmentCacheNode<RscThenable>;
|
|
59
|
+
type RscPatched = RscPatchedResult<RscThenable>;
|
|
73
60
|
type RscFetchResult =
|
|
74
61
|
| { type: "rsc"; node: RscCacheNode; notFound?: boolean }
|
|
75
|
-
|
|
|
76
|
-
type: "patched";
|
|
77
|
-
tree: RscSegmentCacheNode;
|
|
78
|
-
patchedNode: RscSegmentCacheNode;
|
|
79
|
-
patch: AkanRscPatchMetadata;
|
|
80
|
-
outletKey: string;
|
|
81
|
-
headSnapshot: AkanHeadSnapshotV1;
|
|
82
|
-
}
|
|
62
|
+
| RscPatched
|
|
83
63
|
| { type: "not-found" }
|
|
84
64
|
| { type: "redirected"; status?: number };
|
|
85
|
-
|
|
65
|
+
interface ScrollRequest {
|
|
66
|
+
scrollY: number;
|
|
67
|
+
hash?: string;
|
|
68
|
+
}
|
|
86
69
|
let documentNavigationFallbackInFlight = false;
|
|
87
70
|
|
|
88
71
|
class RscRedirectNavigationStarted extends AkanError<"rscRedirectStarted"> {
|
|
@@ -99,10 +82,6 @@ class RscRouteNotFound extends AkanError<"routeNotFound"> {
|
|
|
99
82
|
}
|
|
100
83
|
}
|
|
101
84
|
|
|
102
|
-
function normalizeHref(href: string): string {
|
|
103
|
-
return new URL(href, window.location.origin).href;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
85
|
function trackRscThenable(thenable: RscThenable): RscThenable {
|
|
107
86
|
if (thenable.status !== undefined) return thenable;
|
|
108
87
|
thenable.status = "pending";
|
|
@@ -120,7 +99,9 @@ function trackRscThenable(thenable: RscThenable): RscThenable {
|
|
|
120
99
|
}
|
|
121
100
|
|
|
122
101
|
function createRscThenable(stream: ReadableStream<Uint8Array>): RscThenable {
|
|
123
|
-
|
|
102
|
+
const watched = watchRscErrorRows(stream, () => caches.noteFailedRender(thenable));
|
|
103
|
+
const thenable = trackRscThenable(createFromReadableStream<ReactNode>(watched) as RscThenable);
|
|
104
|
+
return thenable;
|
|
124
105
|
}
|
|
125
106
|
|
|
126
107
|
window.addEventListener("pageshow", (event) => {
|
|
@@ -152,43 +133,26 @@ function navigateAfterRscRedirect(target: string, replace = true): void {
|
|
|
152
133
|
function commitRscPatchNavigation({
|
|
153
134
|
target,
|
|
154
135
|
patch,
|
|
136
|
+
fromCache,
|
|
155
137
|
replace,
|
|
156
138
|
requestScroll,
|
|
157
139
|
}: {
|
|
158
140
|
target: string;
|
|
159
|
-
patch:
|
|
141
|
+
patch: RscPatched;
|
|
142
|
+
fromCache: boolean;
|
|
160
143
|
replace?: boolean;
|
|
161
144
|
requestScroll?: () => void;
|
|
162
145
|
}): boolean {
|
|
163
|
-
const
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
let outletCommitted = false;
|
|
170
|
-
let headApplied = false;
|
|
171
|
-
startTransition(() => {
|
|
172
|
-
try {
|
|
173
|
-
headApplied = commitPreparedAkanHeadSnapshotPatch(preparedHeadPatch);
|
|
174
|
-
if (!headApplied) return;
|
|
175
|
-
outletCommitted = commitAkanSegmentOutletPatch(patch.outletKey, patchThenable);
|
|
176
|
-
if (!outletCommitted) {
|
|
177
|
-
rollbackPreparedAkanHeadSnapshotPatch(preparedHeadPatch);
|
|
178
|
-
return;
|
|
179
|
-
}
|
|
180
|
-
commitHistory(target, replace);
|
|
181
|
-
shownNode = null;
|
|
182
|
-
parkedRedirect.clear();
|
|
183
|
-
requestScroll?.();
|
|
184
|
-
} catch {
|
|
185
|
-
if (headApplied) rollbackPreparedAkanHeadSnapshotPatch(preparedHeadPatch);
|
|
186
|
-
if (outletCommitted) resetAkanSegmentOutletPatches();
|
|
187
|
-
headApplied = false;
|
|
188
|
-
outletCommitted = false;
|
|
189
|
-
}
|
|
146
|
+
const committed = commitRscPatch(target, patch, () => {
|
|
147
|
+
commitHistory(target, replace);
|
|
148
|
+
shownNode = null;
|
|
149
|
+
parkedRedirect.clear();
|
|
150
|
+
requestScroll?.();
|
|
190
151
|
});
|
|
191
|
-
|
|
152
|
+
if (!committed) return false;
|
|
153
|
+
currentCommitFromCache = fromCache;
|
|
154
|
+
rememberPatchedRouteState(patch.tree, patch.patchedNode);
|
|
155
|
+
return true;
|
|
192
156
|
}
|
|
193
157
|
|
|
194
158
|
function akanHistoryState(replace: boolean, shallow = false) {
|
|
@@ -200,8 +164,6 @@ function akanHistoryState(replace: boolean, shallow = false) {
|
|
|
200
164
|
let renderedHref = normalizeHref(window.location.href);
|
|
201
165
|
const scrollRestoration = new RscScrollRestoration();
|
|
202
166
|
const pathnameOf = (href: string) => new URL(href).pathname;
|
|
203
|
-
const withoutHash = (href: string | undefined) => href?.split("#", 1)[0];
|
|
204
|
-
const pageKeyOf = (href: string) => withoutHash(href) ?? href;
|
|
205
167
|
|
|
206
168
|
function commitHistory(target: string, replace: boolean | undefined) {
|
|
207
169
|
if (replace) csrLocation.replace(akanHistoryState(true), target);
|
|
@@ -293,7 +255,7 @@ async function fetchRsc(
|
|
|
293
255
|
const nodeRef: { current?: RscCacheNode } = {};
|
|
294
256
|
const handleRedirect = (redirect: RscRedirectRow) => {
|
|
295
257
|
const node = nodeRef.current;
|
|
296
|
-
if (node) deleteRscCacheEntryIfCurrent(
|
|
258
|
+
if (node) deleteRscCacheEntryIfCurrent(caches.pages, href, node);
|
|
297
259
|
const applies = shouldApplyNavigation();
|
|
298
260
|
|
|
299
261
|
if (!applies && node !== shownNode) return;
|
|
@@ -320,23 +282,13 @@ async function fetchRsc(
|
|
|
320
282
|
};
|
|
321
283
|
}
|
|
322
284
|
|
|
323
|
-
const
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
.join("; ");
|
|
330
|
-
const rscCache = new Map<string, RscCacheNode>();
|
|
331
|
-
const rscPatchCache = new Map<string, RscPatchNavigationCacheNode<RscThenable>>();
|
|
332
|
-
|
|
333
|
-
const prefetchBase = () => (isAkanRscPartialCommitEnabled() ? currentFullNode : null);
|
|
334
|
-
const rscPrefetchCache = new RscPrefetchCache<RscCacheNode | null>({
|
|
335
|
-
fetchResponse: (href, signal) => fetchRscPrefetchResponse(href, signal, currentRouterState),
|
|
336
|
-
baseOf: prefetchBase,
|
|
285
|
+
const caches = new RscClientCache<RscThenable>({
|
|
286
|
+
routerState: () => currentRouterState,
|
|
287
|
+
tree: () => currentSegmentTree,
|
|
288
|
+
base: () => currentFullNode,
|
|
289
|
+
navId: () => navigationSeq,
|
|
290
|
+
pendingTarget: () => pendingRequest?.target,
|
|
337
291
|
});
|
|
338
|
-
|
|
339
|
-
StaleReads.subscribe(() => rscPrefetchCache.clear());
|
|
340
292
|
const initialThenable = createRscThenable(createInitialRscStream());
|
|
341
293
|
const initialRouterState = decodeAkanRouterState(globalThis.__AKAN_RSC_INITIAL_STATE__);
|
|
342
294
|
const initialNode = createRscNavigationCacheNode({
|
|
@@ -344,7 +296,7 @@ const initialNode = createRscNavigationCacheNode({
|
|
|
344
296
|
thenable: initialThenable,
|
|
345
297
|
routerState: initialRouterState,
|
|
346
298
|
});
|
|
347
|
-
|
|
299
|
+
caches.pages.set(initialNode.href, initialNode);
|
|
348
300
|
let currentRouterState: AkanRouterStateV1 | null = initialRouterState;
|
|
349
301
|
let currentSegmentTree: RscSegmentCacheNode | null = createAkanSegmentCacheTree(initialNode);
|
|
350
302
|
let currentFullNode: RscCacheNode | null = initialNode;
|
|
@@ -355,7 +307,6 @@ let currentCommitFromCache = false;
|
|
|
355
307
|
let navigationSeq = 0;
|
|
356
308
|
let pendingRequest: { navId: number; controller: AbortController; target: string } | null = null;
|
|
357
309
|
let latestPageNavId = 0;
|
|
358
|
-
let cachedAuthCookies = readAuthCookies();
|
|
359
310
|
|
|
360
311
|
const stillOnItsEntry = (node: RscCacheNode) => {
|
|
361
312
|
const entry = (window.history.state as { __akanRouter?: { shallow?: boolean; rendered?: string } } | null)
|
|
@@ -418,11 +369,13 @@ function loadDocumentForChunkFailure(chunkId: string, navigation: ChunkNavigatio
|
|
|
418
369
|
else hardNavigateAfterRscFailure(normalizeHref(window.location.href), true, error);
|
|
419
370
|
}
|
|
420
371
|
|
|
421
|
-
function loadDocumentForLazyChunkFailure(error: unknown): void {
|
|
372
|
+
function loadDocumentForLazyChunkFailure(error: unknown, goneKey?: string): void {
|
|
422
373
|
const leaving =
|
|
423
374
|
!!pendingRequest && pendingRequest.navId !== refreshNavId && pendingRequest.target !== pageKeyOf(renderedHref);
|
|
424
|
-
if (
|
|
425
|
-
const
|
|
375
|
+
if (leaving || documentNavigationFallbackInFlight || !isBuildBundle()) return;
|
|
376
|
+
const navId = navigationSeq;
|
|
377
|
+
if (!goneKey) ifLazyChunkGone(error, (key) => navId === navigationSeq && loadDocumentForLazyChunkFailure(error, key));
|
|
378
|
+
const key = goneKey ?? (shownNode === initialNode ? null : lazyLinkFailureKeyOf(error));
|
|
426
379
|
if (key && navigator.onLine && claimChunkReload(key))
|
|
427
380
|
hardNavigateAfterRscFailure(normalizeHref(window.location.href), true, error);
|
|
428
381
|
}
|
|
@@ -433,7 +386,7 @@ function rememberCommittedRouteState(node: RscCacheNode): void {
|
|
|
433
386
|
currentFullNode = node;
|
|
434
387
|
shownNode = node;
|
|
435
388
|
parkedRedirect.clear();
|
|
436
|
-
|
|
389
|
+
caches.forgetPatchesOfLostBases(node);
|
|
437
390
|
currentRouterState = node.routerState;
|
|
438
391
|
currentSegmentTree = createAkanSegmentCacheTree(node);
|
|
439
392
|
currentCommitKind = "full";
|
|
@@ -455,89 +408,32 @@ function rememberPatchedRouteState(tree: RscSegmentCacheNode, patchedNode: RscSe
|
|
|
455
408
|
}
|
|
456
409
|
|
|
457
410
|
function forgetPagesOfAnotherAccount(): void {
|
|
458
|
-
|
|
459
|
-
if (authCookies === cachedAuthCookies) return;
|
|
460
|
-
cachedAuthCookies = authCookies;
|
|
461
|
-
rscCache.clear();
|
|
462
|
-
rscPatchCache.clear();
|
|
463
|
-
rscPrefetchCache.clear();
|
|
411
|
+
if (!caches.forgetAnotherAccount()) return;
|
|
464
412
|
|
|
465
413
|
currentRouterState = null;
|
|
466
414
|
currentSegmentTree = null;
|
|
467
415
|
}
|
|
468
416
|
|
|
469
|
-
|
|
470
|
-
const key = pageKeyOf(target);
|
|
471
|
-
return rscCache.get(target) ?? [...rscCache.values()].findLast((node) => pageKeyOf(node.href) === key);
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
function replayedPageOf(target: string): RscCacheNode | undefined {
|
|
475
|
-
const node = cachedPageOf(target);
|
|
476
|
-
if (node) rememberRscCacheNode(rscCache, node, MAX_RSC_CACHE_ENTRIES);
|
|
477
|
-
return node;
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
const cachedPatchReplayOf = (node: RscPatchNavigationCacheNode<RscThenable>, navId?: number) =>
|
|
481
|
-
resolveCachedRscPatchNavigation({
|
|
482
|
-
currentTree: currentSegmentTree,
|
|
483
|
-
currentBase: currentFullNode,
|
|
484
|
-
node,
|
|
485
|
-
partialCommitEnabled: isAkanRscPartialCommitEnabled(),
|
|
486
|
-
navId,
|
|
487
|
-
getCurrentNavId: () => navigationSeq,
|
|
488
|
-
});
|
|
489
|
-
|
|
490
|
-
function replayCachedPatch(target: string, navId: number, replace?: boolean, requestScroll?: () => void): boolean {
|
|
491
|
-
const cachedPatch = rscPatchCache.get(target);
|
|
492
|
-
if (!cachedPatch) return false;
|
|
493
|
-
const patchResult = cachedPatchReplayOf(cachedPatch, navId);
|
|
494
|
-
if (patchResult.status === "patched") {
|
|
495
|
-
const { tree, patchedNode, outletKey, headSnapshot } = patchResult;
|
|
496
|
-
const patch = { type: "patched" as const, tree, patchedNode, patch: cachedPatch.patch, outletKey, headSnapshot };
|
|
497
|
-
if (commitRscPatchNavigation({ target, patch, replace, requestScroll })) {
|
|
498
|
-
currentCommitFromCache = true;
|
|
499
|
-
rememberPatchedRouteState(tree, patchedNode);
|
|
500
|
-
rememberRscCacheNode(rscPatchCache, cachedPatch, MAX_RSC_CACHE_ENTRIES);
|
|
501
|
-
return true;
|
|
502
|
-
}
|
|
503
|
-
}
|
|
504
|
-
rscPatchCache.delete(target);
|
|
505
|
-
return false;
|
|
506
|
-
}
|
|
507
|
-
|
|
508
|
-
const isConstrainedNetwork = () => {
|
|
509
|
-
const connection = (navigator as Navigator & { connection?: { saveData?: boolean; effectiveType?: string } })
|
|
510
|
-
.connection;
|
|
511
|
-
return connection?.saveData === true || /2g$/.test(connection?.effectiveType ?? "");
|
|
512
|
-
};
|
|
513
|
-
|
|
514
|
-
globalThis.__AKAN_RSC_PREFETCH__ = (href, priority) => {
|
|
515
|
-
const none = () => undefined;
|
|
516
|
-
if (isConstrainedNetwork()) return none;
|
|
517
|
-
const target = normalizeHref(href);
|
|
518
|
-
const key = pageKeyOf(target);
|
|
519
|
-
if (new URL(target).origin !== window.location.origin || pendingRequest?.target === key) return none;
|
|
520
|
-
|
|
521
|
-
const authCookies = readAuthCookies();
|
|
522
|
-
const cachedPatch = rscPatchCache.get(target);
|
|
523
|
-
const replayable = cachedPageOf(target) || (!!cachedPatch && cachedPatchReplayOf(cachedPatch).status === "patched");
|
|
524
|
-
if (authCookies === cachedAuthCookies && replayable) return none;
|
|
525
|
-
return rscPrefetchCache.request(key, authCookies, priority, prefetchBase());
|
|
526
|
-
};
|
|
417
|
+
globalThis.__AKAN_RSC_PREFETCH__ = (href, priority) => caches.prefetch(href, priority);
|
|
527
418
|
|
|
528
419
|
function Root(): ReactNode {
|
|
529
420
|
const [thenable, setThenable] = useState<RscThenable>(initialThenable);
|
|
530
|
-
const [scrollRequest, setScrollRequest] = useState<
|
|
421
|
+
const [scrollRequest, setScrollRequest] = useState<ScrollRequest | null>(null);
|
|
531
422
|
|
|
532
423
|
useLayoutEffect(() => {
|
|
533
424
|
if (scrollRequest?.hash) scrollRestoration.scrollToHash(scrollRequest.hash, scrollRequest.scrollY);
|
|
534
425
|
else if (scrollRequest) scrollRestoration.scrollTo(scrollRequest.scrollY);
|
|
535
426
|
}, [scrollRequest]);
|
|
536
427
|
|
|
428
|
+
installCacheClear();
|
|
429
|
+
installRefresh(setThenable);
|
|
430
|
+
installNavigate(setThenable, setScrollRequest);
|
|
431
|
+
return use(thenable as Usable<ReactNode>);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
function installCacheClear(): void {
|
|
537
435
|
globalThis.__AKAN_RSC_CLEAR_CACHE__ = () => {
|
|
538
|
-
|
|
539
|
-
rscPatchCache.clear();
|
|
540
|
-
rscPrefetchCache.clear();
|
|
436
|
+
caches.clear();
|
|
541
437
|
if (currentCommitKind === "patch") {
|
|
542
438
|
void globalThis.__AKAN_RSC_REFRESH__?.();
|
|
543
439
|
return;
|
|
@@ -553,16 +449,16 @@ function Root(): ReactNode {
|
|
|
553
449
|
currentFullState.routeId === currentRouterState.routeId));
|
|
554
450
|
if (canRestoreFullNode) {
|
|
555
451
|
resetAkanSegmentOutletPatches();
|
|
556
|
-
|
|
452
|
+
caches.pages.set(currentFullNode.href, currentFullNode);
|
|
557
453
|
}
|
|
558
454
|
};
|
|
455
|
+
}
|
|
559
456
|
|
|
457
|
+
function installRefresh(setThenable: (thenable: RscThenable) => void): void {
|
|
560
458
|
globalThis.__AKAN_RSC_REFRESH__ = async (options = {}) => {
|
|
561
459
|
const navId = supersedeForRefresh();
|
|
562
460
|
const target = normalizeHref(window.location.href);
|
|
563
|
-
|
|
564
|
-
rscPatchCache.clear();
|
|
565
|
-
rscPrefetchCache.clear();
|
|
461
|
+
caches.clear();
|
|
566
462
|
try {
|
|
567
463
|
const next = await fetchRsc(target, {
|
|
568
464
|
...options,
|
|
@@ -579,7 +475,7 @@ function Root(): ReactNode {
|
|
|
579
475
|
}
|
|
580
476
|
if (next.type === "patched") return;
|
|
581
477
|
observeRscNavigationNode({
|
|
582
|
-
cache:
|
|
478
|
+
cache: caches.pages,
|
|
583
479
|
node: next.node,
|
|
584
480
|
navId,
|
|
585
481
|
getCurrentNavId: () => navigationSeq,
|
|
@@ -589,10 +485,10 @@ function Root(): ReactNode {
|
|
|
589
485
|
|
|
590
486
|
await next.node.thenable;
|
|
591
487
|
const committed = commitLatestRscNavigation({
|
|
592
|
-
cache: next.notFound ? undefined :
|
|
488
|
+
cache: next.notFound ? undefined : caches.pages,
|
|
593
489
|
href: target,
|
|
594
490
|
thenable: next.node,
|
|
595
|
-
maxEntries:
|
|
491
|
+
maxEntries: RscClientCache.maxEntries,
|
|
596
492
|
startTransition,
|
|
597
493
|
commitThenable: (node) => {
|
|
598
494
|
currentCommitFromCache = false;
|
|
@@ -613,14 +509,19 @@ function Root(): ReactNode {
|
|
|
613
509
|
settleRequestOf(navId);
|
|
614
510
|
}
|
|
615
511
|
};
|
|
512
|
+
}
|
|
616
513
|
|
|
514
|
+
function installNavigate(
|
|
515
|
+
setThenable: (thenable: RscThenable) => void,
|
|
516
|
+
setScrollRequest: (request: ScrollRequest) => void,
|
|
517
|
+
): void {
|
|
617
518
|
globalThis.__AKAN_RSC_NAVIGATE__ = async (href, options = {}) => {
|
|
618
519
|
if (options.shallow && navigateShallow(normalizeHref(href), options.replace)) {
|
|
619
520
|
supersedeKeepingPage();
|
|
620
521
|
return;
|
|
621
522
|
}
|
|
622
523
|
forgetPagesOfAnotherAccount();
|
|
623
|
-
|
|
524
|
+
caches.prefetches.prune();
|
|
624
525
|
const navId = supersedeForPageNavigation();
|
|
625
526
|
const target = normalizeHref(href);
|
|
626
527
|
const signal = requestSignalOf(navId, target);
|
|
@@ -631,13 +532,15 @@ function Root(): ReactNode {
|
|
|
631
532
|
const hash = options.scrollY === undefined ? new URL(target).hash : "";
|
|
632
533
|
const requestScroll = scrollY === undefined ? undefined : () => setScrollRequest({ scrollY, hash });
|
|
633
534
|
try {
|
|
634
|
-
const replayed = replayedPageOf(target);
|
|
535
|
+
const replayed = caches.replayedPageOf(target);
|
|
635
536
|
let nextNode = replayed;
|
|
636
537
|
let notFound = false;
|
|
637
538
|
let servedFromCache = !!nextNode;
|
|
638
539
|
if (!nextNode) {
|
|
639
|
-
|
|
640
|
-
|
|
540
|
+
const commitPatch = (patch: RscPatched, fromCache: boolean) =>
|
|
541
|
+
commitRscPatchNavigation({ target, patch, fromCache, replace: options.replace, requestScroll });
|
|
542
|
+
if (caches.replayPatch(target, navId, (patch) => commitPatch(patch, true))) return;
|
|
543
|
+
const taken = caches.takePrefetch(target, signal);
|
|
641
544
|
const prefetched = (await taken?.response) ?? undefined;
|
|
642
545
|
if (signal.aborted) return;
|
|
643
546
|
servedFromCache = !!prefetched && !taken?.fresh;
|
|
@@ -652,28 +555,11 @@ function Root(): ReactNode {
|
|
|
652
555
|
if (fetched.type === "not-found") throw new RscRouteNotFound(target);
|
|
653
556
|
if (fetched.type === "patched") {
|
|
654
557
|
if (navId !== navigationSeq) return;
|
|
655
|
-
if (
|
|
656
|
-
|
|
657
|
-
target,
|
|
658
|
-
patch: fetched,
|
|
659
|
-
replace: options.replace,
|
|
660
|
-
requestScroll,
|
|
661
|
-
})
|
|
662
|
-
) {
|
|
663
|
-
currentCommitFromCache = servedFromCache;
|
|
664
|
-
rememberPatchedRouteState(fetched.tree, fetched.patchedNode);
|
|
665
|
-
const patchCacheNode = createRscPatchNavigationCacheNode({
|
|
666
|
-
href: target,
|
|
667
|
-
patch: fetched.patch,
|
|
668
|
-
patchedNode: fetched.patchedNode,
|
|
669
|
-
outletKey: fetched.outletKey,
|
|
670
|
-
headSnapshot: fetched.headSnapshot,
|
|
671
|
-
base: currentFullNode,
|
|
672
|
-
});
|
|
673
|
-
if (patchCacheNode) rememberRscCacheNode(rscPatchCache, patchCacheNode, MAX_RSC_CACHE_ENTRIES);
|
|
558
|
+
if (commitPatch(fetched, servedFromCache)) {
|
|
559
|
+
caches.rememberPatch(target, fetched);
|
|
674
560
|
return;
|
|
675
561
|
}
|
|
676
|
-
|
|
562
|
+
caches.forgetPatch(target);
|
|
677
563
|
const fallback = await fetchRsc(target, {
|
|
678
564
|
replaceOnRedirect,
|
|
679
565
|
sendRouterState: false,
|
|
@@ -692,7 +578,7 @@ function Root(): ReactNode {
|
|
|
692
578
|
}
|
|
693
579
|
}
|
|
694
580
|
observeRscNavigationNode({
|
|
695
|
-
cache:
|
|
581
|
+
cache: caches.pages,
|
|
696
582
|
node: nextNode,
|
|
697
583
|
navId,
|
|
698
584
|
getCurrentNavId: () => navigationSeq,
|
|
@@ -703,10 +589,10 @@ function Root(): ReactNode {
|
|
|
703
589
|
await nextNode.thenable;
|
|
704
590
|
|
|
705
591
|
const committed = commitLatestRscNavigation({
|
|
706
|
-
cache: notFound || replayed ? undefined :
|
|
592
|
+
cache: notFound || replayed ? undefined : caches.pages,
|
|
707
593
|
href: target,
|
|
708
594
|
thenable: nextNode,
|
|
709
|
-
maxEntries:
|
|
595
|
+
maxEntries: RscClientCache.maxEntries,
|
|
710
596
|
startTransition,
|
|
711
597
|
commitThenable: (node) => {
|
|
712
598
|
currentCommitFromCache = servedFromCache;
|
|
@@ -733,8 +619,6 @@ function Root(): ReactNode {
|
|
|
733
619
|
settleRequestOf(navId);
|
|
734
620
|
}
|
|
735
621
|
};
|
|
736
|
-
|
|
737
|
-
return use(thenable as Usable<ReactNode>);
|
|
738
622
|
}
|
|
739
623
|
|
|
740
624
|
window.addEventListener("popstate", (event) => {
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import type { PrefetchPriority } from "../client/rscNavigation";
|
|
2
|
+
import { isAuthTokenKey } from "../common/authCookie";
|
|
3
|
+
import { CookieJar } from "../common/cookieJar";
|
|
4
|
+
import { StaleReads } from "../fetch/staleReads";
|
|
5
|
+
import { type AkanRouterStateV1, isAkanRscPartialCommitEnabled } from "./routeState";
|
|
6
|
+
import { fetchRscPrefetchResponse } from "./rscClientFetch";
|
|
7
|
+
import type { RscPatchedResult } from "./rscClientPatch";
|
|
8
|
+
import {
|
|
9
|
+
type AkanSegmentCacheNode,
|
|
10
|
+
createRscPatchNavigationCacheNode,
|
|
11
|
+
forgetRscPatchesOfLostBases,
|
|
12
|
+
type RscNavigationCacheNode,
|
|
13
|
+
type RscPatchNavigationCacheNode,
|
|
14
|
+
rememberRscCacheEntry,
|
|
15
|
+
rememberRscCacheNode,
|
|
16
|
+
resolveCachedRscPatchNavigation,
|
|
17
|
+
} from "./rscNavigationState";
|
|
18
|
+
import { RscPrefetchCache } from "./rscPrefetchCache";
|
|
19
|
+
|
|
20
|
+
export const normalizeHref = (href: string): string => new URL(href, window.location.origin).href;
|
|
21
|
+
export const withoutHash = (href: string | undefined) => href?.split("#", 1)[0];
|
|
22
|
+
export const pageKeyOf = (href: string) => withoutHash(href) ?? href;
|
|
23
|
+
|
|
24
|
+
const readAuthCookies = () =>
|
|
25
|
+
CookieJar.parse(document.cookie)
|
|
26
|
+
.entries()
|
|
27
|
+
.filter(({ name }) => isAuthTokenKey(name))
|
|
28
|
+
.map(({ name, value }) => `${name}=${value}`)
|
|
29
|
+
.sort((a, b) => a.localeCompare(b))
|
|
30
|
+
.join("; ");
|
|
31
|
+
|
|
32
|
+
const isConstrainedNetwork = () => {
|
|
33
|
+
const connection = (navigator as Navigator & { connection?: { saveData?: boolean; effectiveType?: string } })
|
|
34
|
+
.connection;
|
|
35
|
+
return connection?.saveData === true || /2g$/.test(connection?.effectiveType ?? "");
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
interface RscClientScreen<T> {
|
|
39
|
+
routerState: () => AkanRouterStateV1 | null;
|
|
40
|
+
tree: () => AkanSegmentCacheNode<T> | null;
|
|
41
|
+
base: () => RscNavigationCacheNode<T> | null;
|
|
42
|
+
navId: () => number;
|
|
43
|
+
pendingTarget: () => string | undefined;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export class RscClientCache<T extends object> {
|
|
47
|
+
static readonly maxEntries = 32;
|
|
48
|
+
readonly pages = new Map<string, RscNavigationCacheNode<T>>();
|
|
49
|
+
readonly prefetches: RscPrefetchCache<RscNavigationCacheNode<T> | null>;
|
|
50
|
+
#patches = new Map<string, RscPatchNavigationCacheNode<T>>();
|
|
51
|
+
#failed = new WeakSet<T>();
|
|
52
|
+
#account = readAuthCookies();
|
|
53
|
+
#screen: RscClientScreen<T>;
|
|
54
|
+
|
|
55
|
+
constructor(screen: RscClientScreen<T>) {
|
|
56
|
+
this.#screen = screen;
|
|
57
|
+
this.prefetches = new RscPrefetchCache({
|
|
58
|
+
fetchResponse: (href, signal) => fetchRscPrefetchResponse(href, signal, screen.routerState()),
|
|
59
|
+
baseOf: () => this.#prefetchBase(),
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
StaleReads.subscribe(() => this.prefetches.clear());
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
clear(): void {
|
|
66
|
+
this.pages.clear();
|
|
67
|
+
this.#patches.clear();
|
|
68
|
+
this.prefetches.clear();
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
forgetAnotherAccount(): boolean {
|
|
72
|
+
const account = readAuthCookies();
|
|
73
|
+
if (account === this.#account) return false;
|
|
74
|
+
this.#account = account;
|
|
75
|
+
this.clear();
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
noteFailedRender(thenable: T): void {
|
|
80
|
+
this.#failed.add(thenable);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
pageOf(target: string): RscNavigationCacheNode<T> | undefined {
|
|
84
|
+
const key = pageKeyOf(target);
|
|
85
|
+
const exact = this.pages.get(target);
|
|
86
|
+
if (exact && !this.#failed.has(exact.thenable)) return exact;
|
|
87
|
+
return [...this.pages.values()].findLast(
|
|
88
|
+
(node) => pageKeyOf(node.href) === key && !this.#failed.has(node.thenable),
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
replayedPageOf(target: string): RscNavigationCacheNode<T> | undefined {
|
|
93
|
+
const node = this.pageOf(target);
|
|
94
|
+
if (node) rememberRscCacheNode(this.pages, node, RscClientCache.maxEntries);
|
|
95
|
+
return node;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
replayPatch(target: string, navId: number, commit: (patch: RscPatchedResult<T>) => boolean): boolean {
|
|
99
|
+
const key = pageKeyOf(target);
|
|
100
|
+
const cachedPatch = this.#patchOf(key);
|
|
101
|
+
if (!cachedPatch) return false;
|
|
102
|
+
const patchResult = this.#patchReplayOf(cachedPatch, navId);
|
|
103
|
+
if (patchResult.status === "patched") {
|
|
104
|
+
const { tree, patchedNode, outletKey, headSnapshot } = patchResult;
|
|
105
|
+
if (commit({ type: "patched", tree, patchedNode, patch: cachedPatch.patch, outletKey, headSnapshot })) {
|
|
106
|
+
rememberRscCacheEntry(this.#patches, key, cachedPatch, RscClientCache.maxEntries);
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
this.#patches.delete(key);
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
rememberPatch(href: string, { patch, patchedNode, outletKey, headSnapshot }: RscPatchedResult<T>): void {
|
|
115
|
+
const base = this.#screen.base();
|
|
116
|
+
const node = createRscPatchNavigationCacheNode({ href, patch, patchedNode, outletKey, headSnapshot, base });
|
|
117
|
+
if (node) rememberRscCacheEntry(this.#patches, pageKeyOf(href), node, RscClientCache.maxEntries);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
forgetPatch(target: string): void {
|
|
121
|
+
this.#patches.delete(pageKeyOf(target));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
forgetPatchesOfLostBases(base: RscNavigationCacheNode<T>): void {
|
|
125
|
+
forgetRscPatchesOfLostBases(this.#patches, this.pages, base);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
takePrefetch(target: string, signal: AbortSignal) {
|
|
129
|
+
return this.prefetches.take(pageKeyOf(target), this.#account, signal, this.#prefetchBase());
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
prefetch(href: string, priority?: PrefetchPriority): () => void {
|
|
133
|
+
const none = () => undefined;
|
|
134
|
+
if (isConstrainedNetwork()) return none;
|
|
135
|
+
const target = normalizeHref(href);
|
|
136
|
+
const key = pageKeyOf(target);
|
|
137
|
+
if (new URL(target).origin !== window.location.origin || this.#screen.pendingTarget() === key) return none;
|
|
138
|
+
|
|
139
|
+
const account = readAuthCookies();
|
|
140
|
+
const cachedPatch = this.#patchOf(key);
|
|
141
|
+
const replayable = this.pageOf(target) || (!!cachedPatch && this.#patchReplayOf(cachedPatch).status === "patched");
|
|
142
|
+
if (account === this.#account && replayable) return none;
|
|
143
|
+
return this.prefetches.request(key, account, priority, this.#prefetchBase());
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
#patchOf(key: string): RscPatchNavigationCacheNode<T> | undefined {
|
|
147
|
+
const node = this.#patches.get(key);
|
|
148
|
+
return node && !this.#failed.has(node.thenable) ? node : undefined;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
#prefetchBase(): RscNavigationCacheNode<T> | null {
|
|
152
|
+
return isAkanRscPartialCommitEnabled() ? this.#screen.base() : null;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
#patchReplayOf(node: RscPatchNavigationCacheNode<T>, navId?: number) {
|
|
156
|
+
return resolveCachedRscPatchNavigation({
|
|
157
|
+
currentTree: this.#screen.tree(),
|
|
158
|
+
currentBase: this.#screen.base(),
|
|
159
|
+
node,
|
|
160
|
+
partialCommitEnabled: isAkanRscPartialCommitEnabled(),
|
|
161
|
+
navId,
|
|
162
|
+
getCurrentNavId: this.#screen.navId,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
}
|
|
@@ -49,6 +49,44 @@ export const noteChunkLoadFailure = (error: unknown): void => {
|
|
|
49
49
|
export const lazyLinkFailureKeyOf = (error: unknown): string | null =>
|
|
50
50
|
error instanceof Error && isLinkFailure(error) && !chunkLoadFailures.has(error) ? `import() ${error.message}` : null;
|
|
51
51
|
|
|
52
|
+
const fetchFailure = /^(?:Failed to fetch dynamically imported module|error loading dynamically imported module): \S+$/;
|
|
53
|
+
const ownChunkUrlOf = (message: string): string | null => {
|
|
54
|
+
if (!fetchFailure.test(message)) return null;
|
|
55
|
+
try {
|
|
56
|
+
const url = new URL(message.slice(message.lastIndexOf(" ") + 1));
|
|
57
|
+
return url.origin === window.location.origin && url.pathname.startsWith("/_akan/client/") ? url.href : null;
|
|
58
|
+
} catch {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const reloadedPathname = window.location.pathname;
|
|
64
|
+
const onReloadedPath = () =>
|
|
65
|
+
window.location.pathname === reloadedPathname &&
|
|
66
|
+
(performance.getEntriesByType("navigation")[0] as PerformanceNavigationTiming | undefined)?.type === "reload";
|
|
67
|
+
|
|
68
|
+
const unloadEvents = ["beforeunload", "pagehide"] as const;
|
|
69
|
+
|
|
70
|
+
export const ifLazyChunkGone = (error: unknown, then: (key: string) => void): void => {
|
|
71
|
+
if (!(error instanceof TypeError) || chunkLoadFailures.has(error) || !navigator.onLine) return;
|
|
72
|
+
const url = ownChunkUrlOf(error.message);
|
|
73
|
+
if (!url || onReloadedPath()) return;
|
|
74
|
+
let unloading = false;
|
|
75
|
+
const unload = () => {
|
|
76
|
+
unloading = true;
|
|
77
|
+
};
|
|
78
|
+
for (const type of unloadEvents) window.addEventListener(type, unload);
|
|
79
|
+
void fetch(url, { method: "HEAD", cache: "no-store" })
|
|
80
|
+
.then(
|
|
81
|
+
({ status }) => status === 404,
|
|
82
|
+
() => false,
|
|
83
|
+
)
|
|
84
|
+
.then((gone) => {
|
|
85
|
+
for (const type of unloadEvents) window.removeEventListener(type, unload);
|
|
86
|
+
if (gone && !unloading) then(`import() ${error.message}`);
|
|
87
|
+
});
|
|
88
|
+
};
|
|
89
|
+
|
|
52
90
|
const reportGlobalError = (error: unknown): void => {
|
|
53
91
|
if (typeof reportError === "function") {
|
|
54
92
|
reportError(error);
|
package/server/rscClientPatch.ts
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
|
+
import { type ReactNode, startTransition } from "react";
|
|
2
|
+
import { AkanError } from "../base/akanError";
|
|
1
3
|
import { mapFlightLineRows } from "./flightRowReader";
|
|
2
4
|
import { type AkanHeadSnapshotV1, type AkanRscPatchMetadata, readAkanRouterStateResponseHeader } from "./routeState";
|
|
5
|
+
import {
|
|
6
|
+
commitPreparedAkanHeadSnapshotPatch,
|
|
7
|
+
prepareAkanHeadSnapshotPatch,
|
|
8
|
+
rollbackPreparedAkanHeadSnapshotPatch,
|
|
9
|
+
} from "./rscHeadPatch";
|
|
3
10
|
import { getRscPayloadStream } from "./rscHttp";
|
|
4
11
|
import {
|
|
5
12
|
type AkanSegmentCacheNode,
|
|
@@ -7,11 +14,20 @@ import {
|
|
|
7
14
|
type AkanSegmentPatchResult,
|
|
8
15
|
applyAkanSegmentCachePatch,
|
|
9
16
|
} from "./rscNavigationState";
|
|
10
|
-
import { hasAkanSegmentOutlet } from "./rscSegmentOutlet";
|
|
17
|
+
import { commitAkanSegmentOutletPatch, hasAkanSegmentOutlet, resetAkanSegmentOutletPatches } from "./rscSegmentOutlet";
|
|
11
18
|
|
|
12
19
|
const RSC_PATCH_REDIRECT_ROW_RE = /^[0-9a-z]+:E\{[^\n]*"digest":"AKAN_REDIRECT(?:;[^"]*)?"[^\n]*\}\n?$/;
|
|
13
20
|
const RSC_PATCH_ERROR_ROW_RE = /^[0-9a-z]+:E\{[^\n]*\}\n?$/;
|
|
14
21
|
|
|
22
|
+
export interface RscPatchedResult<T> {
|
|
23
|
+
type: "patched";
|
|
24
|
+
tree: AkanSegmentCacheNode<T>;
|
|
25
|
+
patchedNode: AkanSegmentCacheNode<T>;
|
|
26
|
+
patch: AkanRscPatchMetadata;
|
|
27
|
+
outletKey: string;
|
|
28
|
+
headSnapshot: AkanHeadSnapshotV1;
|
|
29
|
+
}
|
|
30
|
+
|
|
15
31
|
interface ValidateRscSegmentPatchInput<T extends PromiseLike<unknown>> {
|
|
16
32
|
href: string;
|
|
17
33
|
response: Response;
|
|
@@ -110,3 +126,36 @@ export async function validateRscPatchForGuardedCommit<T extends PromiseLike<unk
|
|
|
110
126
|
if (!hasAkanSegmentOutlet(patchResult.outletKey)) return { status: "rejected", reason: "outlet-missing" };
|
|
111
127
|
return { ...patchResult, headSnapshot: input.patch.headSnapshot };
|
|
112
128
|
}
|
|
129
|
+
|
|
130
|
+
export function commitRscPatch<T extends PromiseLike<ReactNode>>(
|
|
131
|
+
target: string,
|
|
132
|
+
patch: RscPatchedResult<T>,
|
|
133
|
+
onCommitted: () => void,
|
|
134
|
+
): boolean {
|
|
135
|
+
const patchThenable = patch.patchedNode.thenable;
|
|
136
|
+
if (!patchThenable)
|
|
137
|
+
throw new AkanError("invalidRscResponse", "[rscClient] validated RSC patch is missing a thenable");
|
|
138
|
+
const preparedHeadPatch = prepareAkanHeadSnapshotPatch(patch.headSnapshot, target);
|
|
139
|
+
if (!preparedHeadPatch) return false;
|
|
140
|
+
|
|
141
|
+
let outletCommitted = false;
|
|
142
|
+
let headApplied = false;
|
|
143
|
+
startTransition(() => {
|
|
144
|
+
try {
|
|
145
|
+
headApplied = commitPreparedAkanHeadSnapshotPatch(preparedHeadPatch);
|
|
146
|
+
if (!headApplied) return;
|
|
147
|
+
outletCommitted = commitAkanSegmentOutletPatch(patch.outletKey, patchThenable);
|
|
148
|
+
if (!outletCommitted) {
|
|
149
|
+
rollbackPreparedAkanHeadSnapshotPatch(preparedHeadPatch);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
onCommitted();
|
|
153
|
+
} catch {
|
|
154
|
+
if (headApplied) rollbackPreparedAkanHeadSnapshotPatch(preparedHeadPatch);
|
|
155
|
+
if (outletCommitted) resetAkanSegmentOutletPatches();
|
|
156
|
+
headApplied = false;
|
|
157
|
+
outletCommitted = false;
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
return outletCommitted && headApplied;
|
|
161
|
+
}
|
package/server/rscHttp.ts
CHANGED
|
@@ -2,6 +2,8 @@ import { mapFlightLineRows } from "./flightRowReader";
|
|
|
2
2
|
|
|
3
3
|
export const RSC_CONTENT_TYPE = "text/x-component; charset=utf-8";
|
|
4
4
|
const RSC_REDIRECT_ROW_RE = /^([0-9a-z]+):E(\{[^\n]*"digest":"AKAN_REDIRECT(?:;[^"]*)?"[^\n]*\})(\n?)$/;
|
|
5
|
+
const RSC_UNFAILED_ERROR_ROW_RE =
|
|
6
|
+
/^[0-9a-z]+:E\{[^\n]*"digest":"(?:AKAN_NOT_FOUND|AKAN_REDIRECT(?:;[^"]*)?)?"[^\n]*\}\n?$/;
|
|
5
7
|
const AKAN_REDIRECT_DIGEST_PREFIX = "AKAN_REDIRECT";
|
|
6
8
|
|
|
7
9
|
export interface RscRedirectRow {
|
|
@@ -92,3 +94,14 @@ export function guardRscRedirectRows(
|
|
|
92
94
|
return encoder.encode(`${redirect.rowId}:null${row[row.byteLength - 1] === 10 ? "\n" : ""}`);
|
|
93
95
|
});
|
|
94
96
|
}
|
|
97
|
+
|
|
98
|
+
export function watchRscErrorRows(stream: ReadableStream<Uint8Array>, onError: () => void): ReadableStream<Uint8Array> {
|
|
99
|
+
const decoder = new TextDecoder();
|
|
100
|
+
let failed = false;
|
|
101
|
+
return mapFlightLineRows(stream, (row, tag) => {
|
|
102
|
+
if (tag !== "E" || failed || RSC_UNFAILED_ERROR_ROW_RE.test(decoder.decode(row))) return row;
|
|
103
|
+
failed = true;
|
|
104
|
+
onError();
|
|
105
|
+
return row;
|
|
106
|
+
});
|
|
107
|
+
}
|
|
@@ -4,6 +4,7 @@ interface RscPrefetchEntry<B> {
|
|
|
4
4
|
account: string;
|
|
5
5
|
base: B | undefined;
|
|
6
6
|
whole: boolean;
|
|
7
|
+
optedOut: boolean;
|
|
7
8
|
startedAt: number;
|
|
8
9
|
controller: AbortController;
|
|
9
10
|
response: Promise<Response | null>;
|
|
@@ -75,7 +76,8 @@ export class RscPrefetchCache<B = undefined> {
|
|
|
75
76
|
|
|
76
77
|
has(href: string, account: string, base?: B) {
|
|
77
78
|
const entry = this.#entries.get(href);
|
|
78
|
-
|
|
79
|
+
|
|
80
|
+
return !!entry && entry.account === account && (entry.base === base || entry.optedOut) && !this.#isStale(entry);
|
|
79
81
|
}
|
|
80
82
|
|
|
81
83
|
request(href: string, account: string, priority: PrefetchPriority = "high", base?: B): () => void {
|
|
@@ -177,6 +179,7 @@ export class RscPrefetchCache<B = undefined> {
|
|
|
177
179
|
account,
|
|
178
180
|
base: this.#baseOf?.(),
|
|
179
181
|
whole: false,
|
|
182
|
+
optedOut: false,
|
|
180
183
|
startedAt: this.#now(),
|
|
181
184
|
controller,
|
|
182
185
|
response: this.#fetchResponse(href, controller.signal).then(
|
|
@@ -184,6 +187,7 @@ export class RscPrefetchCache<B = undefined> {
|
|
|
184
187
|
entry.whole = response.headers.get("X-Akan-Rsc-Partial") !== "patch";
|
|
185
188
|
|
|
186
189
|
const optedOut = response.status === 204;
|
|
190
|
+
entry.optedOut = optedOut;
|
|
187
191
|
|
|
188
192
|
const usable = response.ok || response.status === 404;
|
|
189
193
|
if (controller.signal.aborted || optedOut || !usable || !response.body) {
|
package/server/rscWorker.tsx
CHANGED
|
@@ -854,7 +854,7 @@ export class RscRenderer {
|
|
|
854
854
|
const message = error instanceof Error ? error.message : String(error);
|
|
855
855
|
const description = error instanceof Error ? (error.stack ?? message) : message;
|
|
856
856
|
const opaque = process.env.NODE_ENV === "production";
|
|
857
|
-
const digest = opaque ? crypto.randomUUID().slice(0, 8) : message;
|
|
857
|
+
const digest = opaque ? crypto.randomUUID().slice(0, 8) : message || "AKAN_RENDER_ERROR";
|
|
858
858
|
const scope = `${pathname ? ` path=${pathname}` : ""}${opaque ? ` digest=${digest}` : ""}`;
|
|
859
859
|
if (RscRenderer.#isExpectedRequestAbort(error)) this.#logger.debug(`[rsc] render aborted${scope}: ${description}`);
|
|
860
860
|
else this.#logger.error(`[rsc] render failed${scope}: ${description}`);
|
package/server/webAssetRoutes.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { assetHeaders } from "./assetHeaders";
|
|
1
|
+
import { assetHeaders, missingAssetResponse } from "./assetHeaders";
|
|
2
2
|
import type { ImageOptimizer } from "./imageOptimizer";
|
|
3
3
|
import { resolveStaticPath } from "./staticPath";
|
|
4
4
|
import type { HttpRoutes } from "./types";
|
|
@@ -25,7 +25,7 @@ export class WebAssetRoutes {
|
|
|
25
25
|
stats.staticAsset += 1;
|
|
26
26
|
const url = new URL(req.url);
|
|
27
27
|
const filePath = resolveStaticPath(clientOutputDir, url.pathname.slice(clientServePrefix.length + 1));
|
|
28
|
-
if (!filePath) return
|
|
28
|
+
if (!filePath) return missingAssetResponse();
|
|
29
29
|
return WebRouteContext.fileResponse(req, filePath, {
|
|
30
30
|
contentType: Bun.file(filePath).type || "application/javascript",
|
|
31
31
|
cacheControl: prodMode ? "public, max-age=31536000, immutable" : "no-store",
|
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import { CookieJar, getBasePathFromPathname, Logger, parseAkanI18nEnv, RequestLocale } from "akanjs/common";
|
|
3
3
|
import { type MergedManifest, type RouteClientCache, type RouteSeedIndex, RouteSeedIndexStore } from "./artifact";
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
type AssetHeaderOptions,
|
|
6
|
+
applySecurityHeaders,
|
|
7
|
+
assetHeaders,
|
|
8
|
+
missingAssetResponse,
|
|
9
|
+
strictTransportSecurity,
|
|
10
|
+
} from "./assetHeaders";
|
|
5
11
|
import { getClientFacingOrigin, resolveHtmlCacheControl } from "./cachePolicy";
|
|
6
12
|
import { encodedFileResponse, isCompressibleContentType, matchesIfNoneMatch, varyOnEncoding } from "./contentEncoding";
|
|
7
13
|
import { HMR_CLIENT_SCRIPT } from "./hmr/clientScript";
|
|
@@ -201,7 +207,7 @@ export class WebRouteContext {
|
|
|
201
207
|
static async fileResponse(req: Request, filePath: string, options: AssetHeaderOptions): Promise<Response> {
|
|
202
208
|
const headers = assetHeaders(options);
|
|
203
209
|
const file = Bun.file(filePath);
|
|
204
|
-
if (!(await file.exists())) return
|
|
210
|
+
if (!(await file.exists())) return missingAssetResponse();
|
|
205
211
|
const stat = fs.statSync(filePath);
|
|
206
212
|
const lastModifiedMs = Math.floor(stat.mtimeMs / 1000) * 1000;
|
|
207
213
|
const etag = `W/"${stat.size.toString(16)}-${lastModifiedMs.toString(16)}"`;
|
|
@@ -111,7 +111,7 @@ export class WebSocketRedisAdaptor
|
|
|
111
111
|
/** Whether the subscriber has ever been up, so the first `ready` is a start rather than a recovery. */
|
|
112
112
|
#subscriberStarted = false;
|
|
113
113
|
readonly #lossWaiters = new Set<() => void>();
|
|
114
|
-
#
|
|
114
|
+
readonly #lastLogged = new Map<string, number>();
|
|
115
115
|
|
|
116
116
|
get #legacyChannel() {
|
|
117
117
|
return `${this.channelPrefix}ws:broadcast`;
|
|
@@ -134,6 +134,7 @@ export class WebSocketRedisAdaptor
|
|
|
134
134
|
void this.#flushBuffer();
|
|
135
135
|
});
|
|
136
136
|
this.publisher.on("close", () => {
|
|
137
|
+
if (!this.#publisherReady) return;
|
|
137
138
|
this.#publisherReady = false;
|
|
138
139
|
this.logger.warn("Publisher disconnected, buffering messages...");
|
|
139
140
|
});
|
|
@@ -172,19 +173,19 @@ export class WebSocketRedisAdaptor
|
|
|
172
173
|
|
|
173
174
|
override async onDestroy() {
|
|
174
175
|
this.#loseSubscriber();
|
|
176
|
+
this.#subscriberReady = false;
|
|
175
177
|
this.subscriber.disconnect();
|
|
176
178
|
if (this.publisher) {
|
|
177
179
|
this.#cancelRetry();
|
|
178
180
|
|
|
179
181
|
if (this.#publisherReady) await Promise.race([this.#flushBuffer(), this.#closed()]);
|
|
180
182
|
this.#cancelRetry();
|
|
183
|
+
this.#publisherReady = false;
|
|
181
184
|
this.publisher.disconnect();
|
|
182
185
|
}
|
|
183
186
|
this.#eventHandler = null;
|
|
184
187
|
this.#changeHandler = null;
|
|
185
188
|
this.#recoveryHandler = null;
|
|
186
|
-
this.#publisherReady = false;
|
|
187
|
-
this.#subscriberReady = false;
|
|
188
189
|
this.#rooms.clear();
|
|
189
190
|
this.#socketRooms.clear();
|
|
190
191
|
this.#channels.clear();
|
|
@@ -244,6 +245,7 @@ export class WebSocketRedisAdaptor
|
|
|
244
245
|
return;
|
|
245
246
|
}
|
|
246
247
|
this.publisher.publish(buffered.channel, buffered.message).catch((err: Error) => {
|
|
248
|
+
if (this.#refused(buffered, err)) return;
|
|
247
249
|
this.logger.warn(`Publish failed, buffering: ${err.message}`);
|
|
248
250
|
this.#requeue([buffered]);
|
|
249
251
|
void this.#flushBuffer();
|
|
@@ -408,11 +410,11 @@ export class WebSocketRedisAdaptor
|
|
|
408
410
|
#unpack(buffer: Buffer): { kind: number; origin: string; roomId: string; payload: Buffer } | null {
|
|
409
411
|
if (buffer.length < 6) return null;
|
|
410
412
|
if (buffer.readUInt8(0) !== WebSocketRedisAdaptor.#version) {
|
|
411
|
-
if (!this.#
|
|
413
|
+
if (!this.#lastLogged.has("version"))
|
|
412
414
|
this.logger.warn(
|
|
413
415
|
`Dropping cross-server events of envelope version ${buffer.readUInt8(0)}; this server reads 1`,
|
|
414
416
|
);
|
|
415
|
-
this.#
|
|
417
|
+
this.#lastLogged.set("version", Date.now());
|
|
416
418
|
return null;
|
|
417
419
|
}
|
|
418
420
|
const kind = buffer.readUInt8(1);
|
|
@@ -474,7 +476,10 @@ export class WebSocketRedisAdaptor
|
|
|
474
476
|
const results = await Promise.allSettled(
|
|
475
477
|
batch.map((buffered) => this.publisher.publish(buffered.channel, buffered.message)),
|
|
476
478
|
);
|
|
477
|
-
const failed = batch.filter((
|
|
479
|
+
const failed = batch.filter((buffered, idx) => {
|
|
480
|
+
const result = results[idx];
|
|
481
|
+
return result.status === "rejected" && !this.#refused(buffered, result.reason);
|
|
482
|
+
});
|
|
478
483
|
if (!failed.length) {
|
|
479
484
|
this.#retries = 0;
|
|
480
485
|
continue;
|
|
@@ -489,6 +494,17 @@ export class WebSocketRedisAdaptor
|
|
|
489
494
|
}
|
|
490
495
|
}
|
|
491
496
|
|
|
497
|
+
#refused({ channel }: BufferedMessage, err: unknown) {
|
|
498
|
+
if (!(err instanceof Error) || !err.message.startsWith("NOPERM")) return false;
|
|
499
|
+
|
|
500
|
+
const family = channel === this.#legacyChannel ? channel : channel.slice(0, channel.lastIndexOf(":"));
|
|
501
|
+
const now = Date.now();
|
|
502
|
+
if (now - (this.#lastLogged.get(family) ?? Number.NEGATIVE_INFINITY) < 60_000) return true;
|
|
503
|
+
this.#lastLogged.set(family, now);
|
|
504
|
+
this.logger.error(`Redis refused a PUBLISH to ${channel}; events on ${family} are being dropped: ${err.message}`);
|
|
505
|
+
return true;
|
|
506
|
+
}
|
|
507
|
+
|
|
492
508
|
#retryLater() {
|
|
493
509
|
this.#retries += 1;
|
|
494
510
|
this.#retryTimer = setTimeout(
|
|
@@ -12,3 +12,4 @@ export declare const htmlContentSecurityPolicy: (raw?: string | undefined) => st
|
|
|
12
12
|
export declare const DEFAULT_STRICT_TRANSPORT_SECURITY = "max-age=31536000";
|
|
13
13
|
export declare const strictTransportSecurity: (raw?: string | undefined) => string | null;
|
|
14
14
|
export declare const assetHeaders: ({ contentType, cacheControl, anyOrigin }: AssetHeaderOptions) => Headers;
|
|
15
|
+
export declare const missingAssetResponse: () => Response;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { PrefetchPriority } from "../client/rscNavigation.d.ts";
|
|
2
|
+
import { type AkanRouterStateV1 } from "./routeState.d.ts";
|
|
3
|
+
import type { RscPatchedResult } from "./rscClientPatch.d.ts";
|
|
4
|
+
import { type AkanSegmentCacheNode, type RscNavigationCacheNode } from "./rscNavigationState.d.ts";
|
|
5
|
+
import { RscPrefetchCache } from "./rscPrefetchCache.d.ts";
|
|
6
|
+
export declare const normalizeHref: (href: string) => string;
|
|
7
|
+
export declare const withoutHash: (href: string | undefined) => string | undefined;
|
|
8
|
+
export declare const pageKeyOf: (href: string) => string;
|
|
9
|
+
interface RscClientScreen<T> {
|
|
10
|
+
routerState: () => AkanRouterStateV1 | null;
|
|
11
|
+
tree: () => AkanSegmentCacheNode<T> | null;
|
|
12
|
+
base: () => RscNavigationCacheNode<T> | null;
|
|
13
|
+
navId: () => number;
|
|
14
|
+
pendingTarget: () => string | undefined;
|
|
15
|
+
}
|
|
16
|
+
export declare class RscClientCache<T extends object> {
|
|
17
|
+
#private;
|
|
18
|
+
static readonly maxEntries = 32;
|
|
19
|
+
readonly pages: Map<string, RscNavigationCacheNode<T>>;
|
|
20
|
+
readonly prefetches: RscPrefetchCache<RscNavigationCacheNode<T> | null>;
|
|
21
|
+
constructor(screen: RscClientScreen<T>);
|
|
22
|
+
clear(): void;
|
|
23
|
+
forgetAnotherAccount(): boolean;
|
|
24
|
+
noteFailedRender(thenable: T): void;
|
|
25
|
+
pageOf(target: string): RscNavigationCacheNode<T> | undefined;
|
|
26
|
+
replayedPageOf(target: string): RscNavigationCacheNode<T> | undefined;
|
|
27
|
+
replayPatch(target: string, navId: number, commit: (patch: RscPatchedResult<T>) => boolean): boolean;
|
|
28
|
+
rememberPatch(href: string, { patch, patchedNode, outletKey, headSnapshot }: RscPatchedResult<T>): void;
|
|
29
|
+
forgetPatch(target: string): void;
|
|
30
|
+
forgetPatchesOfLostBases(base: RscNavigationCacheNode<T>): void;
|
|
31
|
+
takePrefetch(target: string, signal: AbortSignal): import("./rscPrefetchCache.d.ts").RscPrefetched | null;
|
|
32
|
+
prefetch(href: string, priority?: PrefetchPriority): () => void;
|
|
33
|
+
}
|
|
34
|
+
export {};
|
|
@@ -8,6 +8,7 @@ export declare const navigationOfChunk: (chunkId: string) => ChunkNavigation | u
|
|
|
8
8
|
export declare const isLinkFailure: (error: unknown) => boolean;
|
|
9
9
|
export declare const noteChunkLoadFailure: (error: unknown) => void;
|
|
10
10
|
export declare const lazyLinkFailureKeyOf: (error: unknown) => string | null;
|
|
11
|
+
export declare const ifLazyChunkGone: (error: unknown, then: (key: string) => void) => void;
|
|
11
12
|
export declare const reportingRootErrors: (onError: (error: unknown) => void) => {
|
|
12
13
|
onCaughtError: (error: unknown) => void;
|
|
13
14
|
onUncaughtError: (error: unknown) => void;
|
|
@@ -1,5 +1,14 @@
|
|
|
1
|
+
import { type ReactNode } from "react";
|
|
1
2
|
import { type AkanHeadSnapshotV1, type AkanRscPatchMetadata } from "./routeState.d.ts";
|
|
2
3
|
import { type AkanSegmentCacheNode, type AkanSegmentPatchFailureReason, type AkanSegmentPatchResult } from "./rscNavigationState.d.ts";
|
|
4
|
+
export interface RscPatchedResult<T> {
|
|
5
|
+
type: "patched";
|
|
6
|
+
tree: AkanSegmentCacheNode<T>;
|
|
7
|
+
patchedNode: AkanSegmentCacheNode<T>;
|
|
8
|
+
patch: AkanRscPatchMetadata;
|
|
9
|
+
outletKey: string;
|
|
10
|
+
headSnapshot: AkanHeadSnapshotV1;
|
|
11
|
+
}
|
|
3
12
|
interface ValidateRscSegmentPatchInput<T extends PromiseLike<unknown>> {
|
|
4
13
|
href: string;
|
|
5
14
|
response: Response;
|
|
@@ -18,4 +27,5 @@ export declare function validateRscSegmentPatch<T extends PromiseLike<unknown>>(
|
|
|
18
27
|
export declare function validateRscPatchForGuardedCommit<T extends PromiseLike<unknown>>({ partialCommitEnabled, ...input }: ValidateRscSegmentPatchInput<T> & {
|
|
19
28
|
partialCommitEnabled: boolean;
|
|
20
29
|
}): Promise<AkanSegmentPatchResult<T>>;
|
|
30
|
+
export declare function commitRscPatch<T extends PromiseLike<ReactNode>>(target: string, patch: RscPatchedResult<T>, onCommitted: () => void): boolean;
|
|
21
31
|
export {};
|
|
@@ -17,3 +17,4 @@ export declare function concatBytes(left: Uint8Array, right: Uint8Array): Uint8A
|
|
|
17
17
|
export declare function guardRscRedirectRows(stream: ReadableStream<Uint8Array>, options?: {
|
|
18
18
|
onRedirect?: (redirect: RscRedirectRow) => void;
|
|
19
19
|
}): ReadableStream<Uint8Array>;
|
|
20
|
+
export declare function watchRscErrorRows(stream: ReadableStream<Uint8Array>, onError: () => void): ReadableStream<Uint8Array>;
|