@akanjs/devkit 3.3.0-rc.73 → 3.3.0-rc.74

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.
@@ -80,3 +80,82 @@ describe("ClientEntriesBundler", () => {
80
80
  expect(await bundle("start")).toContain("switch-build");
81
81
  });
82
82
  });
83
+
84
+ describe("ClientEntriesBundler worker chunks", () => {
85
+ const drawApp = async () => {
86
+ const root = await realpath(await makeTempRoot());
87
+ const lib = (file: string, source: string) => writeText(path.join(root, "node_modules/drawlib", file), source);
88
+ await lib("package.json", '{ "name": "drawlib", "type": "module", "exports": "./index.js" }\n');
89
+ await lib("shared.js", "export const scale = (value) => value * 2;\n");
90
+ await lib(
91
+ "index.js",
92
+ [
93
+ 'import { useState } from "react";',
94
+ 'import { scale } from "./shared.js";',
95
+ "const ratio = window.devicePixelRatio;",
96
+ "export const useRatio = () => useState(scale(ratio));",
97
+ 'export const loadWorker = () => import("./worker.js");',
98
+ 'export const loadLazy = () => import("./lazy.js");',
99
+ "",
100
+ ].join("\n"),
101
+ );
102
+ await lib(
103
+ "worker.js",
104
+ [
105
+ 'import { scale } from "./shared.js";',
106
+ "export const WorkerUrl = new URL(import.meta.url);",
107
+ 'if (typeof window === "undefined") self.onmessage = (event) => self.postMessage(scale(event.data));',
108
+ "",
109
+ ].join("\n"),
110
+ );
111
+ await lib(
112
+ "lazy.js",
113
+ 'import { scale } from "./shared.js";\nexport const own = new URL(import.meta.url);\nexport const big = scale(4);\n',
114
+ );
115
+ const entry = path.join(root, "Draw.tsx");
116
+ await writeText(
117
+ entry,
118
+ '"use client";\nimport { loadLazy, loadWorker, useRatio } from "drawlib";\nexport const Draw = () => [useRatio, loadLazy, loadWorker];\n',
119
+ );
120
+ const app = {
121
+ name: "probe",
122
+ cwdPath: path.join(root, "app"),
123
+ dist: { cwdPath: path.join(root, "dist") },
124
+ workspace: { workspaceRoot: root },
125
+ getConfig: async () => ({ optimizeImports: [] }),
126
+ getPublicEnv: () => ({}),
127
+ };
128
+ const result = await new ClientEntriesBundler({
129
+ app: app as never,
130
+ entries: [entry],
131
+ command: "build",
132
+ external: ["react"],
133
+ }).bundle();
134
+ const outdir = path.join(root, "dist/.akan/artifact/client");
135
+ const chunks = await Promise.all(
136
+ [...new Bun.Glob("chunks/*.js").scanSync(outdir)].map(async (file) => ({
137
+ file: path.join(outdir, file),
138
+ text: await Bun.file(path.join(outdir, file)).text(),
139
+ })),
140
+ );
141
+ return { result, chunks };
142
+ };
143
+ const staticImportsOf = (text: string) =>
144
+ [...text.matchAll(/(?:\bfrom|\bimport)\s*["']([^"']+)["']/g)].map((m) => m[1]);
145
+
146
+ test("rebuilds a module that hands its own URL to a worker into its chunk alone, so a worker can load it", async () => {
147
+ const { result, chunks } = await drawApp();
148
+ const worker = chunks.find((chunk) => chunk.text.includes("onmessage"));
149
+ expect(worker && staticImportsOf(worker.text)).toEqual([]);
150
+ expect(result.graph.importsByChunk.get(worker?.file ?? "")).toEqual([]);
151
+ const loaded = (await import(worker?.file ?? "")) as { WorkerUrl: URL };
152
+ expect(loaded.WorkerUrl.href).toEndWith(path.basename(worker?.file ?? ""));
153
+ expect(typeof (globalThis as { onmessage?: unknown }).onmessage).toBe("function");
154
+ }, 30_000);
155
+
156
+ test("leaves a lazy chunk that only reads its own URL sharing what the page loaded", async () => {
157
+ const { chunks } = await drawApp();
158
+ const lazy = chunks.find((chunk) => chunk.text.includes("own"));
159
+ expect(lazy && staticImportsOf(lazy.text).length).toBeGreaterThan(0);
160
+ }, 30_000);
161
+ });
@@ -18,6 +18,7 @@ import {
18
18
  type MetafileOutput,
19
19
  type OpaqueEntryAliases,
20
20
  } from "./clientBuildTypes";
21
+ import { WorkerChunks } from "./workerChunks";
21
22
 
