@akanjs/devkit 3.3.0-rc.72 → 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.
@@ -32,8 +32,9 @@ the server errors logged meanwhile, console errors and warnings, and layout smel
32
32
  name, and reads the account from `process.env`. `--as <name>` reaches it as `as`; `--anonymous` skips it.
33
33
  With none declared a guarded page shows its redirect: add it, or say "not opened signed in".
34
34
  - The viewport is a 390x844 phone; `--desktop` is 1280x800. `--csr` loads each page in the CSR boot the native
35
- shells load. `--screenshot` saves a PNG per page under `local/apps/<app>/runtime/preview/`, for a model
36
- that reads images. `--format json` gives the same report as data.
35
+ shells load. `--screenshot` saves a PNG per page under `local/apps/<app>/runtime/preview/`. `--format json`
36
+ gives the same report as data. `--wait-for <selector>` holds a page that draws after its first client read
37
+ until the selector matches, and fails it at `--timeout`.
37
38
 
38
39
  ### Which platforms that covers
39
40
 
@@ -25,7 +25,7 @@ import path at all**, so keep throwing code out of them entirely rather than rea
25
25
  ## Where each error belongs
26
26
 
27
27
  Which file throws which error, and the sentinel best-effort code returns instead, are the `server` rule.
28
- `try/catch` is rare and always converts an exception into a decision: a guard catches, warns, and returns `false`; an adapter
28
+ `try/catch` is rare and always converts an exception into a decision: a guard catches, warns, and returns `false`, or throws a keyed `Err.Forbidden` the caller must read; an adapter
29
29
  catches, logs (`logger.error`), and returns `null`; a UI `try/finally` resets a spinner. A store action never
30
30
  catches — let the framework toast the `Err`, or list it in the store's `static silent` when no screen waits on it
31
31
  and its caller handles the rejection.
@@ -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.72",
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.72",
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.72",
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",
@@ -18,6 +18,7 @@ export interface PreviewProbeOptions {
18
18
  timeoutMs?: number;
19
19
  /** Waited after the load, so the errors effects throw land before the page is read. */
20
20
  settleMs?: number;
21
+ waitFor?: string;
21
22
  }
22
23
 
23
24
  export interface PreviewProbeResult {
@@ -56,6 +57,7 @@ interface PageRead {
56
57
  export class PreviewView {
57
58
  /** A view's first navigation includes the browser's start, which took ~35 s on a cold CI runner. */
58
59
  static readonly startTimeoutMs = 120_000;
60
+ static readonly selectorPollMs = 100;
59
61
  static readonly #stalled = new Set<PreviewEngine>();
60
62
 
61
63
  static get available() {
@@ -83,6 +85,7 @@ export class PreviewView {
83
85
  startTimeoutMs = PreviewView.startTimeoutMs,
84
86
  timeoutMs = 30_000,
85
87
  settleMs = 0,
88
+ waitFor,
86
89
  }: PreviewProbeOptions = {},
87
90
  ): Promise<PreviewProbeResult> {
88
91
  const logs: string[] = [];
@@ -103,11 +106,11 @@ export class PreviewView {
103
106
  await within(view.navigate(session.url), "opening the session for");
104
107
  await within(view.evaluate(PreviewView.cookieExpression(session.cookies)), "opening the session for");
105
108
  }
106
- let page = await PreviewView.#load(view, url, settleMs, within);
109
+ let page = await PreviewView.#load(view, url, { settleMs, waitFor }, within);
107
110
  //? Right after a save the first load can render nothing (`[rscClient] module not loaded`); the next one has it.
108
111
  if (page.empty) {
109
112
  logs.length = 0;
110
- page = await PreviewView.#load(view, url, settleMs, within);
113
+ page = await PreviewView.#load(view, url, { settleMs, waitFor }, within);
111
114
  }
112
115
  const result: PreviewProbeResult = {
113
116
  url,
@@ -157,11 +160,12 @@ export class PreviewView {
157
160
  static async #load(
158
161
  view: WebViewLike,
159
162
  url: string,
160
- settleMs: number,
163
+ { settleMs, waitFor }: { settleMs: number; waitFor?: string },
161
164
  within: <T>(work: Promise<T>, what: string) => Promise<T>,
162
165
  ): Promise<PageRead> {
163
166
  await within(view.navigate(url), "loading");
164
167
  if (settleMs > 0) await Bun.sleep(settleMs);
168
+ if (waitFor) await PreviewView.#waitForSelector(view, url, waitFor, within);
165
169
  const read = (await within(view.evaluate(readPageExpression), "reading")) as Partial<PageRead> | null;
166
170
  return {
167
171
  href: typeof read?.href === "string" ? read.href : url,
@@ -174,6 +178,17 @@ export class PreviewView {
174
178
  };
175
179
  }
176
180
 
181
+ static async #waitForSelector(
182
+ view: WebViewLike,
183
+ url: string,
184
+ selector: string,
185
+ within: <T>(work: Promise<T>, what: string) => Promise<T>,
186
+ ) {
187
+ const expression = `document.querySelector(${JSON.stringify(selector)}) !== null`;
188
+ const what = `waiting for selector ${JSON.stringify(selector)} on`;
189
+ while (!(await within(view.evaluate(expression), what))) await within(Bun.sleep(PreviewView.selectorPollMs), what);
190
+ }
191
+
177
192
  //? webkit has no Navigation Timing `responseStatus`, so the status comes from asking the server again, unredirected.
178
193
  static async #statusOf(href: string, deadline: number, cookies: string[]) {
179
194
  const left = Math.max(1, deadline - Date.now());
@@ -122,6 +122,37 @@ describe("PreviewView", () => {
122
122
  browserTestMs,
123
123
  );
124
124
 
125
+ test.skipIf(!PreviewView.available)(
126
+ "waits for a selector that a page draws after its first client-side read",
127
+ async () => {
128
+ const server = serve(
129
+ "<!doctype html><title>Late</title><body><script>setTimeout(() => { document.body.innerHTML = '<p id=\"ready\">drawn</p>'; }, 1500);</script></body>",
130
+ );
131
+ try {
132
+ const probe = await PreviewView.probe(`http://localhost:${server.port}/`, { waitFor: "#ready" });
133
+ expect(probe.text).toBe("drawn");
134
+ } finally {
135
+ server.stop(true);
136
+ }
137
+ },
138
+ browserTestMs,
139
+ );
140
+
141
+ test.skipIf(!PreviewView.available)(
142
+ "fails naming the selector when it never appears before the timeout",
143
+ async () => {
144
+ const server = serve("<!doctype html><title>Blank</title><body>blank</body>");
145
+ try {
146
+ await expect(
147
+ PreviewView.probe(`http://localhost:${server.port}/`, { waitFor: "#never", timeoutMs: 2_000 }),
148
+ ).rejects.toThrow('waiting for selector "#never"');
149
+ } finally {
150
+ server.stop(true);
151
+ }
152
+ },
153
+ browserTestMs,
154
+ );
155
+
125
156
  test.skipIf(!PreviewView.available)(
126
157
  "gives up on a server that takes the connection and never answers",
127
158
  async () => {