@akanjs/devkit 3.3.0-rc.36 → 3.3.0-rc.38

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.
Files changed (44) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/app/applicationBuildRunner.ts +7 -1
  3. package/app/dictionarySizes.ts +2 -5
  4. package/app/routeFilesReport.test.ts +59 -0
  5. package/app/routeFilesReport.ts +46 -0
  6. package/app/routeJsBudget.ts +18 -4
  7. package/artifact/storeBootstrap.ts +5 -1
  8. package/biome.base.json +1 -3
  9. package/codeAgent/skills/akan-page/SKILL.md +28 -7
  10. package/executors/clientRuntimeKeys.test.ts +72 -1
  11. package/executors/sysExecutor.ts +10 -8
  12. package/frontendBuild/allRoutesBuilder.ts +14 -7
  13. package/frontendBuild/clientEntryDiscovery.test.ts +193 -0
  14. package/frontendBuild/clientEntryDiscovery.ts +41 -8
  15. package/frontendBuild/devBarrelImports.test.ts +54 -0
  16. package/frontendBuild/devBarrelImports.ts +1 -0
  17. package/frontendBuild/dictionaryAssetBuilder.test.ts +12 -4
  18. package/frontendBuild/dictionaryAssetBuilder.ts +20 -7
  19. package/frontendBuild/dictionaryConstants.ts +55 -1
  20. package/frontendBuild/dictionaryPacking.test.ts +58 -0
  21. package/frontendBuild/dictionaryPacking.ts +43 -0
  22. package/frontendBuild/dictionaryRoutes.test.ts +65 -0
  23. package/frontendBuild/dictionaryRoutes.ts +3 -1
  24. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  25. package/frontendBuild/precompressArtifacts.ts +18 -11
  26. package/frontendBuild/renderedEntries.ts +129 -0
  27. package/frontendBuild/routeHandoffs.test.ts +10 -0
  28. package/frontendBuild/routeHandoffs.ts +3 -1
  29. package/frontendBuild/routeRuntimePays.test.ts +7 -1
  30. package/lint/biomeBase.test.ts +23 -3
  31. package/package.json +3 -3
  32. package/quality/dictionaryKeys.test.ts +185 -2
  33. package/quality/dictionaryKeys.ts +82 -9
  34. package/quality/objectImportReport.ts +6 -3
  35. package/quality/translatorBindings.ts +187 -0
  36. package/transforms/barrelImportsPlugin.ts +6 -1
  37. package/transforms/exportReach.test.ts +162 -0
  38. package/transforms/exportReach.ts +304 -0
  39. package/transforms/objectMemberImports.test.ts +289 -7
  40. package/transforms/objectMemberImports.ts +92 -58
  41. package/transforms/objectMemberLookup.ts +150 -0
  42. package/transforms/objectModule.test.ts +72 -2
  43. package/transforms/objectModule.ts +31 -7
  44. package/workspace/scanInfo.ts +24 -0
@@ -7,7 +7,8 @@ import {
7
7
  ObjectImportEdits,
8
8
  type ObjectMemberUse,
9
9
  } from "./objectImportEdits";
10
- import { ObjectModule, type ObjectModuleClause, type ObjectModuleFacts, type ObjectShape } from "./objectModule";
10
+ import { type ObjectBarrels, type ObjectLookupRead, ObjectMemberLookup, type ObjectSource } from "./objectMemberLookup";
11
+ import { ObjectModule, type ObjectModuleClause } from "./objectModule";
11
12
  import { ObjectModuleAnalyzer, resolveModuleFile } from "./objectModuleAnalyzer";
12
13
  import { hasUseClientDirective } from "./rscUseClientTransform";
13
14
 
@@ -42,14 +43,17 @@ export interface ObjectMemberRewrite {
42
43
  clientImporter: boolean;
43
44
  narrowed: ObjectImportNarrowed[];
44
45
  kept: ObjectImportKept[];
45
- /** The object modules the answer read and the member files whose exports it consulted. */
46
+ /** The object modules the answer read, copied ones included, and the member files whose exports it consulted. */
46
47
  read: string[];
48
+ /** The barrels whose export map said where a copied object is declared. */
49
+ barrels: string[];
47
50
  }
48
51
 
