@akanjs/devkit 3.0.0-beta.23 → 3.0.0-beta.25

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 (60) hide show
  1. package/DEV_RUNTIME_KNOBS.md +37 -22
  2. package/akanApp/akanApp.host.ts +34 -1
  3. package/akanApp/devBootLatch.test.ts +39 -0
  4. package/akanApp/devBootLatch.ts +39 -0
  5. package/akanApp/devHostPolicy.test.ts +25 -0
  6. package/akanApp/devHostPolicy.ts +27 -2
  7. package/cloud/globalConfig.ts +3 -2
  8. package/csrE2e/csrE2eHarness.fixture.ts +455 -0
  9. package/csrE2e/csrFastRefresh.e2e.test.ts +233 -0
  10. package/csrE2e/csrPageStack.e2e.test.ts +187 -0
  11. package/csrE2e/csrPatchFirst.e2e.test.ts +87 -0
  12. package/csrE2e/devHmrLatency.e2e.test.ts +391 -0
  13. package/csrE2e/ssrRegistry.e2e.test.ts +644 -0
  14. package/fileSys.ts +16 -1
  15. package/frontendBuild/buildRouteClient.test.ts +61 -0
  16. package/frontendBuild/bundleDefine.test.ts +12 -0
  17. package/frontendBuild/bundleDefine.ts +5 -1
  18. package/frontendBuild/clientEntryDiscovery.test.ts +37 -0
  19. package/frontendBuild/clientEntryDiscovery.ts +10 -5
  20. package/frontendBuild/csrArtifactBuilder.ts +3 -6
  21. package/frontendBuild/csrDevArtifactWriter.test.ts +143 -0
  22. package/frontendBuild/csrDevArtifactWriter.ts +303 -0
  23. package/frontendBuild/csrDevBundler.test.ts +66 -0
  24. package/frontendBuild/csrDevBundler.ts +95 -0
  25. package/frontendBuild/csrDevModuleCompiler.ts +304 -0
  26. package/frontendBuild/csrDevPatcher.test.ts +340 -0
  27. package/frontendBuild/csrDevPatcher.ts +374 -0
  28. package/frontendBuild/csrDevPaths.ts +124 -0
  29. package/frontendBuild/csrDevResolver.test.ts +165 -0
  30. package/frontendBuild/csrDevResolver.ts +234 -0
  31. package/frontendBuild/csrDevTypes.ts +59 -0
  32. package/frontendBuild/csrEntryFiles.ts +24 -0
  33. package/frontendBuild/cssCompiler.ts +2 -4
  34. package/frontendBuild/devRegistryBundler.ts +177 -0
  35. package/frontendBuild/hmrWatcher.test.ts +51 -0
  36. package/frontendBuild/hmrWatcher.ts +17 -3
  37. package/frontendBuild/index.ts +4 -0
  38. package/frontendBuild/pagesBundleBuilder.ts +24 -1
  39. package/frontendBuild/pagesEntrySourceGenerator.ts +56 -6
  40. package/frontendBuild/registryMetadataFingerprint.test.ts +63 -0
  41. package/frontendBuild/registryMetadataFingerprint.ts +28 -0
  42. package/frontendBuild/routeClientBuilder.ts +79 -18
  43. package/frontendBuild/serverGraphFile.test.ts +77 -0
  44. package/frontendBuild/serverGraphFile.ts +93 -0
  45. package/frontendBuild/ssrDevBundler.ts +91 -0
  46. package/incrementalBuilder/buildBatch.proc.ts +119 -6
  47. package/incrementalBuilder/buildBatchProtocol.ts +6 -3
  48. package/incrementalBuilder/buildBatchRunner.test.ts +31 -0
  49. package/incrementalBuilder/buildBatchRunner.ts +17 -8
  50. package/incrementalBuilder/builderWorkQueue.test.ts +94 -0
  51. package/incrementalBuilder/builderWorkQueue.ts +126 -0
  52. package/incrementalBuilder/incrementalBuilder.host.test.ts +1 -1
  53. package/incrementalBuilder/incrementalBuilder.host.ts +33 -3
  54. package/incrementalBuilder/incrementalBuilder.proc.test.ts +129 -2
  55. package/incrementalBuilder/incrementalBuilder.proc.ts +518 -52
  56. package/integration/devStability.integration.test.ts +18 -7
  57. package/package.json +3 -3
  58. package/transforms/rscUseClientTransform.ts +7 -0
  59. package/transforms/transforms.test.ts +13 -0
  60. package/transforms/useClientBundlePlugin.ts +4 -1
@@ -1,3 +1,4 @@
1
+ import fs from "node:fs";
1
2
  import path from "node:path";
2
3
  import type { BunPlugin } from "bun";
3
4
  import type { PageEntry } from "../artifact/implicitRootLayout";
