@akanjs/devkit 3.3.0-rc.37 → 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 +65 -0
- package/app/applicationBuildRunner.ts +7 -1
- package/app/dictionarySizes.ts +2 -5
- package/app/routeFilesReport.test.ts +59 -0
- package/app/routeFilesReport.ts +46 -0
- package/app/routeJsBudget.ts +18 -4
- package/artifact/storeBootstrap.ts +5 -1
- package/biome.base.json +1 -3
- package/codeAgent/skills/akan-page/SKILL.md +28 -7
- package/executors/clientRuntimeKeys.test.ts +72 -1
- package/executors/sysExecutor.ts +10 -8
- package/frontendBuild/allRoutesBuilder.ts +20 -8
- package/frontendBuild/buildRouteClient.test.ts +65 -0
- package/frontendBuild/clientBuildTypes.ts +11 -0
- package/frontendBuild/clientEntriesBundler.ts +21 -11
- package/frontendBuild/clientEntryDiscovery.test.ts +213 -0
- package/frontendBuild/clientEntryDiscovery.ts +49 -8
- package/frontendBuild/devBarrelImports.test.ts +54 -0
- package/frontendBuild/devBarrelImports.ts +1 -0
- package/frontendBuild/dictionaryAssetBuilder.test.ts +12 -4
- package/frontendBuild/dictionaryAssetBuilder.ts +20 -7
- package/frontendBuild/dictionaryConstants.ts +55 -1
- package/frontendBuild/dictionaryPacking.test.ts +58 -0
- package/frontendBuild/dictionaryPacking.ts +43 -0
- package/frontendBuild/dictionaryRoutes.test.ts +65 -0
- package/frontendBuild/dictionaryRoutes.ts +3 -1
- package/frontendBuild/precompressArtifacts.test.ts +22 -0
- package/frontendBuild/precompressArtifacts.ts +18 -11
- package/frontendBuild/renderedEntries.ts +144 -0
- package/frontendBuild/routeClientBuilder.ts +65 -27
- package/frontendBuild/routeHandoffs.test.ts +10 -0
- package/frontendBuild/routeHandoffs.ts +3 -1
- 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/frontendBuild/routeRuntimePays.test.ts +7 -1
- package/lint/biomeBase.test.ts +23 -3
- package/package.json +3 -3
- package/quality/dictionaryKeys.test.ts +185 -2
- package/quality/dictionaryKeys.ts +82 -9
- package/quality/objectImportReport.ts +6 -3
- package/quality/translatorBindings.ts +187 -0
- package/transforms/barrelImportsPlugin.ts +56 -35
- package/transforms/exportReach.test.ts +162 -0
- package/transforms/exportReach.ts +308 -0
- package/transforms/moduleParts.test.ts +225 -0
- package/transforms/moduleParts.ts +418 -0
- package/transforms/objectMemberImports.test.ts +289 -7
- package/transforms/objectMemberImports.ts +92 -58
- package/transforms/objectMemberLookup.ts +150 -0
- package/transforms/objectModule.test.ts +72 -2
- package/transforms/objectModule.ts +31 -7
- 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/workspace/scanInfo.ts +24 -0
|
@@ -263,12 +263,20 @@ describe("DictionaryAssetBuilder", () => {
|
|
|
263
263
|
);
|
|
264
264
|
|
|
265
265
|
describe("for the routes it is handed", () => {
|
|
266
|
+
//? Texts brotli cannot fold away: with a few words per group a route's own files outweigh the whole file.
|
|
267
|
+
const long = (group: string) => ({
|
|
268
|
+
t: Array.from({ length: 80 }, (_, idx) => Bun.hash(`${group}${idx}`).toString(36)).join(" "),
|
|
269
|
+
});
|
|
266
270
|
const routedDictionary = {
|
|
267
271
|
en: {
|
|
268
|
-
base: { t: "Base", ok: { t: "OK" } },
|
|
269
|
-
memo: {
|
|
270
|
-
|
|
271
|
-
|
|
272
|
+
base: { t: "Base", ok: { t: "OK" }, long: long("base") },
|
|
273
|
+
memo: {
|
|
274
|
+
t: "Memo",
|
|
275
|
+
long: long("memo"),
|
|
276
|
+
signal: { getMemo: { t: "Get Memo", desc: { t: "Reads a memo" } } },
|
|
277
|
+
},
|
|
278
|
+
user: { t: "User", long: long("user") },
|
|
279
|
+
util: { t: "Util", long: long("util") },
|
|
272
280
|
},
|
|
273
281
|
ko: { base: { t: "기본" }, memo: { t: "메모" } },
|
|
274
282
|
};
|
|
@@ -4,6 +4,7 @@ import type { AkanI18nConfig } from "akanjs/common";
|
|
|
4
4
|
import type { DictAsset } from "akanjs/server";
|
|
5
5
|
import type { App } from "../commandDecorators";
|
|
6
6
|
import { DictionaryPacking } from "./dictionaryPacking";
|
|
7
|
+
import { dictionaryBrotliBytesOf } from "./precompressArtifacts";
|
|
7
8
|
|
|
8
9
|
export interface DictionaryAssetBuildOptions {
|
|
9
10
|
/** Each locale's API descriptions go to a file of their own, loaded where shown. */
|
|
@@ -56,11 +57,17 @@ export class DictionaryAssetBuilder {
|
|
|
56
57
|
return { lang, ...(splitApi ? DictionaryAssetBuilder.splitApi(dictionary) : { page: dictionary, api: {} }) };
|
|
57
58
|
});
|
|
58
59
|
const groups = [...new Set(locales.flatMap(({ page }) => Object.keys(page)))].sort();
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
60
|
+
const packed = routes?.size ? DictionaryAssetBuilder.#pack(routes, locales, i18n.defaultLocale, groups) : null;
|
|
61
|
+
if (packed?.wholeRoutes.length)
|
|
62
|
+
this.#app.verbose(
|
|
63
|
+
`[dictionary] ${packed.wholeRoutes.length} route(s) load the whole page dictionary: their own files would not be smaller. Routes: ${packed.wholeRoutes.join(", ")}`,
|
|
64
|
+
);
|
|
65
|
+
const pack =
|
|
66
|
+
packed && Object.keys(packed.partsByRoute).length
|
|
67
|
+
? packed
|
|
68
|
+
: everyGroupAlone
|
|
69
|
+
? { parts: groups.map((group) => [group]), partsByRoute: {} }
|
|
70
|
+
: null;
|
|
64
71
|
const assets = await Promise.all(locales.map((locale) => this.#writeLocale(locale, pack?.parts)));
|
|
65
72
|
const files = assets.flatMap(([, asset]) => [
|
|
66
73
|
asset,
|
|
@@ -91,8 +98,14 @@ export class DictionaryAssetBuilder {
|
|
|
91
98
|
defaultLocale: string,
|
|
92
99
|
groups: string[],
|
|
93
100
|
) {
|
|
94
|
-
const
|
|
95
|
-
|
|
101
|
+
const { lang = defaultLocale, page: sizing = {} } =
|
|
102
|
+
locales.find((locale) => locale.lang === defaultLocale) ?? locales[0] ?? {};
|
|
103
|
+
const servedBytesOf = (held: readonly string[]) => {
|
|
104
|
+
const texts = Object.fromEntries(held.flatMap((group) => (sizing[group] ? [[group, sizing[group]]] : [])));
|
|
105
|
+
return dictionaryBrotliBytesOf(DictionaryAssetBuilder.source(lang, texts));
|
|
106
|
+
};
|
|
107
|
+
const bytesOf = (group: string) => JSON.stringify(sizing[group] ?? {}).length;
|
|
108
|
+
return DictionaryPacking.packUnderWhole(routes, bytesOf, groups, servedBytesOf);
|
|
96
109
|
}
|
|
97
110
|
|
|
98
111
|
//? The same module the root layout's macro evaluates in this process, so the asset and the RSC worker's copy agree.
|
|
@@ -16,6 +16,8 @@ export class DictionaryConstants {
|
|
|
16
16
|
readonly #kindOf = new Map<string, GroupKind>();
|
|
17
17
|
readonly #typesOf = new Map<string, Set<string>>();
|
|
18
18
|
readonly #reach = new Map<string, string[]>();
|
|
19
|
+
readonly #statics = new Map<string, (string[] | null)[]>();
|
|
20
|
+
readonly #classCount = new Map<string, number>();
|
|
19
21
|
|
|
20
22
|
static async read(workspaceRoot: string, scopes: string[]): Promise<DictionaryConstants> {
|
|
21
23
|
const constants = new DictionaryConstants();
|
|
@@ -28,10 +30,11 @@ export class DictionaryConstants {
|
|
|
28
30
|
}
|
|
29
31
|
|
|
30
32
|
add(fileName: string, text: string) {
|
|
33
|
+
const sourceFile = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
34
|
+
this.#addStatics(sourceFile);
|
|
31
35
|
const [, scalar, underscore, group] = fileName.match(constantFile) ?? [];
|
|
32
36
|
if (!group) return;
|
|
33
37
|
this.#kindOf.set(group, scalar ? "scalar" : underscore ? "service" : "model");
|
|
34
|
-
const sourceFile = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
|
35
38
|
const types = this.#typesOf.get(group) ?? new Set<string>();
|
|
36
39
|
for (const constant of DictionaryConstants.#reader.read(sourceFile, null).constants) {
|
|
37
40
|
this.#classTo(constant.name, group);
|
|
@@ -45,6 +48,57 @@ export class DictionaryConstants {
|
|
|
45
48
|
}
|
|
46
49
|
}
|
|
47
50
|
|
|
51
|
+
#addStatics(sourceFile: ts.SourceFile) {
|
|
52
|
+
for (const statement of sourceFile.statements) {
|
|
53
|
+
if (!ts.isClassDeclaration(statement) || !statement.name) continue;
|
|
54
|
+
this.#classCount.set(statement.name.text, (this.#classCount.get(statement.name.text) ?? 0) + 1);
|
|
55
|
+
for (const member of statement.members) {
|
|
56
|
+
const name =
|
|
57
|
+
member.name && (ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)) && member.name.text;
|
|
58
|
+
if (!name || !(ts.getCombinedModifierFlags(member) & ts.ModifierFlags.Static)) continue;
|
|
59
|
+
const key = `${statement.name.text}.${name}`;
|
|
60
|
+
const table = ts.isPropertyDeclaration(member) ? DictionaryConstants.#tableOf(member) : null;
|
|
61
|
+
this.#statics.set(key, [...(this.#statics.get(key) ?? []), table]);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
//? `as const` with no annotation types the static as its literals, so nothing but the written keys is assignable to it.
|
|
67
|
+
static #tableOf(member: ts.PropertyDeclaration): string[] | null {
|
|
68
|
+
let node = member.initializer;
|
|
69
|
+
while (node && (ts.isParenthesizedExpression(node) || ts.isSatisfiesExpression(node))) node = node.expression;
|
|
70
|
+
if (member.type || !node || !ts.isAsExpression(node) || !ts.isConstTypeReference(node.type)) return null;
|
|
71
|
+
let table = node.expression;
|
|
72
|
+
while (ts.isParenthesizedExpression(table)) table = table.expression;
|
|
73
|
+
const values = ts.isArrayLiteralExpression(table)
|
|
74
|
+
? [...table.elements]
|
|
75
|
+
: ts.isObjectLiteralExpression(table)
|
|
76
|
+
? table.properties.map((property) =>
|
|
77
|
+
ts.isPropertyAssignment(property) && !ts.isComputedPropertyName(property.name)
|
|
78
|
+
? property.initializer
|
|
79
|
+
: null,
|
|
80
|
+
)
|
|
81
|
+
: [null];
|
|
82
|
+
const keys: string[] = [];
|
|
83
|
+
for (const value of values) {
|
|
84
|
+
if (!value || !ts.isStringLiteralLike(value)) return null;
|
|
85
|
+
keys.push(value.text);
|
|
86
|
+
}
|
|
87
|
+
return keys;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
//? An app and a lib may each declare a class of the name, and one that leaves the static out may inherit another.
|
|
91
|
+
staticKeysOf(className: string, member: string): string[] | null {
|
|
92
|
+
const tables = this.#statics.get(`${className}.${member}`);
|
|
93
|
+
if (!tables || tables.length !== this.#classCount.get(className)) return null;
|
|
94
|
+
const keys = new Set<string>();
|
|
95
|
+
for (const table of tables) {
|
|
96
|
+
if (!table) return null;
|
|
97
|
+
for (const key of table) keys.add(key);
|
|
98
|
+
}
|
|
99
|
+
return [...keys];
|
|
100
|
+
}
|
|
101
|
+
|
|
48
102
|
#classTo(name: string, group: string) {
|
|
49
103
|
this.#groupOfClass.set(name, (this.#groupOfClass.get(name) ?? new Set()).add(group));
|
|
50
104
|
}
|
|
@@ -69,6 +69,64 @@ describe("DictionaryPacking", () => {
|
|
|
69
69
|
expect(pack.partsByRoute).toEqual({ "/:lang/a": [0], "/:lang/b": [0] });
|
|
70
70
|
});
|
|
71
71
|
|
|
72
|
+
describe("held under the whole dictionary", () => {
|
|
73
|
+
const fileOverhead = 300;
|
|
74
|
+
const servedOf = (bytesOf: (group: string) => number) => (held: readonly string[]) =>
|
|
75
|
+
fileOverhead + held.reduce((sum, group) => sum + bytesOf(group), 0);
|
|
76
|
+
|
|
77
|
+
test("a route whose files would not be smaller than the whole loads the whole file and no longer shapes the cut", () => {
|
|
78
|
+
const modules = Array.from({ length: 8 }, (_, idx) => `module${idx}`);
|
|
79
|
+
const groups = ["base", ...modules];
|
|
80
|
+
const light = new Map(modules.map((module) => [`/:lang/${module}`, ["base", module]]));
|
|
81
|
+
const routes = new Map([...light, ["/:lang/everything", groups]]);
|
|
82
|
+
const bytesOf = (group: string) => (group === "base" ? 2000 : 5000);
|
|
83
|
+
const pack = DictionaryPacking.packUnderWhole(routes, bytesOf, groups, servedOf(bytesOf));
|
|
84
|
+
const alone = DictionaryPacking.pack(routes, bytesOf, groups);
|
|
85
|
+
|
|
86
|
+
expect(pack.wholeRoutes).toEqual(["/:lang/everything"]);
|
|
87
|
+
expect(pack.partsByRoute["/:lang/everything"]).toBeUndefined();
|
|
88
|
+
expect({ parts: pack.parts, partsByRoute: pack.partsByRoute }).toEqual(
|
|
89
|
+
DictionaryPacking.pack(light, bytesOf, groups),
|
|
90
|
+
);
|
|
91
|
+
for (const module of modules) {
|
|
92
|
+
const held = (files: number[] = [], parts: string[][]) => files.flatMap((idx) => parts[idx] ?? []).sort();
|
|
93
|
+
expect(held(pack.partsByRoute[`/:lang/${module}`], pack.parts)).toEqual(["base", module]);
|
|
94
|
+
expect(held(alone.partsByRoute[`/:lang/${module}`], alone.parts).length).toBeGreaterThan(2);
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test("no route left on files loads the whole or more, and all routes together load no more than before", () => {
|
|
99
|
+
const { groups, routes, bytesOf } = manyModules();
|
|
100
|
+
const served = servedOf(bytesOf);
|
|
101
|
+
const whole = served(groups);
|
|
102
|
+
const costOf = ({ parts, partsByRoute }: ReturnType<typeof DictionaryPacking.pack>) =>
|
|
103
|
+
[...routes.keys()].reduce((sum, routeId) => {
|
|
104
|
+
const files = partsByRoute[routeId];
|
|
105
|
+
const own = files?.reduce((bytes, idx) => bytes + served(parts[idx] ?? []), 0) ?? whole;
|
|
106
|
+
return sum + Math.min(own, whole);
|
|
107
|
+
}, 0);
|
|
108
|
+
const pack = DictionaryPacking.packUnderWhole(routes, bytesOf, groups, served);
|
|
109
|
+
|
|
110
|
+
expect(pack.wholeRoutes).toContain("/:lang/everything");
|
|
111
|
+
expect(Object.keys(pack.partsByRoute).length).toBe(routes.size - pack.wholeRoutes.length);
|
|
112
|
+
for (const files of Object.values(pack.partsByRoute))
|
|
113
|
+
expect(files.reduce((sum, idx) => sum + served(pack.parts[idx] ?? []), 0)).toBeLessThan(whole);
|
|
114
|
+
expect(costOf(pack)).toBeLessThanOrEqual(costOf(DictionaryPacking.pack(routes, bytesOf, groups)));
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test("every route loads the whole file where each shows every group", () => {
|
|
118
|
+
const routes = new Map([
|
|
119
|
+
["/:lang/a", ["base", "memo", "user"]],
|
|
120
|
+
["/:lang/b", ["base", "user", "memo"]],
|
|
121
|
+
]);
|
|
122
|
+
const bytesOf = (group: string) => (group === "base" ? 9000 : 300);
|
|
123
|
+
const pack = DictionaryPacking.packUnderWhole(routes, bytesOf, ["base", "memo", "user"], servedOf(bytesOf));
|
|
124
|
+
|
|
125
|
+
expect(pack.wholeRoutes).toEqual(["/:lang/a", "/:lang/b"]);
|
|
126
|
+
expect(pack.partsByRoute).toEqual({});
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
|
|
72
130
|
test("a second route reuses the files the first one loaded where they share groups", () => {
|
|
73
131
|
const routes = new Map([
|
|
74
132
|
["/:lang/memo", ["base", "memo", "user"]],
|
|
@@ -48,6 +48,49 @@ export class DictionaryPacking {
|
|
|
48
48
|
return { parts, partsByRoute };
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
+
//? Several files compress worse than one, so a route showing nearly every text is cheaper on the whole dictionary.
|
|
52
|
+
static packUnderWhole(
|
|
53
|
+
routes: ReadonlyMap<string, readonly string[]>,
|
|
54
|
+
bytesOf: (group: string) => number,
|
|
55
|
+
groups: readonly string[],
|
|
56
|
+
servedBytesOf: (groups: readonly string[]) => number,
|
|
57
|
+
options: { bound?: number; requestBytes?: number } = {},
|
|
58
|
+
): DictionaryPack & { wholeRoutes: string[] } {
|
|
59
|
+
const whole = servedBytesOf([...new Set(groups)].sort());
|
|
60
|
+
const served = new Map<string, number>();
|
|
61
|
+
const servedOf = (part: readonly string[]) => {
|
|
62
|
+
const key = part.join("\n");
|
|
63
|
+
const known = served.get(key) ?? servedBytesOf(part);
|
|
64
|
+
served.set(key, known);
|
|
65
|
+
return known;
|
|
66
|
+
};
|
|
67
|
+
const shownBytesOf = (routeId: string) =>
|
|
68
|
+
[...new Set(routes.get(routeId))].reduce((sum, group) => sum + bytesOf(group), 0);
|
|
69
|
+
const partial = new Map(routes);
|
|
70
|
+
let best: { pack: DictionaryPack; over: string[]; cost: number } | null = null;
|
|
71
|
+
for (;;) {
|
|
72
|
+
const pack = DictionaryPacking.pack(partial, bytesOf, groups, options);
|
|
73
|
+
const costs = Object.entries(pack.partsByRoute).map(([routeId, files]) => ({
|
|
74
|
+
routeId,
|
|
75
|
+
cost: files.reduce((sum, idx) => sum + servedOf(pack.parts[idx] ?? []), 0),
|
|
76
|
+
}));
|
|
77
|
+
const over = costs.filter(({ cost }) => cost >= whole).map(({ routeId }) => routeId);
|
|
78
|
+
const cost =
|
|
79
|
+
costs.reduce((sum, route) => sum + Math.min(route.cost, whole), 0) + (routes.size - partial.size) * whole;
|
|
80
|
+
if (!best || cost < best.cost) best = { pack, over, cost };
|
|
81
|
+
if (!over.length) break;
|
|
82
|
+
//? Half at a time, the routes showing the most first: without them the rest may come out smaller after all.
|
|
83
|
+
over.sort((a, b) => shownBytesOf(b) - shownBytesOf(a) || (a < b ? -1 : 1));
|
|
84
|
+
for (const routeId of over.slice(0, Math.ceil(over.length / 2))) partial.delete(routeId);
|
|
85
|
+
}
|
|
86
|
+
const dropped = new Set(best.over);
|
|
87
|
+
const partsByRoute = Object.fromEntries(
|
|
88
|
+
Object.entries(best.pack.partsByRoute).filter(([routeId]) => !dropped.has(routeId)),
|
|
89
|
+
);
|
|
90
|
+
const wholeRoutes = [...routes.keys()].sort().filter((routeId) => !Object.hasOwn(partsByRoute, routeId));
|
|
91
|
+
return { parts: best.pack.parts, partsByRoute, wholeRoutes };
|
|
92
|
+
}
|
|
93
|
+
|
|
51
94
|
static #setsOf(parts: string[][], needs: string[][]) {
|
|
52
95
|
const partOf = new Map(parts.flatMap((part, idx) => part.map((group) => [group, idx] as const)));
|
|
53
96
|
return needs.map((need) => new Set(need.map((group) => partOf.get(group) as number)));
|
|
@@ -35,6 +35,22 @@ export class User extends via(UserInput, (field) => ({})) {}
|
|
|
35
35
|
"apps/demo/lib/__scalar/address/address.constant.ts",
|
|
36
36
|
`export class Address extends via((field) => ({ city: field(String) })) {}`,
|
|
37
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
|
+
);
|
|
38
54
|
return constants;
|
|
39
55
|
};
|
|
40
56
|
|
|
@@ -153,6 +169,55 @@ describe("DictionaryRoutes", () => {
|
|
|
153
169
|
});
|
|
154
170
|
});
|
|
155
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
|
+
|
|
156
221
|
test("a route naming an API description key says so, for the API description file", async () => {
|
|
157
222
|
const { root, abs } = await workspace({
|
|
158
223
|
"apps/demo/page/Api.tsx": `export const Page = () => <>{l("memo.signal.getMemo.desc")}</>;`,
|
|
@@ -214,7 +214,9 @@ export class DictionaryRoutes {
|
|
|
214
214
|
}
|
|
215
215
|
const known = this.#reads.get(file);
|
|
216
216
|
if (known?.source === source) return known;
|
|
217
|
-
const
|
|
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) };
|
|
218
220
|
this.#reads.set(file, next);
|
|
219
221
|
return next;
|
|
220
222
|
}
|
|
@@ -39,4 +39,26 @@ describe("precompressArtifacts", () => {
|
|
|
39
39
|
expect(await readFile(`${chunkPath}.br`)).toEqual(brotliAt(await readFile(chunkPath), 9));
|
|
40
40
|
expect(await Bun.file(`${dictPath}.gz`).exists()).toBe(true);
|
|
41
41
|
});
|
|
42
|
+
|
|
43
|
+
test("compresses a chunk under 1 KB too, and writes no sidecar that would be larger than its file", async () => {
|
|
44
|
+
const distPath = await tempRoot();
|
|
45
|
+
const artifactDir = path.join(distPath, ".akan/artifact");
|
|
46
|
+
const stubPath = path.join(artifactDir, "client/stub.js");
|
|
47
|
+
const tinyPath = path.join(artifactDir, "client/tiny.js");
|
|
48
|
+
await mkdir(path.dirname(stubPath), { recursive: true });
|
|
49
|
+
await writeFile(
|
|
50
|
+
stubPath,
|
|
51
|
+
'import{a as memoStore,b as memoList}from"./chunks/abc.js";export{memoStore,memoList};\n'.repeat(4),
|
|
52
|
+
);
|
|
53
|
+
await writeFile(tinyPath, "x");
|
|
54
|
+
const app = { dist: { cwdPath: distPath }, verbose: () => undefined } as unknown as App;
|
|
55
|
+
|
|
56
|
+
expect((await precompressArtifacts(app)).files).toBe(1);
|
|
57
|
+
const stubBytes = await readFile(stubPath);
|
|
58
|
+
expect(stubBytes.byteLength).toBeLessThan(1024);
|
|
59
|
+
expect(await readFile(`${stubPath}.br`)).toEqual(brotliAt(stubBytes, 9));
|
|
60
|
+
expect((await readFile(`${stubPath}.gz`)).byteLength).toBeLessThan(stubBytes.byteLength);
|
|
61
|
+
expect(await Bun.file(`${tinyPath}.br`).exists()).toBe(false);
|
|
62
|
+
expect(await Bun.file(`${tinyPath}.gz`).exists()).toBe(false);
|
|
63
|
+
});
|
|
42
64
|
});
|
|
@@ -5,7 +5,6 @@ import type { App } from "../commandDecorators";
|
|
|
5
5
|
import { FontPruner } from "./fontPruner";
|
|
6
6
|
|
|
7
7
|
const COMPRESSIBLE_EXTS = new Set([".css", ".html", ".js", ".json", ".svg"]);
|
|
8
|
-
const MIN_COMPRESS_BYTES = 1024;
|
|
9
8
|
// Brotli 11 is ~100x slower than gzip: worth it for the one CSS asset per basePath and one dictionary per locale, not
|
|
10
9
|
// for hundreds of JS chunks.
|
|
11
10
|
const MAX_BROTLI_QUALITY = 11;
|
|
@@ -59,11 +58,17 @@ async function precompressRoot(
|
|
|
59
58
|
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
|
|
60
59
|
const gz = Bun.gzipSync(buffer, { level: GZIP_LEVEL });
|
|
61
60
|
const br = brotliCompress(buffer, brotliQuality ?? brotliQualityOf(path.extname(filePath).toLowerCase()));
|
|
62
|
-
|
|
61
|
+
//? No 1 KB floor, unlike a response compressed as it is sent: serving a sidecar costs nothing per request.
|
|
62
|
+
const smaller = [
|
|
63
|
+
{ ext: ".gz", encoded: gz },
|
|
64
|
+
{ ext: ".br", encoded: br },
|
|
65
|
+
].filter(({ encoded }) => encoded.byteLength < bytes.byteLength);
|
|
66
|
+
if (smaller.length === 0) continue;
|
|
67
|
+
await Promise.all(smaller.map(({ ext, encoded }) => Bun.write(`${filePath}${ext}`, encoded)));
|
|
63
68
|
result.files += 1;
|
|
64
69
|
result.inputBytes += bytes.byteLength;
|
|
65
|
-
result.outputBytes += gz.byteLength;
|
|
66
|
-
result.brotliBytes += br.byteLength;
|
|
70
|
+
result.outputBytes += Math.min(gz.byteLength, bytes.byteLength);
|
|
71
|
+
result.brotliBytes += Math.min(br.byteLength, bytes.byteLength);
|
|
67
72
|
}
|
|
68
73
|
}
|
|
69
74
|
|
|
@@ -73,20 +78,24 @@ export async function servedBrotliBytesOf(artifactDir: string, filePath: string)
|
|
|
73
78
|
const bytes = await Bun.file(filePath).bytes();
|
|
74
79
|
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
|
|
75
80
|
const quality = ROOT_BROTLI_QUALITY[root] ?? brotliQualityOf(path.extname(filePath).toLowerCase());
|
|
76
|
-
return brotliCompress(buffer, quality).byteLength;
|
|
81
|
+
return Math.min(bytes.byteLength, brotliCompress(buffer, quality).byteLength);
|
|
77
82
|
}
|
|
78
83
|
|
|
79
84
|
export function chunkBrotliBytesOf(bytes: Uint8Array): number {
|
|
80
85
|
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
|
|
81
|
-
return bytes.byteLength
|
|
82
|
-
? bytes.byteLength
|
|
83
|
-
: brotliCompress(buffer, brotliQualityOf(".js")).byteLength;
|
|
86
|
+
return Math.min(bytes.byteLength, brotliCompress(buffer, brotliQualityOf(".js")).byteLength);
|
|
84
87
|
}
|
|
85
88
|
|
|
86
89
|
function brotliQualityOf(ext: string): number {
|
|
87
90
|
return BROTLI_QUALITY_BY_EXT[ext as keyof typeof BROTLI_QUALITY_BY_EXT] ?? DEFAULT_BROTLI_QUALITY;
|
|
88
91
|
}
|
|
89
92
|
|
|
93
|
+
export function dictionaryBrotliBytesOf(source: string): number {
|
|
94
|
+
const bytes = new TextEncoder().encode(source);
|
|
95
|
+
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
|
|
96
|
+
return brotliCompress(buffer, ROOT_BROTLI_QUALITY.dict ?? MAX_BROTLI_QUALITY).byteLength;
|
|
97
|
+
}
|
|
98
|
+
|
|
90
99
|
function brotliCompress(buffer: ArrayBuffer, quality: number): Buffer {
|
|
91
100
|
return zlib.brotliCompressSync(buffer, {
|
|
92
101
|
params: {
|
|
@@ -99,7 +108,5 @@ function brotliCompress(buffer: ArrayBuffer, quality: number): Buffer {
|
|
|
99
108
|
async function shouldPrecompress(filePath: string): Promise<boolean> {
|
|
100
109
|
if (filePath.endsWith(".gz") || filePath.endsWith(".br")) return false;
|
|
101
110
|
if (!COMPRESSIBLE_EXTS.has(path.extname(filePath).toLowerCase())) return false;
|
|
102
|
-
|
|
103
|
-
if (!(await file.exists())) return false;
|
|
104
|
-
return file.size >= MIN_COMPRESS_BYTES;
|
|
111
|
+
return Bun.file(filePath).exists();
|
|
105
112
|
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import type { ExportReach, ReachedImport } from "../transforms/exportReach";
|
|
3
|
+
import type { DiscoverOptions, ScannedImport } from "./clientBuildTypes";
|
|
4
|
+
|
|
5
|
+
export interface RenderedFile {
|
|
6
|
+
isClientEntry: boolean;
|
|
7
|
+
imports: ScannedImport[];
|
|
8
|
+
/** Null for a module whose exports cannot be read. */
|
|
9
|
+
reach?: ExportReach | null;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface RenderedGraph {
|
|
13
|
+
fileOf(file: string): Promise<RenderedFile | null>;
|
|
14
|
+
resolve(specifier: string, fromDir: string): Promise<string | null>;
|
|
15
|
+
/** Bumped when a file changed: an answer computed across a bump is not kept. */
|
|
16
|
+
epoch(): number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
interface ExportAsk {
|
|
20
|
+
file: string;
|
|
21
|
+
name: string;
|
|
22
|
+
how: "whole" | "always" | "named" | "starred";
|
|
23
|
+
key: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface AskAnswer {
|
|
27
|
+
isEntry: boolean;
|
|
28
|
+
whole: boolean;
|
|
29
|
+
next: ExportAsk[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
type ImportsAs = NonNullable<DiscoverOptions["importsAs"]>;
|
|
33
|
+
|
|
34
|
+
interface RenderedWalk {
|
|
35
|
+
serverModules: string[];
|
|
36
|
+
within: string[];
|
|
37
|
+
importsAs?: ImportsAs;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The client entries a route can render. A server module asked for one export gives only what that export's
|
|
42
|
+
* declaration reaches, and every server module the route evaluates gives what its top-level statements reach.
|
|
43
|
+
*/
|
|
44
|
+
export class RenderedEntries {
|
|
45
|
+
#graph: RenderedGraph;
|
|
46
|
+
#answers = new Map<string, AskAnswer>();
|
|
47
|
+
//? Keyed by a walk's `importsAs`: an ask's answer under swapped imports holds only for walks swapping the same ones.
|
|
48
|
+
#swappedAnswers = new WeakMap<ImportsAs, Map<string, AskAnswer>>();
|
|
49
|
+
|
|
50
|
+
constructor(graph: RenderedGraph) {
|
|
51
|
+
this.#graph = graph;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
forget(): void {
|
|
55
|
+
this.#answers.clear();
|
|
56
|
+
this.#swappedAnswers = new WeakMap();
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async of(seeds: string[], options: RenderedWalk): Promise<string[]> {
|
|
60
|
+
return [...(await this.asked(seeds, options)).keys()].sort();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
//* The same entries with the export names the route's server modules ask of each: null where one asks for them all.
|
|
64
|
+
async asked(
|
|
65
|
+
seeds: string[],
|
|
66
|
+
{ serverModules, within, importsAs }: RenderedWalk,
|
|
67
|
+
): Promise<Map<string, string[] | null>> {
|
|
68
|
+
const answers = importsAs ? this.#answersUnder(importsAs) : this.#answers;
|
|
69
|
+
const reachable = new Set(within);
|
|
70
|
+
const entries = new Map<string, string[] | null>();
|
|
71
|
+
const seen = new Set<string>();
|
|
72
|
+
const whole = new Set<string>();
|
|
73
|
+
const queue = seeds.map((seed) => RenderedEntries.#ask(path.resolve(seed), "whole"));
|
|
74
|
+
for (const file of serverModules) queue.push(RenderedEntries.#ask(file, "always"));
|
|
75
|
+
for (const ask of queue) {
|
|
76
|
+
if (seen.has(ask.key) || whole.has(ask.file)) continue;
|
|
77
|
+
seen.add(ask.key);
|
|
78
|
+
const answer = answers.get(ask.key) ?? (await this.#answer(ask, answers, importsAs));
|
|
79
|
+
if (answer.isEntry) {
|
|
80
|
+
if (ask.how === "always" || !reachable.has(ask.file)) continue;
|
|
81
|
+
const names = entries.get(ask.file);
|
|
82
|
+
if (ask.how === "whole") entries.set(ask.file, null);
|
|
83
|
+
else if (names === undefined) entries.set(ask.file, [ask.name]);
|
|
84
|
+
else if (names && !names.includes(ask.name)) names.push(ask.name);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (answer.whole) whole.add(ask.file);
|
|
88
|
+
for (const next of answer.next) if (!seen.has(next.key) && !whole.has(next.file)) queue.push(next);
|
|
89
|
+
}
|
|
90
|
+
return entries;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
#answersUnder(importsAs: ImportsAs): Map<string, AskAnswer> {
|
|
94
|
+
const answers = this.#swappedAnswers.get(importsAs) ?? new Map<string, AskAnswer>();
|
|
95
|
+
this.#swappedAnswers.set(importsAs, answers);
|
|
96
|
+
return answers;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async #answer(ask: ExportAsk, answers: Map<string, AskAnswer>, importsAs?: ImportsAs): Promise<AskAnswer> {
|
|
100
|
+
const epoch = this.#graph.epoch();
|
|
101
|
+
const answer = await this.#answerOf(ask, importsAs);
|
|
102
|
+
if (epoch === this.#graph.epoch()) answers.set(ask.key, answer);
|
|
103
|
+
return answer;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async #answerOf(ask: ExportAsk, importsAs?: ImportsAs): Promise<AskAnswer> {
|
|
107
|
+
const facts = await this.#graph.fileOf(ask.file);
|
|
108
|
+
if (!facts) return { isEntry: false, whole: false, next: [] };
|
|
109
|
+
if (facts.isClientEntry) return { isEntry: true, whole: false, next: [] };
|
|
110
|
+
const reached = RenderedEntries.#reachedBy(ask, facts);
|
|
111
|
+
const swaps = importsAs?.get(ask.file);
|
|
112
|
+
const next: ExportAsk[] = [];
|
|
113
|
+
for (const { specifier, names } of reached.imports) {
|
|
114
|
+
const swapped = swaps?.get(specifier);
|
|
115
|
+
const spec = swapped === undefined ? specifier : swapped;
|
|
116
|
+
if (!spec) continue;
|
|
117
|
+
const resolved = await this.#graph.resolve(spec, path.dirname(ask.file));
|
|
118
|
+
if (!resolved) continue;
|
|
119
|
+
const file = path.resolve(resolved);
|
|
120
|
+
if (names === null) next.push(RenderedEntries.#ask(file, "whole"));
|
|
121
|
+
else for (const name of names) next.push(RenderedEntries.#ask(file, reached.starred ? "starred" : "named", name));
|
|
122
|
+
}
|
|
123
|
+
return { isEntry: false, whole: reached.whole ?? false, next };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
//? A name asked through `export *` that the target does not hold is another target's, so it reaches nothing here.
|
|
127
|
+
static #reachedBy(
|
|
128
|
+
{ name, how }: ExportAsk,
|
|
129
|
+
{ reach, imports }: RenderedFile,
|
|
130
|
+
): { imports: ReachedImport[]; whole?: boolean; starred?: boolean } {
|
|
131
|
+
if (!reach) return { imports: imports.map((imported) => ({ specifier: imported.path, names: null })), whole: true };
|
|
132
|
+
if (how === "whole") return { imports: reach.whole(), whole: true };
|
|
133
|
+
if (how === "always") return { imports: reach.always() };
|
|
134
|
+
const reached = reach.of(name);
|
|
135
|
+
if (reached.known) return { imports: reached.imports };
|
|
136
|
+
if (reached.stars.length > 0)
|
|
137
|
+
return { imports: reached.stars.map((specifier) => ({ specifier, names: [name] })), starred: true };
|
|
138
|
+
return how === "starred" ? { imports: [] } : { imports: reach.whole(), whole: true };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
static #ask(file: string, how: ExportAsk["how"], name = ""): ExportAsk {
|
|
142
|
+
return { file, name, how, key: `${file}\0${how}\0${name}` };
|
|
143
|
+
}
|
|
144
|
+
}
|