@akanjs/devkit 3.3.0-rc.62 → 3.3.0-rc.64

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.
@@ -1385,13 +1385,19 @@ describe("AkanAppConfig.from", () => {
1385
1385
  const libConfigPath = path.join(root, "libs/extlib/akan.config.ts");
1386
1386
  fs.mkdirSync(path.join(root, "apps/extapp"), { recursive: true });
1387
1387
  fs.mkdirSync(path.join(root, "libs/extlib"), { recursive: true });
1388
- fs.writeFileSync(path.join(root, "apps/extapp/akan.config.ts"), "export default {};\n");
1388
+ fs.writeFileSync(
1389
+ path.join(root, "apps/extapp/akan.config.ts"),
1390
+ "export default { preview: { signIn: async () => ({ jwt: 'token' }), examples: ['/chat/1'] } };\n",
1391
+ );
1389
1392
  fs.writeFileSync(libConfigPath, "export default { externalLibs: ['first'] };\n");
1390
1393
  fs.writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "extrepo", version: "1.0.0" }));
1391
1394
  fs.writeFileSync(path.join(root, ".env"), "AKAN_PUBLIC_REPO_NAME=extrepo\nAKAN_PUBLIC_SERVE_DOMAIN=ext.test\n");
1392
1395
  const workspace = WorkspaceExecutor.fromRoot({ workspaceRoot: root, repoName: "extrepo" });
1393
1396
  const app = AppExecutor.from(workspace, "extapp");
1394
- expect((await AkanAppConfig.from(app)).externalLibs).toEqual(["first"]);
1397
+ const config = await AkanAppConfig.from(app);
1398
+ expect(config.externalLibs).toEqual(["first"]);
1399
+ expect(config.preview.examples).toEqual(["/chat/1"]);
1400
+ expect(await config.preview.signIn?.({ origin: "http://localhost:8282", as: null })).toEqual({ jwt: "token" });
1395
1401
 
1396
1402
  fs.writeFileSync(libConfigPath, "export default { externalLibs: ['second'] };\n");
1397
1403
  expect((await AkanAppConfig.from(app, { bustImportCache: true })).externalLibs).toEqual(["second"]);
@@ -1,7 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
- import type { AkanPlugin } from "akanjs";
4
+ import type { AkanPlugin, AkanPreviewConfig } from "akanjs";
5
5
  import { DatabaseModes, normalizeRoutePrefix } from "akanjs/base";
6
6
  import { type AkanI18nConfig, resolveAkanI18nConfig, trimSlashes } from "akanjs/common";
7
7
  import type { AkanImageConfig } from "akanjs/server";
@@ -9,6 +9,7 @@ import type { App, Lib } from "../commandDecorators";
9
9
  import { WorkspaceExecutor } from "../executors/workspaceExecutor";
10
10
  import type { BaseDevEnv, PackageJson } from "../workspace/types";
11
11
  import { AkanBin } from "./akanBin";
12
+ import { AkanPreview } from "./akanPreview";
12
13
  import { AkanWorkers, type LibWorkers } from "./akanWorkers";
13
14
  import { DesktopServerConfig } from "./desktopServerConfig";
14
15
  import { dockerfileOf, resolveDocker, resolveDockerVariants } from "./dockerImage";