@@ -9,7 +10,9 @@ import { loaderFor } from "../transforms/moduleSyntax";
9
10
  import { transformUseClient } from "../transforms/rscUseClientTransform";
10
11
  import { createUseClientBundlePlugin } from "../transforms/useClientBundlePlugin";
11
12
  import { bundleDefine } from "./bundleDefine";
13
+ import { CsrDevPaths } from "./csrDevPaths";
12
14
  import { PagesEntrySourceGenerator } from "./pagesEntrySourceGenerator";
15
+ import { ServerGraphFile } from "./serverGraphFile";
13
16
 
14
17
  export interface BuildPagesBundleResult {
15
18
  bundlePath: string;
@@ -42,6 +45,13 @@ export class PagesBundleBuilder {
42
45
  this.#pageEntries ?? (await resolveSsrPageEntriesForApp(this.#app, await this.#app.getPageKeys()));
43
46
  const entrySource = PagesEntrySourceGenerator.generate(resolvedEntries);
44
47
  const workspaceRoot = this.#app.workspace.workspaceRoot;
48
+ const dev = this.#command === "start";
49
+ const clientExports: Record<string, string[]> = {};
50
+ const onClientModule = dev
51
+ ? (file: string, exports: string[]) => {
52
+ clientExports[CsrDevPaths.realpath(file)] = exports;
53
+ }
54
+ : undefined;
45
55
  const result = await Bun.build({
46
56
  entrypoints: [VIRTUAL_PAGES_ENTRY],
47
57
  outdir: `${this.#artifactDir}/server`,
@@ -55,6 +65,7 @@ export class PagesBundleBuilder {
55
65
  asset: "assets/[name]-[hash].[ext]",
56
66
  },
57
67
  define: bundleDefine(this.#app, this.#command, "ssr"),
68
+ metafile: dev,
58
69
  plugins: [
59
70
  PagesBundleBuilder.createPagesEntryPlugin(entrySource),
60
71
  PagesBundleBuilder.createCssStubPlugin(),
@@ -66,9 +77,10 @@ export class PagesBundleBuilder {
66
77
  transformUseClient(source, {
67
78
  path: args.path,
68
79
  workspaceRoot,
80
+ onClientModule,
69
81
  }),
70
82
  })
71
- : createUseClientBundlePlugin({ workspaceRoot }),
83
+ : createUseClientBundlePlugin({ workspaceRoot, onClientModule }),
72
84
  ],
73
85
  });
74
86
 
@@ -79,6 +91,8 @@ export class PagesBundleBuilder {
79
91
 
80
92
  const bundlePath = path.resolve(entryArtifact.path);
81
93
  const buildId = Date.now();
94
+ if (dev && result.metafile)
95
+ await ServerGraphFile.write(this.#artifactDir, this.#serverGraph(result.metafile, clientExports));
82
96
  const outputBytes = result.outputs.reduce((sum, output) => sum + output.size, 0);
83
97
  const chunkCount = result.outputs.filter((output) => output.kind === "chunk").length;
84
98
  this.#app.verbose(
@@ -95,6 +109,15 @@ export class PagesBundleBuilder {
95
109
  };
96
110
  }
97
111
 
112
+ #serverGraph(metafile: Bun.BuildMetafile, clientExports: Record<string, string[]>) {
113
+ const inputs = Object.keys(metafile.inputs)
114
+ .filter((input) => !input.includes("node_modules"))
115
+ .map((input) => path.resolve(input))
116
+ .filter((input) => fs.existsSync(input))
117
+ .map((input) => CsrDevPaths.realpath(input));
118
+ return { inputs, clientExports };
119
+ }
120
+
98
121
  get #artifactDir(): string {
99
122
  return `${this.#command === "build" ? this.#app.dist.cwdPath : this.#app.cwdPath}/.akan/artifact`;
100
123
  }
@@ -2,11 +2,19 @@ import path from "node:path";
2
2
  import type { PageEntry } from "../artifact/implicitRootLayout";
3
3
  import { AsyncDefaultExportDetector } from "../transforms/asyncDefaultExportDetector";
4
4
 
5
+ export interface PagesEntrySourceOptions {
6
+ /** Detects an async default export; a caller that outlives one generation keeps its own cache across saves. */
7
+ isAsyncDefault?: (moduleAbsPath: string) => Promise<boolean>;
8
+ }
9
+
5
10
  export class PagesEntrySourceGenerator {
6
11
  #pageEntries: PageEntry[];
12
+ readonly #asyncDefaults = new Map<string, Promise<boolean>>();
13
+ readonly #detect: (moduleAbsPath: string) => Promise<boolean>;
7
14
 
8
- constructor(pageEntries: PageEntry[]) {
15
+ constructor(pageEntries: PageEntry[], { isAsyncDefault }: PagesEntrySourceOptions = {}) {
9
16
  this.#pageEntries = pageEntries;
17
+ this.#detect = isAsyncDefault ?? ((moduleAbsPath) => AsyncDefaultExportDetector.detect(moduleAbsPath));
10
18
  }
11
19
 
12
20
  static generate(pageEntries: PageEntry[]): string {
@@ -21,25 +29,67 @@ export class PagesEntrySourceGenerator {
21
29
  return `export const pages = {\n${lines.join("\n")}\n};\n`;
22
30
  }
23
31
 
24
- static async generateStatic(pageEntries: PageEntry[]): Promise<string> {
25
- return await new PagesEntrySourceGenerator(pageEntries).generateStatic();
32
+ static async generateStatic(pageEntries: PageEntry[], { fromDir }: { fromDir?: string } = {}): Promise<string> {
33
+ return await new PagesEntrySourceGenerator(pageEntries).generateStatic({ fromDir });
26
34
  }
27
35
 
28
- async generateStatic(): Promise<string> {
36
+ // `fromDir` makes the specifiers relative: Bun inlines an absolute import of a file that is also an entrypoint.
37
+ async generateStatic({ fromDir }: { fromDir?: string } = {}): Promise<string> {
29
38
  const imports = this.#pageEntries.map(({ moduleAbsPath }, index) => {
30
- const specifier = PagesEntrySourceGenerator.#toImportSpecifier(moduleAbsPath);
39
+ const specifier = fromDir
40
+ ? PagesEntrySourceGenerator.#toRelativeSpecifier(fromDir, moduleAbsPath)
41
+ : PagesEntrySourceGenerator.#toImportSpecifier(moduleAbsPath);
31
42
  return `import * as page${index} from ${JSON.stringify(specifier)};`;
32
43
  });
33
44
  const entries = await Promise.all(
34
45
  this.#pageEntries.map(async ({ key, moduleAbsPath }, index) => {
35
- const isAsyncDefault = await AsyncDefaultExportDetector.detect(moduleAbsPath);
46
+ const isAsyncDefault = await this.#isAsyncDefault(moduleAbsPath);
36
47
  return ` ${JSON.stringify(key)}: { loader: async () => page${index}, isAsyncDefault: ${isAsyncDefault} },`;
37
48
  }),
38
49
  );
39
50
  return `${imports.join("\n")}\nexport const pages = {\n${entries.join("\n")}\n};\n`;
40
51
  }
41
52
 
53
+ // Route HMR in the dev registry bundle: `akanWebkit` is the entry's namespace import of `akanjs/webkit`.
54
+ async generateHotReplace({
55
+ fromDir,
56
+ ownerId,
57
+ moduleIds,
58
+ }: {
59
+ fromDir: string;
60
+ ownerId: string;
61
+ moduleIds: string[];
62
+ }): Promise<string> {
63
+ const entries = await Promise.all(
64
+ this.#pageEntries.map(async ({ key, moduleAbsPath }) => {
65
+ const specifier = PagesEntrySourceGenerator.#toRelativeSpecifier(fromDir, moduleAbsPath);
66
+ const isAsyncDefault = await this.#isAsyncDefault(moduleAbsPath);
67
+ return ` ${JSON.stringify(key)}: { loader: async () => require(${JSON.stringify(specifier)}), isAsyncDefault: ${isAsyncDefault} },`;
68
+ }),
69
+ );
70
+ return `__akan.accept(${JSON.stringify(ownerId)}, ${JSON.stringify(moduleIds)}, async () => {
71
+ const replaced = await akanWebkit.replacePages({
72
+ ${entries.join("\n")}
73
+ });
74
+ if (!replaced) throw new Error("the route table no longer matches the pages it was built from");
75
+ });
76
+ `;
77
+ }
78
+
79
+ #isAsyncDefault(moduleAbsPath: string): Promise<boolean> {
80
+ const known = this.#asyncDefaults.get(moduleAbsPath);
81
+ if (known) return known;
82
+ const detected = this.#detect(moduleAbsPath);
83
+ this.#asyncDefaults.set(moduleAbsPath, detected);
84
+ return detected;
85
+ }
86
+
42
87
  static #toImportSpecifier(moduleAbsPath: string): string {
