@codefast/cli 0.3.13-canary.0 → 0.3.13-canary.1

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.
Files changed (112) hide show
  1. package/dist/bin.mjs +1 -1
  2. package/dist/commands/arrange.mjs +106 -1
  3. package/dist/commands/mirror.mjs +65 -1
  4. package/dist/commands/tag.mjs +57 -1
  5. package/dist/lib/arrange/application/analyze.mjs +91 -1
  6. package/dist/lib/arrange/application/group-file.mjs +112 -1
  7. package/dist/lib/arrange/application/run-target.mjs +64 -1
  8. package/dist/lib/arrange/domain/ast/ast-helpers.mjs +114 -1
  9. package/dist/lib/arrange/domain/ast/collectors-cn.mjs +60 -1
  10. package/dist/lib/arrange/domain/ast/collectors-jsx.mjs +19 -1
  11. package/dist/lib/arrange/domain/ast/collectors-tv.mjs +169 -1
  12. package/dist/lib/arrange/domain/ast/targets.mjs +105 -1
  13. package/dist/lib/arrange/domain/constants.mjs +168 -1
  14. package/dist/lib/arrange/domain/errors.mjs +18 -1
  15. package/dist/lib/arrange/domain/grouping.mjs +234 -1
  16. package/dist/lib/arrange/domain/imports.mjs +53 -1
  17. package/dist/lib/arrange/domain/tokenizer.mjs +215 -1
  18. package/dist/lib/arrange/index.mjs +14 -15
  19. package/dist/lib/arrange/infra/walk.mjs +32 -1
  20. package/dist/lib/arrange/presentation/formatters.mjs +51 -1
  21. package/dist/lib/arrange/presentation/report.mjs +23 -1
  22. package/dist/lib/config/domain/schema.mjs +24 -1
  23. package/dist/lib/config/index.mjs +2 -3
  24. package/dist/lib/config/infra/loader.mjs +77 -1
  25. package/dist/lib/infra/caught-unknown-message.mjs +19 -1
  26. package/dist/lib/infra/config-reporter.mjs +9 -1
  27. package/dist/lib/infra/node-io.mjs +29 -1
  28. package/dist/lib/infra/workspace/repo-root.mjs +21 -1
  29. package/dist/lib/mirror/application/engine.mjs +247 -1
  30. package/dist/lib/mirror/application/sync.mjs +161 -1
  31. package/dist/lib/mirror/domain/constants.mjs +11 -1
  32. package/dist/lib/mirror/domain/errors.mjs +14 -1
  33. package/dist/lib/mirror/index.mjs +1 -2
  34. package/dist/lib/mirror/infra/dirent-list.mjs +13 -1
  35. package/dist/lib/mirror/infra/package-filter.mjs +25 -1
  36. package/dist/lib/mirror/infra/path-normalizer.mjs +6 -1
  37. package/dist/lib/mirror/infra/update-pkg.mjs +104 -1
  38. package/dist/lib/mirror/infra/workspace-packages.mjs +158 -1
  39. package/dist/lib/mirror/presentation/reporter.mjs +111 -2
  40. package/dist/lib/tag/application/engine.mjs +286 -1
  41. package/dist/lib/tag/index.mjs +3 -4
  42. package/dist/lib/tag/infra/target-resolver.mjs +169 -1
  43. package/dist/lib/tag/presentation/colors.mjs +11 -1
  44. package/dist/lib/tag/presentation/tag-presenter.mjs +62 -1
  45. package/dist/program.mjs +33 -1
  46. package/package.json +2 -2
  47. package/dist/analyze-DvtJ3j9m.mjs +0 -92
  48. package/dist/arrange-Bbh62DrU.mjs +0 -107
  49. package/dist/arrange-BqP2DI3w.mjs +0 -8
  50. package/dist/ast-helpers-MDRYuIAk.mjs +0 -115
  51. package/dist/caught-unknown-message-CRhkDWO7.mjs +0 -20
  52. package/dist/collectors-cn-BS8TTQ8O.mjs +0 -61
  53. package/dist/collectors-jsx-D9tL2ZPM.mjs +0 -20
  54. package/dist/collectors-tv-D2PXZaRt.mjs +0 -170
  55. package/dist/colors-BjdkCfGK.mjs +0 -12
  56. package/dist/commands/mirror.test.mjs +0 -48
  57. package/dist/config-DVia_f9a.mjs +0 -3
  58. package/dist/config-reporter-SCcWDZc1.mjs +0 -10
  59. package/dist/constants-AtPhF-Ct.mjs +0 -169
  60. package/dist/constants-Bq5wdyLC.mjs +0 -8
  61. package/dist/dirent-list-BSDeRG5i.mjs +0 -14
  62. package/dist/engine-CcWEHSCq.mjs +0 -287
  63. package/dist/engine-DRTdkc5u.mjs +0 -236
  64. package/dist/errors-CFH4w6ic.mjs +0 -15
  65. package/dist/errors-CpU1ogfA.mjs +0 -19
  66. package/dist/formatters-DGE8jJ53.mjs +0 -52
  67. package/dist/group-file-ClW7XdD6.mjs +0 -113
  68. package/dist/grouping-c1grpCQT.mjs +0 -235
  69. package/dist/imports-DSVq1xhB.mjs +0 -54
  70. package/dist/lib/arrange/application/analyze.test.mjs +0 -171
  71. package/dist/lib/arrange/application/group-file.test.mjs +0 -273
  72. package/dist/lib/arrange/application/run-target.test.mjs +0 -97
  73. package/dist/lib/arrange/domain/ast/ast-helpers.test.mjs +0 -148
  74. package/dist/lib/arrange/domain/ast/collectors-cn.test.mjs +0 -58
  75. package/dist/lib/arrange/domain/ast/collectors-jsx.test.mjs +0 -20
  76. package/dist/lib/arrange/domain/ast/collectors-tv.test.mjs +0 -145
  77. package/dist/lib/arrange/domain/ast/targets.test.mjs +0 -50
  78. package/dist/lib/arrange/domain/grouping.test.mjs +0 -186
  79. package/dist/lib/arrange/domain/imports.test.mjs +0 -48
  80. package/dist/lib/arrange/domain/tokenizer.test.mjs +0 -165
  81. package/dist/lib/arrange/infra/walk.test.mjs +0 -50
  82. package/dist/lib/arrange/presentation/formatters.test.mjs +0 -73
  83. package/dist/lib/config/infra/loader.test.mjs +0 -116
  84. package/dist/lib/infra/workspace/repo-root.test.mjs +0 -45
  85. package/dist/lib/mirror/application/sync.test.mjs +0 -482
  86. package/dist/lib/mirror/infra/dirent-list.test.mjs +0 -18
  87. package/dist/lib/mirror/infra/package-filter.test.mjs +0 -32
  88. package/dist/lib/mirror/infra/workspace-packages.test.mjs +0 -167
  89. package/dist/lib/tag/application/engine.test.mjs +0 -159
  90. package/dist/lib/tag/presentation/tag-presenter.test.mjs +0 -29
  91. package/dist/loader-DpN-zl5g.mjs +0 -78
  92. package/dist/mirror-CbGiLXKT.mjs +0 -2
  93. package/dist/mirror-DqJE3ejL.mjs +0 -66
  94. package/dist/node-io-DFRbHO6m.mjs +0 -30
  95. package/dist/package-filter-C_8ryqvz.mjs +0 -26
  96. package/dist/path-normalizer-D4ceBO3l.mjs +0 -7
  97. package/dist/program-DR-H4tH3.mjs +0 -34
  98. package/dist/repo-root-HmtIEm6J.mjs +0 -22
  99. package/dist/report-DYxvw34T.mjs +0 -24
  100. package/dist/reporter-CwIe_tAM.mjs +0 -108
  101. package/dist/run-target-CJWrqNT4.mjs +0 -65
  102. package/dist/schema-Or8RAARd.mjs +0 -25
  103. package/dist/sync-e1Sp-shi.mjs +0 -157
  104. package/dist/tag-Cd9JujU5.mjs +0 -2
  105. package/dist/tag-hEKVZ_-7.mjs +0 -58
  106. package/dist/tag-presenter-Cs66UBsH.mjs +0 -63
  107. package/dist/target-resolver-CR3FXMTy.mjs +0 -170
  108. package/dist/targets-pCTslnFh.mjs +0 -106
  109. package/dist/tokenizer-CeZx73Zu.mjs +0 -216
  110. package/dist/update-pkg-CnGfjWBy.mjs +0 -37
  111. package/dist/walk-DjgQn66n.mjs +0 -33
  112. package/dist/workspace-packages-K2NYTHJq.mjs +0 -159
