@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.
Files changed (59) hide show
  1. package/CHANGELOG.md +65 -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 +20 -8
  13. package/frontendBuild/buildRouteClient.test.ts +65 -0
  14. package/frontendBuild/clientBuildTypes.ts +11 -0
  15. package/frontendBuild/clientEntriesBundler.ts +21 -11
  16. package/frontendBuild/clientEntryDiscovery.test.ts +213 -0
  17. package/frontendBuild/clientEntryDiscovery.ts +49 -8
  18. package/frontendBuild/devBarrelImports.test.ts +54 -0
  19. package/frontendBuild/devBarrelImports.ts +1 -0
  20. package/frontendBuild/dictionaryAssetBuilder.test.ts +12 -4
  21. package/frontendBuild/dictionaryAssetBuilder.ts +20 -7
  22. package/frontendBuild/dictionaryConstants.ts +55 -1
  23. package/frontendBuild/dictionaryPacking.test.ts +58 -0
  24. package/frontendBuild/dictionaryPacking.ts +43 -0
  25. package/frontendBuild/dictionaryRoutes.test.ts +65 -0
  26. package/frontendBuild/dictionaryRoutes.ts +3 -1
  27. package/frontendBuild/precompressArtifacts.test.ts +22 -0
  28. package/frontendBuild/precompressArtifacts.ts +18 -11
  29. package/frontendBuild/renderedEntries.ts +144 -0
  30. package/frontendBuild/routeClientBuilder.ts +65 -27
  31. package/frontendBuild/routeHandoffs.test.ts +10 -0
  32. package/frontendBuild/routeHandoffs.ts +3 -1
  33. package/frontendBuild/routeModulePreloads.test.ts +32 -0
  34. package/frontendBuild/routeModulePreloads.ts +20 -11
  35. package/frontendBuild/routeRuntimeCheck.test.ts +23 -0
  36. package/frontendBuild/routeRuntimeCheck.ts +10 -3
  37. package/frontendBuild/routeRuntimePays.test.ts +7 -1
  38. package/lint/biomeBase.test.ts +23 -3
  39. package/package.json +3 -3
  40. package/quality/dictionaryKeys.test.ts +185 -2
  41. package/quality/dictionaryKeys.ts +82 -9
  42. package/quality/objectImportReport.ts +6 -3
  43. package/quality/translatorBindings.ts +187 -0
  44. package/transforms/barrelImportsPlugin.ts +56 -35
  45. package/transforms/exportReach.test.ts +162 -0
  46. package/transforms/exportReach.ts +308 -0
  47. package/transforms/moduleParts.test.ts +225 -0
  48. package/transforms/moduleParts.ts +418 -0
  49. package/transforms/objectMemberImports.test.ts +289 -7
  50. package/transforms/objectMemberImports.ts +92 -58
  51. package/transforms/objectMemberLookup.ts +150 -0
  52. package/transforms/objectModule.test.ts +72 -2
  53. package/transforms/objectModule.ts +31 -7
  54. package/transforms/partImports.test.ts +76 -0
  55. package/transforms/partImports.ts +110 -0
  56. package/transforms/partModules.test.ts +187 -0
  57. package/transforms/partModules.ts +90 -0
  58. package/transforms/partPurity.ts +124 -0
  59. package/workspace/scanInfo.ts +24 -0
@@ -2,7 +2,10 @@ import { describe, expect, test } from "bun:test";
2
2
  import { mkdir, realpath, symlink } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { printedInOwnProcess, tempDirs, writeText as write } from "../test/testHelpers";
5
+ import { BarrelAnalyzer } from "./barrelAnalyzer";
6
+ import { createBarrelImportsPlugin } from "./barrelImportsPlugin";
5
7
  import { type ObjectKeepReason, ObjectMemberImports } from "./objectMemberImports";
8
+ import { resolveModuleFile } from "./objectModuleAnalyzer";
6
9
 
7
10
  const makeTempRoot = tempDirs("akan-object-member-imports-");
8
11
 
