@akanjs/devkit 3.3.0-rc.4 → 3.3.0-rc.40
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 +618 -0
- package/DEV_RUNTIME_KNOBS.md +1 -1
- package/README.ko.md +3 -2
- package/README.md +3 -3
- package/akanApp/akanApp.host.test.ts +1 -1
- package/akanApp/akanApp.host.ts +11 -0
- package/akanConfig/akanBin.ts +4 -0
- package/akanConfig/akanConfig.test.ts +66 -7
- package/akanConfig/akanConfig.ts +53 -204
- package/akanConfig/akanWorkers.test.ts +39 -0
- package/akanConfig/akanWorkers.ts +32 -0
- package/akanConfig/desktopServerConfig.ts +96 -0
- package/akanConfig/dockerImage.ts +37 -0
- package/akanConfig/nativeKeys.ts +52 -0
- package/akanConfig/types.ts +1 -0
- package/app/appBin.test.ts +63 -0
- package/app/appBin.ts +50 -0
- package/app/applicationBuildReporter.test.ts +32 -0
- package/app/applicationBuildReporter.ts +4 -0
- package/app/applicationBuildRunner.test.ts +275 -0
- package/app/applicationBuildRunner.ts +133 -6
- package/app/dictionarySizes.ts +91 -0
- package/app/routeFilesReport.test.ts +59 -0
- package/app/routeFilesReport.ts +46 -0
- package/app/routeJsBudget.ts +18 -4
- package/artifact/implicitRootLayout.test.ts +19 -0
- package/artifact/implicitRootLayout.ts +16 -2
- package/artifact/implicitRootLayoutRender.test.tsx +4 -1
- package/artifact/storeBootstrap.test.ts +28 -0
- package/artifact/storeBootstrap.ts +64 -8
- package/biome.base.json +6 -4
- package/codeAgent/agent/CodeAgent.ts +36 -16
- package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
- package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
- package/codeAgent/agent/CodeAgentGate.ts +23 -4
- package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
- package/codeAgent/agent/codeAgent.test.ts +62 -0
- package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
- package/codeAgent/agent/codeAgentContract.test.ts +117 -5
- package/codeAgent/skills/akan-agent/SKILL.md +8 -1
- package/codeAgent/skills/akan-code/SKILL.md +38 -3
- package/codeAgent/skills/akan-deps/SKILL.md +3 -2
- package/codeAgent/skills/akan-err/SKILL.md +13 -8
- package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
- package/codeAgent/skills/akan-module/SKILL.md +2 -2
- package/codeAgent/skills/akan-page/SKILL.md +31 -20
- package/codeAgent/skills/akan-query/SKILL.md +13 -20
- package/codeAgent/skills/akan-runtime/SKILL.md +20 -0
- package/codeAgent/skills/akan-service/SKILL.md +2 -5
- package/codeAgent/skills/akan-transport/SKILL.md +5 -14
- package/codeAgent/skills/akan-ui/SKILL.md +2 -5
- package/context/akanContext.ts +2 -0
- package/docs/apiReference.test.ts +9 -0
- package/docs/apiReference.ts +14 -0
- package/executors/appExecutor.ts +3 -1
- package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
- package/executors/clientRuntimeKeys.fixture.json +393 -0
- package/executors/clientRuntimeKeys.test.ts +1690 -0
- package/executors/executors.test.ts +2 -0
- package/executors/sysExecutor.ts +70 -4
- package/executors/workspaceExecutor.ts +7 -4
- package/frontendBuild/allRoutesBuilder.ts +88 -7
- package/frontendBuild/autoImportSync.ts +3 -2
- package/frontendBuild/buildRouteClient.test.ts +580 -12
- package/frontendBuild/clientBuildTypes.ts +26 -0
- package/frontendBuild/clientEntriesBundler.ts +49 -1
- package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
- package/frontendBuild/clientEntryDiscovery.ts +135 -13
- package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
- package/frontendBuild/csrDevModuleCompiler.ts +44 -8
- package/frontendBuild/csrDevPatcher.ts +33 -7
- package/frontendBuild/csrDevTypes.ts +9 -0
- package/frontendBuild/devBarrelImports.test.ts +154 -0
- package/frontendBuild/devBarrelImports.ts +83 -23
- package/frontendBuild/devRegistryBundler.ts +4 -2
- package/frontendBuild/devRouteRuntime.test.ts +492 -0
- package/frontendBuild/devRouteRuntime.ts +167 -0
- package/frontendBuild/dictionaryAssetBuilder.test.ts +324 -0
- package/frontendBuild/dictionaryAssetBuilder.ts +165 -16
- package/frontendBuild/dictionaryConstants.ts +136 -0
- package/frontendBuild/dictionaryPacking.test.ts +142 -0
- package/frontendBuild/dictionaryPacking.ts +135 -0
- package/frontendBuild/dictionaryRoutes.test.ts +251 -0
- package/frontendBuild/dictionaryRoutes.ts +227 -0
- package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
- package/frontendBuild/pagesBundleBuilder.ts +81 -3
- package/frontendBuild/precompressArtifacts.test.ts +22 -0
- package/frontendBuild/precompressArtifacts.ts +22 -8
- package/frontendBuild/registryMetadataFingerprint.ts +3 -3
- package/frontendBuild/renderedEntries.ts +144 -0
- package/frontendBuild/routeClientBuilder.ts +340 -29
- package/frontendBuild/routeHandoffs.test.ts +155 -0
- package/frontendBuild/routeHandoffs.ts +117 -0
- package/frontendBuild/routeModulePreloads.test.ts +32 -0
- package/frontendBuild/routeModulePreloads.ts +20 -11
- package/frontendBuild/routeRuntimeCheck.test.ts +280 -0
- package/frontendBuild/routeRuntimeCheck.ts +248 -0
- package/frontendBuild/routeRuntimePays.test.ts +143 -0
- package/frontendBuild/routeRuntimePays.ts +117 -0
- package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
- package/frontendBuild/rscServerRendererGuard.ts +68 -0
- package/frontendBuild/ssrBaseArtifactBuilder.ts +24 -34
- package/frontendBuild/ssrDevBundler.test.ts +150 -1
- package/frontendBuild/ssrDevBundler.ts +66 -11
- package/frontendBuild/vendorFileImports.test.ts +254 -0
- package/frontendBuild/vendorFileImports.ts +163 -0
- package/frontendBuild/vendorNarrowing.ts +28 -0
- package/frontendBuild/vendorSpecifiers.ts +2 -0
- package/incrementalBuilder/buildBatch.proc.ts +9 -9
- package/incrementalBuilder/buildBatchProtocol.ts +1 -1
- package/incrementalBuilder/builderBoot.ts +5 -5
- package/incrementalBuilder/builderGraphPayloads.ts +4 -4
- package/incrementalBuilder/builderLanes.ts +2 -2
- package/incrementalBuilder/builderWatch.ts +8 -8
- package/incrementalBuilder/csrRegistry.ts +4 -4
- package/incrementalBuilder/incrementalBuilder.proc.test.ts +79 -0
- package/incrementalBuilder/incrementalBuilder.proc.ts +27 -8
- package/incrementalBuilder/ssrRegistry.ts +6 -6
- package/index.ts +1 -1
- package/integration/renderAdmissionSoak.test.ts +99 -0
- package/integration/renderAdmissionSoak.ts +609 -0
- package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
- package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
- package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
- package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
- package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
- package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
- package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
- package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
- package/lint/biomeBase.test.ts +23 -3
- package/lint/biomeCheck.test.ts +145 -0
- package/lint/biomeCheck.ts +131 -0
- package/lint/no-arbitrary-color.grit +5 -0
- package/lint/no-conditional-st-hook.grit +5 -1
- package/lint/no-daisyui-legacy-class.grit +8 -0
- package/lint/no-document-cookie.grit +3 -0
- package/lint/no-inline-color.grit +10 -2
- package/lint/no-oversized-list-limit.grit +2 -0
- package/lint/no-raw-palette-class.grit +7 -0
- package/lint/no-unpublished-form-setter.grit +2 -0
- package/lint/no-web-only-api-outside-webkit.grit +5 -0
- package/lint/no-web-storage.grit +3 -0
- package/lint/withheldEnvFile.ts +17 -0
- package/mobile/desktopBin.ts +2 -2
- package/mobile/desktopServerStage.ts +1 -0
- package/mobile/nativeApp.test.ts +7 -5
- package/mobile/nativeApp.ts +2 -2
- package/mobile/nativeConfig.test.ts +96 -1
- package/mobile/nativeConfig.ts +46 -12
- package/mobile/serverBundleSecrets.ts +43 -0
- package/package.json +15 -169
- package/packageExports.test.ts +38 -24
- package/quality/dictionaryKeys.test.ts +356 -0
- package/quality/dictionaryKeys.ts +488 -0
- package/quality/objectImportReport.test.ts +36 -0
- package/quality/objectImportReport.ts +105 -0
- package/quality/qualityScanner.ts +1 -1
- package/quality/routeRuntimeReport.test.ts +91 -0
- package/quality/routeRuntimeReport.ts +121 -0
- package/quality/runtimeConstantFacts.ts +71 -0
- package/quality/runtimeConstantGraph.ts +123 -0
- package/quality/runtimeConstantReads.ts +116 -0
- package/quality/runtimeImports.test.ts +190 -0
- package/quality/runtimeImports.ts +233 -0
- package/quality/runtimeKeyNames.ts +46 -0
- package/quality/runtimeLexicalScope.ts +132 -0
- package/quality/runtimeMarkerReach.test.ts +84 -0
- package/quality/runtimeMarkerReach.ts +255 -0
- package/quality/runtimeModuleFacts.ts +290 -0
- package/quality/runtimeNameTable.test.ts +172 -0
- package/quality/runtimeNameTable.ts +477 -0
- package/quality/runtimeScopeReport.test.ts +123 -0
- package/quality/runtimeScopeReport.ts +167 -0
- package/quality/runtimeSliceKey.ts +269 -0
- package/quality/runtimeSyntax.ts +133 -0
- package/quality/runtimeTable.fixture.ts +189 -0
- package/quality/runtimeUse.test.ts +737 -0
- package/quality/runtimeUse.ts +696 -0
- package/quality/runtimeUseReadable.test.ts +393 -0
- package/quality/ssrScanner.test.ts +13 -0
- package/quality/ssrScanner.ts +1 -1
- package/quality/translatorBindings.ts +187 -0
- package/test/secretEnvFixture.ts +134 -0
- package/test/testHelpers.ts +11 -0
- package/transforms/barrelAnalyzer.ts +26 -4
- package/transforms/barrelImportsPlugin.ts +121 -32
- package/transforms/exportReach.test.ts +162 -0
- package/transforms/exportReach.ts +308 -0
- package/transforms/frameworkObjects.fixture.tsx +58 -0
- package/transforms/frameworkObjects.test.ts +54 -0
- package/transforms/modelReference.test.ts +196 -0
- package/transforms/modelReference.ts +39 -0
- package/transforms/moduleParts.test.ts +225 -0
- package/transforms/moduleParts.ts +418 -0
- package/transforms/objectImportEdits.ts +150 -0
- package/transforms/objectMemberImports.test.ts +629 -0
- package/transforms/objectMemberImports.ts +571 -0
- package/transforms/objectMemberLookup.ts +150 -0
- package/transforms/objectModule.test.ts +307 -0
- package/transforms/objectModule.ts +482 -0
- package/transforms/objectModuleAnalyzer.ts +104 -0
- package/transforms/partImports.test.ts +76 -0
- package/transforms/partImports.ts +110 -0
- package/transforms/partModules.test.ts +187 -0
- package/transforms/partModules.ts +90 -0
- package/transforms/partPurity.ts +124 -0
- package/transforms/reactIconImports.test.ts +231 -0
- package/transforms/reactIconImports.ts +325 -0
- package/transforms/routeConstants.ts +122 -0
- package/transforms/routeRuntime.test.ts +835 -0
- package/transforms/routeRuntime.ts +703 -0
- package/transforms/routeRuntimeEdits.ts +92 -0
- package/transforms/routeRuntimeGraph.ts +66 -0
- package/transforms/routeRuntimePlan.ts +244 -0
- package/transforms/secretEnvDeclaration.test.ts +208 -0
- package/transforms/secretEnvDeclaration.ts +213 -0
- package/transforms/secretEnvFile.test.ts +117 -0
- package/transforms/secretEnvFile.ts +113 -0
- package/transforms/secretEnvName.test.ts +54 -0
- package/transforms/secretEnvName.ts +29 -0
- package/transforms/secretEnvSource.test.ts +148 -0
- package/transforms/secretEnvSource.ts +166 -0
- package/transforms/serverEnvEvaluationError.ts +11 -0
- package/transforms/serverEnvPlugin.test.ts +2 -1
- package/transforms/serverEnvPlugin.ts +13 -0
- package/transforms/serverEnvProfile.test.ts +115 -2
- package/transforms/serverEnvProfile.ts +117 -40
- package/transforms/serverEnvSecrets.test.ts +292 -0
- package/transforms/signalDescriptors.test.ts +280 -0
- package/transforms/signalDescriptors.ts +227 -0
- package/transforms/thisFreeExports.ts +87 -0
- package/transforms/transforms.test.ts +180 -3
- package/transforms/tsconfigPackageResolver.test.ts +1 -0
- package/tunnel/createTunnel.test.ts +29 -8
- package/tunnel/createTunnel.ts +18 -11
- package/typecheck/projectTypecheck.test.ts +29 -0
- package/typecheck/typeChecker.test.ts +49 -0
- package/typecheck/typeChecker.ts +9 -7
- package/typecheck/withheldDiagnostics.ts +41 -0
- package/util/fileEditor.ts +1 -0
- package/util/selectModel.ts +1 -0
- package/workflow/executor.ts +6 -2
- package/workflow/index.ts +1 -0
- package/workflow/plan.ts +36 -7
- package/workflow/types.ts +1 -1
- package/workflow/uiTarget.ts +50 -0
- package/workspace/getRelatedCnsts.ts +7 -0
- package/workspace/scanInfo.test.ts +39 -0
- package/workspace/scanInfo.ts +48 -5
- package/workspace/workspaceLayout.ts +1 -0
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import type { ExportReach, ReachedImport } from "../transforms/exportReach";
|
|
3
|
+
import type { DiscoverOptions, ScannedImport } from "./clientBuildTypes";
|
|
4
|
+
|
|
5
|
+
export interface RenderedFile {
|
|
6
|
+
isClientEntry: boolean;
|
|
7
|
+
imports: ScannedImport[];
|
|
8
|
+
/** Null for a module whose exports cannot be read. */
|
|
9
|
+
reach?: ExportReach | null;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface RenderedGraph {
|
|
13
|
+
fileOf(file: string): Promise<RenderedFile | null>;
|
|
14
|
+
resolve(specifier: string, fromDir: string): Promise<string | null>;
|
|
15
|
+
/** Bumped when a file changed: an answer computed across a bump is not kept. */
|
|
16
|
+
epoch(): number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
interface ExportAsk {
|
|
20
|
+
file: string;
|
|
21
|
+
name: string;
|
|
22
|
+
how: "whole" | "always" | "named" | "starred";
|
|
23
|
+
key: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface AskAnswer {
|
|
27
|
+
isEntry: boolean;
|
|
28
|
+
whole: boolean;
|
|
29
|
+
next: ExportAsk[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
type ImportsAs = NonNullable<DiscoverOptions["importsAs"]>;
|
|
33
|
+
|
|
34
|
+
interface RenderedWalk {
|
|
35
|
+
serverModules: string[];
|
|
36
|
+
within: string[];
|
|
37
|
+
importsAs?: ImportsAs;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The client entries a route can render. A server module asked for one export gives only what that export's
|
|
42
|
+
* declaration reaches, and every server module the route evaluates gives what its top-level statements reach.
|
|
43
|
+
*/
|
|
44
|
+
export class RenderedEntries {
|
|
45
|
+
#graph: RenderedGraph;
|
|
46
|
+
#answers = new Map<string, AskAnswer>();
|
|
47
|
+
//? Keyed by a walk's `importsAs`: an ask's answer under swapped imports holds only for walks swapping the same ones.
|
|
48
|
+
#swappedAnswers = new WeakMap<ImportsAs, Map<string, AskAnswer>>();
|
|
49
|
+
|
|
50
|
+
constructor(graph: RenderedGraph) {
|
|
51
|
+
this.#graph = graph;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
forget(): void {
|
|
55
|
+
this.#answers.clear();
|
|
56
|
+
this.#swappedAnswers = new WeakMap();
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async of(seeds: string[], options: RenderedWalk): Promise<string[]> {
|
|
60
|
+
return [...(await this.asked(seeds, options)).keys()].sort();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
//* The same entries with the export names the route's server modules ask of each: null where one asks for them all.
|
|
64
|
+
async asked(
|
|
65
|
+
seeds: string[],
|
|
66
|
+
{ serverModules, within, importsAs }: RenderedWalk,
|
|
67
|
+
): Promise<Map<string, string[] | null>> {
|
|
68
|
+
const answers = importsAs ? this.#answersUnder(importsAs) : this.#answers;
|
|
69
|
+
const reachable = new Set(within);
|
|
70
|
+
const entries = new Map<string, string[] | null>();
|
|
71
|
+
const seen = new Set<string>();
|
|
72
|
+
const whole = new Set<string>();
|
|
73
|
+
const queue = seeds.map((seed) => RenderedEntries.#ask(path.resolve(seed), "whole"));
|
|
74
|
+
for (const file of serverModules) queue.push(RenderedEntries.#ask(file, "always"));
|
|
75
|
+
for (const ask of queue) {
|
|
76
|
+
if (seen.has(ask.key) || whole.has(ask.file)) continue;
|
|
77
|
+
seen.add(ask.key);
|
|
78
|
+
const answer = answers.get(ask.key) ?? (await this.#answer(ask, answers, importsAs));
|
|
79
|
+
if (answer.isEntry) {
|
|
80
|
+
if (ask.how === "always" || !reachable.has(ask.file)) continue;
|
|
81
|
+
const names = entries.get(ask.file);
|
|
82
|
+
if (ask.how === "whole") entries.set(ask.file, null);
|
|
83
|
+
else if (names === undefined) entries.set(ask.file, [ask.name]);
|
|
84
|
+
else if (names && !names.includes(ask.name)) names.push(ask.name);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (answer.whole) whole.add(ask.file);
|
|
88
|
+
for (const next of answer.next) if (!seen.has(next.key) && !whole.has(next.file)) queue.push(next);
|
|
89
|
+
}
|
|
90
|
+
return entries;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
#answersUnder(importsAs: ImportsAs): Map<string, AskAnswer> {
|
|
94
|
+
const answers = this.#swappedAnswers.get(importsAs) ?? new Map<string, AskAnswer>();
|
|
95
|
+
this.#swappedAnswers.set(importsAs, answers);
|
|
96
|
+
return answers;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async #answer(ask: ExportAsk, answers: Map<string, AskAnswer>, importsAs?: ImportsAs): Promise<AskAnswer> {
|
|
100
|
+
const epoch = this.#graph.epoch();
|
|
101
|
+
const answer = await this.#answerOf(ask, importsAs);
|
|
102
|
+
if (epoch === this.#graph.epoch()) answers.set(ask.key, answer);
|
|
103
|
+
return answer;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async #answerOf(ask: ExportAsk, importsAs?: ImportsAs): Promise<AskAnswer> {
|
|
107
|
+
const facts = await this.#graph.fileOf(ask.file);
|
|
108
|
+
if (!facts) return { isEntry: false, whole: false, next: [] };
|
|
109
|
+
if (facts.isClientEntry) return { isEntry: true, whole: false, next: [] };
|
|
110
|
+
const reached = RenderedEntries.#reachedBy(ask, facts);
|
|
111
|
+
const swaps = importsAs?.get(ask.file);
|
|
112
|
+
const next: ExportAsk[] = [];
|
|
113
|
+
for (const { specifier, names } of reached.imports) {
|
|
114
|
+
const swapped = swaps?.get(specifier);
|
|
115
|
+
const spec = swapped === undefined ? specifier : swapped;
|
|
116
|
+
if (!spec) continue;
|
|
117
|
+
const resolved = await this.#graph.resolve(spec, path.dirname(ask.file));
|
|
118
|
+
if (!resolved) continue;
|
|
119
|
+
const file = path.resolve(resolved);
|
|
120
|
+
if (names === null) next.push(RenderedEntries.#ask(file, "whole"));
|
|
121
|
+
else for (const name of names) next.push(RenderedEntries.#ask(file, reached.starred ? "starred" : "named", name));
|
|
122
|
+
}
|
|
123
|
+
return { isEntry: false, whole: reached.whole ?? false, next };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
//? A name asked through `export *` that the target does not hold is another target's, so it reaches nothing here.
|
|
127
|
+
static #reachedBy(
|
|
128
|
+
{ name, how }: ExportAsk,
|
|
129
|
+
{ reach, imports }: RenderedFile,
|
|
130
|
+
): { imports: ReachedImport[]; whole?: boolean; starred?: boolean } {
|
|
131
|
+
if (!reach) return { imports: imports.map((imported) => ({ specifier: imported.path, names: null })), whole: true };
|
|
132
|
+
if (how === "whole") return { imports: reach.whole(), whole: true };
|
|
133
|
+
if (how === "always") return { imports: reach.always() };
|
|
134
|
+
const reached = reach.of(name);
|
|
135
|
+
if (reached.known) return { imports: reached.imports };
|
|
136
|
+
if (reached.stars.length > 0)
|
|
137
|
+
return { imports: reached.stars.map((specifier) => ({ specifier, names: [name] })), starred: true };
|
|
138
|
+
return how === "starred" ? { imports: [] } : { imports: reach.whole(), whole: true };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
static #ask(file: string, how: ExportAsk["how"], name = ""): ExportAsk {
|
|
142
|
+
return { file, name, how, key: `${file}\0${how}\0${name}` };
|
|
143
|
+
}
|
|
144
|
+
}
|
|
@@ -1,17 +1,26 @@
|
|
|
1
|
-
import { mkdir } from "node:fs/promises";
|
|
1
|
+
import { mkdir, rm } from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import type { BaseBuildArtifact, ClientManifest, ClientManifestEntry, SsrManifest } from "akanjs/server";
|
|
4
4
|
import { SSR_DEV_CHUNK, SSR_DEV_ID_PREFIX } from "akanjs/server/hmr/csrDevManifest";
|
|
5
|
-
import { StoreBootstrap } from "../artifact/storeBootstrap";
|
|
5
|
+
import { type ClientRuntimeScope, StoreBootstrap } from "../artifact/storeBootstrap";
|
|
6
6
|
import type { App } from "../commandDecorators";
|
|
7
|
+
import { type RouteRuntimeBuildReport, RouteRuntimeReport } from "../quality/routeRuntimeReport";
|
|
7
8
|
import { createBarrelImportsPlugin } from "../transforms/barrelImportsPlugin";
|
|
9
|
+
import { ModuleParts } from "../transforms/moduleParts";
|
|
8
10
|
import { loaderFor } from "../transforms/moduleSyntax";
|
|
11
|
+
import { PartModules } from "../transforms/partModules";
|
|
12
|
+
import { ReactIconImports } from "../transforms/reactIconImports";
|
|
13
|
+
import { RouteRuntime } from "../transforms/routeRuntime";
|
|
14
|
+
import type { RouteRuntimeBundle } from "../transforms/routeRuntimeGraph";
|
|
9
15
|
import { scanUseClientExports, toClientReferencePath } from "../transforms/rscUseClientTransform";
|
|
10
|
-
import
|
|
16
|
+
import { SignalDescriptors } from "../transforms/signalDescriptors";
|
|
17
|
+
import type { AskedExports, ClientBundleTarget, ClientEntryDiscovery, ClientModuleImport } from "./clientBuildTypes";
|
|
11
18
|
import { ClientEntriesBundler } from "./clientEntriesBundler";
|
|
12
19
|
import { GraphClientEntryDiscovery } from "./clientEntryDiscovery";
|
|
13
20
|
import { CsrDevPaths } from "./csrDevPaths";
|
|
14
|
-
import {
|
|
21
|
+
import { RouteRuntimeCheck } from "./routeRuntimeCheck";
|
|
22
|
+
import { type RoutePaysVerdict, RouteRuntimePays } from "./routeRuntimePays";
|
|
23
|
+
import { VendorFileImports } from "./vendorFileImports";
|
|
15
24
|
|
|
16
25
|
const SSR_CLIENT_ALIAS_EXTERNALS = [
|
|
17
26
|
"react",
|
|
@@ -36,6 +45,12 @@ export interface BuildRouteClientOptions {
|
|
|
36
45
|
entries?: string[];
|
|
37
46
|
/** Defaults to `registry` under `start`: the browser loads each entry from the SSR dev registry, so only `client-ssr` builds. */
|
|
38
47
|
browser?: "chunks" | "registry";
|
|
48
|
+
/** The entries each route loads: an entry only whole-runtime routes hold keeps the whole runtime too. */
|
|
49
|
+
entriesByRoute?: ReadonlyMap<string, readonly string[]>;
|
|
50
|
+
/** The entries each route loads first, which its size is measured over. Defaults to `entriesByRoute`. */
|
|
51
|
+
sizedEntriesByRoute?: ReadonlyMap<string, readonly string[]>;
|
|
52
|
+
/** The exports each route asks of an entry it loads first; an entry left out, or null, is asked for all of them. */
|
|
53
|
+
askedByRoute?: ReadonlyMap<string, AskedExports>;
|
|
39
54
|
}
|
|
40
55
|
|
|
41
56
|
export interface BuildRouteClientResult {
|
|
@@ -49,13 +64,31 @@ export interface BuildRouteClientResult {
|
|
|
49
64
|
registryEntries?: string[];
|
|
50
65
|
/** Chunks mode: the importmap specifiers each browser chunk imports statically. */
|
|
51
66
|
externalsByChunkUrl?: Record<string, string[]>;
|
|
67
|
+
/** The imports of every module the browser loads, or in registry mode of the SSR bundle standing in for it. */
|
|
68
|
+
clientGraph?: ReadonlyMap<string, readonly ClientModuleImport[]>;
|
|
52
69
|
}
|
|
53
70
|
|
|
54
71
|
interface BootstrapEntries {
|
|
55
72
|
buildEntries: string[];
|
|
56
73
|
originalByBuildEntry: Map<string, string>;
|
|
74
|
+
//? Only for an entry built as several: the export names each of its build entries holds.
|
|
75
|
+
namesByBuildEntry?: Map<string, readonly string[]>;
|
|
57
76
|
}
|
|
58
77
|
|
|
78
|
+
interface NarrowedBuild {
|
|
79
|
+
entries: BootstrapEntries;
|
|
80
|
+
kept: ReadonlySet<string>;
|
|
81
|
+
bundle: Awaited<ReturnType<ClientEntriesBundler["bundle"]>>;
|
|
82
|
+
runtime: RouteRuntime;
|
|
83
|
+
report?: RouteRuntimeBuildReport;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
type BundleOf = (runtime: RouteRuntime, kept: ReadonlySet<string>, outputSubdir?: string) => Promise<NarrowedBuild>;
|
|
87
|
+
|
|
88
|
+
const referenceSubdir = "client-whole";
|
|
89
|
+
//? Each trial bundles the whole app again, and the entries left to try shrink slowly where pages share most of them.
|
|
90
|
+
const measuredTrials = 6;
|
|
91
|
+
|
|
59
92
|
export class RouteClientBuilder {
|
|
60
93
|
#app: App;
|
|
61
94
|
#seeds: string[];
|
|
@@ -65,6 +98,10 @@ export class RouteClientBuilder {
|
|
|
65
98
|
#discovery?: ClientEntryDiscovery;
|
|
66
99
|
#entries?: string[];
|
|
67
100
|
#browser: "chunks" | "registry";
|
|
101
|
+
#entriesByRoute?: ReadonlyMap<string, readonly string[]>;
|
|
102
|
+
#sizedEntriesByRoute?: ReadonlyMap<string, readonly string[]>;
|
|
103
|
+
#askedByRoute?: ReadonlyMap<string, AskedExports>;
|
|
104
|
+
readonly #parts = new Map<string, ModuleParts | null>();
|
|
68
105
|
|
|
69
106
|
constructor(options: BuildRouteClientOptions) {
|
|
70
107
|
this.#app = options.app;
|
|
@@ -75,6 +112,9 @@ export class RouteClientBuilder {
|
|
|
75
112
|
this.#discovery = options.discovery;
|
|
76
113
|
this.#entries = options.entries;
|
|
77
114
|
this.#browser = options.browser ?? (this.#command === "start" ? "registry" : "chunks");
|
|
115
|
+
this.#entriesByRoute = options.entriesByRoute;
|
|
116
|
+
this.#sizedEntriesByRoute = options.sizedEntriesByRoute;
|
|
117
|
+
this.#askedByRoute = options.askedByRoute;
|
|
78
118
|
}
|
|
79
119
|
|
|
80
120
|
async build(): Promise<BuildRouteClientResult> {
|
|
@@ -84,12 +124,34 @@ export class RouteClientBuilder {
|
|
|
84
124
|
? [...new Set([...discovered, ...(await (await this.#getDiscovery()).discover(this.#graphSeeds))])].sort()
|
|
85
125
|
: discovered.filter((e) => !this.#knownEntries.has(e));
|
|
86
126
|
|
|
87
|
-
const bootstrapEntries = await this.#createBootstrapEntries(entries);
|
|
88
127
|
//? Registry mode builds no browser bundle: the SSR bundle has the same entries, exports and imports to read.
|
|
89
128
|
const registry = this.#browser === "registry" ? new CsrDevPaths(this.#app.workspace.workspaceRoot) : null;
|
|
90
|
-
const
|
|
91
|
-
|
|
129
|
+
const routeRuntime = registry ? null : await this.#readRouteRuntime();
|
|
130
|
+
if (!registry && !routeRuntime) await rm(path.join(this.#app.cwdPath, RouteRuntimeReport.file), { force: true });
|
|
131
|
+
const ssrEntries = await this.#createBootstrapEntries(entries, "whole");
|
|
132
|
+
//? First: its entries all load the whole runtime, so its graph says which of them a per-route build may narrow.
|
|
133
|
+
const ssrBundle = await this.#buildSsrBundle(ssrEntries);
|
|
134
|
+
const narrowed = routeRuntime
|
|
135
|
+
? await this.#buildNarrowed(entries, ssrEntries, routeRuntime, {
|
|
136
|
+
importsByModule: ssrBundle.graph.importsByModule,
|
|
137
|
+
entries: entries.map((entry) => path.resolve(entry)),
|
|
138
|
+
entriesByRoute: this.#entriesByRoute,
|
|
139
|
+
})
|
|
140
|
+
: null;
|
|
141
|
+
const trusted = narrowed && this.#check(narrowed) ? narrowed : null;
|
|
142
|
+
const browserEntries = registry ? null : (trusted?.entries ?? ssrEntries);
|
|
143
|
+
const browserBundle =
|
|
144
|
+
trusted?.bundle ?? (browserEntries ? await this.#buildBrowserBundle(browserEntries, null) : null);
|
|
145
|
+
if (trusted?.report) await this.#say(trusted.report);
|
|
146
|
+
if (narrowed && !trusted && browserBundle) {
|
|
147
|
+
await rm(path.join(this.#app.cwdPath, RouteRuntimeReport.file), { force: true });
|
|
148
|
+
await RouteClientBuilder.#removeChunks(narrowed.bundle, browserBundle);
|
|
149
|
+
}
|
|
92
150
|
const referenceBundle = browserBundle ?? ssrBundle;
|
|
151
|
+
const bootstrapEntries = browserEntries ?? ssrEntries;
|
|
152
|
+
const ssrEntryByOriginal = new Map(
|
|
153
|
+
[...ssrEntries.originalByBuildEntry].map(([buildEntry, originalEntry]) => [originalEntry, buildEntry]),
|
|
154
|
+
);
|
|
93
155
|
|
|
94
156
|
const acceptedEntries = new Set(entries);
|
|
95
157
|
const routeEntries = new Set(discovered);
|
|
@@ -111,7 +173,9 @@ export class RouteClientBuilder {
|
|
|
111
173
|
: bundleRow;
|
|
112
174
|
manifestDelta[manifestEntry.key] = row;
|
|
113
175
|
|
|
114
|
-
const ssrOutput = ssrBundle.entryOutputAbsByAbsPath.get(
|
|
176
|
+
const ssrOutput = ssrBundle.entryOutputAbsByAbsPath.get(
|
|
177
|
+
ssrEntryByOriginal.get(manifestEntry.originalEntry) ?? manifestEntry.buildEntry,
|
|
178
|
+
);
|
|
115
179
|
if (!ssrOutput) continue;
|
|
116
180
|
|
|
117
181
|
ssrModuleMap[row.id] ??= {};
|
|
@@ -121,7 +185,7 @@ export class RouteClientBuilder {
|
|
|
121
185
|
const buildEntry = path.resolve(entry);
|
|
122
186
|
const originalEntry = path.resolve(bootstrapEntries.originalByBuildEntry.get(buildEntry) ?? buildEntry);
|
|
123
187
|
if (!acceptedEntries.has(originalEntry)) continue;
|
|
124
|
-
const deps = new Set<string>([originalEntry]);
|
|
188
|
+
const deps = new Set<string>(clientDepsByEntry[originalEntry] ?? [originalEntry]);
|
|
125
189
|
for (const dep of referenceBundle.entryDepsByAbsPath.get(buildEntry) ?? []) deps.add(path.resolve(dep));
|
|
126
190
|
const sortedDeps = [...deps].sort();
|
|
127
191
|
clientDepsByEntry[originalEntry] = sortedDeps;
|
|
@@ -137,6 +201,7 @@ export class RouteClientBuilder {
|
|
|
137
201
|
clientDepsByEntry,
|
|
138
202
|
...(registry ? { registryEntries: [...acceptedEntries].sort() } : {}),
|
|
139
203
|
...(browserBundle ? { externalsByChunkUrl: Object.fromEntries(browserBundle.externalsByChunkUrl) } : {}),
|
|
204
|
+
clientGraph: referenceBundle.graph.importsByModule,
|
|
140
205
|
};
|
|
141
206
|
}
|
|
142
207
|
|
|
@@ -165,23 +230,237 @@ export class RouteClientBuilder {
|
|
|
165
230
|
};
|
|
166
231
|
}
|
|
167
232
|
|
|
168
|
-
async #
|
|
233
|
+
async #readRouteRuntime(): Promise<RouteRuntime | null> {
|
|
234
|
+
const { name } = this.#app;
|
|
235
|
+
const whole = (why: string, first = "Run") => {
|
|
236
|
+
this.#app.logger.warn(
|
|
237
|
+
`[client-runtime] ${why}, so every page of this build loads the whole client runtime, not only what it uses. ${first} \`akan sync ${name}\` and build again.`,
|
|
238
|
+
);
|
|
239
|
+
return null;
|
|
240
|
+
};
|
|
241
|
+
const missing = `the per-module runtime files of ${name} or a lib it mounts are missing`;
|
|
242
|
+
if ((await StoreBootstrap.scopeOf(this.#app)) !== "page") return whole(missing);
|
|
243
|
+
try {
|
|
244
|
+
return (await RouteRuntime.read(this.#app.workspace.workspaceRoot, `apps/${name}`)) ?? whole(missing);
|
|
245
|
+
} catch (error) {
|
|
246
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
247
|
+
return whole(`the modules of ${name} or a lib it mounts could not be read (${reason})`, "Fix that, then run");
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async #buildNarrowed(
|
|
252
|
+
entries: string[],
|
|
253
|
+
whole: BootstrapEntries,
|
|
254
|
+
runtime: RouteRuntime,
|
|
255
|
+
planned: RouteRuntimeBundle,
|
|
256
|
+
): Promise<NarrowedBuild> {
|
|
257
|
+
const bundleOf: BundleOf = async (routeRuntime, kept, outputSubdir) => {
|
|
258
|
+
const started = Date.now();
|
|
259
|
+
const browserEntries = await this.#createBootstrapEntries(entries, "page", { kept, whole });
|
|
260
|
+
const bundle = await this.#buildBrowserBundle(browserEntries, routeRuntime, outputSubdir);
|
|
261
|
+
this.#app.verbose(`[client-runtime] bundled ${outputSubdir ?? "client"} (${Date.now() - started}ms)`);
|
|
262
|
+
return { entries: browserEntries, kept, bundle, runtime: routeRuntime };
|
|
263
|
+
};
|
|
264
|
+
const first = await bundleOf(runtime, runtime.plan(planned));
|
|
265
|
+
const routes = this.#entriesByRoute;
|
|
266
|
+
if (!routes || !runtime.decided) return first;
|
|
267
|
+
const perModuleIn = ({ kept }: NarrowedBuild) =>
|
|
268
|
+
[...routes].filter(([, held]) => !held.some((entry) => kept.has(entry))).map(([route]) => route);
|
|
269
|
+
const analysed = perModuleIn(first);
|
|
270
|
+
const { built, refused } =
|
|
271
|
+
analysed.length > 0
|
|
272
|
+
? await this.#keptWhereNotSmaller(first, routes, planned, bundleOf)
|
|
273
|
+
: { built: first, refused: [] };
|
|
274
|
+
const perModule = perModuleIn(built);
|
|
275
|
+
return {
|
|
276
|
+
...built,
|
|
277
|
+
report: {
|
|
278
|
+
app: this.#app.name,
|
|
279
|
+
routes: routes.size,
|
|
280
|
+
perModule,
|
|
281
|
+
notSmaller: analysed.filter((route) => !perModule.includes(route)),
|
|
282
|
+
refused,
|
|
283
|
+
causes: built.runtime.decided?.causes() ?? [],
|
|
284
|
+
},
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async #say(report: RouteRuntimeBuildReport) {
|
|
289
|
+
await RouteRuntimeReport.write(this.#app.cwdPath, report);
|
|
290
|
+
this.#app.log(`[client-runtime] ${RouteRuntimeReport.summary(report)}`);
|
|
291
|
+
for (const route of report.notSmaller) this.#app.verbose(`[client-runtime] not smaller per module: ${route}`);
|
|
292
|
+
for (const route of report.refused ?? [])
|
|
293
|
+
this.#app.verbose(`[client-runtime] larger with the whole runtime here: ${route}`);
|
|
294
|
+
for (const route of report.perModule) this.#app.verbose(`[client-runtime] per module: ${route}`);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
static async #removeChunks(replaced: NarrowedBuild["bundle"], served: NarrowedBuild["bundle"]) {
|
|
298
|
+
for (const chunk of replaced.graph.importsByChunk.keys())
|
|
299
|
+
if (!served.graph.importsByChunk.has(chunk)) await rm(chunk, { force: true });
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
//? A pass either keeps entries or refuses some for good, and neither set ever loses one, so the passes end.
|
|
303
|
+
async #keptWhereNotSmaller(
|
|
304
|
+
first: NarrowedBuild,
|
|
305
|
+
routes: ReadonlyMap<string, readonly string[]>,
|
|
306
|
+
planned: RouteRuntimeBundle,
|
|
307
|
+
bundleOf: BundleOf,
|
|
308
|
+
): Promise<{ built: NarrowedBuild; refused: string[] }> {
|
|
309
|
+
const pays = new RouteRuntimePays();
|
|
310
|
+
const sizesOf = (build: NarrowedBuild) => pays.sizesOf(build.bundle, this.#sizedBuildEntries(build.entries));
|
|
311
|
+
//? A keep is never taken back, so a build that did not pay is replaced from a runtime read again.
|
|
312
|
+
const bundleWith = async (verdicts: readonly RoutePaysVerdict[], last: NarrowedBuild | null, subdir?: string) => {
|
|
313
|
+
const runtime = await this.#readRouteRuntime();
|
|
314
|
+
if (!runtime) return null;
|
|
315
|
+
let kept = runtime.plan(planned);
|
|
316
|
+
for (const { entry, ...measured } of verdicts) kept = runtime.keep([entry], { rule: "not-smaller", ...measured });
|
|
317
|
+
const build = await bundleOf(runtime, subdir ? runtime.keepAll() : kept, subdir);
|
|
318
|
+
if (last) await RouteClientBuilder.#removeChunks(last.bundle, build.bundle);
|
|
319
|
+
return build;
|
|
320
|
+
};
|
|
321
|
+
const reference = await bundleWith([], null, referenceSubdir);
|
|
322
|
+
if (!reference) return { built: first, refused: [] };
|
|
323
|
+
const wholeSizes = await sizesOf(reference);
|
|
324
|
+
await rm(path.join(this.#artifactDir, referenceSubdir), { recursive: true, force: true });
|
|
325
|
+
let current = { build: first, sizes: await sizesOf(first), verdicts: [] as RoutePaysVerdict[] };
|
|
326
|
+
let onDisk = first;
|
|
327
|
+
const refused = new Set<string>();
|
|
328
|
+
const refusedRoutes = new Set<string>();
|
|
329
|
+
for (let trial = 0; trial < measuredTrials; trial++) {
|
|
330
|
+
const verdicts = RouteRuntimePays.decide({
|
|
331
|
+
entriesByRoute: routes,
|
|
332
|
+
isKept: (entry) => current.build.kept.has(entry),
|
|
333
|
+
isRefused: (entry) => refused.has(entry),
|
|
334
|
+
whole: wholeSizes,
|
|
335
|
+
measured: current.sizes,
|
|
336
|
+
});
|
|
337
|
+
if (verdicts.length === 0) break;
|
|
338
|
+
const tried = await bundleWith([...current.verdicts, ...verdicts], onDisk);
|
|
339
|
+
if (!tried) break;
|
|
340
|
+
onDisk = tried;
|
|
341
|
+
const sizes = await sizesOf(tried);
|
|
342
|
+
const larger = RouteRuntimePays.larger({
|
|
343
|
+
entriesByRoute: routes,
|
|
344
|
+
wasKept: (entry) => current.build.kept.has(entry),
|
|
345
|
+
isKept: (entry) => tried.kept.has(entry),
|
|
346
|
+
before: current.sizes,
|
|
347
|
+
after: sizes,
|
|
348
|
+
});
|
|
349
|
+
if (larger.length === 0) {
|
|
350
|
+
current = { build: tried, sizes, verdicts: [...current.verdicts, ...verdicts] };
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
for (const route of larger) {
|
|
354
|
+
refusedRoutes.add(route);
|
|
355
|
+
for (const entry of routes.get(route) ?? []) refused.add(entry);
|
|
356
|
+
}
|
|
357
|
+
if (!verdicts.some(({ entry }) => refused.has(entry))) for (const { entry } of verdicts) refused.add(entry);
|
|
358
|
+
}
|
|
359
|
+
const built = onDisk === current.build ? onDisk : ((await bundleWith(current.verdicts, onDisk)) ?? onDisk);
|
|
360
|
+
return { built, refused: [...refusedRoutes] };
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
get #artifactDir() {
|
|
364
|
+
return path.join(this.#command === "build" ? this.#app.dist.cwdPath : this.#app.cwdPath, ".akan/artifact");
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
#sizedBuildEntries(entries: BootstrapEntries): Map<string, string[]> {
|
|
368
|
+
const buildEntriesOf = RouteClientBuilder.#buildEntriesOf(entries);
|
|
369
|
+
return new Map(
|
|
370
|
+
[...(this.#sizedEntriesByRoute ?? this.#entriesByRoute ?? [])].map(([route, held]) => {
|
|
371
|
+
const asked = this.#askedByRoute?.get(route);
|
|
372
|
+
return [route, held.flatMap((entry) => buildEntriesOf(entry, asked?.get(path.resolve(entry))))];
|
|
373
|
+
}),
|
|
374
|
+
);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
//? An entry built as several answers with the ones holding a name asked, and with all of them asked for none.
|
|
378
|
+
static #buildEntriesOf({ originalByBuildEntry, namesByBuildEntry }: BootstrapEntries) {
|
|
379
|
+
const built = new Map<string, string[]>();
|
|
380
|
+
for (const [buildEntry, original] of originalByBuildEntry) built.getOrInsert(original, []).push(buildEntry);
|
|
381
|
+
return (entry: string, asked?: readonly string[] | null): string[] => {
|
|
382
|
+
const buildEntries = built.get(path.resolve(entry)) ?? [path.resolve(entry)];
|
|
383
|
+
if (!asked) return buildEntries;
|
|
384
|
+
return buildEntries.filter((buildEntry) => {
|
|
385
|
+
const names = namesByBuildEntry?.get(buildEntry);
|
|
386
|
+
return !names || names.some((name) => asked.includes(name));
|
|
387
|
+
});
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
#check({ entries, kept, bundle, runtime: routeRuntime }: NarrowedBuild): boolean {
|
|
392
|
+
const { workspaceRoot } = this.#app.workspace;
|
|
393
|
+
const buildEntriesOf = RouteClientBuilder.#buildEntriesOf(entries);
|
|
394
|
+
const check = new RouteRuntimeCheck(workspaceRoot, bundle.graph, {
|
|
395
|
+
entries: new Map([...entries.originalByBuildEntry].filter(([, entry]) => !kept.has(entry))),
|
|
396
|
+
wholeReaders: routeRuntime.wholeReaders,
|
|
397
|
+
wholeConstantReaders: routeRuntime.wholeConstantReaders,
|
|
398
|
+
routes: new Map(
|
|
399
|
+
[...(this.#entriesByRoute ?? [])].map(([route, held]) => [
|
|
400
|
+
route,
|
|
401
|
+
held.flatMap((entry) => buildEntriesOf(entry)),
|
|
402
|
+
]),
|
|
403
|
+
),
|
|
404
|
+
});
|
|
405
|
+
const { refusal, repeated } = check;
|
|
406
|
+
if (refusal) {
|
|
407
|
+
this.#app.logger.warn(refusal);
|
|
408
|
+
return false;
|
|
409
|
+
}
|
|
410
|
+
if (repeated.length === 0) return true;
|
|
411
|
+
const more = repeated.length - RouteRuntimeCheck.shown;
|
|
412
|
+
this.#app.logger.warn(
|
|
413
|
+
[
|
|
414
|
+
`[client-runtime] a page keeping the whole runtime loads a piece of what that runtime already holds:`,
|
|
415
|
+
...repeated.slice(0, RouteRuntimeCheck.shown).map((line) => ` - ${line}`),
|
|
416
|
+
...(more > 0 ? [` - and ${more} more`] : []),
|
|
417
|
+
].join("\n"),
|
|
418
|
+
);
|
|
419
|
+
return true;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
async #buildBrowserBundle(
|
|
423
|
+
bootstrapEntries: BootstrapEntries,
|
|
424
|
+
routeRuntime: RouteRuntime | null,
|
|
425
|
+
outputSubdir?: string,
|
|
426
|
+
) {
|
|
169
427
|
const reactFastRefresh = process.env.AKAN_REACT_FAST_REFRESH !== "0";
|
|
428
|
+
const icons = ReactIconImports.forApp(this.#app);
|
|
429
|
+
const vendorFiles = await VendorFileImports.of(this.#app.workspace.workspaceRoot);
|
|
170
430
|
return new ClientEntriesBundler({
|
|
171
431
|
app: this.#app,
|
|
172
432
|
entries: bootstrapEntries.buildEntries,
|
|
173
433
|
plugins: [
|
|
434
|
+
icons.plugin,
|
|
435
|
+
...(routeRuntime ? [this.#signalDescriptors(routeRuntime)] : []),
|
|
436
|
+
vendorFiles.plugin(),
|
|
174
437
|
await createBarrelImportsPlugin(this.#app, {
|
|
175
|
-
pipeAfter:
|
|
176
|
-
|
|
438
|
+
pipeAfter: icons.pipe(
|
|
439
|
+
reactFastRefresh ? RouteClientBuilder.normalizeNamedDefaultFunctionForFastRefresh : undefined,
|
|
440
|
+
),
|
|
441
|
+
external: vendorFiles.specifiers,
|
|
442
|
+
routeRuntime,
|
|
443
|
+
...(this.#command === "build" ? { parts: this.#parts } : {}),
|
|
177
444
|
}),
|
|
178
445
|
],
|
|
179
|
-
external:
|
|
446
|
+
external: vendorFiles.specifiers,
|
|
180
447
|
command: this.#command,
|
|
181
448
|
reactFastRefresh,
|
|
449
|
+
...(outputSubdir ? { outputSubdir } : {}),
|
|
182
450
|
}).bundle();
|
|
183
451
|
}
|
|
184
452
|
|
|
453
|
+
#signalDescriptors(routeRuntime: RouteRuntime) {
|
|
454
|
+
const scopes = routeRuntime.table.layers.map(({ scope }) => scope);
|
|
455
|
+
return new SignalDescriptors(this.#app.workspace.workspaceRoot, scopes, {
|
|
456
|
+
onUnread: (reason) =>
|
|
457
|
+
this.#app.logger.warn(
|
|
458
|
+
`[client-runtime] ${reason}, so each of their pieces reads its signal again: a slower build of the same pages. Run \`akan sync ${this.#app.name}\` if their generated files are from an earlier release.`,
|
|
459
|
+
),
|
|
460
|
+
takenFromPieces: (absPath) => routeRuntime.takenFromPieces(absPath),
|
|
461
|
+
}).plugin;
|
|
462
|
+
}
|
|
463
|
+
|
|
185
464
|
async #buildSsrBundle(bootstrapEntries: BootstrapEntries) {
|
|
186
465
|
return new ClientEntriesBundler({
|
|
187
466
|
app: this.#app,
|
|
@@ -193,40 +472,71 @@ export class RouteClientBuilder {
|
|
|
193
472
|
}).bundle();
|
|
194
473
|
}
|
|
195
474
|
|
|
196
|
-
|
|
475
|
+
//? `narrowed.kept`: an entry keeping the whole runtime is the same file a build of every page on it bundles.
|
|
476
|
+
async #createBootstrapEntries(
|
|
477
|
+
entries: string[],
|
|
478
|
+
scope: ClientRuntimeScope,
|
|
479
|
+
narrowed?: { kept: ReadonlySet<string>; whole: BootstrapEntries },
|
|
480
|
+
): Promise<BootstrapEntries> {
|
|
197
481
|
if (!(await Bun.file(path.join(this.#app.cwdPath, "lib", "st.ts")).exists())) {
|
|
198
482
|
return { buildEntries: entries, originalByBuildEntry: new Map() };
|
|
199
483
|
}
|
|
484
|
+
const wholeByOriginal = new Map(
|
|
485
|
+
[...(narrowed?.whole.originalByBuildEntry ?? [])].map(([buildEntry, original]) => [original, buildEntry]),
|
|
486
|
+
);
|
|
200
487
|
|
|
201
|
-
const
|
|
488
|
+
const dirName = scope === "page" ? "client-entry-bootstrap-route" : "client-entry-bootstrap";
|
|
489
|
+
const outdir = path.join(this.#app.cwdPath, ".akan", "generated", dirName);
|
|
202
490
|
await mkdir(outdir, { recursive: true });
|
|
203
491
|
|
|
204
492
|
const originalByBuildEntry = new Map<string, string>();
|
|
493
|
+
const namesByBuildEntry = new Map<string, readonly string[]>();
|
|
494
|
+
const { workspaceRoot } = this.#app.workspace;
|
|
205
495
|
const buildEntries = await Promise.all(
|
|
206
496
|
entries.map(async (entry) => {
|
|
207
497
|
const absEntry = path.resolve(entry);
|
|
498
|
+
const whole = narrowed?.kept.has(absEntry) ? wholeByOriginal.get(absEntry) : undefined;
|
|
499
|
+
if (whole) {
|
|
500
|
+
originalByBuildEntry.set(whole, absEntry);
|
|
501
|
+
return [whole];
|
|
502
|
+
}
|
|
208
503
|
const hash = Bun.hash(`${this.#app.name}\n${absEntry}`).toString(36);
|
|
209
504
|
const base = path.basename(absEntry).replace(/[^A-Za-z0-9._-]/g, "_");
|
|
210
|
-
const
|
|
211
|
-
const exportNames =
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
505
|
+
const source = await Bun.file(absEntry).text();
|
|
506
|
+
const exportNames = scanUseClientExports(source, absEntry, workspaceRoot);
|
|
507
|
+
const byExport = scope === "page" && this.#command === "build" && PartModules.splits(workspaceRoot, absEntry);
|
|
508
|
+
const groups = byExport ? RouteClientBuilder.#exportGroups(source, absEntry, exportNames) : [exportNames];
|
|
509
|
+
return await Promise.all(
|
|
510
|
+
groups.map(async (names, index) => {
|
|
511
|
+
const wrapperEntry = path.join(outdir, `${base}-${hash}${groups.length > 1 ? `-${index}` : ""}.tsx`);
|
|
512
|
+
await Bun.write(
|
|
513
|
+
wrapperEntry,
|
|
514
|
+
RouteClientBuilder.createStoreBootstrapEntrySource({
|
|
515
|
+
appName: this.#app.name,
|
|
516
|
+
originalEntry: absEntry,
|
|
517
|
+
exportNames: names,
|
|
518
|
+
scope,
|
|
519
|
+
}),
|
|
520
|
+
);
|
|
521
|
+
originalByBuildEntry.set(path.resolve(wrapperEntry), absEntry);
|
|
522
|
+
if (groups.length > 1) namesByBuildEntry.set(path.resolve(wrapperEntry), names);
|
|
523
|
+
return wrapperEntry;
|
|
218
524
|
}),
|
|
219
525
|
);
|
|
220
|
-
originalByBuildEntry.set(path.resolve(wrapperEntry), absEntry);
|
|
221
|
-
return wrapperEntry;
|
|
222
526
|
}),
|
|
223
527
|
);
|
|
224
528
|
|
|
225
|
-
return { buildEntries, originalByBuildEntry };
|
|
529
|
+
return { buildEntries: buildEntries.flat(), originalByBuildEntry, namesByBuildEntry };
|
|
226
530
|
}
|
|
227
531
|
|
|
228
|
-
|
|
229
|
-
|
|
532
|
+
//? Names one part of the file holds share a build entry. The parts are read from the file as written, and a bundle
|
|
533
|
+
//? may place a name elsewhere after its rewrites: then a build entry only loads more than the names it holds need.
|
|
534
|
+
static #exportGroups(source: string, absEntry: string, names: string[]): string[][] {
|
|
535
|
+
const parts = names.length > 0 ? ModuleParts.read(source, absEntry) : null;
|
|
536
|
+
if (!parts) return [names];
|
|
537
|
+
const groups = new Map<string, string[]>();
|
|
538
|
+
for (const name of names) groups.getOrInsert(parts.partOf(name) ?? "", []).push(name);
|
|
539
|
+
return [...groups.values()];
|
|
230
540
|
}
|
|
231
541
|
|
|
232
542
|
static normalizeNamedDefaultFunctionForFastRefresh(
|
|
@@ -317,11 +627,12 @@ export class RouteClientBuilder {
|
|
|
317
627
|
appName: string;
|
|
318
628
|
originalEntry: string;
|
|
319
629
|
exportNames: string[];
|
|
630
|
+
scope?: ClientRuntimeScope;
|
|
320
631
|
}): string {
|
|
321
632
|
const originalEntry = JSON.stringify(path.resolve(args.originalEntry));
|
|
322
633
|
const namedExports = args.exportNames.filter((name) => name !== "default");
|
|
323
634
|
const lines = [
|
|
324
|
-
...StoreBootstrap.importLines(args.appName),
|
|
635
|
+
...StoreBootstrap.importLines(args.appName, args.scope),
|
|
325
636
|
...(namedExports.length > 0 ? [`export { ${namedExports.join(", ")} } from ${originalEntry};`] : []),
|
|
326
637
|
];
|
|
327
638
|
if (args.exportNames.includes("default")) lines.push(`export { default } from ${originalEntry};`);
|