43
88
  return path.resolve(moduleAbsPath).split(path.sep).join("/");
44
89
  }
90
+
91
+ static #toRelativeSpecifier(fromDir: string, moduleAbsPath: string): string {
92
+ const relative = path.relative(fromDir, path.resolve(moduleAbsPath)).split(path.sep).join("/");
93
+ return relative.startsWith(".") ? relative : `./${relative}`;
94
+ }
45
95
  }
@@ -0,0 +1,63 @@
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import fs from "node:fs";
3
+ import { mkdtemp, rm } from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { isAkanRuntimeMetadataFile } from "akanjs/server/hmr/runtimeMetadataFile";
7
+ import { RegistryMetadataFingerprint } from "./registryMetadataFingerprint";
8
+
9
+ describe("RegistryMetadataFingerprint", () => {
10
+ let root: string;
11
+ let later = Date.now() / 1000 + 60;
12
+ const file = (relative: string) => path.join(root, relative);
13
+ const touch = (relative: string) => {
14
+ later += 1;
15
+ fs.utimesSync(file(relative), later, later);
16
+ };
17
+ const ssrMetadata = (target: string) =>
18
+ isAkanRuntimeMetadataFile(target) && !target.endsWith(".dictionary.ts") && path.basename(target) !== "dict.ts";
19
+ const stamp = async (isMetadataFile = isAkanRuntimeMetadataFile) =>
20
+ await RegistryMetadataFingerprint.of([root], isMetadataFile);
21
+
22
+ beforeAll(async () => {
23
+ root = await mkdtemp(path.join(os.tmpdir(), "akan-registry-metadata-"));
24
+ for (const relative of [
25
+ "lib/sig.ts",
26
+ "lib/dict.ts",
27
+ "lib/useClient.ts",
28
+ "lib/user/user.signal.ts",
29
+ "lib/user/user.dictionary.ts",
30
+ "lib/user/User.Zone.tsx",
31
+ "lib/user/user.signal.test.ts",
32
+ ])
33
+ await Bun.write(file(relative), "export {};\n");
34
+ });
35
+
36
+ afterAll(async () => {
37
+ await rm(root, { recursive: true, force: true });
38
+ });
39
+
40
+ test("moves with a signal save and stays with a component save", async () => {
41
+ const before = await stamp();
42
+ touch("lib/user/User.Zone.tsx");
43
+ touch("lib/user/user.signal.test.ts");
44
+ expect(await stamp()).toBe(before);
45
+ touch("lib/user/user.signal.ts");
46
+ expect(await stamp()).not.toBe(before);
47
+ });
48
+
49
+ test("a registry that inlines no dictionary is not moved by a dictionary save", async () => {
50
+ const ssrBefore = await stamp(ssrMetadata);
51
+ const csrBefore = await stamp();
52
+ touch("lib/user/user.dictionary.ts");
53
+ touch("lib/dict.ts");
54
+ expect(await stamp(ssrMetadata)).toBe(ssrBefore);
55
+ expect(await stamp()).not.toBe(csrBefore);
56
+ });
57
+
58
+ test("a root without a lib folder counts for nothing", async () => {
59
+ expect(await RegistryMetadataFingerprint.of([root, path.join(root, "lib/user")], isAkanRuntimeMetadataFile)).toBe(
60
+ await stamp(),
61
+ );
62
+ });
63
+ });
@@ -0,0 +1,28 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ //* The sources `lib/useClient.ts` reads through its macros, which no registry graph lists as a dependency. A registry
5
+ //* records their stamp, so a builder that loads one built before a signal or dictionary save rebuilds it, whichever
6
+ //* process saw that save (a builder restarted for it never finishes the rebuild it started).
7
+ export class RegistryMetadataFingerprint {
8
+ static readonly #sources = new Bun.Glob("**/*.{signal,dictionary}.ts");
9
+ static readonly #libFiles = ["sig.ts", "dict.ts", "useClient.ts"];
10
+
11
+ /** `roots` are app and lib directories; only the metadata files under each one's `lib/` count. */
12
+ static async of(roots: string[], isMetadataFile: (file: string) => boolean): Promise<string> {
13
+ const stamps: string[] = [];
14
+ for (const root of new Set(roots)) {
15
+ const libDir = path.join(root, "lib");
16
+ if (!fs.existsSync(libDir)) continue;
17
+ const files = RegistryMetadataFingerprint.#libFiles.map((name) => path.join(libDir, name));
18
+ for await (const relative of RegistryMetadataFingerprint.#sources.scan({ cwd: libDir, onlyFiles: true }))
19
+ files.push(path.join(libDir, relative));
20
+ for (const file of files) {
21
+ if (!isMetadataFile(file)) continue;
22
+ const stat = fs.statSync(file, { throwIfNoEntry: false });
23
+ if (stat) stamps.push(`${file}:${stat.mtimeMs}:${stat.size}`);
24
+ }
25
+ }
26
+ return Bun.hash(stamps.sort((a, b) => a.localeCompare(b)).join("\n")).toString(36);
27
+ }
28
+ }
@@ -1,12 +1,15 @@
1
1
  import { mkdir } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import type { BaseBuildArtifact, ClientManifest, SsrManifest } from "akanjs/server";
3
+ import type { BaseBuildArtifact, ClientManifest, ClientManifestEntry, SsrManifest } from "akanjs/server";
4
+ import { SSR_DEV_CHUNK, SSR_DEV_ID_PREFIX } from "akanjs/server/hmr/csrDevManifest";
4
5
  import type { App } from "../commandDecorators";
5
6
  import { createBarrelImportsPlugin } from "../transforms/barrelImportsPlugin";
7
+ import { loaderFor } from "../transforms/moduleSyntax";
6
8
  import { scanUseClientExports, toClientReferencePath } from "../transforms/rscUseClientTransform";
7
9
  import type { ClientBundleTarget, ClientEntryDiscovery } from "./clientBuildTypes";
8
10
  import { ClientEntriesBundler } from "./clientEntriesBundler";
9
11
  import { GraphClientEntryDiscovery } from "./clientEntryDiscovery";
12
+ import { CsrDevPaths } from "./csrDevPaths";
10
13
  import { VENDOR_SPECIFIERS } from "./vendorSpecifiers";
11
14
 
12
15
  const SSR_CLIENT_ALIAS_EXTERNALS = [
@@ -30,6 +33,8 @@ export interface BuildRouteClientOptions {
30
33
  discovery?: ClientEntryDiscovery;
31
34
  /** Pre-resolved client entries: skips discovery and bundles exactly this list. */
32
35
  entries?: string[];
36
+ /** Defaults to `registry` under `start`: the browser loads each entry from the SSR dev registry, so only `client-ssr` builds. */
37
+ browser?: "chunks" | "registry";
33
38
  }
34
39
 
35
40
  export interface BuildRouteClientResult {
@@ -39,6 +44,8 @@ export interface BuildRouteClientResult {
39
44
  discoveredEntries?: string[];
40
45
  clientDeps: string[];
41
46
  clientDepsByEntry?: Record<string, string[]>;
47
+ /** Registry mode: the entries the manifest rows name, which the SSR dev registry must hold before they are served. */
48
+ registryEntries?: string[];
42
49
  }
43
50
 
44
51
  interface BootstrapEntries {
@@ -54,6 +61,7 @@ export class RouteClientBuilder {
54
61
  #command: "build" | "start";
55
62
  #discovery?: ClientEntryDiscovery;
56
63
  #entries?: string[];
64
+ #browser: "chunks" | "registry";
57
65
 
58
66
  constructor(options: BuildRouteClientOptions) {
59
67
  this.#app = options.app;
@@ -63,6 +71,7 @@ export class RouteClientBuilder {
63
71
  this.#command = options.command ?? "start";
64
72
  this.#discovery = options.discovery;
65
73
  this.#entries = options.entries;
74
+ this.#browser = options.browser ?? (this.#command === "start" ? "registry" : "chunks");
66
75
  }
67
76
 
68
77
  async build(): Promise<BuildRouteClientResult> {
@@ -73,8 +82,11 @@ export class RouteClientBuilder {
73
82
  : discovered.filter((e) => !this.#knownEntries.has(e));
74
83
 
75
84
  const bootstrapEntries = await this.#createBootstrapEntries(entries);
76
- const browserBundle = await this.#buildBrowserBundle(bootstrapEntries);
85
+ //? Registry mode builds no browser bundle: the SSR bundle has the same entries, exports and imports to read.
86
+ const registry = this.#browser === "registry" ? new CsrDevPaths(this.#app.workspace.workspaceRoot) : null;
87
+ const browserBundle = registry ? null : await this.#buildBrowserBundle(bootstrapEntries);
77
88
  const ssrBundle = await this.#buildSsrBundle(bootstrapEntries);
89
+ const referenceBundle = browserBundle ?? ssrBundle;
78
90
 
79
91
  const acceptedEntries = new Set(entries);
80
92
  const routeEntries = new Set(discovered);
@@ -82,15 +94,18 @@ export class RouteClientBuilder {
82
94
  const ssrModuleMap: SsrManifest["moduleMap"] = {};
83
95
  const clientDeps = new Set<string>();
84
96
  const clientDepsByEntry: Record<string, string[]> = {};
85
- for (const [key, row] of Object.entries(browserBundle.manifest)) {
97
+ for (const [key, bundleRow] of Object.entries(referenceBundle.manifest)) {
86
98
  const manifestEntry = RouteClientBuilder.resolveOriginalManifestEntry(
87
99
  key,
88
100
  bootstrapEntries.originalByBuildEntry,
89
- browserBundle.clientReferenceIdByAbsPath,
101
+ referenceBundle.clientReferenceIdByAbsPath,
90
102
  this.#app.workspace.workspaceRoot,
91
103
  );
92
104
  if (!manifestEntry) continue;
93
105
  if (!acceptedEntries.has(manifestEntry.originalEntry)) continue;
106
+ const row = registry
107
+ ? RouteClientBuilder.#registryRow(registry, manifestEntry.originalEntry, bundleRow)
108
+ : bundleRow;
94
109
  manifestDelta[manifestEntry.key] = row;
95
110
 
96
111
  const ssrOutput = ssrBundle.entryOutputAbsByAbsPath.get(manifestEntry.buildEntry);
@@ -104,7 +119,7 @@ export class RouteClientBuilder {
104
119
  const originalEntry = path.resolve(bootstrapEntries.originalByBuildEntry.get(buildEntry) ?? buildEntry);
105
120
  if (!acceptedEntries.has(originalEntry)) continue;
106
121
  const deps = new Set<string>([originalEntry]);
107
- for (const dep of browserBundle.entryDepsByAbsPath.get(buildEntry) ?? []) deps.add(path.resolve(dep));
122
+ for (const dep of referenceBundle.entryDepsByAbsPath.get(buildEntry) ?? []) deps.add(path.resolve(dep));
108
123
  const sortedDeps = [...deps].sort();
109
124
  clientDepsByEntry[originalEntry] = sortedDeps;
110
125
  if (routeEntries.has(originalEntry)) for (const dep of sortedDeps) clientDeps.add(dep);
@@ -117,6 +132,16 @@ export class RouteClientBuilder {
117
132
  discoveredEntries: discovered,
118
133
  clientDeps: [...clientDeps].sort(),
119
134
  clientDepsByEntry,
135
+ ...(registry ? { registryEntries: [...acceptedEntries].sort() } : {}),
136
+ };
137
+ }
138
+
139
+ static #registryRow(paths: CsrDevPaths, entry: string, row: ClientManifestEntry): ClientManifestEntry {
140
+ return {
141
+ id: `${SSR_DEV_ID_PREFIX}${paths.idOf(entry)}`,
142
+ chunks: [SSR_DEV_CHUNK, SSR_DEV_CHUNK],
143
+ name: row.name,
144
+ async: true,
120
145
  };
121
146
  }
122
147
 
@@ -199,19 +224,55 @@ export class RouteClientBuilder {
199
224
  return scanUseClientExports(await Bun.file(absEntry).text(), absEntry, this.#app.workspace.workspaceRoot);
200
225
  }
201
226
 
202
- static normalizeNamedDefaultFunctionForFastRefresh(source: string): string | null {
203
- let changed = false;
204
- const defaultNames: string[] = [];
205
- const next = source.replace(
206
- /(^|\n)(\s*)export\s+default\s+(async\s+)?function\s+([A-Za-z_$][\w$]*)(?=\s*(?:<|\())/g,
207
- (match, lineStart: string, indent: string, asyncKeyword: string | undefined, name: string) => {
208
- changed = true;
209
- defaultNames.push(name);
210
- return `${lineStart}${indent}${asyncKeyword ?? ""}function ${name}`;
211
- },
212
- );
213
- if (!changed) return null;
214
- return `${next}\n${defaultNames.map((name) => `export default ${name};`).join("\n")}\n`;
227
+ static normalizeNamedDefaultFunctionForFastRefresh(
228
+ source: string,
229
+ { path: filePath }: { path?: string } = {},
230
+ ): string | null {
231
+ const declared = RouteClientBuilder.#declaredNamedDefaultFunctions(source, filePath);
232
+ if (declared.length === 0) return null;
233
+ let next = "";
234
+ let cursor = 0;
235
+ for (const { index, text, lineStart, indent, asyncKeyword, name } of declared) {
236
+ next += `${source.slice(cursor, index)}${lineStart}${indent}${asyncKeyword}function ${name}`;
237
+ cursor = index + text.length;
238
+ }
239
+ next += source.slice(cursor);
240
+ return `${next}\n${declared.map(({ name }) => `export default ${name};`).join("\n")}\n`;
241
+ }
242
+
243
+ //? The pattern also matches inside strings and comments (a docs page quoting code), so every candidate is renamed to
244
+ //? a probe export and only the ones the parser reports as exports are declarations.
245
+ static #declaredNamedDefaultFunctions(source: string, filePath?: string) {
246
+ const candidates = [
247
+ ...source.matchAll(/(^|\n)(\s*)export\s+default\s+(async\s+)?function\s+([A-Za-z_$][\w$]*)(?=\s*(?:<|\())/g),
248
+ ].map((match) => ({
249
+ index: match.index,
250
+ text: match[0],
251
+ lineStart: match[1] ?? "",
252
+ indent: match[2] ?? "",
253
+ asyncKeyword: match[3] ?? "",
254
+ name: match[4] ?? "",
255
+ }));
256
+ if (candidates.length === 0) return [];
257
+ const probeName = (idx: number) => `__akanNamedDefault${idx}`;
258
+ let probe = "";
259
+ let cursor = 0;
260
+ candidates.forEach(({ index, text, lineStart, indent, asyncKeyword }, idx) => {
261
+ probe += `${source.slice(cursor, index)}${lineStart}${indent}export ${asyncKeyword}function ${probeName(idx)}`;
262
+ cursor = index + text.length;
263
+ });
264
+ probe += source.slice(cursor);
265
+ const exported = RouteClientBuilder.#scanExports(probe, filePath);
266
+ return candidates.filter((_, idx) => exported.has(probeName(idx)));
267
+ }
268
+
269
+ static #scanExports(source: string, filePath?: string): Set<string> {
270
+ try {
271
+ return new Set(new Bun.Transpiler({ loader: filePath ? loaderFor(filePath) : "tsx" }).scan(source).exports);
272
+ } catch {
273
+ // Unparseable source is left alone, so the bundler reports its syntax error at the real line.
274
+ return new Set();
275
+ }
215
276
  }
216
277
 
217
278
  static resolveSsrClientRuntimeAliases(): Record<string, string> {
@@ -0,0 +1,77 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import fs from "node:fs";
3
+ import { mkdtemp, rm } from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { type ServerGraph, ServerGraphFile } from "./serverGraphFile";
7
+
8
+ //? Resolved, as the graph holds real paths: on Windows a missing `/repo/...` resolves onto the current drive.
9
+ const at = (relative: string) => path.resolve("/repo/apps/a", relative);
10
+
11
+ const graph: ServerGraph = {
12
+ inputs: [at("page/_index.tsx"), at("lib/task.constant.ts"), at("ui/Card.tsx")],
13
+ clientExports: { [at("ui/Card.tsx")]: ["Card", "CardBody"] },
14
+ };
15
+ const touches = (files: string[], exportsNow: string[] | null = ["CardBody", "Card"]) =>
16
+ ServerGraphFile.touches(graph, files, () => exportsNow);
17
+
18
+ describe("ServerGraphFile.touches", () => {
19
+ test("a file the server graph never read changes nothing it renders", async () => {
20
+ expect(await touches([at("ui/OnlyClient.tsx")])).toBe(false);
21
+ });
22
+
23
+ test("a module the server renders counts", async () => {
24
+ expect(await touches([at("lib/task.constant.ts")])).toBe(true);
25
+ });
26
+
27
+ test("a client module that keeps its export names does not count, in any order", async () => {
28
+ expect(await touches([at("ui/Card.tsx")])).toBe(false);
29
+ });
30
+
31
+ test("a client module whose names changed, or that stopped being one, counts", async () => {
32
+ expect(await touches([at("ui/Card.tsx")], ["Card"])).toBe(true);
33
+ expect(await touches([at("ui/Card.tsx")], null)).toBe(true);
34
+ });
35
+
36
+ test("without a graph every save counts", async () => {
37
+ expect(await ServerGraphFile.touches(null, [at("ui/OnlyClient.tsx")], () => null)).toBe(true);
38
+ });
39
+
40
+ test("a changed file the build just read for the first time counts: a failed import was waiting for it", async () => {
41
+ const next: ServerGraph = { ...graph, inputs: [...graph.inputs, at("ui/card.ts")] };
42
+ expect(await ServerGraphFile.touches(graph, [at("ui/card.ts")], () => null, next)).toBe(true);
43
+ expect(await ServerGraphFile.touches(graph, [at("ui/card.ts")], () => null)).toBe(false);
44
+ });
45
+
46
+ test("a failed build keeps the last good graph and carries its files to the next build's check", async () => {
47
+ const dir = await mkdtemp(path.join(os.tmpdir(), "akan-server-graph-"));
48
+ try {
49
+ await ServerGraphFile.write(dir, graph);
50
+ await ServerGraphFile.carry(dir, [at("page/_index.tsx")]);
51
+ const kept = await ServerGraphFile.read(dir);
52
+ expect(kept?.inputs).toEqual(graph.inputs);
53
+ expect(kept?.carried).toEqual([at("page/_index.tsx")]);
54
+ expect(await ServerGraphFile.touches(kept, [at("ui/Card.tsx")], () => ["Card", "CardBody"])).toBe(false);
55
+ const changed = [at("ui/Card.tsx"), ...(kept?.carried ?? [])];
56
+ expect(await ServerGraphFile.touches(kept, changed, () => ["Card", "CardBody"])).toBe(true);
57
+ } finally {
58
+ await rm(dir, { recursive: true, force: true });
59
+ }
60
+ });
61
+
62
+ test("a graph written again inside one mtime tick is read afresh", async () => {
63
+ const dir = await mkdtemp(path.join(os.tmpdir(), "akan-server-graph-"));
64
+ try {
65
+ const file = path.join(dir, ServerGraphFile.fileName);
66
+ const tick = new Date(Math.floor(Date.now() / 1000) * 1000);
67
+ await ServerGraphFile.write(dir, graph);
68
+ fs.utimesSync(file, tick, tick);
69
+ await ServerGraphFile.read(dir);
70
+ await ServerGraphFile.carry(dir, [at("page/_index.tsx")]);
71
+ fs.utimesSync(file, tick, tick);
72
+ expect((await ServerGraphFile.read(dir))?.carried).toEqual([at("page/_index.tsx")]);
73
+ } finally {
74
+ await rm(dir, { recursive: true, force: true });
75
+ }
76
+ });
77
+ });
@@ -0,0 +1,93 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { FileSys } from "../fileSys";
4
+ import { hasUseClientDirective, scanUseClientExports } from "../transforms/rscUseClientTransform";
5
+ import { CsrDevPaths } from "./csrDevPaths";
6
+
7
+ export interface ServerGraph {
8
+ /** Real paths of the workspace sources the dev pages bundle read. */
9
+ inputs: string[];
10
+ /** Export names of every `"use client"` module among them: the server holds each only as a reference by name. */
11
+ clientExports: Record<string, string[]>;
12
+ /** Files saved in batches whose pages build failed since this graph was written: the next build's changes too. */
13
+ carried?: string[];
14
+ }
15
+
16
+ //* What the dev server bundle read, written by every dev pages build that succeeds, so a save can be told apart as one
17
+ //* the server renders (it needs an RSC refresh) or one only the client registry holds. A failed build keeps the last
18
+ //* good graph and carries its files over, so the fixing save still refreshes what the failed ones changed.
19
+ export class ServerGraphFile {
20
+ static readonly fileName = "server-graph.json";
21
+ static #cache: { file: string; stamp: string; graph: ServerGraph } | null = null;
22
+
23
+ static async read(artifactDir: string): Promise<ServerGraph | null> {
24
+ const file = path.join(artifactDir, ServerGraphFile.fileName);
25
+ const stat = fs.statSync(file, { throwIfNoEntry: false });
26
+ if (!stat) return null;
27
+ //? Not the mtime alone: two writes inside one mtime tick (seen on Linux) read back the first. A write replaces the
28
+ //? file, so its inode moves too.
29
+ const stamp = `${stat.ino}:${stat.size}:${stat.mtimeMs}`;
30
+ const cached = ServerGraphFile.#cache;
31
+ if (cached?.file === file && cached.stamp === stamp) return cached.graph;
32
+ const graph = (await Bun.file(file)
33
+ .json()
34
+ .catch(() => null)) as ServerGraph | null;
35
+ if (graph) ServerGraphFile.#cache = { file, stamp, graph };
36
+ return graph;
37
+ }
38
+
39
+ static async write(artifactDir: string, graph: ServerGraph): Promise<void> {
40
+ const file = path.join(artifactDir, ServerGraphFile.fileName);
41
+ const temp = `${file}.${process.pid}.tmp`;
42
+ await Bun.write(temp, JSON.stringify(graph));
43
+ await FileSys.replace(temp, file);
44
+ }
45
+
46
+ static async carry(artifactDir: string, files: string[]): Promise<void> {
47
+ const graph = await ServerGraphFile.read(artifactDir);
48
+ if (!graph || files.length === 0) return;
49
+ const carried = [...new Set([...(graph.carried ?? []), ...files.map((file) => CsrDevPaths.realpath(file))])];
50
+ await ServerGraphFile.write(artifactDir, { ...graph, carried });
51
+ }
52
+
53
+ // `exportsNow` answers a client module's current export names, or null once it is no longer one. `next` is the graph
54
+ // the build just wrote: a changed file it reads for the first time (a module a failed import was waiting for) counts.
55
+ static async touches(
56
+ graph: ServerGraph | null,
57
+ files: string[],
58
+ exportsNow: (file: string) => string[] | null | Promise<string[] | null>,
59
+ next?: ServerGraph | null,
60
+ ): Promise<boolean> {
61
+ if (!graph) return true;
62
+ const inputs = new Set(graph.inputs);
63
+ const joined = new Set((next?.inputs ?? []).filter((input) => !inputs.has(input)));
64
+ for (const rawFile of files) {
65
+ const file = CsrDevPaths.realpath(rawFile);
66
+ if (joined.has(file)) return true;
67
+ if (!inputs.has(file)) continue;
68
+ const before = graph.clientExports[file];
69
+ if (!before) return true;
70
+ //? The server holds a "use client" module only as references by name: an edit that keeps them renders the same.
71
+ const now = await exportsNow(file);
72
+ if (!now || ServerGraphFile.#names(now) !== ServerGraphFile.#names(before)) return true;
73
+ }
74
+ return false;
75
+ }
76
+
77
+ static async clientExportsOf(file: string): Promise<string[] | null> {
78
+ const source = await Bun.file(file)
79
+ .text()
80
+ .catch(() => null);
81
+ if (source === null || !hasUseClientDirective(source)) return null;
82
+ try {
83
+ return scanUseClientExports(source, file);
84
+ } catch {
85
+ // A module the server can no longer read as client references is a server change; the pages build says why.
86
+ return null;
87
+ }
88
+ }
89
+
90
+ static #names(exports: string[]): string {
91
+ return [...exports].sort().join(",");
92
+ }
93
+ }