@akanjs/devkit 3.2.0-rc.12 → 3.2.0-rc.14
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 +8 -0
- package/akanApp/akanApp.host.test.ts +113 -0
- package/akanApp/akanApp.host.ts +145 -1215
- package/akanApp/builderGap.ts +68 -0
- package/akanApp/builderRequestRelay.test.ts +93 -0
- package/akanApp/builderRequestRelay.ts +101 -0
- package/akanApp/builderRssRecycler.ts +182 -0
- package/akanApp/devBackend.ts +392 -0
- package/akanApp/devBuildStatusBoard.ts +128 -0
- package/akanApp/devBuilder.ts +196 -0
- package/akanApp/devIdleSuspend.test.ts +130 -0
- package/akanApp/devIdleSuspend.ts +169 -0
- package/akanApp/devRecycler.test.ts +66 -0
- package/akanApp/devRecycler.ts +305 -0
- package/akanApp/processRss.ts +61 -0
- package/akanConfig/akanConfig.test.ts +23 -0
- package/akanConfig/akanConfig.ts +9 -9
- package/executors/appExecutor.ts +448 -0
- package/executors/commandExecutionError.ts +53 -0
- package/executors/executor.ts +527 -0
- package/executors/libExecutor.ts +23 -0
- package/executors/moduleExecutor.ts +18 -0
- package/executors/pkgExecutor.ts +129 -0
- package/executors/sysExecutor.ts +301 -0
- package/executors/workspaceExecutor.ts +278 -0
- package/executors.test.ts +44 -0
- package/executors.ts +8 -1749
- package/package.json +3 -3
- package/scanInfo.ts +19 -8
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { capitalize, getPageSourceFileViolation } from "akanjs/common";
|
|
4
|
+
import {
|
|
5
|
+
renderScopeAgentBlock,
|
|
6
|
+
renderScopeAgentsMd,
|
|
7
|
+
renderScopeClaudeMd,
|
|
8
|
+
scanScopeRecipes,
|
|
9
|
+
upsertAgentBlock,
|
|
10
|
+
} from "../agentsIndex";
|
|
11
|
+
import { AkanAppConfig, AkanLibConfig } from "../akanConfig";
|
|
12
|
+
import { CodegenLock } from "../codegenLock";
|
|
13
|
+
import { EnvSeed } from "../envSeed";
|
|
14
|
+
import { ManifestDependencies } from "../manifestDependencies";
|
|
15
|
+
import { AppInfo, isAkanFrameworkDependency, LibInfo } from "../scanInfo";
|
|
16
|
+
import type { FileContent } from "../types";
|
|
17
|
+
import { barrelFacetDirs } from "../workspaceLayout";
|
|
18
|
+
import type { AppExecutor } from "./appExecutor";
|
|
19
|
+
import { Executor, execEmoji } from "./executor";
|
|
20
|
+
import type { LibExecutor } from "./libExecutor";
|
|
21
|
+
import { WorkspaceExecutor } from "./workspaceExecutor";
|
|
22
|
+
|
|
23
|
+
export interface NamedExecutorOptions {
|
|
24
|
+
workspace?: WorkspaceExecutor;
|
|
25
|
+
name: string;
|
|
26
|
+
}
|
|
27
|
+
interface SysExecutorOptions extends NamedExecutorOptions {
|
|
28
|
+
type: "app" | "lib";
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export class SysExecutor extends Executor {
|
|
32
|
+
workspace: WorkspaceExecutor;
|
|
33
|
+
override name: string;
|
|
34
|
+
type: "app" | "lib";
|
|
35
|
+
override emoji: string;
|
|
36
|
+
constructor({ workspace = WorkspaceExecutor.fromRoot(), name, type }: SysExecutorOptions) {
|
|
37
|
+
super(name, `${workspace.workspaceRoot}/${type}s/${name}`);
|
|
38
|
+
this.workspace = workspace;
|
|
39
|
+
this.name = name;
|
|
40
|
+
this.type = type;
|
|
41
|
+
this.emoji = execEmoji[type];
|
|
42
|
+
}
|
|
43
|
+
#akanConfig: AkanAppConfig | AkanLibConfig | null = null;
|
|
44
|
+
async getConfig({ refresh }: { refresh?: boolean } = {}) {
|
|
45
|
+
if (this.#akanConfig && !refresh) return this.#akanConfig;
|
|
46
|
+
this.#akanConfig =
|
|
47
|
+
this.type === "app"
|
|
48
|
+
? await AkanAppConfig.from(this as unknown as AppExecutor)
|
|
49
|
+
: await AkanLibConfig.from(this as unknown as LibExecutor);
|
|
50
|
+
return this.#akanConfig;
|
|
51
|
+
}
|
|
52
|
+
async getModules() {
|
|
53
|
+
const path = this.type === "app" ? `apps/${this.name}/lib` : `libs/${this.name}/lib`;
|
|
54
|
+
return await this.workspace.getDirInModule(path, this.name);
|
|
55
|
+
}
|
|
56
|
+
async getPageConventionViolations(): Promise<{ relativePath: string; reason: string }[]> {
|
|
57
|
+
if (!(await this.exists("page"))) return [];
|
|
58
|
+
const violations: { relativePath: string; reason: string }[] = [];
|
|
59
|
+
for (const entry of await this.getAllFiles("**/*", { cwd: this.getPath("page") })) {
|
|
60
|
+
const relativePath = entry.split(path.sep).join("/");
|
|
61
|
+
const reason = getPageSourceFileViolation(relativePath);
|
|
62
|
+
if (reason) violations.push({ relativePath: `page/${relativePath}`, reason });
|
|
63
|
+
}
|
|
64
|
+
return violations;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
#scanInfo: AppInfo | LibInfo | null = null;
|
|
68
|
+
hasScanInfo() {
|
|
69
|
+
return this.#scanInfo !== null;
|
|
70
|
+
}
|
|
71
|
+
getScanInfo<AllowEmpty extends boolean = false>({
|
|
72
|
+
allowEmpty,
|
|
73
|
+
}: {
|
|
74
|
+
allowEmpty?: AllowEmpty;
|
|
75
|
+
} = {}): AllowEmpty extends true ? AppInfo | LibInfo | null : AppInfo | LibInfo {
|
|
76
|
+
if (!this.hasScanInfo() && !allowEmpty) throw new Error("Scan info is not available");
|
|
77
|
+
return this.#scanInfo as AllowEmpty extends true ? AppInfo | LibInfo | null : AppInfo | LibInfo;
|
|
78
|
+
}
|
|
79
|
+
async #seedEnvFiles(): Promise<FileContent[]> {
|
|
80
|
+
const envDir = path.join(this.cwdPath, "env");
|
|
81
|
+
const missing = await new EnvSeed(envDir).missing();
|
|
82
|
+
if (!missing.length) return [];
|
|
83
|
+
const written = await Promise.all(
|
|
84
|
+
missing.map(({ fileName, content }) =>
|
|
85
|
+
this.writeFile(path.join(envDir, fileName), content, { overwrite: false, silent: true }),
|
|
86
|
+
),
|
|
87
|
+
);
|
|
88
|
+
this.logger.info(
|
|
89
|
+
`${missing.map(({ fileName }) => `env/${fileName}`).join(", ")} were missing (gitignored, so a clone has none) and now hold local defaults: put this machine's values in them, or fetch the team's with \`akan download-env\`.`,
|
|
90
|
+
);
|
|
91
|
+
return written;
|
|
92
|
+
}
|
|
93
|
+
#getScanTemplateTasks(scanInfo: AppInfo | LibInfo): (Promise<FileContent[]> | null)[] {
|
|
94
|
+
return [
|
|
95
|
+
this.#seedEnvFiles(),
|
|
96
|
+
this._applyTemplate({ basePath: "env", template: "env", scanInfo }),
|
|
97
|
+
this._applyTemplate({ basePath: "lib", template: "lib", scanInfo }),
|
|
98
|
+
this._applyTemplate({ basePath: ".", template: "server.ts", scanInfo }),
|
|
99
|
+
this._applyTemplate({ basePath: ".", template: "client.ts", scanInfo }),
|
|
100
|
+
this.type === "lib" ? this._applyTemplate({ basePath: ".", template: "index.ts", scanInfo }) : null,
|
|
101
|
+
...barrelFacetDirs.map((facet) =>
|
|
102
|
+
this._applyTemplate({
|
|
103
|
+
basePath: facet,
|
|
104
|
+
template: "facetIndex/index.ts",
|
|
105
|
+
scanInfo,
|
|
106
|
+
options: { exec: this, facet },
|
|
107
|
+
}),
|
|
108
|
+
),
|
|
109
|
+
...[
|
|
110
|
+
...scanInfo.getDatabaseModules().map((model) => [model, `lib/${model}`]),
|
|
111
|
+
...scanInfo.getServiceModules().map((model) => [model, `lib/_${model}`]),
|
|
112
|
+
...scanInfo.getScalarModules().map((model) => [model, `lib/__scalar/${model}`]),
|
|
113
|
+
].map(([model, basePath]) =>
|
|
114
|
+
this._applyTemplate({ basePath, template: "moduleRoot", scanInfo, dict: { model, Model: capitalize(model) } }),
|
|
115
|
+
),
|
|
116
|
+
];
|
|
117
|
+
}
|
|
118
|
+
async scan({
|
|
119
|
+
refresh = false,
|
|
120
|
+
write = true,
|
|
121
|
+
writeLib = write,
|
|
122
|
+
}: {
|
|
123
|
+
refresh?: boolean;
|
|
124
|
+
write?: boolean;
|
|
125
|
+
writeLib?: boolean;
|
|
126
|
+
} = {}): Promise<AppInfo | LibInfo> {
|
|
127
|
+
if (this.#scanInfo && !refresh) return this.#scanInfo;
|
|
128
|
+
const scanInfo =
|
|
129
|
+
this.type === "app"
|
|
130
|
+
? await AppInfo.fromExecutor(this as unknown as AppExecutor, {
|
|
131
|
+
refresh,
|
|
132
|
+
})
|
|
133
|
+
: await LibInfo.fromExecutor(this as unknown as LibExecutor, {
|
|
134
|
+
refresh,
|
|
135
|
+
});
|
|
136
|
+
//* Locked: `writeLib` rewrites dependency-lib barrels that other dev servers regenerate and watch too.
|
|
137
|
+
if (write)
|
|
138
|
+
await CodegenLock.run(this.workspace.workspaceRoot, `scan:${this.name}`, async () => {
|
|
139
|
+
await Promise.all(this.#getScanTemplateTasks(scanInfo));
|
|
140
|
+
await this.writeJson(`akan.${this.type}.json`, scanInfo.getScanResult());
|
|
141
|
+
await this.#updateDependencies(scanInfo);
|
|
142
|
+
if (writeLib) {
|
|
143
|
+
const libInfos = [...scanInfo.getLibInfos().values()];
|
|
144
|
+
await Promise.all(libInfos.flatMap((libInfo) => libInfo.exec.#getScanTemplateTasks(libInfo)));
|
|
145
|
+
}
|
|
146
|
+
await this.syncAgentsIndex(scanInfo);
|
|
147
|
+
});
|
|
148
|
+
this.#scanInfo = scanInfo;
|
|
149
|
+
return scanInfo;
|
|
150
|
+
}
|
|
151
|
+
/** Rewrites only the marker block of the scoped AGENTS.md; content outside the markers belongs to the user. */
|
|
152
|
+
async syncAgentsIndex(scanInfo?: AppInfo | LibInfo) {
|
|
153
|
+
const info = scanInfo ?? (await this.scan({ write: false }));
|
|
154
|
+
const scope = { type: this.type, name: this.name };
|
|
155
|
+
const recipes = await scanScopeRecipes(this.workspace.workspaceRoot, scope, info.getScanResult().libDeps);
|
|
156
|
+
const block = renderScopeAgentBlock(scope, recipes);
|
|
157
|
+
const existing = (await this.exists("AGENTS.md")) ? await this.readFile("AGENTS.md") : null;
|
|
158
|
+
await this.writeFile(
|
|
159
|
+
"AGENTS.md",
|
|
160
|
+
existing?.trim() ? upsertAgentBlock(existing, block) : renderScopeAgentsMd(scope, block),
|
|
161
|
+
);
|
|
162
|
+
// CLAUDE.md 는 얇은 포인터라 최초 1회만 깔아준다 — 사용자가 지우거나 고친 것을 되살리지 않는다.
|
|
163
|
+
if (!(await this.exists("CLAUDE.md"))) await this.writeFile("CLAUDE.md", renderScopeClaudeMd(scope));
|
|
164
|
+
}
|
|
165
|
+
//* The root is the cached copy the dependency scan read, so a name it declares is judged by the same snapshot.
|
|
166
|
+
async #updateDependencies(scanInfo: AppInfo | LibInfo) {
|
|
167
|
+
const [rootPackageJson, packageJson] = await Promise.all([
|
|
168
|
+
this.workspace.getPackageJson(),
|
|
169
|
+
this.getPackageJson({ refresh: true }),
|
|
170
|
+
]);
|
|
171
|
+
const { dependencies: runtime, devDependencies: typeOnly, akanConfig } = scanInfo.getScanResult();
|
|
172
|
+
const kept = new Set([
|
|
173
|
+
...ManifestDependencies.keptBy(packageJson),
|
|
174
|
+
...akanConfig.externalLibs,
|
|
175
|
+
...akanConfig.trustedDependencies,
|
|
176
|
+
]);
|
|
177
|
+
//? The scan leaves the framework out of its imports on purpose, so it is never a prune candidate.
|
|
178
|
+
const isKept = (dep: string) => kept.has(dep) || isAkanFrameworkDependency(dep);
|
|
179
|
+
const { dependencies, devDependencies, removed, unverifiable } = new ManifestDependencies(
|
|
180
|
+
rootPackageJson,
|
|
181
|
+
{ runtime, typeOnly },
|
|
182
|
+
isKept,
|
|
183
|
+
).realign(packageJson);
|
|
184
|
+
const manifestPath = `${this.type}s/${this.name}/package.json`;
|
|
185
|
+
if (removed.length)
|
|
186
|
+
this.logger.info(
|
|
187
|
+
`Removed from ${manifestPath}, declared by the root and imported nowhere: ${removed.join(", ")} (list one in akan.keepDependencies to keep it)`,
|
|
188
|
+
);
|
|
189
|
+
if (unverifiable.length)
|
|
190
|
+
this.logger.warn(
|
|
191
|
+
`${manifestPath} lists ${unverifiable.join(", ")}, which the root package.json does not declare, so sync cannot tell whether it is used; kept as is`,
|
|
192
|
+
);
|
|
193
|
+
await this.setPackageJson({ ...packageJson, dependencies, devDependencies });
|
|
194
|
+
}
|
|
195
|
+
override async getLocalFile(targetPath: string) {
|
|
196
|
+
const filePath = path.isAbsolute(targetPath) ? targetPath : `${this.type}s/${this.name}/${targetPath}`;
|
|
197
|
+
const content = await this.workspace.readFile(filePath);
|
|
198
|
+
return { filePath, content };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async getDatabaseModules() {
|
|
202
|
+
return (await this.readdir("lib"))
|
|
203
|
+
.filter((name) => !name.startsWith("_") && !name.endsWith(".ts"))
|
|
204
|
+
.filter((name) => existsSync(`${this.cwdPath}/lib/${name}/${name}.constant.ts`));
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async getServiceModules() {
|
|
208
|
+
return (await this.readdir("lib"))
|
|
209
|
+
.filter((name) => name.startsWith("_") && !name.startsWith("__"))
|
|
210
|
+
.filter((name) => existsSync(`${this.cwdPath}/lib/${name}/${name.slice(1)}.service.ts`));
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async getScalarModules() {
|
|
214
|
+
return (await this.readdir("lib/__scalar"))
|
|
215
|
+
.filter((name) => !name.startsWith("_"))
|
|
216
|
+
.filter((name) => existsSync(`${this.cwdPath}/lib/__scalar/${name}/${name}.constant.ts`));
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async #getComponentModules(role: "View" | "Unit" | "Template") {
|
|
220
|
+
return (await this.readdir("lib"))
|
|
221
|
+
.filter((name) => !name.startsWith("_") && !name.endsWith(".ts"))
|
|
222
|
+
.filter((name) => existsSync(`${this.cwdPath}/lib/${name}/${capitalize(name)}.${role}.tsx`));
|
|
223
|
+
}
|
|
224
|
+
async #getComponentSources(role: "View" | "Unit" | "Template") {
|
|
225
|
+
const modules = await this.#getComponentModules(role);
|
|
226
|
+
return Promise.all(modules.map((name) => this.getLocalFile(`lib/${name}/${capitalize(name)}.${role}.tsx`)));
|
|
227
|
+
}
|
|
228
|
+
async getViewComponents() {
|
|
229
|
+
return await this.#getComponentModules("View");
|
|
230
|
+
}
|
|
231
|
+
async getUnitComponents() {
|
|
232
|
+
return await this.#getComponentModules("Unit");
|
|
233
|
+
}
|
|
234
|
+
async getTemplateComponents() {
|
|
235
|
+
return await this.#getComponentModules("Template");
|
|
236
|
+
}
|
|
237
|
+
async getViewsSourceCode() {
|
|
238
|
+
return await this.#getComponentSources("View");
|
|
239
|
+
}
|
|
240
|
+
async getUnitsSourceCode() {
|
|
241
|
+
return await this.#getComponentSources("Unit");
|
|
242
|
+
}
|
|
243
|
+
async getTemplatesSourceCode() {
|
|
244
|
+
return await this.#getComponentSources("Template");
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async getScalarConstantFiles() {
|
|
248
|
+
const scalarModules = await this.getScalarModules();
|
|
249
|
+
return Promise.all(
|
|
250
|
+
scalarModules.map((scalarModule) =>
|
|
251
|
+
this.getLocalFile(`lib/__scalar/${scalarModule}/${scalarModule}.constant.ts`),
|
|
252
|
+
),
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async getScalarDictionaryFiles() {
|
|
257
|
+
const scalarModules = await this.getScalarModules();
|
|
258
|
+
return Promise.all(
|
|
259
|
+
scalarModules.map((scalarModule) =>
|
|
260
|
+
this.getLocalFile(`lib/__scalar/${scalarModule}/${scalarModule}.dictionary.ts`),
|
|
261
|
+
),
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async getConstantFiles() {
|
|
266
|
+
const modules = await this.getModules();
|
|
267
|
+
return Promise.all(modules.map((module) => this.getLocalFile(`lib/${module}/${module}.constant.ts`)));
|
|
268
|
+
}
|
|
269
|
+
async getConstantFilesWithLibs() {
|
|
270
|
+
const scanInfo =
|
|
271
|
+
this.type === "app"
|
|
272
|
+
? await AppInfo.fromExecutor(this as unknown as AppExecutor)
|
|
273
|
+
: await LibInfo.fromExecutor(this as unknown as LibExecutor);
|
|
274
|
+
const sysContantFiles = await this.getConstantFiles();
|
|
275
|
+
const sysScalarConstantFiles = await this.getScalarConstantFiles();
|
|
276
|
+
const libDeps = scanInfo.getLibs();
|
|
277
|
+
const libConstantFiles = await Promise.all(
|
|
278
|
+
//? Not LibExecutor.from: libExecutor.ts extends this file's class, so importing it here would load it first.
|
|
279
|
+
libDeps.map(async (lib) => {
|
|
280
|
+
const libSys = new SysExecutor({ workspace: this.workspace, name: lib, type: "lib" });
|
|
281
|
+
return [...(await libSys.getConstantFiles()), ...(await libSys.getScalarConstantFiles())];
|
|
282
|
+
}),
|
|
283
|
+
);
|
|
284
|
+
return [...sysContantFiles, ...sysScalarConstantFiles, ...libConstantFiles.flat()];
|
|
285
|
+
}
|
|
286
|
+
async getDictionaryFiles() {
|
|
287
|
+
const modules = await this.getModules();
|
|
288
|
+
return Promise.all(modules.map((module) => this.getLocalFile(`lib/${module}/${module}.dictionary.ts`)));
|
|
289
|
+
}
|
|
290
|
+
override async applyTemplate(options: {
|
|
291
|
+
basePath: string;
|
|
292
|
+
template: string;
|
|
293
|
+
dict?: { [key: string]: string };
|
|
294
|
+
overwrite?: boolean;
|
|
295
|
+
}): Promise<FileContent[]> {
|
|
296
|
+
const scanInfo = await this.scan();
|
|
297
|
+
const fileContents = await super.applyTemplate({ ...options, scanInfo });
|
|
298
|
+
await this.scan();
|
|
299
|
+
return fileContents;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { stat } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { AkanWorkspaceConfig } from "../akanConfig";
|
|
5
|
+
import { FileSys } from "../fileSys";
|
|
6
|
+
import { resolveRepoName } from "../repoIdentity";
|
|
7
|
+
import { WorkspaceInfo } from "../scanInfo";
|
|
8
|
+
import type { BaseDevEnv, TsConfigJson } from "../types";
|
|
9
|
+
import { Executor, execEmoji } from "./executor";
|
|
10
|
+
import { SysExecutor } from "./sysExecutor";
|
|
11
|
+
|
|
12
|
+
//? As Bun's own .env loader reads it (1.4.4), which fills process.env too: `#` ends an unquoted value even mid-word.
|
|
13
|
+
const parseEnvValue = (value: string) => {
|
|
14
|
+
const [, quote, inner] = value.match(/^(["'`])((?:\\.|(?!\1)[^\\])*)\1/) ?? [];
|
|
15
|
+
if (!quote) return value.replace(/#.*/, "").trim();
|
|
16
|
+
if (quote !== '"') return inner;
|
|
17
|
+
return inner.replace(/\\(.)/g, (pair, char: string) => (char === "n" ? "\n" : char === "r" ? "\r" : pair));
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export const parseEnvFile = (envPath: string): Record<string, string> => {
|
|
21
|
+
const env: Record<string, string> = {};
|
|
22
|
+
const content = (() => {
|
|
23
|
+
try {
|
|
24
|
+
return readFileSync(envPath, "utf8");
|
|
25
|
+
} catch {
|
|
26
|
+
return "";
|
|
27
|
+
}
|
|
28
|
+
})();
|
|
29
|
+
for (const line of content.split(/\r?\n/)) {
|
|
30
|
+
const trimmed = line.trim();
|
|
31
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
32
|
+
const normalized = trimmed.startsWith("export ") ? trimmed.slice("export ".length).trim() : trimmed;
|
|
33
|
+
const separatorIndex = normalized.indexOf("=");
|
|
34
|
+
if (separatorIndex <= 0) continue;
|
|
35
|
+
const key = normalized.slice(0, separatorIndex).trim();
|
|
36
|
+
env[key] = parseEnvValue(normalized.slice(separatorIndex + 1).trim());
|
|
37
|
+
}
|
|
38
|
+
return env;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
interface ExecutorOptions {
|
|
42
|
+
workspaceRoot: string;
|
|
43
|
+
repoName: string;
|
|
44
|
+
}
|
|
45
|
+
export class WorkspaceExecutor extends Executor {
|
|
46
|
+
workspaceRoot: string;
|
|
47
|
+
repoName: string;
|
|
48
|
+
override emoji = execEmoji.workspace;
|
|
49
|
+
constructor({ workspaceRoot, repoName }: ExecutorOptions) {
|
|
50
|
+
super("workspace", workspaceRoot);
|
|
51
|
+
this.workspaceRoot = workspaceRoot;
|
|
52
|
+
this.repoName = repoName;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
static fromRoot({
|
|
56
|
+
workspaceRoot = process.cwd(),
|
|
57
|
+
repoName = resolveRepoName(workspaceRoot),
|
|
58
|
+
}: {
|
|
59
|
+
workspaceRoot?: string;
|
|
60
|
+
repoName?: string;
|
|
61
|
+
} = {}) {
|
|
62
|
+
return new WorkspaceExecutor({ workspaceRoot, repoName });
|
|
63
|
+
}
|
|
64
|
+
/** The public env a native build was told to reproduce (`--public-env`): it outranks the shell, which outranks `.env`. */
|
|
65
|
+
static publicEnvPin: Record<string, string> | null = null;
|
|
66
|
+
static readonly localServeDomain = "localhost";
|
|
67
|
+
static getBaseDevEnv(envPath?: string) {
|
|
68
|
+
// Bun auto-loads .env, so we use process.env directly
|
|
69
|
+
const sourceEnv = {
|
|
70
|
+
...(envPath ? parseEnvFile(envPath) : {}),
|
|
71
|
+
//? An empty export reads as unset, unlike in dotenv, so it can't blank a key the .env sets.
|
|
72
|
+
...Object.fromEntries(Object.entries(process.env).filter(([, value]) => value)),
|
|
73
|
+
...WorkspaceExecutor.publicEnvPin,
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
const appName = sourceEnv.AKAN_PUBLIC_APP_NAME;
|
|
77
|
+
const workspaceRoot = sourceEnv.AKAN_WORKSPACE_ROOT;
|
|
78
|
+
const workspaceId = sourceEnv.AKAN_WORKSPACE_ID;
|
|
79
|
+
|
|
80
|
+
const repoName =
|
|
81
|
+
sourceEnv.AKAN_PUBLIC_REPO_NAME ||
|
|
82
|
+
resolveRepoName(envPath ? path.dirname(envPath) : (workspaceRoot ?? process.cwd()));
|
|
83
|
+
const serveDomain = sourceEnv.AKAN_PUBLIC_SERVE_DOMAIN || WorkspaceExecutor.localServeDomain;
|
|
84
|
+
const defaulted = (["AKAN_PUBLIC_REPO_NAME", "AKAN_PUBLIC_SERVE_DOMAIN"] as const).filter((key) => !sourceEnv[key]);
|
|
85
|
+
|
|
86
|
+
const portOffset = parseInt(sourceEnv.PORT_OFFSET ?? "0");
|
|
87
|
+
|
|
88
|
+
const env = (sourceEnv.AKAN_PUBLIC_ENV ?? "debug") as
|
|
89
|
+
| "testing"
|
|
90
|
+
| "debug"
|
|
91
|
+
| "develop"
|
|
92
|
+
| "main"
|
|
93
|
+
| "local"
|
|
94
|
+
| undefined;
|
|
95
|
+
if (!env) throw new Error("AKAN_PUBLIC_ENV is not set");
|
|
96
|
+
return {
|
|
97
|
+
...(appName ? { appName } : {}),
|
|
98
|
+
workspaceRoot,
|
|
99
|
+
repoName,
|
|
100
|
+
serveDomain,
|
|
101
|
+
env,
|
|
102
|
+
portOffset,
|
|
103
|
+
workspaceId,
|
|
104
|
+
defaulted,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
//? A clone has no `.env` (gitignored for its secrets): it runs local, as a new workspace and env.server.ts do, not debug.
|
|
108
|
+
static defaultCloneToLocalEnv(workspaceRoot: string) {
|
|
109
|
+
if (!existsSync(path.join(workspaceRoot, ".env"))) process.env.AKAN_PUBLIC_ENV ??= "local";
|
|
110
|
+
}
|
|
111
|
+
//? A build or tunnel for a real environment carries these into an image, a bundle or a host name it dials.
|
|
112
|
+
static assertDeployableEnv(baseDevEnv: BaseDevEnv, environment: string, purpose: string) {
|
|
113
|
+
const defaulted = environment === "local" ? [] : (baseDevEnv.defaulted ?? []);
|
|
114
|
+
if (!defaulted.length) return;
|
|
115
|
+
const values = { AKAN_PUBLIC_REPO_NAME: baseDevEnv.repoName, AKAN_PUBLIC_SERVE_DOMAIN: baseDevEnv.serveDomain };
|
|
116
|
+
const standIns = defaulted.map((key) => `${key} (would be "${values[key]}")`).join(" and ");
|
|
117
|
+
throw new Error(
|
|
118
|
+
`${purpose} for the "${environment}" environment needs ${standIns} set, not a local default. ` +
|
|
119
|
+
`Set ${defaulted.length > 1 ? "them" : "it"} in the workspace .env or the shell, or use AKAN_PUBLIC_ENV=local.`,
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
getWorkspaceId<AllowEmpty extends boolean = false>({
|
|
123
|
+
allowEmpty,
|
|
124
|
+
}: {
|
|
125
|
+
allowEmpty?: AllowEmpty;
|
|
126
|
+
} = {}): AllowEmpty extends true ? string | undefined : string {
|
|
127
|
+
const { workspaceId } = WorkspaceExecutor.getBaseDevEnv();
|
|
128
|
+
if (!workspaceId && !allowEmpty) throw new Error("Workspace ID is not found");
|
|
129
|
+
return workspaceId as AllowEmpty extends true ? string | undefined : string;
|
|
130
|
+
}
|
|
131
|
+
async scan(): Promise<WorkspaceInfo> {
|
|
132
|
+
return await WorkspaceInfo.fromExecutor(this);
|
|
133
|
+
}
|
|
134
|
+
#akanConfig: AkanWorkspaceConfig | null = null;
|
|
135
|
+
async getConfig({ refresh }: { refresh?: boolean } = {}) {
|
|
136
|
+
if (this.#akanConfig && !refresh) return this.#akanConfig;
|
|
137
|
+
this.#akanConfig = await AkanWorkspaceConfig.from(this, { bustImportCache: refresh });
|
|
138
|
+
return this.#akanConfig;
|
|
139
|
+
}
|
|
140
|
+
async getApps() {
|
|
141
|
+
return await this.#getDirHasFile(`${this.workspaceRoot}/apps`, "akan.config.ts");
|
|
142
|
+
}
|
|
143
|
+
async getLibs() {
|
|
144
|
+
return await this.#getDirHasFile(`${this.workspaceRoot}/libs`, "akan.config.ts");
|
|
145
|
+
}
|
|
146
|
+
async getSyss() {
|
|
147
|
+
const [appNames, libNames] = await Promise.all([this.getApps(), this.getLibs()]);
|
|
148
|
+
return [appNames, libNames] as [string[], string[]];
|
|
149
|
+
}
|
|
150
|
+
async getPkgs() {
|
|
151
|
+
return await this.#getDirHasFile(`${this.workspaceRoot}/pkgs`, "package.json");
|
|
152
|
+
}
|
|
153
|
+
async getExecs() {
|
|
154
|
+
const [appNames, libNames, pkgNames] = await Promise.all([this.getApps(), this.getLibs(), this.getPkgs()]);
|
|
155
|
+
return [appNames, libNames, pkgNames] as [string[], string[], string[]];
|
|
156
|
+
}
|
|
157
|
+
async setPkgTsPaths(name: string) {
|
|
158
|
+
const rootTsConfig = (await this.readJson("tsconfig.json")) as TsConfigJson;
|
|
159
|
+
rootTsConfig.compilerOptions.paths ??= {};
|
|
160
|
+
rootTsConfig.compilerOptions.paths[name] = [`./pkgs/${name}/index.ts`];
|
|
161
|
+
rootTsConfig.compilerOptions.paths[`${name}/*`] = [`./pkgs/${name}/*`];
|
|
162
|
+
if (rootTsConfig.references) {
|
|
163
|
+
if (!rootTsConfig.references.some((ref) => ref.path === `./pkgs/${name}/tsconfig.json`))
|
|
164
|
+
rootTsConfig.references.push({ path: `./pkgs/${name}/tsconfig.json` });
|
|
165
|
+
}
|
|
166
|
+
await this.writeJson("tsconfig.json", rootTsConfig);
|
|
167
|
+
return this;
|
|
168
|
+
}
|
|
169
|
+
async unsetPkgTsPaths(name: string) {
|
|
170
|
+
const rootTsConfig = (await this.readJson("tsconfig.json")) as TsConfigJson;
|
|
171
|
+
const filteredKeys = Object.keys(rootTsConfig.compilerOptions.paths ?? {}).filter(
|
|
172
|
+
(key) => key !== name && key !== `${name}/*`,
|
|
173
|
+
);
|
|
174
|
+
rootTsConfig.compilerOptions.paths = Object.fromEntries(
|
|
175
|
+
filteredKeys.map((key) => [key, rootTsConfig.compilerOptions.paths?.[key] ?? []]),
|
|
176
|
+
);
|
|
177
|
+
if (rootTsConfig.references) {
|
|
178
|
+
rootTsConfig.references = rootTsConfig.references.filter(
|
|
179
|
+
(ref) => ref.path !== `./pkgs/${name}/tsconfig.json`,
|
|
180
|
+
) as TsConfigJson["references"];
|
|
181
|
+
}
|
|
182
|
+
await this.writeJson("tsconfig.json", rootTsConfig);
|
|
183
|
+
return this;
|
|
184
|
+
}
|
|
185
|
+
async getDirInModule(basePath: string, name: string) {
|
|
186
|
+
const AVOID_DIRS = ["__lib", "__scalar", `_`, `_${name}`];
|
|
187
|
+
const getDirs = async (dirname: string, maxDepth = 3, results: string[] = [], prefix = "") => {
|
|
188
|
+
const dirs = await this.readdir(dirname);
|
|
189
|
+
await Promise.all(
|
|
190
|
+
dirs.map(async (dir) => {
|
|
191
|
+
if (dir.includes("_") || AVOID_DIRS.includes(dir)) return;
|
|
192
|
+
const dirPath = path.join(dirname, dir);
|
|
193
|
+
if ((await stat(dirPath)).isDirectory()) {
|
|
194
|
+
results.push(`${prefix}${dir}`);
|
|
195
|
+
if (maxDepth > 0) await getDirs(dirPath, maxDepth - 1, results, `${prefix}${dir}/`);
|
|
196
|
+
}
|
|
197
|
+
}),
|
|
198
|
+
);
|
|
199
|
+
return results;
|
|
200
|
+
};
|
|
201
|
+
return await getDirs(basePath);
|
|
202
|
+
}
|
|
203
|
+
async commit(
|
|
204
|
+
message: string,
|
|
205
|
+
{
|
|
206
|
+
init = false,
|
|
207
|
+
add = true,
|
|
208
|
+
identity,
|
|
209
|
+
}: { init?: boolean; add?: boolean; identity?: { name: string; email: string } } = {},
|
|
210
|
+
) {
|
|
211
|
+
if (init) await this.spawn("git", ["init", "--quiet"]);
|
|
212
|
+
if (add) await this.spawn("git", ["add", "."]);
|
|
213
|
+
const author = identity ? ["-c", `user.name=${identity.name}`, "-c", `user.email=${identity.email}`] : [];
|
|
214
|
+
// Argument vector, not a shell string: a message carrying a double quote breaks the interpolated form.
|
|
215
|
+
await this.spawn("git", [...author, "commit", "--quiet", "-m", message]);
|
|
216
|
+
}
|
|
217
|
+
/** `git commit` exits non-zero on an empty index, so a re-runnable caller has to ask first. */
|
|
218
|
+
async hasChanges() {
|
|
219
|
+
return !!(await this.spawn("git", ["status", "--porcelain"])).trim();
|
|
220
|
+
}
|
|
221
|
+
/** Sorted workspace-relative paths; `untracked` adds uncommitted files, still honoring `.gitignore`. */
|
|
222
|
+
async listGitFiles(paths: string[], { untracked = false }: { untracked?: boolean } = {}) {
|
|
223
|
+
if (!paths.length) return [];
|
|
224
|
+
const mode = untracked ? ["--cached", "--others", "--exclude-standard"] : ["--cached"];
|
|
225
|
+
const stdout = await this.spawn("git", ["ls-files", "-z", ...mode, "--", ...paths]);
|
|
226
|
+
return stdout
|
|
227
|
+
.split("\0")
|
|
228
|
+
.filter((file) => !!file)
|
|
229
|
+
.sort();
|
|
230
|
+
}
|
|
231
|
+
async #getDirHasFile(basePath: string, targetFilename: string) {
|
|
232
|
+
if (!(await FileSys.dirExists(basePath))) return [];
|
|
233
|
+
//? `local/` is gitignored scratch: a test's temporary workspace there has a package.json of its own.
|
|
234
|
+
const AVOID_DIRS = ["node_modules", "dist", "public", "webkit", "local"];
|
|
235
|
+
const getDirs = async (dirname: string, maxDepth = 3, results: string[] = [], prefix = "") => {
|
|
236
|
+
const dirs = await this.readdir(dirname);
|
|
237
|
+
await Promise.all(
|
|
238
|
+
dirs.map(async (dir) => {
|
|
239
|
+
if (AVOID_DIRS.includes(dir)) return;
|
|
240
|
+
const dirPath = path.join(dirname, dir);
|
|
241
|
+
//* Not `stat`: a dangling symlink would throw, and this walk backs `getApps`, i.e. every command.
|
|
242
|
+
if (await FileSys.dirExists(dirPath)) {
|
|
243
|
+
const hasTargetFile = await FileSys.fileExists(path.join(dirPath, targetFilename));
|
|
244
|
+
if (hasTargetFile) results.push(`${prefix}${dir}`);
|
|
245
|
+
if (maxDepth > 0) await getDirs(dirPath, maxDepth - 1, results, `${prefix}${dir}/`);
|
|
246
|
+
}
|
|
247
|
+
}),
|
|
248
|
+
);
|
|
249
|
+
return results;
|
|
250
|
+
};
|
|
251
|
+
return (await getDirs(basePath)).sort((a, b) => a.localeCompare(b));
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async #fromEverySys<T>(read: (sys: SysExecutor) => Promise<T[]>): Promise<T[]> {
|
|
255
|
+
const [appNames, libNames] = await this.getSyss();
|
|
256
|
+
//? Plain SysExecutors: AppExecutor and LibExecutor extend SysExecutor, which imports this file, so importing them here
|
|
257
|
+
//? would load a subclass before its base. None of the readers below is overridden there.
|
|
258
|
+
const fromApps = await Promise.all(
|
|
259
|
+
appNames.map((name) => read(new SysExecutor({ workspace: this, name, type: "app" }))),
|
|
260
|
+
);
|
|
261
|
+
const fromLibs = await Promise.all(
|
|
262
|
+
libNames.map((name) => read(new SysExecutor({ workspace: this, name, type: "lib" }))),
|
|
263
|
+
);
|
|
264
|
+
return [...fromApps.flat(), ...fromLibs.flat()];
|
|
265
|
+
}
|
|
266
|
+
async getScalarConstantFiles() {
|
|
267
|
+
return await this.#fromEverySys((sys) => sys.getScalarConstantFiles());
|
|
268
|
+
}
|
|
269
|
+
async getConstantFiles() {
|
|
270
|
+
return await this.#fromEverySys((sys) => sys.getConstantFiles());
|
|
271
|
+
}
|
|
272
|
+
async getDictionaryFiles() {
|
|
273
|
+
return await this.#fromEverySys((sys) => sys.getDictionaryFiles());
|
|
274
|
+
}
|
|
275
|
+
async getViewFiles() {
|
|
276
|
+
return await this.#fromEverySys((sys) => sys.getViewsSourceCode());
|
|
277
|
+
}
|
|
278
|
+
}
|
package/executors.test.ts
CHANGED
|
@@ -48,6 +48,27 @@ const rootPackageJson = (extra: Partial<PackageJson> = {}): PackageJson => ({
|
|
|
48
48
|
...extra,
|
|
49
49
|
});
|
|
50
50
|
|
|
51
|
+
describe("executors module graph", () => {
|
|
52
|
+
test("executors.ts and each file under executors/ load first in a fresh process", async () => {
|
|
53
|
+
const entries = ["executors.ts"];
|
|
54
|
+
for await (const file of new Bun.Glob("executors/*.ts").scan({ cwd: import.meta.dir }))
|
|
55
|
+
if (!file.endsWith(".test.ts")) entries.push(file);
|
|
56
|
+
const failures = await Promise.all(
|
|
57
|
+
entries.map(async (entry) => {
|
|
58
|
+
const proc = Bun.spawn([process.execPath, "-e", `await import(${JSON.stringify(`./${entry}`)})`], {
|
|
59
|
+
cwd: import.meta.dir,
|
|
60
|
+
stdout: "ignore",
|
|
61
|
+
stderr: "pipe",
|
|
62
|
+
});
|
|
63
|
+
const [code, stderr] = await Promise.all([proc.exited, new Response(proc.stderr).text()]);
|
|
64
|
+
return code === 0 ? null : `${entry}: ${stderr.split("\n").find((line) => line.includes("error:")) ?? stderr}`;
|
|
65
|
+
}),
|
|
66
|
+
);
|
|
67
|
+
expect(entries.length).toBeGreaterThan(8);
|
|
68
|
+
expect(failures.filter((failure) => failure !== null)).toEqual([]);
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
|
|
51
72
|
describe("Executor filesystem helpers", () => {
|
|
52
73
|
test("reports command failures with command context and captured output", async () => {
|
|
53
74
|
const root = await makeTempRoot();
|
|
@@ -1304,6 +1325,29 @@ describe("WorkspaceExecutor listing", () => {
|
|
|
1304
1325
|
});
|
|
1305
1326
|
|
|
1306
1327
|
describe("SysExecutor module listing", () => {
|
|
1328
|
+
test("reads an app's and a lib's constants from that sys's own folder", async () => {
|
|
1329
|
+
const { root, workspace, app } = trackRoot(await createTempApp("demo"));
|
|
1330
|
+
const appConstant = "export const owner = 'app';\n";
|
|
1331
|
+
const libConstant = "export const owner = 'lib';\n";
|
|
1332
|
+
await writeText(path.join(root, "apps/demo/lib/post/post.constant.ts"), appConstant);
|
|
1333
|
+
await writeText(path.join(root, "libs/shared/lib/user/user.constant.ts"), libConstant);
|
|
1334
|
+
await writeText(path.join(root, "libs/shared/akan.config.ts"), "export default {};\n");
|
|
1335
|
+
await mkdir(path.join(root, "libs/shared/lib/__scalar"), { recursive: true });
|
|
1336
|
+
const contents = (files: { content: string }[]) => files.map((file) => file.content);
|
|
1337
|
+
|
|
1338
|
+
const scan = spyOn(AppInfo, "fromExecutor").mockResolvedValue({ getLibs: () => ["shared"] } as never);
|
|
1339
|
+
const cwd = process.cwd();
|
|
1340
|
+
// `getDirInModule` stats the workspace-relative path it just listed, so it resolves against the process cwd.
|
|
1341
|
+
process.chdir(root);
|
|
1342
|
+
try {
|
|
1343
|
+
expect(contents(await workspace.getConstantFiles())).toEqual([appConstant, libConstant]);
|
|
1344
|
+
expect(contents(await app.getConstantFilesWithLibs())).toEqual([appConstant, libConstant]);
|
|
1345
|
+
} finally {
|
|
1346
|
+
process.chdir(cwd);
|
|
1347
|
+
scan.mockRestore();
|
|
1348
|
+
}
|
|
1349
|
+
});
|
|
1350
|
+
|
|
1307
1351
|
test("lists only the module folders that hold the module's own file", async () => {
|
|
1308
1352
|
const root = await makeTempRoot();
|
|
1309
1353
|
const lib = path.join(root, "apps/modlist/lib");
|