@akanjs/devkit 3.3.0-rc.6 → 3.3.0-rc.60
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/DEV_RUNTIME_KNOBS.md +1 -1
- package/README.ko.md +8 -2
- package/README.md +8 -3
- package/akanApp/akanApp.host.test.ts +4 -2
- package/akanApp/akanApp.host.ts +11 -0
- package/akanConfig/akanBin.ts +4 -0
- package/akanConfig/akanConfig.test.ts +280 -19
- package/akanConfig/akanConfig.ts +96 -270
- package/akanConfig/akanWorkers.test.ts +73 -0
- package/akanConfig/akanWorkers.ts +61 -0
- package/akanConfig/desktopServerConfig.ts +96 -0
- package/akanConfig/dockerImage.ts +216 -0
- package/akanConfig/index.ts +2 -0
- package/akanConfig/nativeFileSettings.ts +33 -0
- package/akanConfig/nativeKeys.ts +52 -0
- package/akanConfig/types.ts +2 -0
- package/app/appBin.test.ts +63 -0
- package/app/appBin.ts +50 -0
- package/app/applicationBuildReporter.test.ts +51 -1
- package/app/applicationBuildReporter.ts +6 -1
- package/app/applicationBuildRunner.test.ts +358 -5
- package/app/applicationBuildRunner.ts +204 -30
- package/app/dictionarySizes.test.ts +40 -0
- package/app/dictionarySizes.ts +95 -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 +7 -5
- 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-debug/SKILL.md +1 -1
- 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 +46 -29
- package/codeAgent/skills/akan-query/SKILL.md +13 -20
- package/codeAgent/skills/akan-runtime/SKILL.md +21 -1
- package/codeAgent/skills/akan-service/SKILL.md +10 -11
- package/codeAgent/skills/akan-transport/SKILL.md +5 -14
- package/codeAgent/skills/akan-ui/SKILL.md +16 -21
- package/commandDecorators/command.ts +28 -12
- package/commandDecorators/commandBuilder.ts +8 -1
- package/commandDecorators/commandDecorators.test.ts +70 -3
- package/commandDecorators/helpFormatter.ts +14 -12
- package/context/akanContext.ts +2 -0
- package/csrE2e/devHmrLatency.e2e.test.ts +1 -1
- package/docs/apiReference.test.ts +9 -0
- package/docs/apiReference.ts +15 -0
- package/executors/appExecutor.ts +26 -12
- package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
- package/executors/clientRuntimeKeys.fixture.json +393 -0
- package/executors/clientRuntimeKeys.test.ts +1690 -0
- package/executors/executor.ts +14 -6
- package/executors/executors.test.ts +140 -1
- package/executors/sysExecutor.ts +112 -8
- package/executors/workspaceExecutor.ts +7 -4
- package/frontendBuild/allRoutesBuilder.ts +99 -7
- package/frontendBuild/autoImportSync.ts +3 -2
- package/frontendBuild/buildRouteClient.test.ts +686 -13
- package/frontendBuild/clientBuildTypes.ts +26 -0
- package/frontendBuild/clientEntriesBundler.ts +49 -1
- package/frontendBuild/clientEntryDiscovery.test.ts +308 -1
- package/frontendBuild/clientEntryDiscovery.ts +136 -14
- package/frontendBuild/clientEntryGroups.test.ts +77 -0
- package/frontendBuild/clientEntryGroups.ts +61 -0
- package/frontendBuild/csrDevArtifactWriter.ts +2 -2
- package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
- package/frontendBuild/csrDevModuleCompiler.ts +44 -8
- package/frontendBuild/csrDevPatcher.test.ts +1 -1
- 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 +408 -0
- package/frontendBuild/dictionaryAssetBuilder.ts +185 -17
- package/frontendBuild/dictionaryConstants.ts +136 -0
- package/frontendBuild/dictionaryOwnParts.ts +88 -0
- package/frontendBuild/dictionaryPackState.ts +131 -0
- package/frontendBuild/dictionaryPacking.test.ts +207 -0
- package/frontendBuild/dictionaryPacking.ts +160 -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 +78 -2
- package/frontendBuild/precompressArtifacts.test.ts +22 -0
- package/frontendBuild/precompressArtifacts.ts +34 -8
- package/frontendBuild/registryMetadataFingerprint.ts +3 -3
- package/frontendBuild/renderedEntries.ts +144 -0
- package/frontendBuild/routeClientBuilder.ts +407 -43
- 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/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 +50 -3
- package/lint/biomeBase.ts +1 -1
- package/lint/biomeCheck.test.ts +162 -0
- package/lint/biomeCheck.ts +131 -0
- package/lint/linter.test.ts +16 -11
- 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.test.ts +18 -3
- package/mobile/desktopServerStage.ts +7 -2
- 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/nativePublicEnv.ts +1 -1
- package/mobile/serverBundleSecrets.ts +43 -0
- package/package.json +20 -171
- 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 +633 -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 +129 -2
- package/transforms/serverEnvProfile.ts +126 -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 +22 -11
- package/tunnel/ssh2Module.test.ts +37 -0
- package/tunnel/ssh2Module.ts +32 -0
- package/tunnel/sshTunnel.ts +4 -2
- package/typecheck/projectTypecheck.test.ts +32 -1
- package/typecheck/projectTypecheck.ts +3 -3
- 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/envSeed.test.ts +30 -1
- package/workspace/envSeed.ts +30 -1
- package/workspace/getRelatedCnsts.ts +7 -0
- package/workspace/mainCheckout.test.ts +55 -0
- package/workspace/mainCheckout.ts +38 -0
- package/workspace/scanInfo.test.ts +39 -0
- package/workspace/scanInfo.ts +55 -6
- package/workspace/slicePlanner.ts +1 -1
- package/workspace/workspaceLayout.test.ts +5 -1
- package/workspace/workspaceLayout.ts +3 -0
- package/CHANGELOG.md +0 -2717
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { type DictionaryOwnNeed, DictionaryOwnParts } from "./dictionaryOwnParts";
|
|
2
|
+
import { DictionaryPackState } from "./dictionaryPackState";
|
|
3
|
+
|
|
4
|
+
export interface DictionaryPack {
|
|
5
|
+
//? Each file's groups. A group no route names sits in the last file, which only a translation miss asks for.
|
|
6
|
+
parts: string[][];
|
|
7
|
+
//? Files past `parts` in `partsByRoute`: each holds, for the routes naming it, the groups of their files past the bound.
|
|
8
|
+
ownParts: string[][];
|
|
9
|
+
partsByRoute: Record<string, number[]>;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface DictionaryPackOptions {
|
|
13
|
+
bound?: number;
|
|
14
|
+
requestBytes?: number;
|
|
15
|
+
overfetchBytes?: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
//* Packs a page dictionary's groups into files so that a route loads at most `bound` of them. It starts from the
|
|
19
|
+
//* groups every route takes or leaves together and merges two files while the requests saved outweigh the bytes added,
|
|
20
|
+
//* never past a route's `overfetchBytes` of texts it does not show; a route past the bound takes the rest in its own file.
|
|
21
|
+
export class DictionaryPacking {
|
|
22
|
+
static readonly bound = 4;
|
|
23
|
+
//? What one more request costs a route in bytes of text: headers, a round trip's share, and the brotli window a
|
|
24
|
+
//? small file compresses without.
|
|
25
|
+
static readonly requestBytes = 1024;
|
|
26
|
+
//? About 2 KB brotli: what other routes showing other texts can add to a route's dictionary at most.
|
|
27
|
+
static readonly overfetchBytes = 8192;
|
|
28
|
+
|
|
29
|
+
static pack(
|
|
30
|
+
routes: ReadonlyMap<string, readonly string[]>,
|
|
31
|
+
bytesOf: (group: string) => number,
|
|
32
|
+
groups: readonly string[],
|
|
33
|
+
{
|
|
34
|
+
bound = DictionaryPacking.bound,
|
|
35
|
+
requestBytes = DictionaryPacking.requestBytes,
|
|
36
|
+
overfetchBytes = DictionaryPacking.overfetchBytes,
|
|
37
|
+
}: DictionaryPackOptions = {},
|
|
38
|
+
): DictionaryPack {
|
|
39
|
+
const known = new Set(groups);
|
|
40
|
+
const routeIds = [...routes.keys()].sort();
|
|
41
|
+
const needs = routeIds.map((routeId) => [...new Set(routes.get(routeId))].filter((group) => known.has(group)));
|
|
42
|
+
const bySignature = new Map<string, string[]>();
|
|
43
|
+
for (const group of [...known].sort()) {
|
|
44
|
+
const signature = needs.flatMap((need, idx) => (need.includes(group) ? [idx] : [])).join(",");
|
|
45
|
+
if (signature) bySignature.set(signature, [...(bySignature.get(signature) ?? []), group]);
|
|
46
|
+
}
|
|
47
|
+
const signed = [...bySignature].map(([signature, held]) => [held, signature.split(",").map(Number)] as const);
|
|
48
|
+
const state = new DictionaryPackState(routeIds.length, signed, bytesOf, overfetchBytes);
|
|
49
|
+
while (state.mergeCheapest(requestBytes));
|
|
50
|
+
const parts = state.parts().sort((a, b) => ((a[0] ?? "") < (b[0] ?? "") ? -1 : 1));
|
|
51
|
+
const used = new Set(parts.flat());
|
|
52
|
+
const rest = [...known].filter((group) => !used.has(group)).sort((a, b) => (a < b ? -1 : 1));
|
|
53
|
+
if (rest.length) parts.push(rest);
|
|
54
|
+
const partOf = new Map(parts.flatMap((part, idx) => part.map((group) => [group, idx] as const)));
|
|
55
|
+
const filesByRoute = new Map<string, number[]>();
|
|
56
|
+
const ownNeeds: DictionaryOwnNeed[] = [];
|
|
57
|
+
for (const [idx, routeId] of routeIds.entries()) {
|
|
58
|
+
const need = needs[idx] ?? [];
|
|
59
|
+
const files = [...new Set(need.map((group) => partOf.get(group) as number))].sort((a, b) => a - b);
|
|
60
|
+
if (files.length <= Math.max(1, bound)) {
|
|
61
|
+
filesByRoute.set(routeId, files);
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
const { kept, own, overfetch } = DictionaryPacking.#keepWithin(files, parts, new Set(need), bytesOf, bound);
|
|
65
|
+
filesByRoute.set(routeId, kept);
|
|
66
|
+
ownNeeds.push({ routeId, groups: own, left: overfetchBytes - overfetch });
|
|
67
|
+
}
|
|
68
|
+
const own = DictionaryOwnParts.share(ownNeeds, bytesOf);
|
|
69
|
+
const partsByRoute = Object.fromEntries(
|
|
70
|
+
routeIds.map((routeId) => {
|
|
71
|
+
const files = filesByRoute.get(routeId) ?? [];
|
|
72
|
+
const ownIdx = own.partOf.get(routeId);
|
|
73
|
+
return [routeId, ownIdx === undefined ? files : [...files, parts.length + ownIdx]];
|
|
74
|
+
}),
|
|
75
|
+
);
|
|
76
|
+
return { parts, ownParts: own.parts, partsByRoute };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
static #keepWithin(
|
|
80
|
+
files: number[],
|
|
81
|
+
parts: string[][],
|
|
82
|
+
need: Set<string>,
|
|
83
|
+
bytesOf: (group: string) => number,
|
|
84
|
+
bound: number,
|
|
85
|
+
): { kept: number[]; own: string[]; overfetch: number } {
|
|
86
|
+
const scored = files.map((idx) => ({
|
|
87
|
+
idx,
|
|
88
|
+
score: (parts[idx] ?? []).reduce((sum, group) => sum + (need.has(group) ? 1 : -1) * bytesOf(group), 0),
|
|
89
|
+
}));
|
|
90
|
+
scored.sort((a, b) => b.score - a.score || a.idx - b.idx);
|
|
91
|
+
const kept = scored
|
|
92
|
+
.slice(0, Math.max(1, bound) - 1)
|
|
93
|
+
.filter(({ score }) => score > 0)
|
|
94
|
+
.map(({ idx }) => idx);
|
|
95
|
+
const keptSet = new Set(kept);
|
|
96
|
+
const own = files
|
|
97
|
+
.filter((idx) => !keptSet.has(idx))
|
|
98
|
+
.flatMap((idx) => (parts[idx] ?? []).filter((group) => need.has(group)))
|
|
99
|
+
.sort();
|
|
100
|
+
const overfetch = kept
|
|
101
|
+
.flatMap((idx) => (parts[idx] ?? []).filter((group) => !need.has(group)))
|
|
102
|
+
.reduce((sum, group) => sum + bytesOf(group), 0);
|
|
103
|
+
return { kept: kept.sort((a, b) => a - b), own, overfetch };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
//? Several files compress worse than one, so a route showing nearly every text is cheaper on the whole dictionary.
|
|
107
|
+
static packUnderWhole(
|
|
108
|
+
routes: ReadonlyMap<string, readonly string[]>,
|
|
109
|
+
bytesOf: (group: string) => number,
|
|
110
|
+
groups: readonly string[],
|
|
111
|
+
servedBytesOf: (groups: readonly string[]) => number,
|
|
112
|
+
options: DictionaryPackOptions = {},
|
|
113
|
+
): DictionaryPack & { wholeRoutes: string[] } {
|
|
114
|
+
const whole = servedBytesOf([...new Set(groups)].sort());
|
|
115
|
+
const served = new Map<string, number>();
|
|
116
|
+
const servedOf = (part: readonly string[]) => {
|
|
117
|
+
const key = part.join("\n");
|
|
118
|
+
const known = served.get(key) ?? servedBytesOf(part);
|
|
119
|
+
served.set(key, known);
|
|
120
|
+
return known;
|
|
121
|
+
};
|
|
122
|
+
const shownBytesOf = (routeId: string) =>
|
|
123
|
+
[...new Set(routes.get(routeId))].reduce((sum, group) => sum + bytesOf(group), 0);
|
|
124
|
+
const partial = new Map(routes);
|
|
125
|
+
let best: { pack: DictionaryPack; over: string[]; cost: number } | null = null;
|
|
126
|
+
for (;;) {
|
|
127
|
+
const pack = DictionaryPacking.pack(partial, bytesOf, groups, options);
|
|
128
|
+
const files = [...pack.parts, ...pack.ownParts];
|
|
129
|
+
const costs = Object.entries(pack.partsByRoute).map(([routeId, held]) => ({
|
|
130
|
+
routeId,
|
|
131
|
+
cost: held.reduce((sum, idx) => sum + servedOf(files[idx] ?? []), 0),
|
|
132
|
+
}));
|
|
133
|
+
const over = costs.filter(({ cost }) => cost >= whole).map(({ routeId }) => routeId);
|
|
134
|
+
const cost =
|
|
135
|
+
costs.reduce((sum, route) => sum + Math.min(route.cost, whole), 0) + (routes.size - partial.size) * whole;
|
|
136
|
+
if (!best || cost < best.cost) best = { pack, over, cost };
|
|
137
|
+
if (!over.length) break;
|
|
138
|
+
//? Half at a time, the routes showing the most first: without them the rest may come out smaller after all.
|
|
139
|
+
over.sort((a, b) => shownBytesOf(b) - shownBytesOf(a) || (a < b ? -1 : 1));
|
|
140
|
+
for (const routeId of over.slice(0, Math.ceil(over.length / 2))) partial.delete(routeId);
|
|
141
|
+
}
|
|
142
|
+
const dropped = new Set(best.over);
|
|
143
|
+
const kept = Object.entries(best.pack.partsByRoute).filter(([routeId]) => !dropped.has(routeId));
|
|
144
|
+
const { parts, ownParts } = best.pack;
|
|
145
|
+
const ownUsed = [...new Set(kept.flatMap(([, held]) => held.filter((idx) => idx >= parts.length)))].sort(
|
|
146
|
+
(a, b) => a - b,
|
|
147
|
+
);
|
|
148
|
+
const ownMoved = new Map(ownUsed.map((idx, at) => [idx, parts.length + at]));
|
|
149
|
+
const partsByRoute = Object.fromEntries(
|
|
150
|
+
kept.map(([routeId, held]) => [routeId, held.map((idx) => ownMoved.get(idx) ?? idx)]),
|
|
151
|
+
);
|
|
152
|
+
const wholeRoutes = [...routes.keys()].sort().filter((routeId) => !Object.hasOwn(partsByRoute, routeId));
|
|
153
|
+
return {
|
|
154
|
+
parts,
|
|
155
|
+
ownParts: ownUsed.map((idx) => ownParts[idx - parts.length] ?? []),
|
|
156
|
+
partsByRoute,
|
|
157
|
+
wholeRoutes,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
}
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { runtimeFixtureTables } from "../quality/runtimeTable.fixture";
|
|
4
|
+
import { tempDirs, writeText } from "../test/testHelpers";
|
|
5
|
+
import { RouteRuntime } from "../transforms/routeRuntime";
|
|
6
|
+
import type { ClientModuleImport } from "./clientBuildTypes";
|
|
7
|
+
import { DictionaryAssetBuilder } from "./dictionaryAssetBuilder";
|
|
8
|
+
import { DictionaryConstants } from "./dictionaryConstants";
|
|
9
|
+
import { type DictionaryPiecesOf, DictionaryRoutes } from "./dictionaryRoutes";
|
|
10
|
+
import { RouteHandoffs } from "./routeHandoffs";
|
|
11
|
+
|
|
12
|
+
const makeRoot = tempDirs("akan-devkit-dict-routes-");
|
|
13
|
+
|
|
14
|
+
const constantsOf = () => {
|
|
15
|
+
const constants = new DictionaryConstants();
|
|
16
|
+
constants.add(
|
|
17
|
+
"apps/demo/lib/memo/memo.constant.ts",
|
|
18
|
+
`export class MemoStatus extends enumOf("memoStatus", ["draft", "done"] as const) {}
|
|
19
|
+
export class MemoInput extends via((field) => ({ status: field(MemoStatus), place: field(Address), author: field(User) })) {}
|
|
20
|
+
export class Memo extends via(MemoInput, (field) => ({})) {}
|
|
21
|
+
`,
|
|
22
|
+
);
|
|
23
|
+
constants.add(
|
|
24
|
+
"apps/demo/lib/user/user.constant.ts",
|
|
25
|
+
`export class UserRole extends enumOf("userRole", ["admin", "member"] as const) {}
|
|
26
|
+
export class UserInput extends via((field) => ({ role: field(UserRole), team: field(Team) })) {}
|
|
27
|
+
export class User extends via(UserInput, (field) => ({})) {}
|
|
28
|
+
`,
|
|
29
|
+
);
|
|
30
|
+
constants.add(
|
|
31
|
+
"apps/demo/lib/team/team.constant.ts",
|
|
32
|
+
`export class Team extends via((field) => ({ name: field(String) })) {}`,
|
|
33
|
+
);
|
|
34
|
+
constants.add(
|
|
35
|
+
"apps/demo/lib/__scalar/address/address.constant.ts",
|
|
36
|
+
`export class Address extends via((field) => ({ city: field(String) })) {}`,
|
|
37
|
+
);
|
|
38
|
+
constants.add(
|
|
39
|
+
"apps/demo/lib/runnerBot/runnerBot.constant.ts",
|
|
40
|
+
`export class RunnerBot extends via((field) => ({ name: field(String) })) {
|
|
41
|
+
static readonly labelKeyOf = { reviewer: "runnerBot.reviewer", fixer: "task.fixer" } as const;
|
|
42
|
+
static stageKeys = ["project.stage.open", "project.stage.done"] as const satisfies readonly string[];
|
|
43
|
+
static loose = { reviewer: "runnerBot.reviewer" };
|
|
44
|
+
static typed: Record<string, string> = { reviewer: "runnerBot.reviewer" } as const;
|
|
45
|
+
static called = { reviewer: "runnerBot.reviewer", fixer: keyOf("fixer") } as const;
|
|
46
|
+
static computed = { reviewer: "runnerBot.reviewer", [fixer]: "runnerBot.fixer" } as const;
|
|
47
|
+
static spread = [...RunnerBotRole.values, "runnerBot.fixer"] as const;
|
|
48
|
+
static nested = { reviewer: { label: "runnerBot.reviewer" } } as const;
|
|
49
|
+
static get made() { return { reviewer: "runnerBot.reviewer" } as const; }
|
|
50
|
+
held = { reviewer: "runnerBot.reviewer" } as const;
|
|
51
|
+
}
|
|
52
|
+
`,
|
|
53
|
+
);
|
|
54
|
+
return constants;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const workspace = async (files: Record<string, string>) => {
|
|
58
|
+
const root = await makeRoot();
|
|
59
|
+
for (const [rel, text] of Object.entries(files)) await writeText(path.join(root, rel), text);
|
|
60
|
+
const abs = (rel: string) => path.join(root, rel);
|
|
61
|
+
return { root, abs };
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const reader = (root: string, imports: Record<string, string[]>, piecesOf?: DictionaryPiecesOf): DictionaryRoutes => {
|
|
65
|
+
const importsByModule = new Map<string, ClientModuleImport[]>(
|
|
66
|
+
Object.entries(imports).map(([from, to]) => [
|
|
67
|
+
path.join(root, from),
|
|
68
|
+
to.map((rel) => ({ path: path.join(root, rel), lazy: false })),
|
|
69
|
+
]),
|
|
70
|
+
);
|
|
71
|
+
return new DictionaryRoutes(root, { importsByModule, constants: constantsOf(), ...(piecesOf ? { piecesOf } : {}) });
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
describe("DictionaryRoutes", () => {
|
|
75
|
+
test("a route shows the framework's own texts even when its client modules name no key", async () => {
|
|
76
|
+
const { root, abs } = await workspace({ "apps/demo/page/Plain.tsx": `export const Plain = () => <div />;` });
|
|
77
|
+
const read = reader(root, {}).read({ entries: [abs("apps/demo/page/Plain.tsx")] });
|
|
78
|
+
|
|
79
|
+
expect(read).toEqual({ groups: ["base"], api: false, whole: null });
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test("a route loading a module's client runtime shows its model, enums, scalars and the models it refers to", async () => {
|
|
83
|
+
const { root, abs } = await workspace({
|
|
84
|
+
"apps/demo/page/Memo.tsx": `export const Page = () => <>{l("memo.modelName")}</>;`,
|
|
85
|
+
});
|
|
86
|
+
const read = reader(root, { "apps/demo/page/Memo.tsx": ["apps/demo/lib/__client/memo.st.ts"] }).read({
|
|
87
|
+
entries: [abs("apps/demo/page/Memo.tsx")],
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
expect(read.whole).toBeNull();
|
|
91
|
+
expect(read.groups).toEqual(["address", "base", "memo", "memoStatus", "user", "userRole"]);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test("a route naming an enum's class shows that enum's texts, through the files its entry imports", async () => {
|
|
95
|
+
const { root, abs } = await workspace({
|
|
96
|
+
"apps/demo/page/Status.tsx": `export const Page = () => <Badge />;`,
|
|
97
|
+
"apps/demo/ui/Badge.tsx": `export const Badge = () => <Select options={MemoStatus.values} label={l("shared.status")} />;`,
|
|
98
|
+
});
|
|
99
|
+
const read = reader(root, { "apps/demo/page/Status.tsx": ["apps/demo/ui/Badge.tsx"] }).read({
|
|
100
|
+
entries: [abs("apps/demo/page/Status.tsx")],
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
expect(read.groups).toEqual(expect.arrayContaining(["base", "memoStatus", "shared"]));
|
|
104
|
+
expect(read.groups).not.toContain("memo");
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
test("a route with a key the build cannot follow loads the whole dictionary, naming the file and line", async () => {
|
|
108
|
+
const { root, abs } = await workspace({
|
|
109
|
+
"apps/demo/page/Any.tsx": `export const Page = () => <Label name="memo" />;`,
|
|
110
|
+
"apps/demo/ui/Label.tsx": [
|
|
111
|
+
`export const Label = ({ name }: { name: string }) => {`,
|
|
112
|
+
` const { l } = usePage();`,
|
|
113
|
+
` return <>{l(name)}</>;`,
|
|
114
|
+
`};`,
|
|
115
|
+
].join("\n"),
|
|
116
|
+
});
|
|
117
|
+
const read = reader(root, { "apps/demo/page/Any.tsx": ["apps/demo/ui/Label.tsx"] }).read({
|
|
118
|
+
entries: [abs("apps/demo/page/Any.tsx")],
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
expect(read.groups).toEqual([]);
|
|
122
|
+
expect(read.whole).toEqual({
|
|
123
|
+
file: "apps/demo/ui/Label.tsx",
|
|
124
|
+
line: 3,
|
|
125
|
+
why: "name is a parameter or prop whose type names no key",
|
|
126
|
+
});
|
|
127
|
+
expect(read.whole && DictionaryRoutes.pinned(read.whole)).toBe(
|
|
128
|
+
"apps/demo/ui/Label.tsx:3 name is a parameter or prop whose type names no key",
|
|
129
|
+
);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
test("a route loading every module's client runtime loads the whole dictionary, unless the build tells it which", async () => {
|
|
133
|
+
const files = {
|
|
134
|
+
"apps/demo/page/Memo.tsx": `export const Page = () => <>{st.use.memo()}</>;`,
|
|
135
|
+
"apps/demo/lib/memo/memo.store.ts": `export class MemoStore { label = "memo.title"; }`,
|
|
136
|
+
};
|
|
137
|
+
const { root, abs } = await workspace(files);
|
|
138
|
+
const imports = { "apps/demo/page/Memo.tsx": ["apps/demo/lib/st.ts"] };
|
|
139
|
+
const entries = [abs("apps/demo/page/Memo.tsx")];
|
|
140
|
+
|
|
141
|
+
expect(reader(root, imports).read({ entries }).whole).toEqual({
|
|
142
|
+
file: "apps/demo/lib/st.ts",
|
|
143
|
+
why: "loads every module's client runtime",
|
|
144
|
+
});
|
|
145
|
+
const piecesOf: DictionaryPiecesOf = () => ({ perModule: true, pieces: ["apps/demo/lib/__client/memo.st"] });
|
|
146
|
+
const read = reader(root, imports, piecesOf).read({ entries });
|
|
147
|
+
expect(read.whole).toBeNull();
|
|
148
|
+
expect(read.groups).toEqual(["address", "base", "memo", "memoStatus", "user", "userRole"]);
|
|
149
|
+
const everyModule: DictionaryPiecesOf = () => ({ perModule: false, pieces: [] });
|
|
150
|
+
expect(reader(root, imports, everyModule).read({ entries }).whole?.why).toBe("needs every module's client runtime");
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
test("a server module handing a client component a model's name adds that group, and a framework surface showing any module loads the whole dictionary", async () => {
|
|
154
|
+
const { root, abs } = await workspace({
|
|
155
|
+
"apps/demo/page/Client.tsx": `export const Client = () => null;`,
|
|
156
|
+
"apps/demo/page/Server.tsx": `export const Page = () => <Load.View modelName="team" />;`,
|
|
157
|
+
"apps/demo/page/Explorer.tsx": `import { Signal } from "akanjs/ui";\nexport const Page = () => <Signal.Doc />;`,
|
|
158
|
+
});
|
|
159
|
+
const routes = reader(root, {});
|
|
160
|
+
const entries = [abs("apps/demo/page/Client.tsx")];
|
|
161
|
+
|
|
162
|
+
expect(routes.read({ entries, serverModules: [abs("apps/demo/page/Server.tsx")] }).groups).toEqual([
|
|
163
|
+
"base",
|
|
164
|
+
"team",
|
|
165
|
+
]);
|
|
166
|
+
expect(routes.read({ entries, serverModules: [abs("apps/demo/page/Explorer.tsx")] }).whole).toEqual({
|
|
167
|
+
file: "apps/demo/page/Explorer.tsx",
|
|
168
|
+
why: "Signal from akanjs/ui shows the texts of any module its data names",
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
test("a constant class's static table gives its written keys only when every entry is one", () => {
|
|
173
|
+
const constants = constantsOf();
|
|
174
|
+
expect(constants.staticKeysOf("RunnerBot", "labelKeyOf")).toEqual(["runnerBot.reviewer", "task.fixer"]);
|
|
175
|
+
expect(constants.staticKeysOf("RunnerBot", "stageKeys")).toEqual(["project.stage.open", "project.stage.done"]);
|
|
176
|
+
for (const member of ["loose", "typed", "called", "computed", "spread", "nested", "made", "held", "missing"])
|
|
177
|
+
expect(constants.staticKeysOf("RunnerBot", member), member).toBeNull();
|
|
178
|
+
expect(constants.staticKeysOf("Missing", "labelKeyOf")).toBeNull();
|
|
179
|
+
|
|
180
|
+
constants.add(
|
|
181
|
+
"libs/shared/lib/runnerBot/runnerBot.constant.ts",
|
|
182
|
+
`export class RunnerBot {
|
|
183
|
+
static readonly labelKeyOf = { planner: "runnerBot.planner", fixer: "task.fixer" } as const;
|
|
184
|
+
static stageKeys = load();
|
|
185
|
+
}
|
|
186
|
+
`,
|
|
187
|
+
);
|
|
188
|
+
expect(constants.staticKeysOf("RunnerBot", "labelKeyOf")).toEqual([
|
|
189
|
+
"runnerBot.reviewer",
|
|
190
|
+
"task.fixer",
|
|
191
|
+
"runnerBot.planner",
|
|
192
|
+
]);
|
|
193
|
+
expect(constants.staticKeysOf("RunnerBot", "stageKeys")).toBeNull();
|
|
194
|
+
|
|
195
|
+
constants.add("libs/util/lib/runnerBot/runnerBot.constant.ts", `export class RunnerBot extends BaseBot {}`);
|
|
196
|
+
expect(constants.staticKeysOf("RunnerBot", "labelKeyOf")).toBeNull();
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
test("a route picking a key from a constant class's static table shows the groups its keys name", async () => {
|
|
200
|
+
const page = (table: string) =>
|
|
201
|
+
[
|
|
202
|
+
`import { cnst } from "@apps/demo/client";`,
|
|
203
|
+
`export const Page = ({ role }: { role: string }) => <>{l(cnst.RunnerBot.${table}[role])}</>;`,
|
|
204
|
+
].join("\n");
|
|
205
|
+
const { root, abs } = await workspace({
|
|
206
|
+
"apps/demo/page/Bots.tsx": page("labelKeyOf"),
|
|
207
|
+
"apps/demo/page/Loose.tsx": page("loose"),
|
|
208
|
+
});
|
|
209
|
+
const routes = reader(root, {});
|
|
210
|
+
|
|
211
|
+
const read = routes.read({ entries: [abs("apps/demo/page/Bots.tsx")] });
|
|
212
|
+
expect(read.whole).toBeNull();
|
|
213
|
+
expect(read.groups).toEqual(["base", "runnerBot", "task"]);
|
|
214
|
+
expect(routes.read({ entries: [abs("apps/demo/page/Loose.tsx")] }).whole).toEqual({
|
|
215
|
+
file: "apps/demo/page/Loose.tsx",
|
|
216
|
+
line: 2,
|
|
217
|
+
why: "cnst.RunnerBot.loose[role] is read from data at run time",
|
|
218
|
+
});
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
test("a route naming an API description key says so, for the API description file", async () => {
|
|
222
|
+
const { root, abs } = await workspace({
|
|
223
|
+
"apps/demo/page/Api.tsx": `export const Page = () => <>{l("memo.signal.getMemo.desc")}</>;`,
|
|
224
|
+
});
|
|
225
|
+
const read = reader(root, {}).read({ entries: [abs("apps/demo/page/Api.tsx")] });
|
|
226
|
+
|
|
227
|
+
expect(read.api).toBe(true);
|
|
228
|
+
expect(read.groups).toEqual([DictionaryAssetBuilder.apiGroup, "base", "memo"]);
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
test("a development route counts the model references its server modules hand over, not every one the root layout imports", async () => {
|
|
232
|
+
const { root, abs } = await workspace({
|
|
233
|
+
"apps/demo/page/Notes.tsx": `import { fetch } from "@apps/demo/client";\nexport const Page = (id: string) => fetch.viewNote(id);\n`,
|
|
234
|
+
"apps/demo/ui/Plain.tsx": `"use client";\nexport const Plain = () => null;\n`,
|
|
235
|
+
});
|
|
236
|
+
const { demo } = await runtimeFixtureTables();
|
|
237
|
+
const referenceOf = (model: string) => abs(`apps/demo/lib/__client/${model}.ref.ts`);
|
|
238
|
+
const handoffs = new RouteHandoffs(
|
|
239
|
+
root,
|
|
240
|
+
new RouteRuntime(root, demo, new Set()),
|
|
241
|
+
new Map(["memo", "note"].map((model) => [model, referenceOf(model)])),
|
|
242
|
+
);
|
|
243
|
+
const discovered = [abs("apps/demo/ui/Plain.tsx"), referenceOf("memo"), referenceOf("note")];
|
|
244
|
+
const serverModules = [abs("apps/demo/page/Notes.tsx")];
|
|
245
|
+
|
|
246
|
+
const entries = await DictionaryRoutes.handedEntries(discovered, serverModules, handoffs);
|
|
247
|
+
expect(entries).toEqual([abs("apps/demo/ui/Plain.tsx"), referenceOf("note")]);
|
|
248
|
+
expect(reader(root, {}).read({ entries }).groups).toEqual(["base", "note"]);
|
|
249
|
+
expect(await DictionaryRoutes.handedEntries(discovered, serverModules, null)).toEqual(discovered);
|
|
250
|
+
});
|
|
251
|
+
});
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { StoreBootstrap } from "../artifact/storeBootstrap";
|
|
4
|
+
import type { App } from "../commandDecorators";
|
|
5
|
+
import { type DictionaryKeyRead, DictionaryKeys } from "../quality/dictionaryKeys";
|
|
6
|
+
import { ModelReference } from "../transforms/modelReference";
|
|
7
|
+
import { RouteRuntime } from "../transforms/routeRuntime";
|
|
8
|
+
import type { ClientEntryDiscovery, ClientModuleImport } from "./clientBuildTypes";
|
|
9
|
+
import { DictionaryAssetBuilder } from "./dictionaryAssetBuilder";
|
|
10
|
+
import { DictionaryConstants } from "./dictionaryConstants";
|
|
11
|
+
import { RouteHandoffs } from "./routeHandoffs";
|
|
12
|
+
|
|
13
|
+
export interface DictionaryRouteUnread {
|
|
14
|
+
file: string;
|
|
15
|
+
line?: number;
|
|
16
|
+
why: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface DictionaryRouteRead {
|
|
20
|
+
//? Every group the route's client modules can show, a superset: names no dictionary holds are dropped when packed.
|
|
21
|
+
groups: string[];
|
|
22
|
+
api: boolean;
|
|
23
|
+
//? Set when the route shows a key the build cannot follow: it loads the whole page dictionary.
|
|
24
|
+
whole: DictionaryRouteUnread | null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface DictionaryRouteInput {
|
|
28
|
+
entries: readonly string[];
|
|
29
|
+
serverModules?: readonly string[];
|
|
30
|
+
references?: readonly string[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
//? Development's graph links the whole runtime, so a file importing it is asked which module pieces it would load.
|
|
34
|
+
export type DictionaryPiecesOf = (absPath: string, source: string) => { perModule: boolean; pieces: string[] } | null;
|
|
35
|
+
|
|
36
|
+
export interface DictionaryRoutesOptions {
|
|
37
|
+
importsByModule: ReadonlyMap<string, readonly ClientModuleImport[]>;
|
|
38
|
+
constants: DictionaryConstants;
|
|
39
|
+
piecesOf?: DictionaryPiecesOf;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const scoped = /^(?:apps|libs)\/[^/]+\//;
|
|
43
|
+
const piece = /^((?:apps|libs)\/[^/]+)\/lib\/__client\/([^/_.][^/.]*)\.(st|fetch|ref)(?:\.ts)?$/;
|
|
44
|
+
const wholeRuntime = /^(?:apps|libs)\/[^/]+\/lib\/(?:st|useClient)\.ts$/;
|
|
45
|
+
const noTexts = /\.(?:constant|dictionary|document|service|signal)\.ts$/;
|
|
46
|
+
const generated = /^(?:apps|libs)\/[^/]+\/(?:lib\/[^/]+\.ts$|client\.ts$|server\.ts$|\.akan\/)/;
|
|
47
|
+
//? Every page shows the framework's own texts: buttons, empty states, confirmations, validation messages.
|
|
48
|
+
const frameworkGroups = ["base"];
|
|
49
|
+
|
|
50
|
+
export class DictionaryRoutes {
|
|
51
|
+
readonly #workspaceRoot: string;
|
|
52
|
+
readonly #options: DictionaryRoutesOptions;
|
|
53
|
+
readonly #reads = new Map<string, { source: string; read: DictionaryKeyRead }>();
|
|
54
|
+
|
|
55
|
+
constructor(workspaceRoot: string, options: DictionaryRoutesOptions) {
|
|
56
|
+
this.#workspaceRoot = workspaceRoot;
|
|
57
|
+
this.#options = options;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
static get frameworkGroups(): readonly string[] {
|
|
61
|
+
return frameworkGroups;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
static async forApp(
|
|
65
|
+
workspaceRoot: string,
|
|
66
|
+
appScope: string,
|
|
67
|
+
options: Omit<DictionaryRoutesOptions, "constants">,
|
|
68
|
+
runtime?: RouteRuntime | null,
|
|
69
|
+
): Promise<DictionaryRoutes> {
|
|
70
|
+
const table = runtime === undefined ? await RouteRuntime.read(workspaceRoot, appScope).catch(() => null) : runtime;
|
|
71
|
+
const scopes = table?.table.layers.map(({ scope }) => scope) ?? [appScope];
|
|
72
|
+
const constants = await DictionaryConstants.read(workspaceRoot, [...new Set([appScope, ...scopes])]);
|
|
73
|
+
return new DictionaryRoutes(workspaceRoot, { ...options, constants });
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
//? Development reads a route as it builds, from the SSR bundle standing in for the browser's, whose graph links the
|
|
77
|
+
//? whole runtime; the constants are read again each time, as saving one restarts no builder.
|
|
78
|
+
static async ofBuiltRoute(
|
|
79
|
+
app: App,
|
|
80
|
+
route: {
|
|
81
|
+
seeds: string[];
|
|
82
|
+
entries: readonly string[];
|
|
83
|
+
importsByModule: ReadonlyMap<string, readonly ClientModuleImport[]>;
|
|
84
|
+
discovery: ClientEntryDiscovery;
|
|
85
|
+
},
|
|
86
|
+
): Promise<string[] | null> {
|
|
87
|
+
const { workspaceRoot } = app.workspace;
|
|
88
|
+
const unbuilt = route.entries.find((entry) => !route.importsByModule.has(path.resolve(entry)));
|
|
89
|
+
if (unbuilt) {
|
|
90
|
+
const fileName = path.relative(workspaceRoot, unbuilt).split(path.sep).join("/");
|
|
91
|
+
app.verbose(`[dictionary] the route loads the whole page dictionary: this builder has not bundled ${fileName}`);
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
const appScope = `apps/${app.name}`;
|
|
95
|
+
const runtime = await RouteRuntime.read(workspaceRoot, appScope).catch(() => null);
|
|
96
|
+
const piecesOf: DictionaryPiecesOf | undefined = runtime
|
|
97
|
+
? (absPath, source) => runtime.transform(source, absPath)
|
|
98
|
+
: undefined;
|
|
99
|
+
const reader = await DictionaryRoutes.forApp(
|
|
100
|
+
workspaceRoot,
|
|
101
|
+
appScope,
|
|
102
|
+
{ importsByModule: route.importsByModule, ...(piecesOf ? { piecesOf } : {}) },
|
|
103
|
+
runtime,
|
|
104
|
+
);
|
|
105
|
+
const { discovery } = route;
|
|
106
|
+
const serverModules =
|
|
107
|
+
"serverModules" in discovery && typeof discovery.serverModules === "function"
|
|
108
|
+
? await (discovery.serverModules as (seeds: string[]) => Promise<string[]>)(route.seeds)
|
|
109
|
+
: [];
|
|
110
|
+
const handoffs = await DictionaryRoutes.#handoffsOf(app, runtime);
|
|
111
|
+
const entries = await DictionaryRoutes.handedEntries(route.entries, serverModules, handoffs);
|
|
112
|
+
const read = reader.read({ entries, serverModules });
|
|
113
|
+
if (read.whole)
|
|
114
|
+
app.verbose(`[dictionary] the route loads the whole page dictionary: ${DictionaryRoutes.pinned(read.whole)}`);
|
|
115
|
+
return read.whole ? null : read.groups;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
//? Development's root layout imports every model's reference; production keeps those a server module hands over.
|
|
119
|
+
static async handedEntries(
|
|
120
|
+
entries: readonly string[],
|
|
121
|
+
serverModules: string[],
|
|
122
|
+
handoffs: RouteHandoffs | null,
|
|
123
|
+
): Promise<readonly string[]> {
|
|
124
|
+
if (!handoffs) return entries;
|
|
125
|
+
const { referenceFiles } = await handoffs.read(serverModules);
|
|
126
|
+
return [...new Set([...entries.filter((entry) => !ModelReference.isFile(entry)), ...referenceFiles])];
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
static async #handoffsOf(app: App, runtime: RouteRuntime | null): Promise<RouteHandoffs | null> {
|
|
130
|
+
if (!runtime || (await StoreBootstrap.scopeOf(app)) !== "page") return null;
|
|
131
|
+
const { workspaceRoot } = app.workspace;
|
|
132
|
+
return new RouteHandoffs(workspaceRoot, runtime, await ModelReference.filesOf(workspaceRoot, `apps/${app.name}`));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
static pinned({ file, line, why }: DictionaryRouteUnread): string {
|
|
136
|
+
return `${file}${line ? `:${line}` : ""} ${why}`;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
read({ entries, serverModules = [], references = [] }: DictionaryRouteInput): DictionaryRouteRead {
|
|
140
|
+
const names = new Set<string>(frameworkGroups);
|
|
141
|
+
const modules = new Set<string>(references);
|
|
142
|
+
const route = { names, modules, api: false as boolean, whole: null as DictionaryRouteUnread | null };
|
|
143
|
+
const queue = entries.map((entry) => path.resolve(entry));
|
|
144
|
+
const visited = new Set<string>();
|
|
145
|
+
for (let file = queue.pop(); file !== undefined && !route.whole; file = queue.pop()) {
|
|
146
|
+
if (visited.has(file)) continue;
|
|
147
|
+
visited.add(file);
|
|
148
|
+
const fileName = this.#fileNameOf(file);
|
|
149
|
+
const pieceOf = fileName.match(piece);
|
|
150
|
+
if (pieceOf?.[2]) modules.add(pieceOf[2]);
|
|
151
|
+
if (wholeRuntime.test(fileName)) {
|
|
152
|
+
if (!this.#options.piecesOf) route.whole = { file: fileName, why: "loads every module's client runtime" };
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
if (noTexts.test(fileName)) continue;
|
|
156
|
+
if (scoped.test(fileName) && !pieceOf && !generated.test(fileName))
|
|
157
|
+
this.#readClient(file, fileName, route, queue);
|
|
158
|
+
for (const imported of this.#options.importsByModule.get(file) ?? []) queue.push(imported.path);
|
|
159
|
+
}
|
|
160
|
+
for (const file of serverModules) {
|
|
161
|
+
if (route.whole) break;
|
|
162
|
+
const fileName = this.#fileNameOf(file);
|
|
163
|
+
if (!scoped.test(fileName) || noTexts.test(fileName) || generated.test(fileName)) continue;
|
|
164
|
+
const read = this.#readOf(file, fileName)?.read;
|
|
165
|
+
if (read?.anyModule) route.whole = { file: fileName, why: read.anyModule };
|
|
166
|
+
for (const name of read?.propNames ?? []) names.add(name);
|
|
167
|
+
}
|
|
168
|
+
if (route.whole) return { groups: [], api: route.api, whole: route.whole };
|
|
169
|
+
const { constants } = this.#options;
|
|
170
|
+
for (const module of modules) for (const group of constants.reachOf(module)) names.add(group);
|
|
171
|
+
if (route.api) names.add(DictionaryAssetBuilder.apiGroup);
|
|
172
|
+
return { groups: [...names].sort(), api: route.api, whole: null };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
#readClient(
|
|
176
|
+
file: string,
|
|
177
|
+
fileName: string,
|
|
178
|
+
route: { names: Set<string>; modules: Set<string>; api: boolean; whole: DictionaryRouteUnread | null },
|
|
179
|
+
queue: string[],
|
|
180
|
+
) {
|
|
181
|
+
const known = this.#readOf(file, fileName);
|
|
182
|
+
if (!known) return;
|
|
183
|
+
const { read, source } = known;
|
|
184
|
+
const [unread] = read.unread;
|
|
185
|
+
if (unread) route.whole = { file: fileName, line: unread.line, why: unread.why };
|
|
186
|
+
else if (read.anyModule) route.whole = { file: fileName, why: read.anyModule };
|
|
187
|
+
for (const name of read.names) route.names.add(name);
|
|
188
|
+
for (const name of read.classNames)
|
|
189
|
+
for (const group of this.#options.constants.groupsOfClass(name)) route.modules.add(group);
|
|
190
|
+
route.api ||= read.api;
|
|
191
|
+
const { piecesOf } = this.#options;
|
|
192
|
+
const readsWhole = (this.#options.importsByModule.get(file) ?? []).some(({ path: imported }) =>
|
|
193
|
+
wholeRuntime.test(this.#fileNameOf(imported)),
|
|
194
|
+
);
|
|
195
|
+
if (!piecesOf || !readsWhole) return;
|
|
196
|
+
const routed = piecesOf(file, source);
|
|
197
|
+
if (routed && !routed.perModule) route.whole = { file: fileName, why: "needs every module's client runtime" };
|
|
198
|
+
for (const loaded of routed?.pieces ?? []) {
|
|
199
|
+
const [, scope, module, role] = loaded.match(piece) ?? [];
|
|
200
|
+
if (!scope || !module) continue;
|
|
201
|
+
route.modules.add(module);
|
|
202
|
+
if (role === "st")
|
|
203
|
+
for (const dir of [module, `_${module}`])
|
|
204
|
+
queue.push(path.join(this.#workspaceRoot, scope, "lib", dir, `${module}.store.ts`));
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
#readOf(file: string, fileName: string) {
|
|
209
|
+
let source: string;
|
|
210
|
+
try {
|
|
211
|
+
source = readFileSync(file, "utf8");
|
|
212
|
+
} catch {
|
|
213
|
+
return null;
|
|
214
|
+
}
|
|
215
|
+
const known = this.#reads.get(file);
|
|
216
|
+
if (known?.source === source) return known;
|
|
217
|
+
const { constants } = this.#options;
|
|
218
|
+
const staticKeys = (className: string, member: string) => constants.staticKeysOf(className, member);
|
|
219
|
+
const next = { source, read: DictionaryKeys.read(source, fileName, staticKeys) };
|
|
220
|
+
this.#reads.set(file, next);
|
|
221
|
+
return next;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
#fileNameOf(absPath: string) {
|
|
225
|
+
return path.relative(this.#workspaceRoot, absPath).split(path.sep).join("/");
|
|
226
|
+
}
|
|
227
|
+
}
|