@@ -1,2 +1,24 @@
1
- import { t as printAnalyzeReport } from "../../../report-DYxvw34T.mjs";
1
+ import "../domain/constants.mjs";
2
+ import path from "node:path";
3
+ //#region src/lib/arrange/presentation/report.ts
4
+ function printAnalyzeReport(analyzeRootDirectoryPath, analyzeReport, logger) {
5
+ const { out } = logger;
6
+ out(`Path: ${path.resolve(analyzeRootDirectoryPath)}`);
7
+ out(`.ts/.tsx files: ${analyzeReport.files}`);
8
+ out(`cn(...) call sites: ${analyzeReport.cnCallExpressions}`);
9
+ out(`tv(...) call sites: ${analyzeReport.tvCallExpressions}`);
10
+ out(`\nLong cn(...) string literals (≥18 tokens — consider splitting arguments): ${analyzeReport.longCnStringLiterals.length}`);
11
+ for (const findingEntry of analyzeReport.longCnStringLiterals.slice(0, 40)) out(` ${findingEntry.file}:${findingEntry.line} (${findingEntry.tokenCount} tokens) ${findingEntry.preview}`);
12
+ if (analyzeReport.longCnStringLiterals.length > 40) out(` … and ${analyzeReport.longCnStringLiterals.length - 40} more`);
13
+ out(`\nLong tv({...}) string literals in base/variants/… (≥18 tokens): ${analyzeReport.longTvStringLiterals.length}`);
14
+ for (const findingEntry of analyzeReport.longTvStringLiterals.slice(0, 40)) out(` ${findingEntry.file}:${findingEntry.line} (${findingEntry.tokenCount} tokens) ${findingEntry.preview}`);
15
+ if (analyzeReport.longTvStringLiterals.length > 40) out(` … and ${analyzeReport.longTvStringLiterals.length - 40} more`);
16
+ out(`\nJSX className="..." or className={'...'} (static strings, ≥18 tokens): ${analyzeReport.longJsxClassNameLiterals.length}`);
17
+ for (const findingEntry of analyzeReport.longJsxClassNameLiterals.slice(0, 40)) out(` ${findingEntry.file}:${findingEntry.line} (${findingEntry.tokenCount} tokens) ${findingEntry.preview}`);
18
+ if (analyzeReport.longJsxClassNameLiterals.length > 40) out(` … and ${analyzeReport.longJsxClassNameLiterals.length - 40} more`);
19
+ out(`\ncn(...) nested inside tv({...}) (prefer a string or array — preview/apply can rewrite): ${analyzeReport.cnInsideTvCalls.length}`);
20
+ for (const findingEntry of analyzeReport.cnInsideTvCalls.slice(0, 40)) out(` ${findingEntry.file}:${findingEntry.line} (${findingEntry.argCount} args) ${findingEntry.preview}`);
21
+ if (analyzeReport.cnInsideTvCalls.length > 40) out(` … and ${analyzeReport.cnInsideTvCalls.length - 40} more`);
22
+ }
23
+ //#endregion
2
24
  export { printAnalyzeReport };