22
23
  export class ClientEntriesBundler {
23
24
  #app: BundleClientEntriesInternalOptions["app"];
@@ -92,6 +93,7 @@ export class ClientEntriesBundler {
92
93
  Object.entries(metafile.outputs).map(([k, v]) => [this.#absFromOutdir(k), v as MetafileOutput]),
93
94
  );
94
95
  this.#metafileInputs = metafile.inputs as Record<string, MetafileInput>;
96
+ if (this.#target === "browser") await this.#sealWorkerChunks();
95
97
 
96
98
  for (const artifact of result.outputs.filter((a) => a.kind === "entry-point"))
97
99
  this.#addEntryArtifact(artifact.path);
@@ -110,6 +112,25 @@ export class ClientEntriesBundler {
110
112
  };
111
113
  }
112
114
 
115
+ async #sealWorkerChunks(): Promise<void> {
116
+ const entries = new Set(this.#opaqueEntries?.entries.map((entry) => path.resolve(entry)));
117
+ const sealed = await WorkerChunks.seal(
118
+ this.#metafileOutputsByAbs,
119
+ entries,
120
+ (entryPoint) => this.#absFromEntryPoint(entryPoint),
121
+ {
122
+ outdir: this.#outdir,
123
+ define: bundleDefine(this.#app, this.#command, "ssr"),
124
+ conditions: bundleConditions(this.#command),
125
+ minify: this.#command === "build",
126
+ },
127
+ );
128
+ for (const chunk of sealed) {
129
+ const info = this.#metafileOutputsByAbs.get(chunk);
130
+ if (info) this.#metafileOutputsByAbs.set(chunk, { ...info, imports: [] });
131
+ }
132
+ }
133
+
113
134
  #graph(): ClientBundleGraph {
114
135
  const absByInput = new Map<string, string>();
115
136
  const absOf = (input: string) => {
@@ -0,0 +1,61 @@
1
+ import { rename } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { CLIENT_BUNDLE_NAMING, type MetafileOutput } from "./clientBuildTypes";
4
+
5
+ export interface WorkerChunkBuild {
6
+ outdir: string;
7
+ define: Record<string, string>;
8
+ conditions: string[];
9
+ minify: boolean;
10
+ }
11
+
12
+ //? A module that hands its own URL to `new Worker` runs again in a worker, which reads no import map and has no
13
+ //? `window`. Bun puts its runtime helpers (`__require`, `__toESM`) in whichever chunk it picks, a page's included, so
14
+ //? that module's chunk can import page code; it is rebuilt into the same file on its own, every import inlined.
15
+ export class WorkerChunks {
16
+ static readonly #ownUrl = /\bnew\s+URL\(\s*import\.meta\.url\s*\)/;
17
+ static readonly #listens = /\bself\.(?:onmessage\s*=|addEventListener\(\s*["']message["'])/;
18
+
19
+ static isWorkerSource(source: string): boolean {
20
+ return WorkerChunks.#ownUrl.test(source) && WorkerChunks.#listens.test(source);
21
+ }
22
+
23
+ static async seal(
24
+ outputs: ReadonlyMap<string, MetafileOutput>,
25
+ entries: ReadonlySet<string>,
26
+ moduleOf: (entryPoint: string) => string,
27
+ build: WorkerChunkBuild,
28
+ ): Promise<string[]> {
29
+ const sealed: string[] = [];
30
+ for (const [chunk, info] of outputs) {
31
+ if (!chunk.endsWith(".js") || !info.entryPoint) continue;
32
+ const module = moduleOf(info.entryPoint);
33
+ if (entries.has(module) || !(await Bun.file(module).exists())) continue;
34
+ if (!WorkerChunks.isWorkerSource(await Bun.file(module).text())) continue;
35
+ await WorkerChunks.#rebuild(module, chunk, build);
36
+ sealed.push(chunk);
37
+ }
38
+ return sealed;
39
+ }
40
+
41
+ static async #rebuild(module: string, chunk: string, build: WorkerChunkBuild): Promise<void> {
42
+ const directory = path.relative(build.outdir, path.dirname(chunk)).split(path.sep).join("/");
43
+ const result = await Bun.build({
44
+ entrypoints: [module],
45
+ outdir: build.outdir,
46
+ target: "browser",
47
+ format: "esm",
48
+ splitting: false,
49
+ minify: build.minify,
50
+ define: build.define,
51
+ conditions: build.conditions,
52
+ //? Beside the chunk it replaces, so a URL it builds from its own reads the same assets.
53
+ naming: { entry: `${directory ? `${directory}/` : ""}[hash]-worker.[ext]`, asset: CLIENT_BUNDLE_NAMING.asset },
54
+ });
55
+ if (!result.success)
56
+ throw new AggregateError(result.logs, `[WorkerChunks] could not rebuild ${module} for a worker`);
57
+ const built = result.outputs.find((output) => output.kind === "entry-point");
58
+ if (!built) throw new Error(`[WorkerChunks] the rebuild of ${module} wrote no entry`);
59
+ await rename(built.path, chunk);
60
+ }
61
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akanjs/devkit",
3
- "version": "3.3.0-rc.73",
3
+ "version": "3.3.0-rc.74",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -52,10 +52,10 @@
52
52
  "./workspace/getRelatedCnsts": "./workspace/getRelatedCnsts.ts"
53
53
  },
54
54
  "dependencies": {
55
- "@akanjs/language": "3.3.0-rc.73",
55
+ "@akanjs/language": "3.3.0-rc.74",
56
56
  "@inquirer/prompts": "^8.7.3",
57
57
  "@tailwindcss/node": "^4.3.3",
58
- "akanjs": "3.3.0-rc.73",
58
+ "akanjs": "3.3.0-rc.74",
59
59
  "chalk": "^6.0.1",
60
60
  "commander": "^15.0.0",
61
61
  "dayjs": "^1.11.23",