@akanjs/devkit 3.3.0-rc.25 → 3.3.0-rc.26
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 +294 -0
- package/akanApp/akanApp.host.ts +11 -0
- package/akanConfig/akanBin.ts +4 -0
- package/akanConfig/akanConfig.test.ts +11 -0
- package/akanConfig/akanConfig.ts +39 -137
- package/akanConfig/akanWorkers.test.ts +39 -0
- package/akanConfig/akanWorkers.ts +32 -0
- package/akanConfig/desktopServerConfig.ts +96 -0
- package/akanConfig/dockerImage.ts +20 -0
- package/akanConfig/types.ts +1 -0
- package/app/appBin.test.ts +63 -0
- package/app/appBin.ts +50 -0
- package/app/applicationBuildReporter.test.ts +32 -0
- package/app/applicationBuildReporter.ts +4 -0
- package/app/applicationBuildRunner.test.ts +3 -0
- package/app/applicationBuildRunner.ts +40 -4
- package/app/dictionarySizes.ts +94 -0
- package/artifact/implicitRootLayout.test.ts +19 -0
- package/artifact/implicitRootLayout.ts +16 -2
- package/artifact/storeBootstrap.test.ts +28 -0
- package/artifact/storeBootstrap.ts +60 -8
- package/biome.base.json +5 -1
- package/codeAgent/skills/akan-agent/SKILL.md +2 -2
- package/codeAgent/skills/akan-deps/SKILL.md +3 -2
- package/codeAgent/skills/akan-err/SKILL.md +2 -6
- package/codeAgent/skills/akan-mcp/SKILL.md +1 -1
- package/codeAgent/skills/akan-module/SKILL.md +2 -2
- package/codeAgent/skills/akan-query/SKILL.md +13 -20
- package/codeAgent/skills/akan-service/SKILL.md +2 -5
- package/codeAgent/skills/akan-transport/SKILL.md +5 -14
- package/codeAgent/skills/akan-ui/SKILL.md +2 -5
- package/context/akanContext.ts +2 -0
- package/executors/clientRuntimeKeyOrder.fixture.json +682 -0
- package/executors/clientRuntimeKeys.fixture.json +393 -0
- package/executors/clientRuntimeKeys.test.ts +1591 -0
- package/executors/executors.test.ts +2 -0
- package/executors/sysExecutor.ts +66 -3
- package/frontendBuild/allRoutesBuilder.ts +72 -3
- package/frontendBuild/autoImportSync.ts +3 -2
- package/frontendBuild/buildRouteClient.test.ts +513 -5
- package/frontendBuild/clientBuildTypes.ts +15 -0
- package/frontendBuild/clientEntriesBundler.ts +38 -0
- package/frontendBuild/clientEntryDiscovery.test.ts +60 -1
- package/frontendBuild/clientEntryDiscovery.ts +72 -4
- package/frontendBuild/csrDevModuleCompiler.test.ts +86 -0
- package/frontendBuild/csrDevModuleCompiler.ts +44 -8
- package/frontendBuild/csrDevPatcher.ts +33 -7
- package/frontendBuild/csrDevTypes.ts +9 -0
- package/frontendBuild/devBarrelImports.test.ts +70 -0
- package/frontendBuild/devBarrelImports.ts +80 -21
- package/frontendBuild/devRegistryBundler.ts +4 -2
- package/frontendBuild/devRouteRuntime.test.ts +492 -0
- package/frontendBuild/devRouteRuntime.ts +167 -0
- package/frontendBuild/dictionaryAssetBuilder.test.ts +316 -0
- package/frontendBuild/dictionaryAssetBuilder.ts +152 -16
- package/frontendBuild/dictionaryConstants.ts +82 -0
- package/frontendBuild/dictionaryPacking.test.ts +84 -0
- package/frontendBuild/dictionaryPacking.ts +92 -0
- package/frontendBuild/dictionaryRoutes.test.ts +186 -0
- package/frontendBuild/dictionaryRoutes.ts +225 -0
- package/frontendBuild/pagesBundleBuilder.test.ts +84 -0
- package/frontendBuild/pagesBundleBuilder.ts +78 -2
- package/frontendBuild/precompressArtifacts.ts +7 -0
- package/frontendBuild/registryMetadataFingerprint.ts +3 -3
- package/frontendBuild/routeClientBuilder.ts +288 -15
- package/frontendBuild/routeHandoffs.test.ts +119 -0
- package/frontendBuild/routeHandoffs.ts +94 -0
- package/frontendBuild/routeRuntimeCheck.test.ts +257 -0
- package/frontendBuild/routeRuntimeCheck.ts +241 -0
- package/frontendBuild/routeRuntimePays.test.ts +137 -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/incrementalBuilder.proc.test.ts +79 -0
- package/incrementalBuilder/incrementalBuilder.proc.ts +20 -1
- package/mobile/desktopBin.ts +2 -2
- package/mobile/desktopServerStage.ts +1 -0
- package/package.json +4 -3
- package/quality/dictionaryKeys.test.ts +173 -0
- package/quality/dictionaryKeys.ts +415 -0
- package/quality/objectImportReport.test.ts +36 -0
- package/quality/objectImportReport.ts +102 -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/test/testHelpers.ts +11 -0
- package/transforms/barrelAnalyzer.ts +17 -1
- package/transforms/barrelImportsPlugin.ts +81 -13
- 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/objectImportEdits.ts +150 -0
- package/transforms/objectMemberImports.test.ts +347 -0
- package/transforms/objectMemberImports.ts +537 -0
- package/transforms/objectModule.test.ts +237 -0
- package/transforms/objectModule.ts +458 -0
- package/transforms/objectModuleAnalyzer.ts +104 -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/signalDescriptors.test.ts +280 -0
- package/transforms/signalDescriptors.ts +227 -0
- package/transforms/thisFreeExports.ts +87 -0
- package/transforms/transforms.test.ts +139 -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/scanInfo.ts +1 -1
- package/workspace/workspaceLayout.ts +1 -0
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { RuntimeImports } from "../quality/runtimeImports";
|
|
3
|
+
import { type ConstantRewrite, RouteConstants } from "./routeConstants";
|
|
4
|
+
|
|
5
|
+
export interface RouteRuntimeTextEdit {
|
|
6
|
+
start: number;
|
|
7
|
+
end: number;
|
|
8
|
+
text: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const handleNames = new Set(["fetch", "sig", "st"]);
|
|
12
|
+
//? The tab's one store: a scope's `lib/st.ts` exports this same object, and a key answers once its module has loaded.
|
|
13
|
+
const tabStore = '"akanjs/store"';
|
|
14
|
+
|
|
15
|
+
export class RouteRuntimeEdits {
|
|
16
|
+
//? `handlesOnly`: in a file whose names cannot be told, an import is repointed only where it takes nothing but handles.
|
|
17
|
+
static importEdit(
|
|
18
|
+
statement: ts.Statement,
|
|
19
|
+
sourceFile: ts.SourceFile,
|
|
20
|
+
fileName: string,
|
|
21
|
+
{ handlesOnly = false, constants = null }: { handlesOnly?: boolean; constants?: ConstantRewrite | null } = {},
|
|
22
|
+
): RouteRuntimeTextEdit[] {
|
|
23
|
+
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) return [];
|
|
24
|
+
const clause = statement.importClause;
|
|
25
|
+
const target = RuntimeImports.targetOf(statement.moduleSpecifier.text, fileName);
|
|
26
|
+
if (!target?.scope || !clause || clause.isTypeOnly) return [];
|
|
27
|
+
const pageRuntime = JSON.stringify(`@${target.scope}/lib/usePage`);
|
|
28
|
+
const specifier = statement.moduleSpecifier;
|
|
29
|
+
const named = !clause.name && clause.namedBindings && ts.isNamedImports(clause.namedBindings);
|
|
30
|
+
const onlyStore =
|
|
31
|
+
named &&
|
|
32
|
+
(clause.namedBindings as ts.NamedImports).elements.every(
|
|
33
|
+
(element) => element.isTypeOnly || (element.propertyName ?? element.name).text === "st",
|
|
34
|
+
);
|
|
35
|
+
if (handlesOnly && ((target.kind === "st" && !onlyStore) || (target.kind === "useClient" && !named))) return [];
|
|
36
|
+
if (target.kind === "useClient" || target.kind === "st")
|
|
37
|
+
return [
|
|
38
|
+
{
|
|
39
|
+
start: specifier.getStart(sourceFile),
|
|
40
|
+
end: specifier.end,
|
|
41
|
+
text: target.kind === "st" ? tabStore : pageRuntime,
|
|
42
|
+
},
|
|
43
|
+
];
|
|
44
|
+
if (target.kind !== "client" || clause.name || !clause.namedBindings || !ts.isNamedImports(clause.namedBindings))
|
|
45
|
+
return [];
|
|
46
|
+
const { elements } = clause.namedBindings;
|
|
47
|
+
const handleOf = (element: ts.ImportSpecifier) =>
|
|
48
|
+
element.isTypeOnly ? "" : (element.propertyName ?? element.name).text;
|
|
49
|
+
const isHandle = (element: ts.ImportSpecifier) => handleNames.has(handleOf(element));
|
|
50
|
+
const [handles, rest] = [elements.filter(isHandle), elements.filter((element) => !isHandle(element))];
|
|
51
|
+
const typedCnst = (element: ts.ImportSpecifier) => !!constants && handleOf(element) === "cnst";
|
|
52
|
+
if (!handles.length)
|
|
53
|
+
return constants ? RouteConstants.typedEdits(statement, sourceFile, (imported) => imported === "cnst") : [];
|
|
54
|
+
const namesOf = (list: ts.ImportSpecifier[]) => list.map((element) => element.getText(sourceFile)).join(", ");
|
|
55
|
+
const typesOnly = rest.every((element) => element.isTypeOnly || typedCnst(element));
|
|
56
|
+
const restNames = typesOnly
|
|
57
|
+
? rest.map((element) => element.getText(sourceFile).replace(/^type\s+/, "")).join(", ")
|
|
58
|
+
: rest.map((element) => `${typedCnst(element) ? "type " : ""}${element.getText(sourceFile)}`).join(", ");
|
|
59
|
+
const [stores, descriptors] = [
|
|
60
|
+
handles.filter((element) => handleOf(element) === "st"),
|
|
61
|
+
handles.filter((element) => handleOf(element) !== "st"),
|
|
62
|
+
];
|
|
63
|
+
const lines = [
|
|
64
|
+
...(descriptors.length ? [`import { ${namesOf(descriptors)} } from ${pageRuntime};`] : []),
|
|
65
|
+
...(stores.length ? [`import { ${namesOf(stores)} } from ${tabStore};`] : []),
|
|
66
|
+
...(rest.length
|
|
67
|
+
? [`import ${typesOnly ? "type " : ""}{ ${restNames} } from ${specifier.getText(sourceFile)};`]
|
|
68
|
+
: []),
|
|
69
|
+
];
|
|
70
|
+
const [start, end] = [statement.getStart(sourceFile), statement.end];
|
|
71
|
+
const newlines = sourceFile.text.slice(start, end).split("\n").length - 1;
|
|
72
|
+
return [{ start, end, text: `${lines.join(" ")}${"\n".repeat(newlines)}` }];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
//? After the directives, on the first statement's own line: `"use client"` stays first and no line moves.
|
|
76
|
+
static leading(sourceFile: ts.SourceFile, imports: string[]): RouteRuntimeTextEdit {
|
|
77
|
+
const first = sourceFile.statements.find(
|
|
78
|
+
(statement) => !ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression),
|
|
79
|
+
);
|
|
80
|
+
const at = first ? first.getStart(sourceFile) : sourceFile.text.length;
|
|
81
|
+
return { start: at, end: at, text: `${imports.join(" ")} ` };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
static apply(source: string, edits: RouteRuntimeTextEdit[]) {
|
|
85
|
+
return [...edits]
|
|
86
|
+
.sort((a, b) => b.start - a.start || b.end - a.end)
|
|
87
|
+
.reduce(
|
|
88
|
+
(text, { start, end, text: replacement }) => text.slice(0, start) + replacement + text.slice(end),
|
|
89
|
+
source,
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
export interface RouteRuntimeImport {
|
|
2
|
+
path: string;
|
|
3
|
+
lazy: boolean;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export interface RouteRuntimeBundle {
|
|
7
|
+
//? Absolute paths, from a bundle of the same entries in which every entry loads the whole runtime.
|
|
8
|
+
importsByModule: ReadonlyMap<string, readonly RouteRuntimeImport[]>;
|
|
9
|
+
entries: readonly string[];
|
|
10
|
+
//? The entries each route renders first; where they are told, an entry of no route keeps the whole runtime.
|
|
11
|
+
entriesByRoute?: ReadonlyMap<string, readonly string[]>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
//* The import graph the per-route runtime is planned over: what one module reaches without passing a runtime file,
|
|
15
|
+
//* whose own imports differ between a page loading the whole runtime and a page loading pieces.
|
|
16
|
+
export class RouteRuntimeGraph {
|
|
17
|
+
readonly #imports: ReadonlyMap<string, readonly RouteRuntimeImport[]>;
|
|
18
|
+
readonly #isRuntimeFile: (absPath: string) => boolean;
|
|
19
|
+
|
|
20
|
+
constructor(
|
|
21
|
+
imports: ReadonlyMap<string, readonly RouteRuntimeImport[]>,
|
|
22
|
+
isRuntimeFile: (absPath: string) => boolean,
|
|
23
|
+
) {
|
|
24
|
+
this.#imports = imports;
|
|
25
|
+
this.#isRuntimeFile = isRuntimeFile;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
get modules(): string[] {
|
|
29
|
+
return [...this.#imports.keys()];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
has(absPath: string) {
|
|
33
|
+
return this.#imports.has(absPath);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
importsOf(absPath: string): string[] {
|
|
37
|
+
return (this.#imports.get(absPath) ?? []).filter(({ lazy }) => !lazy).map(({ path }) => path);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
lazyImportsOf(absPath: string): string[] {
|
|
41
|
+
return (this.#imports.get(absPath) ?? [])
|
|
42
|
+
.filter(({ path, lazy }) => lazy && !this.#isRuntimeFile(path))
|
|
43
|
+
.map(({ path }) => path);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
//? A module asked for by `import()` loads when that call runs, so it is planned as an entry of its own.
|
|
47
|
+
get lazyRoots(): string[] {
|
|
48
|
+
return [...new Set(this.modules.flatMap((module) => this.lazyImportsOf(module)))];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
closureOf(roots: Iterable<string>, into = new Set<string>()): Set<string> {
|
|
52
|
+
const queue: string[] = [];
|
|
53
|
+
for (const root of roots)
|
|
54
|
+
if (!into.has(root) && !this.#isRuntimeFile(root)) {
|
|
55
|
+
into.add(root);
|
|
56
|
+
queue.push(root);
|
|
57
|
+
}
|
|
58
|
+
for (const module of queue)
|
|
59
|
+
for (const imported of this.importsOf(module)) {
|
|
60
|
+
if (into.has(imported) || this.#isRuntimeFile(imported)) continue;
|
|
61
|
+
into.add(imported);
|
|
62
|
+
queue.push(imported);
|
|
63
|
+
}
|
|
64
|
+
return into;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import type { RouteRuntimeGraph } from "./routeRuntimeGraph";
|
|
2
|
+
|
|
3
|
+
//? `file` is the one an author can change, as a workspace path, or a path under `akanjs/` for a framework component.
|
|
4
|
+
export interface RouteRuntimeWhy {
|
|
5
|
+
file: string;
|
|
6
|
+
line?: number;
|
|
7
|
+
message: string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export type RouteRuntimeKeep =
|
|
11
|
+
| ({ rule: "reader"; path: string } & RouteRuntimeWhy)
|
|
12
|
+
| { rule: "store-side"; file: string; message: string }
|
|
13
|
+
| { rule: "lazy"; file: string; asks: string }
|
|
14
|
+
| { rule: "majority"; whole: number; others: number }
|
|
15
|
+
| { rule: "asked" }
|
|
16
|
+
| { rule: "unheld" }
|
|
17
|
+
| { rule: "not-smaller"; route: string; whole: number; perModule: number }
|
|
18
|
+
//? The build every page is measured against, in which every root keeps the whole runtime.
|
|
19
|
+
| { rule: "reference" };
|
|
20
|
+
|
|
21
|
+
export interface RouteRuntimeCause {
|
|
22
|
+
rule: RouteRuntimeKeep["rule"];
|
|
23
|
+
file?: string;
|
|
24
|
+
line?: number;
|
|
25
|
+
message: string;
|
|
26
|
+
entries: string[];
|
|
27
|
+
routes: string[];
|
|
28
|
+
//? For a file a root reaches: the imports from a root down to it, one chain per file importing it.
|
|
29
|
+
chains: string[][];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const ruleMessages = {
|
|
33
|
+
majority:
|
|
34
|
+
"more pages keeping the whole runtime hold it than pages loading per module, whose pieces those pages would carry on top",
|
|
35
|
+
asked: "only files keeping the whole runtime ask for it with import()",
|
|
36
|
+
unheld: "no page loading per module holds it",
|
|
37
|
+
reference: "the build measured every page with the whole runtime",
|
|
38
|
+
} as const;
|
|
39
|
+
|
|
40
|
+
export interface RouteRuntimePlanInput {
|
|
41
|
+
graph: RouteRuntimeGraph;
|
|
42
|
+
entries: ReadonlySet<string>;
|
|
43
|
+
//? Null where no route was told: an entry of no route is then narrowed like any other.
|
|
44
|
+
routes: ReadonlyMap<string, readonly string[]> | null;
|
|
45
|
+
//? Why the file needs every module, or null where it loads only the modules it names.
|
|
46
|
+
readsWhole: (file: string) => RouteRuntimeWhy | null;
|
|
47
|
+
//? Why an entry a store file imports cannot be narrowed, or null.
|
|
48
|
+
storeSide: (root: string) => string | null;
|
|
49
|
+
bringsPieces: (file: string) => boolean;
|
|
50
|
+
nameOf: (file: string) => string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
//* Which roots of a build loading per module keep the whole runtime, each with the reason it does. A root is only
|
|
54
|
+
//* ever added: every rule keeps more as others keep more, so replaying them after a new keep ends and cannot undo one.
|
|
55
|
+
export class RouteRuntimePlan {
|
|
56
|
+
static readonly chainsShown = 3;
|
|
57
|
+
readonly keeps = new Map<string, RouteRuntimeKeep>();
|
|
58
|
+
readonly roots: string[];
|
|
59
|
+
readonly #input: RouteRuntimePlanInput;
|
|
60
|
+
readonly #closures: Map<string, Set<string>>;
|
|
61
|
+
readonly #lazyOf: Map<string, string[]>;
|
|
62
|
+
|
|
63
|
+
constructor(input: RouteRuntimePlanInput) {
|
|
64
|
+
this.#input = input;
|
|
65
|
+
const { graph, entries } = input;
|
|
66
|
+
this.roots = [...new Set([...entries, ...graph.lazyRoots])];
|
|
67
|
+
this.#closures = new Map(this.roots.map((root) => [root, graph.closureOf([root])]));
|
|
68
|
+
this.#lazyOf = new Map(
|
|
69
|
+
this.roots.map((root) => [root, [...this.closureOf(root)].flatMap((file) => graph.lazyImportsOf(file))]),
|
|
70
|
+
);
|
|
71
|
+
this.#keepReaders();
|
|
72
|
+
this.#keepAskers();
|
|
73
|
+
this.#keepMajority(true);
|
|
74
|
+
this.#settle();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
get routes(): ReadonlyMap<string, readonly string[]> {
|
|
78
|
+
return this.#input.routes ?? new Map();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
get told() {
|
|
82
|
+
return this.#input.routes !== null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
closureOf(root: string): Set<string> {
|
|
86
|
+
return this.#closures.get(root) ?? new Set();
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
isWhole(route: readonly string[]) {
|
|
90
|
+
return route.some((entry) => this.keeps.has(entry));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
chainTo(root: string, target: string): string[] {
|
|
94
|
+
const { graph } = this.#input;
|
|
95
|
+
const parents = new Map<string, string | null>([[root, null]]);
|
|
96
|
+
for (const file of parents.keys()) {
|
|
97
|
+
if (file === target) break;
|
|
98
|
+
for (const imported of graph.importsOf(file)) if (!parents.has(imported)) parents.set(imported, file);
|
|
99
|
+
}
|
|
100
|
+
const chain: string[] = [];
|
|
101
|
+
for (let file: string | null = parents.has(target) ? target : null; file; file = parents.get(file) ?? null)
|
|
102
|
+
chain.unshift(file);
|
|
103
|
+
return chain;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
causes(): RouteRuntimeCause[] {
|
|
107
|
+
const { nameOf } = this.#input;
|
|
108
|
+
const causes = new Map<string, RouteRuntimeCause>();
|
|
109
|
+
const tails = new Map<string, Set<string>>();
|
|
110
|
+
for (const [root, keep] of this.keeps) {
|
|
111
|
+
const said =
|
|
112
|
+
keep.rule === "reader" || keep.rule === "store-side"
|
|
113
|
+
? { file: keep.file, ...("line" in keep && keep.line ? { line: keep.line } : {}), message: keep.message }
|
|
114
|
+
: keep.rule === "lazy"
|
|
115
|
+
? { message: `asks with import() for ${keep.asks}, which keeps the whole runtime` }
|
|
116
|
+
: keep.rule === "not-smaller"
|
|
117
|
+
? {
|
|
118
|
+
message: `${keep.route} is ${keep.perModule} B loading per module and ${keep.whole} B with the whole runtime`,
|
|
119
|
+
}
|
|
120
|
+
: { message: ruleMessages[keep.rule] };
|
|
121
|
+
const key = JSON.stringify([keep.rule, said]);
|
|
122
|
+
const cause = causes.get(key) ?? { rule: keep.rule, ...said, entries: [], routes: [], chains: [] };
|
|
123
|
+
causes.set(key, cause);
|
|
124
|
+
cause.entries.push(nameOf(root));
|
|
125
|
+
for (const [route, entries] of this.routes)
|
|
126
|
+
if (entries.includes(root) && !cause.routes.includes(route)) cause.routes.push(route);
|
|
127
|
+
if (keep.rule !== "reader") continue;
|
|
128
|
+
const chain = this.chainTo(root, keep.path).map(nameOf);
|
|
129
|
+
const seen = tails.get(key) ?? new Set<string>();
|
|
130
|
+
tails.set(key, seen);
|
|
131
|
+
const tail = chain.slice(-2).join(" ");
|
|
132
|
+
if (!seen.has(tail) && seen.size < RouteRuntimePlan.chainsShown) cause.chains.push(chain);
|
|
133
|
+
seen.add(tail);
|
|
134
|
+
}
|
|
135
|
+
return [...causes.values()].sort(
|
|
136
|
+
(a, b) => b.routes.length - a.routes.length || b.entries.length - a.entries.length,
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
keep(roots: Iterable<string>, why: RouteRuntimeKeep) {
|
|
141
|
+
for (const root of roots) if (!this.keeps.has(root)) this.keeps.set(root, why);
|
|
142
|
+
this.#settle();
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
#settle() {
|
|
146
|
+
for (let size = -1; size !== this.keeps.size; ) {
|
|
147
|
+
size = this.keeps.size;
|
|
148
|
+
this.#keepAskers();
|
|
149
|
+
this.#keepMajority(false);
|
|
150
|
+
this.#keepAsked();
|
|
151
|
+
this.#keepUnheld();
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
#keepReaders() {
|
|
156
|
+
const { readsWhole, storeSide, nameOf } = this.#input;
|
|
157
|
+
for (const root of this.roots) {
|
|
158
|
+
//? Nothing imports an entry, so no importer loads the stores a store-side entry's code names.
|
|
159
|
+
const side = storeSide(root);
|
|
160
|
+
if (side) {
|
|
161
|
+
this.keeps.set(root, { rule: "store-side", file: nameOf(root), message: side });
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
for (const file of this.closureOf(root)) {
|
|
165
|
+
const why = readsWhole(file);
|
|
166
|
+
if (!why) continue;
|
|
167
|
+
this.keeps.set(root, { rule: "reader", path: file, ...why });
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
//? A module asked for by `import()` gets no entry of its own to load the whole runtime first, so its asker does.
|
|
174
|
+
#keepAskers() {
|
|
175
|
+
const { nameOf } = this.#input;
|
|
176
|
+
for (let more = this.roots; more.length > 0; ) {
|
|
177
|
+
more = this.roots.filter(
|
|
178
|
+
(root) => !this.keeps.has(root) && this.#lazyOf.get(root)?.some((lazy) => this.keeps.has(lazy)),
|
|
179
|
+
);
|
|
180
|
+
for (const root of more) {
|
|
181
|
+
const asks = this.#lazyOf.get(root)?.find((lazy) => this.keeps.has(lazy)) ?? root;
|
|
182
|
+
this.keeps.set(root, { rule: "lazy", file: nameOf(root), asks: nameOf(asks) });
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
//? A narrowed entry's pieces repeat what a whole-runtime page already carries; pages a kept entry makes whole recount.
|
|
188
|
+
//? `guessing` also keeps an entry more whole pages hold than others: once a build has measured its pages, only the
|
|
189
|
+
//? entry no other page holds follows, since a guess there would take the whole runtime to a page measured smaller.
|
|
190
|
+
#keepMajority(guessing: boolean) {
|
|
191
|
+
const { bringsPieces } = this.#input;
|
|
192
|
+
const routes = [...this.routes.values()];
|
|
193
|
+
const brings = new Map<string, boolean>();
|
|
194
|
+
const bringsOf = (root: string) => {
|
|
195
|
+
const known = brings.get(root);
|
|
196
|
+
if (known !== undefined) return known;
|
|
197
|
+
const answer = [...this.closureOf(root)].some(bringsPieces);
|
|
198
|
+
brings.set(root, answer);
|
|
199
|
+
return answer;
|
|
200
|
+
};
|
|
201
|
+
for (let more = this.roots; more.length > 0; ) {
|
|
202
|
+
const count = (held: boolean) => {
|
|
203
|
+
const counts = new Map<string, number>();
|
|
204
|
+
for (const route of routes)
|
|
205
|
+
if (this.isWhole(route) === held) for (const entry of route) counts.set(entry, (counts.get(entry) ?? 0) + 1);
|
|
206
|
+
return counts;
|
|
207
|
+
};
|
|
208
|
+
const [inWhole, inOther] = [count(true), count(false)];
|
|
209
|
+
more = this.roots.filter((root) => {
|
|
210
|
+
const [holding, others] = [inWhole.get(root) ?? 0, inOther.get(root) ?? 0];
|
|
211
|
+
return !this.keeps.has(root) && holding > others && (others === 0 || (guessing && bringsOf(root)));
|
|
212
|
+
});
|
|
213
|
+
for (const root of more)
|
|
214
|
+
this.keeps.set(root, { rule: "majority", whole: inWhole.get(root) ?? 0, others: inOther.get(root) ?? 0 });
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
#keepAsked() {
|
|
219
|
+
const { entries } = this.#input;
|
|
220
|
+
const askers = new Map<string, string[]>();
|
|
221
|
+
for (const [root, lazies] of this.#lazyOf)
|
|
222
|
+
for (const lazy of lazies) askers.set(lazy, [...(askers.get(lazy) ?? []), root]);
|
|
223
|
+
for (let more = [...askers]; more.length > 0; ) {
|
|
224
|
+
more = [...askers].filter(
|
|
225
|
+
([lazy, askedBy]) =>
|
|
226
|
+
!this.keeps.has(lazy) && !entries.has(lazy) && askedBy.every((root) => this.keeps.has(root)),
|
|
227
|
+
);
|
|
228
|
+
for (const [lazy] of more) this.keeps.set(lazy, { rule: "asked" });
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
//? A root no page loading pieces holds or asks for would be narrowed for no page: the files it shares with a whole
|
|
233
|
+
//? page would then load pieces of what that page's whole runtime already holds. With no whole page there is none to
|
|
234
|
+
//? carry both, and a root keeping the whole runtime would split every page's chunks from the stores it reaches.
|
|
235
|
+
#keepUnheld() {
|
|
236
|
+
const routes = [...this.routes.values()];
|
|
237
|
+
if (!this.told || !routes.some((route) => this.isWhole(route))) return;
|
|
238
|
+
const live = new Set<string>();
|
|
239
|
+
for (const route of routes) if (!this.isWhole(route)) for (const entry of route) live.add(entry);
|
|
240
|
+
for (const root of live) for (const lazy of this.#lazyOf.get(root) ?? []) if (!this.keeps.has(lazy)) live.add(lazy);
|
|
241
|
+
for (const root of this.roots)
|
|
242
|
+
if (!this.keeps.has(root) && !live.has(root)) this.keeps.set(root, { rule: "unheld" });
|
|
243
|
+
}
|
|
244
|
+
}
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { realpath } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { tempDirs, writeText } from "../test/testHelpers";
|
|
5
|
+
import { SignalDescriptors } from "./signalDescriptors";
|
|
6
|
+
|
|
7
|
+
const makeTempRoot = tempDirs("akan-devkit-signal-descriptors-");
|
|
8
|
+
|
|
9
|
+
const sigSource = `import { appendFileSync } from "node:fs";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
|
|
12
|
+
appendFileSync(path.join(import.meta.dir, "reads.txt"), "read\\n");
|
|
13
|
+
const serialized = {
|
|
14
|
+
trolley: { endpoint: { pingAt: { type: "query", args: [], returns: { refName: "String" } } } },
|
|
15
|
+
crate: { endpoint: { countOf: { type: "query", args: [], returns: { refName: "Int", nullable: true } } } },
|
|
16
|
+
odd: { endpoint: { at: { type: "query", args: [], returns: { refName: "String", nullable: undefined } } } },
|
|
17
|
+
};
|
|
18
|
+
export const fetch = { ownSerializedSignal: serialized };
|
|
19
|
+
export const getSerializedSignalOf = (name) => (name === "base" ? {} : { [name]: serialized[name] });
|
|
20
|
+
`;
|
|
21
|
+
|
|
22
|
+
const pieceOf = (name: string) => `import { FetchClient } from "akanjs/fetch";
|
|
23
|
+
import * as cnst from "../cnst";
|
|
24
|
+
import { fetch, sig } from "../usePage";
|
|
25
|
+
import { getSerializedSignalOf } from "../sig" with { type: "macro" };
|
|
26
|
+
import type * as signal from "../sig";
|
|
27
|
+
Object.assign(sig, FetchClient.build<typeof signal>(cnst, getSerializedSignalOf("${name}"), { base: fetch }).sig);
|
|
28
|
+
`;
|
|
29
|
+
|
|
30
|
+
const writeScope = async (sig = sigSource) => {
|
|
31
|
+
const root = await realpath(await makeTempRoot());
|
|
32
|
+
await writeText(path.join(root, "apps/shop/lib/sig.ts"), sig);
|
|
33
|
+
const pieceDir = path.join(root, "apps/shop/lib/__client");
|
|
34
|
+
return {
|
|
35
|
+
root,
|
|
36
|
+
pieceDir,
|
|
37
|
+
readsOf: () =>
|
|
38
|
+
Bun.file(path.join(root, "apps/shop/lib/reads.txt"))
|
|
39
|
+
.text()
|
|
40
|
+
.catch(() => ""),
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const writeHangingScope = async () => {
|
|
45
|
+
const scope = await writeScope();
|
|
46
|
+
const pidFile = path.join(scope.root, "reader.pid");
|
|
47
|
+
await writeText(
|
|
48
|
+
path.join(scope.root, "apps/shop/lib/sig.ts"),
|
|
49
|
+
`await Bun.write(${JSON.stringify(pidFile)}, String(process.pid));\nsetInterval(() => undefined, 1_000);\nawait new Promise(() => undefined);\n${sigSource}`,
|
|
50
|
+
);
|
|
51
|
+
return { ...scope, pidFile };
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const alive = (pid: number) => {
|
|
55
|
+
try {
|
|
56
|
+
process.kill(pid, 0);
|
|
57
|
+
return true;
|
|
58
|
+
} catch {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const goneWithin = async (pid: number, ms: number) => {
|
|
64
|
+
for (const started = Date.now(); Date.now() - started < ms; await Bun.sleep(50)) if (!alive(pid)) return true;
|
|
65
|
+
return !alive(pid);
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
describe("SignalDescriptors", () => {
|
|
69
|
+
test("answers each piece with its own descriptors as a literal in place of the macro, reading the signal once", async () => {
|
|
70
|
+
const { root, pieceDir, readsOf } = await writeScope();
|
|
71
|
+
const descriptors = new SignalDescriptors(root, ["apps/shop"]);
|
|
72
|
+
const [trolley, crate, base] = await Promise.all(
|
|
73
|
+
["trolley", "crate", "base"].map((name) =>
|
|
74
|
+
descriptors.inline(pieceOf(name), path.join(pieceDir, `${name === "base" ? "_base" : name}.fetch.ts`)),
|
|
75
|
+
),
|
|
76
|
+
);
|
|
77
|
+
|
|
78
|
+
expect(trolley).toBe(
|
|
79
|
+
pieceOf("trolley")
|
|
80
|
+
.replace('import { getSerializedSignalOf } from "../sig" with { type: "macro" };', "")
|
|
81
|
+
.replace(
|
|
82
|
+
'getSerializedSignalOf("trolley")',
|
|
83
|
+
'{"trolley":{"endpoint":{"pingAt":{"type":"query","args":[],"returns":{"refName":"String"}}}}}',
|
|
84
|
+
),
|
|
85
|
+
);
|
|
86
|
+
expect(crate).toContain('{"crate":{"endpoint":{"countOf":');
|
|
87
|
+
expect(base).toContain("FetchClient.build<typeof signal>(cnst, {}, { base: fetch })");
|
|
88
|
+
expect([trolley, crate, base].some((source) => source?.includes('with { type: "macro" }'))).toBe(false);
|
|
89
|
+
expect(await readsOf()).toBe("read\n");
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test("leaves the macro to a file it cannot answer exactly: not a piece, two calls, a name the signal lacks, or a value JSON cannot carry", async () => {
|
|
93
|
+
const { root, pieceDir } = await writeScope();
|
|
94
|
+
const descriptors = new SignalDescriptors(root, ["apps/shop"]);
|
|
95
|
+
const twoCalls = pieceOf("trolley").replace(
|
|
96
|
+
'getSerializedSignalOf("trolley")',
|
|
97
|
+
'getSerializedSignalOf("trolley"), getSerializedSignalOf("crate")',
|
|
98
|
+
);
|
|
99
|
+
|
|
100
|
+
expect(await descriptors.inline(pieceOf("trolley"), path.join(root, "apps/shop/lib/sigOf.ts"))).toBeNull();
|
|
101
|
+
expect(await descriptors.inline(twoCalls, path.join(pieceDir, "trolley.fetch.ts"))).toBeNull();
|
|
102
|
+
expect(await descriptors.inline(pieceOf("absent"), path.join(pieceDir, "absent.fetch.ts"))).toBeNull();
|
|
103
|
+
expect(await descriptors.inline(pieceOf("odd"), path.join(pieceDir, "odd.fetch.ts"))).toBeNull();
|
|
104
|
+
for (const name of ["valueOf", "__proto__", "constructor"])
|
|
105
|
+
expect(await descriptors.inline(pieceOf(name), path.join(pieceDir, `${name}.fetch.ts`))).toBeNull();
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test("says which scope's signals it could not read, leaves only their pieces to the macro and answers the rest", async () => {
|
|
109
|
+
const { root, pieceDir } = await writeScope();
|
|
110
|
+
await writeText(path.join(root, "libs/kit/lib/sig.ts"), 'throw new Error("the signal broke");\n');
|
|
111
|
+
const said: string[] = [];
|
|
112
|
+
const descriptors = new SignalDescriptors(root, ["libs/kit", "apps/shop"], {
|
|
113
|
+
onUnread: (reason) => said.push(reason),
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
expect(
|
|
117
|
+
await descriptors.inline(pieceOf("crate"), path.join(root, "libs/kit/lib/__client/crate.fetch.ts")),
|
|
118
|
+
).toBeNull();
|
|
119
|
+
expect(await descriptors.inline(pieceOf("trolley"), path.join(pieceDir, "trolley.fetch.ts"))).toContain(
|
|
120
|
+
'{"trolley":{"endpoint":',
|
|
121
|
+
);
|
|
122
|
+
expect(said).toEqual(["the signals of libs/kit could not be read (the signal broke)"]);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
test("stops a signal that does not finish loading within its time, names its scope once and leaves no process behind", async () => {
|
|
126
|
+
const { root, pieceDir, pidFile } = await writeHangingScope();
|
|
127
|
+
const said: string[] = [];
|
|
128
|
+
const descriptors = new SignalDescriptors(root, ["apps/shop"], {
|
|
129
|
+
onUnread: (reason) => said.push(reason),
|
|
130
|
+
timeoutMs: 500,
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
const inlined = await Promise.all(
|
|
134
|
+
["trolley", "crate"].map((name) => descriptors.inline(pieceOf(name), path.join(pieceDir, `${name}.fetch.ts`))),
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
expect(inlined).toEqual([null, null]);
|
|
138
|
+
expect(said).toEqual([
|
|
139
|
+
"the signals of apps/shop could not be read (they did not load within 0.5s, so the process reading them was stopped)",
|
|
140
|
+
]);
|
|
141
|
+
expect(await goneWithin(Number(await Bun.file(pidFile).text()), 3_000)).toBe(true);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
for (const ending of ["exits", "is killed"] as const)
|
|
145
|
+
test(`the process reading the signals ends when the build that started it ${ending}`, async () => {
|
|
146
|
+
const { root, pieceDir, pidFile } = await writeHangingScope();
|
|
147
|
+
const build = path.join(root, "build.ts");
|
|
148
|
+
await writeText(
|
|
149
|
+
build,
|
|
150
|
+
[
|
|
151
|
+
`import { SignalDescriptors } from ${JSON.stringify(path.join(import.meta.dir, "signalDescriptors.ts"))};`,
|
|
152
|
+
`void new SignalDescriptors(${JSON.stringify(root)}, ["apps/shop"]).inline(${JSON.stringify(pieceOf("trolley"))}, ${JSON.stringify(path.join(pieceDir, "trolley.fetch.ts"))});`,
|
|
153
|
+
`while (!(await Bun.file(${JSON.stringify(pidFile)}).exists())) await Bun.sleep(50);`,
|
|
154
|
+
ending === "exits" ? "process.exit(0);" : "",
|
|
155
|
+
"",
|
|
156
|
+
].join("\n"),
|
|
157
|
+
);
|
|
158
|
+
const parent = Bun.spawn([process.execPath, build], { cwd: root, stdout: "ignore", stderr: "ignore" });
|
|
159
|
+
try {
|
|
160
|
+
for (let tries = 0; tries < 200 && !(await Bun.file(pidFile).exists()); tries++) await Bun.sleep(50);
|
|
161
|
+
const reader = Number(await Bun.file(pidFile).text());
|
|
162
|
+
if (ending === "is killed") {
|
|
163
|
+
expect(alive(reader)).toBe(true);
|
|
164
|
+
parent.kill("SIGKILL");
|
|
165
|
+
}
|
|
166
|
+
await parent.exited;
|
|
167
|
+
expect(await goneWithin(reader, 5_000)).toBe(true);
|
|
168
|
+
} finally {
|
|
169
|
+
parent.kill("SIGKILL");
|
|
170
|
+
}
|
|
171
|
+
}, 30_000);
|
|
172
|
+
|
|
173
|
+
test("reads the signals in the build's own environment and its define, never a .env file the build did not load", async () => {
|
|
174
|
+
const { root, pieceDir } = await writeScope(
|
|
175
|
+
sigSource.replace(
|
|
176
|
+
'refName: "String" }',
|
|
177
|
+
'refName: "String", mode: process.env.NODE_ENV, sentinel: process.env.AKAN_SIGNAL_SENTINEL ?? "none" }',
|
|
178
|
+
),
|
|
179
|
+
);
|
|
180
|
+
for (const file of [".env.production", ".env.production.local"])
|
|
181
|
+
await writeText(path.join(root, file), "AKAN_SIGNAL_SENTINEL=from-an-env-file\n");
|
|
182
|
+
const descriptors = new SignalDescriptors(root, ["apps/shop"]);
|
|
183
|
+
descriptors.plugin.setup({
|
|
184
|
+
config: { define: { "process.env.NODE_ENV": '"production"' } },
|
|
185
|
+
onLoad: () => undefined,
|
|
186
|
+
} as never);
|
|
187
|
+
|
|
188
|
+
const trolley = await descriptors.inline(pieceOf("trolley"), path.join(pieceDir, "trolley.fetch.ts"));
|
|
189
|
+
|
|
190
|
+
expect(trolley).toContain('"mode":"production","sentinel":"none"');
|
|
191
|
+
expect(trolley).not.toContain("from-an-env-file");
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
describe("a scope's whole runtime file on a page that also loads pieces", () => {
|
|
195
|
+
const wholeSource = `import { FetchClient } from "akanjs/fetch";
|
|
196
|
+
import * as cnst from "./cnst";
|
|
197
|
+
import { fetch as pageFetch, sig as pageSig } from "./usePage";
|
|
198
|
+
import { getSerializedSignal } from "./sig" with { type: "macro" };
|
|
199
|
+
Object.assign(pageSig, FetchClient.build(cnst, getSerializedSignal(), { base: pageFetch }).sig);
|
|
200
|
+
`;
|
|
201
|
+
const plainSig = sigSource.replace("\n odd: {", "\n spare: {").replace(", nullable: undefined }", " }");
|
|
202
|
+
const writePieces = async (pieceDir: string, names: string[]) =>
|
|
203
|
+
Promise.all(
|
|
204
|
+
names.map(async (name) => {
|
|
205
|
+
const file = path.join(pieceDir, `${name}.fetch.ts`);
|
|
206
|
+
await writeText(file, pieceOf(name));
|
|
207
|
+
return file;
|
|
208
|
+
}),
|
|
209
|
+
);
|
|
210
|
+
|
|
211
|
+
test("leaves out the descriptors of the pieces it is told, imports each piece by a name it uses, and keeps the rest", async () => {
|
|
212
|
+
const { root, pieceDir } = await writeScope(plainSig);
|
|
213
|
+
const [trolley] = await writePieces(pieceDir, ["trolley"]);
|
|
214
|
+
const descriptors = new SignalDescriptors(root, ["apps/shop"]);
|
|
215
|
+
|
|
216
|
+
const whole = await descriptors.withoutPieces(wholeSource, path.join(root, "apps/shop/lib/useClient.ts"), [
|
|
217
|
+
trolley ?? "",
|
|
218
|
+
]);
|
|
219
|
+
|
|
220
|
+
expect(whole).toContain(`import { loaded as __akanPiece0 } from ${JSON.stringify(trolley)};`);
|
|
221
|
+
expect(whole).toContain("__akanPiecesFirst(__akanPiece0);");
|
|
222
|
+
expect(whole).toContain('FetchClient.build(cnst, {"crate":');
|
|
223
|
+
expect(whole).toContain('"spare":');
|
|
224
|
+
expect(whole).not.toContain("pingAt");
|
|
225
|
+
expect(whole).not.toContain('type: "macro"');
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
test("keeps a signal named `base` that the scope takes from its base, unless the base piece holds it", async () => {
|
|
229
|
+
const query = (name: string) =>
|
|
230
|
+
`{ endpoint: { ${name}: { type: "query", args: [], returns: { refName: "String" } } } }`;
|
|
231
|
+
const libSig = `const serialized = {
|
|
232
|
+
base: ${query("pingBase")},
|
|
233
|
+
agent: ${query("askAgent")},
|
|
234
|
+
trolley: ${query("pingAt")},
|
|
235
|
+
crate: ${query("countOf")},
|
|
236
|
+
};
|
|
237
|
+
export const fetch = { ownSerializedSignal: serialized };
|
|
238
|
+
export const getSerializedSignalOf = (name) =>
|
|
239
|
+
name === "base" ? { base: serialized.base, agent: serialized.agent } : { [name]: serialized[name] };
|
|
240
|
+
`;
|
|
241
|
+
const { root, pieceDir } = await writeScope(libSig);
|
|
242
|
+
const [trolley] = await writePieces(pieceDir, ["trolley"]);
|
|
243
|
+
const basePiece = path.join(pieceDir, "_base.fetch.ts");
|
|
244
|
+
await writeText(basePiece, pieceOf("base"));
|
|
245
|
+
const file = path.join(root, "apps/shop/lib/useClient.ts");
|
|
246
|
+
const occurrencesOf = (source: string | null, text: string) => (source ?? "").split(text).length - 1;
|
|
247
|
+
|
|
248
|
+
const beside = await new SignalDescriptors(root, ["apps/shop"]).withoutPieces(wholeSource, file, [trolley ?? ""]);
|
|
249
|
+
expect(occurrencesOf(beside, "pingBase")).toBe(1);
|
|
250
|
+
expect(occurrencesOf(beside, "askAgent")).toBe(1);
|
|
251
|
+
expect(occurrencesOf(beside, "countOf")).toBe(1);
|
|
252
|
+
expect(occurrencesOf(beside, "pingAt")).toBe(0);
|
|
253
|
+
|
|
254
|
+
const taken = await new SignalDescriptors(root, ["apps/shop"]).withoutPieces(wholeSource, file, [
|
|
255
|
+
basePiece,
|
|
256
|
+
trolley ?? "",
|
|
257
|
+
]);
|
|
258
|
+
expect(occurrencesOf(taken, "pingBase")).toBe(0);
|
|
259
|
+
expect(occurrencesOf(taken, "askAgent")).toBe(0);
|
|
260
|
+
expect(occurrencesOf(taken, "countOf")).toBe(1);
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
test("keeps its macro and every descriptor where a name has no literal, or a piece names none", async () => {
|
|
264
|
+
const { root, pieceDir } = await writeScope();
|
|
265
|
+
const [trolley] = await writePieces(pieceDir, ["trolley"]);
|
|
266
|
+
const file = path.join(root, "apps/shop/lib/useClient.ts");
|
|
267
|
+
expect(
|
|
268
|
+
await new SignalDescriptors(root, ["apps/shop"]).withoutPieces(wholeSource, file, [trolley ?? ""]),
|
|
269
|
+
).toBeNull();
|
|
270
|
+
|
|
271
|
+
const plain = await writeScope(plainSig);
|
|
272
|
+
const unnamed = path.join(plain.pieceDir, "_base.fetch.ts");
|
|
273
|
+
await writeText(unnamed, "export const loaded = {};\n");
|
|
274
|
+
const plainFile = path.join(plain.root, "apps/shop/lib/useClient.ts");
|
|
275
|
+
expect(
|
|
276
|
+
await new SignalDescriptors(plain.root, ["apps/shop"]).withoutPieces(wholeSource, plainFile, [unnamed]),
|
|
277
|
+
).toBeNull();
|
|
278
|
+
});
|
|
279
|
+
});
|
|
280
|
+
});
|