@akanjs/devkit 3.3.0-rc.6 → 3.3.0-rc.61
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 +52 -28
- 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 +19 -0
- package/docs/apiReference.ts +28 -5
- 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
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
2
|
import { toError } from "akanjs/common";
|
|
3
|
-
import {
|
|
3
|
+
import { AppWorkerPath } from "akanjs/server/appWorkerPath";
|
|
4
|
+
import { BUILD_ENV_FILE, BUILD_ENV_MODULE } from "akanjs/server/lifecycle/buildEnv";
|
|
5
|
+
import { SecretEnv } from "akanjs/server/lifecycle/secretEnv";
|
|
4
6
|
import type { BunPlugin } from "bun";
|
|
7
|
+
import { AkanBin } from "../akanConfig/akanBin";
|
|
8
|
+
import { DOCKER_IGNORED, DOCKER_VARIANT_FILE_PREFIX } from "../akanConfig/dockerImage";
|
|
5
9
|
import { ProductionLockfile } from "../akanConfig/productionLockfile";
|
|
6
10
|
import type { App } from "../commandDecorators";
|
|
7
11
|
import { parseEnvFile, WorkspaceExecutor } from "../executors";
|
|
8
12
|
import {
|
|
9
13
|
AllRoutesBuilder,
|
|
14
|
+
type BuildAllRoutesResult,
|
|
10
15
|
CsrArtifactBuilder,
|
|
11
16
|
FontPruner,
|
|
12
17
|
NARROWABLE_VENDOR_SPECIFIERS,
|
|
@@ -14,16 +19,24 @@ import {
|
|
|
14
19
|
SsrBaseArtifactBuilder,
|
|
15
20
|
VendorImportScanner,
|
|
16
21
|
} from "../frontendBuild";
|
|
22
|
+
import { ServerBundleSecrets } from "../mobile/serverBundleSecrets";
|
|
23
|
+
import { RouteRuntimeReport } from "../quality/routeRuntimeReport";
|
|
24
|
+
import { SecretEnvDeclaration, type SecretEnvDeclared } from "../transforms/secretEnvDeclaration";
|
|
25
|
+
import { SecretEnvFile } from "../transforms/secretEnvFile";
|
|
26
|
+
import { ServerEnvEvaluationError } from "../transforms/serverEnvEvaluationError";
|
|
17
27
|
import { createServerEnvPlugin } from "../transforms/serverEnvPlugin";
|
|
18
28
|
import { ServerEnvProfile } from "../transforms/serverEnvProfile";
|
|
19
29
|
import { ProjectTypecheck } from "../typecheck/projectTypecheck";
|
|
20
30
|
import { Spinner } from "../util/spinner";
|
|
21
31
|
import type { BaseDevEnv, PackageJson } from "../workspace/types";
|
|
22
|
-
import
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
32
|
+
import { AppBin } from "./appBin";
|
|
33
|
+
import {
|
|
34
|
+
type ApplicationBuildPhaseResult,
|
|
35
|
+
type ApplicationBuildProgressReporter,
|
|
36
|
+
ApplicationBuildReporter,
|
|
37
|
+
type ApplicationBuildResult,
|
|
26
38
|
} from "./applicationBuildReporter";
|
|
39
|
+
import { RouteFilesReport } from "./routeFilesReport";
|
|
27
40
|
import { RouteJsBudget, type RouteJsBudgetMode, type RouteJsBudgetStatus, type RouteJsSize } from "./routeJsBudget";
|
|
28
41
|
|
|
29
42
|
export interface TypecheckOptions {
|
|
@@ -59,6 +72,12 @@ export interface ApplicationBuildRunnerOptions {
|
|
|
59
72
|
environment?: string;
|
|
60
73
|
/** Bundles `env/env.server.<environment>.<profile>.ts`, which may hold no secret, in place of the environment's file. */
|
|
61
74
|
profile?: string;
|
|
75
|
+
/**
|
|
76
|
+
* An image build's: `read` leaves the server env's secret strings out of the server, which reads each from its process
|
|
77
|
+
* env, and `inline` keeps them in it as what an unset variable falls back to. Unset, as for the server a desktop app
|
|
78
|
+
* carries, or under a `profile`, the env files are bundled as written.
|
|
79
|
+
*/
|
|
80
|
+
secretEnv?: "read" | "inline";
|
|
62
81
|
/**
|
|
63
82
|
* `enforce` fails on an overage, a route with no entry, or a missing or unreadable akan.budget.json; `update` and
|
|
64
83
|
* `raise` rewrite the file first; `report` only warns.
|
|
@@ -72,6 +91,7 @@ export interface BuildPhaseRunOptions {
|
|
|
72
91
|
spinner?: boolean;
|
|
73
92
|
}
|
|
74
93
|
|
|
94
|
+
const MAIN_BUNDLE = "main.bundle.js";
|
|
75
95
|
const BUILD_PHASE_EMOJIS: Record<BuildPhaseId, string> = {
|
|
76
96
|
prepare: "🧹",
|
|
77
97
|
typecheck: "🔎",
|
|
@@ -109,6 +129,8 @@ export class ApplicationBuildRunner {
|
|
|
109
129
|
#reporter?: BuildProgressReporter;
|
|
110
130
|
#environment?: string;
|
|
111
131
|
#profile?: string;
|
|
132
|
+
#secretEnv?: "read" | "inline";
|
|
133
|
+
#secrets: SecretEnvDeclared = { variables: [], unmoved: [], moved: [] };
|
|
112
134
|
#budget: RouteJsBudgetMode;
|
|
113
135
|
#modulesByRoute?: Record<string, string[]>;
|
|
114
136
|
#spinner?: boolean;
|
|
@@ -123,6 +145,7 @@ export class ApplicationBuildRunner {
|
|
|
123
145
|
reporter,
|
|
124
146
|
environment,
|
|
125
147
|
profile,
|
|
148
|
+
secretEnv,
|
|
126
149
|
budget = "report",
|
|
127
150
|
}: ApplicationBuildRunnerOptions = {},
|
|
128
151
|
) {
|
|
@@ -132,6 +155,7 @@ export class ApplicationBuildRunner {
|
|
|
132
155
|
this.#reporter = reporter;
|
|
133
156
|
this.#environment = environment;
|
|
134
157
|
this.#profile = profile;
|
|
158
|
+
this.#secretEnv = profile ? undefined : secretEnv;
|
|
135
159
|
this.#budget = budget;
|
|
136
160
|
}
|
|
137
161
|
|
|
@@ -163,7 +187,9 @@ export class ApplicationBuildRunner {
|
|
|
163
187
|
|
|
164
188
|
async build({ spinner = false }: BuildOptions = {}): Promise<BuildResult> {
|
|
165
189
|
// serial build is needed because of Bun.build is unstable for parallel build
|
|
166
|
-
|
|
190
|
+
//? ora writes to stderr, and to a file or a pipe it prints each phase twice, the end line in colour.
|
|
191
|
+
this.#spinner = spinner && process.stderr.isTTY;
|
|
192
|
+
if (spinner && !this.#spinner) this.#reporter ??= ApplicationBuildReporter.create();
|
|
167
193
|
if (this.#verify) this.#app.useVerifyDist();
|
|
168
194
|
const { web, assets, baseDevEnv } = await this.#app.getConfig();
|
|
169
195
|
const environment = this.#environment ?? baseDevEnv.env;
|
|
@@ -172,6 +198,7 @@ export class ApplicationBuildRunner {
|
|
|
172
198
|
//? Before any phase: a profile that would ship a secret stops the build, not the image after it.
|
|
173
199
|
if (this.#profile)
|
|
174
200
|
await ServerEnvProfile.assertShippable({ envDir: this.#envDir, environment, profile: this.#profile });
|
|
201
|
+
if (this.#secretEnv) await this.#declareSecrets(environment);
|
|
175
202
|
await this.#runPhase("prepare", "Preparing output directory", () => this.#app.prepareCommand("build"));
|
|
176
203
|
if (!this.#fast) await this.#runPhase("typecheck", "Typechecking", () => this.typecheck());
|
|
177
204
|
await this.#runPhase(
|
|
@@ -186,14 +213,24 @@ export class ApplicationBuildRunner {
|
|
|
186
213
|
async () => (web.ssr ? await this.#buildSsr() : null),
|
|
187
214
|
(result) =>
|
|
188
215
|
result
|
|
189
|
-
?
|
|
216
|
+
? ApplicationBuildRunner.#ssrSummary(result.allRoutes)
|
|
190
217
|
: web.ssr
|
|
191
218
|
? "skipped"
|
|
192
219
|
: "disabled by akan.config.ts web.ssr",
|
|
193
220
|
);
|
|
221
|
+
const leftOut = ServerEnvProfile.leftOutNotice(
|
|
222
|
+
this.#profile ?? "",
|
|
223
|
+
this.#app.workspace.workspaceRoot,
|
|
224
|
+
this.#libEnvsLeftOut,
|
|
225
|
+
);
|
|
226
|
+
if (leftOut) this.#app.logger.warn(leftOut);
|
|
194
227
|
if (this.#verify) {
|
|
195
228
|
const routeJs = await this.#runBudgetPhase(environment);
|
|
196
|
-
await this.#app.dist.writeJson(
|
|
229
|
+
await this.#app.dist.writeJson(
|
|
230
|
+
"akan.build.json",
|
|
231
|
+
{ profile: "verify", builtAt: new Date().toISOString() },
|
|
232
|
+
{ silent: true },
|
|
233
|
+
);
|
|
197
234
|
return this.#resultOf(environment, routeJs);
|
|
198
235
|
}
|
|
199
236
|
await this.#runPhase(
|
|
@@ -221,10 +258,68 @@ export class ApplicationBuildRunner {
|
|
|
221
258
|
: "no files",
|
|
222
259
|
);
|
|
223
260
|
const routeJs = await this.#runBudgetPhase(environment);
|
|
261
|
+
await this.assertSecretsLeftOut();
|
|
224
262
|
await this.#runPhase("metadata", "Writing production metadata", () => this.buildAppMeta());
|
|
263
|
+
this.#reportSecretEnv(environment);
|
|
225
264
|
return this.#resultOf(environment, routeJs);
|
|
226
265
|
}
|
|
227
266
|
|
|
267
|
+
//* A build that cannot load the env file cannot say what it left out, so it stops; under --inline-secrets, which
|
|
268
|
+
//* leaves nothing out, it goes on as a build without the setting does.
|
|
269
|
+
async #declareSecrets(environment: string) {
|
|
270
|
+
try {
|
|
271
|
+
this.#secrets = await SecretEnvDeclaration.of(this.#envDir, environment);
|
|
272
|
+
} catch (error) {
|
|
273
|
+
if (!(error instanceof ServerEnvEvaluationError)) throw error;
|
|
274
|
+
if (this.#secretEnv === "read")
|
|
275
|
+
throw new Error(
|
|
276
|
+
`${error.message}\nA build leaves the secret values of the server env out of what it writes, and names the variables the server reads them from by loading the env file: with no variable of this shell first, then with them. Make the file load at that line, by setting the variable it reads there in this shell or giving it a fallback, and build again. \`akan build --inline-secrets\` builds with the env files as written until akanjs 3.5.0 removes it.`,
|
|
277
|
+
);
|
|
278
|
+
this.#app.logger.warn(
|
|
279
|
+
`--inline-secrets: ${error.message}. The secret values of the server env could not be listed, so this build holds the env files as written: the server reads no secret from a variable of its process env, and names none at boot.`,
|
|
280
|
+
);
|
|
281
|
+
this.#secretEnv = undefined;
|
|
282
|
+
}
|
|
283
|
+
//? Before any phase, and by the env's value alone: a search of the files written misses a short or a plain one.
|
|
284
|
+
if (this.#secretEnv === "read" && this.#secrets.unmoved.length)
|
|
285
|
+
throw new Error(
|
|
286
|
+
SecretEnvFile.unmovedStop(
|
|
287
|
+
this.#app.name,
|
|
288
|
+
environment,
|
|
289
|
+
path
|
|
290
|
+
.relative(this.#app.workspace.workspaceRoot, path.join(this.#envDir, "env.server.ts"))
|
|
291
|
+
.replaceAll("\\", "/"),
|
|
292
|
+
this.#secrets.unmoved,
|
|
293
|
+
),
|
|
294
|
+
);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
//? Before the metadata phase: a build that still holds a secret gets no Dockerfile to build an image from.
|
|
298
|
+
async assertSecretsLeftOut() {
|
|
299
|
+
if (this.#secretEnv !== "read" || !this.#secrets.moved.length) return;
|
|
300
|
+
const { workspaceRoot } = this.#app.workspace;
|
|
301
|
+
const note = await new ServerBundleSecrets(workspaceRoot, this.#app.cwdPath).assertImageClean(
|
|
302
|
+
this.#app.dist.cwdPath,
|
|
303
|
+
this.#secrets.moved,
|
|
304
|
+
);
|
|
305
|
+
if (note) this.#app.logger.warn(note);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
#reportSecretEnv(environment: string) {
|
|
309
|
+
const { variables } = this.#secrets;
|
|
310
|
+
const { logger, name } = this.#app;
|
|
311
|
+
const names = variables.map((variable) => variable.name).join(", ");
|
|
312
|
+
const count = `${variables.length} secret value${variables.length === 1 ? "" : "s"}`;
|
|
313
|
+
if (variables.length && this.#secretEnv === "inline")
|
|
314
|
+
logger.warn(
|
|
315
|
+
`--inline-secrets keeps ${count} of the server env in this build, where whoever can read the image reads them: ${names}. A variable the deployment sets still wins over the built-in value. akanjs 3.5.0 removes the flag: set them where the server is deployed and build without it.`,
|
|
316
|
+
);
|
|
317
|
+
else if (variables.length)
|
|
318
|
+
logger.info(
|
|
319
|
+
`The server reads ${count} from its process env when it starts, not from this build: ${names}. Set them where it is deployed; \`akan secret-env ${name} --env ${environment}\` lists them and writes them from the env file.`,
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
|
|
228
323
|
#runBudgetPhase(environment: string) {
|
|
229
324
|
return this.#runPhase(
|
|
230
325
|
"budget",
|
|
@@ -268,13 +363,17 @@ export class ApplicationBuildRunner {
|
|
|
268
363
|
"../../page/**/*.ts",
|
|
269
364
|
"../../page/**/*.tsx",
|
|
270
365
|
...libPageIncludes,
|
|
271
|
-
...(options.tests ? ["../../script/**/*.ts"] : []),
|
|
272
366
|
"../../../../pkgs/akanjs/*/types/**/*.d.ts",
|
|
273
367
|
],
|
|
274
368
|
options,
|
|
275
369
|
);
|
|
276
370
|
}
|
|
277
371
|
|
|
372
|
+
static #ssrSummary({ manifest, runtimeReport }: BuildAllRoutesResult) {
|
|
373
|
+
const built = `${manifest.routeIds.length} routes, ${manifest.knownEntries.length} entries`;
|
|
374
|
+
return runtimeReport ? `${built}; ${RouteRuntimeReport.summary(runtimeReport)}` : built;
|
|
375
|
+
}
|
|
376
|
+
|
|
278
377
|
async #runPhase<T>(
|
|
279
378
|
id: BuildPhaseId,
|
|
280
379
|
label: string,
|
|
@@ -305,22 +404,56 @@ export class ApplicationBuildRunner {
|
|
|
305
404
|
const environment = this.#environment ?? akanConfig.baseDevEnv.env;
|
|
306
405
|
const packageJson = akanConfig.getProductionPackageJson();
|
|
307
406
|
const lockfile = await this.#pruneLockfile(packageJson);
|
|
308
|
-
const
|
|
407
|
+
const env = { ...akanConfig.getProductionEnv(environment), ...this.#secretEnvList() };
|
|
408
|
+
const carried = await new AppBin(this.#app, akanConfig).stageImage(this.#app.dist.cwdPath);
|
|
409
|
+
if (carried.length)
|
|
410
|
+
this.#app.logger.info(
|
|
411
|
+
typeof akanConfig.docker === "string"
|
|
412
|
+
? `The build carries ${carried.join(", ")} in ${AppBin.dir}/<TARGETARCH>/; apps/${this.#app.name}/akan.config.ts writes its own Dockerfile, which puts that folder on PATH itself (ENV PATH=${AkanBin.imagePath(AppBin.dir)}).`
|
|
413
|
+
: `The image carries ${carried.join(", ")} from bin, first on its PATH.`,
|
|
414
|
+
);
|
|
415
|
+
const imageParts = {
|
|
416
|
+
lockfile: lockfile !== null,
|
|
417
|
+
env: { ...(carried.length ? { PATH: AkanBin.imagePath(AppBin.dir) } : {}), ...env },
|
|
418
|
+
};
|
|
419
|
+
const dockerfile = akanConfig.dockerfileFor(environment, imageParts);
|
|
420
|
+
const variants = Object.keys(akanConfig.dockerVariants);
|
|
421
|
+
const { dist } = this.#app;
|
|
422
|
+
const buildInfo = {
|
|
423
|
+
buildId: await this.#resolveBuildId(),
|
|
424
|
+
akanVersion: akanConfig.akanVersion,
|
|
425
|
+
builtAt: new Date().toISOString(),
|
|
426
|
+
};
|
|
427
|
+
const silent = { silent: true };
|
|
309
428
|
await Promise.all([
|
|
310
|
-
|
|
311
|
-
|
|
429
|
+
dist.writeJson("package.json", packageJson, silent),
|
|
430
|
+
dist.writeJson(BUILD_ENV_FILE, env, silent),
|
|
312
431
|
...(lockfile !== null
|
|
313
|
-
? [
|
|
432
|
+
? [dist.writeFile(`${dist.cwdPath}/${ProductionLockfile.fileName}`, lockfile, silent)]
|
|
314
433
|
: []),
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
434
|
+
dist.writeFile(`${dist.cwdPath}/Dockerfile`, dockerfile, silent),
|
|
435
|
+
...variants.map((variant) =>
|
|
436
|
+
dist.writeFile(
|
|
437
|
+
`${dist.cwdPath}/${DOCKER_VARIANT_FILE_PREFIX}${variant}`,
|
|
438
|
+
akanConfig.dockerfileFor(environment, { ...imageParts, variant }),
|
|
439
|
+
silent,
|
|
440
|
+
),
|
|
441
|
+
),
|
|
442
|
+
//? A build run by hand writes its database beside main.js, and `COPY . .` would carry it into the image.
|
|
443
|
+
dist.writeFile(`${dist.cwdPath}/.dockerignore`, `${DOCKER_IGNORED.join("\n")}\n`, silent),
|
|
444
|
+
dist.writeJson("akan.build.json", buildInfo, silent),
|
|
321
445
|
]);
|
|
322
446
|
}
|
|
323
447
|
|
|
448
|
+
//? Names and kinds alone: the image carries the list of what its deployment owes, never a value.
|
|
449
|
+
#secretEnvList(): Record<string, string> {
|
|
450
|
+
if (!this.#secrets.variables.length) return {};
|
|
451
|
+
return {
|
|
452
|
+
[SecretEnv.listKey]: SecretEnv.format(this.#secrets.variables),
|
|
453
|
+
...(this.#secretEnv === "inline" ? { [SecretEnv.fallbackKey]: "image" } : {}),
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
|
|
324
457
|
async #pruneLockfile(packageJson: PackageJson): Promise<string | null> {
|
|
325
458
|
try {
|
|
326
459
|
return await ProductionLockfile.prune(this.#app.workspace.workspaceRoot, packageJson);
|
|
@@ -348,7 +481,7 @@ export class ApplicationBuildRunner {
|
|
|
348
481
|
}
|
|
349
482
|
|
|
350
483
|
#serverEnv: BunPlugin | null = null;
|
|
351
|
-
#
|
|
484
|
+
#libEnvsLeftOut = new Map<string, string[]>();
|
|
352
485
|
//? One plugin for every server-side bundle of the build: the backend, the RSC worker and the SSR route bundle.
|
|
353
486
|
#serverEnvPlugin(baseEnv: string, branches: Iterable<string>): BunPlugin {
|
|
354
487
|
this.#serverEnv ??= createServerEnvPlugin({
|
|
@@ -356,13 +489,9 @@ export class ApplicationBuildRunner {
|
|
|
356
489
|
environment: this.#environment ?? baseEnv,
|
|
357
490
|
environments: ["local", "testing", ...branches],
|
|
358
491
|
profile: this.#profile,
|
|
492
|
+
secrets: this.#secretEnv,
|
|
359
493
|
onLibEnv: (file, { profileFile, stripped }) => {
|
|
360
|
-
if (profileFile
|
|
361
|
-
this.#warnedLibEnvs.add(file);
|
|
362
|
-
const lib = path.relative(this.#app.workspace.workspaceRoot, file);
|
|
363
|
-
this.#app.logger.warn(
|
|
364
|
-
`${lib}: the "${this.#profile}" build leaves out ${stripped.join(", ")}. Give the lib ${path.basename(ServerEnvProfile.profileFileOf(file, this.#profile ?? ""))} to say what this profile runs with.`,
|
|
365
|
-
);
|
|
494
|
+
if (!profileFile && stripped.length) this.#libEnvsLeftOut.set(file, stripped);
|
|
366
495
|
},
|
|
367
496
|
});
|
|
368
497
|
return this.#serverEnv;
|
|
@@ -395,11 +524,17 @@ export class ApplicationBuildRunner {
|
|
|
395
524
|
...sharedConfig,
|
|
396
525
|
plugins: [this.#createExternalSpecifiersPlugin(externalLibs), serverEnvPlugin],
|
|
397
526
|
};
|
|
527
|
+
const buildEnvResult = await this.#buildOrThrow("build-env", {
|
|
528
|
+
...sharedConfig,
|
|
529
|
+
entrypoints: [this.#resolveBuildEnvEntry()],
|
|
530
|
+
naming: { entry: BUILD_ENV_MODULE },
|
|
531
|
+
});
|
|
398
532
|
//* Built apart so main.js keeps its own module copies; splitting moves lazy vendor `import()`s out of the boot parse.
|
|
399
533
|
const [mainResult, serverResult] = [
|
|
400
534
|
await this.#buildOrThrow("backend", {
|
|
401
535
|
...backendConfig,
|
|
402
536
|
entrypoints: [backendEntryPoints[0]],
|
|
537
|
+
naming: { entry: MAIN_BUNDLE },
|
|
403
538
|
...(this.#verify ? { banner: this.#verifyBanner() } : {}),
|
|
404
539
|
}),
|
|
405
540
|
await this.#buildOrThrow("backend", { ...backendConfig, entrypoints: [backendEntryPoints[1]], splitting: true }),
|
|
@@ -417,14 +552,39 @@ export class ApplicationBuildRunner {
|
|
|
417
552
|
entrypoints: [this.#resolveConsoleRuntimeBuildEntry()],
|
|
418
553
|
naming: { entry: "console-runtime.[ext]", chunk: "chunk-[hash].[ext]" },
|
|
419
554
|
});
|
|
555
|
+
await Bun.write(
|
|
556
|
+
path.join(this.#app.dist.cwdPath, "main.js"),
|
|
557
|
+
`import "./${BUILD_ENV_MODULE}";\nawait import("./${MAIN_BUNDLE}");\n`,
|
|
558
|
+
);
|
|
420
559
|
await this.#writeConsoleShim();
|
|
421
|
-
const
|
|
560
|
+
const workerResults = await this.#buildWorkers(backendConfig);
|
|
561
|
+
const results = [buildEnvResult, mainResult, serverResult, rscWorkerResult, consoleRuntimeResult, ...workerResults];
|
|
422
562
|
return {
|
|
423
|
-
entrypoints: backendEntryPoints.length + (rscWorkerResult ? 2 : 1),
|
|
424
|
-
outputs: results.reduce((sum, result) => sum + (result?.outputs.length ?? 0),
|
|
563
|
+
entrypoints: backendEntryPoints.length + (rscWorkerResult ? 2 : 1) + workerResults.length,
|
|
564
|
+
outputs: results.reduce((sum, result) => sum + (result?.outputs.length ?? 0), 2),
|
|
425
565
|
};
|
|
426
566
|
}
|
|
427
567
|
|
|
568
|
+
//* Never a chunk of server.js: the process that runs a worker loads nothing of the server, nor the server of it.
|
|
569
|
+
async #buildWorkers(backendConfig: Omit<Bun.BuildConfig, "entrypoints">) {
|
|
570
|
+
const results: Bun.BuildOutput[] = [];
|
|
571
|
+
for (const [name, { owner, entry }] of await this.#app.selectWorkers()) {
|
|
572
|
+
if (!(await Bun.file(entry).exists()))
|
|
573
|
+
throw new Error(
|
|
574
|
+
`${owner}: workers.${name} names ${path.relative(this.#app.workspace.workspaceRoot, entry)}, which does not exist.`,
|
|
575
|
+
);
|
|
576
|
+
results.push(
|
|
577
|
+
await this.#buildOrThrow(`worker ${name}`, {
|
|
578
|
+
...backendConfig,
|
|
579
|
+
outdir: path.join(this.#app.dist.cwdPath, AppWorkerPath.dir),
|
|
580
|
+
entrypoints: [entry],
|
|
581
|
+
naming: { entry: `${name}.[ext]`, chunk: "chunk-[hash].[ext]" },
|
|
582
|
+
}),
|
|
583
|
+
);
|
|
584
|
+
}
|
|
585
|
+
return results;
|
|
586
|
+
}
|
|
587
|
+
|
|
428
588
|
async #writeConsoleShim() {
|
|
429
589
|
await Bun.write(
|
|
430
590
|
path.join(this.#app.dist.cwdPath, "console.js"),
|
|
@@ -458,6 +618,14 @@ void run().catch((error) => {
|
|
|
458
618
|
}
|
|
459
619
|
}
|
|
460
620
|
|
|
621
|
+
#resolveBuildEnvEntry(): string {
|
|
622
|
+
try {
|
|
623
|
+
return path.join(path.dirname(Bun.resolveSync("akanjs/server", import.meta.dir)), "lifecycle/loadBuildEnv.ts");
|
|
624
|
+
} catch {
|
|
625
|
+
return path.join(this.#app.workspace.workspaceRoot, "pkgs/akanjs/server/lifecycle/loadBuildEnv.ts");
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
|
|
461
629
|
#resolveConsoleRuntimeBuildEntry(): string {
|
|
462
630
|
try {
|
|
463
631
|
return path.join(path.dirname(Bun.resolveSync("akanjs/server", import.meta.dir)), "console.ts");
|
|
@@ -484,6 +652,7 @@ void run().catch((error) => {
|
|
|
484
652
|
const base = await new SsrBaseArtifactBuilder(this.#app, "build", {
|
|
485
653
|
serverEnv: this.#serverEnvPlugin(baseDevEnv.env, branches),
|
|
486
654
|
vendorExports,
|
|
655
|
+
dictionaryRoutes: allRoutes.dictionaryRoutes,
|
|
487
656
|
}).build();
|
|
488
657
|
this.#modulesByRoute = (await routes.writeModulePreloads(base.runtimeChunks)).modulesByRoute();
|
|
489
658
|
return { base, allRoutes };
|
|
@@ -493,11 +662,16 @@ void run().catch((error) => {
|
|
|
493
662
|
//? verify build skips writing and measures in memory instead.
|
|
494
663
|
async #measureRouteJs(environment: string): Promise<RouteJsMeasure | null> {
|
|
495
664
|
if (this.#budget === "off" || !this.#modulesByRoute) return null;
|
|
496
|
-
const
|
|
665
|
+
const sizeByUrl = await RouteJsBudget.fileSizes(
|
|
497
666
|
path.join(this.#app.dist.cwdPath, ".akan/artifact"),
|
|
498
667
|
this.#modulesByRoute,
|
|
499
668
|
{ precompressed: !this.#verify },
|
|
500
669
|
);
|
|
670
|
+
const sizes = RouteJsBudget.sizesOf(this.#modulesByRoute, sizeByUrl);
|
|
671
|
+
await RouteFilesReport.write(
|
|
672
|
+
this.#app.cwdPath,
|
|
673
|
+
RouteFilesReport.build(this.#app.name, this.#modulesByRoute, sizeByUrl),
|
|
674
|
+
);
|
|
501
675
|
const budgetPath = path.join(this.#app.cwdPath, RouteJsBudget.fileName);
|
|
502
676
|
const { summary: status, warnings } = await RouteJsBudget.check(sizes, {
|
|
503
677
|
mode: this.#budget,
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { tempDirs } from "../test/testHelpers";
|
|
5
|
+
import { DictionarySizes } from "./dictionarySizes";
|
|
6
|
+
|
|
7
|
+
const tempRoot = tempDirs("akan-devkit-dict-sizes-");
|
|
8
|
+
|
|
9
|
+
describe("DictionarySizes", () => {
|
|
10
|
+
test("counts a route whose files would cost more than the whole page file at the whole, the API file on top", async () => {
|
|
11
|
+
const artifactDir = await tempRoot();
|
|
12
|
+
await mkdir(path.join(artifactDir, "dict"), { recursive: true });
|
|
13
|
+
const sized = { "en-page": 1000, "en-0": 600, "en-1": 500, "en-api": 200 };
|
|
14
|
+
for (const [stem, bytes] of Object.entries(sized)) {
|
|
15
|
+
await writeFile(path.join(artifactDir, `dict/${stem}.js`), "x".repeat(bytes * 4));
|
|
16
|
+
await writeFile(path.join(artifactDir, `dict/${stem}.js.br`), "x".repeat(bytes));
|
|
17
|
+
}
|
|
18
|
+
const fileOf = (stem: string) => ({ url: `/_akan/dict/${stem}.js`, relPath: `dict/${stem}.js` });
|
|
19
|
+
const artifact = {
|
|
20
|
+
dictAssets: {
|
|
21
|
+
en: {
|
|
22
|
+
...fileOf("en-page"),
|
|
23
|
+
parts: { api: fileOf("en-api") },
|
|
24
|
+
routeParts: { table: fileOf("en-groups"), files: [fileOf("en-0"), fileOf("en-1"), fileOf("en-api")] },
|
|
25
|
+
},
|
|
26
|
+
},
|
|
27
|
+
dictRoutes: { "/:lang/light": [0], "/:lang/wide": [0, 1, 2] },
|
|
28
|
+
};
|
|
29
|
+
await writeFile(path.join(artifactDir, "base-artifact.json"), JSON.stringify(artifact));
|
|
30
|
+
|
|
31
|
+
expect(DictionarySizes.of(artifactDir)).toEqual([
|
|
32
|
+
{
|
|
33
|
+
lang: "en",
|
|
34
|
+
pageBrotliBytes: 1000,
|
|
35
|
+
apiBrotliBytes: 200,
|
|
36
|
+
routeBrotliBytes: { lightest: 600, median: 600, largest: 1200 },
|
|
37
|
+
},
|
|
38
|
+
]);
|
|
39
|
+
});
|
|
40
|
+
});
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import zlib from "node:zlib";
|
|
4
|
+
import type { BaseBuildArtifact, DictAsset } from "akanjs/server";
|
|
5
|
+
import { FontPruner } from "../frontendBuild/fontPruner";
|
|
6
|
+
|
|
7
|
+
export interface DictionaryRouteBytes {
|
|
8
|
+
lightest: number;
|
|
9
|
+
median: number;
|
|
10
|
+
largest: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface DictionarySize {
|
|
14
|
+
lang: string;
|
|
15
|
+
pageBrotliBytes: number;
|
|
16
|
+
apiBrotliBytes?: number;
|
|
17
|
+
//? What a first visit downloads of the dictionary cut by route, over every route.
|
|
18
|
+
routeBrotliBytes?: DictionaryRouteBytes;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export class DictionarySizes {
|
|
22
|
+
static of(artifactDir: string): DictionarySize[] {
|
|
23
|
+
const artifactPath = path.join(artifactDir, "base-artifact.json");
|
|
24
|
+
if (!fs.existsSync(artifactPath)) return [];
|
|
25
|
+
const { dictAssets = {}, dictRoutes } = JSON.parse(fs.readFileSync(artifactPath, "utf8")) as Pick<
|
|
26
|
+
BaseBuildArtifact,
|
|
27
|
+
"dictAssets" | "dictRoutes"
|
|
28
|
+
>;
|
|
29
|
+
const brotliOf = (relPath: string) => DictionarySizes.#brotliBytesOf(path.join(artifactDir, relPath));
|
|
30
|
+
const routeIds = dictRoutes ? DictionarySizes.#routeIdsOf(artifactDir, dictRoutes) : [];
|
|
31
|
+
return Object.entries(dictAssets).map(([lang, asset]) => {
|
|
32
|
+
const api = asset.parts?.api;
|
|
33
|
+
const page = brotliOf(asset.relPath);
|
|
34
|
+
const routes =
|
|
35
|
+
dictRoutes && routeIds.length ? DictionarySizes.#routes(asset, page, routeIds, dictRoutes, brotliOf) : null;
|
|
36
|
+
return {
|
|
37
|
+
lang,
|
|
38
|
+
pageBrotliBytes: page,
|
|
39
|
+
...(api ? { apiBrotliBytes: brotliOf(api.relPath) } : {}),
|
|
40
|
+
...(routes ? { routeBrotliBytes: routes } : {}),
|
|
41
|
+
};
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
static format({ lang, pageBrotliBytes, apiBrotliBytes, routeBrotliBytes }: DictionarySize): string {
|
|
46
|
+
const { formatBytes } = FontPruner;
|
|
47
|
+
const api = apiBrotliBytes === undefined ? "" : `, API descriptions ${formatBytes(apiBrotliBytes)} where shown`;
|
|
48
|
+
if (!routeBrotliBytes) return `Dictionary ${lang}: ${formatBytes(pageBrotliBytes)} brotli on every page${api}`;
|
|
49
|
+
const { lightest, median, largest } = routeBrotliBytes;
|
|
50
|
+
const visit = `${formatBytes(lightest)} / ${formatBytes(median)} / ${formatBytes(largest)}`;
|
|
51
|
+
return `Dictionary ${lang}: first visit ${visit} brotli on the lightest / median / largest route (whole ${formatBytes(pageBrotliBytes)})${api}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
//? A route the build could not read, or whose files would cost the whole or more, is served the whole page file.
|
|
55
|
+
static #routes(
|
|
56
|
+
asset: DictAsset,
|
|
57
|
+
pageBytes: number,
|
|
58
|
+
routeIds: string[],
|
|
59
|
+
dictRoutes: Record<string, number[]>,
|
|
60
|
+
brotliOf: (relPath: string) => number,
|
|
61
|
+
): DictionaryRouteBytes | null {
|
|
62
|
+
const files = asset.routeParts?.files;
|
|
63
|
+
if (!files) return null;
|
|
64
|
+
const fileBytes = files.map(({ relPath }) => brotliOf(relPath));
|
|
65
|
+
const apiIdx = files.findIndex(({ url }) => url === asset.parts?.api?.url);
|
|
66
|
+
const sizes = routeIds
|
|
67
|
+
.map((routeId) => {
|
|
68
|
+
const parts = dictRoutes[routeId];
|
|
69
|
+
if (!parts) return pageBytes;
|
|
70
|
+
const api = parts.includes(apiIdx) ? (fileBytes[apiIdx] ?? 0) : 0;
|
|
71
|
+
const page = parts.reduce((total, idx) => total + (idx === apiIdx ? 0 : (fileBytes[idx] ?? 0)), 0);
|
|
72
|
+
return Math.min(page, pageBytes) + api;
|
|
73
|
+
})
|
|
74
|
+
.sort((a, b) => a - b);
|
|
75
|
+
const at = (idx: number) => sizes[idx] ?? 0;
|
|
76
|
+
return { lightest: at(0), median: at(Math.floor((sizes.length - 1) / 2)), largest: at(sizes.length - 1) };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
static #routeIdsOf(artifactDir: string, dictRoutes: Record<string, number[]>): string[] {
|
|
80
|
+
const seedIndexPath = path.join(artifactDir, "route-seed-index.json");
|
|
81
|
+
if (!fs.existsSync(seedIndexPath)) return Object.keys(dictRoutes);
|
|
82
|
+
const { entries = [] } = JSON.parse(fs.readFileSync(seedIndexPath, "utf8")) as { entries?: { routeId: string }[] };
|
|
83
|
+
return [...new Set(entries.map(({ routeId }) => routeId))];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
//? The `.br` sidecar is what a browser gets; a build that stops before the compress phase has none.
|
|
87
|
+
static #brotliBytesOf(file: string): number {
|
|
88
|
+
const sidecar = `${file}.br`;
|
|
89
|
+
if (fs.existsSync(sidecar)) return fs.statSync(sidecar).size;
|
|
90
|
+
const raw = fs.readFileSync(file);
|
|
91
|
+
const params = { [zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY };
|
|
92
|
+
//? precompressArtifacts writes no `.br` that would be larger than its file, so that file is served, and counted, raw.
|
|
93
|
+
return Math.min(raw.byteLength, zlib.brotliCompressSync(raw, { params }).byteLength);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { mkdir, mkdtemp } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { RouteFilesReport } from "./routeFilesReport";
|
|
6
|
+
import { RouteJsBudget } from "./routeJsBudget";
|
|
7
|
+
|
|
8
|
+
const write = async (file: string, text: string) => {
|
|
9
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
10
|
+
await Bun.write(file, text);
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
describe("RouteFilesReport", () => {
|
|
14
|
+
test("lists each file once, sorted, with routes as ascending indexes whose served bytes sum to the budget's", async () => {
|
|
15
|
+
const artifactDir = await mkdtemp(path.join(tmpdir(), "route-files-"));
|
|
16
|
+
await write(path.join(artifactDir, "client/rsc.js"), "r".repeat(3000));
|
|
17
|
+
await write(path.join(artifactDir, "client/rsc.js.br"), "b".repeat(900));
|
|
18
|
+
await write(path.join(artifactDir, "client/chunks/tiny.js"), "t".repeat(200));
|
|
19
|
+
await write(path.join(artifactDir, "client/memo.js"), "m".repeat(5000));
|
|
20
|
+
await write(path.join(artifactDir, "client/memo.js.br"), "b".repeat(1200));
|
|
21
|
+
const modulesByRoute = {
|
|
22
|
+
"/:lang/memo": ["/_akan/client/memo.js", "/_akan/client/rsc.js", "/_akan/client/chunks/tiny.js"],
|
|
23
|
+
"/:lang": ["/_akan/client/rsc.js", "/_akan/client/chunks/tiny.js"],
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const sizeByUrl = await RouteJsBudget.fileSizes(artifactDir, modulesByRoute);
|
|
27
|
+
const report = RouteFilesReport.build("demo", modulesByRoute, sizeByUrl);
|
|
28
|
+
|
|
29
|
+
expect(report.files).toEqual([
|
|
30
|
+
{ file: "/_akan/client/chunks/tiny.js", rawBytes: 200, servedBytes: 200 },
|
|
31
|
+
{ file: "/_akan/client/memo.js", rawBytes: 5000, servedBytes: 1200 },
|
|
32
|
+
{ file: "/_akan/client/rsc.js", rawBytes: 3000, servedBytes: 900 },
|
|
33
|
+
]);
|
|
34
|
+
expect(Object.keys(report.routes)).toEqual(["/:lang", "/:lang/memo"]);
|
|
35
|
+
expect(report.routes).toEqual({ "/:lang": [0, 2], "/:lang/memo": [0, 1, 2] });
|
|
36
|
+
for (const { routeId, brotliBytes, rawBytes } of RouteJsBudget.sizesOf(modulesByRoute, sizeByUrl)) {
|
|
37
|
+
const indexes = report.routes[routeId] ?? [];
|
|
38
|
+
expect(indexes.reduce((sum, index) => sum + (report.files[index]?.servedBytes ?? 0), 0)).toBe(brotliBytes);
|
|
39
|
+
expect(indexes.reduce((sum, index) => sum + (report.files[index]?.rawBytes ?? 0), 0)).toBe(rawBytes);
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test("writes the same bytes for the same input and does not throw when the directory cannot be written", async () => {
|
|
44
|
+
const appDir = await mkdtemp(path.join(tmpdir(), "route-files-app-"));
|
|
45
|
+
const report = RouteFilesReport.build(
|
|
46
|
+
"demo",
|
|
47
|
+
{ "/a": ["/_akan/x.js"] },
|
|
48
|
+
new Map([["/_akan/x.js", { raw: 5, brotli: 4 }]]),
|
|
49
|
+
);
|
|
50
|
+
await RouteFilesReport.write(appDir, report);
|
|
51
|
+
const first = await Bun.file(path.join(appDir, RouteFilesReport.file)).text();
|
|
52
|
+
await RouteFilesReport.write(appDir, report);
|
|
53
|
+
expect(await Bun.file(path.join(appDir, RouteFilesReport.file)).text()).toBe(first);
|
|
54
|
+
expect(JSON.parse(first)).toEqual(report);
|
|
55
|
+
|
|
56
|
+
await write(path.join(appDir, "blocked"), "");
|
|
57
|
+
await RouteFilesReport.write(path.join(appDir, "blocked"), report);
|
|
58
|
+
});
|
|
59
|
+
});
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import type { RouteJsFileSizes } from "./routeJsBudget";
|
|
3
|
+
|
|
4
|
+
export interface RouteFilesReportData {
|
|
5
|
+
app: string;
|
|
6
|
+
files: { file: string; rawBytes: number; servedBytes: number }[];
|
|
7
|
+
routes: Record<string, number[]>;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const byCodeUnit = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
|
|
11
|
+
|
|
12
|
+
export class RouteFilesReport {
|
|
13
|
+
//? Under `.akan/cache`: the development server clears the rest of `.akan` when it starts.
|
|
14
|
+
static readonly file = ".akan/cache/route-files.json";
|
|
15
|
+
|
|
16
|
+
static build(
|
|
17
|
+
app: string,
|
|
18
|
+
modulesByRoute: Record<string, string[]>,
|
|
19
|
+
sizeByUrl: RouteJsFileSizes,
|
|
20
|
+
): RouteFilesReportData {
|
|
21
|
+
const urls = [...sizeByUrl.keys()].sort(byCodeUnit);
|
|
22
|
+
const indexOf = new Map(urls.map((url, index) => [url, index]));
|
|
23
|
+
const routes = Object.fromEntries(
|
|
24
|
+
Object.entries(modulesByRoute)
|
|
25
|
+
.sort(([a], [b]) => byCodeUnit(a, b))
|
|
26
|
+
.map(([routeId, routeUrls]) => [
|
|
27
|
+
routeId,
|
|
28
|
+
routeUrls.flatMap((url) => indexOf.get(url) ?? []).sort((a, b) => a - b),
|
|
29
|
+
]),
|
|
30
|
+
);
|
|
31
|
+
return {
|
|
32
|
+
app,
|
|
33
|
+
files: urls.map((url) => ({
|
|
34
|
+
file: url,
|
|
35
|
+
rawBytes: sizeByUrl.get(url)?.raw ?? 0,
|
|
36
|
+
servedBytes: sizeByUrl.get(url)?.brotli ?? 0,
|
|
37
|
+
})),
|
|
38
|
+
routes,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
static async write(appDir: string, report: RouteFilesReportData) {
|
|
43
|
+
const text = `${JSON.stringify({ app: report.app, files: report.files, routes: report.routes })}\n`;
|
|
44
|
+
await Bun.write(path.join(appDir, RouteFilesReport.file), text).catch(() => 0);
|
|
45
|
+
}
|
|
46
|
+
}
|