@@ -184,6 +185,8 @@ export class AkanAppConfig implements AppConfigResult {
184
185
  libs: string[];
185
186
  /** Live-only: plugins declared in this app's `akan.config.ts` (never serialized). */
186
187
  plugins: AkanPlugin[];
188
+ /** Live-only: `akan preview` reads it from this app's `akan.config.ts` (never serialized). */
189
+ preview: AkanPreviewConfig = {};
187
190
  domains = new Set<string>();
188
191
  subRoutes = new Map<string, Set<string>>();
189
192
  basePaths = new Set<string>();
@@ -507,17 +510,29 @@ export class AkanAppConfig implements AppConfigResult {
507
510
  const {
508
511
  plugins,
509
512
  pipeline: _pipeline,
513
+ preview,
510
514
  ...config
511
515
  } = (resolved ?? {}) as AppConfigDeclaration & {
512
516
  plugins?: AkanPlugin[];
513
517
  pipeline?: unknown;
518
+ preview?: unknown;
514
519
  };
515
520
  if ("subspace" in config)
516
521
  throw new Error(
517
522
  `apps/${app.name}/akan.config.ts declares \`subspace\`, a workspace setting: it belongs in the workspace root akan.config.ts.`,
518
523
  );
519
524
  const libContributions = await AkanAppConfig.#collectLibContributions(app, libs, bustImportCache);
520
- return new AkanAppConfig(app, libs, rootPackageJson, config, baseDevEnv, plugins ?? [], libContributions);
525
+ const appConfig = new AkanAppConfig(
526
+ app,
527
+ libs,
528
+ rootPackageJson,
529
+ config,
530
+ baseDevEnv,
531
+ plugins ?? [],
532
+ libContributions,
533
+ );
534
+ appConfig.preview = AkanPreview.parse(preview, `apps/${app.name}/akan.config.ts`);
535
+ return appConfig;
521
536
  }
522
537
  //* Every workspace lib is read, not just this app's lib deps: narrowing the set needs the dependency
523
538
  //* scan, and the incremental page rebundle re-reads this config on every file change.
@@ -0,0 +1,28 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { AkanPreview } from "./akanPreview";
3
+
4
+ const owner = "apps/demo/akan.config.ts";
5
+
6
+ describe("AkanPreview.parse", () => {
7
+ test("keeps the sign-in function and the example paths, and reads a missing section as empty", () => {
8
+ const signIn = async () => ({ jwt: "token" });
9
+ expect(AkanPreview.parse(undefined, owner)).toEqual({});
10
+ expect(AkanPreview.parse({}, owner)).toEqual({});
11
+ expect(AkanPreview.parse({ signIn, examples: ["/chat/1?tab=files"] }, owner)).toEqual({
12
+ signIn,
13
+ examples: ["/chat/1?tab=files"],
14
+ });
15
+ });
16
+
17
+ test("refuses a section it cannot read, naming the file and the key", () => {
18
+ expect(() => AkanPreview.parse([], owner)).toThrow(`${owner} declares \`preview\`, which has to be an object`);
19
+ expect(() => AkanPreview.parse({ login: () => null }, owner)).toThrow(
20
+ "preview.login; it takes signIn and examples",
21
+ );
22
+ expect(() => AkanPreview.parse({ signIn: "/api/signin" }, owner)).toThrow(
23
+ "preview.signIn, which has to be a function",
24
+ );
25
+ for (const examples of ["/chat/1", ["chat/1"], ["//host/chat/1"], [1]])
26
+ expect(() => AkanPreview.parse({ examples }, owner)).toThrow("preview.examples, which has to list paths");
27
+ });
28
+ });
@@ -0,0 +1,24 @@
1
+ import type { AkanPreviewConfig } from "./types";
2
+
3
+ export class AkanPreview {
4
+ static parse(value: unknown, owner: string): AkanPreviewConfig {
5
+ if (value === undefined) return {};
6
+ if (typeof value !== "object" || value === null || Array.isArray(value))
7
+ throw new Error(`[preview] ${owner} declares \`preview\`, which has to be an object: { signIn, examples }`);
8
+ const { signIn, examples, ...unknown } = value as Record<string, unknown>;
9
+ const [stray] = Object.keys(unknown);
10
+ if (stray) throw new Error(`[preview] ${owner} declares preview.${stray}; it takes signIn and examples`);
11
+ if (signIn !== undefined && typeof signIn !== "function")
12
+ throw new Error(`[preview] ${owner} declares preview.signIn, which has to be a function`);
13
+ if (examples !== undefined && !(Array.isArray(examples) && examples.every(AkanPreview.#isPath)))
14
+ throw new Error(`[preview] ${owner} declares preview.examples, which has to list paths that start with "/"`);
15
+ return {
16
+ ...(signIn ? { signIn: signIn as AkanPreviewConfig["signIn"] } : {}),
17
+ ...(examples ? { examples: examples as string[] } : {}),
18
+ };
19
+ }
20
+
21
+ static #isPath(value: unknown) {
22
+ return typeof value === "string" && value.startsWith("/") && !value.startsWith("//");
23
+ }
24
+ }
@@ -1,5 +1,6 @@
1
1
  export * from "./akanBin";
2
2
  export * from "./akanConfig";
3
+ export * from "./akanPreview";
3
4
  export * from "./akanWorkers";
4
5
  export * from "./akanWorkspaceConfig";
5
6
  export * from "./dockerImage";
@@ -22,6 +22,8 @@ export type {
22
22
  AkanNativeValue,
23
23
  AkanPlugin,
24
24
  AkanPluginNativeConfig,
25
+ AkanPreviewConfig,
26
+ AkanPreviewSignIn,
25
27
  AkanRouteConfig,
26
28
  AkanScanInfo,
27
29
  AkanSyncContext,
@@ -24,8 +24,13 @@ the server errors logged meanwhile, console errors and warnings, and layout smel
24
24
  opens its path and query the same way, always on the app's dev server, with a note when it names another
25
25
  server: use it for an endpoint mounted outside the API prefix. A page `--changed` finds opens as a page even at
26
26
  a server route's path, under the same locale rule, and `/en` and `/en/` open once.
27
- `--changed` adds the pages your uncommitted page and layout edits reach. A dynamic route needs a concrete
28
- path (`/memo/1`); `akan context --app <app>` lists every route with its params and search names.
27
+ `--changed` adds the pages your uncommitted page and layout edits reach. A dynamic route opens at the first
28
+ `preview.examples` path of `akan.config.ts` that fits it (`["/memo/1"]`, no locale), else type a concrete
29
+ one; `akan context --app <app>` lists every route with its params and search names.
30
+ - A page behind a sign-in opens through `preview.signIn({ origin, as })` in `akan.config.ts`, called once per
31
+ run: it returns the sign-in `Response` (its `Set-Cookie` pairs become every page's cookies) or the cookies by
32
+ name, and reads the account from `process.env`. `--as <name>` reaches it as `as`; `--anonymous` skips it.
33
+ With none declared a guarded page shows its redirect: add it, or say "not opened signed in".
29
34
  - The viewport is a 390x844 phone; `--desktop` is 1280x800. `--csr` loads each page in the CSR boot the native
30
35
  shells load. `--screenshot` saves a PNG per page under `local/apps/<app>/runtime/preview/`, for a model
31
36
  that reads images. `--format json` gives the same report as data.
@@ -64,6 +64,9 @@ File names, stages, the `.render()` order and what a route file must never do ar
64
64
  that answers everyone alike, lets the server keep the page.
65
65
  - Loading: `.loading(() => <Skeleton />)` on a page or layout is what that level shows until its `.render()` and the
66
66
  levels below it resolve; the levels above it stream first.
67
+ - A page left on screen while its next path loads (`/chat/a` to `/chat/b` under an awaiting layout):
68
+ `.loading(fn, { atPress: true })` shows the fallback after 150 ms of waiting on the server (`{ atPress: { delayMs } }`).
69
+ `page()` only; never on Back, Forward or a held page. It is the path being left's fallback: draw it from no argument.
67
70
  - `router.notFound()` from `.guard()`, `.head()` or `.render()` answers 404 with the nearest layout's `.notFound()`
68
71
  above it (an unmatched URL: the deepest layout covering it), else the built-in 404.
69
72
  - A layout's own 404 and error views: `.notFound(({ pathname }) => …)` and `.error(({ error }) => …)` on `layout()`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akanjs/devkit",
3
- "version": "3.3.0-rc.62",
3
+ "version": "3.3.0-rc.64",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -50,7 +50,7 @@
50
50
  "./workspace/getRelatedCnsts": "./workspace/getRelatedCnsts.ts"
51
51
  },
52
52
  "dependencies": {
53
- "@akanjs/language": "3.3.0-rc.62",
53
+ "@akanjs/language": "3.3.0-rc.64",
54
54
  "@earendil-works/pi-agent-core": "1.5.2",
55
55
  "@earendil-works/pi-ai": "1.5.2",
56
56
  "@earendil-works/pi-codemode": "1.5.2",
@@ -59,7 +59,7 @@
59
59
  "@earendil-works/pi-tui": "1.5.2",
60
60
  "@inquirer/prompts": "^8.7.3",
61
61
  "@tailwindcss/node": "^4.3.3",
62
- "akanjs": "3.3.0-rc.62",
62
+ "akanjs": "3.3.0-rc.64",
63
63
  "chalk": "^6.0.1",
64
64
  "commander": "^15.0.0",
65
65
  "dayjs": "^1.11.23",
@@ -1,6 +1,14 @@
1
1
  import { PreviewChrome, type PreviewEngine } from "./PreviewChrome";
2
2
 
3
+ export interface PreviewSession {
4
+ /** A document of the pages' origin, where the cookies are written before a page opens. */
5
+ url: string;
6
+ /** `name=value` pairs. */
7
+ cookies: string[];
8
+ }
9
+
3
10
  export interface PreviewProbeOptions {
11
+ session?: PreviewSession | null;
4
12
  screenshot?: boolean;
5
13
  width?: number;
6
14
  height?: number;
@@ -67,6 +75,7 @@ export class PreviewView {
67
75
  static async probe(
68
76
  url: string,
69
77
  {
78
+ session = null,
70
79
  screenshot = false,
71
80
  width = 1280,
72
81
  height = 800,
@@ -90,6 +99,10 @@ export class PreviewView {
90
99
  deadline,
91
100
  new Error(`Timed out ${what} ${url}; the dev server may be rebuilding or stuck.`),
92
101
  );
102
+ if (session?.cookies.length) {
103
+ await within(view.navigate(session.url), "opening the session for");
104
+ await within(view.evaluate(PreviewView.cookieExpression(session.cookies)), "opening the session for");
105
+ }
93
106
  let page = await PreviewView.#load(view, url, settleMs, within);
94
107
  //? Right after a save the first load can render nothing (`[rscClient] module not loaded`); the next one has it.
95
108
  if (page.empty) {
@@ -99,7 +112,7 @@ export class PreviewView {
99
112
  const result: PreviewProbeResult = {
100
113
  url,
101
114
  finalUrl: page.href,
102
- status: page.status ?? (await PreviewView.#statusOf(page.href, deadline)),
115
+ status: page.status ?? (await PreviewView.#statusOf(page.href, deadline, session?.cookies ?? [])),
103
116
  title: page.title,
104
117
  text: page.text,
105
118
  consoleErrors: logs.filter((line) => line.startsWith("error")),
@@ -162,12 +175,21 @@ export class PreviewView {
162
175
  }
163
176
 
164
177
  //? webkit has no Navigation Timing `responseStatus`, so the status comes from asking the server again, unredirected.
165
- static async #statusOf(href: string, deadline: number) {
178
+ static async #statusOf(href: string, deadline: number, cookies: string[]) {
166
179
  const left = Math.max(1, deadline - Date.now());
167
- const response = await fetch(href, { redirect: "manual", signal: AbortSignal.timeout(left) }).catch(() => null);
180
+ const response = await fetch(href, {
181
+ redirect: "manual",
182
+ signal: AbortSignal.timeout(left),
183
+ ...(cookies.length ? { headers: { Cookie: cookies.join("; ") } } : {}),
184
+ }).catch(() => null);
168
185
  return response?.status ?? null;
169
186
  }
170
187
 
188
+ //? Written from a document: the webkit backend has no cookie API, and a page sends a cookie its script set like any other.
189
+ static cookieExpression(cookies: string[]) {
190
+ return `(() => { for (const pair of ${JSON.stringify(cookies)}) document.cookie = pair + "; Path=/; SameSite=Lax"; return true; })()`;
191
+ }
192
+
171
193
  static async #within<T>(work: Promise<T>, deadline: number, expiry: Error): Promise<T> {
172
194
  let timer: ReturnType<typeof setTimeout> | undefined;
173
195
  const expired = new Promise<never>((_, reject) => {
@@ -52,13 +52,17 @@ describe("JsonFormatter", () => {
52
52
  expect(JsonFormatter.stringify(manifest, "libs/x/package.json")).toBe(`${JSON.stringify(manifest, null, 2)}\n`);
53
53
  });
54
54
 
55
- test.skipIf(!hasBiome)("prints what Biome prints", async () => {
56
- expect(await formatWithBiome('{"a":[1]}', "libs/fixture/akan.lib.json")).toBe('{ "a": [1] }\n');
57
- for (const [name, fixture] of Object.entries(fixtures)) {
58
- const printed = JsonFormatter.stringify(fixture, `libs/fixture/${name}.json`);
59
- expect(await formatWithBiome(printed, `libs/fixture/${name}.json`)).toBe(printed);
60
- }
61
- const manifest = JsonFormatter.stringify({ name: "x", workspaces: ["a", "b"] }, "package.json");
62
- expect(await formatWithBiome(manifest, "libs/fixture/package.json")).toBe(manifest);
63
- });
55
+ test.skipIf(!hasBiome)(
56
+ "prints what Biome prints",
57
+ async () => {
58
+ expect(await formatWithBiome('{"a":[1]}', "libs/fixture/akan.lib.json")).toBe('{ "a": [1] }\n');
59
+ for (const [name, fixture] of Object.entries(fixtures)) {
60
+ const printed = JsonFormatter.stringify(fixture, `libs/fixture/${name}.json`);
61
+ expect(await formatWithBiome(printed, `libs/fixture/${name}.json`)).toBe(printed);
62
+ }
63
+ const manifest = JsonFormatter.stringify({ name: "x", workspaces: ["a", "b"] }, "package.json");
64
+ expect(await formatWithBiome(manifest, "libs/fixture/package.json")).toBe(manifest);
65
+ },
66
+ 30_000,
67
+ );
64
68
  });