akanjs 3.2.0-rc.7 → 3.2.0-rc.8
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 +90 -0
- package/common/failureCode.ts +18 -0
- package/common/index.ts +3 -0
- package/common/mcpFailure.ts +9 -0
- package/common/restartSchedule.ts +55 -0
- package/fetch/client/httpClient.ts +12 -2
- package/package.json +1 -1
- package/server/akanApp.ts +21 -21
- package/server/mcp/McpDispatcher.ts +20 -5
- package/server/mcp/McpPages.ts +21 -6
- package/server/mcp/McpRouter.ts +51 -22
- package/server/rscClient.tsx +47 -71
- package/server/rscClientChunks.ts +29 -0
- package/server/rscInlineStream.ts +34 -0
- package/server/rscNavigationState.ts +21 -1
- package/server/rscWorkerHost.ts +9 -13
- package/service/documentStoreError.ts +16 -0
- package/service/index.ts +3 -0
- package/service/injectError.ts +5 -0
- package/service/injectInfo.ts +28 -17
- package/service/insightQueryError.ts +19 -0
- package/service/liveSyncHub.ts +5 -2
- package/service/predefinedAdaptor/anthropicLlm.ts +2 -0
- package/service/predefinedAdaptor/cache.adaptor.ts +3 -2
- package/service/predefinedAdaptor/compress.adaptor.ts +5 -1
- package/service/predefinedAdaptor/database.adaptor.ts +3 -1
- package/service/predefinedAdaptor/documentTransfer.ts +2 -1
- package/service/predefinedAdaptor/insightQuery.ts +35 -11
- package/service/predefinedAdaptor/llm.adaptor.ts +2 -0
- package/service/predefinedAdaptor/openaiDialect.ts +2 -0
- package/service/predefinedAdaptor/searchIndex.ts +5 -1
- package/service/predefinedAdaptor/sql/PostgresInsightSession.ts +15 -5
- package/service/predefinedAdaptor/sql/QueryCompiler.ts +29 -13
- package/service/predefinedAdaptor/sql/RawDocumentTable.ts +20 -8
- package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +45 -94
- package/service/predefinedAdaptor/sql/SqliteInsightSession.ts +2 -1
- package/service/predefinedAdaptor/sql/UpdateCompiler.ts +6 -2
- package/service/predefinedAdaptor/sql/fieldValues.ts +74 -0
- package/service/predefinedAdaptor/sql/search/fts5.ts +4 -1
- package/service/predefinedAdaptor/sql/search/postgres.ts +6 -2
- package/service/predefinedAdaptor/sql/values.ts +8 -4
- package/service/predefinedAdaptor/storage.adaptor.ts +7 -3
- package/service/serve.ts +3 -2
- package/service/serviceModule.ts +2 -2
- package/signal/SignalFailure.ts +8 -1
- package/signal/endpointErrorContract.ts +9 -2
- package/signal/endpointInfo.ts +6 -5
- package/signal/exception.ts +1 -0
- package/signal/index.ts +2 -0
- package/signal/internalInfo.ts +6 -4
- package/signal/mcp/Msg.ts +23 -10
- package/signal/mcp/index.ts +1 -0
- package/signal/mcp/promptError.ts +9 -0
- package/signal/middleware.ts +5 -5
- package/signal/serializer/fetch.serializer.ts +2 -1
- package/signal/signalContext.ts +15 -16
- package/signal/signalContractError.ts +10 -0
- package/signal/signalDeclarationError.ts +13 -0
- package/signal/signalRegistry.ts +3 -1
- package/signal/slice.ts +2 -1
- package/signal/sliceInfo.ts +12 -9
- package/types/common/failureCode.d.ts +6 -0
- package/types/common/index.d.ts +3 -0
- package/types/common/mcpFailure.d.ts +6 -0
- package/types/common/restartSchedule.d.ts +16 -0
- package/types/server/logging/rotatingLogWriter.d.ts +1 -1
- package/types/server/mcp/McpPages.d.ts +2 -1
- package/types/server/rscClient.d.ts +0 -5
- package/types/server/rscClientChunks.d.ts +6 -0
- package/types/server/rscInlineStream.d.ts +9 -0
- package/types/server/rscNavigationState.d.ts +8 -3
- package/types/service/documentStoreError.d.ts +7 -0
- package/types/service/index.d.ts +3 -0
- package/types/service/injectError.d.ts +4 -0
- package/types/service/insightQueryError.d.ts +9 -0
- package/types/service/predefinedAdaptor/llm.adaptor.d.ts +2 -0
- package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +0 -5
- package/types/service/predefinedAdaptor/sql/fieldValues.d.ts +5 -0
- package/types/service/serviceModule.d.ts +1 -1
- package/types/signal/SignalFailure.d.ts +1 -0
- package/types/signal/exception.d.ts +1 -0
- package/types/signal/index.d.ts +2 -0
- package/types/signal/mcp/index.d.ts +1 -0
- package/types/signal/mcp/promptError.d.ts +5 -0
- package/types/signal/signalContractError.d.ts +4 -0
- package/types/signal/signalDeclarationError.d.ts +4 -0
- package/types/vendor/use-agentic/types.d.ts +5 -0
- package/vendor/use-agentic/CHANGELOG.md +24 -0
- package/vendor/use-agentic/ToolRunner.ts +18 -3
- package/vendor/use-agentic/WIRE.md +5 -0
- package/vendor/use-agentic/types.ts +5 -0
- package/webkit/McpAppAgent.ts +8 -3
- package/webkit/McpAppFetchBridge.ts +9 -5
package/server/mcp/McpRouter.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { type BackendEnv, getEnv } from "akanjs/base";
|
|
2
|
-
import { Logger } from "akanjs/common";
|
|
1
|
+
import { AkanError, type BackendEnv, getEnv } from "akanjs/base";
|
|
2
|
+
import { Logger, MCP_FAILURE_META, type McpFailure } from "akanjs/common";
|
|
3
3
|
import { DictionaryLookup } from "akanjs/dictionary";
|
|
4
4
|
import { CacheAdaptorRole, type InjectRegistry, type LiveRegistry } from "akanjs/service";
|
|
5
5
|
import {
|
|
@@ -286,7 +286,7 @@ export class McpRouter {
|
|
|
286
286
|
McpRouter.logger.error(
|
|
287
287
|
`MCP ${method} failed: ${error instanceof Error ? (error.stack ?? error.message) : error}`,
|
|
288
288
|
);
|
|
289
|
-
return McpRouter.#error(id, McpErrorCode.internal, "Internal server error.");
|
|
289
|
+
return McpRouter.#error(id, McpErrorCode.internal, "Internal server error.", McpRouter.#coded("internalError"));
|
|
290
290
|
}
|
|
291
291
|
}
|
|
292
292
|
|
|
@@ -437,6 +437,7 @@ export class McpRouter {
|
|
|
437
437
|
: `Too many calls in flight: at most ${this.#limiter.concurrent} at once. Retry in ${seconds}s.`;
|
|
438
438
|
return {
|
|
439
439
|
refused: McpRouter.#error(call.id, McpErrorCode.rateLimited, message, {
|
|
440
|
+
...McpRouter.#coded(AkanError.codeOfStatus(429)),
|
|
440
441
|
status: 429,
|
|
441
442
|
headers: { "retry-after": String(seconds) },
|
|
442
443
|
}),
|
|
@@ -447,13 +448,20 @@ export class McpRouter {
|
|
|
447
448
|
let streaming = false;
|
|
448
449
|
try {
|
|
449
450
|
const name = call.params.name;
|
|
450
|
-
if (typeof name !== "string")
|
|
451
|
+
if (typeof name !== "string")
|
|
452
|
+
return McpRouter.#error(call.id, McpErrorCode.invalidParams, "Missing tool name.", McpRouter.#invalid);
|
|
451
453
|
|
|
452
454
|
const exposed = document.isAppOnly(name) && !call.ui ? undefined : document.findTool(name);
|
|
453
455
|
|
|
454
|
-
if (!exposed)
|
|
456
|
+
if (!exposed)
|
|
457
|
+
return McpRouter.#error(
|
|
458
|
+
call.id,
|
|
459
|
+
McpErrorCode.invalidParams,
|
|
460
|
+
`Unknown tool: ${name}.`,
|
|
461
|
+
McpRouter.#coded("unknownTool"),
|
|
462
|
+
);
|
|
455
463
|
const args = McpRouter.#arguments(call.params);
|
|
456
|
-
if (!args) return McpRouter.#
|
|
464
|
+
if (!args) return McpRouter.#badArgumentsError(call.id);
|
|
457
465
|
const progressToken = McpRouter.#progressToken(call);
|
|
458
466
|
const option = { forView: this.#pages.forView(call.ui, McpRouter.#meta(call.params)) };
|
|
459
467
|
if (progressToken === undefined)
|
|
@@ -510,7 +518,7 @@ export class McpRouter {
|
|
|
510
518
|
|
|
511
519
|
stream.write(
|
|
512
520
|
"error" in outcome
|
|
513
|
-
? McpRouter.#errorBody(call.id, McpErrorCode.internal, "Internal server error.")
|
|
521
|
+
? McpRouter.#errorBody(call.id, McpErrorCode.internal, "Internal server error.", { code: "internalError" })
|
|
514
522
|
: this.#envelope(call, outcome.result),
|
|
515
523
|
);
|
|
516
524
|
} finally {
|
|
@@ -520,6 +528,16 @@ export class McpRouter {
|
|
|
520
528
|
|
|
521
529
|
static readonly #badArguments = "`arguments` must be an object of named values.";
|
|
522
530
|
|
|
531
|
+
static #coded(code: string) {
|
|
532
|
+
return { data: { code } };
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
static readonly #invalid = McpRouter.#coded("invalidArgument");
|
|
536
|
+
|
|
537
|
+
static #badArgumentsError(id: string | number | null) {
|
|
538
|
+
return McpRouter.#error(id, McpErrorCode.invalidParams, McpRouter.#badArguments, McpRouter.#invalid);
|
|
539
|
+
}
|
|
540
|
+
|
|
523
541
|
static #arguments(params: Record<string, unknown>) {
|
|
524
542
|
const args = params.arguments;
|
|
525
543
|
if (args === undefined || args === null) return {};
|
|
@@ -546,37 +564,45 @@ export class McpRouter {
|
|
|
546
564
|
|
|
547
565
|
async #pageToolCall(call: McpCall, document: McpDocument, entry: PagePromptEntry) {
|
|
548
566
|
const outcome = await this.#pages.toolCall(call, document, entry, McpRouter.#arguments(call.params));
|
|
549
|
-
if ("badArguments" in outcome)
|
|
550
|
-
return McpRouter.#error(call.id, McpErrorCode.invalidParams, McpRouter.#badArguments);
|
|
567
|
+
if ("badArguments" in outcome) return McpRouter.#badArgumentsError(call.id);
|
|
551
568
|
return this.#result(call, outcome.result);
|
|
552
569
|
}
|
|
553
570
|
|
|
554
571
|
async #promptsGet(call: McpCall, document: McpDocument) {
|
|
555
572
|
const name = call.params.name;
|
|
556
|
-
if (typeof name !== "string")
|
|
573
|
+
if (typeof name !== "string")
|
|
574
|
+
return McpRouter.#error(call.id, McpErrorCode.invalidParams, "Missing prompt name.", McpRouter.#invalid);
|
|
575
|
+
const unknown = McpRouter.#coded("unknownPrompt");
|
|
557
576
|
const entry = await this.#pages.prompt(name);
|
|
558
|
-
if (!entry) return McpRouter.#error(call.id, McpErrorCode.invalidParams, `Unknown prompt: ${name}
|
|
577
|
+
if (!entry) return McpRouter.#error(call.id, McpErrorCode.invalidParams, `Unknown prompt: ${name}.`, unknown);
|
|
559
578
|
const page = await this.#pages.run(call, document, entry, McpRouter.#arguments(call.params));
|
|
560
|
-
if ("badArguments" in page) return McpRouter.#
|
|
561
|
-
if ("refusal" in page)
|
|
579
|
+
if ("badArguments" in page) return McpRouter.#badArgumentsError(call.id);
|
|
580
|
+
if ("refusal" in page)
|
|
581
|
+
return McpRouter.#error(call.id, McpErrorCode.invalidParams, page.refusal, McpRouter.#coded(page.failure.code));
|
|
562
582
|
return this.#result(call, { description: entry.description, messages: page.messages });
|
|
563
583
|
}
|
|
564
584
|
|
|
565
585
|
async #resourcesRead(call: McpCall, document: McpDocument) {
|
|
566
586
|
const uri = call.params.uri;
|
|
567
|
-
if (typeof uri !== "string")
|
|
587
|
+
if (typeof uri !== "string")
|
|
588
|
+
return McpRouter.#error(call.id, McpErrorCode.invalidParams, "Missing resource uri.", McpRouter.#invalid);
|
|
589
|
+
const unknown = McpRouter.#coded("unknownResource");
|
|
568
590
|
if (this.#apps && uri.startsWith(McpApps.scheme)) {
|
|
569
591
|
const contents = await this.#apps.read(uri, this.#auth.publicOrigin(call.req));
|
|
570
|
-
if (!contents) return McpRouter.#error(call.id, McpErrorCode.invalidParams, `Unknown resource: ${uri}
|
|
592
|
+
if (!contents) return McpRouter.#error(call.id, McpErrorCode.invalidParams, `Unknown resource: ${uri}.`, unknown);
|
|
571
593
|
return this.#result(call, { contents: [contents] });
|
|
572
594
|
}
|
|
573
595
|
const resolved = document.resolveResource(uri);
|
|
574
|
-
if (!resolved) return McpRouter.#error(call.id, McpErrorCode.invalidParams, `Unknown resource: ${uri}
|
|
596
|
+
if (!resolved) return McpRouter.#error(call.id, McpErrorCode.invalidParams, `Unknown resource: ${uri}.`, unknown);
|
|
575
597
|
const result = await this.#dispatcher.call(resolved.exposed, resolved.args, call.req);
|
|
576
598
|
const [first] = result.content;
|
|
577
599
|
const firstText = first?.type === "text" ? first.text : undefined;
|
|
578
600
|
|
|
579
|
-
if (result.isError)
|
|
601
|
+
if (result.isError) {
|
|
602
|
+
const failure = result._meta?.[MCP_FAILURE_META] as McpFailure | undefined;
|
|
603
|
+
const code = failure?.code ?? AkanError.codeOfStatus(500);
|
|
604
|
+
return McpRouter.#error(call.id, McpErrorCode.invalidParams, firstText ?? "Read failed.", McpRouter.#coded(code));
|
|
605
|
+
}
|
|
580
606
|
|
|
581
607
|
const text =
|
|
582
608
|
result.structuredContent === undefined ? (firstText ?? "null") : JSON.stringify(result.structuredContent);
|
|
@@ -631,11 +657,14 @@ export class McpRouter {
|
|
|
631
657
|
|
|
632
658
|
#envelope(call: McpCall, result: object, cache?: McpCacheHint) {
|
|
633
659
|
|
|
634
|
-
const
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
660
|
+
const own = (result as { _meta?: Record<string, unknown> })._meta;
|
|
661
|
+
if (call.era !== "modern") return { jsonrpc: "2.0", id: call.id, result } satisfies McpJsonRpcResponse;
|
|
662
|
+
const _meta = { [MCP_META_SERVER_INFO]: this.#serverInfo(), ...own };
|
|
663
|
+
return {
|
|
664
|
+
jsonrpc: "2.0",
|
|
665
|
+
id: call.id,
|
|
666
|
+
result: { resultType: "complete", ...cache, ...result, _meta },
|
|
667
|
+
} satisfies McpJsonRpcResponse;
|
|
639
668
|
}
|
|
640
669
|
|
|
641
670
|
static #page<T>(items: T[], cursor: unknown, size: number) {
|
package/server/rscClient.tsx
CHANGED
|
@@ -21,8 +21,11 @@ import {
|
|
|
21
21
|
claimChunkReload,
|
|
22
22
|
isBuildBundle,
|
|
23
23
|
isLinkFailure,
|
|
24
|
+
lazyLinkFailureKeyOf,
|
|
24
25
|
navigationOfChunk,
|
|
26
|
+
noteChunkLoadFailure,
|
|
25
27
|
recordChunksOf,
|
|
28
|
+
reportingRootErrors,
|
|
26
29
|
} from "./rscClientChunks";
|
|
27
30
|
import { fetchRscNavigationResponse, fetchRscPrefetchResponse } from "./rscClientFetch";
|
|
28
31
|
import { validateRscPatchForGuardedCommit } from "./rscClientPatch";
|
|
@@ -33,6 +36,7 @@ import {
|
|
|
33
36
|
rollbackPreparedAkanHeadSnapshotPatch,
|
|
34
37
|
} from "./rscHeadPatch";
|
|
35
38
|
import { getRscPayloadStream, guardRscRedirectRows, type RscRedirectRow } from "./rscHttp";
|
|
39
|
+
import { createInitialRscStream } from "./rscInlineStream";
|
|
36
40
|
import {
|
|
37
41
|
type AkanSegmentCacheNode,
|
|
38
42
|
commitLatestRscNavigation,
|
|
@@ -40,6 +44,7 @@ import {
|
|
|
40
44
|
createRscNavigationCacheNode,
|
|
41
45
|
createRscPatchNavigationCacheNode,
|
|
42
46
|
deleteRscCacheEntryIfCurrent,
|
|
47
|
+
forgetRscPatchesOfLostBases,
|
|
43
48
|
observeRscNavigationNode,
|
|
44
49
|
type RscNavigationCacheNode,
|
|
45
50
|
type RscPatchNavigationCacheNode,
|
|
@@ -51,26 +56,12 @@ import { RscPrefetchCache } from "./rscPrefetchCache";
|
|
|
51
56
|
import { RscScrollRestoration } from "./rscScrollRestoration";
|
|
52
57
|
import { commitAkanSegmentOutletPatch, resetAkanSegmentOutletPatches } from "./rscSegmentOutlet";
|
|
53
58
|
|
|
54
|
-
type InlineRscChunk = [1, string] | [3, string];
|
|
55
|
-
|
|
56
59
|
declare global {
|
|
57
|
-
var __RSC_CHUNKS__: InlineRscChunk[] | undefined;
|
|
58
|
-
var __RSC_CLOSED__: boolean | undefined;
|
|
59
|
-
var __RSC_PUSH__: ((type: InlineRscChunk[0], data: string) => void) | undefined;
|
|
60
|
-
var __RSC_CLOSE__: (() => void) | undefined;
|
|
61
60
|
var __AKAN_RSC_INITIAL_STATE__: string | undefined;
|
|
62
61
|
var __AKAN_DICT_URL__: string | undefined;
|
|
63
62
|
var __webpack_chunk_load__: ((chunkId: string) => Promise<unknown>) | undefined;
|
|
64
63
|
}
|
|
65
64
|
|
|
66
|
-
function decodeInlineRscChunk([type, data]: InlineRscChunk): Uint8Array {
|
|
67
|
-
if (type === 1) return new TextEncoder().encode(data);
|
|
68
|
-
const binary = atob(data);
|
|
69
|
-
const bytes = new Uint8Array(binary.length);
|
|
70
|
-
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
71
|
-
return bytes;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
65
|
type RscThenable = Promise<ReactNode> & {
|
|
75
66
|
status?: "pending" | "fulfilled" | "rejected";
|
|
76
67
|
value?: ReactNode;
|
|
@@ -107,24 +98,6 @@ class RscRouteNotFound extends Error {
|
|
|
107
98
|
}
|
|
108
99
|
}
|
|
109
100
|
|
|
110
|
-
function createInitialRscStream(): ReadableStream<Uint8Array> {
|
|
111
|
-
return new ReadableStream<Uint8Array>({
|
|
112
|
-
start(controller) {
|
|
113
|
-
const queued = globalThis.__RSC_CHUNKS__ ?? [];
|
|
114
|
-
for (const chunk of queued) controller.enqueue(decodeInlineRscChunk(chunk));
|
|
115
|
-
globalThis.__RSC_CHUNKS__ = [];
|
|
116
|
-
|
|
117
|
-
if (globalThis.__RSC_CLOSED__) {
|
|
118
|
-
controller.close();
|
|
119
|
-
return;
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
globalThis.__RSC_PUSH__ = (type, data) => controller.enqueue(decodeInlineRscChunk([type, data]));
|
|
123
|
-
globalThis.__RSC_CLOSE__ = () => controller.close();
|
|
124
|
-
},
|
|
125
|
-
});
|
|
126
|
-
}
|
|
127
|
-
|
|
128
101
|
function normalizeHref(href: string): string {
|
|
129
102
|
return new URL(href, window.location.origin).href;
|
|
130
103
|
}
|
|
@@ -418,6 +391,7 @@ if (loadChunk)
|
|
|
418
391
|
globalThis.__webpack_chunk_load__ = (chunkId) => {
|
|
419
392
|
const loading = loadChunk(chunkId);
|
|
420
393
|
const navigation = navigationOfChunk(chunkId);
|
|
394
|
+
loading.catch(noteChunkLoadFailure);
|
|
421
395
|
if (navigation) loading.catch((error: unknown) => loadDocumentForChunkFailure(chunkId, navigation, error));
|
|
422
396
|
return loading;
|
|
423
397
|
};
|
|
@@ -433,21 +407,28 @@ function loadDocumentForChunkFailure(chunkId: string, navigation: ChunkNavigatio
|
|
|
433
407
|
else hardNavigateAfterRscFailure(normalizeHref(window.location.href), true, error);
|
|
434
408
|
}
|
|
435
409
|
|
|
410
|
+
function loadDocumentForLazyChunkFailure(error: unknown): void {
|
|
411
|
+
const leaving =
|
|
412
|
+
!!pendingRequest && pendingRequest.navId !== refreshNavId && pendingRequest.target !== pageKeyOf(renderedHref);
|
|
413
|
+
if (shownNode === initialNode || leaving || documentNavigationFallbackInFlight || !isBuildBundle()) return;
|
|
414
|
+
const key = lazyLinkFailureKeyOf(error);
|
|
415
|
+
if (key && navigator.onLine && claimChunkReload(key))
|
|
416
|
+
hardNavigateAfterRscFailure(normalizeHref(window.location.href), true, error);
|
|
417
|
+
}
|
|
418
|
+
|
|
436
419
|
globalThis.__AKAN_RSC_IS_FROM_CACHE__ = () => currentCommitFromCache;
|
|
437
420
|
|
|
438
421
|
function rememberCommittedRouteState(node: RscCacheNode): void {
|
|
439
|
-
|
|
422
|
+
currentFullNode = node;
|
|
440
423
|
shownNode = node;
|
|
441
424
|
parkedRedirect.clear();
|
|
442
|
-
|
|
425
|
+
forgetRscPatchesOfLostBases(rscPatchCache, rscCache, node);
|
|
443
426
|
currentRouterState = node.routerState;
|
|
444
427
|
currentSegmentTree = createAkanSegmentCacheTree(node);
|
|
445
|
-
currentFullNode = node;
|
|
446
428
|
currentCommitKind = "full";
|
|
447
429
|
}
|
|
448
430
|
|
|
449
431
|
function forgetCommittedRouteState(): void {
|
|
450
|
-
rscPatchCache.clear();
|
|
451
432
|
shownNode = null;
|
|
452
433
|
parkedRedirect.clear();
|
|
453
434
|
currentRouterState = null;
|
|
@@ -485,6 +466,31 @@ function replayedPageOf(target: string): RscCacheNode | undefined {
|
|
|
485
466
|
return node;
|
|
486
467
|
}
|
|
487
468
|
|
|
469
|
+
function replayCachedPatch(target: string, navId: number, replace?: boolean, requestScroll?: () => void): boolean {
|
|
470
|
+
const cachedPatch = rscPatchCache.get(target);
|
|
471
|
+
if (!cachedPatch) return false;
|
|
472
|
+
const patchResult = resolveCachedRscPatchNavigation({
|
|
473
|
+
currentTree: currentSegmentTree,
|
|
474
|
+
currentBase: currentFullNode,
|
|
475
|
+
node: cachedPatch,
|
|
476
|
+
partialCommitEnabled: isAkanRscPartialCommitEnabled(),
|
|
477
|
+
navId,
|
|
478
|
+
getCurrentNavId: () => navigationSeq,
|
|
479
|
+
});
|
|
480
|
+
if (patchResult.status === "patched") {
|
|
481
|
+
const { tree, patchedNode, outletKey, headSnapshot } = patchResult;
|
|
482
|
+
const patch = { type: "patched" as const, tree, patchedNode, patch: cachedPatch.patch, outletKey, headSnapshot };
|
|
483
|
+
if (commitRscPatchNavigation({ target, patch, replace, requestScroll })) {
|
|
484
|
+
currentCommitFromCache = true;
|
|
485
|
+
rememberPatchedRouteState(tree, patchedNode);
|
|
486
|
+
rememberRscCacheNode(rscPatchCache, cachedPatch, MAX_RSC_CACHE_ENTRIES);
|
|
487
|
+
return true;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
rscPatchCache.delete(target);
|
|
491
|
+
return false;
|
|
492
|
+
}
|
|
493
|
+
|
|
488
494
|
const isConstrainedNetwork = () => {
|
|
489
495
|
const connection = (navigator as Navigator & { connection?: { saveData?: boolean; effectiveType?: string } })
|
|
490
496
|
.connection;
|
|
@@ -614,40 +620,7 @@ function Root(): ReactNode {
|
|
|
614
620
|
let notFound = false;
|
|
615
621
|
let servedFromCache = !!nextNode;
|
|
616
622
|
if (!nextNode) {
|
|
617
|
-
|
|
618
|
-
if (cachedPatch) {
|
|
619
|
-
const patchResult = resolveCachedRscPatchNavigation({
|
|
620
|
-
currentTree: currentSegmentTree,
|
|
621
|
-
node: cachedPatch,
|
|
622
|
-
partialCommitEnabled: isAkanRscPartialCommitEnabled(),
|
|
623
|
-
navId,
|
|
624
|
-
getCurrentNavId: () => navigationSeq,
|
|
625
|
-
});
|
|
626
|
-
if (patchResult.status === "patched") {
|
|
627
|
-
const replayedPatch = {
|
|
628
|
-
type: "patched" as const,
|
|
629
|
-
tree: patchResult.tree,
|
|
630
|
-
patchedNode: patchResult.patchedNode,
|
|
631
|
-
patch: cachedPatch.patch,
|
|
632
|
-
outletKey: patchResult.outletKey,
|
|
633
|
-
headSnapshot: patchResult.headSnapshot,
|
|
634
|
-
};
|
|
635
|
-
if (
|
|
636
|
-
commitRscPatchNavigation({
|
|
637
|
-
target,
|
|
638
|
-
patch: replayedPatch,
|
|
639
|
-
replace: options.replace,
|
|
640
|
-
requestScroll,
|
|
641
|
-
})
|
|
642
|
-
) {
|
|
643
|
-
currentCommitFromCache = true;
|
|
644
|
-
rememberPatchedRouteState(patchResult.tree, patchResult.patchedNode);
|
|
645
|
-
rememberRscCacheNode(rscPatchCache, cachedPatch, MAX_RSC_CACHE_ENTRIES);
|
|
646
|
-
return;
|
|
647
|
-
}
|
|
648
|
-
}
|
|
649
|
-
rscPatchCache.delete(target);
|
|
650
|
-
}
|
|
623
|
+
if (replayCachedPatch(target, navId, options.replace, requestScroll)) return;
|
|
651
624
|
const taken = rscPrefetchCache.take(pageKeyOf(target), cachedAuthCookies, signal);
|
|
652
625
|
const prefetched = (await taken?.response) ?? undefined;
|
|
653
626
|
if (signal.aborted) return;
|
|
@@ -679,6 +652,7 @@ function Root(): ReactNode {
|
|
|
679
652
|
patchedNode: fetched.patchedNode,
|
|
680
653
|
outletKey: fetched.outletKey,
|
|
681
654
|
headSnapshot: fetched.headSnapshot,
|
|
655
|
+
base: currentFullNode,
|
|
682
656
|
});
|
|
683
657
|
if (patchCacheNode) rememberRscCacheNode(rscPatchCache, patchCacheNode, MAX_RSC_CACHE_ENTRIES);
|
|
684
658
|
return;
|
|
@@ -770,8 +744,10 @@ window.addEventListener("popstate", (event) => {
|
|
|
770
744
|
}, 0);
|
|
771
745
|
});
|
|
772
746
|
|
|
747
|
+
window.addEventListener("unhandledrejection", (event) => loadDocumentForLazyChunkFailure(event.reason));
|
|
748
|
+
const rootOptions = isBuildBundle() ? reportingRootErrors(loadDocumentForLazyChunkFailure) : undefined;
|
|
773
749
|
const hydrate = () => {
|
|
774
|
-
hydrateRoot(document, createElement(Root));
|
|
750
|
+
hydrateRoot(document, createElement(Root), rootOptions);
|
|
775
751
|
scrollRestoration.restoreDocumentLoad();
|
|
776
752
|
};
|
|
777
753
|
|
|
@@ -41,6 +41,35 @@ const linkFailure =
|
|
|
41
41
|
export const isLinkFailure = (error: unknown): boolean =>
|
|
42
42
|
(error instanceof SyntaxError || error instanceof TypeError) && linkFailure.test(error.message);
|
|
43
43
|
|
|
44
|
+
const chunkLoadFailures = new WeakSet<object>();
|
|
45
|
+
export const noteChunkLoadFailure = (error: unknown): void => {
|
|
46
|
+
if (typeof error === "object" && error !== null) chunkLoadFailures.add(error);
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export const lazyLinkFailureKeyOf = (error: unknown): string | null =>
|
|
50
|
+
error instanceof Error && isLinkFailure(error) && !chunkLoadFailures.has(error) ? `import() ${error.message}` : null;
|
|
51
|
+
|
|
52
|
+
const reportGlobalError = (error: unknown): void => {
|
|
53
|
+
if (typeof reportError === "function") {
|
|
54
|
+
reportError(error);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
58
|
+
if (window.dispatchEvent(new ErrorEvent("error", { bubbles: true, cancelable: true, message, error })))
|
|
59
|
+
console.error(error);
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export const reportingRootErrors = (onError: (error: unknown) => void) => ({
|
|
63
|
+
onCaughtError: (error: unknown) => {
|
|
64
|
+
console.error(error);
|
|
65
|
+
onError(error);
|
|
66
|
+
},
|
|
67
|
+
onUncaughtError: (error: unknown) => {
|
|
68
|
+
reportGlobalError(error);
|
|
69
|
+
onError(error);
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
|
|
44
73
|
const chunkReloadsKey = "akan.rsc.chunkReloads";
|
|
45
74
|
export function claimChunkReload(chunkId: string): boolean {
|
|
46
75
|
try {
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
type InlineRscChunk = [1, string] | [3, string];
|
|
2
|
+
|
|
3
|
+
declare global {
|
|
4
|
+
var __RSC_CHUNKS__: InlineRscChunk[] | undefined;
|
|
5
|
+
var __RSC_CLOSED__: boolean | undefined;
|
|
6
|
+
var __RSC_PUSH__: ((type: InlineRscChunk[0], data: string) => void) | undefined;
|
|
7
|
+
var __RSC_CLOSE__: (() => void) | undefined;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function decodeInlineRscChunk([type, data]: InlineRscChunk): Uint8Array {
|
|
11
|
+
if (type === 1) return new TextEncoder().encode(data);
|
|
12
|
+
const binary = atob(data);
|
|
13
|
+
const bytes = new Uint8Array(binary.length);
|
|
14
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
15
|
+
return bytes;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function createInitialRscStream(): ReadableStream<Uint8Array> {
|
|
19
|
+
return new ReadableStream<Uint8Array>({
|
|
20
|
+
start(controller) {
|
|
21
|
+
const queued = globalThis.__RSC_CHUNKS__ ?? [];
|
|
22
|
+
for (const chunk of queued) controller.enqueue(decodeInlineRscChunk(chunk));
|
|
23
|
+
globalThis.__RSC_CHUNKS__ = [];
|
|
24
|
+
|
|
25
|
+
if (globalThis.__RSC_CLOSED__) {
|
|
26
|
+
controller.close();
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
globalThis.__RSC_PUSH__ = (type, data) => controller.enqueue(decodeInlineRscChunk([type, data]));
|
|
31
|
+
globalThis.__RSC_CLOSE__ = () => controller.close();
|
|
32
|
+
},
|
|
33
|
+
});
|
|
34
|
+
}
|
|
@@ -27,6 +27,8 @@ export interface RscPatchNavigationCacheNode<T> {
|
|
|
27
27
|
patch: AkanRscPatchMetadata;
|
|
28
28
|
outletKey: string;
|
|
29
29
|
headSnapshot: AkanHeadSnapshotV1;
|
|
30
|
+
/** The full commit whose layouts the patch went under; it keeps them, so it applies under that very commit only. */
|
|
31
|
+
base: RscNavigationCacheNode<T>;
|
|
30
32
|
}
|
|
31
33
|
|
|
32
34
|
export interface AkanSegmentCacheNode<T> {
|
|
@@ -39,6 +41,7 @@ export interface AkanSegmentCacheNode<T> {
|
|
|
39
41
|
|
|
40
42
|
export type AkanSegmentPatchFailureReason =
|
|
41
43
|
| "missing-current-tree"
|
|
44
|
+
| "base-changed"
|
|
42
45
|
| "segment-path-mismatch"
|
|
43
46
|
| "stale"
|
|
44
47
|
| "unsupported-suffix"
|
|
@@ -92,14 +95,16 @@ export function createRscPatchNavigationCacheNode<T>({
|
|
|
92
95
|
patchedNode,
|
|
93
96
|
outletKey,
|
|
94
97
|
headSnapshot,
|
|
98
|
+
base,
|
|
95
99
|
}: {
|
|
96
100
|
href: string;
|
|
97
101
|
patch: AkanRscPatchMetadata;
|
|
98
102
|
patchedNode: AkanSegmentCacheNode<T>;
|
|
99
103
|
outletKey: string;
|
|
100
104
|
headSnapshot: AkanHeadSnapshotV1;
|
|
105
|
+
base: RscNavigationCacheNode<T> | null;
|
|
101
106
|
}): RscPatchNavigationCacheNode<T> | null {
|
|
102
|
-
if (!patchedNode.thenable) return null;
|
|
107
|
+
if (!patchedNode.thenable || !base) return null;
|
|
103
108
|
return {
|
|
104
109
|
href,
|
|
105
110
|
thenable: patchedNode.thenable,
|
|
@@ -107,9 +112,21 @@ export function createRscPatchNavigationCacheNode<T>({
|
|
|
107
112
|
patch,
|
|
108
113
|
outletKey,
|
|
109
114
|
headSnapshot,
|
|
115
|
+
base,
|
|
110
116
|
};
|
|
111
117
|
}
|
|
112
118
|
|
|
119
|
+
export function forgetRscPatchesOfLostBases<T>(
|
|
120
|
+
patchCache: RscNavigationCache<RscPatchNavigationCacheNode<T>>,
|
|
121
|
+
fullCache: RscNavigationCache<RscNavigationCacheNode<T>>,
|
|
122
|
+
currentBase: RscNavigationCacheNode<T> | null,
|
|
123
|
+
): void {
|
|
124
|
+
for (const href of [...patchCache.keys()]) {
|
|
125
|
+
const base = patchCache.get(href)?.base;
|
|
126
|
+
if (base && base !== currentBase && fullCache.get(base.href) !== base) patchCache.delete(href);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
113
130
|
export function createAkanSegmentCacheTree<T>(node: RscNavigationCacheNode<T>): AkanSegmentCacheNode<T> | null {
|
|
114
131
|
const routerState = node.routerState;
|
|
115
132
|
if (!routerState || routerState.segments.length === 0) return null;
|
|
@@ -221,18 +238,21 @@ export function rememberRscCacheNode<N extends { href: string }>(
|
|
|
221
238
|
|
|
222
239
|
export function resolveCachedRscPatchNavigation<T>({
|
|
223
240
|
currentTree,
|
|
241
|
+
currentBase,
|
|
224
242
|
node,
|
|
225
243
|
partialCommitEnabled,
|
|
226
244
|
navId,
|
|
227
245
|
getCurrentNavId,
|
|
228
246
|
}: {
|
|
229
247
|
currentTree: AkanSegmentCacheNode<T> | null;
|
|
248
|
+
currentBase: RscNavigationCacheNode<T> | null;
|
|
230
249
|
node: RscPatchNavigationCacheNode<T>;
|
|
231
250
|
partialCommitEnabled: boolean;
|
|
232
251
|
navId?: number;
|
|
233
252
|
getCurrentNavId?: () => number;
|
|
234
253
|
}): RscPatchNavigationCacheResult<T> {
|
|
235
254
|
if (!partialCommitEnabled) return { status: "rejected", reason: "guard-disabled" };
|
|
255
|
+
if (node.base !== currentBase) return { status: "rejected", reason: "base-changed" };
|
|
236
256
|
const patchResult = applyAkanSegmentCachePatch({
|
|
237
257
|
currentTree,
|
|
238
258
|
targetRouterState: node.routerState,
|
package/server/rscWorkerHost.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { fileURLToPath } from "node:url";
|
|
|
4
4
|
import { type AkanI18nConfig, DEFAULT_AKAN_I18N, Logger, type LogRecord } from "akanjs/common";
|
|
5
5
|
import type { AkanTheme } from "akanjs/fetch";
|
|
6
6
|
import type { AkanMetricsReport } from "akanjs/service";
|
|
7
|
+
import { RestartSchedule } from "../common/restartSchedule";
|
|
7
8
|
import type {
|
|
8
9
|
PagePromptEntry,
|
|
9
10
|
PagePromptRun,
|
|
@@ -422,7 +423,7 @@ export class RscWorker {
|
|
|
422
423
|
#status: RscWorkerStatus = "starting";
|
|
423
424
|
#killed = false;
|
|
424
425
|
#queuedSends: { requestId: string; send: () => void }[] = [];
|
|
425
|
-
#
|
|
426
|
+
readonly #restart = new RestartSchedule({ min: 200, max: 30_000 });
|
|
426
427
|
#restartCount = 0;
|
|
427
428
|
#recycleCount = 0;
|
|
428
429
|
#reloadsSinceSpawn = 0;
|
|
@@ -432,7 +433,6 @@ export class RscWorker {
|
|
|
432
433
|
onLogRecords: ((records: LogRecord[], dropped: number) => void) | null = null;
|
|
433
434
|
#logLevel: number | null = null;
|
|
434
435
|
#hostPendingChunkOverflowCount = 0;
|
|
435
|
-
#restartTimer: ReturnType<typeof setTimeout> | null = null;
|
|
436
436
|
#recycleTimer: ReturnType<typeof setTimeout> | null = null;
|
|
437
437
|
#rollingRecycle: { oldProc: RscProcess; reason: string; reloadsSinceSpawn: number } | null = null;
|
|
438
438
|
#booting: RscProcess | null = null;
|
|
@@ -542,9 +542,8 @@ export class RscWorker {
|
|
|
542
542
|
kill(): void {
|
|
543
543
|
this.#killed = true;
|
|
544
544
|
this.#status = "stopped";
|
|
545
|
-
|
|
545
|
+
this.#restart.cancel();
|
|
546
546
|
if (this.#recycleTimer) clearTimeout(this.#recycleTimer);
|
|
547
|
-
this.#restartTimer = null;
|
|
548
547
|
this.#recycleTimer = null;
|
|
549
548
|
this.#rollingRecycle?.oldProc.kill();
|
|
550
549
|
this.#rollingRecycle = null;
|
|
@@ -781,7 +780,7 @@ export class RscWorker {
|
|
|
781
780
|
this.#status = "ready";
|
|
782
781
|
this.#answeredReloadId = this.#nextReloadId - 1;
|
|
783
782
|
this.#droppedWhileBooting = false;
|
|
784
|
-
this.#
|
|
783
|
+
this.#restart.reset();
|
|
785
784
|
this.#resolveReady();
|
|
786
785
|
this.#finishRollingRecycle();
|
|
787
786
|
|
|
@@ -1013,7 +1012,7 @@ export class RscWorker {
|
|
|
1013
1012
|
const err = new Error(`rsc worker exited with code ${code}`);
|
|
1014
1013
|
|
|
1015
1014
|
const queued = new Set(this.#queuedSends.map((entry) => entry.requestId));
|
|
1016
|
-
const keepsQueue = this.#
|
|
1015
|
+
const keepsQueue = this.#restart.attempts < RscWorker.#queuedRespawns;
|
|
1017
1016
|
this.#failRequests(err, (requestId) => !keepsQueue || !queued.has(requestId));
|
|
1018
1017
|
|
|
1019
1018
|
if (this.#killed) {
|
|
@@ -1035,12 +1034,7 @@ export class RscWorker {
|
|
|
1035
1034
|
|
|
1036
1035
|
#scheduleRestart(): void {
|
|
1037
1036
|
this.#status = "restarting";
|
|
1038
|
-
const delay =
|
|
1039
|
-
this.#restartAttempts += 1;
|
|
1040
|
-
this.#restartCount += 1;
|
|
1041
|
-
this.#logger.verbose(`[rsc] worker crashed, restarting in ${delay}ms (attempt ${this.#restartAttempts})`);
|
|
1042
|
-
this.#restartTimer = setTimeout(() => {
|
|
1043
|
-
this.#restartTimer = null;
|
|
1037
|
+
const delay = this.#restart.schedule(() => {
|
|
1044
1038
|
if (this.#killed) return;
|
|
1045
1039
|
try {
|
|
1046
1040
|
this.#proc = this.#spawn();
|
|
@@ -1048,7 +1042,9 @@ export class RscWorker {
|
|
|
1048
1042
|
this.#logger.error(`[rsc] failed to spawn worker: ${err instanceof Error ? err.message : String(err)}`);
|
|
1049
1043
|
this.#scheduleRestart();
|
|
1050
1044
|
}
|
|
1051
|
-
}
|
|
1045
|
+
});
|
|
1046
|
+
this.#restartCount += 1;
|
|
1047
|
+
this.#logger.verbose(`[rsc] worker crashed, restarting in ${delay}ms (attempt ${this.#restart.attempts})`);
|
|
1052
1048
|
}
|
|
1053
1049
|
|
|
1054
1050
|
#shouldRecycleForReloadAccumulation(): boolean {
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { AkanError } from "akanjs/base";
|
|
2
|
+
|
|
3
|
+
export type DocumentStoreErrorCode =
|
|
4
|
+
| "invalidQuery"
|
|
5
|
+
| "invalidSchema"
|
|
6
|
+
| "invalidDocument"
|
|
7
|
+
| "unstorableValue"
|
|
8
|
+
| "tableMissing"
|
|
9
|
+
| "searchUnavailable"
|
|
10
|
+
| "searchMisconfigured";
|
|
11
|
+
|
|
12
|
+
export class DocumentStoreError extends AkanError<DocumentStoreErrorCode> {
|
|
13
|
+
constructor(code: DocumentStoreErrorCode, message: string, options?: { cause?: unknown }) {
|
|
14
|
+
super(code, message, { statusCode: code === "unstorableValue" ? 400 : 500, cause: options?.cause });
|
|
15
|
+
}
|
|
16
|
+
}
|
package/service/index.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
export * from "./adapt";
|
|
2
2
|
export * from "./agent.service";
|
|
3
3
|
export * from "./base.service";
|
|
4
|
+
export * from "./documentStoreError";
|
|
4
5
|
export * from "./endpointCacheKeys";
|
|
6
|
+
export * from "./injectError";
|
|
5
7
|
export * from "./injectInfo";
|
|
8
|
+
export * from "./insightQueryError";
|
|
6
9
|
export * from "./ipcTypes";
|
|
7
10
|
export * from "./liveSyncHub";
|
|
8
11
|
export * from "./predefinedAdaptor";
|