adorn-api 1.0.15 → 1.0.16

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/dist/cli.cjs CHANGED
@@ -24,8 +24,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
24
24
  ));
25
25
 
26
26
  // src/cli.ts
27
- var import_node_fs5 = require("fs");
28
- var import_node_path5 = require("path");
27
+ var import_node_fs6 = require("fs");
28
+ var import_node_path6 = require("path");
29
29
 
30
30
  // src/compiler/runner/createProgram.ts
31
31
  var import_typescript = __toESM(require("typescript"), 1);
@@ -2351,16 +2351,961 @@ function writeCache(params) {
2351
2351
  import_node_fs4.default.writeFileSync(import_node_path4.default.join(outDirAbs, "cache.json"), JSON.stringify(cache, null, 2), "utf8");
2352
2352
  }
2353
2353
 
2354
- // src/cli.ts
2355
- var import_typescript12 = __toESM(require("typescript"), 1);
2354
+ // src/cli/progress.ts
2356
2355
  var import_node_process = __toESM(require("process"), 1);
2356
+ var ProgressTracker = class {
2357
+ phases = /* @__PURE__ */ new Map();
2358
+ startTime;
2359
+ verbose = false;
2360
+ quiet = false;
2361
+ indentLevel = 0;
2362
+ constructor(options = {}) {
2363
+ this.verbose = options.verbose ?? false;
2364
+ this.quiet = options.quiet ?? false;
2365
+ this.startTime = performance.now();
2366
+ }
2367
+ /**
2368
+ * Start a new phase.
2369
+ */
2370
+ startPhase(name, message) {
2371
+ this.phases.set(name, {
2372
+ name,
2373
+ startTime: performance.now(),
2374
+ status: "running",
2375
+ message
2376
+ });
2377
+ if (!this.quiet) {
2378
+ this.log(`\u25CF ${message || name}`);
2379
+ }
2380
+ }
2381
+ /**
2382
+ * Complete a phase successfully.
2383
+ */
2384
+ completePhase(name, message) {
2385
+ const phase = this.phases.get(name);
2386
+ if (phase) {
2387
+ phase.endTime = performance.now();
2388
+ phase.status = "completed";
2389
+ phase.message = message;
2390
+ }
2391
+ if (!this.quiet) {
2392
+ const elapsed = phase ? this.formatElapsed(phase.startTime, phase.endTime) : "";
2393
+ const status = this.verbose ? `\u2713 ${message || name} ${elapsed}` : `\u2713 ${message || name}`;
2394
+ this.log(status);
2395
+ }
2396
+ }
2397
+ /**
2398
+ * Mark a phase as failed.
2399
+ */
2400
+ failPhase(name, message) {
2401
+ const phase = this.phases.get(name);
2402
+ if (phase) {
2403
+ phase.endTime = performance.now();
2404
+ phase.status = "failed";
2405
+ phase.message = message;
2406
+ }
2407
+ if (!this.quiet) {
2408
+ this.log(`\u2717 ${message || name}`);
2409
+ }
2410
+ }
2411
+ /**
2412
+ * Log a verbose message.
2413
+ */
2414
+ verboseLog(message) {
2415
+ if (this.verbose && !this.quiet) {
2416
+ const elapsed = this.formatElapsed(this.startTime);
2417
+ this.log(`[${elapsed}] ${message}`);
2418
+ }
2419
+ }
2420
+ /**
2421
+ * Log a regular message.
2422
+ */
2423
+ log(message) {
2424
+ const indent = " ".repeat(this.indentLevel);
2425
+ import_node_process.default.stdout.write(indent + message + "\n");
2426
+ }
2427
+ /**
2428
+ * Log a sub-message (indented).
2429
+ */
2430
+ logSub(message) {
2431
+ this.indentLevel++;
2432
+ this.log(message);
2433
+ this.indentLevel--;
2434
+ }
2435
+ /**
2436
+ * Get the total elapsed time in milliseconds.
2437
+ */
2438
+ getTotalElapsed() {
2439
+ return performance.now() - this.startTime;
2440
+ }
2441
+ /**
2442
+ * Format elapsed time as a human-readable string.
2443
+ */
2444
+ formatElapsed(startTime, endTime) {
2445
+ const elapsed = (endTime ?? performance.now()) - (startTime ?? this.startTime);
2446
+ if (elapsed < 1) {
2447
+ return `${(elapsed * 1e3).toFixed(0)}ms`;
2448
+ } else if (elapsed < 1e3) {
2449
+ return `${elapsed.toFixed(0)}ms`;
2450
+ } else {
2451
+ return `${(elapsed / 1e3).toFixed(2)}s`;
2452
+ }
2453
+ }
2454
+ /**
2455
+ * Get all completed phases with their timings.
2456
+ */
2457
+ getPhases() {
2458
+ return Array.from(this.phases.values());
2459
+ }
2460
+ /**
2461
+ * Print a build summary.
2462
+ */
2463
+ printSummary(stats) {
2464
+ if (this.quiet) return;
2465
+ const totalTime = this.getTotalElapsed();
2466
+ this.log("");
2467
+ this.log("Build Summary:");
2468
+ this.log(` Controllers: ${stats.controllers}`);
2469
+ this.log(` Operations: ${stats.operations}`);
2470
+ this.log(` Schemas: ${stats.schemas}`);
2471
+ this.log(` Source files: ${stats.sourceFiles}`);
2472
+ this.log(` Output dir: ${stats.artifactsWritten[0]?.split("/").slice(0, -1).join("/") || ".adorn"}`);
2473
+ this.log("");
2474
+ this.log("Timings:");
2475
+ for (const phase of this.phases.values()) {
2476
+ if (phase.status === "completed" && phase.endTime) {
2477
+ const elapsed = phase.endTime - phase.startTime;
2478
+ const timeStr = elapsed < 1 ? `${(elapsed * 1e3).toFixed(0)}ms` : elapsed < 1e3 ? `${elapsed.toFixed(0)}ms` : `${(elapsed / 1e3).toFixed(2)}s`;
2479
+ this.log(` ${phase.name.padEnd(20)} ${timeStr}`);
2480
+ }
2481
+ }
2482
+ this.log(` ${"\u2500".repeat(21)}`);
2483
+ this.log(` Total time: ${this.formatElapsed()}`);
2484
+ this.log("");
2485
+ }
2486
+ /**
2487
+ * Print artifact list.
2488
+ */
2489
+ printArtifacts(artifacts) {
2490
+ if (this.quiet) return;
2491
+ this.log("Written artifacts:");
2492
+ for (const artifact of artifacts) {
2493
+ const sizeStr = artifact.size ? ` (${artifact.size >= 1024 ? `${(artifact.size / 1024).toFixed(1)} KB` : `${artifact.size} B`})` : "";
2494
+ this.log(` \u251C\u2500\u2500 ${artifact.name}${sizeStr}`);
2495
+ }
2496
+ }
2497
+ };
2498
+ var Spinner = class {
2499
+ frames = ["\u280B", "\u2819", "\u2839", "\u2838", "\u28B0", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
2500
+ interval;
2501
+ message;
2502
+ constructor(message = "") {
2503
+ this.message = message;
2504
+ }
2505
+ /**
2506
+ * Start the spinner.
2507
+ */
2508
+ start() {
2509
+ let frameIndex = 0;
2510
+ this.interval = setInterval(() => {
2511
+ const frame = this.frames[frameIndex];
2512
+ import_node_process.default.stdout.write(`\r${frame} ${this.message}`);
2513
+ frameIndex = (frameIndex + 1) % this.frames.length;
2514
+ }, 80);
2515
+ }
2516
+ /**
2517
+ * Stop the spinner with a completion message.
2518
+ */
2519
+ stop(completedMessage) {
2520
+ if (this.interval) {
2521
+ clearInterval(this.interval);
2522
+ this.interval = void 0;
2523
+ }
2524
+ import_node_process.default.stdout.write("\r" + " ".repeat(50) + "\r");
2525
+ if (completedMessage) {
2526
+ import_node_process.default.stdout.write(completedMessage + "\n");
2527
+ }
2528
+ }
2529
+ /**
2530
+ * Stop the spinner with a failure message.
2531
+ */
2532
+ fail(failedMessage) {
2533
+ this.stop();
2534
+ if (failedMessage) {
2535
+ import_node_process.default.stdout.write(`\u2717 ${failedMessage}
2536
+ `);
2537
+ }
2538
+ }
2539
+ };
2540
+
2541
+ // src/compiler/schema/partitioner.ts
2542
+ var DEFAULT_CONFIG = {
2543
+ strategy: "auto",
2544
+ threshold: 50,
2545
+ maxGroupSize: 50,
2546
+ complexityThreshold: 10,
2547
+ verbose: false
2548
+ };
2549
+ function calculateSchemaComplexity(schema) {
2550
+ let propertyCount = 0;
2551
+ let nestedDepth = 0;
2552
+ let refCount = 0;
2553
+ let hasUnion = false;
2554
+ let hasIntersection = false;
2555
+ let hasEnum = false;
2556
+ const jsonSize = JSON.stringify(schema).length;
2557
+ const analyze = (s, depth) => {
2558
+ if (!s || typeof s !== "object") return;
2559
+ nestedDepth = Math.max(nestedDepth, depth);
2560
+ if (s.type === "object" && s.properties) {
2561
+ propertyCount += Object.keys(s.properties).length;
2562
+ for (const prop of Object.values(s.properties)) {
2563
+ analyze(prop, depth + 1);
2564
+ }
2565
+ }
2566
+ if (s.$ref) refCount++;
2567
+ if (s.anyOf || s.oneOf) hasUnion = true;
2568
+ if (s.allOf) hasIntersection = true;
2569
+ if (s.enum) hasEnum = true;
2570
+ if (s.items) {
2571
+ analyze(s.items, depth + 1);
2572
+ }
2573
+ };
2574
+ analyze(schema, 0);
2575
+ const complexity = propertyCount * 1 + nestedDepth * 2 + refCount * 0.5 + (hasUnion ? 5 : 0) + (hasIntersection ? 5 : 0) + (hasEnum ? 1 : 0);
2576
+ return {
2577
+ propertyCount,
2578
+ nestedDepth,
2579
+ refCount,
2580
+ hasUnion,
2581
+ hasIntersection,
2582
+ hasEnum,
2583
+ jsonSize
2584
+ };
2585
+ }
2586
+ function countExternalRefs(schema, allSchemas) {
2587
+ let count = 0;
2588
+ const analyze = (s) => {
2589
+ if (!s || typeof s !== "object") return;
2590
+ if (s.$ref && typeof s.$ref === "string") {
2591
+ const refName = s.$ref.replace("#/components/schemas/", "");
2592
+ if (refName && allSchemas.has(refName)) {
2593
+ count++;
2594
+ }
2595
+ }
2596
+ if (s.properties) {
2597
+ for (const prop of Object.values(s.properties)) {
2598
+ analyze(prop);
2599
+ }
2600
+ }
2601
+ if (s.items) analyze(s.items);
2602
+ if (s.anyOf) s.anyOf.forEach(analyze);
2603
+ if (s.oneOf) s.oneOf.forEach(analyze);
2604
+ if (s.allOf) s.allOf.forEach(analyze);
2605
+ };
2606
+ analyze(schema);
2607
+ return count;
2608
+ }
2609
+ function analyzeDependencyDensity(schemas) {
2610
+ let totalDeps = 0;
2611
+ let maxDeps = 0;
2612
+ for (const schema of schemas.values()) {
2613
+ const deps = countExternalRefs(schema, schemas);
2614
+ totalDeps += deps;
2615
+ maxDeps = Math.max(maxDeps, deps);
2616
+ }
2617
+ return {
2618
+ avgDeps: schemas.size > 0 ? totalDeps / schemas.size : 0,
2619
+ maxDeps
2620
+ };
2621
+ }
2622
+ function partitionByController(schemas, graph, config) {
2623
+ const groups = /* @__PURE__ */ new Map();
2624
+ const sharedSchemas = /* @__PURE__ */ new Map();
2625
+ groups.set("_shared", sharedSchemas);
2626
+ const schemaUsage = /* @__PURE__ */ new Map();
2627
+ for (const [nodeId, node] of graph.nodes.entries()) {
2628
+ if (node.kind === "Operation") {
2629
+ const opNode = node;
2630
+ const returnType = opNode.operation?.returnType;
2631
+ if (returnType && schemas.has(returnType)) {
2632
+ if (!schemaUsage.has(returnType)) {
2633
+ schemaUsage.set(returnType, /* @__PURE__ */ new Set());
2634
+ }
2635
+ schemaUsage.get(returnType).add(node.metadata.name);
2636
+ }
2637
+ }
2638
+ }
2639
+ for (const [schemaName, schema] of schemas.entries()) {
2640
+ const usage = schemaUsage.get(schemaName);
2641
+ if (!usage || usage.size === 0) {
2642
+ sharedSchemas.set(schemaName, schema);
2643
+ } else if (usage.size === 1) {
2644
+ const controllerName = Array.from(usage)[0].split(":")[0] || "default";
2645
+ const groupName = controllerName.toLowerCase();
2646
+ if (!groups.has(groupName)) {
2647
+ groups.set(groupName, /* @__PURE__ */ new Map());
2648
+ }
2649
+ groups.get(groupName).set(schemaName, schema);
2650
+ } else {
2651
+ sharedSchemas.set(schemaName, schema);
2652
+ }
2653
+ }
2654
+ return Array.from(groups.entries()).map(([name, schemaMap]) => {
2655
+ let totalComplexity = 0;
2656
+ const dependencies = [];
2657
+ for (const [schemaName, schema] of schemaMap.entries()) {
2658
+ totalComplexity += calculateSchemaComplexity(schema).propertyCount;
2659
+ const deps = countExternalRefs(schema, schemas);
2660
+ for (let i = 0; i < deps; i++) {
2661
+ dependencies.push(schemaName);
2662
+ }
2663
+ }
2664
+ return {
2665
+ name,
2666
+ schemas: schemaMap,
2667
+ complexity: totalComplexity,
2668
+ dependencies
2669
+ };
2670
+ });
2671
+ }
2672
+ function partitionByDependency(schemas, schemaGraph, config) {
2673
+ const groups = /* @__PURE__ */ new Map();
2674
+ const sccs = schemaGraph.findStronglyConnectedComponents();
2675
+ const processed = /* @__PURE__ */ new Set();
2676
+ for (const scc of sccs) {
2677
+ if (scc.length === 1 && processed.has(scc[0])) continue;
2678
+ const groupSchemas = /* @__PURE__ */ new Map();
2679
+ const groupName = `dependent-${groups.size + 1}`;
2680
+ for (const nodeId of scc) {
2681
+ const node = schemaGraph.getGraph().nodes.get(nodeId);
2682
+ if (node && node.kind === "TypeDefinition") {
2683
+ const schemaName = node.metadata.name;
2684
+ if (schemas.has(schemaName)) {
2685
+ groupSchemas.set(schemaName, schemas.get(schemaName));
2686
+ processed.add(nodeId);
2687
+ }
2688
+ }
2689
+ }
2690
+ if (groupSchemas.size > 0) {
2691
+ groups.set(groupName, groupSchemas);
2692
+ }
2693
+ }
2694
+ for (const [nodeId, node] of schemaGraph.getGraph().nodes.entries()) {
2695
+ if (processed.has(nodeId)) continue;
2696
+ if (node.kind !== "TypeDefinition") continue;
2697
+ const schemaName = node.metadata.name;
2698
+ if (!schemas.has(schemaName)) continue;
2699
+ const groupSchemas = /* @__PURE__ */ new Map();
2700
+ groupSchemas.set(schemaName, schemas.get(schemaName));
2701
+ groups.set(`standalone-${groups.size + 1}`, groupSchemas);
2702
+ processed.add(nodeId);
2703
+ }
2704
+ return Array.from(groups.entries()).map(([name, schemaMap]) => {
2705
+ let totalComplexity = 0;
2706
+ const dependencies = [];
2707
+ for (const [schemaName, schema] of schemaMap.entries()) {
2708
+ totalComplexity += calculateSchemaComplexity(schema).propertyCount;
2709
+ const deps = countExternalRefs(schema, schemas);
2710
+ for (let i = 0; i < deps; i++) {
2711
+ dependencies.push(schemaName);
2712
+ }
2713
+ }
2714
+ return {
2715
+ name,
2716
+ schemas: schemaMap,
2717
+ complexity: totalComplexity,
2718
+ dependencies
2719
+ };
2720
+ });
2721
+ }
2722
+ function partitionBySize(schemas, config) {
2723
+ const sortedSchemas = Array.from(schemas.entries()).sort((a, b) => {
2724
+ const complexityA = calculateSchemaComplexity(a[1]).propertyCount;
2725
+ const complexityB = calculateSchemaComplexity(b[1]).propertyCount;
2726
+ return complexityB - complexityA;
2727
+ });
2728
+ const groups = /* @__PURE__ */ new Map();
2729
+ let currentGroup = /* @__PURE__ */ new Map();
2730
+ let currentCount = 0;
2731
+ let groupIndex = 1;
2732
+ for (const [schemaName, schema] of sortedSchemas) {
2733
+ if (currentCount >= config.maxGroupSize) {
2734
+ groups.set(`group-${groupIndex}`, currentGroup);
2735
+ currentGroup = /* @__PURE__ */ new Map();
2736
+ currentCount = 0;
2737
+ groupIndex++;
2738
+ }
2739
+ currentGroup.set(schemaName, schema);
2740
+ currentCount++;
2741
+ }
2742
+ if (currentCount > 0) {
2743
+ groups.set(`group-${groupIndex}`, currentGroup);
2744
+ }
2745
+ return Array.from(groups.entries()).map(([name, schemaMap]) => {
2746
+ let totalComplexity = 0;
2747
+ const dependencies = [];
2748
+ for (const [schemaName, schema] of schemaMap.entries()) {
2749
+ totalComplexity += calculateSchemaComplexity(schema).propertyCount;
2750
+ const deps = countExternalRefs(schema, schemas);
2751
+ for (let i = 0; i < deps; i++) {
2752
+ dependencies.push(schemaName);
2753
+ }
2754
+ }
2755
+ return {
2756
+ name,
2757
+ schemas: schemaMap,
2758
+ complexity: totalComplexity,
2759
+ dependencies
2760
+ };
2761
+ });
2762
+ }
2763
+ function determineBestStrategy(schemas, graph, schemaGraph, config) {
2764
+ const schemaCount = schemas.size;
2765
+ const { avgDeps } = analyzeDependencyDensity(schemas);
2766
+ let controllerGroups = 0;
2767
+ for (const node of graph.nodes.values()) {
2768
+ if (node.kind === "Controller") {
2769
+ controllerGroups++;
2770
+ }
2771
+ }
2772
+ if (schemaCount < config.threshold) {
2773
+ return "none";
2774
+ }
2775
+ if (avgDeps > 3) {
2776
+ return "dependency";
2777
+ }
2778
+ if (controllerGroups > 1 && avgDeps < 2) {
2779
+ return "controller";
2780
+ }
2781
+ return "size";
2782
+ }
2783
+ function partitionSchemas(schemas, graph, schemaGraph, config = {}) {
2784
+ const finalConfig = { ...DEFAULT_CONFIG, ...config };
2785
+ const schemaCount = schemas.size;
2786
+ let totalComplexity = 0;
2787
+ let totalSchemas = 0;
2788
+ const { avgDeps } = analyzeDependencyDensity(schemas);
2789
+ let controllerGroups = 0;
2790
+ for (const node of graph.nodes.values()) {
2791
+ if (node.kind === "Controller") {
2792
+ controllerGroups++;
2793
+ }
2794
+ }
2795
+ for (const schema of schemas.values()) {
2796
+ totalComplexity += calculateSchemaComplexity(schema).propertyCount;
2797
+ totalSchemas++;
2798
+ }
2799
+ const avgComplexity = totalSchemas > 0 ? totalComplexity / totalSchemas : 0;
2800
+ let strategy = finalConfig.strategy;
2801
+ let recommendation = "";
2802
+ if (strategy === "auto") {
2803
+ strategy = determineBestStrategy(schemas, graph, schemaGraph, finalConfig);
2804
+ if (schemaCount < finalConfig.threshold) {
2805
+ recommendation = `Schema count (${schemaCount}) below threshold (${finalConfig.threshold}), single file optimal`;
2806
+ } else if (strategy === "dependency") {
2807
+ recommendation = `High dependency density (${avgDeps.toFixed(2)} avg refs/schema), using dependency-based partitioning`;
2808
+ } else if (strategy === "controller") {
2809
+ recommendation = `Found ${controllerGroups} controller groups with low coupling, using controller-based partitioning`;
2810
+ } else {
2811
+ recommendation = `Using size-based partitioning with max ${finalConfig.maxGroupSize} schemas per group`;
2812
+ }
2813
+ }
2814
+ let groups = [];
2815
+ if (strategy === "none") {
2816
+ groups = [{
2817
+ name: "all",
2818
+ schemas: new Map(schemas),
2819
+ complexity: totalComplexity,
2820
+ dependencies: []
2821
+ }];
2822
+ recommendation = recommendation || "Single file mode (--no-split)";
2823
+ } else if (strategy === "controller") {
2824
+ groups = partitionByController(schemas, graph, finalConfig);
2825
+ } else if (strategy === "dependency") {
2826
+ groups = partitionByDependency(schemas, schemaGraph, finalConfig);
2827
+ } else {
2828
+ groups = partitionBySize(schemas, finalConfig);
2829
+ }
2830
+ const shouldSplit = strategy !== "none" && schemaCount >= finalConfig.threshold;
2831
+ return {
2832
+ shouldSplit,
2833
+ strategy,
2834
+ groups,
2835
+ recommendation,
2836
+ metrics: {
2837
+ totalSchemas: schemaCount,
2838
+ averageComplexity: avgComplexity,
2839
+ avgDependencyDensity: avgDeps,
2840
+ controllerGroups
2841
+ }
2842
+ };
2843
+ }
2844
+
2845
+ // src/compiler/schema/splitOpenapi.ts
2846
+ var import_node_fs5 = require("fs");
2847
+ var import_node_path5 = require("path");
2848
+ function sanitizeFilename(name) {
2849
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
2850
+ }
2851
+ function getSchemaFilename(group) {
2852
+ const name = sanitizeFilename(group.name);
2853
+ return `schemas/${name}.json`;
2854
+ }
2855
+ function collectAllSchemas(groups) {
2856
+ const result = /* @__PURE__ */ new Map();
2857
+ for (const group of groups) {
2858
+ for (const [schemaName, schema] of group.schemas.entries()) {
2859
+ result.set(schemaName, { schema, group: group.name });
2860
+ }
2861
+ }
2862
+ return result;
2863
+ }
2864
+ function convertToExternalRef(schema, schemaMap) {
2865
+ if (!schema || typeof schema !== "object") return schema;
2866
+ const result = { ...schema };
2867
+ if (schema.$ref && typeof schema.$ref === "string") {
2868
+ const refName = schema.$ref.replace("#/components/schemas/", "");
2869
+ if (refName && schemaMap.has(refName)) {
2870
+ const target = schemaMap.get(refName);
2871
+ const filename = sanitizeFilename(target.group);
2872
+ result.$ref = `schemas/${filename}.json#/components/schemas/${refName}`;
2873
+ }
2874
+ }
2875
+ const nestedProps = ["properties", "items", "additionalProperties"];
2876
+ for (const prop of nestedProps) {
2877
+ if (prop in result) {
2878
+ const value = result[prop];
2879
+ if (Array.isArray(value)) {
2880
+ result[prop] = value.map(
2881
+ (item) => typeof item === "object" ? convertToExternalRef(item, schemaMap) : item
2882
+ );
2883
+ } else if (typeof value === "object" && value !== null) {
2884
+ result[prop] = convertToExternalRef(value, schemaMap);
2885
+ }
2886
+ }
2887
+ }
2888
+ const arrayProps = ["anyOf", "oneOf", "allOf"];
2889
+ for (const prop of arrayProps) {
2890
+ if (prop in result && Array.isArray(result[prop])) {
2891
+ result[prop] = result[prop].map(
2892
+ (item) => typeof item === "object" ? convertToExternalRef(item, schemaMap) : item
2893
+ );
2894
+ }
2895
+ }
2896
+ return result;
2897
+ }
2898
+ function generateSchemaFileContent(group, schemaMap) {
2899
+ const content = {};
2900
+ for (const [schemaName, schema] of group.schemas.entries()) {
2901
+ content[schemaName] = convertToExternalRef(schema, schemaMap);
2902
+ }
2903
+ return content;
2904
+ }
2905
+ function generateSchemaIndex(groups, schemaMap) {
2906
+ const index = {
2907
+ schemas: {}
2908
+ };
2909
+ for (const [schemaName, { group }] of schemaMap.entries()) {
2910
+ const filename = sanitizeFilename(group);
2911
+ index.schemas[schemaName] = {
2912
+ $ref: `schemas/${filename}.json#/components/schemas/${schemaName}`
2913
+ };
2914
+ }
2915
+ return index;
2916
+ }
2917
+ function generateModularOpenAPI(openapi, partitioning, config) {
2918
+ const {
2919
+ outputDir,
2920
+ schemasDir = "schemas",
2921
+ createIndexFile = true,
2922
+ prettyPrint = true
2923
+ } = config;
2924
+ const indent = prettyPrint ? 2 : 0;
2925
+ let totalSize = 0;
2926
+ const schemaFiles = [];
2927
+ if (!partitioning.shouldSplit || partitioning.groups.length === 1) {
2928
+ const mainPath2 = (0, import_node_path5.resolve)(outputDir, "openapi.json");
2929
+ (0, import_node_fs5.writeFileSync)(mainPath2, JSON.stringify(openapi, null, indent));
2930
+ totalSize = Buffer.byteLength(JSON.stringify(openapi));
2931
+ return {
2932
+ mainSpec: mainPath2,
2933
+ schemaFiles: [],
2934
+ totalSize,
2935
+ splitEnabled: false
2936
+ };
2937
+ }
2938
+ const schemasPath = (0, import_node_path5.resolve)(outputDir, schemasDir);
2939
+ (0, import_node_fs5.mkdirSync)(schemasPath, { recursive: true });
2940
+ const schemaMap = collectAllSchemas(partitioning.groups);
2941
+ const schemaToFile = /* @__PURE__ */ new Map();
2942
+ for (const group of partitioning.groups) {
2943
+ const filename = getSchemaFilename(group);
2944
+ const filePath = (0, import_node_path5.resolve)(outputDir, filename);
2945
+ const content = generateSchemaFileContent(group, schemaMap);
2946
+ (0, import_node_fs5.writeFileSync)(filePath, JSON.stringify(content, null, indent));
2947
+ for (const schemaName of group.schemas.keys()) {
2948
+ schemaToFile.set(schemaName, filename);
2949
+ }
2950
+ schemaFiles.push(filePath);
2951
+ totalSize += Buffer.byteLength(JSON.stringify(content));
2952
+ }
2953
+ let indexFile;
2954
+ if (createIndexFile) {
2955
+ const indexPath = (0, import_node_path5.resolve)(outputDir, "schemas/index.json");
2956
+ const indexContent = generateSchemaIndex(partitioning.groups, schemaMap);
2957
+ (0, import_node_fs5.writeFileSync)(indexPath, JSON.stringify(indexContent, null, indent));
2958
+ totalSize += Buffer.byteLength(JSON.stringify(indexContent));
2959
+ indexFile = indexPath;
2960
+ }
2961
+ const mainSpec = generateMainSpec(openapi, schemaMap, schemaToFile);
2962
+ const mainPath = (0, import_node_path5.resolve)(outputDir, "openapi.json");
2963
+ (0, import_node_fs5.writeFileSync)(mainPath, JSON.stringify(mainSpec, null, indent));
2964
+ totalSize += Buffer.byteLength(JSON.stringify(mainSpec));
2965
+ return {
2966
+ mainSpec: mainPath,
2967
+ schemaFiles,
2968
+ indexFile,
2969
+ totalSize,
2970
+ splitEnabled: true
2971
+ };
2972
+ }
2973
+ function generateMainSpec(original, schemaMap, schemaToFile) {
2974
+ const schemas = {};
2975
+ for (const [schemaName, { group }] of schemaMap.entries()) {
2976
+ const filename = sanitizeFilename(group);
2977
+ schemas[schemaName] = {
2978
+ $ref: `schemas/${filename}.json#/components/schemas/${schemaName}`
2979
+ };
2980
+ }
2981
+ return {
2982
+ ...original,
2983
+ components: {
2984
+ ...original.components,
2985
+ schemas
2986
+ },
2987
+ "x-original-schemas": Object.keys(schemaMap).length,
2988
+ "x-split-enabled": true,
2989
+ "x-schema-files": Array.from(new Set(schemaToFile.values()))
2990
+ };
2991
+ }
2992
+
2993
+ // src/compiler/graph/types.ts
2994
+ function createGraph(tsVersion) {
2995
+ return {
2996
+ nodes: /* @__PURE__ */ new Map(),
2997
+ roots: /* @__PURE__ */ new Set(),
2998
+ version: "1.0.0",
2999
+ metadata: {
3000
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
3001
+ generatedBy: "adorn-api-gems",
3002
+ tsVersion
3003
+ }
3004
+ };
3005
+ }
3006
+ function addNode(graph, node) {
3007
+ graph.nodes.set(node.id, node);
3008
+ }
3009
+ function addEdge(graph, sourceId, targetId, relation, properties) {
3010
+ const sourceNode = graph.nodes.get(sourceId);
3011
+ if (!sourceNode) {
3012
+ throw new Error(`Source node ${sourceId} not found`);
3013
+ }
3014
+ const targetExists = graph.nodes.has(targetId);
3015
+ if (!targetExists) {
3016
+ throw new Error(`Target node ${targetId} not found`);
3017
+ }
3018
+ sourceNode.edges.push({
3019
+ targetId,
3020
+ relation,
3021
+ properties
3022
+ });
3023
+ }
3024
+ function getEdgesByRelation(graph, relation) {
3025
+ const edges = [];
3026
+ for (const [id, node] of graph.nodes.entries()) {
3027
+ for (const edge of node.edges) {
3028
+ if (edge.relation === relation) {
3029
+ edges.push({ sourceId: id, edge });
3030
+ }
3031
+ }
3032
+ }
3033
+ return edges;
3034
+ }
3035
+
3036
+ // src/compiler/graph/builder.ts
3037
+ var import_typescript12 = __toESM(require("typescript"), 1);
3038
+
3039
+ // src/compiler/graph/schemaGraph.ts
3040
+ var SchemaGraph = class {
3041
+ graph;
3042
+ adjacency = /* @__PURE__ */ new Map();
3043
+ reverseAdjacency = /* @__PURE__ */ new Map();
3044
+ constructor(graph) {
3045
+ this.graph = graph;
3046
+ this.buildAdjacencyLists();
3047
+ }
3048
+ /**
3049
+ * Build adjacency lists for faster traversal
3050
+ */
3051
+ buildAdjacencyLists() {
3052
+ for (const [id, node] of this.graph.nodes.entries()) {
3053
+ this.adjacency.set(id, /* @__PURE__ */ new Set());
3054
+ this.reverseAdjacency.set(id, /* @__PURE__ */ new Set());
3055
+ }
3056
+ for (const [sourceId, node] of this.graph.nodes.entries()) {
3057
+ for (const edge of node.edges) {
3058
+ this.adjacency.get(sourceId)?.add(edge.targetId);
3059
+ this.reverseAdjacency.get(edge.targetId)?.add(sourceId);
3060
+ }
3061
+ }
3062
+ }
3063
+ /**
3064
+ * Find all nodes that use a given type
3065
+ */
3066
+ findTypeUsages(typeId) {
3067
+ const usages = [];
3068
+ const usesEdges = getEdgesByRelation(this.graph, "uses");
3069
+ for (const { sourceId, edge } of usesEdges) {
3070
+ if (edge.targetId === typeId) {
3071
+ usages.push(sourceId);
3072
+ }
3073
+ }
3074
+ return usages;
3075
+ }
3076
+ /**
3077
+ * Detect cycles in the dependency graph
3078
+ */
3079
+ detectCycles() {
3080
+ const visited = /* @__PURE__ */ new Set();
3081
+ const recursionStack = /* @__PURE__ */ new Set();
3082
+ const cycles = [];
3083
+ for (const nodeId of this.graph.nodes.keys()) {
3084
+ if (!visited.has(nodeId)) {
3085
+ this.detectCyclesDFS(nodeId, visited, recursionStack, [], cycles);
3086
+ }
3087
+ }
3088
+ return {
3089
+ hasCycles: cycles.length > 0,
3090
+ cycles,
3091
+ cycleCount: cycles.length
3092
+ };
3093
+ }
3094
+ /**
3095
+ * Depth-first search for cycle detection
3096
+ */
3097
+ detectCyclesDFS(nodeId, visited, recursionStack, path4, cycles) {
3098
+ visited.add(nodeId);
3099
+ recursionStack.add(nodeId);
3100
+ path4.push(nodeId);
3101
+ const neighbors = this.adjacency.get(nodeId) || /* @__PURE__ */ new Set();
3102
+ for (const neighbor of neighbors) {
3103
+ if (!visited.has(neighbor)) {
3104
+ this.detectCyclesDFS(neighbor, visited, recursionStack, path4, cycles);
3105
+ } else if (recursionStack.has(neighbor)) {
3106
+ const cycleStart = path4.indexOf(neighbor);
3107
+ cycles.push([...path4.slice(cycleStart), neighbor]);
3108
+ }
3109
+ }
3110
+ recursionStack.delete(nodeId);
3111
+ path4.pop();
3112
+ }
3113
+ /**
3114
+ * Find strongly connected components using Tarjan's algorithm
3115
+ */
3116
+ findStronglyConnectedComponents() {
3117
+ let index = 0;
3118
+ const stack = [];
3119
+ const indices = /* @__PURE__ */ new Map();
3120
+ const lowlinks = /* @__PURE__ */ new Map();
3121
+ const onStack = /* @__PURE__ */ new Set();
3122
+ const sccs = [];
3123
+ const strongConnect = (v) => {
3124
+ indices.set(v, index);
3125
+ lowlinks.set(v, index);
3126
+ index++;
3127
+ stack.push(v);
3128
+ onStack.add(v);
3129
+ const neighbors = this.adjacency.get(v) || /* @__PURE__ */ new Set();
3130
+ for (const w of neighbors) {
3131
+ if (!indices.has(w)) {
3132
+ strongConnect(w);
3133
+ lowlinks.set(v, Math.min(lowlinks.get(v), lowlinks.get(w)));
3134
+ } else if (onStack.has(w)) {
3135
+ lowlinks.set(v, Math.min(lowlinks.get(v), indices.get(w)));
3136
+ }
3137
+ }
3138
+ if (lowlinks.get(v) === indices.get(v)) {
3139
+ const scc = [];
3140
+ let w;
3141
+ do {
3142
+ w = stack.pop();
3143
+ onStack.delete(w);
3144
+ scc.push(w);
3145
+ } while (w !== v);
3146
+ sccs.push(scc);
3147
+ }
3148
+ };
3149
+ for (const nodeId of this.graph.nodes.keys()) {
3150
+ if (!indices.has(nodeId)) {
3151
+ strongConnect(nodeId);
3152
+ }
3153
+ }
3154
+ return sccs;
3155
+ }
3156
+ /**
3157
+ * Topological sort of the graph
3158
+ */
3159
+ topologicalSort() {
3160
+ const inDegree = /* @__PURE__ */ new Map();
3161
+ for (const nodeId of this.graph.nodes.keys()) {
3162
+ inDegree.set(nodeId, 0);
3163
+ }
3164
+ for (const [sourceId, node] of this.graph.nodes.entries()) {
3165
+ for (const edge of node.edges) {
3166
+ inDegree.set(
3167
+ edge.targetId,
3168
+ (inDegree.get(edge.targetId) || 0) + 1
3169
+ );
3170
+ }
3171
+ }
3172
+ const queue = [];
3173
+ for (const [nodeId, degree] of inDegree.entries()) {
3174
+ if (degree === 0) {
3175
+ queue.push(nodeId);
3176
+ }
3177
+ }
3178
+ const sorted = [];
3179
+ while (queue.length > 0) {
3180
+ const current = queue.shift();
3181
+ sorted.push(current);
3182
+ const neighbors = this.adjacency.get(current) || /* @__PURE__ */ new Set();
3183
+ for (const neighbor of neighbors) {
3184
+ inDegree.set(neighbor, inDegree.get(neighbor) - 1);
3185
+ if (inDegree.get(neighbor) === 0) {
3186
+ queue.push(neighbor);
3187
+ }
3188
+ }
3189
+ }
3190
+ return sorted;
3191
+ }
3192
+ /**
3193
+ * Find nodes reachable from a given start node
3194
+ */
3195
+ findReachable(startNodeId) {
3196
+ const reachable = /* @__PURE__ */ new Set();
3197
+ const visited = /* @__PURE__ */ new Set();
3198
+ const queue = [startNodeId];
3199
+ while (queue.length > 0) {
3200
+ const current = queue.shift();
3201
+ if (visited.has(current)) continue;
3202
+ visited.add(current);
3203
+ reachable.add(current);
3204
+ const neighbors = this.adjacency.get(current) || /* @__PURE__ */ new Set();
3205
+ for (const neighbor of neighbors) {
3206
+ if (!visited.has(neighbor)) {
3207
+ queue.push(neighbor);
3208
+ }
3209
+ }
3210
+ }
3211
+ return reachable;
3212
+ }
3213
+ /**
3214
+ * Find shortest path between two nodes (BFS)
3215
+ */
3216
+ findShortestPath(fromId, toId) {
3217
+ const visited = /* @__PURE__ */ new Set();
3218
+ const previous = /* @__PURE__ */ new Map();
3219
+ const queue = [fromId];
3220
+ visited.add(fromId);
3221
+ while (queue.length > 0) {
3222
+ const current = queue.shift();
3223
+ if (current === toId) {
3224
+ return this.reconstructPath(previous, toId);
3225
+ }
3226
+ const neighbors = this.adjacency.get(current) || /* @__PURE__ */ new Set();
3227
+ for (const neighbor of neighbors) {
3228
+ if (!visited.has(neighbor)) {
3229
+ visited.add(neighbor);
3230
+ previous.set(neighbor, current);
3231
+ queue.push(neighbor);
3232
+ }
3233
+ }
3234
+ }
3235
+ return null;
3236
+ }
3237
+ /**
3238
+ * Reconstruct path from previous map
3239
+ */
3240
+ reconstructPath(previous, toId) {
3241
+ const path4 = [toId];
3242
+ let current = toId;
3243
+ while (current !== void 0) {
3244
+ current = previous.get(current);
3245
+ if (current !== void 0) {
3246
+ path4.unshift(current);
3247
+ }
3248
+ }
3249
+ return path4;
3250
+ }
3251
+ /**
3252
+ * Get nodes grouped by their depth from roots
3253
+ */
3254
+ getDepthGroups() {
3255
+ const depths = /* @__PURE__ */ new Map();
3256
+ const groups = /* @__PURE__ */ new Map();
3257
+ for (const rootId of this.graph.roots) {
3258
+ const queue = [rootId];
3259
+ depths.set(rootId, 0);
3260
+ while (queue.length > 0) {
3261
+ const current = queue.shift();
3262
+ const currentDepth = depths.get(current);
3263
+ for (const neighbor of this.adjacency.get(current) || /* @__PURE__ */ new Set()) {
3264
+ const newDepth = currentDepth + 1;
3265
+ if (!depths.has(neighbor) || depths.get(neighbor) > newDepth) {
3266
+ depths.set(neighbor, newDepth);
3267
+ queue.push(neighbor);
3268
+ }
3269
+ }
3270
+ }
3271
+ }
3272
+ for (const [nodeId, depth] of depths.entries()) {
3273
+ if (!groups.has(depth)) {
3274
+ groups.set(depth, []);
3275
+ }
3276
+ groups.get(depth).push(nodeId);
3277
+ }
3278
+ return groups;
3279
+ }
3280
+ /**
3281
+ * Get the underlying graph
3282
+ */
3283
+ getGraph() {
3284
+ return this.graph;
3285
+ }
3286
+ };
3287
+
3288
+ // src/cli.ts
3289
+ var import_typescript13 = __toESM(require("typescript"), 1);
3290
+ var import_node_process2 = __toESM(require("process"), 1);
2357
3291
  var ADORN_VERSION = "0.1.0";
2358
- function log(msg) {
2359
- import_node_process.default.stdout.write(msg + "\n");
3292
+ function log(msg, options) {
3293
+ if (options?.indent) {
3294
+ import_node_process2.default.stdout.write(" " + msg + "\n");
3295
+ } else {
3296
+ import_node_process2.default.stdout.write(msg + "\n");
3297
+ }
2360
3298
  }
2361
- function debug(...args) {
2362
- if (import_node_process.default.env.ADORN_DEBUG) {
2363
- console.error("[adorn-api]", ...args);
3299
+ function formatBytes(bytes) {
3300
+ if (bytes < 1024) return `${bytes} B`;
3301
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
3302
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
3303
+ }
3304
+ function getFileSize(path4) {
3305
+ try {
3306
+ return (0, import_node_fs6.statSync)(path4).size;
3307
+ } catch {
3308
+ return void 0;
2364
3309
  }
2365
3310
  }
2366
3311
  function sanitizeForJson(obj) {
@@ -2383,49 +3328,241 @@ function sanitizeForJson(obj) {
2383
3328
  }
2384
3329
  return result;
2385
3330
  }
3331
+ function buildControllerGraph(controllers) {
3332
+ const graph = createGraph(import_typescript13.default.version);
3333
+ const nodeMap = /* @__PURE__ */ new Map();
3334
+ for (const ctrl of controllers) {
3335
+ const nodeId = `Controller:${ctrl.className}`;
3336
+ const node = {
3337
+ id: nodeId,
3338
+ kind: "Controller",
3339
+ metadata: {
3340
+ name: ctrl.className,
3341
+ sourceLocation: { filePath: "", line: 0, column: 0 },
3342
+ tags: /* @__PURE__ */ new Set(),
3343
+ annotations: /* @__PURE__ */ new Map()
3344
+ },
3345
+ edges: [],
3346
+ controller: {
3347
+ basePath: ctrl.basePath
3348
+ }
3349
+ };
3350
+ addNode(graph, node);
3351
+ nodeMap.set(nodeId, node);
3352
+ }
3353
+ let opIndex = 0;
3354
+ for (const ctrl of controllers) {
3355
+ for (const op of ctrl.operations) {
3356
+ const nodeId = `Operation:${op.operationId}`;
3357
+ const node = {
3358
+ id: nodeId,
3359
+ kind: "Operation",
3360
+ metadata: {
3361
+ name: op.operationId,
3362
+ sourceLocation: { filePath: "", line: 0, column: 0 },
3363
+ tags: /* @__PURE__ */ new Set(),
3364
+ annotations: /* @__PURE__ */ new Map()
3365
+ },
3366
+ edges: [],
3367
+ operation: {
3368
+ httpMethod: op.httpMethod,
3369
+ path: op.path,
3370
+ operationId: op.operationId,
3371
+ returnType: op.returnType || ""
3372
+ }
3373
+ };
3374
+ addNode(graph, node);
3375
+ nodeMap.set(nodeId, node);
3376
+ const ctrlNode = nodeMap.get(`Controller:${ctrl.className}`);
3377
+ if (ctrlNode) {
3378
+ addEdge(graph, ctrlNode.id, node.id, "contains");
3379
+ }
3380
+ opIndex++;
3381
+ }
3382
+ }
3383
+ for (const ctrl of controllers) {
3384
+ for (const op of ctrl.operations) {
3385
+ if (op.returnType && !nodeMap.has(op.returnType)) {
3386
+ const node = {
3387
+ id: op.returnType,
3388
+ kind: "TypeDefinition",
3389
+ metadata: {
3390
+ name: op.returnType,
3391
+ sourceLocation: { filePath: "", line: 0, column: 0 },
3392
+ tags: /* @__PURE__ */ new Set(),
3393
+ annotations: /* @__PURE__ */ new Map()
3394
+ },
3395
+ edges: [],
3396
+ typeDef: {
3397
+ isGeneric: false,
3398
+ properties: /* @__PURE__ */ new Map()
3399
+ }
3400
+ };
3401
+ addNode(graph, node);
3402
+ nodeMap.set(op.returnType, node);
3403
+ const opNodeId = `Operation:${op.operationId}`;
3404
+ const opNode = nodeMap.get(opNodeId);
3405
+ if (opNode) {
3406
+ addEdge(graph, opNode.id, node.id, "uses");
3407
+ }
3408
+ }
3409
+ }
3410
+ }
3411
+ return graph;
3412
+ }
2386
3413
  async function buildCommand(args) {
3414
+ const progress = new ProgressTracker({ verbose: args.includes("--verbose"), quiet: args.includes("--quiet") });
2387
3415
  const projectIndex = args.indexOf("-p");
2388
3416
  const projectPath = projectIndex !== -1 ? args[projectIndex + 1] : "./tsconfig.json";
2389
3417
  const outputDir = args.includes("--output") ? args[args.indexOf("--output") + 1] : ".adorn";
2390
3418
  const ifStale = args.includes("--if-stale");
2391
3419
  const validationModeIndex = args.indexOf("--validation-mode");
2392
3420
  const validationMode = validationModeIndex !== -1 ? args[validationModeIndex + 1] : "ajv-runtime";
3421
+ const verbose = args.includes("--verbose");
3422
+ const quiet = args.includes("--quiet");
3423
+ const noSplit = args.includes("--no-split");
3424
+ const splitStrategyIndex = args.indexOf("--split-strategy");
3425
+ const splitStrategy = splitStrategyIndex !== -1 ? args[splitStrategyIndex + 1] : void 0;
3426
+ const splitThresholdIndex = args.indexOf("--split-threshold");
3427
+ const splitThreshold = splitThresholdIndex !== -1 ? parseInt(args[splitThresholdIndex + 1], 10) : 50;
2393
3428
  if (validationMode !== "none" && validationMode !== "ajv-runtime" && validationMode !== "precompiled") {
2394
3429
  console.error(`Invalid validation mode: ${validationMode}. Valid values: none, ajv-runtime, precompiled`);
2395
- import_node_process.default.exit(1);
3430
+ import_node_process2.default.exit(1);
3431
+ }
3432
+ const outputPath = (0, import_node_path6.resolve)(outputDir);
3433
+ if (!quiet) {
3434
+ log(`adorn-api v${ADORN_VERSION} - Building API artifacts`);
3435
+ log("");
2396
3436
  }
2397
- const outputPath = (0, import_node_path5.resolve)(outputDir);
2398
3437
  if (ifStale) {
3438
+ progress.startPhase("staleness-check", "Checking for stale artifacts");
2399
3439
  const stale = await isStale({
2400
3440
  outDir: outputDir,
2401
3441
  project: projectPath,
2402
3442
  adornVersion: ADORN_VERSION,
2403
- typescriptVersion: import_typescript12.default.version
3443
+ typescriptVersion: import_typescript13.default.version
2404
3444
  });
2405
3445
  if (!stale.stale) {
2406
- log("adorn-api: artifacts up-to-date");
3446
+ progress.completePhase("staleness-check");
3447
+ if (!quiet) {
3448
+ log("adorn-api: artifacts up-to-date");
3449
+ }
2407
3450
  return;
2408
3451
  }
2409
- log(`adorn-api: building artifacts (reason: ${stale.reason}${stale.detail ? `: ${stale.detail}` : ""})`);
2410
- debug("Stale detail:", stale.detail);
3452
+ progress.completePhase("staleness-check", `Artifacts stale (${stale.reason})`);
3453
+ if (verbose) {
3454
+ progress.verboseLog(`Stale reason: ${stale.detail || stale.reason}`);
3455
+ }
2411
3456
  } else {
2412
- log("adorn-api: building artifacts (reason: forced-build)");
3457
+ progress.startPhase("configuration", "Initializing build");
3458
+ progress.completePhase("configuration", "Build forced (--if-stale not used)");
3459
+ }
3460
+ progress.startPhase("program", "Loading TypeScript configuration");
3461
+ if (verbose) {
3462
+ progress.verboseLog(`Loading ${projectPath}`);
2413
3463
  }
2414
3464
  const { program, checker, sourceFiles } = createProgramFromConfig(projectPath);
3465
+ const projectSourceFiles = sourceFiles.filter((sf) => !sf.fileName.includes("node_modules"));
3466
+ progress.completePhase("program");
3467
+ if (verbose) {
3468
+ progress.verboseLog(`Found ${projectSourceFiles.length} source files`);
3469
+ }
3470
+ progress.startPhase("scan", "Scanning for controllers");
2415
3471
  const controllers = scanControllers(sourceFiles, checker);
2416
3472
  if (controllers.length === 0) {
2417
3473
  console.warn("No controllers found!");
2418
- import_node_process.default.exit(1);
3474
+ import_node_process2.default.exit(1);
3475
+ }
3476
+ const totalOperations = controllers.reduce((sum, ctrl) => sum + ctrl.operations.length, 0);
3477
+ progress.completePhase("scan", `Found ${controllers.length} controller(s) with ${totalOperations} operation(s)`);
3478
+ if (verbose) {
3479
+ for (const ctrl of controllers) {
3480
+ progress.verboseLog(`Controller: ${ctrl.className} (${ctrl.basePath}) - ${ctrl.operations.length} operations`);
3481
+ }
3482
+ }
3483
+ progress.startPhase("openapi", "Generating OpenAPI schema");
3484
+ if (verbose) {
3485
+ progress.verboseLog("Processing schemas from type definitions");
2419
3486
  }
2420
- log(`Found ${controllers.length} controller(s)`);
2421
3487
  const openapi = generateOpenAPI(controllers, checker, { title: "API", version: "1.0.0" });
3488
+ const schemaCount = Object.keys(openapi.components?.schemas || {}).length;
3489
+ let splitEnabled = false;
3490
+ if (!noSplit && schemaCount >= splitThreshold) {
3491
+ progress.verboseLog(`Schema count (${schemaCount}) >= threshold (${splitThreshold}), analyzing for auto-split...`);
3492
+ const graph = buildControllerGraph(controllers);
3493
+ const schemaGraph = new SchemaGraph(graph);
3494
+ const schemasMap = new Map(Object.entries(openapi.components?.schemas || {}));
3495
+ const strategy = splitStrategy || "auto";
3496
+ const partitioning = partitionSchemas(schemasMap, graph, schemaGraph, {
3497
+ strategy,
3498
+ threshold: splitThreshold,
3499
+ verbose
3500
+ });
3501
+ splitEnabled = partitioning.shouldSplit;
3502
+ if (splitEnabled) {
3503
+ progress.verboseLog(`Partitioning result: ${partitioning.strategy} strategy`);
3504
+ progress.verboseLog(`Recommendation: ${partitioning.recommendation}`);
3505
+ generateModularOpenAPI(openapi, partitioning, {
3506
+ outputDir: outputPath,
3507
+ schemasDir: "schemas",
3508
+ createIndexFile: true,
3509
+ prettyPrint: true
3510
+ });
3511
+ if (!quiet) {
3512
+ log(` Auto-split enabled: ${partitioning.strategy} strategy`);
3513
+ log(` Schema groups: ${partitioning.groups.length}`);
3514
+ }
3515
+ } else {
3516
+ if (!quiet) {
3517
+ log(` Auto-split not needed: ${partitioning.recommendation}`);
3518
+ }
3519
+ }
3520
+ } else if (noSplit) {
3521
+ if (!quiet) {
3522
+ log(` Splitting disabled (--no-split)`);
3523
+ }
3524
+ } else {
3525
+ if (!quiet) {
3526
+ log(` Schema count (${schemaCount}) below threshold (${splitThreshold}), single file mode`);
3527
+ }
3528
+ }
3529
+ progress.completePhase("openapi", `Generated ${schemaCount} schema(s)${splitEnabled ? " (split into groups)" : ""}`);
3530
+ progress.startPhase("manifest", "Generating manifest");
2422
3531
  const manifest = generateManifest(controllers, checker, ADORN_VERSION, validationMode);
2423
- (0, import_node_fs5.mkdirSync)(outputPath, { recursive: true });
2424
- (0, import_node_fs5.writeFileSync)((0, import_node_path5.resolve)(outputPath, "openapi.json"), JSON.stringify(sanitizeForJson(openapi), null, 2));
2425
- (0, import_node_fs5.writeFileSync)((0, import_node_path5.resolve)(outputPath, "manifest.json"), JSON.stringify(manifest, null, 2));
3532
+ progress.completePhase("manifest");
3533
+ progress.startPhase("write", "Writing artifacts");
3534
+ (0, import_node_fs6.mkdirSync)(outputPath, { recursive: true });
3535
+ const openapiPath = (0, import_node_path6.resolve)(outputPath, "openapi.json");
3536
+ const manifestPath = (0, import_node_path6.resolve)(outputPath, "manifest.json");
3537
+ if (!splitEnabled) {
3538
+ (0, import_node_fs6.writeFileSync)(openapiPath, JSON.stringify(sanitizeForJson(openapi), null, 2));
3539
+ }
3540
+ (0, import_node_fs6.writeFileSync)(manifestPath, JSON.stringify(manifest, null, 2));
3541
+ const artifacts = [
3542
+ { name: "openapi.json", size: getFileSize(openapiPath) },
3543
+ { name: "manifest.json", size: getFileSize(manifestPath) }
3544
+ ];
3545
+ if (splitEnabled) {
3546
+ const schemasDir = (0, import_node_path6.resolve)(outputPath, "schemas");
3547
+ if ((0, import_node_fs6.existsSync)(schemasDir)) {
3548
+ const fs4 = await import("fs");
3549
+ const files = fs4.readdirSync(schemasDir);
3550
+ for (const file of files) {
3551
+ const filePath = (0, import_node_path6.resolve)(schemasDir, file);
3552
+ artifacts.push({ name: `schemas/${file}`, size: getFileSize(filePath) });
3553
+ }
3554
+ }
3555
+ }
3556
+ if (verbose) {
3557
+ for (const artifact of artifacts) {
3558
+ progress.verboseLog(`Written: ${artifact.name} (${formatBytes(artifact.size || 0)})`);
3559
+ }
3560
+ }
2426
3561
  if (validationMode === "precompiled") {
2427
- log("Generating precompiled validators...");
2428
- const manifestObj = JSON.parse((0, import_node_fs5.readFileSync)((0, import_node_path5.resolve)(outputPath, "manifest.json"), "utf-8"));
3562
+ progress.startPhase("validators", "Generating precompiled validators");
3563
+ const manifestObj = JSON.parse((0, import_node_fs6.readFileSync)(manifestPath, "utf-8"));
3564
+ const spinner = new Spinner("Generating validators...");
3565
+ if (!quiet) spinner.start();
2429
3566
  await emitPrecompiledValidators({
2430
3567
  outDir: outputPath,
2431
3568
  openapi,
@@ -2433,45 +3570,71 @@ async function buildCommand(args) {
2433
3570
  strict: "off",
2434
3571
  formatsMode: "full"
2435
3572
  });
3573
+ if (!quiet) spinner.stop();
2436
3574
  manifestObj.validation = {
2437
3575
  mode: "precompiled",
2438
3576
  precompiledModule: "./validators.mjs"
2439
3577
  };
2440
- (0, import_node_fs5.writeFileSync)((0, import_node_path5.resolve)(outputPath, "manifest.json"), JSON.stringify(manifestObj, null, 2));
2441
- log(" - validators.cjs");
2442
- log(" - validators.mjs");
2443
- log(" - validators.meta.json");
3578
+ (0, import_node_fs6.writeFileSync)(manifestPath, JSON.stringify(manifestObj, null, 2));
3579
+ const validatorsCjsPath = (0, import_node_path6.resolve)(outputPath, "validators.cjs");
3580
+ const validatorsMjsPath = (0, import_node_path6.resolve)(outputPath, "validators.mjs");
3581
+ const validatorsMetaPath = (0, import_node_path6.resolve)(outputPath, "validators.meta.json");
3582
+ artifacts.push(
3583
+ { name: "validators.cjs", size: getFileSize(validatorsCjsPath) },
3584
+ { name: "validators.mjs", size: getFileSize(validatorsMjsPath) },
3585
+ { name: "validators.meta.json", size: getFileSize(validatorsMetaPath) }
3586
+ );
3587
+ progress.completePhase("validators");
3588
+ if (verbose) {
3589
+ progress.verboseLog("Precompiled validators generated successfully");
3590
+ }
2444
3591
  }
3592
+ progress.startPhase("cache", "Writing cache");
2445
3593
  writeCache({
2446
3594
  outDir: outputDir,
2447
- tsconfigAbs: (0, import_node_path5.resolve)(projectPath),
3595
+ tsconfigAbs: (0, import_node_path6.resolve)(projectPath),
2448
3596
  program,
2449
3597
  adornVersion: ADORN_VERSION
2450
3598
  });
2451
- log(`Written to ${outputPath}/`);
2452
- log(" - openapi.json");
2453
- log(" - manifest.json");
2454
- log(" - cache.json");
3599
+ const cachePath = (0, import_node_path6.resolve)(outputPath, "cache.json");
3600
+ artifacts.push({ name: "cache.json", size: getFileSize(cachePath) });
3601
+ progress.completePhase("cache");
3602
+ if (verbose) {
3603
+ progress.verboseLog(`Written: cache.json (${formatBytes(getFileSize(cachePath) || 0)})`);
3604
+ }
3605
+ const stats = {
3606
+ controllers: controllers.length,
3607
+ operations: totalOperations,
3608
+ schemas: schemaCount,
3609
+ sourceFiles: projectSourceFiles.length,
3610
+ artifactsWritten: artifacts.map((a) => a.name),
3611
+ splitEnabled
3612
+ };
3613
+ progress.printSummary(stats);
3614
+ progress.printArtifacts(artifacts);
2455
3615
  }
2456
3616
  function cleanCommand(args) {
3617
+ const quiet = args.includes("--quiet");
2457
3618
  const outputDir = args.includes("--output") ? args[args.indexOf("--output") + 1] : ".adorn";
2458
- const outputPath = (0, import_node_path5.resolve)(outputDir);
2459
- if ((0, import_node_fs5.existsSync)(outputPath)) {
2460
- (0, import_node_fs5.rmSync)(outputPath, { recursive: true, force: true });
3619
+ const outputPath = (0, import_node_path6.resolve)(outputDir);
3620
+ if ((0, import_node_fs6.existsSync)(outputPath)) {
3621
+ (0, import_node_fs6.rmSync)(outputPath, { recursive: true, force: true });
3622
+ }
3623
+ if (!quiet) {
3624
+ log(`adorn-api: cleaned ${outputDir}`);
2461
3625
  }
2462
- log(`adorn-api: cleaned ${outputDir}`);
2463
3626
  }
2464
- var command = import_node_process.default.argv[2];
3627
+ var command = import_node_process2.default.argv[2];
2465
3628
  if (command === "build") {
2466
- buildCommand(import_node_process.default.argv.slice(3)).catch((err) => {
3629
+ buildCommand(import_node_process2.default.argv.slice(3)).catch((err) => {
2467
3630
  console.error(err);
2468
- import_node_process.default.exit(1);
3631
+ import_node_process2.default.exit(1);
2469
3632
  });
2470
3633
  } else if (command === "clean") {
2471
- cleanCommand(import_node_process.default.argv.slice(3));
3634
+ cleanCommand(import_node_process2.default.argv.slice(3));
2472
3635
  } else {
2473
3636
  console.log(`
2474
- adorn-api CLI
3637
+ adorn-api CLI v${ADORN_VERSION}
2475
3638
 
2476
3639
  Commands:
2477
3640
  build Generate OpenAPI and manifest from TypeScript source
@@ -2482,11 +3645,20 @@ Options:
2482
3645
  --output <dir> Output directory (default: .adorn)
2483
3646
  --if-stale Only rebuild if artifacts are stale
2484
3647
  --validation-mode <mode> Validation mode: none, ajv-runtime, precompiled (default: ajv-runtime)
3648
+ --no-split Disable automatic schema splitting (default: auto-split enabled)
3649
+ --split-strategy <mode> Override splitting strategy: controller, dependency, size, auto (default: auto)
3650
+ --split-threshold <num> Schema count threshold for auto-split (default: 50)
3651
+ --verbose Show detailed progress information
3652
+ --quiet Suppress non-essential output
2485
3653
 
2486
3654
  Examples:
2487
3655
  adorn-api build -p ./tsconfig.json --output .adorn
2488
3656
  adorn-api build --if-stale
2489
3657
  adorn-api build --validation-mode precompiled
3658
+ adorn-api build --verbose
3659
+ adorn-api build --no-split # Force single file mode
3660
+ adorn-api build --split-strategy controller # Force controller-based splitting
3661
+ adorn-api build --split-threshold 100 # Increase threshold to 100
2490
3662
  adorn-api clean
2491
3663
  `);
2492
3664
  }