@kubb/core 5.0.0-beta.15 → 5.0.0-beta.17

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/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_PluginDriver = require("./PluginDriver-C1OsqGBJ.cjs");
2
+ const require_PluginDriver = require("./PluginDriver-C5hyNJfM.cjs");
3
3
  let node_events = require("node:events");
4
4
  let node_fs_promises = require("node:fs/promises");
5
5
  let node_path = require("node:path");
@@ -525,7 +525,7 @@ function createAdapter(build) {
525
525
  }
526
526
  //#endregion
527
527
  //#region package.json
528
- var version = "5.0.0-beta.15";
528
+ var version = "5.0.0-beta.17";
529
529
  //#endregion
530
530
  //#region src/createStorage.ts
531
531
  /**
@@ -564,133 +564,6 @@ function createStorage(build) {
564
564
  return (options) => build(options ?? {});
565
565
  }
566
566
  //#endregion
567
- //#region ../../node_modules/.pnpm/yocto-queue@1.2.2/node_modules/yocto-queue/index.js
568
- var Node = class {
569
- value;
570
- next;
571
- constructor(value) {
572
- this.value = value;
573
- }
574
- };
575
- var Queue = class {
576
- #head;
577
- #tail;
578
- #size;
579
- constructor() {
580
- this.clear();
581
- }
582
- enqueue(value) {
583
- const node = new Node(value);
584
- if (this.#head) {
585
- this.#tail.next = node;
586
- this.#tail = node;
587
- } else {
588
- this.#head = node;
589
- this.#tail = node;
590
- }
591
- this.#size++;
592
- }
593
- dequeue() {
594
- const current = this.#head;
595
- if (!current) return;
596
- this.#head = this.#head.next;
597
- this.#size--;
598
- if (!this.#head) this.#tail = void 0;
599
- return current.value;
600
- }
601
- peek() {
602
- if (!this.#head) return;
603
- return this.#head.value;
604
- }
605
- clear() {
606
- this.#head = void 0;
607
- this.#tail = void 0;
608
- this.#size = 0;
609
- }
610
- get size() {
611
- return this.#size;
612
- }
613
- *[Symbol.iterator]() {
614
- let current = this.#head;
615
- while (current) {
616
- yield current.value;
617
- current = current.next;
618
- }
619
- }
620
- *drain() {
621
- while (this.#head) yield this.dequeue();
622
- }
623
- };
624
- //#endregion
625
- //#region ../../node_modules/.pnpm/p-limit@7.3.0/node_modules/p-limit/index.js
626
- function pLimit(concurrency) {
627
- let rejectOnClear = false;
628
- if (typeof concurrency === "object") ({concurrency, rejectOnClear = false} = concurrency);
629
- validateConcurrency(concurrency);
630
- if (typeof rejectOnClear !== "boolean") throw new TypeError("Expected `rejectOnClear` to be a boolean");
631
- const queue = new Queue();
632
- let activeCount = 0;
633
- const resumeNext = () => {
634
- if (activeCount < concurrency && queue.size > 0) {
635
- activeCount++;
636
- queue.dequeue().run();
637
- }
638
- };
639
- const next = () => {
640
- activeCount--;
641
- resumeNext();
642
- };
643
- const run = async (function_, resolve, arguments_) => {
644
- const result = (async () => function_(...arguments_))();
645
- resolve(result);
646
- try {
647
- await result;
648
- } catch {}
649
- next();
650
- };
651
- const enqueue = (function_, resolve, reject, arguments_) => {
652
- const queueItem = { reject };
653
- new Promise((internalResolve) => {
654
- queueItem.run = internalResolve;
655
- queue.enqueue(queueItem);
656
- }).then(run.bind(void 0, function_, resolve, arguments_));
657
- if (activeCount < concurrency) resumeNext();
658
- };
659
- const generator = (function_, ...arguments_) => new Promise((resolve, reject) => {
660
- enqueue(function_, resolve, reject, arguments_);
661
- });
662
- Object.defineProperties(generator, {
663
- activeCount: { get: () => activeCount },
664
- pendingCount: { get: () => queue.size },
665
- clearQueue: { value() {
666
- if (!rejectOnClear) {
667
- queue.clear();
668
- return;
669
- }
670
- const abortError = AbortSignal.abort().reason;
671
- while (queue.size > 0) queue.dequeue().reject(abortError);
672
- } },
673
- concurrency: {
674
- get: () => concurrency,
675
- set(newConcurrency) {
676
- validateConcurrency(newConcurrency);
677
- concurrency = newConcurrency;
678
- queueMicrotask(() => {
679
- while (activeCount < concurrency && queue.size > 0) resumeNext();
680
- });
681
- }
682
- },
683
- map: { async value(iterable, function_) {
684
- const promises = Array.from(iterable, (value, index) => this(function_, value, index));
685
- return Promise.all(promises);
686
- } }
687
- });
688
- return generator;
689
- }
690
- function validateConcurrency(concurrency) {
691
- if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) throw new TypeError("Expected `concurrency` to be a number from 1 and up");
692
- }
693
- //#endregion
694
567
  //#region src/FileProcessor.ts
695
568
  function joinSources(file) {
696
569
  return file.sources.map((item) => (0, _kubb_ast.extractStringsFromNodes)(item.nodes)).filter(Boolean).join("\n\n");
@@ -703,7 +576,6 @@ function joinSources(file) {
703
576
  */
