@akanjs/devkit 3.3.0-rc.2 → 3.3.0-rc.21
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 +284 -20
- package/DEV_RUNTIME_KNOBS.md +1 -1
- package/README.ko.md +3 -2
- package/README.md +3 -3
- package/akanApp/akanApp.host.test.ts +1 -1
- package/akanConfig/akanConfig.test.ts +57 -8
- package/akanConfig/akanConfig.ts +16 -69
- package/akanConfig/dockerImage.ts +17 -0
- package/akanConfig/nativeKeys.ts +52 -0
- package/app/applicationBuildRunner.test.ts +321 -1
- package/app/applicationBuildRunner.ts +90 -3
- package/artifact/implicitRootLayoutRender.test.tsx +4 -1
- package/codeAgent/agent/CodeAgent.ts +36 -16
- package/codeAgent/agent/CodeAgentAllowed.ts +35 -0
- package/codeAgent/agent/CodeAgentCommandLine.ts +372 -0
- package/codeAgent/agent/CodeAgentGate.ts +23 -4
- package/codeAgent/agent/CodeAgentRpcHost.ts +1 -1
- package/codeAgent/agent/codeAgent.test.ts +62 -0
- package/codeAgent/agent/codeAgentCommandLine.test.ts +212 -0
- package/codeAgent/agent/codeAgentContract.test.ts +117 -5
- package/codeAgent/skills/akan-agent/SKILL.md +8 -1
- package/codeAgent/skills/akan-code/SKILL.md +38 -3
- package/codeAgent/skills/akan-err/SKILL.md +11 -2
- package/codeAgent/skills/akan-page/SKILL.md +21 -26
- package/codeAgent/skills/akan-runtime/SKILL.md +41 -16
- package/codeAgent/skills/akan-service/SKILL.md +2 -2
- package/docs/apiReference.test.ts +14 -0
- package/docs/apiReference.ts +21 -3
- package/docs/declarationReader.ts +28 -1
- package/executors/appExecutor.ts +16 -7
- package/executors/workspaceExecutor.ts +7 -4
- package/frontendBuild/buildRouteClient.test.ts +2 -7
- package/frontendBuild/clientEntryDiscovery.test.ts +35 -0
- package/frontendBuild/clientEntryDiscovery.ts +16 -3
- package/frontendBuild/cssCompiler.test.ts +112 -0
- package/frontendBuild/cssCompiler.ts +41 -21
- package/frontendBuild/devBarrelImports.test.ts +30 -0
- package/frontendBuild/devBarrelImports.ts +2 -2
- package/frontendBuild/pagesBundleBuilder.ts +3 -1
- package/frontendBuild/plainStylesheet.test.ts +155 -0
- package/frontendBuild/plainStylesheet.ts +197 -0
- package/frontendBuild/rscServerRendererGuard.test.ts +60 -0
- package/frontendBuild/rscServerRendererGuard.ts +68 -0
- package/guideline/agentAssets.test.ts +10 -0
- package/guideline/agentAssets.ts +52 -11
- package/incrementalBuilder/buildBatch.proc.ts +9 -9
- package/incrementalBuilder/buildBatchProtocol.ts +1 -1
- package/incrementalBuilder/builderBoot.ts +5 -5
- package/incrementalBuilder/builderGraphPayloads.ts +4 -4
- package/incrementalBuilder/builderLanes.ts +2 -2
- package/incrementalBuilder/builderWatch.ts +8 -8
- package/incrementalBuilder/csrRegistry.ts +4 -4
- package/incrementalBuilder/incrementalBuilder.proc.ts +8 -8
- package/incrementalBuilder/ssrRegistry.ts +6 -6
- package/index.ts +1 -1
- package/integration/renderAdmissionSoak.test.ts +99 -0
- package/integration/renderAdmissionSoak.ts +609 -0
- package/lint/__fixtures__/no-arbitrary-color/every-color-function/bad.tsx +11 -0
- package/lint/__fixtures__/no-arbitrary-color/every-color-function/good.tsx +2 -0
- package/lint/__fixtures__/no-daisyui-legacy-class/every-class/bad.tsx +34 -0
- package/lint/__fixtures__/no-daisyui-legacy-class/every-class/good.tsx +2 -0
- package/lint/__fixtures__/no-inline-color/every-color-function/bad.tsx +10 -0
- package/lint/__fixtures__/no-inline-color/every-color-function/good.tsx +2 -0
- package/lint/__fixtures__/no-raw-palette-class/every-palette/bad.tsx +22 -0
- package/lint/__fixtures__/no-raw-palette-class/every-palette/good.tsx +2 -0
- package/lint/biomeCheck.test.ts +145 -0
- package/lint/biomeCheck.ts +131 -0
- package/lint/no-arbitrary-color.grit +5 -0
- package/lint/no-conditional-st-hook.grit +5 -1
- package/lint/no-daisyui-legacy-class.grit +8 -0
- package/lint/no-document-cookie.grit +3 -0
- package/lint/no-inline-color.grit +10 -2
- package/lint/no-oversized-list-limit.grit +2 -0
- package/lint/no-raw-palette-class.grit +7 -0
- package/lint/no-unpublished-form-setter.grit +2 -0
- package/lint/no-web-only-api-outside-webkit.grit +5 -0
- package/lint/no-web-storage.grit +3 -0
- package/lint/withheldEnvFile.ts +17 -0
- package/mobile/nativeApp.test.ts +7 -5
- package/mobile/nativeApp.ts +2 -2
- package/mobile/nativeConfig.test.ts +117 -1
- package/mobile/nativeConfig.ts +66 -22
- package/mobile/serverBundleSecrets.ts +43 -0
- package/package.json +14 -169
- package/packageExports.test.ts +38 -24
- package/test/secretEnvFixture.ts +134 -0
- package/transforms/barrelAnalyzer.ts +2 -2
- package/transforms/secretEnvDeclaration.test.ts +208 -0
- package/transforms/secretEnvDeclaration.ts +213 -0
- package/transforms/secretEnvFile.test.ts +117 -0
- package/transforms/secretEnvFile.ts +113 -0
- package/transforms/secretEnvName.test.ts +54 -0
- package/transforms/secretEnvName.ts +29 -0
- package/transforms/secretEnvSource.test.ts +148 -0
- package/transforms/secretEnvSource.ts +166 -0
- package/transforms/serverEnvEvaluationError.ts +11 -0
- package/transforms/serverEnvPlugin.test.ts +2 -1
- package/transforms/serverEnvPlugin.ts +13 -0
- package/transforms/serverEnvProfile.test.ts +115 -2
- package/transforms/serverEnvProfile.ts +117 -40
- package/transforms/serverEnvSecrets.test.ts +292 -0
- package/transforms/transforms.test.ts +3 -3
- package/tunnel/createTunnel.test.ts +29 -8
- package/tunnel/createTunnel.ts +18 -11
- package/typecheck/projectTypecheck.test.ts +29 -0
- package/typecheck/typeChecker.test.ts +49 -0
- package/typecheck/typeChecker.ts +9 -7
- package/typecheck/withheldDiagnostics.ts +41 -0
- package/util/fileEditor.ts +1 -0
- package/util/selectModel.ts +1 -0
- package/workspace/getRelatedCnsts.ts +7 -0
|
@@ -28,6 +28,20 @@ describe("ApiReference", () => {
|
|
|
28
28
|
expect(rendered).toMatch(/^\/\*\* .+ \*\/\nserverMode\?: "batch" \| "federation";$/m);
|
|
29
29
|
});
|
|
30
30
|
|
|
31
|
+
test("says what each listed subpath holds, and lists only subpaths the package exports", async () => {
|
|
32
|
+
const exports = Object.keys((await Bun.file(path.join(akanjsDir, "package.json")).json()).exports);
|
|
33
|
+
const listed = [...rendered.matchAll(/^- `akanjs\/([^`]+)` — .+\.$/gm)].map(([, subpath]) => `./${subpath}`);
|
|
34
|
+
expect(listed).toEqual(
|
|
35
|
+
["dictionary", "document", "service", "store", "client/native", "native/desktop", "test"].map((s) => `./${s}`),
|
|
36
|
+
);
|
|
37
|
+
for (const subpath of listed) expect(exports).toContain(subpath);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("says what Link takes beyond its own props, and names its static parts", () => {
|
|
41
|
+
expect(rendered).toContain('Every prop of `Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href">`, and:');
|
|
42
|
+
expect(rendered).toMatch(/^Link\.Back\(.+\): Element$/m);
|
|
43
|
+
});
|
|
44
|
+
|
|
31
45
|
test("lists the keys of akan.config.ts, so the web and i18n shapes have a field to belong to", () => {
|
|
32
46
|
const appConfig = rendered.slice(rendered.indexOf("### `AppConfigInput`"));
|
|
33
47
|
expect(appConfig).toMatch(/^web\?: AkanWebOption;$/m);
|
package/docs/apiReference.ts
CHANGED
|
@@ -118,6 +118,16 @@ const conventionImports = [
|
|
|
118
118
|
'import { signedIn } from "@libs/shared/webkit"; // a workspace created with --libs true',
|
|
119
119
|
];
|
|
120
120
|
|
|
121
|
+
const subpathPurposes = [
|
|
122
|
+
["akanjs/dictionary", "locales, translations and the dictionaries behind labels, descriptions and `Err` keys"],
|
|
123
|
+
["akanjs/document", "database documents, filters, query builders, full-text search and persistence"],
|
|
124
|
+
["akanjs/service", "services, adapters, dependency injection and the business-logic runtime"],
|
|
125
|
+
["akanjs/store", "domain state, actions and the in-page agent's `st.tool` / `st.use` surface"],
|
|
126
|
+
["akanjs/client/native", "the native bridge and the built-in plugins of iOS, Android and desktop apps"],
|
|
127
|
+
["akanjs/native/desktop", "what an app's or a lib's own native plugin builds its desktop part from"],
|
|
128
|
+
["akanjs/test", "signal-test setup, MCP catalogue checks and sample data (`sampleOf`)"],
|
|
129
|
+
] as const;
|
|
130
|
+
|
|
121
131
|
const routeInternals = ["assertPattern", "resolveArgs", "toRouteModule"];
|
|
122
132
|
|
|
123
133
|
export class ApiReference {
|
|
@@ -153,13 +163,17 @@ export class ApiReference {
|
|
|
153
163
|
"Generated from the akanjs sources of this release: the import paths and signatures a first app needs, so none of",
|
|
154
164
|
"them has to be looked up in `node_modules`. A stage's return type is the same chain, left out below.",
|
|
155
165
|
"",
|
|
156
|
-
"## Imports",
|
|
166
|
+
"## Imports (`akanjs/*`, `@apps/<app>/client`, `../cnst`, `../dict`, `../srv`, layer barrels)",
|
|
157
167
|
"",
|
|
158
168
|
"```ts",
|
|
159
169
|
...importLines,
|
|
160
170
|
...conventionImports,
|
|
161
171
|
"```",
|
|
162
172
|
"",
|
|
173
|
+
"What these subpaths hold:",
|
|
174
|
+
"",
|
|
175
|
+
...subpathPurposes.map(([from, purpose]) => `- \`${from}\` — ${purpose}.`),
|
|
176
|
+
"",
|
|
163
177
|
...body,
|
|
164
178
|
]
|
|
165
179
|
.join("\n")
|
|
@@ -183,8 +197,12 @@ export class ApiReference {
|
|
|
183
197
|
return [heading, "", "```ts", reader.declarationText(symbol), "```"].join("\n");
|
|
184
198
|
if (item.show.kind === "signature")
|
|
185
199
|
return [heading, "", "```ts", ...reader.signatures(symbol, item.name), "```"].join("\n");
|
|
186
|
-
if (item.show.kind === "props")
|
|
187
|
-
|
|
200
|
+
if (item.show.kind === "props") {
|
|
201
|
+
const bases = reader.foreignBases(symbol).map((base) => `\`${base}\``);
|
|
202
|
+
const inherits = bases.length ? ["", `Every prop of ${bases.join(" and ")}, and:`] : [];
|
|
203
|
+
const props = reader.props(reader.declaredType(symbol), item.show.omit);
|
|
204
|
+
return [heading, ...inherits, "", "```ts", ...props, "```"].join("\n");
|
|
205
|
+
}
|
|
188
206
|
const members = reader.members(reader.instanceType(symbol), item.show);
|
|
189
207
|
return [heading, "", "```ts", ...members.map(([, line]) => line), "```"].join("\n");
|
|
190
208
|
}
|
|
@@ -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.
|
|
@@ -8,12 +8,15 @@ import type { BaseDevEnv, TsConfigJson } from "../workspace/types";
|
|
|
8
8
|
import { Executor, execEmoji } from "./executor";
|
|
9
9
|
import { SysExecutor } from "./sysExecutor";
|
|
10
10
|
|
|
11
|
-
//? As Bun's
|
|
11
|
+
//? As Bun's .env loader reads it (1.4.4), which fills process.env too: `#` ends an unquoted value mid-word, `\$` is `$`.
|
|
12
12
|
const parseEnvValue = (value: string) => {
|
|
13
13
|
const [, quote, inner] = value.match(/^(["'`])((?:\\.|(?!\1)[^\\])*)\1/) ?? [];
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
14
|
+
const text = !quote
|
|
15
|
+
? value.replace(/#.*/, "").trim()
|
|
16
|
+
: quote !== '"'
|
|
17
|
+
? inner
|
|
18
|
+
: inner.replace(/\\(.)/g, (pair, char: string) => (char === "n" ? "\n" : char === "r" ? "\r" : pair));
|
|
19
|
+
return text.replaceAll("\\$", "$");
|
|
17
20
|
};
|
|
18
21
|
|
|
19
22
|
export const parseEnvFile = (envPath: string): Record<string, string> => {
|
|
@@ -428,14 +428,9 @@ describe("route client store bootstrap", () => {
|
|
|
428
428
|
await write(uiEntry, 'export { ClientPathWrapper } from "./System/Client";\n');
|
|
429
429
|
await write(clientEntry, '"use client";\nexport const ClientPathWrapper = () => null;\n');
|
|
430
430
|
|
|
431
|
-
const entryFiles = new Map([
|
|
432
|
-
["akanjs/ui", uiEntry],
|
|
433
|
-
["akanjs/ui/System/Client.tsx", clientEntry],
|
|
434
|
-
]);
|
|
435
431
|
const discovery = new GraphClientEntryDiscovery({ barrelImports: ["akanjs/ui"] }, async (specifier) => {
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
return { pkgName: specifier, entryFile, pkgDir: path.dirname(entryFile), preserveFilePath: true };
|
|
432
|
+
if (specifier !== "akanjs/ui") return null;
|
|
433
|
+
return { pkgName: specifier, entryFile: uiEntry, pkgDir: path.dirname(uiEntry), preserveFilePath: true };
|
|
439
434
|
});
|
|
440
435
|
|
|
441
436
|
expect(await discovery.discover([seed])).toEqual([clientEntry]);
|
|
@@ -189,4 +189,39 @@ describe("GraphClientEntryDiscovery", () => {
|
|
|
189
189
|
fresh.invalidate([file("Server.tsx")]);
|
|
190
190
|
expect(await fresh.discover([file("Page.tsx")], { importsAs })).toEqual([]);
|
|
191
191
|
});
|
|
192
|
+
|
|
193
|
+
test("a client file exporting only hooks is no entry of a server graph that imports it, one with a component still is", async () => {
|
|
194
|
+
const file = await tempDir();
|
|
195
|
+
await Bun.write(file("Layout.tsx"), 'import "./store";\nimport "./Panel";\n');
|
|
196
|
+
await Bun.write(
|
|
197
|
+
file("store.ts"),
|
|
198
|
+
'import { useForm } from "./useForm";\nimport { useEffect } from "./reactHooks";\nimport "./useMixed";\nexport const st = { useForm, useEffect };\n',
|
|
199
|
+
);
|
|
200
|
+
await Bun.write(
|
|
201
|
+
file("useForm.ts"),
|
|
202
|
+
'"use client";\nimport "./Inner";\nexport interface FormShape {}\nexport const useForm = () => null;\nexport function useOther() {}\n',
|
|
203
|
+
);
|
|
204
|
+
await Bun.write(file("reactHooks.ts"), '"use client";\nexport { useContext, useEffect } from "react";\n');
|
|
205
|
+
await Bun.write(
|
|
206
|
+
file("useMixed.ts"),
|
|
207
|
+
'"use client";\nexport const useMixed = () => null;\nexport const Mixed = () => null;\n',
|
|
208
|
+
);
|
|
209
|
+
await Bun.write(file("Inner.tsx"), '"use client";\nexport const Inner = () => null;\n');
|
|
210
|
+
await Bun.write(
|
|
211
|
+
file("Panel.tsx"),
|
|
212
|
+
'"use client";\nimport { useForm } from "./useForm";\nexport const Panel = () => useForm();\n',
|
|
213
|
+
);
|
|
214
|
+
const discovery = new GraphClientEntryDiscovery({ barrelImports: [] }, (async () => null) as never);
|
|
215
|
+
expect(await discovery.discover([file("Layout.tsx")])).toEqual([file("Panel.tsx"), file("useMixed.ts")]);
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
test("a client file with a default export or a star re-export stays an entry", async () => {
|
|
219
|
+
const file = await tempDir();
|
|
220
|
+
await Bun.write(file("S.tsx"), 'import "./A";\nimport "./B";\nimport "./C";\n');
|
|
221
|
+
await Bun.write(file("A.ts"), '"use client";\nexport default function useA() {}\n');
|
|
222
|
+
await Bun.write(file("B.ts"), '"use client";\nexport * from "./C";\nexport const useB = () => null;\n');
|
|
223
|
+
await Bun.write(file("C.ts"), '"use client";\nexport const C = () => null;\n');
|
|
224
|
+
const discovery = new GraphClientEntryDiscovery({ barrelImports: [] }, (async () => null) as never);
|
|
225
|
+
expect(await discovery.discover([file("S.tsx")])).toEqual([file("A.ts"), file("B.ts"), file("C.ts")]);
|
|
226
|
+
});
|
|
192
227
|
});
|
|
@@ -7,6 +7,8 @@ import { createTsconfigPackageResolver, rewriteBarrelImports } from "../transfor
|
|
|
7
7
|
import type { AkanConfig, ClientEntryDiscovery, DiscoverOptions, ScannedImport } from "./clientBuildTypes";
|
|
8
8
|
|
|
9
9
|
const USE_CLIENT_RE = /^\s*(?:\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\/\s*|\/\/[^\n]*\n\s*)*["']use client["']/;
|
|
10
|
+
const EXPORT_STAR_RE = /^\s*export\s*\*/m;
|
|
11
|
+
const HOOK_NAME_RE = /^use[A-Z0-9]/;
|
|
10
12
|
const NODE_MODULES_RE = /[\\/]node_modules[\\/]/;
|
|
11
13
|
const AKANJS_NODE_MODULE_RE = /[\\/]node_modules[\\/]akanjs[\\/]/;
|
|
12
14
|
// Bun's scanImports also surfaces CSS and asset imports, none of which can be a client component.
|
|
@@ -172,7 +174,7 @@ export class GraphClientEntryDiscovery implements ClientEntryDiscovery {
|
|
|
172
174
|
.catch(() => null);
|
|
173
175
|
if (content === null) return null;
|
|
174
176
|
this.#readFiles.add(absPath);
|
|
175
|
-
if (USE_CLIENT_RE.test(content)) return { isClientEntry:
|
|
177
|
+
if (USE_CLIENT_RE.test(content)) return { isClientEntry: !this.#exportsOnlyHooks(content), imports: [] };
|
|
176
178
|
return { isClientEntry: false, imports: this.#scanImports(await this.#rewrite(content, absPath)) };
|
|
177
179
|
})();
|
|
178
180
|
this.#factsCache.set(absPath, cached);
|
|
@@ -191,6 +193,17 @@ export class GraphClientEntryDiscovery implements ClientEntryDiscovery {
|
|
|
191
193
|
}
|
|
192
194
|
}
|
|
193
195
|
|
|
196
|
+
//? A hook is never rendered, so no flight row names its file; `export *` hides names from the scan, so it stays an entry.
|
|
197
|
+
#exportsOnlyHooks(content: string): boolean {
|
|
198
|
+
if (EXPORT_STAR_RE.test(content)) return false;
|
|
199
|
+
try {
|
|
200
|
+
const { exports } = this.#tsTranspiler.scan(content);
|
|
201
|
+
return exports.length > 0 && exports.every((name) => HOOK_NAME_RE.test(name));
|
|
202
|
+
} catch {
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
194
207
|
#scanImports(source: string): ScannedImport[] {
|
|
195
208
|
try {
|
|
196
209
|
return this.#tsTranspiler.scanImports(source);
|
|
@@ -226,8 +239,8 @@ export class GraphClientEntryDiscovery implements ClientEntryDiscovery {
|
|
|
226
239
|
this.#resolvedSpecifierCache,
|
|
227
240
|
cacheKey,
|
|
228
241
|
async () => {
|
|
229
|
-
if (spec.startsWith(".") ||
|
|
230
|
-
const abs =
|
|
242
|
+
if (spec.startsWith(".") || path.isAbsolute(spec)) {
|
|
243
|
+
const abs = path.resolve(importerDir, spec);
|
|
231
244
|
return await this.#resolveFileCandidate(abs);
|
|
232
245
|
}
|
|
233
246
|
const pkg = await this.#resolvePackage(spec);
|
|
@@ -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,30 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { mkdir, realpath, symlink } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { tempDirs, writeText as write } from "../test/testHelpers";
|
|
5
|
+
import { DevBarrelImports } from "./devBarrelImports";
|
|
6
|
+
|
|
7
|
+
const makeTempRoot = tempDirs("akan-dev-barrel-imports-");
|
|
8
|
+
|
|
9
|
+
describe("DevBarrelImports", () => {
|
|
10
|
+
test("points an installed package's import at the real file behind its link, relative to the importer", async () => {
|
|
11
|
+
const root = await realpath(await makeTempRoot());
|
|
12
|
+
const installed = path.join(root, "store/akanjs");
|
|
13
|
+
await write(path.join(installed, "ui/index.ts"), 'export { Link } from "./Link";\n');
|
|
14
|
+
await write(path.join(installed, "ui/Link/index.tsx"), "export const Link = () => null;\n");
|
|
15
|
+
await mkdir(path.join(root, "node_modules"), { recursive: true });
|
|
16
|
+
await symlink(installed, path.join(root, "node_modules/akanjs"));
|
|
17
|
+
const uiEntry = path.join(root, "node_modules/akanjs/ui/index.ts");
|
|
18
|
+
const importer = path.join(root, "apps/demo/page/_index.tsx");
|
|
19
|
+
await write(importer, "");
|
|
20
|
+
|
|
21
|
+
const barrels = new DevBarrelImports(["akanjs/ui"], async (specifier) =>
|
|
22
|
+
specifier === "akanjs/ui"
|
|
23
|
+
? { pkgName: specifier, entryFile: uiEntry, pkgDir: path.dirname(uiEntry), preserveFilePath: true }
|
|
24
|
+
: null,
|
|
25
|
+
);
|
|
26
|
+
const rewrite = await barrels.rewrite('import { Link } from "akanjs/ui";\n', importer);
|
|
27
|
+
|
|
28
|
+
expect(rewrite?.contents).toBe('import { Link } from "../../../store/akanjs/ui/Link/index.tsx";\n');
|
|
29
|
+
});
|
|
30
|
+
});
|
|
@@ -115,8 +115,8 @@ export class DevBarrelImports {
|
|
|
115
115
|
|
|
116
116
|
static #fileOf(subpath: string, packages: PackageEntry[]): string | null {
|
|
117
117
|
const pkg = packages.find(({ pkgName }) => subpath === pkgName || subpath.startsWith(`${pkgName}/`));
|
|
118
|
-
if (!pkg) return null;
|
|
119
|
-
const file = CsrDevPaths.resolveOnDisk(path.join(pkg.pkgDir, subpath.slice(pkg.pkgName.length)));
|
|
118
|
+
if (!pkg && !path.isAbsolute(subpath)) return null;
|
|
119
|
+
const file = CsrDevPaths.resolveOnDisk(pkg ? path.join(pkg.pkgDir, subpath.slice(pkg.pkgName.length)) : subpath);
|
|
120
120
|
return file ? CsrDevPaths.realpath(file) : null;
|
|
121
121
|
}
|
|
122
122
|
|
|
@@ -13,6 +13,7 @@ import { createUseClientBundlePlugin } from "../transforms/useClientBundlePlugin
|
|
|
13
13
|
import { bundleDefine } from "./bundleDefine";
|
|
14
14
|
import { CsrDevPaths } from "./csrDevPaths";
|
|
15
15
|
import { PagesEntrySourceGenerator } from "./pagesEntrySourceGenerator";
|
|
16
|
+
import { RscServerRendererGuard } from "./rscServerRendererGuard";
|
|
16
17
|
import { ServerGraphFile } from "./serverGraphFile";
|
|
17
18
|
|
|
18
19
|
export interface BuildPagesBundleResult {
|
|
@@ -74,7 +75,7 @@ export class PagesBundleBuilder {
|
|
|
74
75
|
asset: "assets/[name]-[hash].[ext]",
|
|
75
76
|
},
|
|
76
77
|
define: bundleDefine(this.#app, this.#command, "ssr"),
|
|
77
|
-
metafile:
|
|
78
|
+
metafile: true,
|
|
78
79
|
plugins: [
|
|
79
80
|
//? First: the use-client plugins below load every module, and an env file must be swapped before they do.
|
|
80
81
|
...(this.#serverEnv ? [this.#serverEnv] : []),
|
|
@@ -96,6 +97,7 @@ export class PagesBundleBuilder {
|
|
|
96
97
|
});
|
|
97
98
|
|
|
98
99
|
if (!result.success) throw new AggregateError(result.logs, "[PagesBundleBuilder] Bun.build failed");
|
|
100
|
+
RscServerRendererGuard.assert(result.metafile, workspaceRoot);
|
|
99
101
|
|
|
100
102
|
const entryArtifact = result.outputs.find((a) => a.kind === "entry-point");
|
|
101
103
|
if (!entryArtifact) throw new Error("[PagesBundleBuilder] Bun.build emitted no entry-point artifact");
|