@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
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import type { BarrelAnalyzer } from "./barrelAnalyzer";
|
|
2
|
+
import type { ObjectKeepReason, ObjectMemberImportsOptions } from "./objectMemberImports";
|
|
3
|
+
import type { ObjectMemberImport, ObjectModuleFacts, ObjectShape } from "./objectModule";
|
|
4
|
+
import type { ObjectModuleAnalyzer } from "./objectModuleAnalyzer";
|
|
5
|
+
|
|
6
|
+
export interface ObjectBarrels {
|
|
7
|
+
names: readonly string[];
|
|
8
|
+
analyzer: BarrelAnalyzer;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface ObjectSource {
|
|
12
|
+
file: string;
|
|
13
|
+
object: string;
|
|
14
|
+
facts: ObjectModuleFacts;
|
|
15
|
+
shape: ObjectShape;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface ObjectMemberOwner {
|
|
19
|
+
/** The object module that lists the member, which the member's specifier is relative to. */
|
|
20
|
+
file: string;
|
|
21
|
+
member: ObjectMemberImport;
|
|
22
|
+
nested: boolean;
|
|
23
|
+
/** Whether the object module the importer names, the one that lists the member or one between is `"use client"`. */
|
|
24
|
+
useClient: boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface ObjectLookupRead {
|
|
28
|
+
files: Set<string>;
|
|
29
|
+
barrels: Set<string>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
type ObjectCopyLink = [module: string, specifier: string, imported: string, file: string | null, object: string | null];
|
|
33
|
+
|
|
34
|
+
export interface ObjectCopyReach {
|
|
35
|
+
modules: string[];
|
|
36
|
+
barrelFiles: string[];
|
|
37
|
+
links: ObjectCopyLink[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const MAX_COPY_DEPTH = 4;
|
|
41
|
+
|
|
42
|
+
const keyOf = ({ file, object }: Pick<ObjectSource, "file" | "object">) => `${file}#${object}`;
|
|
43
|
+
|
|
44
|
+
//* Finds the object module that lists a member an importer names. A member the object's own shape does not list may
|
|
45
|
+
//* come from an imported object `Object.assign` copied in (`Object.assign(Section, Field, { Rich })`), read from that
|
|
46
|
+
//* object's module, last copy first as the later source wins.
|
|
47
|
+
export class ObjectMemberLookup {
|
|
48
|
+
readonly #modules: ObjectModuleAnalyzer;
|
|
49
|
+
readonly #resolve: ObjectMemberImportsOptions["resolve"];
|
|
50
|
+
readonly #barrels: ObjectBarrels | null;
|
|
51
|
+
|
|
52
|
+
constructor(
|
|
53
|
+
modules: ObjectModuleAnalyzer,
|
|
54
|
+
resolve: ObjectMemberImportsOptions["resolve"],
|
|
55
|
+
barrels: ObjectBarrels | null = null,
|
|
56
|
+
) {
|
|
57
|
+
this.#modules = modules;
|
|
58
|
+
this.#resolve = resolve;
|
|
59
|
+
this.#barrels = barrels;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async find(
|
|
63
|
+
source: ObjectSource,
|
|
64
|
+
memberPath: string[],
|
|
65
|
+
read: ObjectLookupRead,
|
|
66
|
+
): Promise<ObjectMemberOwner | ObjectKeepReason> {
|
|
67
|
+
return (await this.#find(source, memberPath, read, [])) ?? "unresolved-member";
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async namesFile(source: ObjectSource, read: ObjectLookupRead, above: string[] = []): Promise<boolean> {
|
|
71
|
+
if ([...source.shape.members.values()].some(Boolean)) return true;
|
|
72
|
+
const path = [...above, keyOf(source)];
|
|
73
|
+
if (source.shape.open || path.length > MAX_COPY_DEPTH) return false;
|
|
74
|
+
for (const copied of source.shape.copied) {
|
|
75
|
+
const from = await this.#copiedSource(source.file, copied, read);
|
|
76
|
+
if (from && !path.includes(keyOf(from)) && (await this.namesFile(from, read, path))) return true;
|
|
77
|
+
}
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async reach(file: string): Promise<ObjectCopyReach> {
|
|
82
|
+
const read: ObjectLookupRead = { files: new Set([file]), barrels: new Set() };
|
|
83
|
+
const links: ObjectCopyLink[] = [];
|
|
84
|
+
for (const module of read.files) {
|
|
85
|
+
const facts = await this.#modules.facts(module);
|
|
86
|
+
for (const shape of facts?.objects.values() ?? [])
|
|
87
|
+
for (const copied of shape.copied) {
|
|
88
|
+
const declared = await this.#declarationOf(copied, read);
|
|
89
|
+
const from = declared && (await this.#resolve(declared.specifier, module));
|
|
90
|
+
if (from) read.files.add(from);
|
|
91
|
+
links.push([module, copied.specifier, copied.imported, from ?? null, declared?.imported ?? null]);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const barrelFiles = await Promise.all([...read.barrels].map((barrel) => this.#barrels?.analyzer.filesOf(barrel)));
|
|
95
|
+
return { modules: [...read.files], barrelFiles: barrelFiles.flatMap((files) => files ?? []), links };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
//? null: the object holds no such member, so an object copied in before it may.
|
|
99
|
+
async #find(
|
|
100
|
+
source: ObjectSource,
|
|
101
|
+
memberPath: string[],
|
|
102
|
+
read: ObjectLookupRead,
|
|
103
|
+
above: string[],
|
|
104
|
+
): Promise<ObjectMemberOwner | ObjectKeepReason | null> {
|
|
105
|
+
const { file, facts, shape } = source;
|
|
106
|
+
const [name, inner] = memberPath;
|
|
107
|
+
if (name === undefined) return "unresolved-member";
|
|
108
|
+
const nestedKey = inner === undefined ? null : `${name}.${inner}`;
|
|
109
|
+
if (shape.members.has(name) || (nestedKey !== null && shape.members.has(nestedKey))) {
|
|
110
|
+
const nested = nestedKey === null ? null : shape.members.get(nestedKey);
|
|
111
|
+
const member = nested ?? shape.members.get(name);
|
|
112
|
+
return member ? { file, member, nested: !!nested, useClient: facts.useClient } : "unresolved-member";
|
|
113
|
+
}
|
|
114
|
+
if (shape.open) return "unresolved-member";
|
|
115
|
+
const path = [...above, keyOf(source)];
|
|
116
|
+
for (const copied of [...shape.copied].reverse()) {
|
|
117
|
+
const from = await this.#copiedSource(file, copied, read);
|
|
118
|
+
if (!from || path.includes(keyOf(from)) || path.length > MAX_COPY_DEPTH) return "unresolved-member";
|
|
119
|
+
//? Naming the member's file skips this module as well as the one that copies from it.
|
|
120
|
+
if (from.facts.failed) return from.facts.failed.clause;
|
|
121
|
+
const found = await this.#find(from, memberPath, read, path);
|
|
122
|
+
if (found === null) continue;
|
|
123
|
+
return typeof found === "string" ? found : { ...found, useClient: found.useClient || facts.useClient };
|
|
124
|
+
}
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async #copiedSource(
|
|
129
|
+
importer: string,
|
|
130
|
+
copied: ObjectMemberImport,
|
|
131
|
+
read: ObjectLookupRead,
|
|
132
|
+
): Promise<ObjectSource | null> {
|
|
133
|
+
const declared = await this.#declarationOf(copied, read);
|
|
134
|
+
const file = declared && (await this.#resolve(declared.specifier, importer));
|
|
135
|
+
if (!declared || !file) return null;
|
|
136
|
+
read.files.add(file);
|
|
137
|
+
const facts = await this.#modules.facts(file);
|
|
138
|
+
const shape = facts?.objects.get(declared.imported);
|
|
139
|
+
return facts && shape ? { file, object: declared.imported, facts, shape } : null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
//? Followed as `rewriteBarrelImports` rewrites an importer's own import, so every caller finds the object at one file.
|
|
143
|
+
async #declarationOf(copied: ObjectMemberImport, read: ObjectLookupRead): Promise<ObjectMemberImport | null> {
|
|
144
|
+
if (!this.#barrels?.names.includes(copied.specifier) || copied.imported === "default") return copied;
|
|
145
|
+
read.barrels.add(copied.specifier);
|
|
146
|
+
const target = (await this.#barrels.analyzer.analyze(copied.specifier))?.get(copied.imported);
|
|
147
|
+
if (!target) return copied;
|
|
148
|
+
return target.namespace ? null : { specifier: target.subpath, imported: target.originalName };
|
|
149
|
+
}
|
|
150
|
+
}
|
|
@@ -112,11 +112,41 @@ describe("ObjectModule: a module an importer may skip for the members it names",
|
|
|
112
112
|
});
|
|
113
113
|
|
|
114
114
|
test("fails a call or construction evaluated at load (call)", () => {
|
|
115
|
-
const head = 'import {
|
|
116
|
-
for (const value of ["
|
|
115
|
+
const head = 'import { wrap } from "./wrap";\nimport { A } from "./A";';
|
|
116
|
+
for (const value of ["wrap(A)", "new Map()", "tag`x`", "{ Text: wrap(A) }", "Object.assign({}, { A: wrap(A) })"])
|
|
117
117
|
expect(read([head, `export const X = ${value};`]).failed).toEqual({ clause: "call", line: 3 });
|
|
118
118
|
});
|
|
119
119
|
|
|
120
|
+
test("passes a call of React's memo, forwardRef, lazy or createContext, whose arguments are values like any other", () => {
|
|
121
|
+
const failedOn = (head: string, value: string, ...rest: string[]) =>
|
|
122
|
+
read([head, 'import { A } from "./A";', `const Wrapped = ${value};`, "export const X = { A, Wrapped };", ...rest])
|
|
123
|
+
.failed;
|
|
124
|
+
|
|
125
|
+
for (const name of ["memo", "forwardRef", "lazy", "createContext"])
|
|
126
|
+
expect(failedOn(`import { ${name} } from "react";`, `${name}(A)`)).toBeNull();
|
|
127
|
+
expect(failedOn('import { memo as wrap } from "react";', "wrap(A)")).toBeNull();
|
|
128
|
+
expect(failedOn('import React from "react";', "React.memo(A)")).toBeNull();
|
|
129
|
+
expect(failedOn('import * as React from "react";', "React.forwardRef<HTMLDivElement>(() => null)")).toBeNull();
|
|
130
|
+
expect(
|
|
131
|
+
failedOn('import React, { memo } from "react";', "memo(React.lazy(() => import('./A')), ...[A])"),
|
|
132
|
+
).toBeNull();
|
|
133
|
+
|
|
134
|
+
const call = { clause: "call" as const, line: 3 };
|
|
135
|
+
expect(failedOn('import { memo } from "./memo";', "memo(A)")).toEqual(call);
|
|
136
|
+
expect(failedOn('import { memo } from "preact/compat";', "memo(A)")).toEqual(call);
|
|
137
|
+
expect(failedOn('import * as React from "./react";', "React.memo(A)")).toEqual(call);
|
|
138
|
+
expect(failedOn("const memo = (value: unknown) => value;", "memo(A)")).toEqual(call);
|
|
139
|
+
expect(failedOn('import { useMemo } from "react";', "useMemo(A)")).toEqual(call);
|
|
140
|
+
expect(failedOn('import React from "react";', "React.createElement(A)")).toEqual(call);
|
|
141
|
+
expect(failedOn('import { memo } from "react";', "new memo(A)")).toEqual(call);
|
|
142
|
+
expect(failedOn('import { memo, version } from "react";', "memo(version.trim())")).toEqual(call);
|
|
143
|
+
expect(failedOn('import { memo } from "react";', "memo((globalThis.seen = A))")?.clause).toBe("effect-value");
|
|
144
|
+
expect(failedOn('import { memo } from "react";', "memo(A)", 'Wrapped.displayName = "Wrapped";')).toEqual({
|
|
145
|
+
clause: "effect-statement",
|
|
146
|
+
line: 5,
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
|
|
120
150
|
test("fails a value that assigns or awaits while it is evaluated (effect-value)", () => {
|
|
121
151
|
const head = 'import { A } from "./A";\nconst state = { n: 0 };';
|
|
122
152
|
for (const value of ["{ A, n: (state.n = 1) }", "{ A, n: ++state.n }", "await A", "Object.assign(window, { A })"])
|
|
@@ -182,6 +212,46 @@ describe("ObjectModule: a module an importer may skip for the members it names",
|
|
|
182
212
|
});
|
|
183
213
|
});
|
|
184
214
|
|
|
215
|
+
test("records an imported object `Object.assign` copies in, and names no file for a member it may replace", () => {
|
|
216
|
+
const head = [
|
|
217
|
+
'import { Field } from "./Field";',
|
|
218
|
+
'import Base from "./Base";',
|
|
219
|
+
'import * as parts from "./parts";',
|
|
220
|
+
'import { A } from "./A";',
|
|
221
|
+
'import { B } from "./B";',
|
|
222
|
+
];
|
|
223
|
+
const shapeOf = (...lines: string[]) => {
|
|
224
|
+
const shape = read([...head, ...lines]).objects.get("X");
|
|
225
|
+
return { members: Object.fromEntries(shape?.members ?? []), open: shape?.open, copied: shape?.copied };
|
|
226
|
+
};
|
|
227
|
+
const field = { specifier: "./Field", imported: "Field" };
|
|
228
|
+
const b = { specifier: "./B", imported: "B" };
|
|
229
|
+
|
|
230
|
+
expect(read([...head, "export const X = Object.assign(() => null, Field, { A });"]).failed).toBeNull();
|
|
231
|
+
expect(shapeOf("export const X = Object.assign(() => null, { A }, Field, { B });")).toEqual({
|
|
232
|
+
members: { A: null, B: b },
|
|
233
|
+
open: false,
|
|
234
|
+
copied: [field],
|
|
235
|
+
});
|
|
236
|
+
expect(shapeOf("export const X = Object.assign({}, Field, { A }, Base as object, { B });")).toEqual({
|
|
237
|
+
members: { A: null, B: b },
|
|
238
|
+
open: false,
|
|
239
|
+
copied: [field, { specifier: "./Base", imported: "default" }],
|
|
240
|
+
});
|
|
241
|
+
expect(shapeOf("export const X = { A };", "Object.assign(X, Field);", "X.B = B;")).toEqual({
|
|
242
|
+
members: { A: null, B: b },
|
|
243
|
+
open: false,
|
|
244
|
+
copied: [field],
|
|
245
|
+
});
|
|
246
|
+
expect(shapeOf("export const X = Object.assign({ A }, parts, { B });")).toEqual({
|
|
247
|
+
members: { A: null, B: b },
|
|
248
|
+
open: true,
|
|
249
|
+
copied: [],
|
|
250
|
+
});
|
|
251
|
+
expect(shapeOf("export const X = Object.assign({ A }, Field.Sub, { B });").open).toBe(true);
|
|
252
|
+
expect(shapeOf("export const X = Object.assign({}, Field, { ...parts, B });").open).toBe(true);
|
|
253
|
+
});
|
|
254
|
+
|
|
185
255
|
test("points a member written one level down at its file, and no deeper", () => {
|
|
186
256
|
const lines = [
|
|
187
257
|
'import { Zone } from "./Doc";',
|
|
@@ -21,8 +21,10 @@ export interface ObjectShape {
|
|
|
21
21
|
* `Doc.Zone` keys a member of an object literal written one level down (`{ Doc: { Zone } }`).
|
|
22
22
|
*/
|
|
23
23
|
members: Map<string, ObjectMemberImport | null>;
|
|
24
|
-
/** Members the analysis cannot list (a spread, a computed key,
|
|
24
|
+
/** Members the analysis cannot list (a spread, a computed key, a source copied in that is no imported object). */
|
|
25
25
|
open: boolean;
|
|
26
|
+
/** Imported objects `Object.assign` copied in, in source order: each may hold a member the shape does not list. */
|
|
27
|
+
copied: ObjectMemberImport[];
|
|
26
28
|
}
|
|
27
29
|
|
|
28
30
|
export interface ObjectModuleFacts {
|
|
@@ -61,13 +63,15 @@ const ASSIGN_OPERATORS = new Set([
|
|
|
61
63
|
ts.SyntaxKind.BarBarEqualsToken,
|
|
62
64
|
ts.SyntaxKind.QuestionQuestionEqualsToken,
|
|
63
65
|
]);
|
|
66
|
+
const REACT_WRAPPERS = new Set(["memo", "forwardRef", "lazy", "createContext"]);
|
|
64
67
|
|
|
65
68
|
//* The rule a module meets before an importer may skip it and import the object's members instead. Every top-level
|
|
66
69
|
//* statement is a declaration (an import that binds names, a type, a directive, a `const` or `function`, an `export`
|
|
67
70
|
//* list) or puts a member on an object the module created above it (`X.m = v`, `Object.assign(X, …)`), and every
|
|
68
|
-
//* value evaluated at load is effect-free (no call but `Object.assign` onto the module's own object
|
|
69
|
-
//* only binds names, so an importer that never
|
|
70
|
-
//*
|
|
71
|
+
//* value evaluated at load is effect-free (no call but `Object.assign` onto the module's own object and React's
|
|
72
|
+
//* `memo`, `forwardRef`, `lazy` and `createContext`). Such a module only binds names, so an importer that never
|
|
73
|
+
//* reaches the object loses nothing by not running it. A re-export fails: skipping the module would skip the module
|
|
74
|
+
//* it re-exports from, which nothing else loads.
|
|
71
75
|
export class ObjectModule {
|
|
72
76
|
static scriptKindOf(file: string): ts.ScriptKind {
|
|
73
77
|
if (file.endsWith(".tsx")) return ts.ScriptKind.TSX;
|
|
@@ -272,12 +276,27 @@ export class ObjectModule {
|
|
|
272
276
|
if (assign) this.#checkObjectAssign(assign, value);
|
|
273
277
|
else if (ts.isObjectLiteralExpression(value)) this.#checkObjectLiteral(value);
|
|
274
278
|
else {
|
|
275
|
-
const parts = ObjectModule.#partsOf(value);
|
|
279
|
+
const parts = this.#reactWrapped(value) ?? ObjectModule.#partsOf(value);
|
|
276
280
|
if (typeof parts === "string") this.#fail(parts, value);
|
|
277
281
|
else for (const part of parts) this.#checkValue(part);
|
|
278
282
|
}
|
|
279
283
|
}
|
|
280
284
|
|
|
285
|
+
//? These four only wrap what they are given: none renders a component, runs a loader or reads a context at load.
|
|
286
|
+
#reactWrapped(value: ts.Expression): ts.Expression[] | null {
|
|
287
|
+
if (!ts.isCallExpression(value)) return null;
|
|
288
|
+
const callee = value.expression;
|
|
289
|
+
const { imports } = this.#collected;
|
|
290
|
+
let wrapper = ts.isIdentifier(callee) ? imports.get(callee.text) : undefined;
|
|
291
|
+
if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression)) {
|
|
292
|
+
const react = imports.get(callee.expression.text);
|
|
293
|
+
if (react && ["default", "*"].includes(react.imported))
|
|
294
|
+
wrapper = { specifier: react.specifier, imported: callee.name.text };
|
|
295
|
+
}
|
|
296
|
+
if (wrapper?.specifier !== "react" || !REACT_WRAPPERS.has(wrapper.imported)) return null;
|
|
297
|
+
return value.arguments.map((argument) => (ts.isSpreadElement(argument) ? argument.expression : argument));
|
|
298
|
+
}
|
|
299
|
+
|
|
281
300
|
static #partsOf(value: ts.Expression): ts.Expression[] | ObjectModuleClause {
|
|
282
301
|
if (
|
|
283
302
|
ts.isIdentifier(value) ||
|
|
@@ -331,7 +350,7 @@ export class ObjectModule {
|
|
|
331
350
|
#shapeOf(local: string): ObjectShape | null {
|
|
332
351
|
const root = this.#collected.roots.get(local);
|
|
333
352
|
if (!root || (!root.literal && root.edits.length === 0)) return null;
|
|
334
|
-
const shape: ObjectShape = { members: new Map(), open: false };
|
|
353
|
+
const shape: ObjectShape = { members: new Map(), open: false, copied: [] };
|
|
335
354
|
if (root.literal) this.#addLiteral(shape, root.literal);
|
|
336
355
|
for (const { member, value } of root.edits) {
|
|
337
356
|
if (member === null) this.#addSource(shape, value);
|
|
@@ -357,7 +376,12 @@ export class ObjectModule {
|
|
|
357
376
|
if (ts.isObjectLiteralExpression(value)) return this.#addLiteral(shape, value);
|
|
358
377
|
if (ObjectModule.#isFunction(value)) return;
|
|
359
378
|
const root = ts.isIdentifier(value) ? this.#collected.roots.get(value.text) : undefined;
|
|
360
|
-
if (
|
|
379
|
+
if (root && !root.literal && root.edits.length === 0) return;
|
|
380
|
+
const copied = ts.isIdentifier(value) && !root ? this.#collected.imports.get(value.text) : undefined;
|
|
381
|
+
if (!copied || copied.imported === "*") return ObjectModule.#cover(shape, "");
|
|
382
|
+
//? A later source wins: the copy may replace a member listed before it, and one listed after replaces the copy's.
|
|
383
|
+
for (const key of shape.members.keys()) shape.members.set(key, null);
|
|
384
|
+
shape.copied.push(copied);
|
|
361
385
|
}
|
|
362
386
|
|
|
363
387
|
static #isFunction(value: ts.Expression) {
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { ModuleParts } from "./moduleParts";
|
|
4
|
+
import { PartImports } from "./partImports";
|
|
5
|
+
|
|
6
|
+
const dir = "/repo/apps/demo/ui";
|
|
7
|
+
const pair = `${dir}/Pair.tsx`;
|
|
8
|
+
const importer = `${dir}/Page.tsx`;
|
|
9
|
+
const part = (id: string) => `"${pair}?akan-part=${id}"`;
|
|
10
|
+
const pairSource = [
|
|
11
|
+
"export interface Props { a: number }",
|
|
12
|
+
"export const A = () => 1;",
|
|
13
|
+
"export const B = () => 2;",
|
|
14
|
+
"const C = () => 3;",
|
|
15
|
+
"export default C;",
|
|
16
|
+
"",
|
|
17
|
+
].join("\n");
|
|
18
|
+
|
|
19
|
+
const imports = new PartImports({
|
|
20
|
+
resolve: async (specifier, from) => path.resolve(path.dirname(from), `${specifier}.tsx`),
|
|
21
|
+
partsOf: async (file) => (file === pair ? ModuleParts.read(pairSource, pair) : null),
|
|
22
|
+
});
|
|
23
|
+
const rewritten = async (...lines: string[]) => imports.rewrite(`${lines.join("\n")}\n`, importer);
|
|
24
|
+
|
|
25
|
+
describe("PartImports", () => {
|
|
26
|
+
test("each name asked of a file in parts is asked of the part holding it, and a type is asked of none", async () => {
|
|
27
|
+
expect(
|
|
28
|
+
await rewritten(
|
|
29
|
+
'import Pair, { A, B as Bee, type Props } from "./Pair";',
|
|
30
|
+
'import { Other } from "./Other";',
|
|
31
|
+
"export const page = [Pair, A, Bee, Other];",
|
|
32
|
+
),
|
|
33
|
+
).toBe(
|
|
34
|
+
[
|
|
35
|
+
`import { default as Pair } from ${part("p2")};`,
|
|
36
|
+
`import { A } from ${part("p0")};`,
|
|
37
|
+
`import { B as Bee } from ${part("p1")};`,
|
|
38
|
+
'import { Other } from "./Other";',
|
|
39
|
+
"export const page = [Pair, A, Bee, Other];",
|
|
40
|
+
"",
|
|
41
|
+
].join("\n"),
|
|
42
|
+
);
|
|
43
|
+
expect(await rewritten('import { A, Props } from "./Pair";', "export const page = A;")).toBe(
|
|
44
|
+
[`import { A } from ${part("p0")};`, "export const page = A;", ""].join("\n"),
|
|
45
|
+
);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test("a re-export follows its names to their parts the same way", async () => {
|
|
49
|
+
expect(await rewritten('export { A as First, B } from "./Pair";')).toBe(
|
|
50
|
+
[`export { A as First } from ${part("p0")};`, `export { B } from ${part("p1")};`, ""].join("\n"),
|
|
51
|
+
);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test("a name the parts do not hold stays asked of the file", async () => {
|
|
55
|
+
expect(await rewritten('import { A, Missing } from "./Pair";')).toBe(
|
|
56
|
+
[`import { A } from ${part("p0")};`, 'import { Missing } from "./Pair";', ""].join("\n"),
|
|
57
|
+
);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test.each([
|
|
61
|
+
["a namespace import", 'import * as Pair from "./Pair";'],
|
|
62
|
+
["`export *`", 'export * from "./Pair";'],
|
|
63
|
+
["a bare import", 'import "./Pair";'],
|
|
64
|
+
["a type import", 'import type { Props } from "./Pair";'],
|
|
65
|
+
["an import with attributes", 'import { A } from "./Pair" with { type: "json" };'],
|
|
66
|
+
["`import()`", 'export const later = () => import("./Pair");'],
|
|
67
|
+
["an import of a file left whole", 'import { Other } from "./Other";'],
|
|
68
|
+
["an import already naming a part", `import { A } from ${part("p0")};`],
|
|
69
|
+
])("%s is left as written", async (_, line) => {
|
|
70
|
+
expect(await rewritten(line)).toBeNull();
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test("a file's import of itself is left as written", async () => {
|
|
74
|
+
expect(await imports.rewrite('import { A } from "./Pair";\n', pair)).toBeNull();
|
|
75
|
+
});
|
|
76
|
+
});
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { ModuleParts } from "./moduleParts";
|
|
3
|
+
import { ObjectModule } from "./objectModule";
|
|
4
|
+
|
|
5
|
+
export interface PartImportsOptions {
|
|
6
|
+
resolve: (specifier: string, importer: string) => Promise<string | null>;
|
|
7
|
+
//? Null for a file that stays one module.
|
|
8
|
+
partsOf: (file: string) => Promise<ModuleParts | null>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
interface Asked {
|
|
12
|
+
imported: string;
|
|
13
|
+
local: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
interface Statement {
|
|
17
|
+
kind: "import" | "export";
|
|
18
|
+
specifier: string;
|
|
19
|
+
written: string;
|
|
20
|
+
names: Asked[];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
interface Edit {
|
|
24
|
+
start: number;
|
|
25
|
+
end: number;
|
|
26
|
+
text: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const FROM = /\bfrom\s*["']/;
|
|
30
|
+
|
|
31
|
+
//* Sends each name an import or re-export asks of a file in parts to the part holding it, so a bundler follows that
|
|
32
|
+
//* part alone. A namespace import, `export *`, a bare import and `import()` keep asking the file, which loads them all.
|
|
33
|
+
export class PartImports {
|
|
34
|
+
readonly #resolve: PartImportsOptions["resolve"];
|
|
35
|
+
readonly #partsOf: PartImportsOptions["partsOf"];
|
|
36
|
+
|
|
37
|
+
constructor({ resolve, partsOf }: PartImportsOptions) {
|
|
38
|
+
this.#resolve = resolve;
|
|
39
|
+
this.#partsOf = partsOf;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async rewrite(source: string, importer: string): Promise<string | null> {
|
|
43
|
+
if (!FROM.test(source)) return null;
|
|
44
|
+
const sourceFile = ts.createSourceFile(
|
|
45
|
+
importer,
|
|
46
|
+
source,
|
|
47
|
+
ts.ScriptTarget.Latest,
|
|
48
|
+
true,
|
|
49
|
+
ObjectModule.scriptKindOf(importer),
|
|
50
|
+
);
|
|
51
|
+
const edits: Edit[] = [];
|
|
52
|
+
for (const statement of sourceFile.statements) {
|
|
53
|
+
const asked = PartImports.#askedBy(statement);
|
|
54
|
+
if (!asked) continue;
|
|
55
|
+
const file = await this.#resolve(asked.specifier, importer);
|
|
56
|
+
const parts = file && file !== importer ? await this.#partsOf(file) : null;
|
|
57
|
+
if (!file || !parts) continue;
|
|
58
|
+
const lines = PartImports.#lines(asked, parts, file);
|
|
59
|
+
edits.push({ start: statement.getStart(sourceFile), end: statement.end, text: lines.join("\n") });
|
|
60
|
+
}
|
|
61
|
+
if (edits.length === 0) return null;
|
|
62
|
+
let next = "";
|
|
63
|
+
let cursor = 0;
|
|
64
|
+
for (const { start, end, text } of edits) {
|
|
65
|
+
next += `${source.slice(cursor, start)}${text}`;
|
|
66
|
+
cursor = end;
|
|
67
|
+
}
|
|
68
|
+
return `${next}${source.slice(cursor)}`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
static #askedBy(statement: ts.Statement): Statement | null {
|
|
72
|
+
if (!ts.isImportDeclaration(statement) && !ts.isExportDeclaration(statement)) return null;
|
|
73
|
+
const { moduleSpecifier, attributes } = statement;
|
|
74
|
+
if (!moduleSpecifier || !ts.isStringLiteral(moduleSpecifier) || attributes) return null;
|
|
75
|
+
if (ModuleParts.specifier.test(moduleSpecifier.text)) return null;
|
|
76
|
+
const from = { specifier: moduleSpecifier.text, written: moduleSpecifier.getText() };
|
|
77
|
+
const namesOf = (elements: readonly (ts.ImportSpecifier | ts.ExportSpecifier)[]) =>
|
|
78
|
+
elements
|
|
79
|
+
.filter((element) => !element.isTypeOnly)
|
|
80
|
+
.map((element) => ({ imported: (element.propertyName ?? element.name).text, local: element.name.text }));
|
|
81
|
+
if (ts.isExportDeclaration(statement)) {
|
|
82
|
+
const clause = statement.exportClause;
|
|
83
|
+
if (statement.isTypeOnly || !clause || !ts.isNamedExports(clause)) return null;
|
|
84
|
+
const names = namesOf(clause.elements);
|
|
85
|
+
return names.length ? { kind: "export", ...from, names } : null;
|
|
86
|
+
}
|
|
87
|
+
const clause = statement.importClause;
|
|
88
|
+
if (!clause || clause.phaseModifier === ts.SyntaxKind.TypeKeyword) return null;
|
|
89
|
+
const bindings = clause.namedBindings;
|
|
90
|
+
if (bindings && ts.isNamespaceImport(bindings)) return null;
|
|
91
|
+
const names = namesOf(bindings?.elements ?? []);
|
|
92
|
+
if (clause.name) names.unshift({ imported: "default", local: clause.name.text });
|
|
93
|
+
return names.length ? { kind: "import", ...from, names } : null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
//? A name the file's parts do not hold stays asked of the file, so the bundler reports it as it did before.
|
|
97
|
+
static #lines({ kind, names, written }: Statement, parts: ModuleParts, file: string): string[] {
|
|
98
|
+
const byTarget = new Map<string, Asked[]>();
|
|
99
|
+
for (const asked of names) {
|
|
100
|
+
const part = parts.partOf(asked.imported);
|
|
101
|
+
if (!part && parts.isType(asked.imported)) continue;
|
|
102
|
+
const target = part ? JSON.stringify(`${file}${ModuleParts.query}${part}`) : written;
|
|
103
|
+
byTarget.set(target, [...(byTarget.get(target) ?? []), asked]);
|
|
104
|
+
}
|
|
105
|
+
return [...byTarget].map(([target, held]) => {
|
|
106
|
+
const list = held.map(({ imported, local }) => (imported === local ? local : `${imported} as ${local}`));
|
|
107
|
+
return `${kind} { ${list.join(", ")} } from ${target};`;
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
}
|