@@ -31,14 +34,15 @@ const writeObjects = async () => {
31
34
  "ui/Scroll/Render.tsx": "export const Render = () => null;\n",
32
35
  "ui/Boundary/index.tsx": '"use client";\nimport { Part } from "./Part";\nexport const Boundary = { Part };\n',
33
36
  "ui/Boundary/Part.tsx": "export const Part = () => null;\n",
34
- "ui/Memoed/index.tsx": [
35
- 'import { memo } from "react";',
37
+ "ui/Observed/index.tsx": [
38
+ 'import { observer } from "./observer";',
36
39
  'import { A } from "./A";',
37
40
  'import { B } from "./B";',
38
- "export const Memoed = { A: memo(A), B };",
41
+ "export const Observed = { A: observer(A), B };",
39
42
  ].join("\n"),
40
- "ui/Memoed/A.tsx": "export const A = () => null;\n",
41
- "ui/Memoed/B.tsx": "export const B = () => null;\n",
43
+ "ui/Observed/A.tsx": "export const A = () => null;\n",
44
+ "ui/Observed/B.tsx": "export const B = () => null;\n",
45
+ "ui/Observed/observer.ts": "export const observer = <T,>(value: T) => value;\n",
42
46
  "ui/settings.ts": "export const settings = { columns: 2 };\n",
43
47
  "ui/Runner/index.ts": [
44
48
  'import { run } from "./run";',
@@ -148,8 +152,8 @@ describe("ObjectMemberImports", () => {
148
152
  expect(await keptFor('import { Scroll } from "../ui/Scroll";', "<Scroll><Scroll.Render /></Scroll>")).toEqual([
149
153
  { object: "Scroll", file: fileOf("ui/Scroll/index.tsx"), line: 2, reason: "rendered-or-called" },
150
154
  ]);
151
- expect(await keptFor('import { Memoed } from "../ui/Memoed";', "<Memoed.B />")).toEqual([
152
- { object: "Memoed", file: fileOf("ui/Memoed/index.tsx"), line: 1, reason: "call" },
155
+ expect(await keptFor('import { Observed } from "../ui/Observed";', "<Observed.B />")).toEqual([
156
+ { object: "Observed", file: fileOf("ui/Observed/index.tsx"), line: 1, reason: "call" },
153
157
  ]);
154
158
  });
155
159
 
@@ -256,6 +260,284 @@ describe("ObjectMemberImports", () => {
256
260
  });
257
261
  });
258
262
 
263
+ const writeWrappers = async () => {
264
+ const root = await realpath(await makeTempRoot());
265
+ const client = (name: string) => `"use client";\nexport const ${name} = () => null;\n`;
266
+ const plain = (name: string) => `export const ${name} = () => null;\n`;
267
+ const copying = (name: string, from: string[], members = "{}") =>
268
+ [
269
+ ...from.map((source) => `import { ${source} } from "./${source}";`),
270
+ `export const ${name} = Object.assign({}, ${[...from, members].join(", ")});`,
271
+ ].join("\n");
272
+ const files: Record<string, string> = {
273
+ "ui/index.ts": 'export * from "./Field";\nexport * as Parts from "./Parts";\n',
274
+ "ui/Parts.ts": plain("Text"),
275
+ "ui/Field/index.tsx": [
276
+ '"use client";',
277
+ 'import { Label } from "./Label";',
278
+ 'import { Text } from "./Text";',
279
+ 'import { Zone } from "./Zone";',
280
+ "const FieldSection = () => null;",
281
+ "export const Field = Object.assign(FieldSection, { Label, Text, Doc: { Zone } });",
282
+ ].join("\n"),
283
+ "ui/Field/Label.tsx": client("Label"),
284
+ "ui/Field/Text.tsx": client("Text"),
285
+ "ui/Field/TextNext.tsx": client("Text"),
286
+ "ui/Field/Zone.tsx": client("Zone"),
287
+ "ui/FieldNext/index.tsx": 'import { Text } from "./Text";\nexport const Field = { Text };\n',
288
+ "ui/FieldNext/Text.tsx": plain("Text"),
289
+ "wrap/Field.tsx": [
290
+ '"use client";',
291
+ 'import { memo } from "react";',
292
+ 'import { Field as BaseField } from "../ui/Field";',
293
+ 'import { Editor } from "./Editor";',
294
+ 'import { Label } from "./Label";',
295
+ 'import { Upload } from "./Upload";',
296
+ "const Rich = memo(() => <Editor />);",
297
+ "const Section = () => <BaseField />;",
298
+ "export const Field = Object.assign(Section, { Upload }, BaseField, { Rich, Label });",
299
+ ].join("\n"),
300
+ "wrap/Editor.tsx": client("Editor"),
301
+ "wrap/Label.tsx": client("Label"),
302
+ "wrap/Upload.tsx": client("Upload"),
303
+ "barrel/Field.tsx": [
304
+ 'import { Field as BaseField } from "@demo/ui";',
305
+ 'import { Label } from "../wrap/Label";',
306
+ "export const Field = Object.assign(() => null, BaseField, { Label });",
307
+ ].join("\n"),
308
+ "barrel/Parts.ts": [
309
+ 'import { Parts as BaseParts } from "@demo/ui";',
310
+ 'import { Label } from "../wrap/Label";',
311
+ "export const Parts = Object.assign({}, BaseParts, { Label });",
312
+ ].join("\n"),
313
+ "copies/A.ts": plain("A"),
314
+ "copies/B.ts": plain("B"),
315
+ "copies/Shared.ts": plain("Shared"),
316
+ "copies/SharedNext.ts": plain("Shared"),
317
+ "copies/rest.ts": plain("Rest"),
318
+ "copies/First.ts":
319
+ 'import { A } from "./A";\nimport { Shared } from "./Shared";\nexport const First = { A, Shared };\n',
320
+ "copies/Second.ts":
321
+ 'import { B } from "./B";\nimport { Shared } from "./SharedNext";\nexport const Second = { B, Shared };\n',
322
+ "copies/Both.ts": copying("Both", ["First", "Second"]),
323
+ "copies/Failing.ts": 'import { A } from "./A";\nexport const Failing = { A };\nregister(Failing);\n',
324
+ "copies/OverFailing.ts": `import { B } from "./B";\n${copying("OverFailing", ["Failing"], "{ B }")}`,
325
+ "copies/Open.ts":
326
+ 'import { A } from "./A";\nimport * as rest from "./rest";\nexport const Open = { ...rest, A };\n',
327
+ "copies/OverOpen.ts": copying("OverOpen", ["Open"]),
328
+ "copies/Plain.ts": plain("Plain"),
329
+ "copies/OverPlain.ts": `import { B } from "./B";\n${copying("OverPlain", ["Plain"], "{ B }")}`,
330
+ "copies/Left.ts": `import { A } from "./A";\n${copying("Left", ["Right"], "{ A }")}`,
331
+ "copies/Right.ts": `import { B } from "./B";\n${copying("Right", ["Left"], "{ B }")}`,
332
+ "copies/Deep5.ts": 'import { A } from "./A";\nexport const Deep5 = { A };\n',
333
+ ...Object.fromEntries(
334
+ [1, 2, 3, 4].map((depth) => [`copies/Deep${depth}.ts`, copying(`Deep${depth}`, [`Deep${depth + 1}`])]),
335
+ ),
336
+ "copies/Deep0.ts": `import { B } from "./B";\n${copying("Deep0", ["Deep1"], "{ B }")}`,
337
+ "copies/Values.ts": "export const Values = { columns: 2 };\n",
338
+ "copies/OverValues.ts": copying("OverValues", ["Values"], "{ rows: 3 }"),
339
+ "boundary/Server.ts": 'import { Part } from "./Part";\nexport const Server = { Part };\n',
340
+ "boundary/Client.ts": '"use client";\nimport { Part } from "./Part";\nexport const Client = { Part };\n',
341
+ "boundary/Part.tsx": plain("Part"),
342
+ "boundary/ClientOverServer.ts": `"use client";\n${copying("ClientOverServer", ["Server"])}`,
343
+ "boundary/ServerOverClient.ts": copying("ServerOverClient", ["Client"]),
344
+ };
345
+ for (const [file, content] of Object.entries(files)) await write(path.join(root, file), content);
346
+ const fileOf = (file: string) => path.join(root, file);
347
+ const resolvePackage = async (pkgName: string) => {
348
+ if (pkgName !== "@demo/ui" && !pkgName.startsWith("@demo/ui/")) return null;
349
+ const entryFile = await resolveModuleFile(fileOf("x"), `./ui${pkgName.slice("@demo/ui".length)}`);
350
+ return entryFile ? { pkgName, entryFile, pkgDir: fileOf("ui") } : null;
351
+ };
352
+ const objectsOf = ({ barrels = ["@demo/ui"] }: { barrels?: string[] } = {}) =>
353
+ new ObjectMemberImports({
354
+ resolve: ObjectMemberImports.resolverOf(resolvePackage),
355
+ barrels: { names: barrels, analyzer: new BarrelAnalyzer({ resolvePackage }) },
356
+ });
357
+ const rewrite = (lines: string[], objects = objectsOf()) =>
358
+ objects.rewrite(lines.join("\n"), fileOf("page/_index.tsx"));
359
+ const answerOf = async (
360
+ object: string,
361
+ member: string,
362
+ { dir = "copies", head = "" } = {},
363
+ ): Promise<string | null> => {
364
+ const result = await rewrite([
365
+ `${head}import { ${object} } from "../${dir}/${object}";`,
366
+ `export const value = ${object}.${member};`,
367
+ ]);
368
+ const [kept] = result?.kept ?? [];
369
+ const narrowedTo = result?.contents?.match(/ from "([^"]+)";/)?.[1];
370
+ return kept?.reason ?? (narrowedTo ? path.relative(root, narrowedTo) : null);
371
+ };
372
+ return { root, fileOf, objectsOf, rewrite, answerOf };
373
+ };
374
+
375
+ describe("ObjectMemberImports on an object that copies an imported one in", () => {
376
+ test("imports a member of the copied object from that object's part file, and a member the wrapper lists after the copy from the wrapper's", async () => {
377
+ const { root, fileOf, rewrite } = await writeWrappers();
378
+
379
+ const result = await rewrite([
380
+ 'import { Field } from "../wrap/Field";',
381
+ "export const Page = () => <Field.Text><Field.Label /><Field.Doc.Zone /></Field.Text>;",
382
+ ]);
383
+
384
+ expect(result?.contents?.split("\n")).toEqual([
385
+ `import { Text as Field$Text } from ${JSON.stringify(fileOf("ui/Field/Text.tsx"))};`,
386
+ `import { Label as Field$Label } from ${JSON.stringify(fileOf("wrap/Label.tsx"))};`,
387
+ `import { Zone as Field$Doc$Zone } from ${JSON.stringify(fileOf("ui/Field/Zone.tsx"))};`,
388
+ "export const Page = () => <Field$Text><Field$Label /><Field$Doc$Zone /></Field$Text>;",
389
+ ]);
390
+ expect(result?.narrowed).toEqual([
391
+ { object: "Field", file: fileOf("wrap/Field.tsx"), members: ["Doc.Zone", "Label", "Text"] },
392
+ ]);
393
+ expect(result?.read.map((file) => path.relative(root, file)).sort()).toEqual([
394
+ "ui/Field/Text.tsx",
395
+ "ui/Field/Zone.tsx",
396
+ "ui/Field/index.tsx",
397
+ "wrap/Field.tsx",
398
+ "wrap/Label.tsx",
399
+ ]);
400
+ });
401
+
402
+ test("keeps the whole wrapper for a member declared in its own file, one it lists before the copy, and one no object holds", async () => {
403
+ const { answerOf } = await writeWrappers();
404
+
405
+ for (const member of ["Rich", "Upload", "Missing", "Doc.Missing"])
406
+ expect(await answerOf("Field", member, { dir: "wrap" })).toBe("unresolved-member");
407
+ });
408
+
409
+ test("reads two copied objects last one first, as `Object.assign` lets the later source win", async () => {
410
+ const { answerOf } = await writeWrappers();
411
+
412
+ expect(await answerOf("Both", "A")).toBe("copies/A.ts");
413
+ expect(await answerOf("Both", "B")).toBe("copies/B.ts");
414
+ expect(await answerOf("Both", "Shared")).toBe("copies/SharedNext.ts");
415
+ expect(await answerOf("Both", "Missing")).toBe("unresolved-member");
416
+ });
417
+
418
+ test("keeps the whole wrapper for a member of a copied object whose module fails the rule, lists no such member, or is no object module", async () => {
419
+ const { answerOf } = await writeWrappers();
420
+
421
+ expect(await answerOf("OverFailing", "A")).toBe("effect-statement");
422
+ expect(await answerOf("OverFailing", "B")).toBe("copies/B.ts");
423
+ expect(await answerOf("OverOpen", "A")).toBe("copies/A.ts");
424
+ expect(await answerOf("OverOpen", "Rest")).toBe("unresolved-member");
425
+ expect(await answerOf("OverPlain", "B")).toBe("copies/B.ts");
426
+ expect(await answerOf("OverPlain", "displayName")).toBe("unresolved-member");
427
+ });
428
+
429
+ test("stops at an object that copies itself in through another, and four copies down", async () => {
430
+ const { answerOf } = await writeWrappers();
431
+
432
+ expect(await answerOf("Left", "A")).toBe("copies/A.ts");
433
+ expect(await answerOf("Left", "B")).toBe("copies/B.ts");
434
+ expect(await answerOf("Left", "Missing")).toBe("unresolved-member");
435
+ expect(await answerOf("Deep1", "A")).toBe("copies/A.ts");
436
+ expect(await answerOf("Deep0", "A")).toBe("unresolved-member");
437
+ expect(await answerOf("Deep0", "B")).toBe("copies/B.ts");
438
+ });
439
+
440
+ test("leaves a wrapper alone when neither it nor an object it copies in points a member at a file", async () => {
441
+ const { rewrite } = await writeWrappers();
442
+
443
+ expect(
444
+ await rewrite(['import { OverValues } from "../copies/OverValues";', "export const n = OverValues.columns;"]),
445
+ ).toBeNull();
446
+ });
447
+
448
+ test("finds an object copied in from a barrel at the file the barrel declares it in, as an importer's own barrel import is", async () => {
449
+ const { fileOf, objectsOf, rewrite } = await writeWrappers();
450
+ const lines = ['import { Field } from "../barrel/Field";', "export const Page = () => <Field.Text />;"];
451
+
452
+ const narrowed = await rewrite(lines);
453
+ const unlisted = await rewrite(lines, objectsOf({ barrels: [] }));
454
+ const namespace = await rewrite(['import { Parts } from "../barrel/Parts";', "export const text = Parts.Text;"]);
455
+
456
+ expect(narrowed?.contents).toContain(
457
+ `import { Text as Field$Text } from ${JSON.stringify(fileOf("ui/Field/Text.tsx"))};`,
458
+ );
459
+ expect(narrowed?.barrels).toEqual(["@demo/ui"]);
460
+ expect(unlisted?.kept.map(({ reason }) => reason)).toEqual(["unresolved-member"]);
461
+ expect(unlisted?.barrels).toEqual([]);
462
+ expect(namespace?.kept.map(({ reason }) => reason)).toEqual(["unresolved-member"]);
463
+ });
464
+
465
+ test('narrows past a "use client" module anywhere between a server importer and the member only to a client file', async () => {
466
+ const { answerOf } = await writeWrappers();
467
+ const client = { dir: "boundary", head: '"use client";\n' };
468
+
469
+ expect(await answerOf("Field", "Text", { dir: "wrap" })).toBe("ui/Field/Text.tsx");
470
+ expect(await answerOf("ClientOverServer", "Part", { dir: "boundary" })).toBe("server-boundary");
471
+ expect(await answerOf("ServerOverClient", "Part", { dir: "boundary" })).toBe("server-boundary");
472
+ expect(await answerOf("ClientOverServer", "Part", client)).toBe("boundary/Part.tsx");
473
+ expect(await answerOf("ServerOverClient", "Part", client)).toBe("boundary/Part.tsx");
474
+ });
475
+
476
+ test("counts the copied object's module, its part files and the barrel among a wrapper's files, so a part moved there moves the wrapper's digest and fingerprint", async () => {
477
+ const { root, fileOf, objectsOf } = await writeWrappers();
478
+ const wrapper = fileOf("barrel/Field.tsx");
479
+ const stateOf = async () => {
480
+ const objects = objectsOf();
481
+ return [await objects.digest(wrapper), await objects.fingerprint(wrapper, "Field", ["Text"], true)];
482
+ };
483
+
484
+ const files = await objectsOf().filesOf(wrapper);
485
+ expect(new Set(files.map((file) => path.relative(root, file)))).toEqual(
486
+ new Set([
487
+ "barrel/Field.tsx",
488
+ "ui/Field/Label.tsx",
489
+ "ui/Field/Text.tsx",
490
+ "ui/Field/Zone.tsx",
491
+ "ui/Field/index.tsx",
492
+ "ui/index.ts",
493
+ "wrap/Label.tsx",
494
+ ]),
495
+ );
496
+ const before = await stateOf();
497
+ await write(fileOf("ui/Field/Text.tsx"), '"use client";\nexport const Text = () => "saved";\n');
498
+ expect(await stateOf()).toEqual(before);
499
+
500
+ const index = await Bun.file(fileOf("ui/Field/index.tsx")).text();
501
+ await write(fileOf("ui/Field/index.tsx"), index.replace("./Text", "./TextNext"));
502
+ const moved = await stateOf();
503
+ expect(moved[0]).not.toBe(before[0]);
504
+ expect(moved[1]).not.toBe(before[1]);
505
+
506
+ await write(fileOf("ui/index.ts"), 'export * from "./FieldNext";\n');
507
+ const redeclared = await stateOf();
508
+ expect(redeclared[0]).not.toBe(moved[0]);
509
+ expect(redeclared[1]).not.toBe(moved[1]);
510
+ });
511
+
512
+ test("a bundle built with the barrel plugin holds the parts a page names through such a wrapper, and neither the wrapper nor the copied object", async () => {
513
+ const { root, fileOf } = await writeWrappers();
514
+ await write(
515
+ fileOf("page/_index.tsx"),
516
+ 'import { Field } from "../barrel/Field";\nexport const parts = [Field.Text, Field.Label];\n',
517
+ );
518
+ const app = {
519
+ name: "demo",
520
+ cwdPath: root,
521
+ workspace: { workspaceRoot: root },
522
+ getConfig: async () => ({ barrelImports: ["@demo/ui"] }),
523
+ getTsConfig: async () => ({
524
+ compilerOptions: { paths: { "@demo/ui": ["./ui/index.ts"], "@demo/ui/*": ["./ui/*"] } },
525
+ }),
526
+ };
527
+
528
+ const built = await Bun.build({
529
+ entrypoints: [fileOf("page/_index.tsx")],
530
+ target: "browser",
531
+ metafile: true,
532
+ throw: true,
533
+ plugins: [await createBarrelImportsPlugin(app as never)],
534
+ });
535
+
536
+ const inputs = Object.keys(built.metafile?.inputs ?? {}).map((input) => path.relative(root, path.resolve(input)));
537
+ expect(inputs.sort()).toEqual(["page/_index.tsx", "ui/Field/Text.tsx", "wrap/Label.tsx"]);
538
+ });
539
+ });
540
+
259
541
  describe("ObjectMemberImports on a server-rendered page", () => {
260
542
  const repoRoot = path.resolve(import.meta.dir, "../../../..");
261
543
 
@@ -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 };