@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.
@@ -0,0 +1,527 @@
1
+ import {
2
+ type ChildProcess,
3
+ type ExecOptions,
4
+ exec,
5
+ type ForkOptions,
6
+ fork,
7
+ type SpawnOptions,
8
+ spawn,
9
+ } from "node:child_process";
10
+ import { copyFile, cp as cpEntry, mkdir, readdir as readDirEntries, rm, stat } from "node:fs/promises";
11
+ import path from "node:path";
12
+ import { capitalize, Logger, toError } from "akanjs/common";
13
+ import { $ } from "bun";
14
+ import chalk from "chalk";
15
+ import { FileSys, getDirname } from "../fileSys";
16
+ import { JsonFormatter } from "../jsonFormatter";
17
+ import { Linter } from "../linter";
18
+ import type { AppInfo, LibInfo } from "../scanInfo";
19
+ import { Spinner } from "../spinner";
20
+ // Type-only: `getTypeChecker` loads it on demand to keep `typescript` out of the resident module graph.
21
+ import type { TypeChecker } from "../typeChecker";
22
+ import { ProjectTypecheck } from "../typecheck/projectTypecheck";
23
+ import type { FileContent, PackageJson, TsConfigJson } from "../types";
24
+ import { CommandExecutionError } from "./commandExecutionError";
25
+
26
+ export interface WrittenFileContent extends FileContent {
27
+ written: boolean;
28
+ }
29
+
30
+ const staticTemplateFileExtensions = new Set(
31
+ ".avif .bmp .cjs .css .eot .gif .html .ico .jpeg .jpg .js .json .map .md .mjs .mp3 .mp4 .ogg .otf .pdf .png .svg"
32
+ .split(" ")
33
+ .concat(".ttf .txt .wasm .wav .webm .webp .woff .woff2 .xml".split(" ")),
34
+ );
35
+
36
+ export const execEmoji = {
37
+ workspace: "🏠",
38
+ app: "πŸš€",
39
+ lib: "πŸ”§",
40
+ pkg: "πŸ“¦",
41
+ dist: "πŸ’Ώ",
42
+ module: "βš™οΈ",
43
+ default: "✈️",
44
+ };
45
+
46
+ const withCapitalizedDict = (dict: { [key: string]: string } = {}) => ({
47
+ ...dict,
48
+ ...Object.fromEntries(Object.entries(dict).map(([key, value]) => [capitalize(key), capitalize(value)])),
49
+ });
50
+
51
+ export class Executor {
52
+ static verbose = false;
53
+ static setVerbose(verbose: boolean) {
54
+ Executor.verbose = verbose;
55
+ }
56
+
57
+ name: string;
58
+ logger: Logger;
59
+ logs: string[];
60
+ cwdPath: string;
61
+ emoji = execEmoji.default;
62
+ typeChecker: TypeChecker | null = null;
63
+ linter: Linter | null = null;
64
+ constructor(name: string, cwdPath: string) {
65
+ this.name = name;
66
+ this.logger = new Logger(name);
67
+ this.logs = [] as string[];
68
+ this.cwdPath = cwdPath;
69
+ }
70
+ #stdout(data: Buffer) {
71
+ if (Executor.verbose) Logger.raw(chalk.dim(data.toString()));
72
+ }
73
+ #stderr(data: Buffer) {
74
+ Logger.raw(chalk.red(data.toString()));
75
+ }
76
+ #settle(
77
+ proc: ChildProcess,
78
+ target: { command: string; args?: string[]; cwd: string },
79
+ { onClose = false, keepLogs = false, redStderr = false } = {},
80
+ ): Promise<{ code: number | null; signal: NodeJS.Signals | null; stdout: string }> {
81
+ let stdout = "";
82
+ let stderr = "";
83
+ proc.stdout?.on("data", (data: Buffer) => {
84
+ stdout += data.toString();
85
+ if (keepLogs) this.logs.push(data.toString());
86
+ this.#stdout(data);
87
+ });
88
+ proc.stderr?.on("data", (data: Buffer) => {
89
+ stderr += data.toString();
90
+ if (keepLogs) this.logs.push(data.toString());
91
+ if (redStderr) this.#stderr(data);
92
+ else this.#stdout(data); // μ •μƒλ‘œκ·Έλ„ stderr둜 λ‚˜μ˜΄
93
+ });
94
+ return new Promise((resolve, reject) => {
95
+ proc.on("error", (cause) =>
96
+ reject(new CommandExecutionError({ ...target, code: null, signal: null, stdout, stderr, cause })),
97
+ );
98
+ proc.on(onClose ? "close" : "exit", (code: number | null, signal: NodeJS.Signals | null) => {
99
+ if ((onClose ? code !== 0 : code) || signal)
100
+ reject(new CommandExecutionError({ ...target, code, signal, stdout, stderr }));
101
+ else resolve({ code, signal, stdout });
102
+ });
103
+ });
104
+ }
105
+ exec(command: string, options: ExecOptions = {}): Promise<unknown> {
106
+ const target = { command, cwd: options.cwd?.toString() ?? this.cwdPath };
107
+ const proc = exec(command, { cwd: this.cwdPath, ...options });
108
+ return this.#settle(proc, target).then(({ code, signal }) => ({ code, signal }));
109
+ }
110
+
111
+ spawn(command: string, args: string[] = [], options: SpawnOptions = {}): Promise<string> {
112
+ const target = { command, args, cwd: options.cwd?.toString() ?? this.cwdPath };
113
+ const proc = spawn(command, args, { cwd: this.cwdPath, ...options });
114
+ return this.#settle(proc, target, { onClose: true, keepLogs: true }).then(({ stdout }) => stdout);
115
+ }
116
+ spawnSync(command: string, args: string[] = [], options: SpawnOptions = {}): ChildProcess {
117
+ return spawn(command, args, { cwd: this.cwdPath, ...options });
118
+ }
119
+ fork(modulePath: string, args: string[] = [], options: ForkOptions = {}): Promise<unknown> {
120
+ const target = { command: modulePath, args, cwd: options.cwd?.toString() ?? this.cwdPath };
121
+ const proc = fork(modulePath, args, { cwd: this.cwdPath, ...options });
122
+ return this.#settle(proc, target, { redStderr: true }).then(({ code, signal }) => ({ code, signal }));
123
+ }
124
+ getPath(filePath: string) {
125
+ if (path.isAbsolute(filePath)) return filePath;
126
+ if (filePath.startsWith(".")) return path.join(this.cwdPath, filePath);
127
+ const baseParts = this.cwdPath.split(/[\\/]/).filter(Boolean);
128
+ const targetParts = filePath.split(/[\\/]/).filter(Boolean);
129
+
130
+ let overlapLength = 0;
131
+ for (let i = 1; i <= Math.min(baseParts.length, targetParts.length); i++) {
132
+ let isOverlap = true;
133
+ for (let j = 0; j < i; j++)
134
+ if (baseParts[baseParts.length - i + j] !== targetParts[j]) {
135
+ isOverlap = false;
136
+ break;
137
+ }
138
+ if (isOverlap) overlapLength = i;
139
+ }
140
+ return path.join(this.cwdPath, ...targetParts.slice(overlapLength));
141
+ }
142
+ async mkdir(dirPath: string) {
143
+ const writePath = this.getPath(dirPath);
144
+ if (!(await FileSys.dirExists(writePath))) await mkdir(writePath, { recursive: true });
145
+ this.logger.verbose(`Make directory ${writePath}`);
146
+ return this;
147
+ }
148
+ async readdir(dirPath: string): Promise<string[]> {
149
+ const readPath = this.getPath(dirPath);
150
+ try {
151
+ const glob = new Bun.Glob("*");
152
+ return Array.from(glob.scanSync({ cwd: readPath, onlyFiles: false })).sort();
153
+ } catch {
154
+ return [];
155
+ }
156
+ }
157
+ async getAllFiles(pattern = "**/*", { cwd }: { cwd?: string } = {}): Promise<string[]> {
158
+ const glob = new Bun.Glob(pattern);
159
+ return Array.from(glob.scanSync({ cwd: cwd ?? this.cwdPath, onlyFiles: true })).sort();
160
+ }
161
+ async getFilesAndDirs(dirPath: string): Promise<{ files: string[]; dirs: string[] }> {
162
+ const fullDirPath = this.getPath(dirPath);
163
+ const glob = new Bun.Glob("*");
164
+ const files = Array.from(glob.scanSync({ cwd: fullDirPath, onlyFiles: true })).sort();
165
+ const allEntries = Array.from(glob.scanSync({ cwd: fullDirPath, onlyFiles: false })).sort();
166
+ const dirs = allEntries.filter((entry) => !files.includes(entry));
167
+ return { files, dirs };
168
+ }
169
+ async exists(filePath: string) {
170
+ return await FileSys.exists(this.getPath(filePath));
171
+ }
172
+ async remove(filePath: string) {
173
+ const readPath = this.getPath(filePath);
174
+ if (await FileSys.fileExists(readPath)) await FileSys.delete(readPath);
175
+ this.logger.verbose(`Remove file ${readPath}`);
176
+ return this;
177
+ }
178
+ async removeDir(dirPath: string) {
179
+ //* XXX: `path.join(…, ".")` drops a trailing slash: `rm -rf link/` wipes the target, `rm -rf link` only unlinks.
180
+ const readPath = path.join(this.getPath(dirPath), ".");
181
+ if (await FileSys.entryExists(readPath)) await rm(readPath, { recursive: true, force: true });
182
+ this.logger.verbose(`Remove directory ${readPath}`);
183
+ return this;
184
+ }
185
+ async writeFile(
186
+ filePath: string,
187
+ content: string | object,
188
+ { overwrite = true, silent = false }: { overwrite?: boolean; silent?: boolean } = {},
189
+ ): Promise<WrittenFileContent> {
190
+ const writePath = this.getPath(filePath);
191
+ const dir = path.dirname(writePath);
192
+ if (!(await FileSys.dirExists(dir))) await mkdir(dir, { recursive: true });
193
+ let contentStr = typeof content === "string" ? content : JsonFormatter.stringify(content, writePath);
194
+ let written = true;
195
+
196
+ if (await FileSys.fileExists(writePath)) {
197
+ const currentContent = await FileSys.readText(writePath);
198
+ if (currentContent === contentStr || !overwrite) {
199
+ this.logger.verbose(`File ${writePath} is unchanged`);
200
+ contentStr = currentContent;
201
+ written = false;
202
+ } else {
203
+ await FileSys.writeText(writePath, contentStr);
204
+ if (Logger.isVerbose()) this.logger.rawLog(chalk.yellow(`File Update: ${filePath}`));
205
+ }
206
+ } else {
207
+ await FileSys.writeText(writePath, contentStr);
208
+ if (!silent) this.logger.rawLog(chalk.green(`File Create: ${filePath}`));
209
+ }
210
+ return { filePath: writePath, content: contentStr, written };
211
+ }
212
+ async writeJson(filePath: string, content: object) {
213
+ await this.writeFile(filePath, content);
214
+ }
215
+ async getLocalFile(targetPath: string) {
216
+ const filePath = path.isAbsolute(targetPath) ? targetPath : targetPath.replace(this.cwdPath, "");
217
+ const content = await this.readFile(filePath);
218
+ return { filePath, content };
219
+ }
220
+ async readFile(filePath: string) {
221
+ return await FileSys.readText(this.getPath(filePath));
222
+ }
223
+ async readJson(filePath: string) {
224
+ return await FileSys.readJson<object>(this.getPath(filePath));
225
+ }
226
+ async cp(srcPath: string, destPath: string, { dereference = false }: { dereference?: boolean } = {}) {
227
+ const src = this.getPath(srcPath);
228
+ const dest = this.getPath(destPath);
229
+ if (!(await FileSys.exists(src))) return;
230
+ const isDirectory = (await stat(src)).isDirectory();
231
+ if (!(await FileSys.exists(dest)) && isDirectory) await mkdir(dest, { recursive: true });
232
+ //* `cp -r` keeps symlinks on GNU but follows them on macOS; Windows has no `cp -r <dir>/.` and rarely the
233
+ //* privilege a symlink needs, so it always copies real files.
234
+ if (dereference || process.platform === "win32")
235
+ await cpEntry(src, dest, { recursive: isDirectory, dereference: true, force: true });
236
+ else await $`cp -r ${src}${isDirectory ? "/." : ""} ${dest}`;
237
+ }
238
+ log(msg: string) {
239
+ this.logger.info(msg);
240
+ return this;
241
+ }
242
+ verbose(msg: string) {
243
+ this.logger.verbose(msg);
244
+ return this;
245
+ }
246
+ debug(msg: string) {
247
+ this.logger.debug(msg);
248
+ return this;
249
+ }
250
+ spinning(msg: string, { prefix = `${this.emoji}${this.name}`, indent = 0, enableSpin = !Executor.verbose } = {}) {
251
+ return new Spinner(msg, { prefix, indent, enableSpin }).start();
252
+ }
253
+
254
+ #tsconfig: TsConfigJson | null = null;
255
+ async getTsConfig(pathname = "tsconfig.json", { refresh }: { refresh?: boolean } = {}): Promise<TsConfigJson> {
256
+ if (this.#tsconfig && !refresh) return this.#tsconfig;
257
+ let tsconfig = (await this.readJson(pathname)) as TsConfigJson;
258
+ if (tsconfig.extends) {
259
+ const base = await this.getTsConfig(tsconfig.extends, { refresh });
260
+ tsconfig = { ...base, ...tsconfig, compilerOptions: { ...base.compilerOptions, ...tsconfig.compilerOptions } };
261
+ }
262
+ this.#tsconfig = tsconfig;
263
+ return tsconfig;
264
+ }
265
+ async setTsConfig(tsconfig: TsConfigJson) {
266
+ await this.writeJson("tsconfig.json", tsconfig);
267
+ this.#tsconfig = tsconfig;
268
+ }
269
+
270
+ #packageJson: PackageJson | null = null;
271
+ async getPackageJson({ refresh }: { refresh?: boolean } = {}): Promise<PackageJson> {
272
+ if (this.#packageJson && !refresh) return this.#packageJson;
273
+ const packageJson = (await this.readJson("package.json")) as PackageJson;
274
+ this.#packageJson = packageJson;
275
+ return packageJson;
276
+ }
277
+ async setPackageJson(packageJson: PackageJson) {
278
+ await this.writeJson("package.json", packageJson);
279
+ this.#packageJson = packageJson;
280
+ }
281
+
282
+ #gitignorePatterns: string[] = [];
283
+ async getGitignorePatterns(): Promise<string[]> {
284
+ if (this.#gitignorePatterns.length) return this.#gitignorePatterns;
285
+ const gitignore = await this.readFile(".gitignore");
286
+ this.#gitignorePatterns = gitignore
287
+ .split("\n")
288
+ .map((line) => line.trim())
289
+ .filter((line) => !!line && !line.startsWith("#"));
290
+ return this.#gitignorePatterns;
291
+ }
292
+
293
+ async #applyTemplateFile(
294
+ {
295
+ templatePath,
296
+ targetPath,
297
+ scanInfo,
298
+ overwrite = true,
299
+ dryRun = false,
300
+ }: {
301
+ templatePath: string;
302
+ targetPath: string;
303
+ scanInfo?: AppInfo | LibInfo | null;
304
+ overwrite?: boolean;
305
+ dryRun?: boolean;
306
+ },
307
+ dict: { [key: string]: string } = {},
308
+ options: { [key: string]: unknown } = {},
309
+ ): Promise<WrittenFileContent | null> {
310
+ const convertPath = (target: string) =>
311
+ Object.entries(dict).reduce(
312
+ (converted, [key, value]) => converted.replace(new RegExp(`__${key}__`, "g"), value),
313
+ target,
314
+ );
315
+ if (targetPath.endsWith(".ts") || targetPath.endsWith(".tsx")) {
316
+ const getContent = (await import(templatePath)) as {
317
+ default: (
318
+ scanInfo: AppInfo | LibInfo | null,
319
+ dict: { [key: string]: string },
320
+ options?: { [key: string]: unknown },
321
+ ) => Promise<string | null | { filename: string; content: string }>;
322
+ };
323
+ const result = await getContent.default(scanInfo ?? null, dict, options);
324
+ if (result === null) return null;
325
+ const filename = typeof result === "object" ? result.filename : path.basename(targetPath).replace(".js", ".ts");
326
+ const content = typeof result === "object" ? result.content : result;
327
+ const convertedTargetPath = convertPath(`${path.dirname(targetPath)}/${filename}`);
328
+ if (dryRun) return { filePath: this.getPath(convertedTargetPath), content, written: false };
329
+ this.logger.verbose(`Apply template ${templatePath} to ${convertedTargetPath}`);
330
+ return this.writeFile(convertedTargetPath, content, { overwrite });
331
+ } else if (targetPath.endsWith(".template")) {
332
+ const content = await FileSys.readText(templatePath);
333
+ const convertedTargetPath = convertPath(targetPath.slice(0, -9));
334
+ const convertedContent = Object.entries(dict).reduce(
335
+ (data, [key, value]) => data.replace(new RegExp(`<%= ${key} %>`, "g"), value),
336
+ content,
337
+ );
338
+ if (dryRun) return { filePath: this.getPath(convertedTargetPath), content: convertedContent, written: false };
339
+ this.logger.verbose(`Apply template ${templatePath} to ${convertedTargetPath}`);
340
+ return this.writeFile(convertedTargetPath, convertedContent, { overwrite });
341
+ } else if (staticTemplateFileExtensions.has(path.extname(targetPath).toLowerCase())) {
342
+ const convertedTargetPath = convertPath(targetPath);
343
+ const writePath = this.getPath(convertedTargetPath);
344
+ if (dryRun) return { filePath: writePath, content: "", written: false };
345
+ if (!overwrite && (await FileSys.fileExists(writePath)))
346
+ return { filePath: writePath, content: "", written: false };
347
+ const dirname = path.dirname(writePath);
348
+ if (!(await FileSys.dirExists(dirname))) await mkdir(dirname, { recursive: true });
349
+ await copyFile(templatePath, writePath);
350
+ this.logger.verbose(`Apply template ${templatePath} to ${convertedTargetPath}`);
351
+ return { filePath: writePath, content: "", written: true };
352
+ } else return null;
353
+ }
354
+ async _applyTemplate({
355
+ basePath,
356
+ template,
357
+ scanInfo,
358
+ dict = {},
359
+ options = {},
360
+ overwrite = true,
361
+ dryRun = false,
362
+ }: {
363
+ basePath: string;
364
+ template: string;
365
+ scanInfo?: AppInfo | LibInfo | null;
366
+ dict?: { [key: string]: string };
367
+ options?: { [key: string]: unknown };
368
+ overwrite?: boolean;
369
+ dryRun?: boolean;
370
+ }): Promise<WrittenFileContent[]> {
371
+ const templateRoot = await this.#resolveTemplateRoot();
372
+ const templatePath = `${templateRoot}${template ? `/${template}` : ""}`;
373
+ if ((await stat(templatePath)).isFile()) {
374
+ const fileContent = await this.#applyTemplateFile(
375
+ {
376
+ templatePath,
377
+ targetPath: path.join(basePath, path.basename(templatePath)),
378
+ scanInfo,
379
+ overwrite,
380
+ dryRun,
381
+ },
382
+ dict,
383
+ options,
384
+ );
385
+ return fileContent ? [fileContent] : ([] as WrittenFileContent[]);
386
+ } else {
387
+ const subdirs = await readDirEntries(templatePath);
388
+ const fileContents = (
389
+ await Promise.all(
390
+ subdirs.map(async (subdir) => {
391
+ const subpath = path.join(templatePath, subdir);
392
+ if ((await stat(subpath)).isFile()) {
393
+ const fileContent = await this.#applyTemplateFile(
394
+ {
395
+ templatePath: subpath,
396
+ targetPath: path.join(basePath, subdir),
397
+ scanInfo,
398
+ overwrite,
399
+ dryRun,
400
+ },
401
+ dict,
402
+ options,
403
+ );
404
+ return fileContent ? [fileContent] : ([] as WrittenFileContent[]);
405
+ } else
406
+ return await this._applyTemplate({
407
+ basePath: path.join(basePath, subdir),
408
+ template: path.join(template, subdir),
409
+ scanInfo,
410
+ dict,
411
+ overwrite,
412
+ dryRun,
413
+ options,
414
+ });
415
+ }),
416
+ )
417
+ ).flat();
418
+ return fileContents;
419
+ }
420
+ }
421
+ async #resolveTemplateRoot() {
422
+ const candidates = [
423
+ path.resolve(getDirname(import.meta.url), "templates"),
424
+ path.resolve(getDirname(import.meta.url), "../../cli/templates"),
425
+ ];
426
+ for (const candidate of candidates) {
427
+ if (await FileSys.dirExists(candidate)) return candidate;
428
+ }
429
+ return candidates[0];
430
+ }
431
+ async applyTemplate(options: {
432
+ basePath: string;
433
+ template: string;
434
+ scanInfo?: AppInfo | LibInfo | null;
435
+ dict?: { [key: string]: string };
436
+ options?: { [key: string]: unknown };
437
+ overwrite?: boolean;
438
+ dryRun?: boolean;
439
+ }): Promise<FileContent[]> {
440
+ const fileContents = await this._applyTemplate({ ...options, dict: withCapitalizedDict(options.dict) });
441
+ await this.#formatAppliedTemplate(fileContents.filter((fileContent) => fileContent.written));
442
+ return fileContents;
443
+ }
444
+
445
+ // Best-effort: `create-akan-workspace` scaffolds before `bun install`, with no local Biome binary yet, so a
446
+ // template emits Biome's form itself (`templates/biomeForm.ts`).
447
+ async #formatAppliedTemplate(fileContents: FileContent[]) {
448
+ const filePaths = fileContents
449
+ .map((fileContent) => fileContent.filePath)
450
+ .filter((filePath) => filePath.endsWith(".ts") || filePath.endsWith(".tsx"));
451
+ if (filePaths.length === 0) return;
452
+ try {
453
+ const { fixed } = await this.getLinter().fixFiles(filePaths);
454
+ if (fixed.length > 0) this.logger.verbose(`Formatted ${fixed.length} scaffolded file(s)`);
455
+ } catch (err) {
456
+ this.logger.verbose(`Skipped formatting scaffolded files: ${toError(err).message}`);
457
+ }
458
+ }
459
+ // Async so `typescript` (~65MB resident) loads only in the commands that typecheck.
460
+ async getTypeChecker() {
461
+ const { TypeChecker } = await import("../typeChecker");
462
+ this.typeChecker ??= new TypeChecker(this);
463
+ return this.typeChecker;
464
+ }
465
+ async typeCheck(filePath: string) {
466
+ const path = this.getPath(filePath);
467
+ const typeChecker = await this.getTypeChecker();
468
+ const { fileDiagnostics, fileErrors, fileWarnings } = typeChecker.check(path);
469
+ const message = typeChecker.formatDiagnostics(fileDiagnostics);
470
+ return { fileDiagnostics, fileErrors, fileWarnings, message };
471
+ }
472
+ async typeCheckAsync(filePath: string) {
473
+ const path = this.getPath(filePath);
474
+ const entry = await ProjectTypecheck.workerEntry(process.cwd());
475
+ const proc = Bun.spawn([process.execPath, entry], {
476
+ cwd: this.cwdPath,
477
+ env: {
478
+ ...process.env,
479
+ AKAN_TYPECHECK_CWD: this.cwdPath,
480
+ AKAN_TYPECHECK_FILE: path,
481
+ },
482
+ stdout: "pipe",
483
+ stderr: "pipe",
484
+ });
485
+ const [stdout, stderr, exitCode] = await Promise.all([
486
+ new Response(proc.stdout).text(),
487
+ new Response(proc.stderr).text(),
488
+ proc.exited,
489
+ ]);
490
+ if (exitCode !== 0) throw new Error((stderr || stdout).trim() || `Typecheck failed with exit code ${exitCode}`);
491
+
492
+ const result = JSON.parse(stdout) as {
493
+ fileDiagnosticsCount: number;
494
+ fileErrorsCount: number;
495
+ fileWarningsCount: number;
496
+ message: string;
497
+ };
498
+ return {
499
+ fileDiagnostics: Array.from({ length: result.fileDiagnosticsCount }),
500
+ fileErrors: Array.from({ length: result.fileErrorsCount }),
501
+ fileWarnings: Array.from({ length: result.fileWarningsCount }),
502
+ message: result.message,
503
+ };
504
+ }
505
+ getLinter() {
506
+ this.linter ??= new Linter(this.cwdPath);
507
+ return this.linter;
508
+ }
509
+ async lint(
510
+ filePath: string,
511
+ { fix = false, dryRun = false }: { fix?: boolean; dryRun?: boolean } = {},
512
+ ): Promise<{
513
+ results: unknown[];
514
+ message: string;
515
+ errors: unknown[];
516
+ warnings: unknown[];
517
+ }> {
518
+ const path = this.getPath(filePath);
519
+ const linter = this.getLinter();
520
+ const { results, errors, warnings } = await linter.lint(path, {
521
+ fix,
522
+ dryRun,
523
+ });
524
+ const message = linter.formatLintResults(results);
525
+ return { results, message, errors, warnings };
526
+ }
527
+ }
@@ -0,0 +1,23 @@
1
+ import { AkanLibConfig } from "../akanConfig";
2
+ import { Executor, execEmoji } from "./executor";
3
+ import { type NamedExecutorOptions, SysExecutor } from "./sysExecutor";
4
+ import { WorkspaceExecutor } from "./workspaceExecutor";
5
+
6
+ export class LibExecutor extends SysExecutor {
7
+ dist: Executor;
8
+ override emoji = execEmoji.lib;
9
+ constructor({ workspace, name }: NamedExecutorOptions) {
10
+ super({ workspace, name, type: "lib" });
11
+ this.dist = new Executor(`dist/${name}`, `${this.workspace.workspaceRoot}/dist/libs/${name}`);
12
+ }
13
+ static from(executor: SysExecutor | WorkspaceExecutor, name: string) {
14
+ return new LibExecutor({ workspace: executor instanceof WorkspaceExecutor ? executor : executor.workspace, name });
15
+ }
16
+
17
+ #akanConfig: AkanLibConfig | null = null;
18
+ override async getConfig({ refresh }: { refresh?: boolean } = {}) {
19
+ if (this.#akanConfig && !refresh) return this.#akanConfig;
20
+ this.#akanConfig = await AkanLibConfig.from(this, { bustImportCache: refresh });
21
+ return this.#akanConfig;
22
+ }
23
+ }
@@ -0,0 +1,18 @@
1
+ import { Executor, execEmoji } from "./executor";
2
+ import type { SysExecutor } from "./sysExecutor";
3
+
4
+ interface ModuleExecutorOptions {
5
+ sys: SysExecutor;
6
+ name: string;
7
+ }
8
+ export class ModuleExecutor extends Executor {
9
+ sys: SysExecutor;
10
+ override emoji = execEmoji.module;
11
+ constructor({ sys, name }: ModuleExecutorOptions) {
12
+ super(name, `${sys.workspace.workspaceRoot}/${sys.type}s/${sys.name}/lib/${name}`);
13
+ this.sys = sys;
14
+ }
15
+ static from(sysExecutor: SysExecutor, name: string) {
16
+ return new ModuleExecutor({ sys: sysExecutor, name });
17
+ }
18
+ }
@@ -0,0 +1,129 @@
1
+ import path from "node:path";
2
+ import { PkgInfo } from "../scanInfo";
3
+ import type { PackageJson, TsConfigJson } from "../types";
4
+ import { Executor, execEmoji } from "./executor";
5
+ import type { NamedExecutorOptions, SysExecutor } from "./sysExecutor";
6
+ import { WorkspaceExecutor } from "./workspaceExecutor";
7
+
8
+ export class PkgExecutor extends Executor {
9
+ workspace: WorkspaceExecutor;
10
+ override name: string;
11
+ dist: Executor;
12
+ override emoji = execEmoji.pkg;
13
+ constructor({ workspace = WorkspaceExecutor.fromRoot(), name }: NamedExecutorOptions) {
14
+ super(name, `${workspace.workspaceRoot}/pkgs/${name}`);
15
+ this.workspace = workspace;
16
+ this.name = name;
17
+ this.dist = new Executor(`dist/${name}`, `${this.workspace.workspaceRoot}/dist/pkgs/${name}`);
18
+ }
19
+ static from(executor: SysExecutor | WorkspaceExecutor, name: string) {
20
+ return new PkgExecutor({ workspace: executor instanceof WorkspaceExecutor ? executor : executor.workspace, name });
21
+ }
22
+
23
+ #scanInfo: PkgInfo | null = null;
24
+ async scan({ refresh }: { refresh?: boolean } = {}): Promise<PkgInfo> {
25
+ if (this.#scanInfo && !refresh) return this.#scanInfo;
26
+ const scanInfo = await PkgInfo.fromExecutor(this, { refresh });
27
+ this.#scanInfo = scanInfo;
28
+ return scanInfo;
29
+ }
30
+ async #getDependencyVersion(rootPackageJson: PackageJson, dep: string): Promise<string | undefined> {
31
+ const rootDeps = {
32
+ ...rootPackageJson.dependencies,
33
+ ...rootPackageJson.devDependencies,
34
+ };
35
+ const rootVersion = rootDeps[dep];
36
+ if (rootVersion) return rootVersion;
37
+ // Overrides never reach a consumer's install, so a pinned transitive dep is published as a dependency.
38
+ const overrideVersion = rootPackageJson.overrides?.[dep];
39
+ if (typeof overrideVersion === "string") return overrideVersion;
40
+
41
+ try {
42
+ const packageJsonPath = `pkgs/${dep}/package.json`;
43
+ if (!(await Bun.file(path.join(this.workspace.workspaceRoot, packageJsonPath)).exists())) return undefined;
44
+ const packageJson = await this.workspace.readJson(packageJsonPath);
45
+ if ((packageJson as PackageJson).name === dep) return (packageJson as PackageJson).version;
46
+ } catch {
47
+ return undefined;
48
+ }
49
+ }
50
+ async #toDependencyMap(
51
+ rootPackageJson: PackageJson,
52
+ dependencies: string[] = [],
53
+ devDependencies: string[] = [],
54
+ ): Promise<Pick<PackageJson, "dependencies" | "devDependencies">> {
55
+ const dependencyNames = [...new Set(dependencies)].sort();
56
+ const devDependencyNames = [...new Set(devDependencies)]
57
+ .filter((dep) => !dependencyNames.includes(dep))
58
+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
59
+ const dependencyVersions = new Map<string, string>();
60
+ const missingDeps: string[] = [];
61
+ for (const dep of [...dependencyNames, ...devDependencyNames]) {
62
+ const version = await this.#getDependencyVersion(rootPackageJson, dep);
63
+ if (version) dependencyVersions.set(dep, version);
64
+ else missingDeps.push(dep);
65
+ }
66
+ if (missingDeps.length > 0)
67
+ throw new Error(`Missing dependency versions in root package.json: ${missingDeps.join(", ")}`);
68
+
69
+ const toDependencyMap = (names: string[]) =>
70
+ Object.fromEntries(names.map((dep) => [dep, dependencyVersions.get(dep) as string]));
71
+ return { dependencies: toDependencyMap(dependencyNames), devDependencies: toDependencyMap(devDependencyNames) };
72
+ }
73
+ async updatePackageJsonDependencies(
74
+ dependencies: string[] = [],
75
+ devDependencies: string[] = [],
76
+ ): Promise<PackageJson> {
77
+ const [rootPackageJson, pkgJson] = await Promise.all([this.workspace.getPackageJson(), this.getPackageJson()]);
78
+ const dependencyMaps = await this.#toDependencyMap(rootPackageJson, dependencies, devDependencies);
79
+ const newPkgJson = {
80
+ ...pkgJson,
81
+ ...dependencyMaps,
82
+ };
83
+ await this.writeJson("package.json", newPkgJson);
84
+ return newPkgJson;
85
+ }
86
+ async generateDistPackageJson(dependencies: string[] = [], devDependencies: string[] = []): Promise<PackageJson> {
87
+ const [rootPackageJson, pkgJson] = await Promise.all([this.workspace.getPackageJson(), this.getPackageJson()]);
88
+ const dependencyMaps = await this.#toDependencyMap(rootPackageJson, dependencies, devDependencies);
89
+ const distPkgJson: PackageJson = {
90
+ ...pkgJson,
91
+ type: "module",
92
+ exports: {
93
+ ...pkgJson.exports,
94
+ ".": {
95
+ import: "./index.ts",
96
+ types: "./index.ts",
97
+ default: "./index.ts",
98
+ },
99
+ },
100
+ engines: { bun: ">=1.4.4" },
101
+ ...dependencyMaps,
102
+ };
103
+ await Promise.all([this.dist.writeJson("package.json", distPkgJson), this.writeJson("package.json", distPkgJson)]);
104
+ return distPkgJson;
105
+ }
106
+ async build(): Promise<void> {
107
+ await Bun.build({
108
+ root: this.cwdPath,
109
+ entrypoints: [`${this.cwdPath}/index.ts`],
110
+ splitting: false,
111
+ target: "bun",
112
+ });
113
+ await this.cp(`${this.cwdPath}/dist`, this.dist.cwdPath);
114
+ }
115
+ async generateTsconfigJson(): Promise<TsConfigJson> {
116
+ const [rootTsconfig, pkgTsconfig] = await Promise.all([this.workspace.getTsConfig(), this.getTsConfig()]);
117
+ const tsconfig: TsConfigJson = {
118
+ ...rootTsconfig,
119
+ ...pkgTsconfig,
120
+ compilerOptions: {
121
+ ...rootTsconfig.compilerOptions,
122
+ ...pkgTsconfig.compilerOptions,
123
+ paths: {},
124
+ },
125
+ };
126
+ await this.dist.writeJson("tsconfig.json", tsconfig);
127
+ return tsconfig;
128
+ }
129
+ }