@akanjs/devkit 3.3.0-rc.38 → 3.3.0-rc.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/frontendBuild/allRoutesBuilder.ts +7 -2
- package/frontendBuild/buildRouteClient.test.ts +65 -0
- package/frontendBuild/clientBuildTypes.ts +11 -0
- package/frontendBuild/clientEntriesBundler.ts +21 -11
- package/frontendBuild/clientEntryDiscovery.test.ts +20 -0
- package/frontendBuild/clientEntryDiscovery.ts +10 -2
- package/frontendBuild/renderedEntries.ts +25 -10
- package/frontendBuild/routeClientBuilder.ts +65 -27
- package/frontendBuild/routeModulePreloads.test.ts +32 -0
- package/frontendBuild/routeModulePreloads.ts +20 -11
- package/frontendBuild/routeRuntimeCheck.test.ts +23 -0
- package/frontendBuild/routeRuntimeCheck.ts +10 -3
- package/package.json +3 -3
- package/transforms/barrelImportsPlugin.ts +56 -40
- package/transforms/exportReach.ts +4 -0
- package/transforms/moduleParts.test.ts +225 -0
- package/transforms/moduleParts.ts +418 -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/CHANGELOG.md
CHANGED
|
@@ -409,6 +409,16 @@
|
|
|
409
409
|
- f678e80: The skills no longer repeat the path rule an agent has already loaded for the same files: `akan-query` points at the `module` rule for its musts (500 rows, soft removal, hookless writes, secret projections, cascade direction), `akan-transport` at the `auth` rule for guards and drops what the `server` rule says about body types, the 30-second default deadline and remote errors, `akan-service`, `akan-err` and `akan-mcp` at the `server` rule, and `akan-ui`, `cssRule` and `componentRule` at the `style` rule for class order and the colour vocabulary. The `server` rule drops its in-page agent line, which the `akan-agent` skill already holds and which no service, signal or document file needs. Run `akan agent install` in a workspace to pick up the new files.
|
|
410
410
|
- ce430ed: A coding agent reads less before its first page: the generated AGENTS.md is about 9% smaller, leaving to the path rules what they already say while still naming every check that breaks the build, and it now says that `i18n: { localePrefix: "as-needed" }` in `akan.config.ts` serves URLs without `/<locale>/`. The `akan-page` skill now holds the guard basics, the first-render `searchParams` snapshot and Link prefetch, so `pageRule` keeps only the deeper contract (12 KB to 7 KB), and the `@akanjs/cli` README tells an agent to read the workspace's `AGENTS.md`, rules and skills rather than the package's `guidelines/` folder. Run `akan agent install` in a workspace to pick up the new files.
|
|
411
411
|
- c44d068: A coding agent reads less to build its first app: the `akanjs` README keeps the path to a first app and links the rest on akanjs.com (17 KB to 7 KB), the `akan-page` and `akan-service` skills ship the API reference one section at a time with every entry named in the skill's index (`Link` now lists the anchor attributes it takes and `Link.Back`, `Link.Close` and `Link.Lang`), the `akan-page` skill holds what a first page looks up while `pageRule` keeps the deeper contract, and each rule is stated once across AGENTS.md, the path rules and the skills. Run `akan agent install` in a workspace to pick up the new files.
|
|
412
|
+
- 56d67dd: A production page loads the exports of a client file it uses, not everything else the file holds.
|
|
413
|
+
|
|
414
|
+
A workspace file with several exports — a `*.Util.tsx`, a `*.Zone.tsx`, a `ui/` or `webkit/` file — was one module to the bundler, so a page rendering `Memo.Util.Remove` also downloaded what `Memo.Util.Edit` imports. `akan build` now hands the browser bundle each such file as one module per export: a top-level declaration that only builds a value (a component, a function, a constant, a class) becomes its own module with the imports it alone reads, and an importer naming `{ Remove }` follows that module only. A `"use client"` file is likewise built as one entry per export, and a route preloads and counts as Route JS the entries of the exports its server files ask for.
|
|
415
|
+
|
|
416
|
+
How a file is written does not change: several exports in one file, imported by name or as `Memo.Util.Remove`. What the file does when it loads — a bare import, a call at the top level, anything that is not a plain declaration — stays together in one module that each of its exports loads first.
|
|
417
|
+
|
|
418
|
+
A file stays one module when it has a top-level `let` or `var`, `export *`, a namespace or a macro import, and so do generated barrels, `lib/__client` pieces, `index.ts` files and `*.constant|dictionary|document|service|signal|store.ts`. A namespace import (`import * as Util`) used as a value still loads every export.
|
|
419
|
+
|
|
420
|
+
On a real workspace's largest app (236 routes, brotli as served) the JS all routes load fell 9.3% in total, the lightest route went from 363.8 to 290.2 KB and the median from 795.3 to 764.7 KB. The build writes more, smaller files: 1,827 client files against 1,141, and 8.8% more bytes on disk. An app with little to take apart grows by a fraction of a KB per route. `akan start` (development) and the server bundle are unchanged. No upgrade step.
|
|
421
|
+
|
|
412
422
|
- 55d1518: A production build of a workspace with several libs loads its client modules in order, and a page that needs every module weighs what it weighed before.
|
|
413
423
|
|
|
414
424
|
- Each generated piece exports a name, and a module that needs the piece imports that name and hands it to `loadedAfter` from `akanjs/base`. A piece imported only for its effect could end up in a chunk the importer's chunk did not load first; a store or an endpoint was then read before it existed.
|
|
@@ -12,7 +12,7 @@ import type { App } from "../commandDecorators";
|
|
|
12
12
|
import { type RouteRuntimeDictionaryFallback, RouteRuntimeReport } from "../quality/routeRuntimeReport";
|
|
13
13
|
import { ModelReference } from "../transforms/modelReference";
|
|
14
14
|
import { RouteRuntime } from "../transforms/routeRuntime";
|
|
15
|
-
import type { ClientEntryDiscovery } from "./clientBuildTypes";
|
|
15
|
+
import type { AskedExports, ClientEntryDiscovery } from "./clientBuildTypes";
|
|
16
16
|
import { GraphClientEntryDiscovery } from "./clientEntryDiscovery";
|
|
17
17
|
import { DictionaryRoutes } from "./dictionaryRoutes";
|
|
18
18
|
import { type BuildRouteClientResult, RouteClientBuilder } from "./routeClientBuilder";
|
|
@@ -41,6 +41,7 @@ export class AllRoutesBuilder {
|
|
|
41
41
|
#routeIds: string[] = [];
|
|
42
42
|
#ssrEntriesByRoute = new Map<string, string[]>();
|
|
43
43
|
#entriesByRoute = new Map<string, string[]>();
|
|
44
|
+
#askedByRoute = new Map<string, AskedExports>();
|
|
44
45
|
#serverModulesByRoute = new Map<string, string[]>();
|
|
45
46
|
#externalsByChunkUrl: Record<string, string[]> = {};
|
|
46
47
|
#discovery: ClientEntryDiscovery | null = null;
|
|
@@ -70,7 +71,9 @@ export class AllRoutesBuilder {
|
|
|
70
71
|
const routeEntries = await discovery.discover(seeds);
|
|
71
72
|
for (const discovered of routeEntries) allEntries.add(discovered);
|
|
72
73
|
const serverModules = dictionary ? await discovery.serverModules(seeds, { importsAs }) : undefined;
|
|
73
|
-
const
|
|
74
|
+
const asked = await discovery.discoverAsked(seeds, { importsAs, serverModules });
|
|
75
|
+
const ssrEntries = [...asked.keys()].sort();
|
|
76
|
+
this.#askedByRoute.set(entry.routeId, asked);
|
|
74
77
|
if (serverModules) this.#serverModulesByRoute.set(entry.routeId, serverModules);
|
|
75
78
|
const handed = handoffs
|
|
76
79
|
? await handoffs.read(await discovery.serverModules(seeds, { importsAs: rendering }))
|
|
@@ -167,6 +170,7 @@ export class AllRoutesBuilder {
|
|
|
167
170
|
const preloads = new RouteModulePreloads({
|
|
168
171
|
runtimeChunks,
|
|
169
172
|
entriesByRoute: this.#ssrEntriesByRoute,
|
|
173
|
+
askedByRoute: this.#askedByRoute,
|
|
170
174
|
clientManifest: this.#merged.clientManifest,
|
|
171
175
|
externalsByChunkUrl: this.#externalsByChunkUrl,
|
|
172
176
|
workspaceRoot: this.#app.workspace.workspaceRoot,
|
|
@@ -209,6 +213,7 @@ export class AllRoutesBuilder {
|
|
|
209
213
|
command: this.#command,
|
|
210
214
|
entriesByRoute: this.#entriesByRoute,
|
|
211
215
|
sizedEntriesByRoute: this.#ssrEntriesByRoute,
|
|
216
|
+
askedByRoute: this.#askedByRoute,
|
|
212
217
|
}).build();
|
|
213
218
|
this.#app.verbose(`[build-all] bundled ${delta.newEntries.length} entries (${Date.now() - started}ms)`);
|
|
214
219
|
return delta;
|
|
@@ -744,6 +744,71 @@ export const getSerializedSignalOf = (name: string) => (name === "base" ? {} : {
|
|
|
744
744
|
const report = await Bun.file(path.join(appDir, RouteRuntimeReport.file)).json();
|
|
745
745
|
expect(report).toMatchObject({ perModule: ["/draft", "/board"], notSmaller: [], refused: ["/board"] });
|
|
746
746
|
}, 30_000);
|
|
747
|
+
|
|
748
|
+
test("a production build answers each export of a client file from its own entry, so a route asking one loads no import of the other; under start the file is one entry", async () => {
|
|
749
|
+
const { root, appDir, app, file, warnings } = await describedFixture();
|
|
750
|
+
for (const name of ["a", "b"])
|
|
751
|
+
await write(file(`heavy-${name}`), `export const heavy = { mark: "heavy-${name}-marker" };\n`);
|
|
752
|
+
const pair = file("Pair");
|
|
753
|
+
await write(
|
|
754
|
+
pair,
|
|
755
|
+
'"use client";\nimport { heavy as a } from "./heavy-a";\nimport { heavy as b } from "./heavy-b";\nexport const A = () => a.mark;\nexport const B = () => b.mark;\n',
|
|
756
|
+
);
|
|
757
|
+
const entriesByRoute = new Map([
|
|
758
|
+
["/a", [pair]],
|
|
759
|
+
["/b", [pair]],
|
|
760
|
+
]);
|
|
761
|
+
const askedByRoute = new Map([
|
|
762
|
+
["/a", new Map([[pair, ["A"]]])],
|
|
763
|
+
["/b", new Map([[pair, ["B"]]])],
|
|
764
|
+
]);
|
|
765
|
+
const buildAs = async (command: "build" | "start") => {
|
|
766
|
+
const { manifestDelta } = await new RouteClientBuilder({
|
|
767
|
+
app,
|
|
768
|
+
seeds: [],
|
|
769
|
+
entries: [pair],
|
|
770
|
+
artifact: {} as never,
|
|
771
|
+
browser: "chunks",
|
|
772
|
+
command,
|
|
773
|
+
entriesByRoute,
|
|
774
|
+
askedByRoute,
|
|
775
|
+
}).build();
|
|
776
|
+
const artifact = path.join(
|
|
777
|
+
command === "build" ? path.join(root, "dist/apps/demo") : appDir,
|
|
778
|
+
".akan/artifact",
|
|
779
|
+
);
|
|
780
|
+
const sized = new RouteModulePreloads({
|
|
781
|
+
runtimeChunks: { runtime: [], vendors: {} },
|
|
782
|
+
entriesByRoute,
|
|
783
|
+
askedByRoute,
|
|
784
|
+
clientManifest: manifestDelta,
|
|
785
|
+
externalsByChunkUrl: {},
|
|
786
|
+
workspaceRoot: root,
|
|
787
|
+
}).modulesByRoute();
|
|
788
|
+
const loadedBy = async (route: string) =>
|
|
789
|
+
(
|
|
790
|
+
await Promise.all(
|
|
791
|
+
(sized[route] ?? []).map((url) => Bun.file(path.join(artifact, url.replace(/^\/_akan\//, ""))).text()),
|
|
792
|
+
)
|
|
793
|
+
).join("\n");
|
|
794
|
+
const idOf = (name: string) => manifestDelta[`apps/demo/ui/Pair.tsx#${name}`]?.id;
|
|
795
|
+
return { rows: Object.keys(manifestDelta).sort(), idOf, a: await loadedBy("/a"), b: await loadedBy("/b") };
|
|
796
|
+
};
|
|
797
|
+
|
|
798
|
+
const built = await buildAs("build");
|
|
799
|
+
expect(built.rows).toEqual(["apps/demo/ui/Pair.tsx#A", "apps/demo/ui/Pair.tsx#B"]);
|
|
800
|
+
expect(built.idOf("A")).not.toBe(built.idOf("B"));
|
|
801
|
+
expect(built.a).toContain("heavy-a-marker");
|
|
802
|
+
expect(built.a).not.toContain("heavy-b-marker");
|
|
803
|
+
expect(built.b).toContain("heavy-b-marker");
|
|
804
|
+
expect(built.b).not.toContain("heavy-a-marker");
|
|
805
|
+
|
|
806
|
+
const started = await buildAs("start");
|
|
807
|
+
expect(started.rows).toEqual(built.rows);
|
|
808
|
+
expect(started.idOf("A")).toBe(started.idOf("B"));
|
|
809
|
+
for (const marker of ["heavy-a-marker", "heavy-b-marker"]) expect(started.a).toContain(marker);
|
|
810
|
+
expect(warnings).toEqual([]);
|
|
811
|
+
}, 30_000);
|
|
747
812
|
});
|
|
748
813
|
|
|
749
814
|
test("the files a route is sized by hold the store piece of the module its client code names, and no assembled runtime", async () => {
|
|
@@ -86,6 +86,17 @@ export interface ClientBundleGraph {
|
|
|
86
86
|
chunksByModule: Map<string, string[]>;
|
|
87
87
|
/** Static imports only: a chunk loaded by `import()` runs after the chunk asking for it. */
|
|
88
88
|
importsByChunk: Map<string, string[]>;
|
|
89
|
+
/** What the bundler placed on its own: a file taken apart by export is several, held together in the maps above. */
|
|
90
|
+
linked?: ClientLinkedInput[];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** By client entry, the export names asked of it; null for all of them. */
|
|
94
|
+
export type AskedExports = ReadonlyMap<string, readonly string[] | null>;
|
|
95
|
+
|
|
96
|
+
export interface ClientLinkedInput {
|
|
97
|
+
module: string;
|
|
98
|
+
imports: ClientModuleImport[];
|
|
99
|
+
chunks: string[];
|
|
89
100
|
}
|
|
90
101
|
|
|
91
102
|
export interface ClientModuleImport {
|
|
@@ -2,6 +2,7 @@ import fs from "node:fs";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import type { SsrManifest, SsrManifestEntry } from "akanjs/server";
|
|
4
4
|
import type { BunPlugin } from "bun";
|
|
5
|
+
import { ModuleParts } from "../transforms/moduleParts";
|
|
5
6
|
import { scanUseClientExports, toClientReferencePath } from "../transforms/rscUseClientTransform";
|
|
6
7
|
import { bundleConditions, bundleDefine } from "./bundleDefine";
|
|
7
8
|
import {
|
|
@@ -10,6 +11,7 @@ import {
|
|
|
10
11
|
CLIENT_BUNDLE_NAMING,
|
|
11
12
|
type ClientBundleGraph,
|
|
12
13
|
type ClientBundleTarget,
|
|
14
|
+
type ClientLinkedInput,
|
|
13
15
|
type ClientManifest,
|
|
14
16
|
type ClientModuleImport,
|
|
15
17
|
type MetafileInput,
|
|
@@ -118,20 +120,26 @@ export class ClientEntriesBundler {
|
|
|
118
120
|
return abs;
|
|
119
121
|
};
|
|
120
122
|
const importsByModule = new Map<string, ClientModuleImport[]>();
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
123
|
+
const linkedByInput = new Map<string, ClientLinkedInput>();
|
|
124
|
+
for (const [input, { imports = [] }] of Object.entries(this.#metafileInputs)) {
|
|
125
|
+
const module = absOf(input);
|
|
126
|
+
const own = imports
|
|
127
|
+
.filter((imported) => !imported.external)
|
|
128
|
+
.map((imported) => ({ path: absOf(imported.path), lazy: imported.kind === "dynamic-import" }))
|
|
129
|
+
.filter((imported) => imported.path !== module);
|
|
130
|
+
linkedByInput.set(input, { module, imports: own, chunks: [] });
|
|
131
|
+
const held = importsByModule.getOrInsert(module, []);
|
|
132
|
+
for (const imported of own)
|
|
133
|
+
if (!held.some((known) => known.path === imported.path && known.lazy === imported.lazy)) held.push(imported);
|
|
134
|
+
}
|
|
128
135
|
const chunksByModule = new Map<string, string[]>();
|
|
129
136
|
const importsByChunk = new Map<string, string[]>();
|
|
130
137
|
for (const [chunk, info] of this.#metafileOutputsByAbs) {
|
|
131
138
|
if (!chunk.endsWith(".js")) continue;
|
|
132
139
|
for (const input of Object.keys(info.inputs ?? {})) {
|
|
133
|
-
const
|
|
134
|
-
|
|
140
|
+
const chunks = chunksByModule.getOrInsert(absOf(input), []);
|
|
141
|
+
if (!chunks.includes(chunk)) chunks.push(chunk);
|
|
142
|
+
linkedByInput.get(input)?.chunks.push(chunk);
|
|
135
143
|
}
|
|
136
144
|
importsByChunk.set(
|
|
137
145
|
chunk,
|
|
@@ -140,7 +148,7 @@ export class ClientEntriesBundler {
|
|
|
140
148
|
.map((imported) => this.#absFromOutdir(imported.path)),
|
|
141
149
|
);
|
|
142
150
|
}
|
|
143
|
-
return { importsByModule, chunksByModule, importsByChunk };
|
|
151
|
+
return { importsByModule, chunksByModule, importsByChunk, linked: [...linkedByInput.values()] };
|
|
144
152
|
}
|
|
145
153
|
|
|
146
154
|
async #createOpaqueEntryAliases(): Promise<OpaqueEntryAliases> {
|
|
@@ -271,7 +279,9 @@ export class ClientEntriesBundler {
|
|
|
271
279
|
return path.isAbsolute(p) ? p : path.resolve(this.#outdir, p);
|
|
272
280
|
}
|
|
273
281
|
|
|
274
|
-
|
|
282
|
+
//? A file taken apart by export is linked as several inputs, each named by the file's path and its part.
|
|
283
|
+
#absFromEntryPoint(input: string): string {
|
|
284
|
+
const p = input.replace(ModuleParts.specifier, "");
|
|
275
285
|
if (path.isAbsolute(p)) return path.resolve(p);
|
|
276
286
|
const candidates = [path.resolve(process.cwd(), p), path.resolve(this.#app.cwdPath, p)];
|
|
277
287
|
return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0];
|
|
@@ -326,6 +326,26 @@ describe("GraphClientEntryDiscovery", () => {
|
|
|
326
326
|
expect(await discovery.discoverRendered([file("all.tsx")])).toEqual(whole);
|
|
327
327
|
});
|
|
328
328
|
|
|
329
|
+
test("each entry comes with the exports the route's server files ask of it, and with none named when one asks for the file", async () => {
|
|
330
|
+
const file = await tempDir();
|
|
331
|
+
const pair = file("ui/Pair.tsx");
|
|
332
|
+
await Bun.write(pair, `${client("A")}export const B = () => null;\nexport const C = () => null;\n`);
|
|
333
|
+
await Bun.write(file("a.tsx"), 'import { A } from "./ui/Pair";\nexport default () => <A />;\n');
|
|
334
|
+
await Bun.write(
|
|
335
|
+
file("ab.tsx"),
|
|
336
|
+
'import { A } from "./ui/Pair";\nimport { B as Bee } from "./ui/Pair";\nexport default () => [A, Bee];\n',
|
|
337
|
+
);
|
|
338
|
+
await Bun.write(file("all.tsx"), 'import * as Pair from "./ui/Pair";\nexport default () => Pair;\n');
|
|
339
|
+
const discovery = byExport();
|
|
340
|
+
|
|
341
|
+
expect(await discovery.discoverAsked([file("a.tsx")])).toEqual(new Map([[pair, ["A"]]]));
|
|
342
|
+
expect(await discovery.discoverAsked([file("ab.tsx")])).toEqual(new Map([[pair, ["A", "B"]]]));
|
|
343
|
+
expect(await discovery.discoverAsked([file("all.tsx")])).toEqual(new Map([[pair, null]]));
|
|
344
|
+
expect(await discovery.discoverAsked([file("a.tsx"), file("all.tsx")])).toEqual(new Map([[pair, null]]));
|
|
345
|
+
const whole = new GraphClientEntryDiscovery({ barrelImports: [] }, (async () => null) as never);
|
|
346
|
+
expect(await whole.discoverAsked([file("a.tsx")])).toEqual(new Map([[pair, null]]));
|
|
347
|
+
});
|
|
348
|
+
|
|
329
349
|
test("a second route asking the same export gets the same answer, and a saved file is read again", async () => {
|
|
330
350
|
const file = await tempDir();
|
|
331
351
|
await writeView(file);
|
|
@@ -118,9 +118,17 @@ export class GraphClientEntryDiscovery implements ClientEntryDiscovery {
|
|
|
118
118
|
seeds: string[],
|
|
119
119
|
{ importsAs, serverModules }: DiscoverOptions & { serverModules?: string[] } = {},
|
|
120
120
|
): Promise<string[]> {
|
|
121
|
+
return [...(await this.discoverAsked(seeds, { importsAs, serverModules })).keys()].sort();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
//? The same entries, each with the export names asked of it: null for all of them.
|
|
125
|
+
async discoverAsked(
|
|
126
|
+
seeds: string[],
|
|
127
|
+
{ importsAs, serverModules }: DiscoverOptions & { serverModules?: string[] } = {},
|
|
128
|
+
): Promise<Map<string, string[] | null>> {
|
|
121
129
|
const within = await this.discover(seeds, { importsAs });
|
|
122
|
-
if (!this.#rendered) return within;
|
|
123
|
-
return await this.#rendered.
|
|
130
|
+
if (!this.#rendered) return new Map(within.map((entry) => [entry, null]));
|
|
131
|
+
return await this.#rendered.asked(seeds, {
|
|
124
132
|
serverModules: serverModules ?? (await this.serverModules(seeds, { importsAs })),
|
|
125
133
|
within,
|
|
126
134
|
importsAs,
|
|
@@ -31,6 +31,12 @@ interface AskAnswer {
|
|
|
31
31
|
|
|
32
32
|
type ImportsAs = NonNullable<DiscoverOptions["importsAs"]>;
|
|
33
33
|
|
|
34
|
+
interface RenderedWalk {
|
|
35
|
+
serverModules: string[];
|
|
36
|
+
within: string[];
|
|
37
|
+
importsAs?: ImportsAs;
|
|
38
|
+
}
|
|
39
|
+
|
|
34
40
|
/**
|
|
35
41
|
* The client entries a route can render. A server module asked for one export gives only what that export's
|
|
36
42
|
* declaration reaches, and every server module the route evaluates gives what its top-level statements reach.
|
|
@@ -50,29 +56,38 @@ export class RenderedEntries {
|
|
|
50
56
|
this.#swappedAnswers = new WeakMap();
|
|
51
57
|
}
|
|
52
58
|
|
|
53
|
-
async of(
|
|
59
|
+
async of(seeds: string[], options: RenderedWalk): Promise<string[]> {
|
|
60
|
+
return [...(await this.asked(seeds, options)).keys()].sort();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
//* The same entries with the export names the route's server modules ask of each: null where one asks for them all.
|
|
64
|
+
async asked(
|
|
54
65
|
seeds: string[],
|
|
55
|
-
{ serverModules, within, importsAs }:
|
|
56
|
-
): Promise<string[]
|
|
66
|
+
{ serverModules, within, importsAs }: RenderedWalk,
|
|
67
|
+
): Promise<Map<string, string[] | null>> {
|
|
57
68
|
const answers = importsAs ? this.#answersUnder(importsAs) : this.#answers;
|
|
58
69
|
const reachable = new Set(within);
|
|
59
|
-
const entries = new
|
|
60
|
-
const
|
|
70
|
+
const entries = new Map<string, string[] | null>();
|
|
71
|
+
const seen = new Set<string>();
|
|
61
72
|
const whole = new Set<string>();
|
|
62
73
|
const queue = seeds.map((seed) => RenderedEntries.#ask(path.resolve(seed), "whole"));
|
|
63
74
|
for (const file of serverModules) queue.push(RenderedEntries.#ask(file, "always"));
|
|
64
75
|
for (const ask of queue) {
|
|
65
|
-
if (
|
|
66
|
-
|
|
76
|
+
if (seen.has(ask.key) || whole.has(ask.file)) continue;
|
|
77
|
+
seen.add(ask.key);
|
|
67
78
|
const answer = answers.get(ask.key) ?? (await this.#answer(ask, answers, importsAs));
|
|
68
79
|
if (answer.isEntry) {
|
|
69
|
-
if (ask.how
|
|
80
|
+
if (ask.how === "always" || !reachable.has(ask.file)) continue;
|
|
81
|
+
const names = entries.get(ask.file);
|
|
82
|
+
if (ask.how === "whole") entries.set(ask.file, null);
|
|
83
|
+
else if (names === undefined) entries.set(ask.file, [ask.name]);
|
|
84
|
+
else if (names && !names.includes(ask.name)) names.push(ask.name);
|
|
70
85
|
continue;
|
|
71
86
|
}
|
|
72
87
|
if (answer.whole) whole.add(ask.file);
|
|
73
|
-
for (const next of answer.next) if (!
|
|
88
|
+
for (const next of answer.next) if (!seen.has(next.key) && !whole.has(next.file)) queue.push(next);
|
|
74
89
|
}
|
|
75
|
-
return
|
|
90
|
+
return entries;
|
|
76
91
|
}
|
|
77
92
|
|
|
78
93
|
#answersUnder(importsAs: ImportsAs): Map<string, AskAnswer> {
|
|
@@ -6,13 +6,15 @@ import { type ClientRuntimeScope, StoreBootstrap } from "../artifact/storeBootst
|
|
|
6
6
|
import type { App } from "../commandDecorators";
|
|
7
7
|
import { type RouteRuntimeBuildReport, RouteRuntimeReport } from "../quality/routeRuntimeReport";
|
|
8
8
|
import { createBarrelImportsPlugin } from "../transforms/barrelImportsPlugin";
|
|
9
|
+
import { ModuleParts } from "../transforms/moduleParts";
|
|
9
10
|
import { loaderFor } from "../transforms/moduleSyntax";
|
|
11
|
+
import { PartModules } from "../transforms/partModules";
|
|
10
12
|
import { ReactIconImports } from "../transforms/reactIconImports";
|
|
11
13
|
import { RouteRuntime } from "../transforms/routeRuntime";
|
|
12
14
|
import type { RouteRuntimeBundle } from "../transforms/routeRuntimeGraph";
|
|
13
15
|
import { scanUseClientExports, toClientReferencePath } from "../transforms/rscUseClientTransform";
|
|
14
16
|
import { SignalDescriptors } from "../transforms/signalDescriptors";
|
|
15
|
-
import type { ClientBundleTarget, ClientEntryDiscovery, ClientModuleImport } from "./clientBuildTypes";
|
|
17
|
+
import type { AskedExports, ClientBundleTarget, ClientEntryDiscovery, ClientModuleImport } from "./clientBuildTypes";
|
|
16
18
|
import { ClientEntriesBundler } from "./clientEntriesBundler";
|
|
17
19
|
import { GraphClientEntryDiscovery } from "./clientEntryDiscovery";
|
|
18
20
|
import { CsrDevPaths } from "./csrDevPaths";
|
|
@@ -47,6 +49,8 @@ export interface BuildRouteClientOptions {
|
|
|
47
49
|
entriesByRoute?: ReadonlyMap<string, readonly string[]>;
|
|
48
50
|
/** The entries each route loads first, which its size is measured over. Defaults to `entriesByRoute`. */
|
|
49
51
|
sizedEntriesByRoute?: ReadonlyMap<string, readonly string[]>;
|
|
52
|
+
/** The exports each route asks of an entry it loads first; an entry left out, or null, is asked for all of them. */
|
|
53
|
+
askedByRoute?: ReadonlyMap<string, AskedExports>;
|
|
50
54
|
}
|
|
51
55
|
|
|
52
56
|
export interface BuildRouteClientResult {
|
|
@@ -67,6 +71,8 @@ export interface BuildRouteClientResult {
|
|
|
67
71
|
interface BootstrapEntries {
|
|
68
72
|
buildEntries: string[];
|
|
69
73
|
originalByBuildEntry: Map<string, string>;
|
|
74
|
+
//? Only for an entry built as several: the export names each of its build entries holds.
|
|
75
|
+
namesByBuildEntry?: Map<string, readonly string[]>;
|
|
70
76
|
}
|
|
71
77
|
|
|
72
78
|
interface NarrowedBuild {
|
|
@@ -94,6 +100,8 @@ export class RouteClientBuilder {
|
|
|
94
100
|
#browser: "chunks" | "registry";
|
|
95
101
|
#entriesByRoute?: ReadonlyMap<string, readonly string[]>;
|
|
96
102
|
#sizedEntriesByRoute?: ReadonlyMap<string, readonly string[]>;
|
|
103
|
+
#askedByRoute?: ReadonlyMap<string, AskedExports>;
|
|
104
|
+
readonly #parts = new Map<string, ModuleParts | null>();
|
|
97
105
|
|
|
98
106
|
constructor(options: BuildRouteClientOptions) {
|
|
99
107
|
this.#app = options.app;
|
|
@@ -106,6 +114,7 @@ export class RouteClientBuilder {
|
|
|
106
114
|
this.#browser = options.browser ?? (this.#command === "start" ? "registry" : "chunks");
|
|
107
115
|
this.#entriesByRoute = options.entriesByRoute;
|
|
108
116
|
this.#sizedEntriesByRoute = options.sizedEntriesByRoute;
|
|
117
|
+
this.#askedByRoute = options.askedByRoute;
|
|
109
118
|
}
|
|
110
119
|
|
|
111
120
|
async build(): Promise<BuildRouteClientResult> {
|
|
@@ -176,7 +185,7 @@ export class RouteClientBuilder {
|
|
|
176
185
|
const buildEntry = path.resolve(entry);
|
|
177
186
|
const originalEntry = path.resolve(bootstrapEntries.originalByBuildEntry.get(buildEntry) ?? buildEntry);
|
|
178
187
|
if (!acceptedEntries.has(originalEntry)) continue;
|
|
179
|
-
const deps = new Set<string>([originalEntry]);
|
|
188
|
+
const deps = new Set<string>(clientDepsByEntry[originalEntry] ?? [originalEntry]);
|
|
180
189
|
for (const dep of referenceBundle.entryDepsByAbsPath.get(buildEntry) ?? []) deps.add(path.resolve(dep));
|
|
181
190
|
const sortedDeps = [...deps].sort();
|
|
182
191
|
clientDepsByEntry[originalEntry] = sortedDeps;
|
|
@@ -355,21 +364,33 @@ export class RouteClientBuilder {
|
|
|
355
364
|
return path.join(this.#command === "build" ? this.#app.dist.cwdPath : this.#app.cwdPath, ".akan/artifact");
|
|
356
365
|
}
|
|
357
366
|
|
|
358
|
-
#sizedBuildEntries(
|
|
359
|
-
const
|
|
367
|
+
#sizedBuildEntries(entries: BootstrapEntries): Map<string, string[]> {
|
|
368
|
+
const buildEntriesOf = RouteClientBuilder.#buildEntriesOf(entries);
|
|
360
369
|
return new Map(
|
|
361
|
-
[...(this.#sizedEntriesByRoute ?? this.#entriesByRoute ?? [])].map(([route, held]) =>
|
|
362
|
-
route
|
|
363
|
-
held.
|
|
364
|
-
|
|
370
|
+
[...(this.#sizedEntriesByRoute ?? this.#entriesByRoute ?? [])].map(([route, held]) => {
|
|
371
|
+
const asked = this.#askedByRoute?.get(route);
|
|
372
|
+
return [route, held.flatMap((entry) => buildEntriesOf(entry, asked?.get(path.resolve(entry))))];
|
|
373
|
+
}),
|
|
365
374
|
);
|
|
366
375
|
}
|
|
367
376
|
|
|
377
|
+
//? An entry built as several answers with the ones holding a name asked, and with all of them asked for none.
|
|
378
|
+
static #buildEntriesOf({ originalByBuildEntry, namesByBuildEntry }: BootstrapEntries) {
|
|
379
|
+
const built = new Map<string, string[]>();
|
|
380
|
+
for (const [buildEntry, original] of originalByBuildEntry) built.getOrInsert(original, []).push(buildEntry);
|
|
381
|
+
return (entry: string, asked?: readonly string[] | null): string[] => {
|
|
382
|
+
const buildEntries = built.get(path.resolve(entry)) ?? [path.resolve(entry)];
|
|
383
|
+
if (!asked) return buildEntries;
|
|
384
|
+
return buildEntries.filter((buildEntry) => {
|
|
385
|
+
const names = namesByBuildEntry?.get(buildEntry);
|
|
386
|
+
return !names || names.some((name) => asked.includes(name));
|
|
387
|
+
});
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
|
|
368
391
|
#check({ entries, kept, bundle, runtime: routeRuntime }: NarrowedBuild): boolean {
|
|
369
392
|
const { workspaceRoot } = this.#app.workspace;
|
|
370
|
-
const
|
|
371
|
-
[...entries.originalByBuildEntry].map(([buildEntry, original]) => [original, buildEntry]),
|
|
372
|
-
);
|
|
393
|
+
const buildEntriesOf = RouteClientBuilder.#buildEntriesOf(entries);
|
|
373
394
|
const check = new RouteRuntimeCheck(workspaceRoot, bundle.graph, {
|
|
374
395
|
entries: new Map([...entries.originalByBuildEntry].filter(([, entry]) => !kept.has(entry))),
|
|
375
396
|
wholeReaders: routeRuntime.wholeReaders,
|
|
@@ -377,7 +398,7 @@ export class RouteClientBuilder {
|
|
|
377
398
|
routes: new Map(
|
|
378
399
|
[...(this.#entriesByRoute ?? [])].map(([route, held]) => [
|
|
379
400
|
route,
|
|
380
|
-
held.
|
|
401
|
+
held.flatMap((entry) => buildEntriesOf(entry)),
|
|
381
402
|
]),
|
|
382
403
|
),
|
|
383
404
|
});
|
|
@@ -419,6 +440,7 @@ export class RouteClientBuilder {
|
|
|
419
440
|
),
|
|
420
441
|
external: vendorFiles.specifiers,
|
|
421
442
|
routeRuntime,
|
|
443
|
+
...(this.#command === "build" ? { parts: this.#parts } : {}),
|
|
422
444
|
}),
|
|
423
445
|
],
|
|
424
446
|
external: vendorFiles.specifiers,
|
|
@@ -468,37 +490,53 @@ export class RouteClientBuilder {
|
|
|
468
490
|
await mkdir(outdir, { recursive: true });
|
|
469
491
|
|
|
470
492
|
const originalByBuildEntry = new Map<string, string>();
|
|
493
|
+
const namesByBuildEntry = new Map<string, readonly string[]>();
|
|
494
|
+
const { workspaceRoot } = this.#app.workspace;
|
|
471
495
|
const buildEntries = await Promise.all(
|
|
472
496
|
entries.map(async (entry) => {
|
|
473
497
|
const absEntry = path.resolve(entry);
|
|
474
498
|
const whole = narrowed?.kept.has(absEntry) ? wholeByOriginal.get(absEntry) : undefined;
|
|
475
499
|
if (whole) {
|
|
476
500
|
originalByBuildEntry.set(whole, absEntry);
|
|
477
|
-
return whole;
|
|
501
|
+
return [whole];
|
|
478
502
|
}
|
|
479
503
|
const hash = Bun.hash(`${this.#app.name}\n${absEntry}`).toString(36);
|
|
480
504
|
const base = path.basename(absEntry).replace(/[^A-Za-z0-9._-]/g, "_");
|
|
481
|
-
const
|
|
482
|
-
const exportNames =
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
505
|
+
const source = await Bun.file(absEntry).text();
|
|
506
|
+
const exportNames = scanUseClientExports(source, absEntry, workspaceRoot);
|
|
507
|
+
const byExport = scope === "page" && this.#command === "build" && PartModules.splits(workspaceRoot, absEntry);
|
|
508
|
+
const groups = byExport ? RouteClientBuilder.#exportGroups(source, absEntry, exportNames) : [exportNames];
|
|
509
|
+
return await Promise.all(
|
|
510
|
+
groups.map(async (names, index) => {
|
|
511
|
+
const wrapperEntry = path.join(outdir, `${base}-${hash}${groups.length > 1 ? `-${index}` : ""}.tsx`);
|
|
512
|
+
await Bun.write(
|
|
513
|
+
wrapperEntry,
|
|
514
|
+
RouteClientBuilder.createStoreBootstrapEntrySource({
|
|
515
|
+
appName: this.#app.name,
|
|
516
|
+
originalEntry: absEntry,
|
|
517
|
+
exportNames: names,
|
|
518
|
+
scope,
|
|
519
|
+
}),
|
|
520
|
+
);
|
|
521
|
+
originalByBuildEntry.set(path.resolve(wrapperEntry), absEntry);
|
|
522
|
+
if (groups.length > 1) namesByBuildEntry.set(path.resolve(wrapperEntry), names);
|
|
523
|
+
return wrapperEntry;
|
|
490
524
|
}),
|
|
491
525
|
);
|
|
492
|
-
originalByBuildEntry.set(path.resolve(wrapperEntry), absEntry);
|
|
493
|
-
return wrapperEntry;
|
|
494
526
|
}),
|
|
495
527
|
);
|
|
496
528
|
|
|
497
|
-
return { buildEntries, originalByBuildEntry };
|
|
529
|
+
return { buildEntries: buildEntries.flat(), originalByBuildEntry, namesByBuildEntry };
|
|
498
530
|
}
|
|
499
531
|
|
|
500
|
-
|
|
501
|
-
|
|
532
|
+
//? Names one part of the file holds share a build entry. The parts are read from the file as written, and a bundle
|
|
533
|
+
//? may place a name elsewhere after its rewrites: then a build entry only loads more than the names it holds need.
|
|
534
|
+
static #exportGroups(source: string, absEntry: string, names: string[]): string[][] {
|
|
535
|
+
const parts = names.length > 0 ? ModuleParts.read(source, absEntry) : null;
|
|
536
|
+
if (!parts) return [names];
|
|
537
|
+
const groups = new Map<string, string[]>();
|
|
538
|
+
for (const name of names) groups.getOrInsert(parts.partOf(name) ?? "", []).push(name);
|
|
539
|
+
return [...groups.values()];
|
|
502
540
|
}
|
|
503
541
|
|
|
504
542
|
static normalizeNamedDefaultFunctionForFastRefresh(
|
|
@@ -56,4 +56,36 @@ describe("RouteModulePreloads", () => {
|
|
|
56
56
|
],
|
|
57
57
|
});
|
|
58
58
|
});
|
|
59
|
+
|
|
60
|
+
test("a route asking an entry for some exports lists the chunks of those alone, and of them all when it asks for the file", () => {
|
|
61
|
+
const pair = entry("Pair");
|
|
62
|
+
const byExport = new RouteModulePreloads({
|
|
63
|
+
runtimeChunks: { runtime: [], vendors: {} },
|
|
64
|
+
entriesByRoute: new Map([
|
|
65
|
+
["/a", [pair]],
|
|
66
|
+
["/b", [pair]],
|
|
67
|
+
["/whole", [pair]],
|
|
68
|
+
["/unasked", [pair]],
|
|
69
|
+
]),
|
|
70
|
+
askedByRoute: new Map<string, Map<string, string[] | null>>([
|
|
71
|
+
["/a", new Map([[pair, ["A"]]])],
|
|
72
|
+
["/b", new Map([[pair, ["B", "Missing"]]])],
|
|
73
|
+
["/whole", new Map([[pair, null]])],
|
|
74
|
+
]),
|
|
75
|
+
clientManifest: {
|
|
76
|
+
"apps/demo/ui/Pair.tsx#A": { ...row("/_akan/client/a.js", "/_akan/client/chunks/s.js"), name: "A" },
|
|
77
|
+
"apps/demo/ui/Pair.tsx#B": { ...row("/_akan/client/b.js", "/_akan/client/chunks/s.js"), name: "B" },
|
|
78
|
+
},
|
|
79
|
+
externalsByChunkUrl: {},
|
|
80
|
+
workspaceRoot: root,
|
|
81
|
+
});
|
|
82
|
+
const both = ["/_akan/client/a.js", "/_akan/client/chunks/s.js", "/_akan/client/b.js"];
|
|
83
|
+
|
|
84
|
+
expect(byExport.modulesByRoute()).toEqual({
|
|
85
|
+
"/a": ["/_akan/client/a.js", "/_akan/client/chunks/s.js"],
|
|
86
|
+
"/b": ["/_akan/client/b.js", "/_akan/client/chunks/s.js"],
|
|
87
|
+
"/whole": both,
|
|
88
|
+
"/unasked": both,
|
|
89
|
+
});
|
|
90
|
+
});
|
|
59
91
|
});
|
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
import type { ClientManifest } from "akanjs/server";
|
|
2
2
|
import { ModulePreloadPlan, type ModulePreloadTable } from "akanjs/server/artifact/modulePreloadPlan";
|
|
3
3
|
import { toClientReferencePath } from "../transforms/rscUseClientTransform";
|
|
4
|
+
import type { AskedExports } from "./clientBuildTypes";
|
|
4
5
|
|
|
5
6
|
export type RuntimeChunks = Pick<ModulePreloadTable, "runtime" | "vendors">;
|
|
6
7
|
|
|
7
8
|
export interface RouteModulePreloadsInput {
|
|
8
9
|
runtimeChunks: RuntimeChunks;
|
|
9
10
|
entriesByRoute: Map<string, string[]>;
|
|
11
|
+
/** The exports each route asks of its entries; an entry left out, or null, is preloaded with all of them. */
|
|
12
|
+
askedByRoute?: ReadonlyMap<string, AskedExports>;
|
|
10
13
|
clientManifest: ClientManifest;
|
|
11
14
|
externalsByChunkUrl: Record<string, string[]>;
|
|
12
15
|
workspaceRoot: string;
|
|
@@ -15,13 +18,13 @@ export interface RouteModulePreloadsInput {
|
|
|
15
18
|
export class RouteModulePreloads {
|
|
16
19
|
readonly table: ModulePreloadTable;
|
|
17
20
|
#input: RouteModulePreloadsInput;
|
|
18
|
-
#chunksByReferenceId = new Map<string,
|
|
21
|
+
#chunksByReferenceId = new Map<string, Map<string, string[]>>();
|
|
19
22
|
|
|
20
23
|
constructor(input: RouteModulePreloadsInput) {
|
|
21
24
|
this.#input = input;
|
|
22
25
|
for (const [key, row] of Object.entries(input.clientManifest)) {
|
|
23
|
-
const
|
|
24
|
-
|
|
26
|
+
const hash = key.lastIndexOf("#");
|
|
27
|
+
this.#chunksByReferenceId.getOrInsert(key.slice(0, hash), new Map()).set(key.slice(hash + 1), row.chunks);
|
|
25
28
|
}
|
|
26
29
|
this.table = {
|
|
27
30
|
...input.runtimeChunks,
|
|
@@ -39,14 +42,20 @@ export class RouteModulePreloads {
|
|
|
39
42
|
modulesByRoute(): Record<string, string[]> {
|
|
40
43
|
const plan = new ModulePreloadPlan(this.table);
|
|
41
44
|
return Object.fromEntries(
|
|
42
|
-
[...this.#input.entriesByRoute].map(([routeId, entries]) =>
|
|
43
|
-
routeId
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
]),
|
|
45
|
+
[...this.#input.entriesByRoute].map(([routeId, entries]) => {
|
|
46
|
+
const asked = this.#input.askedByRoute?.get(routeId);
|
|
47
|
+
return [
|
|
48
|
+
routeId,
|
|
49
|
+
plan.urlsOf([...new Set(entries.flatMap((entry) => this.#chunksOf(entry, asked?.get(entry))))]),
|
|
50
|
+
];
|
|
51
|
+
}),
|
|
50
52
|
);
|
|
51
53
|
}
|
|
54
|
+
|
|
55
|
+
#chunksOf(entry: string, names?: readonly string[] | null): string[] {
|
|
56
|
+
const chunksByName = this.#chunksByReferenceId.get(toClientReferencePath(entry, this.#input.workspaceRoot));
|
|
57
|
+
if (!chunksByName) return [];
|
|
58
|
+
const rows = names ? names.map((name) => chunksByName.get(name) ?? []) : [...chunksByName.values()];
|
|
59
|
+
return rows.flat();
|
|
60
|
+
}
|
|
52
61
|
}
|