@akanjs/devkit 3.3.0-rc.2 → 3.3.0-rc.4
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.
- package/CHANGELOG.md +38 -20
- package/akanConfig/akanConfig.test.ts +2 -1
- package/akanConfig/akanConfig.ts +1 -1
- package/app/applicationBuildRunner.test.ts +49 -1
- package/app/applicationBuildRunner.ts +3 -1
- package/codeAgent/skills/akan-page/SKILL.md +18 -13
- package/codeAgent/skills/akan-runtime/SKILL.md +21 -16
- package/codeAgent/skills/akan-service/SKILL.md +2 -2
- package/docs/apiReference.test.ts +5 -0
- package/docs/apiReference.ts +7 -3
- package/docs/declarationReader.ts +28 -1
- package/executors/appExecutor.ts +16 -7
- package/frontendBuild/cssCompiler.test.ts +112 -0
- package/frontendBuild/cssCompiler.ts +41 -21
- package/frontendBuild/plainStylesheet.test.ts +155 -0
- package/frontendBuild/plainStylesheet.ts +197 -0
- package/guideline/agentAssets.test.ts +10 -0
- package/guideline/agentAssets.ts +52 -11
- package/mobile/nativeConfig.test.ts +21 -0
- package/mobile/nativeConfig.ts +20 -10
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,43 @@
|
|
|
2
2
|
|
|
3
3
|
## 3.3.0
|
|
4
4
|
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- c44d068: A coding agent reads less to build its first app: the `akanjs` README keeps the path to a first app and links the rest on akanjs.com (17 KB to 7 KB), the `akan-page` and `akan-service` skills ship the API reference one section at a time with every entry named in the skill's index (`Link` now lists the anchor attributes it takes and `Link.Back`, `Link.Close` and `Link.Lang`), the `akan-page` skill holds what a first page looks up while `pageRule` keeps the deeper contract, and each rule is stated once across AGENTS.md, the path rules and the skills. Run `akan agent install` in a workspace to pick up the new files.
|
|
8
|
+
- 1d8c8c2: An app with `basePaths` keeps every base path's CSS class scan in the candidate cache, so a start or build no longer rescans the sources of all but one of them. An entry is dropped only once its source file is deleted.
|
|
9
|
+
- 90d740f: `native.ios.hideFormAccessoryBar: true` (or a target's `ios.hideFormAccessoryBar`) leaves out the bar WebKit shows above the keyboard while a page field is focused. The iOS shell already had the switch, but `akan.config.ts` refused the key and the native config never carried it, so every iOS app showed the bar.
|
|
10
|
+
|
|
11
|
+
The key defaults to false, so existing apps are unchanged. The api report lists one new optional `AkanNativeIosConfig` property; no upgrade step is needed.
|
|
12
|
+
|
|
13
|
+
- 4732186: `akan --version` loads no command module, and `akan tunnel`, `akan subspace` and the package commands such as `akan version` no longer load the TypeScript compiler unless a step compiles.
|
|
14
|
+
- 0d5e75e: A stylesheet whose imports use no Tailwind (no `@import "tailwindcss"`, Tailwind at-rule or `theme()` function anywhere in its import graph) is no longer run through the Tailwind compiler: its imports are inlined and it ships without the `/*! tailwindcss … */` banner. A stylesheet that uses Tailwind compiles exactly as before.
|
|
15
|
+
- 98931e4: `akan start` boots the backend while the first base build runs: the backend loads its server graph beside the build and mounts the web surface as soon as the build's artifact is on disk, so the dev server is ready sooner.
|
|
16
|
+
|
|
17
|
+
The port now answers from the start of the build. A request to `localhost` or an IP address, page or API, waits for the first artifact; a build longer than the 15 s the gateway holds a request ends the wait with a 503 "Backend is starting" page that reloads itself. A request to one of the app's own domains (a custom local domain) gets that 503 at once until the backend is ready, because the build has not written the app's hosts yet; after that it is served as before, and any other Host is refused as before.
|
|
18
|
+
|
|
19
|
+
- 1d8c8c2: `akan start` keeps `apps/<app>/.akan/cache` between runs, so a restart reuses the CSS class scan and the subset fonts instead of redoing them. Each entry names the akanjs and Bun versions and the build of the cache code that wrote it, and an entry another one wrote, or one cut short, is rebuilt.
|
|
20
|
+
- 98931e4: `akan start` prints one line when the dev server is ready that says where the start's time went: what the CLI did before the builder, the base build and its parts, the backend's boot, and when the first artifact was on disk.
|
|
21
|
+
- 694444d: `akan verify` writes its build check to `dist/verify/<app>` and leaves `dist/apps/<app>` as `akan build` left it, so running `akan verify` after `akan build` no longer stops `cd dist/apps/<app> && bun main.js` from starting. The check no longer copies the app's `public/` and `private/` folders either.
|
|
22
|
+
- Updated dependencies [c44d068]
|
|
23
|
+
- Updated dependencies [24315d1]
|
|
24
|
+
- Updated dependencies [bf582c1]
|
|
25
|
+
- Updated dependencies [90d740f]
|
|
26
|
+
- Updated dependencies [3032627]
|
|
27
|
+
- Updated dependencies [c10f7cf]
|
|
28
|
+
- Updated dependencies [c10f7cf]
|
|
29
|
+
- Updated dependencies [045699c]
|
|
30
|
+
- Updated dependencies [5c7e083]
|
|
31
|
+
- Updated dependencies [aead1aa]
|
|
32
|
+
- Updated dependencies [5c6d039]
|
|
33
|
+
- Updated dependencies [0492e0b]
|
|
34
|
+
- Updated dependencies [0492e0b]
|
|
35
|
+
- Updated dependencies [5c7e083]
|
|
36
|
+
- Updated dependencies [98931e4]
|
|
37
|
+
- akanjs@3.3.0
|
|
38
|
+
- @akanjs/language@3.3.0
|
|
39
|
+
|
|
40
|
+
## 3.2.0
|
|
41
|
+
|
|
5
42
|
### Minor Changes
|
|
6
43
|
|
|
7
44
|
- 038d918: Akan.js 3.2.0. Read **Upgrade notes** before deploying an app that runs 3.1.1: unguarded endpoints, log levels, the `Err` class, loaders, SQLite transactions, exit codes and a CLI version check change behaviour.
|
|
@@ -66,27 +103,8 @@
|
|
|
66
103
|
|
|
67
104
|
### Patch Changes
|
|
68
105
|
|
|
69
|
-
- 1d8c8c2: An app with `basePaths` keeps every base path's CSS class scan in the candidate cache, so a start or build no longer rescans the sources of all but one of them. An entry is dropped only once its source file is deleted.
|
|
70
|
-
- 4732186: `akan --version` loads no command module, and `akan tunnel`, `akan subspace` and the package commands such as `akan version` no longer load the TypeScript compiler unless a step compiles.
|
|
71
|
-
- 98931e4: `akan start` boots the backend while the first base build runs: the backend loads its server graph beside the build and mounts the web surface as soon as the build's artifact is on disk, so the dev server is ready sooner.
|
|
72
|
-
|
|
73
|
-
The port now answers from the start of the build. A request to `localhost` or an IP address, page or API, waits for the first artifact; a build longer than the 15 s the gateway holds a request ends the wait with a 503 "Backend is starting" page that reloads itself. A request to one of the app's own domains (a custom local domain) gets that 503 at once until the backend is ready, because the build has not written the app's hosts yet; after that it is served as before, and any other Host is refused as before.
|
|
74
|
-
|
|
75
|
-
- 1d8c8c2: `akan start` keeps `apps/<app>/.akan/cache` between runs, so a restart reuses the CSS class scan and the subset fonts instead of redoing them. Each entry names the akanjs and Bun versions and the build of the cache code that wrote it, and an entry another one wrote, or one cut short, is rebuilt.
|
|
76
|
-
- 98931e4: `akan start` prints one line when the dev server is ready that says where the start's time went: what the CLI did before the builder, the base build and its parts, the backend's boot, and when the first artifact was on disk.
|
|
77
|
-
- Updated dependencies [bf582c1]
|
|
78
|
-
- Updated dependencies [c10f7cf]
|
|
79
|
-
- Updated dependencies [c10f7cf]
|
|
80
|
-
- Updated dependencies [5c7e083]
|
|
81
106
|
- Updated dependencies [038d918]
|
|
82
|
-
-
|
|
83
|
-
- Updated dependencies [5c6d039]
|
|
84
|
-
- Updated dependencies [0492e0b]
|
|
85
|
-
- Updated dependencies [0492e0b]
|
|
86
|
-
- Updated dependencies [5c7e083]
|
|
87
|
-
- Updated dependencies [98931e4]
|
|
88
|
-
- akanjs@3.3.0
|
|
89
|
-
- @akanjs/language@3.3.0
|
|
107
|
+
- akanjs@3.2.0
|
|
90
108
|
|
|
91
109
|
## 3.1.1
|
|
92
110
|
|
|
@@ -662,7 +662,7 @@ describe("AkanAppConfig", () => {
|
|
|
662
662
|
targets: {
|
|
663
663
|
default: {
|
|
664
664
|
plugins: ["share"],
|
|
665
|
-
ios: { files: { "extra.caf": "assets/extra.caf" } },
|
|
665
|
+
ios: { files: { "extra.caf": "assets/extra.caf" }, hideFormAccessoryBar: true },
|
|
666
666
|
android: { manifest: ["<uses-feature/>"] },
|
|
667
667
|
},
|
|
668
668
|
},
|
|
@@ -677,6 +677,7 @@ describe("AkanAppConfig", () => {
|
|
|
677
677
|
ios: {
|
|
678
678
|
infoPlist: { ITSAppUsesNonExemptEncryption: false },
|
|
679
679
|
files: { "sound.caf": "assets/sound.caf", "extra.caf": "assets/extra.caf" },
|
|
680
|
+
hideFormAccessoryBar: true,
|
|
680
681
|
},
|
|
681
682
|
android: {
|
|
682
683
|
manifest: ["<uses-feature/>"],
|
package/akanConfig/akanConfig.ts
CHANGED
|
@@ -475,7 +475,7 @@ export class AkanAppConfig implements AppConfigResult {
|
|
|
475
475
|
"android",
|
|
476
476
|
"desktop",
|
|
477
477
|
],
|
|
478
|
-
ios: ["indexPath", "teamId", "infoPlist", "entitlements", "privacy", "files"],
|
|
478
|
+
ios: ["indexPath", "teamId", "infoPlist", "entitlements", "privacy", "files", "hideFormAccessoryBar"],
|
|
479
479
|
android: [
|
|
480
480
|
"indexPath",
|
|
481
481
|
"sha256CertFingerprints",
|
|
@@ -439,7 +439,9 @@ console.info(new SampleService().name);
|
|
|
439
439
|
|
|
440
440
|
expect(proc.exitCode).toBe(1);
|
|
441
441
|
expect(proc.stdout.toString()).toBe("");
|
|
442
|
-
expect(proc.stderr.toString()).toContain(
|
|
442
|
+
expect(proc.stderr.toString()).toContain(
|
|
443
|
+
`${path.join("dist", "verify", "portal")} holds the partial output of akan verify, not a build. Run \`akan build portal\` and start dist/apps/portal.`,
|
|
444
|
+
);
|
|
443
445
|
expect(await Bun.file(path.join(app.dist.cwdPath, "akan.build.json")).json()).toMatchObject({
|
|
444
446
|
profile: "verify",
|
|
445
447
|
});
|
|
@@ -452,4 +454,50 @@ console.info(new SampleService().name);
|
|
|
452
454
|
await rm(root, { recursive: true, force: true });
|
|
453
455
|
}
|
|
454
456
|
});
|
|
457
|
+
|
|
458
|
+
test("a verify build writes to dist/verify/<app> and leaves the full build in dist/apps/<app> as it was", async () => {
|
|
459
|
+
const { root, workspace } = await createTempApp("portal");
|
|
460
|
+
const keys = ["AKAN_PUBLIC_ENV", "AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN"] as const;
|
|
461
|
+
const shellEnv = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
|
|
462
|
+
const appDir = path.join(root, "apps", "portal");
|
|
463
|
+
await Promise.all(["main.ts", "server.ts"].map((file) => writeFile(path.join(appDir, file), "")));
|
|
464
|
+
await mkdir(path.join(appDir, "public"));
|
|
465
|
+
await writeFile(path.join(appDir, "public", "hero.png"), "image");
|
|
466
|
+
const built = path.join(root, "dist", "apps", "portal");
|
|
467
|
+
const fullBuild = {
|
|
468
|
+
"main.js": 'console.log("booted");\n',
|
|
469
|
+
"akan.build.json": '{ "buildId": "abc123" }\n',
|
|
470
|
+
"akan.env.json": '{ "AKAN_PUBLIC_ENV": "local" }\n',
|
|
471
|
+
"public/hero.png": "image",
|
|
472
|
+
};
|
|
473
|
+
for (const [file, content] of Object.entries(fullBuild)) {
|
|
474
|
+
await mkdir(path.dirname(path.join(built, file)), { recursive: true });
|
|
475
|
+
await writeFile(path.join(built, file), content);
|
|
476
|
+
}
|
|
477
|
+
const app = AppExecutor.from(workspace, "portal");
|
|
478
|
+
const bundle = spyOn(Bun, "build").mockImplementation(
|
|
479
|
+
async () => ({ success: true, outputs: [], logs: [] }) as unknown as Bun.BuildOutput,
|
|
480
|
+
);
|
|
481
|
+
try {
|
|
482
|
+
const { outputDir } = await new ApplicationBuildRunner(app, { verify: true }).build();
|
|
483
|
+
|
|
484
|
+
for (const [file, content] of Object.entries(fullBuild))
|
|
485
|
+
expect(await readFile(path.join(built, file), "utf8").catch(() => null)).toBe(content);
|
|
486
|
+
const verified = path.join(root, "dist", "verify", "portal");
|
|
487
|
+
expect(outputDir).toBe(verified);
|
|
488
|
+
expect(await Bun.file(path.join(verified, "akan.build.json")).json()).toMatchObject({ profile: "verify" });
|
|
489
|
+
expect(await Bun.file(path.join(verified, "console.js")).exists()).toBe(true);
|
|
490
|
+
expect(await Bun.file(path.join(verified, "public", "hero.png")).exists()).toBe(false);
|
|
491
|
+
const outdirs = bundle.mock.calls.map(([config]) => config.outdir);
|
|
492
|
+
expect(outdirs.length).toBeGreaterThan(0);
|
|
493
|
+
expect(outdirs.every((outdir) => outdir === verified)).toBe(true);
|
|
494
|
+
} finally {
|
|
495
|
+
bundle.mockRestore();
|
|
496
|
+
for (const key of keys) {
|
|
497
|
+
if (shellEnv[key] === undefined) delete process.env[key];
|
|
498
|
+
else process.env[key] = shellEnv[key];
|
|
499
|
+
}
|
|
500
|
+
await rm(root, { recursive: true, force: true });
|
|
501
|
+
}
|
|
502
|
+
});
|
|
455
503
|
});
|
|
@@ -164,6 +164,7 @@ export class ApplicationBuildRunner {
|
|
|
164
164
|
async build({ spinner = false }: BuildOptions = {}): Promise<BuildResult> {
|
|
165
165
|
// serial build is needed because of Bun.build is unstable for parallel build
|
|
166
166
|
this.#spinner = spinner;
|
|
167
|
+
if (this.#verify) this.#app.useVerifyDist();
|
|
167
168
|
const { web, assets, baseDevEnv } = await this.#app.getConfig();
|
|
168
169
|
const environment = this.#environment ?? baseDevEnv.env;
|
|
169
170
|
WorkspaceExecutor.assertDeployableEnv(baseDevEnv, environment, "akan build");
|
|
@@ -370,7 +371,8 @@ export class ApplicationBuildRunner {
|
|
|
370
371
|
//? `bun main.js` in dist/apps/<app> is a documented way to run a build, and a verify output has no CSR bundle or
|
|
371
372
|
//? production env file, so its main.js refuses to boot before any app module runs.
|
|
372
373
|
#verifyBanner() {
|
|
373
|
-
const
|
|
374
|
+
const { name, dist, workspace } = this.#app;
|
|
375
|
+
const message = `${path.relative(workspace.workspaceRoot, dist.cwdPath)} holds the partial output of akan verify, not a build. Run \`akan build ${name}\` and start dist/apps/${name}.`;
|
|
374
376
|
return `console.error(${JSON.stringify(message)});process.exit(1);`;
|
|
375
377
|
}
|
|
376
378
|
|
|
@@ -26,19 +26,19 @@ export default page()
|
|
|
26
26
|
## Steps
|
|
27
27
|
|
|
28
28
|
1. Place the file: `<route>.tsx` or `<dir>/_index.tsx` serves the path, `_layout.tsx` nests a layout (`layout()`;
|
|
29
|
-
the root one is `rootLayout()`), `[id]` is a dynamic segment, `(group)` groups without a segment.
|
|
30
|
-
route modules only — no helpers, no `.ts` files.
|
|
29
|
+
the root one is `rootLayout()`), `[id]` is a dynamic segment, `(group)` groups without a segment.
|
|
31
30
|
2. Name every `[x]` segment with `.param("x", Type)` and read a query key only with `.search("k", Type)`. Values
|
|
32
|
-
arrive typed
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
31
|
+
arrive typed: `ID` / `String` → string, `Int` / `Float` → number, `Boolean`, `Date` → Dayjs, an `enumOf` class →
|
|
32
|
+
its union, `[T]` → array. A path value the type refuses answers not-found, and a search value that fails is
|
|
33
|
+
dropped. `lang` reaches every stage and is never declared.
|
|
34
|
+
3. Gate with `.guard(() => signedIn())` on the `_layout.tsx`, and repeat a stricter guard on a page that needs more.
|
|
35
|
+
`.guard((_, { path }) => signedIn({ path }))` sends a refused visitor to `/signin?redirect=<path>`.
|
|
36
36
|
4. In `.render()`: `usePage()`, then fetch, then return. Hand `fetch.init*` / `view*` / `edit*` fields to sections
|
|
37
37
|
unawaited; await only what the shell reads, in one `Promise.all`.
|
|
38
|
-
5. `.head()` takes JSX (or a function returning it), never a metadata object.
|
|
39
|
-
page's own head.
|
|
38
|
+
5. `.head()` takes JSX (or a function returning it), never a metadata object.
|
|
40
39
|
6. Re-skin an `akanjs/ui` component for a subtree with `_overrides.tsx`:
|
|
41
|
-
`export default override({ Slot: AppComponent })`, no logic.
|
|
40
|
+
`export default override({ Slot: AppComponent })`, no logic. Nested ones merge slot by slot, the closest winning;
|
|
41
|
+
`componentRule` lists the slots.
|
|
42
42
|
|
|
43
43
|
## API at a glance
|
|
44
44
|
|
|
@@ -50,12 +50,16 @@ declared params and search keys plus `lang`.
|
|
|
50
50
|
where `Book` is the `common/` interface for the query's `Any` return (`akan-service`).
|
|
51
51
|
- Async page: `.render(async ({ id }) => { const book = (await fetch.book(id)) as Book | null; if (!book) return router.notFound(); … })`;
|
|
52
52
|
the same query in `.head()` and `.render()` is one request.
|
|
53
|
+
- Loading: `.loading(() => <Skeleton />)` on a page or layout is what that level shows until its `.render()` and the
|
|
54
|
+
levels below it resolve; the levels above it stream first.
|
|
53
55
|
- `router.notFound()` from `.guard()`, `.head()` or `.render()` answers 404 with the nearest layout's `.notFound()`
|
|
54
56
|
above it (an unmatched URL: the deepest layout covering it), else the built-in 404.
|
|
55
57
|
- A layout's own 404 and error views: `.notFound(({ pathname }) => …)` and `.error(({ error }) => …)` on `layout()`
|
|
56
|
-
or `rootLayout()`.
|
|
58
|
+
or `rootLayout()`. A `<title>` and `<meta>` at the top of what they return replace the page's head:
|
|
59
|
+
`.notFound(() => <><title>Not found</title>…</>)`, except below a `.loading()`, where the head is already out.
|
|
57
60
|
- `<Link href="/books/OL45804W">`: write the path without the locale; Link adds it, or leaves it off for the default
|
|
58
|
-
locale under `i18n.localePrefix: "as-needed"`.
|
|
61
|
+
locale under `i18n.localePrefix: "as-needed"`. It renders an `<a>` and takes its attributes; `activeClassName`
|
|
62
|
+
marks the current one.
|
|
59
63
|
- From a handler: `router.push(href)` / `router.replace(href)`; in a server stage, `router.redirect(href)`.
|
|
60
64
|
- A client filter kept in the URL without reloading the page: ``router.replace(`/books?q=${q}`, { shallow: true,
|
|
61
65
|
scrollToTop: false })`` in a `"use client"` component, read back with `usePageLocation().searchParams`. Shallow
|
|
@@ -68,5 +72,6 @@ declared params and search keys plus `lang`.
|
|
|
68
72
|
- `useState`, `useEffect`, comments, a named export beside the chain, or the legacy `export default async function`.
|
|
69
73
|
- Editing a lib page through its link in `page/(libs)/` — edit the lib's own `page/` source.
|
|
70
74
|
|
|
71
|
-
Full detail: `get_guideline` with `pageRule
|
|
72
|
-
signature, the router's methods, Link's props and every
|
|
75
|
+
Full detail: `get_guideline` with `pageRule` (guards in depth, heads, MCP apps, CSR root layouts, lib pages), or
|
|
76
|
+
`ssrRule` for what may render on the server. Every stage's signature, the router's methods, Link's props and every
|
|
77
|
+
import path are in the `akanApi-*` references below.
|
|
@@ -5,8 +5,9 @@ description: "Configure how an app runs: web surfaces, route prefixes, gateway v
|
|
|
5
5
|
|
|
6
6
|
# Akan runtime
|
|
7
7
|
|
|
8
|
-
Runtime and build settings are declared in `akan.config.ts
|
|
9
|
-
|
|
8
|
+
Runtime and build settings are declared in `akan.config.ts`. What must hold when you edit it, `main.ts` or an env
|
|
9
|
+
file — the prefixes, the `main.ts` import, the image, log sinks, the desktop server's guard — is the `config` rule in
|
|
10
|
+
the agent guide's Path Rules table.
|
|
10
11
|
|
|
11
12
|
## Where each setting lives
|
|
12
13
|
|
|
@@ -16,28 +17,32 @@ Domain code reaches none of them.
|
|
|
16
17
|
| Move the API or websocket mount | `new AkanApp({ prefix, websocketPrefix })` in `main.ts`, mirrored in `api: { … }`; read with `getApiPrefix()` / `getWsPrefix()` |
|
|
17
18
|
| The production image | `docker: string \| { image, preRuns, postRuns, command }` |
|
|
18
19
|
| iOS, Android, desktop | the `native` section; `desktop: { server: true }` carries the server |
|
|
19
|
-
| SQLite, several databases, a cluster | `database: { modes: [...] }`, picked by `AKAN_DATABASE_MODE` |
|
|
20
|
+
| SQLite, several databases, a cluster | `database: { modes: [...] }` (`single`, `multiple`, `cluster`), picked by `AKAN_DATABASE_MODE` |
|
|
20
21
|
| URLs without `/<locale>/`: one language, or paths fixed from outside (OAuth callback, QR code, mail link) | `i18n: { localePrefix: "as-needed" }` — the default locale's pages and `<Link>` hrefs drop the prefix, other locales keep it |
|
|
21
22
|
|
|
22
|
-
- `main.ts` imports `AkanApp` from `akanjs/server/akanApp`, never the barrel.
|
|
23
|
-
- Never write `/api` or `/ws` literally, and never pass a prefix as a prop.
|
|
24
|
-
- The generated image installs only `ca-certificates` and `tzdata`; add the rest in `preRuns`.
|
|
25
|
-
- An app running in two database modes avoids `q.raw`.
|
|
26
|
-
|
|
27
23
|
## Running and logs
|
|
28
24
|
|
|
29
25
|
- `akan start <app>` (`a,b` or `all` for several) runs the dev server; `akan build <app>` checks the production
|
|
30
|
-
build. A supervised session writes `local/apps/<app>/runtime/dev.log` — hand over that
|
|
31
|
-
live view. Tail with `akan logs <app>`.
|
|
26
|
+
build. A supervised session writes `local/apps/<app>/runtime/dev.log` (previous: `dev.prev.log`) — hand over that
|
|
27
|
+
path, not a paste of the live view. Tail with `akan logs <app>`.
|
|
32
28
|
- Run a build without Docker with `cd dist/apps/<app> && bun main.js`: it boots with the env the Dockerfile sets,
|
|
33
29
|
read from `akan.env.json` beside it, and a variable you set yourself (`PORT=3000`) wins.
|
|
34
|
-
- Give every log sink a floor (`Logger.addSink(sink, { minLevel })`) and never log once per delivered record.
|
|
35
30
|
|
|
36
31
|
## Native and desktop
|
|
37
32
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
33
|
+
A `start-*` command loads its pages from a running `akan start`; a desktop app carrying its server starts it itself.
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
akan start-desktop <app> # Run the desktop app on this computer
|
|
37
|
+
akan start-ios <app> # Run it in a simulator or on an iPhone (start-android alike)
|
|
38
|
+
akan build-desktop <app> # Build it for this computer into dist/native/<app>/<target>/build
|
|
39
|
+
akan build-desktop <app> --installer true # Windows: add a per-user setup program
|
|
40
|
+
akan update-keygen <app> # Make the update signing key once; print its public key
|
|
41
|
+
akan publish-update <app> # Build a key-signed release for updates.url; --sign true also code-signs it
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
A device capability the framework lacks is a plugin the app owns in `native/<id>/`: `native-plugin.json`,
|
|
45
|
+
`src/index.ts` (the page API, used from a `webkit/` hook), `src/desktop.ts`, Kotlin and Swift.
|
|
42
46
|
|
|
43
|
-
Full detail: `get_guideline` with `runtimeRule
|
|
47
|
+
Full detail: `get_guideline` with `runtimeRule` (keys, `--plain`, boot waves, `--kill`, watch scope, booting a
|
|
48
|
+
server in a test, native targets and updates).
|
|
@@ -106,5 +106,5 @@ The page calls it as `await fetch.book(id)` (`fetch` from `@apps/<app>/client`)
|
|
|
106
106
|
`common/`, or return a scalar (`akan create-scalar`) for a typed wire shape. A query that answers `null` without
|
|
107
107
|
`nullable: true` fails the render, naming the endpoint.
|
|
108
108
|
|
|
109
|
-
Full detail: `get_guideline` with `modelService
|
|
110
|
-
|
|
109
|
+
Full detail: `get_guideline` with `modelService`. The exact signatures of serve, adapt, endpoint and
|
|
110
|
+
serviceDictionary, and every import path, are in the `akanApi-*` references below.
|
|
@@ -28,6 +28,11 @@ describe("ApiReference", () => {
|
|
|
28
28
|
expect(rendered).toMatch(/^\/\*\* .+ \*\/\nserverMode\?: "batch" \| "federation";$/m);
|
|
29
29
|
});
|
|
30
30
|
|
|
31
|
+
test("says what Link takes beyond its own props, and names its static parts", () => {
|
|
32
|
+
expect(rendered).toContain('Every prop of `Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href">`, and:');
|
|
33
|
+
expect(rendered).toMatch(/^Link\.Back\(.+\): Element$/m);
|
|
34
|
+
});
|
|
35
|
+
|
|
31
36
|
test("lists the keys of akan.config.ts, so the web and i18n shapes have a field to belong to", () => {
|
|
32
37
|
const appConfig = rendered.slice(rendered.indexOf("### `AppConfigInput`"));
|
|
33
38
|
expect(appConfig).toMatch(/^web\?: AkanWebOption;$/m);
|
package/docs/apiReference.ts
CHANGED
|
@@ -153,7 +153,7 @@ export class ApiReference {
|
|
|
153
153
|
"Generated from the akanjs sources of this release: the import paths and signatures a first app needs, so none of",
|
|
154
154
|
"them has to be looked up in `node_modules`. A stage's return type is the same chain, left out below.",
|
|
155
155
|
"",
|
|
156
|
-
"## Imports",
|
|
156
|
+
"## Imports (`akanjs/*`, `@apps/<app>/client`, `../cnst`, `../dict`, `../srv`, layer barrels)",
|
|
157
157
|
"",
|
|
158
158
|
"```ts",
|
|
159
159
|
...importLines,
|
|
@@ -183,8 +183,12 @@ export class ApiReference {
|
|
|
183
183
|
return [heading, "", "```ts", reader.declarationText(symbol), "```"].join("\n");
|
|
184
184
|
if (item.show.kind === "signature")
|
|
185
185
|
return [heading, "", "```ts", ...reader.signatures(symbol, item.name), "```"].join("\n");
|
|
186
|
-
if (item.show.kind === "props")
|
|
187
|
-
|
|
186
|
+
if (item.show.kind === "props") {
|
|
187
|
+
const bases = reader.foreignBases(symbol).map((base) => `\`${base}\``);
|
|
188
|
+
const inherits = bases.length ? ["", `Every prop of ${bases.join(" and ")}, and:`] : [];
|
|
189
|
+
const props = reader.props(reader.declaredType(symbol), item.show.omit);
|
|
190
|
+
return [heading, ...inherits, "", "```ts", ...props, "```"].join("\n");
|
|
191
|
+
}
|
|
188
192
|
const members = reader.members(reader.instanceType(symbol), item.show);
|
|
189
193
|
return [heading, "", "```ts", ...members.map(([, line]) => line), "```"].join("\n");
|
|
190
194
|
}
|
|
@@ -91,7 +91,34 @@ export class DeclarationReader {
|
|
|
91
91
|
const type = this.#checker.getTypeOfSymbol(symbol);
|
|
92
92
|
const signatures = type.getCallSignatures();
|
|
93
93
|
if (signatures.length === 0) throw new Error(`${name} is not callable`);
|
|
94
|
-
|
|
94
|
+
const statics = this.#checker.getPropertiesOfType(type).flatMap((property) => {
|
|
95
|
+
const [declaration] = property.declarations ?? [];
|
|
96
|
+
if (!declaration || DeclarationReader.#isInternalName(property.name)) return [];
|
|
97
|
+
return this.#checker
|
|
98
|
+
.getTypeOfSymbolAtLocation(property, declaration)
|
|
99
|
+
.getCallSignatures()
|
|
100
|
+
.map((each) => `${name}.${property.name}${this.#checker.signatureToString(each, undefined, typeFlags)}`);
|
|
101
|
+
});
|
|
102
|
+
return [
|
|
103
|
+
...signatures.map((signature) => `${name}${this.#checker.signatureToString(signature, undefined, typeFlags)}`),
|
|
104
|
+
...statics,
|
|
105
|
+
];
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
foreignBases(symbol: ts.Symbol): string[] {
|
|
109
|
+
const [declaration] = symbol.declarations ?? [];
|
|
110
|
+
const nodes =
|
|
111
|
+
declaration && ts.isTypeAliasDeclaration(declaration) && ts.isIntersectionTypeNode(declaration.type)
|
|
112
|
+
? declaration.type.types.filter((each) => !ts.isTypeLiteralNode(each))
|
|
113
|
+
: declaration && ts.isInterfaceDeclaration(declaration)
|
|
114
|
+
? (declaration.heritageClauses ?? []).flatMap((clause) => [...clause.types])
|
|
115
|
+
: [];
|
|
116
|
+
return nodes
|
|
117
|
+
.filter((node) => {
|
|
118
|
+
const properties = this.#checker.getPropertiesOfType(this.#checker.getTypeFromTypeNode(node));
|
|
119
|
+
return properties.length > 0 && properties.every((each) => !each.declarations?.some((d) => this.#isOwn(d)));
|
|
120
|
+
})
|
|
121
|
+
.map((node) => DeclarationReader.#print(node, node.getSourceFile()));
|
|
95
122
|
}
|
|
96
123
|
|
|
97
124
|
props(type: ts.Type, omit: string[] = []): string[] {
|
package/executors/appExecutor.ts
CHANGED
|
@@ -44,6 +44,12 @@ export class AppExecutor extends SysExecutor {
|
|
|
44
44
|
static from(executor: SysExecutor | WorkspaceExecutor, name: string) {
|
|
45
45
|
return new AppExecutor({ workspace: executor instanceof WorkspaceExecutor ? executor : executor.workspace, name });
|
|
46
46
|
}
|
|
47
|
+
#verifyBuild: boolean = false;
|
|
48
|
+
//? `akan verify` builds apart: dist/apps/<app> may hold the full build someone is about to start or deploy.
|
|
49
|
+
useVerifyDist() {
|
|
50
|
+
this.dist = new Executor(`dist/verify/${this.name}`, `${this.workspace.workspaceRoot}/dist/verify/${this.name}`);
|
|
51
|
+
this.#verifyBuild = true;
|
|
52
|
+
}
|
|
47
53
|
//* Not dev output: the downloaded `bin` sources, and caches whose entries name the akanjs and Bun that wrote them.
|
|
48
54
|
static readonly #keptOnStart = [path.join(".akan", "cache")];
|
|
49
55
|
//* Native builds moved to dist/native/<app>; the old folder may hold a signed release nobody uploaded yet.
|
|
@@ -131,13 +137,16 @@ export class AppExecutor extends SysExecutor {
|
|
|
131
137
|
this.#excludeDevOnlyPages = true;
|
|
132
138
|
this.#pageKeys = null;
|
|
133
139
|
await this.dist.removeDir(this.dist.cwdPath);
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
140
|
+
//? A verify build stops before anything reads these copies; the font optimizer falls back to the app's `public/`.
|
|
141
|
+
if (!this.#verifyBuild) {
|
|
142
|
+
await Promise.all([this.dist.mkdir("private"), this.dist.mkdir("public")]);
|
|
143
|
+
//* Lib assets are symlinks, which neither the docker context nor the release tarball follows out of dist.
|
|
144
|
+
//* Only the web router reads `public/`, so an api-only build leaves it out.
|
|
145
|
+
await Promise.all([
|
|
146
|
+
this.cp("private", `${this.dist.cwdPath}/private`, { dereference: true }),
|
|
147
|
+
...(akanConfig.web.ssr ? [this.cp("public", `${this.dist.cwdPath}/public`, { dereference: true })] : []),
|
|
148
|
+
]);
|
|
149
|
+
}
|
|
141
150
|
} else {
|
|
142
151
|
await this.#removeDevOutput();
|
|
143
152
|
//? `akan start` keeps the full dev surface: the incremental builder is also the file watcher.
|
|
@@ -2,8 +2,120 @@ import { describe, expect, test } from "bun:test";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { tempDirs, writeText as write } from "../test/testHelpers";
|
|
4
4
|
import { CssCompiler, declaredCustomProperties } from "./cssCompiler";
|
|
5
|
+
import { prepareCssAsset } from "./ssrBaseArtifactBuilder";
|
|
5
6
|
|
|
6
7
|
const makeTempRoot = tempDirs("akan-css-compiler-");
|
|
8
|
+
const TAILWIND_BANNER = "/*! tailwindcss v";
|
|
9
|
+
|
|
10
|
+
const cssCompilerFor = (root: string, cwdPath: string, app: object = {}) =>
|
|
11
|
+
new CssCompiler({
|
|
12
|
+
workspace: { workspaceRoot: root },
|
|
13
|
+
cwdPath,
|
|
14
|
+
getTsConfig: async () => ({ compilerOptions: { paths: {} } }),
|
|
15
|
+
getPageKeys: async () => ["./_index.tsx"],
|
|
16
|
+
getConfig: async () => ({ barrelImports: [], basePaths: [] }),
|
|
17
|
+
...app,
|
|
18
|
+
} as never);
|
|
19
|
+
|
|
20
|
+
describe("CssCompiler on a stylesheet that uses no Tailwind", () => {
|
|
21
|
+
test("passes it through as written, with no banner, before and after the build's optimizer", async () => {
|
|
22
|
+
const root = await makeTempRoot();
|
|
23
|
+
const css = "/* brand */\n:root {\n --brand: #111111;\n}\n\n.card { color: var(--brand); padding: 1rem; }\n";
|
|
24
|
+
await write(path.join(root, "styles.css"), css);
|
|
25
|
+
|
|
26
|
+
const compiled = await cssCompilerFor(root, root).compileCss([path.join(root, "styles.css")], []);
|
|
27
|
+
|
|
28
|
+
expect(compiled).toBe(css);
|
|
29
|
+
const built = prepareCssAsset("build", "", compiled);
|
|
30
|
+
expect(built).toBe(":root{--brand:#111}.card{color:var(--brand);padding:1rem}");
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("inlines its imports through the resolver alone, where Tailwind stamped its banner", async () => {
|
|
34
|
+
const root = await makeTempRoot();
|
|
35
|
+
await write(path.join(root, "page/styles.css"), '@import "../ui/reset.css" layer(reset);\n.page { margin: 0; }\n');
|
|
36
|
+
await write(path.join(root, "ui/reset.css"), "* { box-sizing: border-box; }\n");
|
|
37
|
+
|
|
38
|
+
const compiled = await cssCompilerFor(root, root).compileCss([path.join(root, "page/styles.css")], []);
|
|
39
|
+
|
|
40
|
+
expect(compiled).toBe("@layer reset {\n* { box-sizing: border-box; }\n\n}\n.page { margin: 0; }\n");
|
|
41
|
+
expect(prepareCssAsset("build", "", compiled)).not.toContain("tailwind");
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
test("reports its imports like a compiled stylesheet's", async () => {
|
|
45
|
+
const root = await makeTempRoot();
|
|
46
|
+
const appDir = path.join(root, "apps/demo");
|
|
47
|
+
await write(path.join(appDir, "page/_index.tsx"), 'import "./styles.css";\nexport default () => null;\n');
|
|
48
|
+
await write(path.join(appDir, "page/styles.css"), '@import "../../../libs/shared/ui/brand.css";\n');
|
|
49
|
+
await write(path.join(root, "libs/shared/ui/brand.css"), ":root { --kakao : #fee500; }\n");
|
|
50
|
+
|
|
51
|
+
const compiler = cssCompilerFor(root, appDir);
|
|
52
|
+
const cssByBasePath = await compiler.getCssByBasePath();
|
|
53
|
+
|
|
54
|
+
expect(cssByBasePath[""]).toBe(":root { --kakao : #fee500; }\n\n");
|
|
55
|
+
expect(compiler.importedStylesheetsByBasePath[""]).toEqual([
|
|
56
|
+
{ cssPath: path.join(root, "libs/shared/ui/brand.css"), declaredNames: ["--kakao"] },
|
|
57
|
+
]);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test.each([
|
|
61
|
+
["@theme", "@theme { --color-brand: red; }"],
|
|
62
|
+
["@utility", "@utility tab-4 { tab-size: 4; }"],
|
|
63
|
+
["@variant", ".a { @variant hover { color: red; } }"],
|
|
64
|
+
["@custom-variant", "@custom-variant pointer-coarse (@media (pointer: coarse));"],
|
|
65
|
+
["@source", '@source "./src";'],
|
|
66
|
+
["@tailwind", "@tailwind utilities;"],
|
|
67
|
+
["@apply", ".a { @apply flex; }"],
|
|
68
|
+
["@plugin", '@plugin "./plugin.js";'],
|
|
69
|
+
["@config", '@config "./tailwind.config.js";'],
|
|
70
|
+
["@reference", '@reference "./plain.css";'],
|
|
71
|
+
["--alpha()", ".a { color: --alpha(red / 50%); }"],
|
|
72
|
+
["--theme()", ".a { color: --theme(--color-brand, red); }"],
|
|
73
|
+
["an import's source()", '@import "./plain.css" source(none);'],
|
|
74
|
+
])("compiles with Tailwind when only an imported stylesheet uses %s", async (_, directive) => {
|
|
75
|
+
const root = await makeTempRoot();
|
|
76
|
+
await write(path.join(root, "styles.css"), '@import "./part.css";\n.app { margin: 0; }\n');
|
|
77
|
+
await write(path.join(root, "part.css"), `${directive}\n`);
|
|
78
|
+
await write(path.join(root, "plain.css"), ".plain { color: red; }\n");
|
|
79
|
+
await write(path.join(root, "plugin.js"), "export default function () {}\n");
|
|
80
|
+
await write(path.join(root, "tailwind.config.js"), "export default {};\n");
|
|
81
|
+
|
|
82
|
+
const compiled = await cssCompilerFor(root, root).compileCss([path.join(root, "styles.css")], []);
|
|
83
|
+
|
|
84
|
+
expect(compiled.startsWith(TAILWIND_BANNER)).toBe(true);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test('compiles `@import "tailwindcss"` and the utilities the sources use', async () => {
|
|
88
|
+
const root = await makeTempRoot();
|
|
89
|
+
await write(path.join(root, "styles.css"), '@import "tailwindcss";\n');
|
|
90
|
+
await write(path.join(root, "Page.tsx"), 'export const Page = () => <main className="flex" />;\n');
|
|
91
|
+
|
|
92
|
+
const compiled = await cssCompilerFor(root, root).compileCss(
|
|
93
|
+
[path.join(root, "styles.css")],
|
|
94
|
+
[path.join(root, "Page.tsx")],
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
expect(compiled.startsWith(TAILWIND_BANNER)).toBe(true);
|
|
98
|
+
expect(compiled).toContain(".flex {");
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
test("switches to Tailwind on the next rebuild once a stylesheet gains a directive, and back", async () => {
|
|
102
|
+
const root = await makeTempRoot();
|
|
103
|
+
const stylesPath = path.join(root, "page/styles.css");
|
|
104
|
+
await write(path.join(root, "page/_index.tsx"), 'import "./styles.css";\nexport default () => null;\n');
|
|
105
|
+
await write(stylesPath, '@import "./tokens.css";\n');
|
|
106
|
+
await write(path.join(root, "page/tokens.css"), ":root { --brand: #111; }\n");
|
|
107
|
+
const compiler = cssCompilerFor(root, root);
|
|
108
|
+
|
|
109
|
+
expect((await compiler.getCssByBasePath({ refresh: true }))[""]).toBe(":root { --brand: #111; }\n\n");
|
|
110
|
+
await write(
|
|
111
|
+
path.join(root, "page/tokens.css"),
|
|
112
|
+
":root { --brand: #111; }\n@theme { --color-brand: var(--brand); }\n",
|
|
113
|
+
);
|
|
114
|
+
expect((await compiler.getCssByBasePath({ refresh: true }))[""]?.startsWith(TAILWIND_BANNER)).toBe(true);
|
|
115
|
+
await write(path.join(root, "page/tokens.css"), ":root { --brand: #222; }\n");
|
|
116
|
+
expect((await compiler.getCssByBasePath({ refresh: true }))[""]).toBe(":root { --brand: #222; }\n\n");
|
|
117
|
+
});
|
|
118
|
+
});
|
|
7
119
|
|
|
8
120
|
describe("declaredCustomProperties", () => {
|
|
9
121
|
test("names what the regex-based version named", () => {
|
|
@@ -9,6 +9,7 @@ import { CsrEntryFiles } from "./csrEntryFiles";
|
|
|
9
9
|
import { CssBlockParser } from "./cssBlockParser";
|
|
10
10
|
import { CssCandidateCache } from "./cssCandidateCache";
|
|
11
11
|
import { CssImportResolver } from "./cssImportResolver";
|
|
12
|
+
import { PlainStylesheet } from "./plainStylesheet";
|
|
12
13
|
|
|
13
14
|
const NON_SOURCE_EXT_RE = /\.(json|svg|png|jpe?g|webp|gif|avif|ico|woff2?|ttf|otf|mp3|mp4|wav)$/i;
|
|
14
15
|
const NODE_MODULES_RE = /[\\/]node_modules[\\/]/;
|
|
@@ -24,6 +25,13 @@ export interface ImportedStylesheet {
|
|
|
24
25
|
declaredNames: string[];
|
|
25
26
|
}
|
|
26
27
|
|
|
28
|
+
interface CompiledStylesheet {
|
|
29
|
+
cssPath: string;
|
|
30
|
+
compiler: Awaited<ReturnType<typeof compile>> | null;
|
|
31
|
+
plainCss: string;
|
|
32
|
+
imported: Map<string, string>;
|
|
33
|
+
}
|
|
34
|
+
|
|
27
35
|
export class CssCompiler {
|
|
28
36
|
#logger = new Logger("CssCompiler");
|
|
29
37
|
#transpiler = new Bun.Transpiler({ loader: "tsx" });
|
|
@@ -233,38 +241,30 @@ export class CssCompiler {
|
|
|
233
241
|
if (cssPaths.length === 0) return { css: "", imported: [] };
|
|
234
242
|
|
|
235
243
|
const compileStarted = Date.now();
|
|
236
|
-
const compilers = await Promise.all(
|
|
237
|
-
cssPaths.map(async (cssPath) => {
|
|
238
|
-
const css = await Bun.file(cssPath).text();
|
|
239
|
-
const base = path.dirname(cssPath);
|
|
240
|
-
const imported = new Map<string, string>();
|
|
241
|
-
const compiler = await compile(css, {
|
|
242
|
-
base,
|
|
243
|
-
loadStylesheet: (id, fromBase) => this.#loadStylesheet(id, fromBase, imported),
|
|
244
|
-
loadModule: (id, fromBase) => this.#loadModule(id, fromBase),
|
|
245
|
-
});
|
|
246
|
-
return { cssPath, compiler, imported };
|
|
247
|
-
}),
|
|
248
|
-
);
|
|
244
|
+
const compilers = await Promise.all(cssPaths.map((cssPath) => this.#compileStylesheet(cssPath)));
|
|
249
245
|
|
|
250
246
|
const sourceDirs = new Set<string>();
|
|
251
247
|
for (const entry of compilers) {
|
|
252
|
-
for (const s of entry.compiler
|
|
248
|
+
for (const s of (entry.compiler?.sources ?? []) as { base: string }[]) sourceDirs.add(s.base);
|
|
249
|
+
}
|
|
250
|
+
let candidates: string[] = [];
|
|
251
|
+
if (compilers.some((entry) => entry.compiler)) {
|
|
252
|
+
const scanStarted = Date.now();
|
|
253
|
+
candidates = await this.#scanCandidates(sourcePaths, [...sourceDirs]);
|
|
254
|
+
this.#logger.verbose(
|
|
255
|
+
`css candidates scanned count=${candidates.length} sources=${sourcePaths.length} dirs=${sourceDirs.size} in ${Date.now() - scanStarted}ms`,
|
|
256
|
+
);
|
|
253
257
|
}
|
|
254
|
-
const scanStarted = Date.now();
|
|
255
|
-
const candidates = await this.#scanCandidates(sourcePaths, [...sourceDirs]);
|
|
256
|
-
this.#logger.verbose(
|
|
257
|
-
`css candidates scanned count=${candidates.length} sources=${sourcePaths.length} dirs=${sourceDirs.size} in ${Date.now() - scanStarted}ms`,
|
|
258
|
-
);
|
|
259
258
|
const parts: string[] = [];
|
|
260
259
|
const imported: ImportedStylesheet[] = [];
|
|
261
260
|
for (const entry of compilers) {
|
|
262
|
-
const part = entry.compiler.build(candidates);
|
|
261
|
+
const part = entry.compiler ? entry.compiler.build(candidates) : entry.plainCss;
|
|
263
262
|
parts.push(part);
|
|
264
263
|
for (const [cssPath, content] of entry.imported) {
|
|
265
264
|
const declaredNames = declaredCustomProperties(content);
|
|
266
265
|
imported.push({ cssPath, declaredNames });
|
|
267
|
-
if (declaredNames.length === 0 || declaredNames.some((name) => part.includes(`${name}:`)))
|
|
266
|
+
if (!entry.compiler || declaredNames.length === 0 || declaredNames.some((name) => part.includes(`${name}:`)))
|
|
267
|
+
continue;
|
|
268
268
|
this.#logger.warn(
|
|
269
269
|
`css @import ${cssPath} was loaded by ${entry.cssPath} but none of its ${declaredNames.length} declaration(s) reached the compiled CSS`,
|
|
270
270
|
);
|
|
@@ -276,6 +276,26 @@ export class CssCompiler {
|
|
|
276
276
|
return { css: parts.join("\n"), imported };
|
|
277
277
|
}
|
|
278
278
|
|
|
279
|
+
// `compile()` stamps its banner on any stylesheet with an `@import`, so one that needs no Tailwind never reaches it.
|
|
280
|
+
async #compileStylesheet(cssPath: string): Promise<CompiledStylesheet> {
|
|
281
|
+
const css = await Bun.file(cssPath).text();
|
|
282
|
+
const base = path.dirname(cssPath);
|
|
283
|
+
const imported = new Map<string, string>();
|
|
284
|
+
const loadStylesheet = (id: string, fromBase: string) => this.#loadStylesheet(id, fromBase, imported);
|
|
285
|
+
const plainCss = await PlainStylesheet.bundle(css, base, loadStylesheet);
|
|
286
|
+
if (plainCss !== null) {
|
|
287
|
+
this.#logger.verbose(`css ${cssPath} uses no Tailwind; passed through with ${imported.size} import(s) inlined`);
|
|
288
|
+
return { cssPath, compiler: null, plainCss, imported };
|
|
289
|
+
}
|
|
290
|
+
imported.clear();
|
|
291
|
+
const compiler = await compile(css, {
|
|
292
|
+
base,
|
|
293
|
+
loadStylesheet,
|
|
294
|
+
loadModule: (id, fromBase) => this.#loadModule(id, fromBase),
|
|
295
|
+
});
|
|
296
|
+
return { cssPath, compiler, plainCss: "", imported };
|
|
297
|
+
}
|
|
298
|
+
|
|
279
299
|
async #loadStylesheet(id: string, fromBase: string, imported?: Map<string, string>) {
|
|
280
300
|
const p = await this.#resolveCssImport(id, fromBase);
|
|
281
301
|
this.#discoveredCssPaths.add(p);
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { PlainStylesheet, type StylesheetLoader } from "./plainStylesheet";
|
|
4
|
+
|
|
5
|
+
const loaderOf = (files: Record<string, string>): StylesheetLoader => {
|
|
6
|
+
return async (id, fromBase) => {
|
|
7
|
+
const filePath = path.resolve(fromBase, id);
|
|
8
|
+
const content = files[filePath];
|
|
9
|
+
if (content === undefined) throw new Error(`no stylesheet at ${filePath}`);
|
|
10
|
+
return { path: filePath, base: path.dirname(filePath), content };
|
|
11
|
+
};
|
|
12
|
+
};
|
|
13
|
+
const refuseLoad: StylesheetLoader = async (id) => {
|
|
14
|
+
throw new Error(`loaded ${id}`);
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
describe("PlainStylesheet.scan", () => {
|
|
18
|
+
test("finds nothing Tailwind in plain CSS", () => {
|
|
19
|
+
const css = [
|
|
20
|
+
'@charset "utf-8";',
|
|
21
|
+
"@layer reset, app;",
|
|
22
|
+
":root { --brand: #111; }",
|
|
23
|
+
"@media (prefers-reduced-motion: reduce) { .a { animation: none; } }",
|
|
24
|
+
"@supports (display: grid) { .grid { display: grid; } }",
|
|
25
|
+
"@container card (min-width: 20rem) { .b { color: color-mix(in oklab, var(--brand) 50%, transparent); } }",
|
|
26
|
+
"@font-face { font-family: X; src: url(data:font/woff2;base64,AAAA) format('woff2'); }",
|
|
27
|
+
"@keyframes spin { to { transform: rotate(1turn); } }",
|
|
28
|
+
'.c::before { content: "@apply theme(x)"; }',
|
|
29
|
+
"/* @theme { --color-x: red; } and --spacing(4) */",
|
|
30
|
+
".icon { background: url(icon@2x.png); }",
|
|
31
|
+
].join("\n");
|
|
32
|
+
expect(PlainStylesheet.scan(css)).toEqual([]);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test.each([
|
|
36
|
+
"@tailwind utilities;",
|
|
37
|
+
"@TAILWIND utilities;",
|
|
38
|
+
".a { @apply flex; }",
|
|
39
|
+
'@plugin "tailwind-scrollbar";',
|
|
40
|
+
'@config "./tailwind.config.js";',
|
|
41
|
+
"@theme { --color-brand: red; }",
|
|
42
|
+
"@theme inline { --color-brand: var(--brand); }",
|
|
43
|
+
"@utility tab-4 { tab-size: 4; }",
|
|
44
|
+
".a { @variant hover { color: red; } }",
|
|
45
|
+
"@custom-variant dark (&:where([data-theme=dark] *));",
|
|
46
|
+
"@custom-variant any-hover { @media (any-hover: hover) { &:hover { @slot; } } }",
|
|
47
|
+
'@source "../node_modules/x";',
|
|
48
|
+
'@source not "./legacy";',
|
|
49
|
+
'@source inline("underline");',
|
|
50
|
+
'@reference "./app.css";',
|
|
51
|
+
".a { color: theme(colors.red.500); }",
|
|
52
|
+
".a { color: --theme(--color-red-500); }",
|
|
53
|
+
".a { color: --alpha(var(--brand) / 50%); }",
|
|
54
|
+
".a { margin: --spacing(4); }",
|
|
55
|
+
"@media (width >= theme(--breakpoint-md)) { .a { color: red; } }",
|
|
56
|
+
"@media source(none) { .a { color: red; } }",
|
|
57
|
+
'@import "tailwindcss";',
|
|
58
|
+
"@import 'tailwindcss';",
|
|
59
|
+
'@import "tailwindcss/theme.css" layer(theme);',
|
|
60
|
+
'@import "tailwindcss/utilities";',
|
|
61
|
+
'@import "./theme.css" theme(reference);',
|
|
62
|
+
'@import "./app.css" source(none);',
|
|
63
|
+
'@import "./app.css" prefix(tw);',
|
|
64
|
+
'@import "./app.css" important;',
|
|
65
|
+
'@import "./app.css" reference;',
|
|
66
|
+
])("needs Tailwind: %s", (css) => {
|
|
67
|
+
expect(PlainStylesheet.scan(css)).toBeNull();
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test("reads the conditions of an import Tailwind would inline", () => {
|
|
71
|
+
const css = [
|
|
72
|
+
'@import "./a.css";',
|
|
73
|
+
"@import './b.css' layer;",
|
|
74
|
+
'@import "./c.css" layer(base) supports(display: grid) screen and (min-width: 40rem);',
|
|
75
|
+
'@import "./d.css" supports((display: flex) and (gap: 1rem)) print;',
|
|
76
|
+
].join("\n");
|
|
77
|
+
expect(
|
|
78
|
+
PlainStylesheet.scan(css)?.map(({ uri, layer, supports, media }) => ({ uri, layer, supports, media })),
|
|
79
|
+
).toEqual([
|
|
80
|
+
{ uri: "./a.css", layer: null, supports: null, media: null },
|
|
81
|
+
{ uri: "./b.css", layer: "", supports: null, media: null },
|
|
82
|
+
{ uri: "./c.css", layer: "base", supports: "display: grid", media: "screen and (min-width: 40rem)" },
|
|
83
|
+
{ uri: "./d.css", layer: null, supports: "(display: flex) and (gap: 1rem)", media: "print" },
|
|
84
|
+
]);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test("leaves url(), data: and remote imports where they stand, as Tailwind does", () => {
|
|
88
|
+
const css = [
|
|
89
|
+
'@import url("./a.css");',
|
|
90
|
+
"@import url(./b.css) screen;",
|
|
91
|
+
'@import "https://fonts.example.com/x.css";',
|
|
92
|
+
'@import "data:text/css,.a{color:red}";',
|
|
93
|
+
].join("\n");
|
|
94
|
+
expect(PlainStylesheet.scan(css)).toEqual([]);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test("defers to Tailwind on CSS it cannot read with certainty", () => {
|
|
98
|
+
expect(PlainStylesheet.scan("/* never closed")).toBeNull();
|
|
99
|
+
expect(PlainStylesheet.scan(".a { color: red;")).toBeNull();
|
|
100
|
+
expect(PlainStylesheet.scan(".a { color: red; } }")).toBeNull();
|
|
101
|
+
expect(PlainStylesheet.scan('@import "./a.css" layer(x) layer(y);')).toBeNull();
|
|
102
|
+
expect(PlainStylesheet.scan('@import "./a.css" supports(display: grid;')).toBeNull();
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
describe("PlainStylesheet.bundle", () => {
|
|
107
|
+
test("returns a stylesheet without imports byte for byte", async () => {
|
|
108
|
+
const css = "/* brand */\n:root {\n --brand: #111;\n}\n.a { color: var(--brand) }";
|
|
109
|
+
expect(await PlainStylesheet.bundle(css, "/app", refuseLoad)).toBe(css);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
test("inlines imports, nested ones too, wrapped in their layer, supports and media conditions", async () => {
|
|
113
|
+
const load = loaderOf({
|
|
114
|
+
"/app/a.css": '@import "./nested/b.css";\n.a { color: red; }\n',
|
|
115
|
+
"/app/nested/b.css": ".b { color: blue; }",
|
|
116
|
+
"/app/c.css": ".c { color: green; }",
|
|
117
|
+
});
|
|
118
|
+
const css =
|
|
119
|
+
'@import "./a.css";\n@import "./c.css" layer(base) supports(display: grid) print;\n.app { margin: 0; }\n';
|
|
120
|
+
|
|
121
|
+
expect(await PlainStylesheet.bundle(css, "/app", load)).toBe(
|
|
122
|
+
[
|
|
123
|
+
".b { color: blue; }",
|
|
124
|
+
".a { color: red; }",
|
|
125
|
+
"",
|
|
126
|
+
"@supports (display: grid) {",
|
|
127
|
+
"@media print {",
|
|
128
|
+
"@layer base {",
|
|
129
|
+
".c { color: green; }",
|
|
130
|
+
"}",
|
|
131
|
+
"}",
|
|
132
|
+
"}",
|
|
133
|
+
".app { margin: 0; }",
|
|
134
|
+
"",
|
|
135
|
+
].join("\n"),
|
|
136
|
+
);
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
test("needs Tailwind when only an imported stylesheet uses it", async () => {
|
|
140
|
+
const load = loaderOf({
|
|
141
|
+
"/app/a.css": '@import "./b.css";\n',
|
|
142
|
+
"/app/b.css": ".b { color: red; }\n@custom-variant dark (&:where(.dark *));\n",
|
|
143
|
+
});
|
|
144
|
+
expect(await PlainStylesheet.bundle('@import "./a.css";\n.app { margin: 0; }\n', "/app", load)).toBeNull();
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
test('decides on `@import "tailwindcss"` without resolving it', async () => {
|
|
148
|
+
expect(await PlainStylesheet.bundle('@import "tailwindcss";\n.a { color: red; }\n', "/app", refuseLoad)).toBeNull();
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
test("hands an import cycle to Tailwind instead of following it forever", async () => {
|
|
152
|
+
const load = loaderOf({ "/app/a.css": '@import "./b.css";', "/app/b.css": '@import "./a.css";' });
|
|
153
|
+
expect(await PlainStylesheet.bundle('@import "./a.css";', "/app", load)).toBeNull();
|
|
154
|
+
});
|
|
155
|
+
});
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
export interface LoadedStylesheet {
|
|
2
|
+
path: string;
|
|
3
|
+
base: string;
|
|
4
|
+
content: string;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export type StylesheetLoader = (id: string, fromBase: string) => Promise<LoadedStylesheet>;
|
|
8
|
+
|
|
9
|
+
interface ImportConditions {
|
|
10
|
+
layer: string | null;
|
|
11
|
+
supports: string | null;
|
|
12
|
+
media: string | null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface PlainImport extends ImportConditions {
|
|
16
|
+
start: number;
|
|
17
|
+
end: number;
|
|
18
|
+
uri: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Every at-rule Tailwind v4's `compile()` acts on (`parseCss`, `substituteAtImports`, `registerPlugins`, `@apply`).
|
|
22
|
+
const TAILWIND_AT_RULES = new Set([
|
|
23
|
+
"@tailwind",
|
|
24
|
+
"@apply",
|
|
25
|
+
"@plugin",
|
|
26
|
+
"@config",
|
|
27
|
+
"@theme",
|
|
28
|
+
"@utility",
|
|
29
|
+
"@variant",
|
|
30
|
+
"@custom-variant",
|
|
31
|
+
"@slot",
|
|
32
|
+
"@source",
|
|
33
|
+
"@reference",
|
|
34
|
+
]);
|
|
35
|
+
// Tailwind's own test (`theme\(` also covers `--theme(`), run over declaration values and media/supports params.
|
|
36
|
+
const TAILWIND_FUNCTION_RE = /(?:--alpha|--spacing|theme)\(/;
|
|
37
|
+
// `@import "x" theme(…)`, `source(…)`, `prefix(…)`, `important` and `reference` become Tailwind-only `@media` params.
|
|
38
|
+
const TAILWIND_CONDITION_RE = /\b(?:source|prefix|theme)\(|(?:^|\s)(?:important|reference)(?=\s|$)/i;
|
|
39
|
+
const TAILWIND_PACKAGE_RE = /^tailwindcss(?:\/|$)/;
|
|
40
|
+
const REMOTE_URI_RE = /^(?:data:|https?:\/\/)/i;
|
|
41
|
+
const COMMENT_RE = /\/\*[\s\S]*?\*\//g;
|
|
42
|
+
const AT_KEYWORD_RE = /@[\w-]+/y;
|
|
43
|
+
const QUOTED_IMPORT_RE = /^\s*(["'])((?:\\[\s\S]|(?!\1)[^\\\n])*)\1([\s\S]*)$/;
|
|
44
|
+
const LAYER_RE = /^layer(?:\(\s*([^()]*?)\s*\))?(?![\w(-])/i;
|
|
45
|
+
const MAX_IMPORT_DEPTH = 100;
|
|
46
|
+
|
|
47
|
+
interface OpenAtRule {
|
|
48
|
+
name: string;
|
|
49
|
+
start: number;
|
|
50
|
+
preludeStart: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
type AtRuleVerdict = (ImportConditions & { uri: string }) | "tailwind" | "plain";
|
|
54
|
+
|
|
55
|
+
export class PlainStylesheet {
|
|
56
|
+
static async bundle(css: string, base: string, load: StylesheetLoader, depth = 0): Promise<string | null> {
|
|
57
|
+
//? Past Tailwind's own depth limit (an import cycle), `compile()` runs instead and reports it.
|
|
58
|
+
if (depth > MAX_IMPORT_DEPTH) return null;
|
|
59
|
+
const imports = PlainStylesheet.scan(css);
|
|
60
|
+
if (!imports) return null;
|
|
61
|
+
const parts: string[] = [];
|
|
62
|
+
let cursor = 0;
|
|
63
|
+
for (const rule of imports) {
|
|
64
|
+
const loaded = await load(rule.uri, base);
|
|
65
|
+
const inner = await PlainStylesheet.bundle(loaded.content, loaded.base, load, depth + 1);
|
|
66
|
+
if (inner === null) return null;
|
|
67
|
+
parts.push(css.slice(cursor, rule.start), PlainStylesheet.#wrap(inner, rule));
|
|
68
|
+
cursor = rule.end;
|
|
69
|
+
}
|
|
70
|
+
parts.push(css.slice(cursor));
|
|
71
|
+
return parts.join("");
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
static scan(css: string): PlainImport[] | null {
|
|
75
|
+
const imports: PlainImport[] = [];
|
|
76
|
+
const code: string[] = [];
|
|
77
|
+
let segmentStart = 0;
|
|
78
|
+
let parenDepth = 0;
|
|
79
|
+
let braceDepth = 0;
|
|
80
|
+
let atRule: OpenAtRule | null = null;
|
|
81
|
+
let idx = 0;
|
|
82
|
+
while (idx < css.length) {
|
|
83
|
+
const char = css[idx];
|
|
84
|
+
if (char === "/" && css[idx + 1] === "*") {
|
|
85
|
+
const end = css.indexOf("*/", idx + 2);
|
|
86
|
+
if (end === -1) return null;
|
|
87
|
+
code.push(css.slice(segmentStart, idx));
|
|
88
|
+
idx = segmentStart = end + 2;
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
if (char === "\\") {
|
|
92
|
+
idx += 2;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (char === '"' || char === "'") {
|
|
96
|
+
code.push(css.slice(segmentStart, idx));
|
|
97
|
+
idx = segmentStart = PlainStylesheet.#skipString(css, idx);
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (char === "@" && !atRule && parenDepth === 0) {
|
|
101
|
+
AT_KEYWORD_RE.lastIndex = idx;
|
|
102
|
+
const keyword = AT_KEYWORD_RE.exec(css);
|
|
103
|
+
if (keyword) {
|
|
104
|
+
const name = keyword[0].toLowerCase();
|
|
105
|
+
if (TAILWIND_AT_RULES.has(name)) return null;
|
|
106
|
+
atRule = { name, start: idx, preludeStart: idx + keyword[0].length };
|
|
107
|
+
idx += keyword[0].length;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
if (char === "(") parenDepth += 1;
|
|
112
|
+
else if (char === ")") parenDepth = Math.max(0, parenDepth - 1);
|
|
113
|
+
else if (parenDepth === 0 && (char === ";" || char === "{" || char === "}")) {
|
|
114
|
+
if (atRule && !PlainStylesheet.#closeAtRule(css, atRule, idx, char, imports)) return null;
|
|
115
|
+
atRule = null;
|
|
116
|
+
braceDepth += char === "{" ? 1 : char === "}" ? -1 : 0;
|
|
117
|
+
if (braceDepth < 0) return null;
|
|
118
|
+
}
|
|
119
|
+
idx += 1;
|
|
120
|
+
}
|
|
121
|
+
if (atRule && !PlainStylesheet.#closeAtRule(css, atRule, css.length, "", imports)) return null;
|
|
122
|
+
if (braceDepth !== 0 || parenDepth !== 0) return null;
|
|
123
|
+
code.push(css.slice(segmentStart));
|
|
124
|
+
return TAILWIND_FUNCTION_RE.test(code.join(" ")) ? null : imports;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
static #closeAtRule(css: string, atRule: OpenAtRule, end: number, terminator: string, imports: PlainImport[]) {
|
|
128
|
+
const prelude = css.slice(atRule.preludeStart, end).replace(COMMENT_RE, " ");
|
|
129
|
+
const verdict = PlainStylesheet.#readAtRule(atRule.name, prelude, terminator === "{");
|
|
130
|
+
if (verdict === "tailwind") return false;
|
|
131
|
+
if (verdict !== "plain") imports.push({ ...verdict, start: atRule.start, end: terminator === ";" ? end + 1 : end });
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
static #readAtRule(name: string, prelude: string, opensBlock: boolean): AtRuleVerdict {
|
|
136
|
+
if (name === "@media") return TAILWIND_CONDITION_RE.test(prelude) ? "tailwind" : "plain";
|
|
137
|
+
if (name !== "@import") return "plain";
|
|
138
|
+
const match = QUOTED_IMPORT_RE.exec(prelude);
|
|
139
|
+
//? Tailwind leaves an `@import url(…)` where it stands, so this does too.
|
|
140
|
+
if (!match) return "plain";
|
|
141
|
+
const [, , uri = "", rest = ""] = match;
|
|
142
|
+
if (TAILWIND_PACKAGE_RE.test(uri) || TAILWIND_CONDITION_RE.test(rest) || opensBlock) return "tailwind";
|
|
143
|
+
if (REMOTE_URI_RE.test(uri)) return "plain";
|
|
144
|
+
const conditions = PlainStylesheet.#parseConditions(rest.trim());
|
|
145
|
+
return conditions ? { uri, ...conditions } : "tailwind";
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
static #parseConditions(text: string): ImportConditions | null {
|
|
149
|
+
let rest = text;
|
|
150
|
+
let layer: string | null = null;
|
|
151
|
+
let supports: string | null = null;
|
|
152
|
+
const layerMatch = LAYER_RE.exec(rest);
|
|
153
|
+
if (layerMatch) {
|
|
154
|
+
layer = layerMatch[1] ?? "";
|
|
155
|
+
rest = rest.slice(layerMatch[0].length).trim();
|
|
156
|
+
}
|
|
157
|
+
if (/^supports\(/i.test(rest)) {
|
|
158
|
+
const close = PlainStylesheet.#closingParen(rest, "supports".length);
|
|
159
|
+
if (close === -1) return null;
|
|
160
|
+
supports = rest.slice("supports(".length, close).trim();
|
|
161
|
+
rest = rest.slice(close + 1).trim();
|
|
162
|
+
}
|
|
163
|
+
if (/["']|\burl\(|\blayer\b|\bsupports\(/i.test(rest)) return null;
|
|
164
|
+
return { layer, supports, media: rest || null };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
static #closingParen(text: string, open: number): number {
|
|
168
|
+
let depth = 0;
|
|
169
|
+
for (let idx = open; idx < text.length; idx++) {
|
|
170
|
+
if (text[idx] === "(") depth += 1;
|
|
171
|
+
else if (text[idx] === ")" && --depth === 0) return idx;
|
|
172
|
+
}
|
|
173
|
+
return -1;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
static #wrap(css: string, { layer, media, supports }: PlainImport): string {
|
|
177
|
+
let wrapped = css;
|
|
178
|
+
if (layer !== null) wrapped = `@layer${layer ? ` ${layer}` : ""} {\n${wrapped}\n}`;
|
|
179
|
+
if (media !== null) wrapped = `@media ${media} {\n${wrapped}\n}`;
|
|
180
|
+
if (supports !== null)
|
|
181
|
+
wrapped = `@supports ${supports.startsWith("(") ? supports : `(${supports})`} {\n${wrapped}\n}`;
|
|
182
|
+
return wrapped;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
static #skipString(css: string, start: number): number {
|
|
186
|
+
const quote = css[start];
|
|
187
|
+
let idx = start + 1;
|
|
188
|
+
while (idx < css.length) {
|
|
189
|
+
const char = css[idx];
|
|
190
|
+
if (char === "\\") idx += 2;
|
|
191
|
+
else if (char === quote) return idx + 1;
|
|
192
|
+
else if (char === "\n") return idx;
|
|
193
|
+
else idx += 1;
|
|
194
|
+
}
|
|
195
|
+
return css.length;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
@@ -46,6 +46,16 @@ describe("AgentAssets", () => {
|
|
|
46
46
|
expect(references.filter((asset) => asset.path.includes("/agentRule")).length).toBeGreaterThan(1);
|
|
47
47
|
});
|
|
48
48
|
|
|
49
|
+
test("ships a guideline section on its own, and the skill's index names every entry in it", async () => {
|
|
50
|
+
const assets = await AgentAssets.skills();
|
|
51
|
+
const read = (file: string) => assets.find((asset) => asset.path === file)?.content ?? "";
|
|
52
|
+
const routes = read(".agents/skills/akan-page/references/akanApi-routes.md");
|
|
53
|
+
expect(read(".agents/skills/akan-page/SKILL.md")).toMatch(/akanApi-routes\.md` — Routes .*`Link`/);
|
|
54
|
+
expect(routes).toContain("### `Link` · `akanjs/ui`");
|
|
55
|
+
expect(routes).toContain("none of\nthem has to be looked up in `node_modules`");
|
|
56
|
+
expect(routes).not.toContain("## Endpoints");
|
|
57
|
+
});
|
|
58
|
+
|
|
49
59
|
test("names no rule or skill file that a new workspace's .gitignore would keep out of git", async () => {
|
|
50
60
|
const assets = [...(await AgentAssets.rules()), ...(await AgentAssets.skills())];
|
|
51
61
|
const root = await fsPromise.mkdtemp(path.join(os.tmpdir(), "akan-agent-ignore-"));
|
package/guideline/agentAssets.ts
CHANGED
|
@@ -31,7 +31,15 @@ export class AgentAssets {
|
|
|
31
31
|
"akan-scaffold": ["workspaceRecipes"],
|
|
32
32
|
"akan-module": ["moduleOverview", "modelConstant", "modelDictionary", "fieldRule"],
|
|
33
33
|
"akan-scalar": ["scalarModule", "scalarConstant", "scalarDictionary"],
|
|
34
|
-
"akan-service": [
|
|
34
|
+
"akan-service": [
|
|
35
|
+
"modelService",
|
|
36
|
+
"modelSignal",
|
|
37
|
+
"modelDocument",
|
|
38
|
+
"akanApi#imports",
|
|
39
|
+
"akanApi#services-and-adapters",
|
|
40
|
+
"akanApi#endpoints",
|
|
41
|
+
"akanApi#dictionaries",
|
|
42
|
+
],
|
|
35
43
|
"akan-store": ["modelStore"],
|
|
36
44
|
"akan-ui": [
|
|
37
45
|
"ssrRule",
|
|
@@ -48,7 +56,7 @@ export class AgentAssets {
|
|
|
48
56
|
"akan-err": ["errorCodes"],
|
|
49
57
|
"akan-deps": [],
|
|
50
58
|
"akan-debug": [],
|
|
51
|
-
"akan-page": ["pageRule", "akanApi"],
|
|
59
|
+
"akan-page": ["pageRule", "akanApi#imports", "akanApi#routes", "akanApi#app-config"],
|
|
52
60
|
"akan-query": ["queryRule"],
|
|
53
61
|
"akan-transport": ["transportRule"],
|
|
54
62
|
"akan-runtime": ["runtimeRule"],
|
|
@@ -101,14 +109,12 @@ ${AgentAssets.marker}
|
|
|
101
109
|
for (const [name, guidelines] of Object.entries(AgentAssets.skillReferences)) {
|
|
102
110
|
const source = await fsPromise.readFile(path.join(dir, name, "SKILL.md"), "utf-8");
|
|
103
111
|
const index: string[] = [];
|
|
104
|
-
for (const
|
|
105
|
-
const
|
|
106
|
-
parts.forEach((part, idx) => {
|
|
107
|
-
const file = parts.length === 1 ? `${guideline}.md` : `${guideline}-${idx + 1}.md`;
|
|
112
|
+
for (const reference of guidelines) {
|
|
113
|
+
for (const { file, text, summary } of await AgentAssets.#referenceFiles(reference)) {
|
|
108
114
|
const referencePath = `.agents/skills/${name}/references/${file}`;
|
|
109
|
-
assets.push({ path: referencePath, content: `${AgentAssets.marker}\n\n${
|
|
110
|
-
index.push(`- \`${referencePath}\` — ${
|
|
111
|
-
}
|
|
115
|
+
assets.push({ path: referencePath, content: `${AgentAssets.marker}\n\n${text.trim()}\n` });
|
|
116
|
+
index.push(`- \`${referencePath}\` — ${summary}`);
|
|
117
|
+
}
|
|
112
118
|
}
|
|
113
119
|
const skill = AgentAssets.#skillFile(source, index);
|
|
114
120
|
for (const root of AgentAssets.skillRoots) assets.push({ path: `${root}/${name}/SKILL.md`, content: skill });
|
|
@@ -116,7 +122,38 @@ ${AgentAssets.marker}
|
|
|
116
122
|
return assets;
|
|
117
123
|
}
|
|
118
124
|
|
|
119
|
-
static
|
|
125
|
+
static async #referenceFiles(reference: string) {
|
|
126
|
+
const [guideline = reference, slug] = reference.split("#");
|
|
127
|
+
const text = await Prompter.getInstruction(guideline);
|
|
128
|
+
if (slug) {
|
|
129
|
+
const sections = AgentAssets.sections(text);
|
|
130
|
+
const preamble = sections[0]?.headings.length === 0 ? sections[0].text : "";
|
|
131
|
+
const section = sections.find((each) => each.headings[0] && AgentAssets.slug(each.headings[0]) === slug);
|
|
132
|
+
if (!section) throw new Error(`Guideline ${guideline} has no section ${slug}`);
|
|
133
|
+
const entries = [...section.text.matchAll(/^### (.+?)(?: · .*)?$/gm)].map((match) => match[1]);
|
|
134
|
+
const title = section.headings[0];
|
|
135
|
+
return [
|
|
136
|
+
{
|
|
137
|
+
file: `${guideline}-${slug}.md`,
|
|
138
|
+
text: preamble ? `${preamble.trim()}\n\n${section.text.trim()}` : section.text,
|
|
139
|
+
summary: entries.length ? `${title}: ${entries.join(", ")}` : title,
|
|
140
|
+
},
|
|
141
|
+
];
|
|
142
|
+
}
|
|
143
|
+
const parts = AgentAssets.split(text);
|
|
144
|
+
return parts.map((part, idx) => ({
|
|
145
|
+
file: parts.length === 1 ? `${guideline}.md` : `${guideline}-${idx + 1}.md`,
|
|
146
|
+
text: part.text,
|
|
147
|
+
summary: AgentAssets.#summarize(part.headings),
|
|
148
|
+
}));
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
static slug(heading: string) {
|
|
152
|
+
const paren = heading.indexOf("(");
|
|
153
|
+
return (paren === -1 ? heading : heading.slice(0, paren).trimEnd()).toLowerCase().replace(/[^a-z0-9]+/g, "-");
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
static sections(markdown: string): ReferencePart[] {
|
|
120
157
|
const sections: ReferencePart[] = [];
|
|
121
158
|
let fenced = false;
|
|
122
159
|
for (const line of markdown.trim().split("\n")) {
|
|
@@ -126,8 +163,12 @@ ${AgentAssets.marker}
|
|
|
126
163
|
if (heading !== null || !last) sections.push({ text: line, headings: heading === null ? [] : [heading] });
|
|
127
164
|
else last.text += `\n${line}`;
|
|
128
165
|
}
|
|
166
|
+
return sections;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
static split(markdown: string): ReferencePart[] {
|
|
129
170
|
const parts: ReferencePart[] = [];
|
|
130
|
-
for (const section of sections) {
|
|
171
|
+
for (const section of AgentAssets.sections(markdown)) {
|
|
131
172
|
const last = parts.at(-1);
|
|
132
173
|
if (last && last.text.length + section.text.length + 1 <= AgentAssets.referenceLimit) {
|
|
133
174
|
last.text += `\n${section.text}`;
|
|
@@ -484,6 +484,27 @@ describe("NativeConfig.build", () => {
|
|
|
484
484
|
expect((await NativeApi.load(repoApp)).validateConfig(config, { appDir: root })).toEqual([]);
|
|
485
485
|
});
|
|
486
486
|
|
|
487
|
+
test("ios.hideFormAccessoryBar reaches the iOS shell, and the runtime accepts it; left out, the bar stays", async () => {
|
|
488
|
+
const root = await makeTempRoot();
|
|
489
|
+
const build = (ios?: { hideFormAccessoryBar?: boolean }) =>
|
|
490
|
+
NativeConfig.build({
|
|
491
|
+
appPath: root,
|
|
492
|
+
target: { ...minimalTarget, permissions: [], deepLinks: undefined, android: undefined, ios },
|
|
493
|
+
webDir: path.join(root, "web"),
|
|
494
|
+
contributions: [],
|
|
495
|
+
locales: ["en"],
|
|
496
|
+
platform: "ios",
|
|
497
|
+
}).config;
|
|
498
|
+
const config = build({ hideFormAccessoryBar: true });
|
|
499
|
+
|
|
500
|
+
expect(config.ios).toEqual({ hideFormAccessoryBar: true });
|
|
501
|
+
expect(build().ios).toBeUndefined();
|
|
502
|
+
expect(build({ hideFormAccessoryBar: false }).ios).toBeUndefined();
|
|
503
|
+
await mkdir(path.join(root, "web"), { recursive: true });
|
|
504
|
+
await writeFile(path.join(root, "web/index.html"), "<html><head></head><body></body></html>");
|
|
505
|
+
expect((await NativeApi.load(repoApp)).validateConfig(config, { appDir: root })).toEqual([]);
|
|
506
|
+
});
|
|
507
|
+
|
|
487
508
|
test("an app with updates ships the updates plugin and its settings", () => {
|
|
488
509
|
const updates = { url: "https://releases.example.com/board", publicKey: `${"a".repeat(43)}=`, channel: "pilot" };
|
|
489
510
|
const { config } = NativeConfig.build({
|
package/mobile/nativeConfig.ts
CHANGED
|
@@ -214,16 +214,7 @@ export class NativeConfig {
|
|
|
214
214
|
const native = NativeConfig.#compact({ ios, macos, android, resources });
|
|
215
215
|
const googleServices = target.android?.googleServices;
|
|
216
216
|
const pushAndroid = target.android?.push;
|
|
217
|
-
const desktop = NativeConfig.#
|
|
218
|
-
recovery: target.desktop?.recovery,
|
|
219
|
-
screenCapture: target.desktop?.screenCapture,
|
|
220
|
-
webview2: target.desktop?.webview2,
|
|
221
|
-
publisher: target.desktop?.publisher,
|
|
222
|
-
window: NativeConfig.#compact({ ...target.desktop?.window }),
|
|
223
|
-
server: desktopServer,
|
|
224
|
-
bin: desktopBin,
|
|
225
|
-
dmg: NativeConfig.#dmg(target.desktop?.dmg, abs),
|
|
226
|
-
});
|
|
217
|
+
const desktop = NativeConfig.#desktop(target.desktop, desktopServer, desktopBin, abs);
|
|
227
218
|
const background = target.backgroundColor;
|
|
228
219
|
const shell = NativeConfig.#compact<NonNullable<AkanNativeConfig["shell"]>>({
|
|
229
220
|
backgroundColor: typeof background === "string" ? background : background?.light,
|
|
@@ -270,6 +261,7 @@ export class NativeConfig {
|
|
|
270
261
|
}
|
|
271
262
|
: {}),
|
|
272
263
|
...(target.ios?.privacy ? { privacy: target.ios.privacy } : {}),
|
|
264
|
+
...(target.ios?.hideFormAccessoryBar ? { ios: { hideFormAccessoryBar: true } } : {}),
|
|
273
265
|
//? assetlinks.json vouches for `<appId>.debug` outside main, the suffix a debug build installs under.
|
|
274
266
|
android: {
|
|
275
267
|
debugAppIdSuffix: ".debug",
|
|
@@ -363,6 +355,24 @@ export class NativeConfig {
|
|
|
363
355
|
return { ...splash, ...(splash.image ? { image: abs(splash.image) } : {}) };
|
|
364
356
|
}
|
|
365
357
|
|
|
358
|
+
static #desktop(
|
|
359
|
+
desktop: AkanNativeTarget["desktop"],
|
|
360
|
+
server: DesktopServerBundle | undefined,
|
|
361
|
+
bin: string | undefined,
|
|
362
|
+
abs: (relative: string) => string,
|
|
363
|
+
) {
|
|
364
|
+
return NativeConfig.#compact<NonNullable<AkanNativeConfig["desktop"]>>({
|
|
365
|
+
recovery: desktop?.recovery,
|
|
366
|
+
screenCapture: desktop?.screenCapture,
|
|
367
|
+
webview2: desktop?.webview2,
|
|
368
|
+
publisher: desktop?.publisher,
|
|
369
|
+
window: NativeConfig.#compact({ ...desktop?.window }),
|
|
370
|
+
server,
|
|
371
|
+
bin,
|
|
372
|
+
dmg: NativeConfig.#dmg(desktop?.dmg, abs),
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
|
|
366
376
|
static #dmg(dmg: AkanNativeDmgConfig | undefined, abs: (relative: string) => string) {
|
|
367
377
|
if (!dmg) return undefined;
|
|
368
378
|
const { background, background2x, ...layout } = dmg;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@akanjs/devkit",
|
|
3
|
-
"version": "3.3.0-rc.
|
|
3
|
+
"version": "3.3.0-rc.4",
|
|
4
4
|
"sourceType": "module",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -205,7 +205,7 @@
|
|
|
205
205
|
"./*": "./*.ts"
|
|
206
206
|
},
|
|
207
207
|
"dependencies": {
|
|
208
|
-
"@akanjs/language": "3.3.0-rc.
|
|
208
|
+
"@akanjs/language": "3.3.0-rc.4",
|
|
209
209
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
210
210
|
"@earendil-works/pi-ai": "1.5.2",
|
|
211
211
|
"@earendil-works/pi-codemode": "1.5.2",
|
|
@@ -214,7 +214,7 @@
|
|
|
214
214
|
"@earendil-works/pi-tui": "1.5.2",
|
|
215
215
|
"@inquirer/prompts": "^8.7.3",
|
|
216
216
|
"@tailwindcss/node": "^4.3.3",
|
|
217
|
-
"akanjs": "3.3.0-rc.
|
|
217
|
+
"akanjs": "3.3.0-rc.4",
|
|
218
218
|
"chalk": "^6.0.1",
|
|
219
219
|
"commander": "^15.0.0",
|
|
220
220
|
"dayjs": "^1.11.23",
|