49
52
  export interface ObjectMemberImportsOptions {
50
53
  resolve: (specifier: string, importer: string) => Promise<string | null>;
51
54
  specifierOf?: (file: string, importer: string) => string;
52
55
  keepLines?: boolean;
56
+ barrels?: ObjectBarrels;
53
57
  }
54
58
 
55
59
  const ASSIGN_OPERATOR_FIRST = ts.SyntaxKind.FirstAssignment;
@@ -66,18 +70,25 @@ const escapeRe = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
66
70
  export class ObjectMemberImports {
67
71
  static readonly keyPrefix = "object:";
68
72
  readonly #modules: ObjectModuleAnalyzer;
73
+ readonly #lookup: ObjectMemberLookup;
69
74
  readonly #resolve: ObjectMemberImportsOptions["resolve"];
70
75
  readonly #specifierOf: NonNullable<ObjectMemberImportsOptions["specifierOf"]>;
71
76
  readonly #keepLines: boolean;
72
77
 
73
78
  constructor(
74
- { resolve, specifierOf = ObjectMemberImports.absoluteSpecifier, keepLines = false }: ObjectMemberImportsOptions,
79
+ {
80
+ resolve,
81
+ specifierOf = ObjectMemberImports.absoluteSpecifier,
82
+ keepLines = false,
83
+ barrels,
84
+ }: ObjectMemberImportsOptions,
75
85
  modules = new ObjectModuleAnalyzer(),
76
86
  ) {
77
87
  this.#resolve = resolve;
78
88
  this.#specifierOf = specifierOf;
79
89
  this.#keepLines = keepLines;
80
90
  this.#modules = modules;
91
+ this.#lookup = new ObjectMemberLookup(modules, resolve, barrels);
81
92
  }
82
93
 
83
94
  get modules() {
@@ -129,31 +140,40 @@ export class ObjectMemberImports {
129
140
  );
130
141
  const candidates = ObjectMemberImports.#importsOf(sourceFile, locals);
131
142
  if (candidates.size === 0) return null;
132
- const read = new Set<string>();
133
- const facts = new Map<Candidate, { facts: ObjectModuleFacts; shape: ObjectShape }>();
143
+ const read: ObjectLookupRead = { files: new Set(), barrels: new Set() };
144
+ const sources = new Map<Candidate, ObjectSource>();
134
145
  for (const candidate of candidates.values()) {
135
146
  const specifier = (candidate.declaration.moduleSpecifier as ts.StringLiteral).text;
136
147
  const file = await this.#resolve(specifier, importer);
137
148
  if (!file) continue;
138
- const moduleFacts = await this.#modules.facts(file);
139
- const shape = moduleFacts?.objects.get(candidate.imported);
140
- if (!moduleFacts || !shape || ![...shape.members.values()].some(Boolean)) continue;
149
+ const facts = await this.#modules.facts(file);
150
+ const shape = facts?.objects.get(candidate.imported);
151
+ if (!facts || !shape) continue;
152
+ const objectSource = { file, object: candidate.imported, facts, shape };
153
+ if (!(await this.#lookup.namesFile(objectSource, read))) continue;
141
154
  candidate.file = file;
142
- read.add(file);
143
- facts.set(candidate, { facts: moduleFacts, shape });
155
+ read.files.add(file);
156
+ sources.set(candidate, objectSource);
144
157
  }
145
- if (facts.size === 0) return null;
146
- ObjectMemberImports.#classifyUses(sourceFile, new Map([...facts.keys()].map((c) => [c.local, c])));
158
+ if (sources.size === 0) return null;
159
+ ObjectMemberImports.#classifyUses(sourceFile, new Map([...sources.keys()].map((c) => [c.local, c])));
147
160
  const clientImporter = hasUseClientDirective(source);
148
- const result: ObjectMemberRewrite = { contents: null, clientImporter, narrowed: [], kept: [], read: [] };
161
+ const result: ObjectMemberRewrite = {
162
+ contents: null,
163
+ clientImporter,
164
+ narrowed: [],
165
+ kept: [],
166
+ read: [],
167
+ barrels: [],
168
+ };
149
169
  const plan = new ObjectImportEdits(source, sourceFile, this.#keepLines);
150
- for (const [candidate, { facts: moduleFacts, shape }] of facts) {
151
- const file = candidate.file ?? "";
170
+ for (const [candidate, objectSource] of sources) {
171
+ const { file, facts } = objectSource;
152
172
  const lineOf = (node: ts.Node) => sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
153
173
  const keep = (reason: ObjectKeepReason, node: ts.Node) =>
154
174
  result.kept.push({ object: candidate.imported, file, line: lineOf(node), reason });
155
- if (moduleFacts.failed) {
156
- keep(moduleFacts.failed.clause, candidate.element);
175
+ if (facts.failed) {
176
+ keep(facts.failed.clause, candidate.element);
157
177
  continue;
158
178
  }
159
179
  if (candidate.shadowed) {
@@ -164,7 +184,7 @@ export class ObjectMemberImports {
164
184
  keep(candidate.keep.reason, candidate.keep.node);
165
185
  continue;
166
186
  }
167
- const targets = await this.#targetsOf(candidate, moduleFacts, shape, importer, clientImporter, read);
187
+ const targets = await this.#targetsOf(candidate, objectSource, importer, clientImporter, read);
168
188
  if ("reason" in targets) {
169
189
  keep(targets.reason, targets.node);
170
190
  continue;
@@ -176,64 +196,80 @@ export class ObjectMemberImports {
176
196
  members: [...new Set(targets.map(({ written }) => written))].sort(),
177
197
  });
178
198
  }
179
- result.read = [...read];
199
+ result.read = [...read.files];
200
+ result.barrels = [...read.barrels];
180
201
  result.contents = plan.apply();
181
202
  return result;
182
203
  }
183
204
 
184
205
  async fingerprint(file: string, object: string, members: string[], clientImporter: boolean): Promise<string> {
185
- const moduleFacts = await this.#modules.facts(file);
186
- const shape = moduleFacts?.objects.get(object);
206
+ const facts = await this.#modules.facts(file);
207
+ const shape = facts?.objects.get(object);
208
+ const read: ObjectLookupRead = { files: new Set(), barrels: new Set() };
187
209
  const targets = await Promise.all(
188
210
  members.map(async (member) => {
189
- if (!moduleFacts || !shape) return null;
211
+ if (!facts || !shape) return null;
190
212
  const called = member.endsWith("()");
191
213
  const memberPath = (called ? member.slice(0, -2) : member).split(".");
192
- const target = await this.#targetOf(file, moduleFacts, shape, memberPath, file, clientImporter, new Set());
214
+ const target = await this.#targetOf({ file, object, facts, shape }, memberPath, file, clientImporter, read);
193
215
  return await this.#calledTargetOf(target, memberPath, called);
194
216
  }),
195
217
  );
196
- return Bun.hash(JSON.stringify([moduleFacts?.failed ?? null, targets])).toString(36);
218
+ return Bun.hash(JSON.stringify([facts?.failed ?? null, targets])).toString(36);
197
219
  }
198
220
 
199
221
  async filesOf(file: string): Promise<string[]> {
200
- const moduleFacts = await this.#modules.facts(file);
201
- const files = new Set([file]);
202
- for (const shape of moduleFacts?.objects.values() ?? [])
203
- for (const member of shape.members.values()) {
204
- if (!member || !ObjectMemberImports.#isPathSpecifier(member.specifier)) continue;
205
- const resolved = await resolveModuleFile(file, member.specifier);
206
- if (resolved) files.add(resolved);
207
- }
208
- return [...files];
222
+ const { modules, barrelFiles } = await this.#lookup.reach(file);
223
+ return [...new Set([...(await this.#memberFilesOf(modules)), ...barrelFiles])];
209
224
  }
210
225
 
226
+ //? A barrel moves a fingerprint only by where it declares a copied object: the links hold that, not its exports.
211
227
  async digest(file: string): Promise<string> {
212
- const moduleFacts = await this.#modules.facts(file);
213
- const objects = [...(moduleFacts?.objects ?? [])].map(([name, shape]) => [
214
- name,
215
- shape.open,
216
- [...shape.members].map(([key, member]) => [key, member?.specifier ?? null, member?.imported ?? null]),
217
- ]);
228
+ const { modules, links } = await this.#lookup.reach(file);
229
+ const facts = await Promise.all(
230
+ modules.map(async (module) => {
231
+ const moduleFacts = await this.#modules.facts(module);
232
+ const objects = [...(moduleFacts?.objects ?? [])].map(([name, shape]) => [
233
+ name,
234
+ shape.open,
235
+ [...shape.members].map(([key, member]) => [key, member?.specifier ?? null, member?.imported ?? null]),
236
+ shape.copied.map(({ specifier, imported }) => [specifier, imported]),
237
+ ]);
238
+ return [moduleFacts?.useClient, moduleFacts?.failed, objects];
239
+ }),
240
+ );
218
241
  const exports = await Promise.all(
219
- (await this.filesOf(file)).map(async (member) => {
242
+ (await this.#memberFilesOf(modules)).map(async (member) => {
220
243
  const scanned = await this.#modules.exportsOf(member);
221
244
  const thisFree = [...(await this.#modules.thisFreeOf(member))].sort();
222
245
  return [member, scanned ? [[...scanned.names].sort(), scanned.star, scanned.useClient, thisFree] : null];
223
246
  }),
224
247
  );
225
- return Bun.hash(JSON.stringify([moduleFacts?.useClient, moduleFacts?.failed, objects, exports])).toString(36);
248
+ return Bun.hash(JSON.stringify([facts, links, exports])).toString(36);
249
+ }
250
+
251
+ async #memberFilesOf(modules: string[]): Promise<string[]> {
252
+ const files = new Set<string>();
253
+ for (const file of modules) {
254
+ files.add(file);
255
+ const facts = await this.#modules.facts(file);
256
+ for (const shape of facts?.objects.values() ?? [])
257
+ for (const member of shape.members.values()) {
258
+ if (!member || !ObjectMemberImports.#isPathSpecifier(member.specifier)) continue;
259
+ const resolved = await resolveModuleFile(file, member.specifier);
260
+ if (resolved) files.add(resolved);
261
+ }
262
+ }
263
+ return [...files];
226
264
  }
227
265
 
228
266
  async #targetsOf(
229
267
  candidate: Candidate,
230
- moduleFacts: ObjectModuleFacts,
231
- shape: ObjectShape,
268
+ source: ObjectSource,
232
269
  importer: string,
233
270
  clientImporter: boolean,
234
- read: Set<string>,
271
+ read: ObjectLookupRead,
235
272
  ): Promise<ObjectMemberUse[] | { reason: ObjectKeepReason; node: ts.Node }> {
236
- const file = candidate.file ?? "";
237
273
  const targets: ObjectMemberUse[] = [];
238
274
  const uses = [
239
275
  ...candidate.paths,
@@ -242,7 +278,7 @@ export class ObjectMemberImports {
242
278
  ),
243
279
  ];
244
280
  for (const use of uses) {
245
- const found = await this.#targetOf(file, moduleFacts, shape, use.path, importer, clientImporter, read);
281
+ const found = await this.#targetOf(source, use.path, importer, clientImporter, read);
246
282
  const target = await this.#calledTargetOf(found, use.path, use.called);
247
283
  const node = use.nodes[0] ?? candidate.element;
248
284
  if (typeof target === "string") return { reason: target, node };
@@ -268,27 +304,25 @@ export class ObjectMemberImports {
268
304
  }
269
305
 
270
306
  async #targetOf(
271
- file: string,
272
- moduleFacts: ObjectModuleFacts,
273
- shape: ObjectShape,
307
+ source: ObjectSource,
274
308
  memberPath: string[],
275
309
  importer: string,
276
310
  clientImporter: boolean,
277
- read: Set<string>,
311
+ read: ObjectLookupRead,
278
312
  ): Promise<MemberTarget | ObjectKeepReason> {
279
- const [name, inner] = memberPath;
280
- const nested = inner === undefined ? undefined : shape.members.get(`${name}.${inner}`);
281
- const member = nested ?? (name === undefined ? undefined : shape.members.get(name));
282
- if (!member) return "unresolved-member";
313
+ const owner = await this.#lookup.find(source, memberPath, read);
314
+ if (typeof owner === "string") return owner;
315
+ const { member, nested } = owner;
316
+ const inner = memberPath[1];
283
317
  const bare = ObjectMemberImports.#isPathSpecifier(member.specifier) ? null : member.specifier;
284
318
  const target = bare
285
- ? ObjectMemberImports.#sameBareTarget(bare, file, importer)
286
- : await resolveModuleFile(file, member.specifier);
319
+ ? ObjectMemberImports.#sameBareTarget(bare, owner.file, importer)
320
+ : await resolveModuleFile(owner.file, member.specifier);
287
321
  if (!target) return "unresolved-member";
288
322
  const exports = await this.#modules.exportsOf(target);
289
323
  if (!exports) return "unresolved-member";
290
- read.add(target);
291
- if (moduleFacts.useClient && !clientImporter && !exports.useClient) return "server-boundary";
324
+ read.files.add(target);
325
+ if (owner.useClient && !clientImporter && !exports.useClient) return "server-boundary";
292
326
  if (nested) return { file: target, bare, imported: member.imported, depth: 2 };
293
327
  if (member.imported !== "*") return { file: target, bare, imported: member.imported, depth: 1 };
294
328
  if (inner !== undefined && exports.names.has(inner)) return { file: target, bare, imported: inner, depth: 2 };
@@ -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 { memo } from "react";\nimport { A } from "./A";';
116
- for (const value of ["memo(A)", "new Map()", "tag`x`", "{ Text: memo(A) }", "Object.assign({}, { A: memo(A) })"])
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, an object copied in by name). */
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). Such a module
69
- //* only binds names, so an importer that never reaches the object loses nothing by not running it. A re-export fails:
70
- //* skipping the module would skip the module it re-exports from, which nothing else loads.
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 (!root || root.literal || root.edits.length > 0) ObjectModule.#cover(shape, "");
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) {
@@ -275,6 +275,14 @@ class ScanInfo {
275
275
  return [...this.scalar.keys()];
276
276
  }
277
277
 
278
+ protected takeLibDeps(libNames: Iterable<string>) {
279
+ const known = new Set([this.name, ...this.scanResult.libDeps]);
280
+ const added = [...new Set(libNames)].filter((libName) => !known.has(libName));
281
+ if (!added.length) return;
282
+ this.scanResult.libDeps.push(...added);
283
+ this.#sortedLibs = null;
284
+ }
285
+
278
286
  #sortedLibs: string[] | null = null;
279
287
  protected sortedLibs(libDeps: string[]) {
280
288
  if (this.#sortedLibs) return this.#sortedLibs;
@@ -332,6 +340,7 @@ export class AppInfo extends ScanInfo {
332
340
  AppInfo.scanMigrations(exec),
333
341
  ]);
334
342
  const appInfo = new AppInfo(exec, scanResult as AppScanResult, libDeps, migrations);
343
+ appInfo.takeLibDeps(libDeps);
335
344
  AppInfo.appInfos.set(exec.name, appInfo);
336
345
  return appInfo;
337
346
  }
@@ -429,10 +438,25 @@ export class LibInfo extends ScanInfo {
429
438
  );
430
439
  const libInfo = new LibInfo(exec, scanResult as LibScanResult);
431
440
  LibInfo.libInfos.set(exec.name, libInfo);
441
+ LibInfo.#closeDependencies();
432
442
  LibInfo.#sortedLibIndices = null;
433
443
  return libInfo;
434
444
  }
435
445
 
446
+ //? A scope's generated files import the libs of its libs, so its own imports name them only from a second scan on.
447
+ static #closeDependencies() {
448
+ const reachOf = (libInfo: LibInfo, reached = new Set<string>()) => {
449
+ for (const libName of libInfo.scanResult.libDeps) {
450
+ if (reached.has(libName)) continue;
451
+ reached.add(libName);
452
+ const dependency = LibInfo.libInfos.get(libName);
453
+ if (dependency) reachOf(dependency, reached);
454
+ }
455
+ return reached;
456
+ };
457
+ for (const libInfo of LibInfo.libInfos.values()) libInfo.takeLibDeps(reachOf(libInfo));
458
+ }
459
+
436
460
  constructor(exec: LibExecutor, scanResult: LibScanResult) {
437
461
  super(scanResult);
438
462
  this.exec = exec;