@@ -1,2 +1,25 @@
1
- import { a as mirrorConfigSchema, i as hookSchema, n as codefastConfigSchema, r as codefastTagConfigSchema, t as codefastArrangeConfigSchema } from "../../../schema-Or8RAARd.mjs";
1
+ import { z } from "zod";
2
+ //#region src/lib/config/domain/schema.ts
3
+ const hookSchema = z.custom((value) => typeof value === "function", { message: "Expected a function" });
4
+ const mirrorConfigSchema = z.object({
5
+ skipPackages: z.array(z.string()).optional(),
6
+ pathTransformations: z.record(z.string(), z.object({ removePrefix: z.string().optional() }).strict()).optional(),
7
+ customExports: z.record(z.string(), z.record(z.string(), z.string())).optional(),
8
+ cssExports: z.record(z.string(), z.union([z.boolean(), z.object({
9
+ enabled: z.boolean().optional(),
10
+ customExports: z.record(z.string(), z.string()).optional(),
11
+ forceExportFiles: z.boolean().optional()
12
+ }).strict()])).optional()
13
+ }).strict();
14
+ const codefastTagConfigSchema = z.object({
15
+ skipPackages: z.array(z.string()).optional(),
16
+ onAfterWrite: hookSchema.optional()
17
+ }).strict();
18
+ const codefastArrangeConfigSchema = z.object({ onAfterWrite: hookSchema.optional() }).strict();
19
+ const codefastConfigSchema = z.object({
20
+ mirror: mirrorConfigSchema.optional(),
21
+ tag: codefastTagConfigSchema.optional(),
22
+ arrange: codefastArrangeConfigSchema.optional()
23
+ }).strict();
24
+ //#endregion
2
25
  export { codefastArrangeConfigSchema, codefastConfigSchema, codefastTagConfigSchema, hookSchema, mirrorConfigSchema };
@@ -1,4 +1,3 @@
1
- import { a as mirrorConfigSchema, i as hookSchema, n as codefastConfigSchema, r as codefastTagConfigSchema, t as codefastArrangeConfigSchema } from "../../schema-Or8RAARd.mjs";
2
- import { n as resetConfigLoaderCacheForTests, t as loadConfig } from "../../loader-DpN-zl5g.mjs";
3
- import "../../config-DVia_f9a.mjs";
1
+ import { codefastArrangeConfigSchema, codefastConfigSchema, codefastTagConfigSchema, hookSchema, mirrorConfigSchema } from "./domain/schema.mjs";
2
+ import { loadConfig, resetConfigLoaderCacheForTests } from "./infra/loader.mjs";
4
3
  export { codefastArrangeConfigSchema, codefastConfigSchema, codefastTagConfigSchema, hookSchema, loadConfig, mirrorConfigSchema, resetConfigLoaderCacheForTests };
@@ -1,2 +1,78 @@
1
- import { n as resetConfigLoaderCacheForTests, t as loadConfig } from "../../../loader-DpN-zl5g.mjs";
1
+ import { codefastConfigSchema } from "../domain/schema.mjs";
2
+ import process from "node:process";
3
+ import path from "node:path";
4
+ import jiti from "jiti";
5
+ import { ZodError } from "zod";
6
+ //#region src/lib/config/infra/loader.ts
7
+ const CONFIG_JS_PRIORITY = [
8
+ "codefast.config.mjs",
9
+ "codefast.config.js",
10
+ "codefast.config.cjs"
11
+ ];
12
+ const CONFIG_JSON = "codefast.config.json";
13
+ const cachedLoads = /* @__PURE__ */ new Map();
14
+ function formatZodError(error, filePath) {
15
+ const formatted = error.issues.map((issue) => {
16
+ return ` - ${issue.path.length > 0 ? issue.path.join(".") : "<root>"}: ${issue.message}`;
17
+ }).join("\n");
18
+ return `Invalid config schema in ${path.basename(filePath)}:\n${formatted}`;
19
+ }
20
+ function parseLoadedConfig(raw, filePath) {
21
+ try {
22
+ return codefastConfigSchema.parse(raw);
23
+ } catch (caughtError) {
24
+ if (caughtError instanceof ZodError) throw new Error(formatZodError(caughtError, filePath));
25
+ throw caughtError;
26
+ }
27
+ }
28
+ function listConfigCandidates(startDir, fs) {
29
+ const candidates = [];
30
+ let current = path.resolve(startDir);
31
+ while (true) {
32
+ for (const name of CONFIG_JS_PRIORITY) {
33
+ const candidate = path.join(current, name);
34
+ if (fs.existsSync(candidate)) candidates.push(candidate);
35
+ }
36
+ const jsonCandidate = path.join(current, CONFIG_JSON);
37
+ if (fs.existsSync(jsonCandidate)) candidates.push(jsonCandidate);
38
+ const parent = path.dirname(current);
39
+ if (parent === current) break;
40
+ current = parent;
41
+ }
42
+ return candidates;
43
+ }
44
+ async function readConfigFromPath(filePath, fs) {
45
+ if (path.extname(filePath) === ".json") {
46
+ const content = await fs.readFile(filePath, "utf8");
47
+ return parseLoadedConfig(JSON.parse(content), filePath);
48
+ }
49
+ const moduleConfig = jiti(process.cwd(), {
50
+ interopDefault: true,
51
+ moduleCache: false
52
+ })(filePath);
53
+ return parseLoadedConfig(typeof moduleConfig === "object" && moduleConfig !== null && "default" in moduleConfig ? moduleConfig.default : moduleConfig, filePath);
54
+ }
55
+ async function loadOnce(fs, startDir) {
56
+ const warnings = [];
57
+ const configPaths = listConfigCandidates(startDir, fs);
58
+ if (configPaths.length === 0) return {
59
+ config: {},
60
+ warnings
61
+ };
62
+ const configPath = configPaths[0];
63
+ return {
64
+ config: await readConfigFromPath(configPath, fs),
65
+ warnings,
66
+ configPath
67
+ };
68
+ }
69
+ async function loadConfig(fs, startDir = process.cwd()) {
70
+ const cacheKey = path.resolve(startDir);
71
+ if (!cachedLoads.has(cacheKey)) cachedLoads.set(cacheKey, loadOnce(fs, cacheKey));
72
+ return cachedLoads.get(cacheKey);
73
+ }
74
+ function resetConfigLoaderCacheForTests() {
75
+ cachedLoads.clear();
76
+ }
77
+ //#endregion
2
78
  export { loadConfig, resetConfigLoaderCacheForTests };