704
577
  var FileProcessor = class {
705
578
  events = new AsyncEventEmitter();
706
- #limit = pLimit(16);
707
579
  async parse(file, { parsers, extension } = {}) {
708
580
  const parseExtName = extension?.[file.extname] || void 0;
709
581
  if (!parsers || !file.extname) return joinSources(file);
@@ -711,27 +583,37 @@ var FileProcessor = class {
711
583
  if (!parser) return joinSources(file);
712
584
  return parser.parse(file, { extname: parseExtName });
713
585
  }
714
- async run(files, { parsers, mode = "sequential", extension } = {}) {
715
- await this.events.emit("start", files);
586
+ /**
587
+ * Streams parsed files one at a time as each is processed.
588
+ *
589
+ * Unlike `run()`, files are yielded immediately after parsing rather than batched.
590
+ * Storage writes can begin as soon as the first file is ready, keeping peak
591
+ * memory proportional to one file at a time instead of the full batch.
592
+ */
593
+ async *stream(files, options = {}) {
716
594
  const total = files.length;
717
595
  let processed = 0;
718
- const processOne = async (file) => {
719
- const source = await this.parse(file, {
720
- extension,
721
- parsers
722
- });
723
- const currentProcessed = ++processed;
724
- const percentage = currentProcessed / total * 100;
725
- await this.events.emit("update", {
596
+ for (const file of files) {
597
+ const source = await this.parse(file, options);
598
+ processed++;
599
+ yield {
726
600
  file,
727
601
  source,
728
- processed: currentProcessed,
729
- percentage,
730
- total
731
- });
732
- };
733
- if (mode === "sequential") for (const file of files) await processOne(file);
734
- else await Promise.all(files.map((file) => this.#limit(() => processOne(file))));
602
+ processed,
603
+ total,
604
+ percentage: processed / total * 100
605
+ };
606
+ }
607
+ }
608
+ async run(files, options = {}) {
609
+ await this.events.emit("start", files);
610
+ for await (const { file, source, processed, total, percentage } of this.stream(files, options)) await this.events.emit("update", {
611
+ file,
612
+ source,
613
+ processed,
614
+ percentage,
615
+ total
616
+ });
735
617
  await this.events.emit("end", files);
736
618
  return files;
737
619
  }
@@ -927,15 +809,40 @@ async function setup(userConfig, options = {}) {
927
809
  logs: [`Running adapter: ${config.adapter.name}`]
928
810
  });
929
811
  driver.adapter = config.adapter;
930
- driver.inputNode = await config.adapter.parse(source);
931
- await hooks.emit("kubb:debug", {
932
- date: /* @__PURE__ */ new Date(),
933
- logs: [
934
- `✓ Adapter '${config.adapter.name}' resolved InputNode`,
935
- ` • Schemas: ${driver.inputNode.schemas.length}`,
936
- ` • Operations: ${driver.inputNode.operations.length}`
937
- ]
938
- });
812
+ if (config.adapter.count && config.adapter.stream) {
813
+ const { schemas: schemaCount, operations: operationCount } = await config.adapter.count(source);
814
+ if (schemaCount > 100) {
815
+ driver.inputStreamNode = await config.adapter.stream(source);
816
+ await hooks.emit("kubb:debug", {
817
+ date: /* @__PURE__ */ new Date(),
818
+ logs: [
819
+ `✓ Adapter '${config.adapter.name}' streaming InputStreamNode`,
820
+ ` • Schemas: ${schemaCount} (threshold: 100)`,
821
+ ` • Operations: ${operationCount}`
822
+ ]
823
+ });
824
+ } else {
825
+ driver.inputNode = await config.adapter.parse(source);
826
+ await hooks.emit("kubb:debug", {
827
+ date: /* @__PURE__ */ new Date(),
828
+ logs: [
829
+ `✓ Adapter '${config.adapter.name}' resolved InputNode`,
830
+ ` • Schemas: ${driver.inputNode.schemas.length}`,
831
+ ` • Operations: ${driver.inputNode.operations.length}`
832
+ ]
833
+ });
834
+ }
835
+ } else {
836
+ driver.inputNode = await config.adapter.parse(source);
837
+ await hooks.emit("kubb:debug", {
838
+ date: /* @__PURE__ */ new Date(),
839
+ logs: [
840
+ `✓ Adapter '${config.adapter.name}' resolved InputNode`,
841
+ ` • Schemas: ${driver.inputNode.schemas.length}`,
842
+ ` • Operations: ${driver.inputNode.operations.length}`
843
+ ]
844
+ });
845
+ }
939
846
  }
940
847
  return {
941
848
  config,
@@ -949,15 +856,134 @@ async function setup(userConfig, options = {}) {
949
856
  };
950
857
  }
951
858
  /**
952
- * Walks the AST and dispatches nodes to a plugin's direct AST hooks
953
- * (`schema`, `operation`, `operations`).
859
+ * Single-pass fan-out for streaming mode.
860
+ *
861
+ * Iterates `inputStreamNode.schemas` and `.operations` exactly once, distributing each
862
+ * node to every plugin in parallel. This replaces the N-pass-per-plugin pattern (where
863
+ * each plugin got its own `for await` iterator) with a single parse pass fanned to all
864
+ * plugins — eliminating the N×parse-time overhead for multi-plugin builds.
954
865
  *
955
- * When `include` contains only operation-scoped filters (`tag`, `operationId`, `path`,
956
- * `method`, `contentType`) and no `schemaName` filter, the function pre-computes the set
957
- * of top-level schema names transitively reachable from the included operations and skips
958
- * schemas that fall outside that set. This ensures that component schemas referenced
959
- * exclusively by excluded operations are not generated.
866
+ * Each plugin still gets independent `plugin:start` / `plugin:end` events and its own
867
+ * timing, but the schema and operation nodes are parsed only once total.
960
868
  */
869
+ async function runPluginStreamHooks(inputStreamNode, entries, driver, hooks, config, pluginTimings, failedPlugins, flushPendingFiles) {
870
+ function resolveRendererFor(gen, state) {
871
+ return gen.renderer === null ? void 0 : gen.renderer ?? state.plugin.renderer ?? state.generatorContext.config.renderer;
872
+ }
873
+ const states = entries.map(({ plugin, context, hrStart }) => ({
874
+ plugin,
875
+ generatorContext: {
876
+ ...context,
877
+ resolver: driver.getResolver(plugin.name)
878
+ },
879
+ generators: plugin.generators ?? [],
880
+ hrStart,
881
+ failed: false,
882
+ error: void 0
883
+ }));
884
+ let schemasProcessed = 0;
885
+ for await (const node of inputStreamNode.schemas) {
886
+ for (const state of states) {
887
+ if (state.failed) continue;
888
+ try {
889
+ const { plugin, generatorContext, generators } = state;
890
+ const { exclude, include, override } = plugin.options;
891
+ const transformedNode = plugin.transformer ? (0, _kubb_ast.transform)(node, plugin.transformer) : node;
892
+ const options = generatorContext.resolver.resolveOptions(transformedNode, {
893
+ options: plugin.options,
894
+ exclude,
895
+ include,
896
+ override
897
+ });
898
+ if (options === null) continue;
899
+ const ctx = {
900
+ ...generatorContext,
901
+ options
902
+ };
903
+ for (const gen of generators) {
904
+ if (!gen.schema) continue;
905
+ await require_PluginDriver.applyHookResult(await gen.schema(transformedNode, ctx), driver, resolveRendererFor(gen, state));
906
+ }
907
+ await driver.hooks.emit("kubb:generate:schema", transformedNode, ctx);
908
+ } catch (caughtError) {
909
+ state.failed = true;
910
+ state.error = caughtError;
911
+ }
912
+ }
913
+ schemasProcessed++;
914
+ if (schemasProcessed % 50 === 0) await flushPendingFiles();
915
+ }
916
+ const collectedOperations = [];
917
+ for await (const node of inputStreamNode.operations) {
918
+ collectedOperations.push(node);
919
+ for (const state of states) {
920
+ if (state.failed) continue;
921
+ try {
922
+ const { plugin, generatorContext, generators } = state;
923
+ const { exclude, include, override } = plugin.options;
924
+ const transformedNode = plugin.transformer ? (0, _kubb_ast.transform)(node, plugin.transformer) : node;
925
+ const options = generatorContext.resolver.resolveOptions(transformedNode, {
926
+ options: plugin.options,
927
+ exclude,
928
+ include,
929
+ override
930
+ });
931
+ if (options === null) continue;
932
+ const ctx = {
933
+ ...generatorContext,
934
+ options
935
+ };
936
+ for (const gen of generators) {
937
+ if (!gen.operation) continue;
938
+ await require_PluginDriver.applyHookResult(await gen.operation(transformedNode, ctx), driver, resolveRendererFor(gen, state));
939
+ }
940
+ await driver.hooks.emit("kubb:generate:operation", transformedNode, ctx);
941
+ } catch (caughtError) {
942
+ state.failed = true;
943
+ state.error = caughtError;
944
+ }
945
+ }
946
+ }
947
+ for (const state of states) {
948
+ if (!state.failed) try {
949
+ const { plugin, generatorContext, generators } = state;
950
+ const ctx = {
951
+ ...generatorContext,
952
+ options: plugin.options
953
+ };
954
+ for (const gen of generators) {
955
+ if (!gen.operations) continue;
956
+ await require_PluginDriver.applyHookResult(await gen.operations(collectedOperations, ctx), driver, resolveRendererFor(gen, state));
957
+ }
958
+ await driver.hooks.emit("kubb:generate:operations", collectedOperations, ctx);
959
+ } catch (caughtError) {
960
+ state.failed = true;
961
+ state.error = caughtError;
962
+ }
963
+ const duration = getElapsedMs(state.hrStart);
964
+ pluginTimings.set(state.plugin.name, duration);
965
+ await hooks.emit("kubb:plugin:end", {
966
+ plugin: state.plugin,
967
+ duration,
968
+ success: !state.failed,
969
+ ...state.failed && state.error ? { error: state.error } : {},
970
+ config,
971
+ get files() {
972
+ return driver.fileManager.files;
973
+ },
974
+ upsertFile: (...files) => driver.fileManager.upsert(...files)
975
+ });
976
+ if (state.failed && state.error) failedPlugins.add({
977
+ plugin: state.plugin,
978
+ error: state.error
979
+ });
980
+ await hooks.emit("kubb:debug", {
981
+ date: /* @__PURE__ */ new Date(),
982
+ logs: [state.failed ? "✗ Plugin start failed" : `✓ Plugin started successfully (${formatMs(duration)})`]
983
+ });
984
+ }
985
+ await flushPendingFiles();
986
+ }
961
987
  async function runPluginAstHooks(plugin, context) {
962
988
  const { adapter, inputNode, resolver, driver } = context;
963
989
  const { exclude, include, override } = plugin.options;
@@ -1046,54 +1072,90 @@ async function safeBuild(setupResult) {
1046
1072
  const parsersMap = /* @__PURE__ */ new Map();
1047
1073
  for (const parser of config.parsers) if (parser.extNames) for (const extname of parser.extNames) parsersMap.set(extname, parser);
1048
1074
  const fileProcessor = new FileProcessor();
1049
- fileProcessor.events.on("start", async (processingFiles) => {
1050
- await hooks.emit("kubb:files:processing:start", { files: processingFiles });
1051
- });
1052
- fileProcessor.events.on("update", async ({ file, source, processed, total, percentage }) => {
1053
- await hooks.emit("kubb:file:processing:update", {
1054
- file,
1055
- source,
1056
- processed,
1057
- total,
1058
- percentage,
1059
- config
1060
- });
1061
- if (source) await storage.setItem(file.path, source);
1062
- });
1063
- fileProcessor.events.on("end", async (processed) => {
1064
- await hooks.emit("kubb:files:processing:end", { files: processed });
1065
- await hooks.emit("kubb:debug", {
1066
- date: /* @__PURE__ */ new Date(),
1067
- logs: [`✓ File write process completed for ${processed.length} files`]
1068
- });
1069
- });
1070
- async function flushPendingFiles() {
1071
- const files = driver.fileManager.files.filter((f) => !writtenPaths.has(f.path));
1075
+ async function flushPendingFiles(snapshot) {
1076
+ const files = driver.fileManager.files.filter((f) => !writtenPaths.has(f.path) && (!snapshot || !snapshot.has(f.path)));
1072
1077
  if (files.length === 0) return;
1073
1078
  await hooks.emit("kubb:debug", {
1074
1079
  date: /* @__PURE__ */ new Date(),
1075
1080
  logs: [`Writing ${files.length} files...`]
1076
1081
  });
1077
- await fileProcessor.run(files, {
1082
+ await hooks.emit("kubb:files:processing:start", { files });
1083
+ const stream = fileProcessor.stream(files, {
1078
1084
  parsers: parsersMap,
1079
- mode: "parallel",
1080
1085
  extension: config.output.extension
1081
1086
  });
1082
- for (const file of files) writtenPaths.add(file.path);
1087
+ for await (const { file, source, processed, total, percentage } of stream) {
1088
+ await hooks.emit("kubb:file:processing:update", {
1089
+ file,
1090
+ source,
1091
+ processed,
1092
+ total,
1093
+ percentage,
1094
+ config
1095
+ });
1096
+ if (source) await storage.setItem(file.path, source);
1097
+ writtenPaths.add(file.path);
1098
+ }
1099
+ await hooks.emit("kubb:files:processing:end", { files });
1100
+ await hooks.emit("kubb:debug", {
1101
+ date: /* @__PURE__ */ new Date(),
1102
+ logs: [`✓ File write process completed for ${files.length} files`]
1103
+ });
1083
1104
  }
1084
1105
  try {
1085
1106
  await driver.emitSetupHooks();
1086
- if (driver.adapter && driver.inputNode) await hooks.emit("kubb:build:start", {
1107
+ if (driver.adapter && (driver.inputNode || driver.inputStreamNode)) await hooks.emit("kubb:build:start", {
1087
1108
  config,
1088
1109
  adapter: driver.adapter,
1089
- inputNode: driver.inputNode,
1110
+ inputNode: driver.inputNode ?? {
1111
+ kind: "Input",
1112
+ schemas: [],
1113
+ operations: [],
1114
+ meta: driver.inputStreamNode?.meta
1115
+ },
1090
1116
  getPlugin: driver.getPlugin.bind(driver),
1091
1117
  get files() {
1092
1118
  return driver.fileManager.files;
1093
1119
  },
1094
1120
  upsertFile: (...files) => driver.fileManager.upsert(...files)
1095
1121
  });
1096
- for (const plugin of driver.plugins.values()) {
1122
+ const inputStreamNode = driver.inputStreamNode;
1123
+ if (inputStreamNode) {
1124
+ const streamPluginEntries = [];
1125
+ for (const plugin of driver.plugins.values()) {
1126
+ const context = driver.getContext(plugin);
1127
+ const hrStart = process.hrtime();
1128
+ await hooks.emit("kubb:plugin:start", { plugin });
1129
+ await hooks.emit("kubb:debug", {
1130
+ date: /* @__PURE__ */ new Date(),
1131
+ logs: ["Starting plugin...", ` • Plugin Name: ${plugin.name}`]
1132
+ });
1133
+ if (plugin.generators?.length || driver.hasRegisteredGenerators(plugin.name)) streamPluginEntries.push({
1134
+ plugin,
1135
+ context,
1136
+ hrStart
1137
+ });
1138
+ else {
1139
+ const duration = getElapsedMs(hrStart);
1140
+ pluginTimings.set(plugin.name, duration);
1141
+ await hooks.emit("kubb:plugin:end", {
1142
+ plugin,
1143
+ duration,
1144
+ success: true,
1145
+ config,
1146
+ get files() {
1147
+ return driver.fileManager.files;
1148
+ },
1149
+ upsertFile: (...files) => driver.fileManager.upsert(...files)
1150
+ });
1151
+ await hooks.emit("kubb:debug", {
1152
+ date: /* @__PURE__ */ new Date(),
1153
+ logs: [`✓ Plugin started successfully (${formatMs(duration)})`]
1154
+ });
1155
+ }
1156
+ }
1157
+ if (streamPluginEntries.length > 0) await runPluginStreamHooks(inputStreamNode, streamPluginEntries, driver, hooks, config, pluginTimings, failedPlugins, flushPendingFiles);
1158
+ } else for (const plugin of driver.plugins.values()) {
1097
1159
  const context = driver.getContext(plugin);
1098
1160
  const hrStart = process.hrtime();
1099
1161
  try {
@@ -1150,6 +1212,7 @@ async function safeBuild(setupResult) {
1150
1212
  error
1151
1213
  });
1152
1214
  }
1215
+ await flushPendingFiles();
1153
1216
  }
1154
1217
  await hooks.emit("kubb:plugins:end", {
1155
1218
  config,