@@ -1,2 +1,20 @@
1
- import { t as messageFromCaughtUnknown } from "../../caught-unknown-message-CRhkDWO7.mjs";
1
+ //#region src/lib/infra/caught-unknown-message.ts
2
+ /**
3
+ * Stable, user-facing text for values caught as `unknown`.
4
+ * Avoids `String(unknown)` / `[object Object]` and satisfies strict `no-base-to-string`.
5
+ */
6
+ function messageFromCaughtUnknown(value) {
7
+ if (value instanceof Error) return value.message;
8
+ if (typeof value === "string") return value;
9
+ if (typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") return String(value);
10
+ if (typeof value === "symbol") return String(value);
11
+ if (value === null) return "null";
12
+ if (value === void 0) return "undefined";
13
+ try {
14
+ const serialized = JSON.stringify(value);
15
+ if (typeof serialized === "string") return serialized;
16
+ } catch {}
17
+ return "[unserializable non-Error value]";
18
+ }
19
+ //#endregion
2
20
  export { messageFromCaughtUnknown };
@@ -1,2 +1,10 @@
1
- import { t as printConfigSchemaWarnings } from "../../config-reporter-SCcWDZc1.mjs";
1
+ //#region src/lib/infra/config-reporter.ts
2
+ const YELLOW = "\x1B[33m";
3
+ const RESET = "\x1B[0m";
4
+ /** User-visible lines for non-fatal issues returned with a successfully parsed config. */
5
+ function printConfigSchemaWarnings(logger, warnings) {
6
+ const { out } = logger;
7
+ for (const warningMessage of warnings) out(`${YELLOW}\u26A0\uFE0F ${warningMessage}${RESET}`);
8
+ }
9
+ //#endregion
2
10
  export { printConfigSchemaWarnings };
@@ -1,2 +1,30 @@
1
- import { n as createNodeCliLogger, t as createNodeCliFs } from "../../node-io-DFRbHO6m.mjs";
1
+ import process from "node:process";
2
+ import fsSync from "node:fs";
3
+ import fsPromises from "node:fs/promises";
4
+ //#region src/lib/infra/node-io.ts
5
+ function createNodeCliFs() {
6
+ return {
7
+ existsSync: fsSync.existsSync,
8
+ statSync: fsSync.statSync,
9
+ readFileSync: fsSync.readFileSync,
10
+ writeFileSync: fsSync.writeFileSync,
11
+ readdirSync: fsSync.readdirSync,
12
+ readFile: (p, enc) => fsPromises.readFile(p, enc),
13
+ writeFile: (p, data, enc) => fsPromises.writeFile(p, data, enc),
14
+ readdir: (p, opts) => fsPromises.readdir(p, opts),
15
+ rename: (oldPath, newPath) => fsPromises.rename(oldPath, newPath),
16
+ unlink: (p) => fsPromises.unlink(p)
17
+ };
18
+ }
19
+ function createNodeCliLogger() {
20
+ return {
21
+ out: (line) => {
22
+ process.stdout.write(`${line}\n`);
23
+ },
24
+ err: (line) => {
25
+ process.stderr.write(`${line}\n`);
26
+ }
27
+ };
28
+ }
29
+ //#endregion
2
30
  export { createNodeCliFs, createNodeCliLogger };
@@ -1,2 +1,22 @@
1
- import { t as findRepoRoot } from "../../../repo-root-HmtIEm6J.mjs";
1
+ import path from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ //#region src/lib/infra/workspace/repo-root.ts
4
+ /**
5
+ * Resolve the monorepo root (directory containing `pnpm-workspace.yaml`).
6
+ * Tries the compiled package location first, then `process.cwd()`.
7
+ */
8
+ function findRepoRoot(fs) {
9
+ const candidates = [path.dirname(fileURLToPath(import.meta.url)), process.cwd()];
10
+ for (const start of candidates) {
11
+ let dir = path.resolve(start);
12
+ for (;;) {
13
+ if (fs.existsSync(path.join(dir, "pnpm-workspace.yaml"))) return dir;
14
+ const parent = path.dirname(dir);
15
+ if (parent === dir) break;
16
+ dir = parent;
17
+ }
18
+ }
19
+ throw new Error(`Could not locate monorepo root (missing pnpm-workspace.yaml). Searched from: ${candidates.join(", ")}`);
20
+ }
21
+ //#endregion
2
22
  export { findRepoRoot };
@@ -1,2 +1,248 @@
1
- import { n as generateExports, t as createPathTransform } from "../../../engine-DRTdkc5u.mjs";
1
+ import { DTS_EXTENSION, PACKAGE_JSON_EXPORT, VALID_JS_EXTENSIONS } from "../domain/constants.mjs";
2
+ import { isDirentList } from "../infra/dirent-list.mjs";
3
+ import { normalizePath } from "../infra/path-normalizer.mjs";
4
+ import path from "node:path";
5
+ //#region src/lib/mirror/application/engine.ts
6
+ function resolvePackageScopedConfig(configMap, pkgMeta) {
7
+ if (!configMap) return;
8
+ return configMap[pkgMeta.packageName];
9
+ }
10
+ async function scanDirectoryFiles(fs, dir, baseDir = dir) {
11
+ try {
12
+ const raw = await fs.readdir(dir, {
13
+ recursive: true,
14
+ withFileTypes: true
15
+ });
16
+ if (!isDirentList(raw)) return [];
17
+ return raw.filter((dirent) => dirent.isFile()).map((dirent) => {
18
+ const fullPath = path.join(dirent.parentPath, dirent.name);
19
+ return normalizePath(path.relative(baseDir, fullPath));
20
+ });
21
+ } catch (caughtError) {
22
+ if (caughtError && typeof caughtError === "object" && "code" in caughtError) {
23
+ if (caughtError.code === "ENOENT" || caughtError.code === "EACCES") return [];
24
+ }
25
+ throw caughtError;
26
+ }
27
+ }
28
+ async function isDirectoryCssOnly(fs, distDir, dirPath) {
29
+ try {
30
+ const raw = await fs.readdir(path.join(distDir, dirPath), { withFileTypes: true });
31
+ if (!isDirentList(raw)) return false;
32
+ if (raw.length === 0) return true;
33
+ return raw.every((dirent) => dirent.isFile() && dirent.name.endsWith(".css"));
34
+ } catch {
35
+ return false;
36
+ }
37
+ }
38
+ function groupFilesByModule(files) {
39
+ const modules = /* @__PURE__ */ new Map();
40
+ for (const file of files) {
41
+ let ext;
42
+ let modulePath;
43
+ if (file.endsWith(".d.ts")) {
44
+ ext = DTS_EXTENSION;
45
+ modulePath = file.slice(0, -DTS_EXTENSION.length);
46
+ } else {
47
+ ext = path.extname(file);
48
+ if (!VALID_JS_EXTENSIONS.has(ext)) continue;
49
+ modulePath = file.slice(0, -ext.length);
50
+ }
51
+ if (!path.basename(modulePath)) continue;
52
+ let distModule = modules.get(modulePath);
53
+ if (!distModule) {
54
+ distModule = {
55
+ path: modulePath,
56
+ files: {
57
+ js: null,
58
+ mjs: null,
59
+ cjs: null,
60
+ dts: null
61
+ }
62
+ };
63
+ modules.set(modulePath, distModule);
64
+ }
65
+ if (ext === ".js") distModule.files.js = file;
66
+ else if (ext === ".mjs") distModule.files.mjs = file;
67
+ else if (ext === ".cjs") distModule.files.cjs = file;
68
+ else if (ext === ".d.ts") distModule.files.dts = file;
69
+ }
70
+ return modules;
71
+ }
72
+ function toExportPath(distPath) {
73
+ if (distPath === "index") return ".";
74
+ if (distPath.endsWith("/index")) return `./${distPath.slice(0, -6)}`;
75
+ return `./${distPath}`;
76
+ }
77
+ const GROUP_ORDER = {
78
+ components: 100,
79
+ hooks: 200,
80
+ primitives: 300,
81
+ core: 400,
82
+ loaders: 500,
83
+ utils: 600,
84
+ adapters: 700,
85
+ script: 750,
86
+ css: 900
87
+ };
88
+ function getExportGroup(exportPath, pathTransform) {
89
+ if (exportPath === ".") return [
90
+ ".",
91
+ "",
92
+ 0,
93
+ 0
94
+ ];
95
+ const cleanPath = exportPath.startsWith("./") ? exportPath.slice(2) : exportPath;
96
+ if (cleanPath.endsWith("/*")) {
97
+ const dirName = cleanPath.slice(0, -2);
98
+ return [
99
+ dirName,
100
+ "",
101
+ dirName === "css" ? 900 : 100,
102
+ 0
103
+ ];
104
+ }
105
+ const parts = cleanPath.split("/");
106
+ if (parts.length === 1) {
107
+ const name = parts[0];
108
+ if (name in GROUP_ORDER) return [
109
+ name,
110
+ "",
111
+ GROUP_ORDER[name] ?? 0,
112
+ 0
113
+ ];
114
+ if (pathTransform) return [
115
+ "components",
116
+ name,
117
+ 100,
118
+ 1
119
+ ];
120
+ return [
121
+ "",
122
+ name,
123
+ 800,
124
+ 1
125
+ ];
126
+ }
127
+ const group = parts[0] ?? "";
128
+ return [
129
+ group,
130
+ parts.slice(1).join("/"),
131
+ GROUP_ORDER[group] ?? 700,
132
+ 1
133
+ ];
134
+ }
135
+ function createPathTransform(config, pkgMeta) {
136
+ const pathConfig = resolvePackageScopedConfig(config?.pathTransformations, pkgMeta);
137
+ if (!pathConfig) return null;
138
+ const { removePrefix } = pathConfig;
139
+ if (!removePrefix) return null;
140
+ return (exportPath) => {
141
+ if (!exportPath.startsWith(removePrefix)) return exportPath;
142
+ const result = exportPath.slice(removePrefix.length);
143
+ if (result && result !== "." && !result.startsWith("./")) return `./${result}`;
144
+ return result;
145
+ };
146
+ }
147
+ function getSortTuple(exportPath, pathTransform) {
148
+ const [group, subpath, order, isIndex] = getExportGroup(exportPath, pathTransform);
149
+ return [
150
+ order,
151
+ group,
152
+ isIndex,
153
+ subpath
154
+ ];
155
+ }
156
+ function compareTuples(left, right) {
157
+ if (left[0] !== right[0]) return left[0] - right[0];
158
+ if (left[1] !== right[1]) return left[1] < right[1] ? -1 : 1;
159
+ if (left[2] !== right[2]) return left[2] - right[2];
160
+ if (left[3] !== right[3]) return left[3] < right[3] ? -1 : 1;
161
+ return 0;
162
+ }
163
+ async function generateCssExports(fs, distDir, cssConfig) {
164
+ if (cssConfig === false) return {};
165
+ if (cssConfig === true) cssConfig = { enabled: true };
166
+ if (!cssConfig || cssConfig.enabled === false) return {};
167
+ const cssFiles = (await scanDirectoryFiles(fs, distDir)).filter((relativeDistPath) => relativeDistPath.endsWith(".css"));
168
+ if (!cssFiles.length) return {};
169
+ const cssExports = { ...cssConfig.customExports };
170
+ const cssByDir = /* @__PURE__ */ new Map();
171
+ const rootCss = [];
172
+ for (const file of cssFiles) {
173
+ const dirName = normalizePath(path.dirname(file));
174
+ if (dirName === ".") rootCss.push(file);
175
+ else {
176
+ const arr = cssByDir.get(dirName) || [];
177
+ arr.push(file);
178
+ cssByDir.set(dirName, arr);
179
+ }
180
+ }
181
+ for (const file of rootCss) {
182
+ const exportPath = `./${file}`;
183
+ if (!(exportPath in cssExports)) cssExports[exportPath] = `./dist/${file}`;
184
+ }
185
+ for (const [dirName, dirFiles] of cssByDir.entries()) if (await isDirectoryCssOnly(fs, distDir, dirName) && !cssConfig.forceExportFiles) {
186
+ const wildcardExport = `./${dirName}/*`;
187
+ if (!(wildcardExport in cssExports)) cssExports[wildcardExport] = `./dist/${dirName}/*`;
188
+ } else for (const file of dirFiles) {
189
+ const exportPath = `./${file}`;
190
+ if (!(exportPath in cssExports)) cssExports[exportPath] = `./dist/${file}`;
191
+ }
192
+ return cssExports;
193
+ }
194
+ /**
195
+ * Compute `package.json#exports` from a built `dist/` tree. No logging; no writes.
196
+ */
197
+ async function generateExports(fs, distDir, pathTransform, cssConfig, customExports) {
198
+ const files = await scanDirectoryFiles(fs, distDir);
199
+ if (!files.length) return {
200
+ exports: { [PACKAGE_JSON_EXPORT]: PACKAGE_JSON_EXPORT },
201
+ originalPathBySpecifier: { [PACKAGE_JSON_EXPORT]: PACKAGE_JSON_EXPORT },
202
+ jsCount: 0,
203
+ cssCount: 0
204
+ };
205
+ const modules = groupFilesByModule(files);
206
+ const validModules = Array.from(modules.values()).filter((moduleEntry) => (moduleEntry.files.js || moduleEntry.files.mjs) && moduleEntry.files.dts);
207
+ if (!validModules.length) return {
208
+ exports: { [PACKAGE_JSON_EXPORT]: PACKAGE_JSON_EXPORT },
209
+ originalPathBySpecifier: { [PACKAGE_JSON_EXPORT]: PACKAGE_JSON_EXPORT },
210
+ jsCount: 0,
211
+ cssCount: 0
212
+ };
213
+ const exportsObj = {};
214
+ const originalPathBySpecifier = {};
215
+ for (const distModuleEntry of validModules) {
216
+ const originalExportPath = toExportPath(distModuleEntry.path);
217
+ let exportPath = originalExportPath;
218
+ if (pathTransform) exportPath = pathTransform(exportPath);
219
+ const distPath = `./dist/${distModuleEntry.path}`;
220
+ const entry = { types: `${distPath}.d.ts` };
221
+ if (distModuleEntry.files.mjs) entry.import = `${distPath}.mjs`;
222
+ else if (distModuleEntry.files.js) entry.import = `${distPath}.js`;
223
+ if (distModuleEntry.files.cjs) entry.require = `${distPath}.cjs`;
224
+ exportsObj[exportPath] = entry;
225
+ originalPathBySpecifier[exportPath] = originalExportPath;
226
+ }
227
+ let sortedKeys = Object.keys(exportsObj).sort((pathA, pathB) => compareTuples(getSortTuple(pathA, pathTransform), getSortTuple(pathB, pathTransform)));
228
+ const sortedExports = {};
229
+ for (const exportKey of sortedKeys) sortedExports[exportKey] = exportsObj[exportKey];
230
+ const cssExports = await generateCssExports(fs, distDir, cssConfig ?? { enabled: true });
231
+ Object.assign(sortedExports, cssExports);
232
+ for (const [specifier, mappedPath] of Object.entries(customExports || {})) if (specifier !== "./package.json") sortedExports[specifier] = mappedPath;
233
+ for (const cssSpecifier of Object.keys(cssExports)) if (!(cssSpecifier in originalPathBySpecifier)) originalPathBySpecifier[cssSpecifier] = cssSpecifier;
234
+ for (const customSpecifier of Object.keys(customExports || {})) if (customSpecifier !== "./package.json" && !(customSpecifier in originalPathBySpecifier)) originalPathBySpecifier[customSpecifier] = customSpecifier;
235
+ sortedKeys = Object.keys(sortedExports).filter((exportKey) => exportKey !== PACKAGE_JSON_EXPORT).sort((pathA, pathB) => compareTuples(getSortTuple(pathA, pathTransform), getSortTuple(pathB, pathTransform)));
236
+ const finalExports = {};
237
+ for (const exportKey of sortedKeys) finalExports[exportKey] = sortedExports[exportKey];
238
+ finalExports[PACKAGE_JSON_EXPORT] = PACKAGE_JSON_EXPORT;
239
+ originalPathBySpecifier[PACKAGE_JSON_EXPORT] = PACKAGE_JSON_EXPORT;
240
+ return {
241
+ exports: finalExports,
242
+ originalPathBySpecifier,
243
+ jsCount: Object.keys(exportsObj).length,
244
+ cssCount: Object.keys(cssExports).length
245
+ };
246
+ }
247
+ //#endregion
2
248
  export { createPathTransform, generateExports };
@@ -1,2 +1,162 @@
1
- import { t as runMirrorSync } from "../../../sync-e1Sp-shi.mjs";
1
+ import { messageFromCaughtUnknown } from "../../infra/caught-unknown-message.mjs";
2
+ import { DIST_DIR, PACKAGE_JSON } from "../domain/constants.mjs";
3
+ import { createPathTransform, generateExports } from "./engine.mjs";
4
+ import { resolvePackageFilterUnderRoot } from "../infra/package-filter.mjs";
5
+ import { configureMirrorColors, logPackageError, logPackageSuccess, logPrunedStaleExport, logSkippedWorkspacePackage, mirrorBanner, mirrorFatalError, mirrorNoPackages, mirrorProcessingMode, mirrorSummary, mirrorSummarySeparator } from "../presentation/reporter.mjs";
6
+ import { resolvePackageDisplayName, writePackageJsonExportsAtomic } from "../infra/update-pkg.mjs";
7
+ import { findWorkspacePackageRelPaths } from "../infra/workspace-packages.mjs";
8
+ import path from "node:path";
9
+ //#region src/lib/mirror/application/sync.ts
10
+ function resolvePackageScopedConfig(configMap, pkgMeta) {
11
+ if (!configMap) return;
12
+ return configMap[pkgMeta.packageName];
13
+ }
14
+ function isPackageSkipped(skipPackagesArray, pkgMeta) {
15
+ if (!skipPackagesArray) return false;
16
+ return skipPackagesArray.includes(pkgMeta.packageName);
17
+ }
18
+ async function syncExportsForWorkspacePackage(fs, logger, rootDir, packagePathStr, index, total, config, verbose, stats) {
19
+ const packageDir = path.resolve(rootDir, packagePathStr);
20
+ const distDir = path.join(packageDir, DIST_DIR);
21
+ const packageJsonPath = path.join(packageDir, PACKAGE_JSON);
22
+ const folderBasename = path.basename(packageDir);
23
+ const pkgStats = {
24
+ name: folderBasename,
25
+ path: packageDir,
26
+ jsModules: 0,
27
+ cssExports: 0,
28
+ customExports: 0,
29
+ totalExports: 0,
30
+ hasTransform: false,
31
+ cssConfigStatus: "",
32
+ skipped: false,
33
+ skipReason: "",
34
+ error: null
35
+ };
36
+ if (!fs.existsSync(packageJsonPath)) {
37
+ pkgStats.skipped = true;
38
+ pkgStats.skipReason = "package.json not found";
39
+ stats.packagesSkipped++;
40
+ logSkippedWorkspacePackage(logger, index, total, folderBasename, pkgStats.skipReason);
41
+ return pkgStats;
42
+ }
43
+ let packageJsonParseError;
44
+ try {
45
+ const pkgContent = await fs.readFile(packageJsonPath, "utf8");
46
+ const raw = JSON.parse(pkgContent);
47
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) throw new SyntaxError("package.json root must be a JSON object");
48
+ pkgStats.name = resolvePackageDisplayName(raw, folderBasename);
49
+ } catch (caughtError) {
50
+ pkgStats.name = folderBasename;
51
+ packageJsonParseError = caughtError;
52
+ }
53
+ const pkgMeta = { packageName: pkgStats.name };
54
+ if (isPackageSkipped(config.skipPackages, pkgMeta)) {
55
+ pkgStats.skipped = true;
56
+ pkgStats.skipReason = "configured to skip";
57
+ stats.packagesSkipped++;
58
+ logSkippedWorkspacePackage(logger, index, total, pkgStats.name, pkgStats.skipReason);
59
+ return pkgStats;
60
+ }
61
+ if (packageJsonParseError !== void 0) {
62
+ if (!fs.existsSync(distDir)) {
63
+ pkgStats.skipped = true;
64
+ pkgStats.skipReason = "dist/ not found";
65
+ stats.packagesSkipped++;
66
+ logSkippedWorkspacePackage(logger, index, total, pkgStats.name, pkgStats.skipReason);
67
+ return pkgStats;
68
+ }
69
+ pkgStats.error = messageFromCaughtUnknown(packageJsonParseError);
70
+ stats.packagesErrored++;
71
+ logPackageError(logger, index, total, pkgStats.name, packageJsonParseError, verbose);
72
+ return pkgStats;
73
+ }
74
+ if (!fs.existsSync(distDir)) {
75
+ pkgStats.skipped = true;
76
+ pkgStats.skipReason = "dist/ not found";
77
+ stats.packagesSkipped++;
78
+ logSkippedWorkspacePackage(logger, index, total, pkgStats.name, pkgStats.skipReason);
79
+ return pkgStats;
80
+ }
81
+ try {
82
+ const pathTransform = createPathTransform(config, pkgMeta);
83
+ pkgStats.hasTransform = !!pathTransform;
84
+ const cssConfig = resolvePackageScopedConfig(config.cssExports, pkgMeta);
85
+ if (cssConfig === false) pkgStats.cssConfigStatus = "disabled";
86
+ else if (cssConfig !== void 0) pkgStats.cssConfigStatus = "configured";
87
+ const customExports = resolvePackageScopedConfig(config.customExports, pkgMeta) || {};
88
+ const generatedExports = await generateExports(fs, distDir, pathTransform, cssConfig, customExports);
89
+ const { prunedKeys } = await writePackageJsonExportsAtomic(fs, packageJsonPath, {
90
+ generatedExports: generatedExports.exports,
91
+ managedExportSpecifiers: Object.keys(generatedExports.exports),
92
+ originalPathBySpecifier: generatedExports.originalPathBySpecifier
93
+ });
94
+ for (const exportSpecifier of prunedKeys) logPrunedStaleExport(logger, exportSpecifier);
95
+ pkgStats.jsModules = generatedExports.jsCount;
96
+ pkgStats.cssExports = generatedExports.cssCount;
97
+ pkgStats.customExports = Object.keys(customExports).length;
98
+ pkgStats.totalExports = Object.keys(generatedExports.exports).length;
99
+ stats.packagesProcessed++;
100
+ stats.totalExports += pkgStats.totalExports;
101
+ stats.totalJsModules += pkgStats.jsModules;
102
+ stats.totalCssExports += pkgStats.cssExports;
103
+ logPackageSuccess(logger, index, total, pkgStats, generatedExports, verbose);
104
+ } catch (caughtError) {
105
+ pkgStats.error = messageFromCaughtUnknown(caughtError);
106
+ stats.packagesErrored++;
107
+ logPackageError(logger, index, total, pkgStats.name, caughtError, verbose);
108
+ }
109
+ return pkgStats;
110
+ }
111
+ /** @returns Process exit code (0 or 1). */
112
+ async function runMirrorSync(opts) {
113
+ const { fs, logger } = opts;
114
+ const config = opts.config ?? {};
115
+ configureMirrorColors(!!opts.noColor);
116
+ mirrorBanner(logger);
117
+ const startTime = performance.now();
118
+ const verbose = !!opts.verbose;
119
+ try {
120
+ const stats = {
121
+ packagesFound: 0,
122
+ packagesProcessed: 0,
123
+ packagesSkipped: 0,
124
+ packagesErrored: 0,
125
+ totalExports: 0,
126
+ totalJsModules: 0,
127
+ totalCssExports: 0,
128
+ packageDetails: []
129
+ };
130
+ let targetPackages = [];
131
+ if (opts.packageFilter) {
132
+ targetPackages = [resolvePackageFilterUnderRoot(opts.rootDir, opts.packageFilter)];
133
+ mirrorProcessingMode(logger, { kind: "single" });
134
+ } else {
135
+ const { relPaths, multiSource } = await findWorkspacePackageRelPaths(opts.rootDir, fs, logger);
136
+ targetPackages = relPaths;
137
+ mirrorProcessingMode(logger, {
138
+ kind: "multi",
139
+ source: multiSource
140
+ });
141
+ }
142
+ stats.packagesFound = targetPackages.length;
143
+ if (targetPackages.length === 0) {
144
+ mirrorNoPackages(logger);
145
+ return 0;
146
+ }
147
+ let nextPackageOrdinal = 1;
148
+ for (const pkgPath of targetPackages) {
149
+ const pkgStats = await syncExportsForWorkspacePackage(fs, logger, opts.rootDir, pkgPath, nextPackageOrdinal++, targetPackages.length, config, verbose, stats);
150
+ stats.packageDetails.push(pkgStats);
151
+ }
152
+ const elapsed = (performance.now() - startTime) / 1e3;
153
+ mirrorSummarySeparator(logger);
154
+ mirrorSummary(logger, stats, elapsed);
155
+ return stats.packagesErrored > 0 ? 1 : 0;
156
+ } catch (caughtError) {
157
+ mirrorFatalError(logger, caughtError);
158
+ return 1;
159
+ }
160
+ }
161
+ //#endregion
2
162
  export { runMirrorSync };
@@ -1,2 +1,12 @@
1
- import { a as VALID_JS_EXTENSIONS, i as PACKAGE_JSON_EXPORT, n as DTS_EXTENSION, r as PACKAGE_JSON, t as DIST_DIR } from "../../../constants-Bq5wdyLC.mjs";
1
+ //#region src/lib/mirror/domain/constants.ts
2
+ const DIST_DIR = "dist";
3
+ const PACKAGE_JSON = "package.json";
4
+ const VALID_JS_EXTENSIONS = new Set([
5
+ ".js",
6
+ ".mjs",
7
+ ".cjs"
8
+ ]);
9
+ const DTS_EXTENSION = ".d.ts";
10
+ const PACKAGE_JSON_EXPORT = "./package.json";
11
+ //#endregion
2
12
  export { DIST_DIR, DTS_EXTENSION, PACKAGE_JSON, PACKAGE_JSON_EXPORT, VALID_JS_EXTENSIONS };
@@ -1,2 +1,15 @@
1
- import { n as MirrorErrorCode, t as MirrorError } from "../../../errors-CFH4w6ic.mjs";
1
+ //#region src/lib/mirror/domain/errors.ts
2
+ const MirrorErrorCode = {
3
+ FATAL: "FATAL",
4
+ PACKAGE_WRITE: "PACKAGE_WRITE"
5
+ };
6
+ var MirrorError = class extends Error {
7
+ code;
8
+ constructor(code, message, options) {
9
+ super(message, options);
10
+ this.name = "MirrorError";
11
+ this.code = code;
12
+ }
13
+ };
14
+ //#endregion
2
15
  export { MirrorError, MirrorErrorCode };