@kubb/agent 5.0.0-beta.17 → 5.0.0-beta.19

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.
@@ -4428,13 +4428,15 @@ function sendToBetterStack(level, tag, message, ctx) {
4428
4428
  if (level === "error") {
4429
4429
  client.error(fullMessage, context).then(() => client.flush()).catch(() => {
4430
4430
  });
4431
- } else if (level === "warn") {
4431
+ return;
4432
+ }
4433
+ if (level === "warn") {
4432
4434
  client.warn(fullMessage, context).then(() => client.flush()).catch(() => {
4433
4435
  });
4434
- } else {
4435
- client.info(fullMessage, context).then(() => client.flush()).catch(() => {
4436
- });
4436
+ return;
4437
4437
  }
4438
+ client.info(fullMessage, context).then(() => client.flush()).catch(() => {
4439
+ });
4438
4440
  } catch (_e) {
4439
4441
  }
4440
4442
  }
@@ -4833,14 +4835,12 @@ async function _walk(node, visitor, recurse, limit, parent) {
4833
4835
  for (const child of children) await _walk(child, visitor, recurse, limit, node);
4834
4836
  }
4835
4837
  function transform(node, options) {
4836
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
4838
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
4837
4839
  const { depth, parent, ...visitor } = options;
4838
4840
  const recurse = (depth != null ? depth : visitorDepths.deep) === visitorDepths.deep;
4839
4841
  switch (node.kind) {
4840
4842
  case "Input": {
4841
- let input = node;
4842
- const replaced = (_a = visitor.input) == null ? void 0 : _a.call(visitor, input, { parent });
4843
- if (replaced) input = replaced;
4843
+ const input = (_b = (_a = visitor.input) == null ? void 0 : _a.call(visitor, node, { parent })) != null ? _b : node;
4844
4844
  return {
4845
4845
  ...input,
4846
4846
  schemas: input.schemas.map((s) => transform(s, {
@@ -4853,16 +4853,10 @@ function transform(node, options) {
4853
4853
  }))
4854
4854
  };
4855
4855
  }
4856
- case "Output": {
4857
- let output = node;
4858
- const replaced = (_b = visitor.output) == null ? void 0 : _b.call(visitor, output, { parent });
4859
- if (replaced) output = replaced;
4860
- return output;
4861
- }
4856
+ case "Output":
4857
+ return (_d = (_c = visitor.output) == null ? void 0 : _c.call(visitor, node, { parent })) != null ? _d : node;
4862
4858
  case "Operation": {
4863
- let op = node;
4864
- const replaced = (_c = visitor.operation) == null ? void 0 : _c.call(visitor, op, { parent });
4865
- if (replaced) op = replaced;
4859
+ const op = (_f = (_e = visitor.operation) == null ? void 0 : _e.call(visitor, node, { parent })) != null ? _f : node;
4866
4860
  return {
4867
4861
  ...op,
4868
4862
  parameters: op.parameters.map((p) => transform(p, {
@@ -4871,7 +4865,7 @@ function transform(node, options) {
4871
4865
  })),
4872
4866
  requestBody: op.requestBody ? {
4873
4867
  ...op.requestBody,
4874
- content: (_d = op.requestBody.content) == null ? void 0 : _d.map((c) => ({
4868
+ content: (_g = op.requestBody.content) == null ? void 0 : _g.map((c) => ({
4875
4869
  ...c,
4876
4870
  schema: c.schema ? transform(c.schema, {
4877
4871
  ...options,
@@ -4886,9 +4880,7 @@ function transform(node, options) {
4886
4880
  };
4887
4881
  }
4888
4882
  case "Schema": {
4889
- let schema = node;
4890
- const replaced = (_e = visitor.schema) == null ? void 0 : _e.call(visitor, schema, { parent });
4891
- if (replaced) schema = replaced;
4883
+ const schema = (_i = (_h = visitor.schema) == null ? void 0 : _h.call(visitor, node, { parent })) != null ? _i : node;
4892
4884
  const childOptions = {
4893
4885
  ...options,
4894
4886
  parent: schema
@@ -4896,15 +4888,13 @@ function transform(node, options) {
4896
4888
  return {
4897
4889
  ...schema,
4898
4890
  ..."properties" in schema && recurse ? { properties: schema.properties.map((p) => transform(p, childOptions)) } : {},
4899
- ..."items" in schema && recurse ? { items: (_f = schema.items) == null ? void 0 : _f.map((i) => transform(i, childOptions)) } : {},
4900
- ..."members" in schema && recurse ? { members: (_g = schema.members) == null ? void 0 : _g.map((m) => transform(m, childOptions)) } : {},
4891
+ ..."items" in schema && recurse ? { items: (_j = schema.items) == null ? void 0 : _j.map((i) => transform(i, childOptions)) } : {},
4892
+ ..."members" in schema && recurse ? { members: (_k = schema.members) == null ? void 0 : _k.map((m) => transform(m, childOptions)) } : {},
4901
4893
  ..."additionalProperties" in schema && recurse && schema.additionalProperties && schema.additionalProperties !== true ? { additionalProperties: transform(schema.additionalProperties, childOptions) } : {}
4902
4894
  };
4903
4895
  }
4904
4896
  case "Property": {
4905
- let prop = node;
4906
- const replaced = (_h = visitor.property) == null ? void 0 : _h.call(visitor, prop, { parent });
4907
- if (replaced) prop = replaced;
4897
+ const prop = (_m = (_l = visitor.property) == null ? void 0 : _l.call(visitor, node, { parent })) != null ? _m : node;
4908
4898
  return createProperty({
4909
4899
  ...prop,
4910
4900
  schema: transform(prop.schema, {
@@ -4914,9 +4904,7 @@ function transform(node, options) {
4914
4904
  });
4915
4905
  }
4916
4906
  case "Parameter": {
4917
- let param = node;
4918
- const replaced = (_i = visitor.parameter) == null ? void 0 : _i.call(visitor, param, { parent });
4919
- if (replaced) param = replaced;
4907
+ const param = (_o = (_n = visitor.parameter) == null ? void 0 : _n.call(visitor, node, { parent })) != null ? _o : node;
4920
4908
  return createParameter({
4921
4909
  ...param,
4922
4910
  schema: transform(param.schema, {
@@ -4926,9 +4914,7 @@ function transform(node, options) {
4926
4914
  });
4927
4915
  }
4928
4916
  case "Response": {
4929
- let response = node;
4930
- const replaced = (_j = visitor.response) == null ? void 0 : _j.call(visitor, response, { parent });
4931
- if (replaced) response = replaced;
4917
+ const response = (_q = (_p = visitor.response) == null ? void 0 : _p.call(visitor, node, { parent })) != null ? _q : node;
4932
4918
  return {
4933
4919
  ...response,
4934
4920
  schema: transform(response.schema, {
@@ -5145,7 +5131,15 @@ function collectReferencedSchemaNames(node, out = /* @__PURE__ */ new Set()) {
5145
5131
  for (const name of collectSchemaRefs(node)) out.add(name);
5146
5132
  return out;
5147
5133
  }
5134
+ const usedSchemaNamesCache = /* @__PURE__ */ new WeakMap();
5148
5135
  function collectUsedSchemaNames(operations, schemas) {
5136
+ let byOps = usedSchemaNamesCache.get(operations);
5137
+ if (!byOps) {
5138
+ byOps = /* @__PURE__ */ new WeakMap();
5139
+ usedSchemaNamesCache.set(operations, byOps);
5140
+ }
5141
+ const cached = byOps.get(schemas);
5142
+ if (cached) return cached;
5149
5143
  const schemaMap = /* @__PURE__ */ new Map();
5150
5144
  for (const schema of schemas) if (schema.name) schemaMap.set(schema.name, schema);
5151
5145
  const result = /* @__PURE__ */ new Set();
@@ -5161,6 +5155,7 @@ function collectUsedSchemaNames(operations, schemas) {
5161
5155
  depth: "shallow",
5162
5156
  schema: (node) => node
5163
5157
  })) visitSchema(schema);
5158
+ byOps.set(schemas, result);
5164
5159
  return result;
5165
5160
  }
5166
5161
  function syncOptionality(schema, required) {
@@ -5298,12 +5293,12 @@ function matchesSchemaPattern(node, type, pattern) {
5298
5293
  }
5299
5294
  }
5300
5295
  function defaultResolver(name, type) {
5301
- let resolvedName = camelCase(name);
5302
- if (type === "file" || type === "function") resolvedName = camelCase(name, { isFile: type === "file" });
5303
- if (type === "type") resolvedName = pascalCase(name);
5304
- return resolvedName;
5296
+ if (type === "file" || type === "function") return camelCase(name, { isFile: type === "file" });
5297
+ if (type === "type") return pascalCase(name);
5298
+ return camelCase(name);
5305
5299
  }
5306
- function defaultResolveOptions(node, { options, exclude = [], include, override = [] }) {
5300
+ const resolveOptionsCache = /* @__PURE__ */ new WeakMap();
5301
+ function computeOptions(node, options, exclude, include, override) {
5307
5302
  var _a2, _b2;
5308
5303
  if (isOperationNode(node)) {
5309
5304
  if (exclude.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))) return null;
@@ -5328,19 +5323,34 @@ function defaultResolveOptions(node, { options, exclude = [], include, override
5328
5323
  }
5329
5324
  return options;
5330
5325
  }
5326
+ function defaultResolveOptions(node, { options, exclude = [], include, override = [] }) {
5327
+ const optionsKey = options;
5328
+ let byOptions = resolveOptionsCache.get(optionsKey);
5329
+ if (!byOptions) {
5330
+ byOptions = /* @__PURE__ */ new WeakMap();
5331
+ resolveOptionsCache.set(optionsKey, byOptions);
5332
+ }
5333
+ const cached = byOptions.get(node);
5334
+ if (cached !== void 0) return cached.value;
5335
+ const result = computeOptions(node, options, exclude, include, override);
5336
+ byOptions.set(node, { value: result });
5337
+ return result;
5338
+ }
5331
5339
  function defaultResolvePath({ baseName, pathMode, tag, path: groupPath }, { root, output, group }) {
5332
- var _a2;
5333
5340
  if ((pathMode != null ? pathMode : getMode(path$1.resolve(root, output.path))) === "single") return path$1.resolve(root, output.path);
5334
- let result;
5335
- if (group && (groupPath || tag)) {
5336
- const groupValue = group.type === "path" ? groupPath : tag;
5337
- const defaultName = group.type === "tag" ? ({ group: g }) => `${camelCase(g)}Controller` : ({ group: g }) => {
5338
- const segment = g.split("/").filter((s) => s !== "" && s !== "." && s !== "..")[0];
5339
- return segment ? camelCase(segment) : "";
5340
- };
5341
- const resolveName = (_a2 = group.name) != null ? _a2 : defaultName;
5342
- result = path$1.resolve(root, output.path, resolveName({ group: groupValue }), baseName);
5343
- } else result = path$1.resolve(root, output.path, baseName);
5341
+ const result = (() => {
5342
+ var _a2;
5343
+ if (group && (groupPath || tag)) {
5344
+ const groupValue = group.type === "path" ? groupPath : tag;
5345
+ const defaultName = group.type === "tag" ? ({ group: g }) => `${camelCase(g)}Controller` : ({ group: g }) => {
5346
+ const segment = g.split("/").filter((s) => s !== "" && s !== "." && s !== "..")[0];
5347
+ return segment ? camelCase(segment) : "";
5348
+ };
5349
+ const resolveName = (_a2 = group.name) != null ? _a2 : defaultName;
5350
+ return path$1.resolve(root, output.path, resolveName({ group: groupValue }), baseName);
5351
+ }
5352
+ return path$1.resolve(root, output.path, baseName);
5353
+ })();
5344
5354
  const outputDir = path$1.resolve(root, output.path);
5345
5355
  const outputDirWithSep = outputDir.endsWith(path$1.sep) ? outputDir : `${outputDir}${path$1.sep}`;
5346
5356
  if (result !== outputDir && !result.startsWith(outputDirWithSep)) throw new Error(`[Kubb] Resolved path "${result}" is outside the output directory "${outputDir}". This may indicate a path traversal attempt in the OpenAPI specification or a misconfigured group.name function.`);
@@ -5366,12 +5376,16 @@ function defaultResolveFile({ name, extname: extname2, tag, path: groupPath }, c
5366
5376
  }
5367
5377
  function buildDefaultBanner({ title, description, version, config }) {
5368
5378
  try {
5369
- let source = "";
5370
- if (Array.isArray(config.input)) {
5371
- const first = config.input[0];
5372
- if (first && "path" in first) source = path$1.basename(first.path);
5373
- } else if (config.input && "path" in config.input) source = path$1.basename(config.input.path);
5374
- else if (config.input && "data" in config.input) source = "text content";
5379
+ const source = (() => {
5380
+ if (Array.isArray(config.input)) {
5381
+ const first = config.input[0];
5382
+ if (first && "path" in first) return path$1.basename(first.path);
5383
+ return "";
5384
+ }
5385
+ if (config.input && "path" in config.input) return path$1.basename(config.input.path);
5386
+ if (config.input && "data" in config.input) return "text content";
5387
+ return "";
5388
+ })();
5375
5389
  let banner = "/**\n* Generated by Kubb (https://kubb.dev/).\n* Do not edit manually.\n";
5376
5390
  if (config.output.defaultBanner === "simple") {
5377
5391
  banner += "*/\n";
@@ -5505,6 +5519,9 @@ var FileManager = (_a$1 = class {
5505
5519
  dispose() {
5506
5520
  this.clear();
5507
5521
  }
5522
+ [Symbol.dispose]() {
5523
+ this.dispose();
5524
+ }
5508
5525
  /**
5509
5526
  * All stored files, sorted by path length (shorter paths first).
5510
5527
  */
@@ -5697,7 +5714,11 @@ var PluginDriver = (_b$1 = class {
5697
5714
  if (gen.schema) {
5698
5715
  const schemaHandler = async (node, ctx) => {
5699
5716
  if (ctx.plugin.name !== pluginName) return;
5700
- await applyHookResult(await gen.schema(node, ctx), this, resolveRenderer());
5717
+ await applyHookResult({
5718
+ result: await gen.schema(node, ctx),
5719
+ driver: this,
5720
+ rendererFactory: resolveRenderer()
5721
+ });
5701
5722
  };
5702
5723
  this.hooks.on("kubb:generate:schema", schemaHandler);
5703
5724
  __privateMethod$1(this, _PluginDriver_instances, trackHookListener_fn).call(this, "kubb:generate:schema", schemaHandler);
@@ -5705,7 +5726,11 @@ var PluginDriver = (_b$1 = class {
5705
5726
  if (gen.operation) {
5706
5727
  const operationHandler = async (node, ctx) => {
5707
5728
  if (ctx.plugin.name !== pluginName) return;
5708
- await applyHookResult(await gen.operation(node, ctx), this, resolveRenderer());
5729
+ await applyHookResult({
5730
+ result: await gen.operation(node, ctx),
5731
+ driver: this,
5732
+ rendererFactory: resolveRenderer()
5733
+ });
5709
5734
  };
5710
5735
  this.hooks.on("kubb:generate:operation", operationHandler);
5711
5736
  __privateMethod$1(this, _PluginDriver_instances, trackHookListener_fn).call(this, "kubb:generate:operation", operationHandler);
@@ -5713,7 +5738,11 @@ var PluginDriver = (_b$1 = class {
5713
5738
  if (gen.operations) {
5714
5739
  const operationsHandler = async (nodes, ctx) => {
5715
5740
  if (ctx.plugin.name !== pluginName) return;
5716
- await applyHookResult(await gen.operations(nodes, ctx), this, resolveRenderer());
5741
+ await applyHookResult({
5742
+ result: await gen.operations(nodes, ctx),
5743
+ driver: this,
5744
+ rendererFactory: resolveRenderer()
5745
+ });
5717
5746
  };
5718
5747
  this.hooks.on("kubb:generate:operations", operationsHandler);
5719
5748
  __privateMethod$1(this, _PluginDriver_instances, trackHookListener_fn).call(this, "kubb:generate:operations", operationsHandler);
@@ -5746,6 +5775,9 @@ var PluginDriver = (_b$1 = class {
5746
5775
  this.inputNode = void 0;
5747
5776
  this.inputStreamNode = void 0;
5748
5777
  }
5778
+ [Symbol.dispose]() {
5779
+ this.dispose();
5780
+ }
5749
5781
  /**
5750
5782
  * Merges `partial` with the plugin's default resolver and stores the result.
5751
5783
  * Also mirrors it onto `plugin.resolver` so callers using `getPlugin(name).resolver`
@@ -5787,8 +5819,9 @@ var PluginDriver = (_b$1 = class {
5787
5819
  driver.fileManager.upsert(...files);
5788
5820
  },
5789
5821
  get inputNode() {
5790
- var _a2, _b2;
5791
- return (_b2 = driver.inputNode) != null ? _b2 : {
5822
+ var _a2;
5823
+ if (driver.inputNode) return driver.inputNode;
5824
+ return {
5792
5825
  kind: "Input",
5793
5826
  schemas: [],
5794
5827
  operations: [],
@@ -5866,7 +5899,7 @@ normalizePlugin_fn = function(hookPlugin) {
5866
5899
  __privateGet$1(this, _defaultResolvers).set(pluginName, resolver);
5867
5900
  return resolver;
5868
5901
  }, _b$1);
5869
- async function applyHookResult(result, driver, rendererFactory) {
5902
+ function applyHookResult({ result, driver, rendererFactory }) {
5870
5903
  if (!result) return;
5871
5904
  if (Array.isArray(result)) {
5872
5905
  driver.fileManager.upsert(...result);
@@ -5874,6 +5907,18 @@ async function applyHookResult(result, driver, rendererFactory) {
5874
5907
  }
5875
5908
  if (!rendererFactory) return;
5876
5909
  const renderer = rendererFactory();
5910
+ if (renderer.stream) {
5911
+ for (const file of renderer.stream(result)) driver.fileManager.upsert(file);
5912
+ renderer.unmount();
5913
+ return;
5914
+ }
5915
+ return applyAsyncRender({
5916
+ renderer,
5917
+ result,
5918
+ driver
5919
+ });
5920
+ }
5921
+ async function applyAsyncRender({ renderer, result, driver }) {
5877
5922
  await renderer.render(result);
5878
5923
  driver.fileManager.upsert(...renderer.files);
5879
5924
  renderer.unmount();
@@ -5890,7 +5935,7 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
5890
5935
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
5891
5936
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
5892
5937
  var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
5893
- var _emitter, _a, _options, _URLPath_instances, transformParam_fn, eachParam_fn, _b;
5938
+ var _emitter, _AsyncEventEmitter_instances, emitAll_fn, _a, _options, _URLPath_instances, transformParam_fn, eachParam_fn, _b;
5894
5939
  var BuildError = class extends Error {
5895
5940
  constructor(message, options) {
5896
5941
  super(message, { cause: options.cause });
@@ -5908,6 +5953,7 @@ var AsyncEventEmitter = (_a = class {
5908
5953
  * @default 10
5909
5954
  */
5910
5955
  constructor(maxListener = 10) {
5956
+ __privateAdd(this, _AsyncEventEmitter_instances);
5911
5957
  __privateAdd(this, _emitter, new EventEmitter());
5912
5958
  __privateGet(this, _emitter).setMaxListeners(maxListener);
5913
5959
  }
@@ -5920,20 +5966,10 @@ var AsyncEventEmitter = (_a = class {
5920
5966
  * await emitter.emit('build', 'petstore')
5921
5967
  * ```
5922
5968
  */
5923
- async emit(eventName, ...eventArgs) {
5969
+ emit(eventName, ...eventArgs) {
5924
5970
  const listeners = __privateGet(this, _emitter).listeners(eventName);
5925
5971
  if (listeners.length === 0) return;
5926
- for (const listener of listeners) try {
5927
- await listener(...eventArgs);
5928
- } catch (err) {
5929
- let serializedArgs;
5930
- try {
5931
- serializedArgs = JSON.stringify(eventArgs);
5932
- } catch {
5933
- serializedArgs = String(eventArgs);
5934
- }
5935
- throw new Error(`Error in async listener for "${eventName}" with eventArgs ${serializedArgs}`, { cause: toError(err) });
5936
- }
5972
+ return __privateMethod(this, _AsyncEventEmitter_instances, emitAll_fn).call(this, eventName, listeners, eventArgs);
5937
5973
  }
5938
5974
  /**
5939
5975
  * Registers a persistent listener for `eventName`.
@@ -5995,7 +6031,19 @@ var AsyncEventEmitter = (_a = class {
5995
6031
  removeAll() {
5996
6032
  __privateGet(this, _emitter).removeAllListeners();
5997
6033
  }
5998
- }, _emitter = new WeakMap(), _a);
6034
+ }, _emitter = new WeakMap(), _AsyncEventEmitter_instances = new WeakSet(), emitAll_fn = async function(eventName, listeners, eventArgs) {
6035
+ for (const listener of listeners) try {
6036
+ await listener(...eventArgs);
6037
+ } catch (err) {
6038
+ let serializedArgs;
6039
+ try {
6040
+ serializedArgs = JSON.stringify(eventArgs);
6041
+ } catch {
6042
+ serializedArgs = String(eventArgs);
6043
+ }
6044
+ throw new Error(`Error in async listener for "${eventName}" with eventArgs ${serializedArgs}`, { cause: toError(err) });
6045
+ }
6046
+ }, _a);
5999
6047
  function getElapsedMs(hrStart) {
6000
6048
  const [seconds, nanoseconds] = process.hrtime(hrStart);
6001
6049
  const ms = seconds * 1e3 + nanoseconds / 1e6;
@@ -6046,6 +6094,9 @@ async function clean(path) {
6046
6094
  force: true
6047
6095
  });
6048
6096
  }
6097
+ function isPromise(result) {
6098
+ return result !== null && result !== void 0 && typeof result["then"] === "function";
6099
+ }
6049
6100
  const reservedWords = /* @__PURE__ */ new Set([
6050
6101
  "abstract",
6051
6102
  "arguments",
@@ -6268,36 +6319,37 @@ eachParam_fn = function(fn) {
6268
6319
  fn(raw, __privateMethod(this, _URLPath_instances, transformParam_fn).call(this, raw));
6269
6320
  }
6270
6321
  }, _b);
6271
- var version$1 = "5.0.0-beta.17";
6322
+ var version$1 = "5.0.0-beta.19";
6272
6323
  function createStorage(build2) {
6273
6324
  return (options) => build2(options != null ? options : {});
6274
6325
  }
6275
6326
  function joinSources(file) {
6276
- return file.sources.map((item) => extractStringsFromNodes(item.nodes)).filter(Boolean).join("\n\n");
6327
+ const sources = file.sources;
6328
+ if (sources.length === 0) return "";
6329
+ const parts = [];
6330
+ for (const source of sources) {
6331
+ const s = extractStringsFromNodes(source.nodes);
6332
+ if (s) parts.push(s);
6333
+ }
6334
+ return parts.join("\n\n");
6277
6335
  }
6278
6336
  var FileProcessor = class {
6279
6337
  constructor() {
6280
6338
  __publicField(this, "events", new AsyncEventEmitter());
6281
6339
  }
6282
- async parse(file, { parsers, extension } = {}) {
6340
+ parse(file, { parsers, extension } = {}) {
6283
6341
  const parseExtName = (extension == null ? void 0 : extension[file.extname]) || void 0;
6284
6342
  if (!parsers || !file.extname) return joinSources(file);
6285
6343
  const parser = parsers.get(file.extname);
6286
6344
  if (!parser) return joinSources(file);
6287
6345
  return parser.parse(file, { extname: parseExtName });
6288
6346
  }
6289
- /**
6290
- * Streams parsed files one at a time as each is processed.
6291
- *
6292
- * Unlike `run()`, files are yielded immediately after parsing rather than batched.
6293
- * Storage writes can begin as soon as the first file is ready, keeping peak
6294
- * memory proportional to one file at a time instead of the full batch.
6295
- */
6296
- async *stream(files, options = {}) {
6347
+ *stream(files, options = {}) {
6297
6348
  const total = files.length;
6349
+ if (total === 0) return;
6298
6350
  let processed = 0;
6299
6351
  for (const file of files) {
6300
- const source = await this.parse(file, options);
6352
+ const source = this.parse(file, options);
6301
6353
  processed++;
6302
6354
  yield {
6303
6355
  file,
@@ -6310,7 +6362,7 @@ var FileProcessor = class {
6310
6362
  }
6311
6363
  async run(files, options = {}) {
6312
6364
  await this.events.emit("start", files);
6313
- for await (const { file, source, processed, total, percentage } of this.stream(files, options)) await this.events.emit("update", {
6365
+ for (const { file, source, processed, total, percentage } of this.stream(files, options)) await this.events.emit("update", {
6314
6366
  file,
6315
6367
  source,
6316
6368
  processed,
@@ -6368,6 +6420,64 @@ const fsStorage = createStorage(() => ({
6368
6420
  await clean(resolve(base));
6369
6421
  }
6370
6422
  }));
6423
+ function _usingCtx() {
6424
+ var r = "function" == typeof SuppressedError ? SuppressedError : function(r2, e2) {
6425
+ var n2 = Error();
6426
+ return n2.name = "SuppressedError", n2.error = r2, n2.suppressed = e2, n2;
6427
+ };
6428
+ var e = {};
6429
+ var n = [];
6430
+ function using(r2, e2) {
6431
+ if (null != e2) {
6432
+ if (Object(e2) !== e2) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
6433
+ if (r2) var o = e2[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
6434
+ if (void 0 === o && (o = e2[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r2)) var t = o;
6435
+ if ("function" != typeof o) throw new TypeError("Object is not disposable.");
6436
+ t && (o = function o2() {
6437
+ try {
6438
+ t.call(e2);
6439
+ } catch (r3) {
6440
+ return Promise.reject(r3);
6441
+ }
6442
+ }), n.push({
6443
+ v: e2,
6444
+ d: o,
6445
+ a: r2
6446
+ });
6447
+ } else r2 && n.push({
6448
+ d: e2,
6449
+ a: r2
6450
+ });
6451
+ return e2;
6452
+ }
6453
+ return {
6454
+ e,
6455
+ u: using.bind(null, false),
6456
+ a: using.bind(null, true),
6457
+ d: function d() {
6458
+ var o;
6459
+ var t = this.e;
6460
+ var s = 0;
6461
+ function next() {
6462
+ for (; o = n.pop(); ) try {
6463
+ if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
6464
+ if (o.d) {
6465
+ var r2 = o.d.call(o.v);
6466
+ if (o.a) return s |= 2, Promise.resolve(r2).then(next, err);
6467
+ } else s |= 1;
6468
+ } catch (r3) {
6469
+ return err(r3);
6470
+ }
6471
+ if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
6472
+ if (t !== e) throw t;
6473
+ }
6474
+ function err(n2) {
6475
+ return t = t !== e ? new r(n2, t) : n2, next();
6476
+ }
6477
+ return next();
6478
+ }
6479
+ };
6480
+ }
6371
6481
  function createSourcesView(storage) {
6372
6482
  const paths = /* @__PURE__ */ new Set();
6373
6483
  return createStorage(() => ({
@@ -6488,18 +6598,9 @@ async function setup(userConfig, options = {}) {
6488
6598
  ` \u2022 Operations: ${operationCount}`
6489
6599
  ]
6490
6600
  });
6491
- } else {
6492
- driver.inputNode = await config.adapter.parse(source);
6493
- await hooks.emit("kubb:debug", {
6494
- date: /* @__PURE__ */ new Date(),
6495
- logs: [
6496
- `\u2713 Adapter '${config.adapter.name}' resolved InputNode`,
6497
- ` \u2022 Schemas: ${driver.inputNode.schemas.length}`,
6498
- ` \u2022 Operations: ${driver.inputNode.operations.length}`
6499
- ]
6500
- });
6501
6601
  }
6502
- } else {
6602
+ }
6603
+ if (!driver.inputStreamNode) {
6503
6604
  driver.inputNode = await config.adapter.parse(source);
6504
6605
  await hooks.emit("kubb:debug", {
6505
6606
  date: /* @__PURE__ */ new Date(),
@@ -6516,19 +6617,26 @@ async function setup(userConfig, options = {}) {
6516
6617
  hooks,
6517
6618
  driver,
6518
6619
  storage,
6519
- dispose: () => {
6520
- driver.dispose();
6521
- for (const [event, handler] of middlewareListeners) hooks.off(event, handler);
6522
- }
6620
+ dispose,
6621
+ [Symbol.dispose]: dispose
6523
6622
  };
6623
+ function dispose() {
6624
+ driver.dispose();
6625
+ for (const [event, handler] of middlewareListeners) hooks.off(event, handler);
6626
+ }
6524
6627
  }
6525
- async function runPluginStreamHooks(inputStreamNode, entries, driver, hooks, config, pluginTimings, failedPlugins, flushPendingFiles) {
6628
+ async function runPluginStreamHooks({ entries, driver, pluginTimings, failedPlugins }) {
6629
+ const inputStreamNode = driver.inputStreamNode;
6526
6630
  function resolveRendererFor(gen, state) {
6527
6631
  var _a2, _b2;
6528
6632
  return gen.renderer === null ? void 0 : (_b2 = (_a2 = gen.renderer) != null ? _a2 : state.plugin.renderer) != null ? _b2 : state.generatorContext.config.renderer;
6529
6633
  }
6530
6634
  const states = entries.map(({ plugin, context, hrStart }) => {
6531
6635
  var _a2;
6636
+ const { exclude, include, override } = plugin.options;
6637
+ const hasExclude = Array.isArray(exclude) && exclude.length > 0;
6638
+ const hasInclude = Array.isArray(include) && include.length > 0;
6639
+ const hasOverride = Array.isArray(override) && override.length > 0;
6532
6640
  return {
6533
6641
  plugin,
6534
6642
  generatorContext: {
@@ -6538,72 +6646,82 @@ async function runPluginStreamHooks(inputStreamNode, entries, driver, hooks, con
6538
6646
  generators: (_a2 = plugin.generators) != null ? _a2 : [],
6539
6647
  hrStart,
6540
6648
  failed: false,
6541
- error: void 0
6649
+ error: void 0,
6650
+ optionsAreStatic: !hasExclude && !hasInclude && !hasOverride
6542
6651
  };
6543
6652
  });
6544
- let schemasProcessed = 0;
6545
- for await (const node of inputStreamNode.schemas) {
6546
- for (const state of states) {
6547
- if (state.failed) continue;
6548
- try {
6549
- const { plugin, generatorContext, generators } = state;
6550
- const { exclude, include, override } = plugin.options;
6551
- const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node;
6552
- const options = generatorContext.resolver.resolveOptions(transformedNode, {
6553
- options: plugin.options,
6554
- exclude,
6555
- include,
6556
- override
6653
+ async function dispatchSchema(state, node) {
6654
+ if (state.failed) return;
6655
+ try {
6656
+ const { plugin, generatorContext, generators } = state;
6657
+ const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node;
6658
+ const { exclude, include, override } = plugin.options;
6659
+ const options = state.optionsAreStatic ? plugin.options : generatorContext.resolver.resolveOptions(transformedNode, {
6660
+ options: plugin.options,
6661
+ exclude,
6662
+ include,
6663
+ override
6664
+ });
6665
+ if (options === null) return;
6666
+ const ctx = {
6667
+ ...generatorContext,
6668
+ options
6669
+ };
6670
+ for (const gen of generators) {
6671
+ if (!gen.schema) continue;
6672
+ const raw = gen.schema(transformedNode, ctx);
6673
+ const applied = applyHookResult({
6674
+ result: isPromise(raw) ? await raw : raw,
6675
+ driver,
6676
+ rendererFactory: resolveRendererFor(gen, state)
6557
6677
  });
6558
- if (options === null) continue;
6559
- const ctx = {
6560
- ...generatorContext,
6561
- options
6562
- };
6563
- for (const gen of generators) {
6564
- if (!gen.schema) continue;
6565
- await applyHookResult(await gen.schema(transformedNode, ctx), driver, resolveRendererFor(gen, state));
6566
- }
6567
- await driver.hooks.emit("kubb:generate:schema", transformedNode, ctx);
6568
- } catch (caughtError) {
6569
- state.failed = true;
6570
- state.error = caughtError;
6678
+ if (isPromise(applied)) await applied;
6571
6679
  }
6680
+ await driver.hooks.emit("kubb:generate:schema", transformedNode, ctx);
6681
+ } catch (caughtError) {
6682
+ state.failed = true;
6683
+ state.error = caughtError;
6572
6684
  }
6573
- schemasProcessed++;
6574
- if (schemasProcessed % 50 === 0) await flushPendingFiles();
6575
6685
  }
6576
- const collectedOperations = [];
6577
- for await (const node of inputStreamNode.operations) {
6578
- collectedOperations.push(node);
6579
- for (const state of states) {
6580
- if (state.failed) continue;
6581
- try {
6582
- const { plugin, generatorContext, generators } = state;
6583
- const { exclude, include, override } = plugin.options;
6584
- const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node;
6585
- const options = generatorContext.resolver.resolveOptions(transformedNode, {
6586
- options: plugin.options,
6587
- exclude,
6588
- include,
6589
- override
6686
+ async function dispatchOperation(state, node) {
6687
+ if (state.failed) return;
6688
+ try {
6689
+ const { plugin, generatorContext, generators } = state;
6690
+ const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node;
6691
+ const { exclude, include, override } = plugin.options;
6692
+ const options = state.optionsAreStatic ? plugin.options : generatorContext.resolver.resolveOptions(transformedNode, {
6693
+ options: plugin.options,
6694
+ exclude,
6695
+ include,
6696
+ override
6697
+ });
6698
+ if (options === null) return;
6699
+ const ctx = {
6700
+ ...generatorContext,
6701
+ options
6702
+ };
6703
+ for (const gen of generators) {
6704
+ if (!gen.operation) continue;
6705
+ const raw = gen.operation(transformedNode, ctx);
6706
+ const applied = applyHookResult({
6707
+ result: isPromise(raw) ? await raw : raw,
6708
+ driver,
6709
+ rendererFactory: resolveRendererFor(gen, state)
6590
6710
  });
6591
- if (options === null) continue;
6592
- const ctx = {
6593
- ...generatorContext,
6594
- options
6595
- };
6596
- for (const gen of generators) {
6597
- if (!gen.operation) continue;
6598
- await applyHookResult(await gen.operation(transformedNode, ctx), driver, resolveRendererFor(gen, state));
6599
- }
6600
- await driver.hooks.emit("kubb:generate:operation", transformedNode, ctx);
6601
- } catch (caughtError) {
6602
- state.failed = true;
6603
- state.error = caughtError;
6711
+ if (isPromise(applied)) await applied;
6604
6712
  }
6713
+ await driver.hooks.emit("kubb:generate:operation", transformedNode, ctx);
6714
+ } catch (caughtError) {
6715
+ state.failed = true;
6716
+ state.error = caughtError;
6605
6717
  }
6606
6718
  }
6719
+ for await (const node of inputStreamNode.schemas) await Promise.all(states.map((state) => dispatchSchema(state, node)));
6720
+ const collectedOperations = [];
6721
+ for await (const node of inputStreamNode.operations) {
6722
+ collectedOperations.push(node);
6723
+ await Promise.all(states.map((state) => dispatchOperation(state, node)));
6724
+ }
6607
6725
  for (const state of states) {
6608
6726
  if (!state.failed) try {
6609
6727
  const { plugin, generatorContext, generators } = state;
@@ -6613,7 +6731,11 @@ async function runPluginStreamHooks(inputStreamNode, entries, driver, hooks, con
6613
6731
  };
6614
6732
  for (const gen of generators) {
6615
6733
  if (!gen.operations) continue;
6616
- await applyHookResult(await gen.operations(collectedOperations, ctx), driver, resolveRendererFor(gen, state));
6734
+ await applyHookResult({
6735
+ result: await gen.operations(collectedOperations, ctx),
6736
+ driver,
6737
+ rendererFactory: resolveRendererFor(gen, state)
6738
+ });
6617
6739
  }
6618
6740
  await driver.hooks.emit("kubb:generate:operations", collectedOperations, ctx);
6619
6741
  } catch (caughtError) {
@@ -6622,12 +6744,12 @@ async function runPluginStreamHooks(inputStreamNode, entries, driver, hooks, con
6622
6744
  }
6623
6745
  const duration = getElapsedMs(state.hrStart);
6624
6746
  pluginTimings.set(state.plugin.name, duration);
6625
- await hooks.emit("kubb:plugin:end", {
6747
+ await driver.hooks.emit("kubb:plugin:end", {
6626
6748
  plugin: state.plugin,
6627
6749
  duration,
6628
6750
  success: !state.failed,
6629
6751
  ...state.failed && state.error ? { error: state.error } : {},
6630
- config,
6752
+ config: driver.config,
6631
6753
  get files() {
6632
6754
  return driver.fileManager.files;
6633
6755
  },
@@ -6637,12 +6759,11 @@ async function runPluginStreamHooks(inputStreamNode, entries, driver, hooks, con
6637
6759
  plugin: state.plugin,
6638
6760
  error: state.error
6639
6761
  });
6640
- await hooks.emit("kubb:debug", {
6762
+ await driver.hooks.emit("kubb:debug", {
6641
6763
  date: /* @__PURE__ */ new Date(),
6642
6764
  logs: [state.failed ? "\u2717 Plugin start failed" : `\u2713 Plugin started successfully (${formatMs(duration)})`]
6643
6765
  });
6644
6766
  }
6645
- await flushPendingFiles();
6646
6767
  }
6647
6768
  async function runPluginAstHooks(plugin, context) {
6648
6769
  var _a2, _b2, _c;
@@ -6668,13 +6789,15 @@ async function runPluginAstHooks(plugin, context) {
6668
6789
  ]);
6669
6790
  const hasOperationBasedIncludes = (_b2 = include == null ? void 0 : include.some(({ type }) => operationFilterTypes.has(type))) != null ? _b2 : false;
6670
6791
  const hasSchemaNameIncludes = (_c = include == null ? void 0 : include.some(({ type }) => type === "schemaName")) != null ? _c : false;
6671
- let allowedSchemaNames;
6672
- if (hasOperationBasedIncludes && !hasSchemaNameIncludes) allowedSchemaNames = collectUsedSchemaNames(inputNode.operations.filter((op) => resolver.resolveOptions(op, {
6673
- options: plugin.options,
6674
- exclude,
6675
- include,
6676
- override
6677
- }) !== null), inputNode.schemas);
6792
+ const allowedSchemaNames = (() => {
6793
+ if (!hasOperationBasedIncludes || hasSchemaNameIncludes) return void 0;
6794
+ return collectUsedSchemaNames(inputNode.operations.filter((op) => resolver.resolveOptions(op, {
6795
+ options: plugin.options,
6796
+ exclude,
6797
+ include,
6798
+ override
6799
+ }) !== null), inputNode.schemas);
6800
+ })();
6678
6801
  await walk(inputNode, {
6679
6802
  depth: "shallow",
6680
6803
  async schema(node) {
@@ -6691,7 +6814,13 @@ async function runPluginAstHooks(plugin, context) {
6691
6814
  ...generatorContext,
6692
6815
  options
6693
6816
  };
6694
- await Promise.all(generators.filter((gen) => gen.schema).map((gen) => Promise.resolve(gen.schema(transformedNode, ctx)).then((result) => applyHookResult(result, driver, resolveRenderer(gen)))));
6817
+ await Promise.all(generators.filter((gen) => gen.schema).map(async (gen) => {
6818
+ return applyHookResult({
6819
+ result: await gen.schema(transformedNode, ctx),
6820
+ driver,
6821
+ rendererFactory: resolveRenderer(gen)
6822
+ });
6823
+ }));
6695
6824
  await driver.hooks.emit("kubb:generate:schema", transformedNode, ctx);
6696
6825
  },
6697
6826
  async operation(node) {
@@ -6702,15 +6831,20 @@ async function runPluginAstHooks(plugin, context) {
6702
6831
  include,
6703
6832
  override
6704
6833
  });
6705
- if (options !== null) {
6706
- collectedOperations.push(transformedNode);
6707
- const ctx = {
6708
- ...generatorContext,
6709
- options
6710
- };
6711
- await Promise.all(generators.filter((gen) => gen.operation).map((gen) => Promise.resolve(gen.operation(transformedNode, ctx)).then((result) => applyHookResult(result, driver, resolveRenderer(gen)))));
6712
- await driver.hooks.emit("kubb:generate:operation", transformedNode, ctx);
6713
- }
6834
+ if (options === null) return;
6835
+ collectedOperations.push(transformedNode);
6836
+ const ctx = {
6837
+ ...generatorContext,
6838
+ options
6839
+ };
6840
+ await Promise.all(generators.filter((gen) => gen.operation).map(async (gen) => {
6841
+ return applyHookResult({
6842
+ result: await gen.operation(transformedNode, ctx),
6843
+ driver,
6844
+ rendererFactory: resolveRenderer(gen)
6845
+ });
6846
+ }));
6847
+ await driver.hooks.emit("kubb:generate:operation", transformedNode, ctx);
6714
6848
  }
6715
6849
  });
6716
6850
  if (collectedOperations.length > 0) {
@@ -6720,85 +6854,130 @@ async function runPluginAstHooks(plugin, context) {
6720
6854
  };
6721
6855
  for (const gen of generators) {
6722
6856
  if (!gen.operations) continue;
6723
- await applyHookResult(await gen.operations(collectedOperations, ctx), driver, resolveRenderer(gen));
6857
+ await applyHookResult({
6858
+ result: await gen.operations(collectedOperations, ctx),
6859
+ driver,
6860
+ rendererFactory: resolveRenderer(gen)
6861
+ });
6724
6862
  }
6725
6863
  await driver.hooks.emit("kubb:generate:operations", collectedOperations, ctx);
6726
6864
  }
6727
6865
  }
6728
6866
  async function safeBuild(setupResult) {
6729
6867
  var _a2, _b2, _c, _d;
6730
- const { driver, hooks, storage } = setupResult;
6731
- const failedPlugins = /* @__PURE__ */ new Set();
6732
- const pluginTimings = /* @__PURE__ */ new Map();
6733
- const config = driver.config;
6734
- const writtenPaths = /* @__PURE__ */ new Set();
6735
- const parsersMap = /* @__PURE__ */ new Map();
6736
- for (const parser of config.parsers) if (parser.extNames) for (const extname of parser.extNames) parsersMap.set(extname, parser);
6737
- const fileProcessor = new FileProcessor();
6738
- async function flushPendingFiles(snapshot) {
6739
- const files = driver.fileManager.files.filter((f) => !writtenPaths.has(f.path) && (!snapshot || !snapshot.has(f.path)));
6740
- if (files.length === 0) return;
6741
- await hooks.emit("kubb:debug", {
6742
- date: /* @__PURE__ */ new Date(),
6743
- logs: [`Writing ${files.length} files...`]
6744
- });
6745
- await hooks.emit("kubb:files:processing:start", { files });
6746
- const stream = fileProcessor.stream(files, {
6747
- parsers: parsersMap,
6748
- extension: config.output.extension
6749
- });
6750
- for await (const { file, source, processed, total, percentage } of stream) {
6751
- await hooks.emit("kubb:file:processing:update", {
6752
- file,
6753
- source,
6754
- processed,
6755
- total,
6756
- percentage,
6757
- config
6868
+ try {
6869
+ var _usingCtx$1 = _usingCtx();
6870
+ _usingCtx$1.u(setupResult);
6871
+ const { driver, hooks, storage } = setupResult;
6872
+ const failedPlugins = /* @__PURE__ */ new Set();
6873
+ const pluginTimings = /* @__PURE__ */ new Map();
6874
+ const config = driver.config;
6875
+ const writtenPaths = /* @__PURE__ */ new Set();
6876
+ const parsersMap = /* @__PURE__ */ new Map();
6877
+ for (const parser of config.parsers) if (parser.extNames) for (const extname of parser.extNames) parsersMap.set(extname, parser);
6878
+ const fileProcessor = new FileProcessor();
6879
+ async function flushPendingFiles() {
6880
+ const files = driver.fileManager.files.filter((f) => !writtenPaths.has(f.path));
6881
+ if (files.length === 0) return;
6882
+ await hooks.emit("kubb:debug", {
6883
+ date: /* @__PURE__ */ new Date(),
6884
+ logs: [`Writing ${files.length} files...`]
6885
+ });
6886
+ await hooks.emit("kubb:files:processing:start", { files });
6887
+ const stream = fileProcessor.stream(files, {
6888
+ parsers: parsersMap,
6889
+ extension: config.output.extension
6890
+ });
6891
+ for (const { file, source, processed, total, percentage } of stream) {
6892
+ await hooks.emit("kubb:file:processing:update", {
6893
+ file,
6894
+ source,
6895
+ processed,
6896
+ total,
6897
+ percentage,
6898
+ config
6899
+ });
6900
+ if (source) await storage.setItem(file.path, source);
6901
+ writtenPaths.add(file.path);
6902
+ }
6903
+ await hooks.emit("kubb:files:processing:end", { files });
6904
+ await hooks.emit("kubb:debug", {
6905
+ date: /* @__PURE__ */ new Date(),
6906
+ logs: [`\u2713 File write process completed for ${files.length} files`]
6758
6907
  });
6759
- if (source) await storage.setItem(file.path, source);
6760
- writtenPaths.add(file.path);
6761
6908
  }
6762
- await hooks.emit("kubb:files:processing:end", { files });
6763
- await hooks.emit("kubb:debug", {
6764
- date: /* @__PURE__ */ new Date(),
6765
- logs: [`\u2713 File write process completed for ${files.length} files`]
6766
- });
6767
- }
6768
- try {
6769
- await driver.emitSetupHooks();
6770
- if (driver.adapter && (driver.inputNode || driver.inputStreamNode)) await hooks.emit("kubb:build:start", {
6771
- config,
6772
- adapter: driver.adapter,
6773
- inputNode: (_b2 = driver.inputNode) != null ? _b2 : {
6774
- kind: "Input",
6775
- schemas: [],
6776
- operations: [],
6777
- meta: (_a2 = driver.inputStreamNode) == null ? void 0 : _a2.meta
6778
- },
6779
- getPlugin: driver.getPlugin.bind(driver),
6780
- get files() {
6781
- return driver.fileManager.files;
6782
- },
6783
- upsertFile: (...files2) => driver.fileManager.upsert(...files2)
6784
- });
6785
- const inputStreamNode = driver.inputStreamNode;
6786
- if (inputStreamNode) {
6787
- const streamPluginEntries = [];
6788
- for (const plugin of driver.plugins.values()) {
6909
+ try {
6910
+ await driver.emitSetupHooks();
6911
+ if (driver.adapter && (driver.inputNode || driver.inputStreamNode)) await hooks.emit("kubb:build:start", {
6912
+ config,
6913
+ adapter: driver.adapter,
6914
+ inputNode: (_b2 = driver.inputNode) != null ? _b2 : {
6915
+ kind: "Input",
6916
+ schemas: [],
6917
+ operations: [],
6918
+ meta: (_a2 = driver.inputStreamNode) == null ? void 0 : _a2.meta
6919
+ },
6920
+ getPlugin: driver.getPlugin.bind(driver),
6921
+ get files() {
6922
+ return driver.fileManager.files;
6923
+ },
6924
+ upsertFile: (...files2) => driver.fileManager.upsert(...files2)
6925
+ });
6926
+ if (driver.inputStreamNode) {
6927
+ const streamPluginEntries = [];
6928
+ for (const plugin of driver.plugins.values()) {
6929
+ const context = driver.getContext(plugin);
6930
+ const hrStart = process.hrtime();
6931
+ await hooks.emit("kubb:plugin:start", { plugin });
6932
+ await hooks.emit("kubb:debug", {
6933
+ date: /* @__PURE__ */ new Date(),
6934
+ logs: ["Starting plugin...", ` \u2022 Plugin Name: ${plugin.name}`]
6935
+ });
6936
+ if (((_c = plugin.generators) == null ? void 0 : _c.length) || driver.hasRegisteredGenerators(plugin.name)) {
6937
+ streamPluginEntries.push({
6938
+ plugin,
6939
+ context,
6940
+ hrStart
6941
+ });
6942
+ continue;
6943
+ }
6944
+ const duration = getElapsedMs(hrStart);
6945
+ pluginTimings.set(plugin.name, duration);
6946
+ await hooks.emit("kubb:plugin:end", {
6947
+ plugin,
6948
+ duration,
6949
+ success: true,
6950
+ config,
6951
+ get files() {
6952
+ return driver.fileManager.files;
6953
+ },
6954
+ upsertFile: (...files2) => driver.fileManager.upsert(...files2)
6955
+ });
6956
+ await hooks.emit("kubb:debug", {
6957
+ date: /* @__PURE__ */ new Date(),
6958
+ logs: [`\u2713 Plugin started successfully (${formatMs(duration)})`]
6959
+ });
6960
+ }
6961
+ if (streamPluginEntries.length > 0) {
6962
+ await runPluginStreamHooks({
6963
+ entries: streamPluginEntries,
6964
+ driver,
6965
+ pluginTimings,
6966
+ failedPlugins
6967
+ });
6968
+ await flushPendingFiles();
6969
+ }
6970
+ } else for (const plugin of driver.plugins.values()) {
6789
6971
  const context = driver.getContext(plugin);
6790
6972
  const hrStart = process.hrtime();
6791
- await hooks.emit("kubb:plugin:start", { plugin });
6792
- await hooks.emit("kubb:debug", {
6793
- date: /* @__PURE__ */ new Date(),
6794
- logs: ["Starting plugin...", ` \u2022 Plugin Name: ${plugin.name}`]
6795
- });
6796
- if (((_c = plugin.generators) == null ? void 0 : _c.length) || driver.hasRegisteredGenerators(plugin.name)) streamPluginEntries.push({
6797
- plugin,
6798
- context,
6799
- hrStart
6800
- });
6801
- else {
6973
+ try {
6974
+ const timestamp = /* @__PURE__ */ new Date();
6975
+ await hooks.emit("kubb:plugin:start", { plugin });
6976
+ await hooks.emit("kubb:debug", {
6977
+ date: timestamp,
6978
+ logs: ["Starting plugin...", ` \u2022 Plugin Name: ${plugin.name}`]
6979
+ });
6980
+ if (((_d = plugin.generators) == null ? void 0 : _d.length) || driver.hasRegisteredGenerators(plugin.name)) await runPluginAstHooks(plugin, context);
6802
6981
  const duration = getElapsedMs(hrStart);
6803
6982
  pluginTimings.set(plugin.name, duration);
6804
6983
  await hooks.emit("kubb:plugin:end", {
@@ -6815,100 +6994,73 @@ async function safeBuild(setupResult) {
6815
6994
  date: /* @__PURE__ */ new Date(),
6816
6995
  logs: [`\u2713 Plugin started successfully (${formatMs(duration)})`]
6817
6996
  });
6997
+ } catch (caughtError) {
6998
+ const error = caughtError;
6999
+ const errorTimestamp = /* @__PURE__ */ new Date();
7000
+ const duration = getElapsedMs(hrStart);
7001
+ await hooks.emit("kubb:plugin:end", {
7002
+ plugin,
7003
+ duration,
7004
+ success: false,
7005
+ error,
7006
+ config,
7007
+ get files() {
7008
+ return driver.fileManager.files;
7009
+ },
7010
+ upsertFile: (...files2) => driver.fileManager.upsert(...files2)
7011
+ });
7012
+ await hooks.emit("kubb:debug", {
7013
+ date: errorTimestamp,
7014
+ logs: [
7015
+ "\u2717 Plugin start failed",
7016
+ ` \u2022 Plugin Name: ${plugin.name}`,
7017
+ ` \u2022 Error: ${error.constructor.name} - ${error.message}`,
7018
+ " \u2022 Stack Trace:",
7019
+ error.stack || "No stack trace available"
7020
+ ]
7021
+ });
7022
+ failedPlugins.add({
7023
+ plugin,
7024
+ error
7025
+ });
6818
7026
  }
7027
+ await flushPendingFiles();
6819
7028
  }
6820
- if (streamPluginEntries.length > 0) await runPluginStreamHooks(inputStreamNode, streamPluginEntries, driver, hooks, config, pluginTimings, failedPlugins, flushPendingFiles);
6821
- } else for (const plugin of driver.plugins.values()) {
6822
- const context = driver.getContext(plugin);
6823
- const hrStart = process.hrtime();
6824
- try {
6825
- const timestamp = /* @__PURE__ */ new Date();
6826
- await hooks.emit("kubb:plugin:start", { plugin });
6827
- await hooks.emit("kubb:debug", {
6828
- date: timestamp,
6829
- logs: ["Starting plugin...", ` \u2022 Plugin Name: ${plugin.name}`]
6830
- });
6831
- if (((_d = plugin.generators) == null ? void 0 : _d.length) || driver.hasRegisteredGenerators(plugin.name)) await runPluginAstHooks(plugin, context);
6832
- const duration = getElapsedMs(hrStart);
6833
- pluginTimings.set(plugin.name, duration);
6834
- await hooks.emit("kubb:plugin:end", {
6835
- plugin,
6836
- duration,
6837
- success: true,
6838
- config,
6839
- get files() {
6840
- return driver.fileManager.files;
6841
- },
6842
- upsertFile: (...files2) => driver.fileManager.upsert(...files2)
6843
- });
6844
- await hooks.emit("kubb:debug", {
6845
- date: /* @__PURE__ */ new Date(),
6846
- logs: [`\u2713 Plugin started successfully (${formatMs(duration)})`]
6847
- });
6848
- } catch (caughtError) {
6849
- const error = caughtError;
6850
- const errorTimestamp = /* @__PURE__ */ new Date();
6851
- const duration = getElapsedMs(hrStart);
6852
- await hooks.emit("kubb:plugin:end", {
6853
- plugin,
6854
- duration,
6855
- success: false,
6856
- error,
6857
- config,
6858
- get files() {
6859
- return driver.fileManager.files;
6860
- },
6861
- upsertFile: (...files2) => driver.fileManager.upsert(...files2)
6862
- });
6863
- await hooks.emit("kubb:debug", {
6864
- date: errorTimestamp,
6865
- logs: [
6866
- "\u2717 Plugin start failed",
6867
- ` \u2022 Plugin Name: ${plugin.name}`,
6868
- ` \u2022 Error: ${error.constructor.name} - ${error.message}`,
6869
- " \u2022 Stack Trace:",
6870
- error.stack || "No stack trace available"
6871
- ]
6872
- });
6873
- failedPlugins.add({
6874
- plugin,
6875
- error
6876
- });
6877
- }
7029
+ await hooks.emit("kubb:plugins:end", {
7030
+ config,
7031
+ get files() {
7032
+ return driver.fileManager.files;
7033
+ },
7034
+ upsertFile: (...files2) => driver.fileManager.upsert(...files2)
7035
+ });
6878
7036
  await flushPendingFiles();
7037
+ const files = driver.fileManager.files;
7038
+ await hooks.emit("kubb:build:end", {
7039
+ files,
7040
+ config,
7041
+ outputDir: resolve(config.root, config.output.path)
7042
+ });
7043
+ return {
7044
+ failedPlugins,
7045
+ files,
7046
+ driver,
7047
+ pluginTimings,
7048
+ storage
7049
+ };
7050
+ } catch (error) {
7051
+ return {
7052
+ failedPlugins,
7053
+ files: [],
7054
+ driver,
7055
+ pluginTimings,
7056
+ error,
7057
+ storage
7058
+ };
6879
7059
  }
6880
- await hooks.emit("kubb:plugins:end", {
6881
- config,
6882
- get files() {
6883
- return driver.fileManager.files;
6884
- },
6885
- upsertFile: (...files2) => driver.fileManager.upsert(...files2)
6886
- });
6887
- await flushPendingFiles();
6888
- const files = driver.fileManager.files;
6889
- await hooks.emit("kubb:build:end", {
6890
- files,
6891
- config,
6892
- outputDir: resolve(config.root, config.output.path)
6893
- });
6894
- return {
6895
- failedPlugins,
6896
- files,
6897
- driver,
6898
- pluginTimings,
6899
- storage
6900
- };
6901
- } catch (error) {
6902
- return {
6903
- failedPlugins,
6904
- files: [],
6905
- driver,
6906
- pluginTimings,
6907
- error,
6908
- storage
6909
- };
7060
+ } catch (_) {
7061
+ _usingCtx$1.e = _;
6910
7062
  } finally {
6911
- setupResult.dispose();
7063
+ _usingCtx$1.d();
6912
7064
  }
6913
7065
  }
6914
7066
  async function build(setupResult) {
@@ -7020,7 +7172,7 @@ const memoryStorage = createStorage(() => {
7020
7172
  };
7021
7173
  });
7022
7174
 
7023
- var version = "5.0.0-beta.17";
7175
+ var version = "5.0.0-beta.19";
7024
7176
 
7025
7177
  function isCommandMessage(msg) {
7026
7178
  return msg.type === "command";
@@ -7031,9 +7183,6 @@ function isPongMessage(msg) {
7031
7183
  function isDisconnectMessage(msg) {
7032
7184
  return msg.type === "disconnect";
7033
7185
  }
7034
- function isPublishCommandMessage(msg) {
7035
- return msg.type === "command" && msg.command === "publish";
7036
- }
7037
7186
 
7038
7187
  function getStorage() {
7039
7188
  return useStorage("kubb");
@@ -7279,44 +7428,6 @@ async function mergePlugins(diskPlugins, studioPlugins) {
7279
7428
  return [...mergedDisk, ...studioOnly];
7280
7429
  }
7281
7430
 
7282
- async function publish({ command, outputPath, root, hooks }) {
7283
- var _a, _b, _c, _d;
7284
- const resolvedOutputPath = path$1.isAbsolute(outputPath) ? outputPath : path$1.resolve(root, outputPath);
7285
- const [cmd, ...args] = tokenize(command);
7286
- if (!cmd) {
7287
- throw new Error(`[plugin-publish] Invalid publish command: "${command}"`);
7288
- }
7289
- const commandWithArgs = args.length ? `${cmd} ${args.join(" ")}` : cmd;
7290
- await hooks.emit("kubb:info", { message: `[publish] Running "${commandWithArgs}" in "${resolvedOutputPath}"` });
7291
- const startTime = Date.now();
7292
- let exitCode = null;
7293
- try {
7294
- const proc = x(cmd, args, {
7295
- nodeOptions: { cwd: resolvedOutputPath }
7296
- });
7297
- for await (const line of proc) {
7298
- if (line.trim()) {
7299
- await hooks.emit("kubb:info", { message: line.trim() });
7300
- }
7301
- }
7302
- const result = await proc;
7303
- exitCode = (_a = result.exitCode) != null ? _a : null;
7304
- } catch (err) {
7305
- const message = (_d = (_c = (_b = err == null ? void 0 : err.stderr) == null ? void 0 : _b.trim()) != null ? _c : err == null ? void 0 : err.message) != null ? _d : String(err);
7306
- const error = new Error(`[publish] Failed to run "${commandWithArgs}": ${message}`);
7307
- error.cause = err;
7308
- await hooks.emit("kubb:error", { error });
7309
- throw error;
7310
- }
7311
- if (exitCode !== 0) {
7312
- const error = new Error(`[publish] "${commandWithArgs}" exited with code ${exitCode}`);
7313
- await hooks.emit("kubb:error", { error });
7314
- throw error;
7315
- }
7316
- const duration = Date.now() - startTime;
7317
- await hooks.emit("kubb:success", { message: `[publish] Published successfully in ${duration}ms` });
7318
- }
7319
-
7320
7431
  function setupHookListener(hooks, root) {
7321
7432
  hooks.on("kubb:hook:start", async (ctx) => {
7322
7433
  const { id, command, args } = ctx;
@@ -7387,11 +7498,11 @@ function sendAgentMessage(ws, message) {
7387
7498
  throw new Error("Failed to send message to Kubb Studio", { cause: error });
7388
7499
  }
7389
7500
  }
7390
- function setupEventsStream(ws, hooks, getSource) {
7501
+ function setupEventsStream(ws, hooks) {
7391
7502
  function sendDataMessage(payload) {
7392
7503
  sendAgentMessage(ws, {
7393
7504
  type: "data",
7394
- payload: { ...payload, source: getSource == null ? void 0 : getSource() }
7505
+ payload
7395
7506
  });
7396
7507
  }
7397
7508
  hooks.on("kubb:plugin:start", (ctx) => {
@@ -7506,7 +7617,6 @@ async function connectToStudio(options) {
7506
7617
  resolvedConfigPath,
7507
7618
  allowAll,
7508
7619
  allowWrite,
7509
- allowPublish,
7510
7620
  root,
7511
7621
  retryInterval,
7512
7622
  heartbeatInterval = 3e4,
@@ -7514,7 +7624,6 @@ async function connectToStudio(options) {
7514
7624
  nitro
7515
7625
  } = options;
7516
7626
  const hooks = new AsyncEventEmitter();
7517
- let currentSource;
7518
7627
  async function reconnect() {
7519
7628
  logger.info(`Retrying connection in ${formatMs$1(retryInterval)} to Kubb Studio ...`);
7520
7629
  setTimeout(() => connectToStudio({ ...options, initialSession: void 0 }), retryInterval);
@@ -7529,7 +7638,6 @@ async function connectToStudio(options) {
7529
7638
  const maskedSessionId = maskString(sessionId);
7530
7639
  const effectiveAllowAll = isSandbox ? false : allowAll;
7531
7640
  const effectiveWrite = isSandbox ? false : allowWrite;
7532
- const effectivePublish = isSandbox ? false : allowPublish;
7533
7641
  let serverDisconnected = false;
7534
7642
  let heartbeatTimer;
7535
7643
  async function cleanup(reason = "cleanup") {
@@ -7541,6 +7649,7 @@ async function connectToStudio(options) {
7541
7649
  ws.removeEventListener("open", onOpen);
7542
7650
  ws.removeEventListener("close", onClose);
7543
7651
  ws.removeEventListener("error", onError);
7652
+ ws.removeEventListener("message", onMessage);
7544
7653
  } catch (_error) {
7545
7654
  }
7546
7655
  }
@@ -7573,9 +7682,9 @@ async function connectToStudio(options) {
7573
7682
  });
7574
7683
  });
7575
7684
  heartbeatTimer = setInterval(() => sendAgentMessage(ws, { type: "ping" }), heartbeatInterval);
7576
- setupEventsStream(ws, hooks, () => currentSource);
7577
- ws.addEventListener("message", async (message) => {
7578
- var _a2, _b, _c, _d, _e, _f;
7685
+ setupEventsStream(ws, hooks);
7686
+ const onMessage = async (message) => {
7687
+ var _a2, _b, _c, _d;
7579
7688
  try {
7580
7689
  const data = JSON.parse(message.data);
7581
7690
  logger.info(`[${maskedSessionId}] Received "${data.type}" from Studio`);
@@ -7597,7 +7706,6 @@ async function connectToStudio(options) {
7597
7706
  }
7598
7707
  if (isCommandMessage(data)) {
7599
7708
  if (data.command === "generate") {
7600
- currentSource = "generate";
7601
7709
  const config = await loadConfig(resolvedConfigPath);
7602
7710
  const storedConfig = data.payload ? null : await getLatestStudioConfigFromStorage({ sessionId }).catch(() => null);
7603
7711
  const patch = (_b = (_a2 = data.payload) != null ? _a2 : storedConfig) != null ? _b : void 0;
@@ -7620,7 +7728,7 @@ async function connectToStudio(options) {
7620
7728
  }
7621
7729
  const generationHooks = new AsyncEventEmitter();
7622
7730
  setupHookListener(generationHooks, root);
7623
- setupEventsStream(ws, generationHooks, () => currentSource);
7731
+ setupEventsStream(ws, generationHooks);
7624
7732
  await generate({
7625
7733
  config: {
7626
7734
  ...config,
@@ -7639,7 +7747,6 @@ async function connectToStudio(options) {
7639
7747
  hooks: generationHooks
7640
7748
  });
7641
7749
  logger.success(`[${maskedSessionId}] Completed "${data.type}" from Studio`);
7642
- currentSource = void 0;
7643
7750
  return;
7644
7751
  }
7645
7752
  if (data.command === "connect") {
@@ -7651,8 +7758,7 @@ async function connectToStudio(options) {
7651
7758
  configPath,
7652
7759
  permissions: {
7653
7760
  allowAll: effectiveAllowAll,
7654
- allowWrite: effectiveWrite,
7655
- allowPublish: effectivePublish
7761
+ allowWrite: effectiveWrite
7656
7762
  },
7657
7763
  config: {
7658
7764
  plugins: config.plugins.map((plugin) => ({
@@ -7665,30 +7771,13 @@ async function connectToStudio(options) {
7665
7771
  logger.success(`[${maskedSessionId}] Completed "${data.type}" from Studio`);
7666
7772
  return;
7667
7773
  }
7668
- if (isPublishCommandMessage(data)) {
7669
- if (!effectivePublish) {
7670
- logger.warn(`[${maskedSessionId}] Publish command rejected \u2014 KUBB_AGENT_ALLOW_PUBLISH is not enabled`);
7671
- return;
7672
- }
7673
- currentSource = "publish";
7674
- const config = await loadConfig(resolvedConfigPath);
7675
- const resolvedCommand = (_e = (_d = data.payload.command) != null ? _d : process.env.KUBB_AGENT_PUBLISH_COMMAND) != null ? _e : "npm publish";
7676
- await publish({
7677
- command: resolvedCommand,
7678
- outputPath: config.output.path,
7679
- root,
7680
- hooks
7681
- });
7682
- logger.success(`[${maskedSessionId}] Completed "${data.command}" from Studio`);
7683
- currentSource = void 0;
7684
- return;
7685
- }
7686
7774
  }
7687
7775
  logger.warn(`[${maskedSessionId}] Unknown message type from Kubb Studio: ${message.data}`);
7688
7776
  } catch (error) {
7689
- logger.error(`[${maskedSessionId}] [unhandledRejection] ${(_f = error == null ? void 0 : error.message) != null ? _f : error}`);
7777
+ logger.error(`[${maskedSessionId}] [unhandledRejection] ${(_d = error == null ? void 0 : error.message) != null ? _d : error}`);
7690
7778
  }
7691
- });
7779
+ };
7780
+ ws.addEventListener("message", onMessage);
7692
7781
  } catch (error) {
7693
7782
  throw new Error(`[unhandledRejection] ${(_a = error == null ? void 0 : error.message) != null ? _a : error}`, {
7694
7783
  cause: error
@@ -7718,7 +7807,6 @@ function resolveStudioRuntimeConfig(env = process$1.env, cwd = process$1.cwd())
7718
7807
  root,
7719
7808
  allowAll,
7720
7809
  allowWrite: allowAll || parseBooleanEnv(env.KUBB_AGENT_ALLOW_WRITE),
7721
- allowPublish: allowAll || parseBooleanEnv(env.KUBB_AGENT_ALLOW_PUBLISH),
7722
7810
  poolSize: parsePositiveIntegerEnv(env.KUBB_AGENT_POOL_SIZE, agentDefaults.poolSize),
7723
7811
  hasSecret: Boolean(env.KUBB_AGENT_SECRET)
7724
7812
  };
@@ -7728,7 +7816,7 @@ function getErrorMessage(error) {
7728
7816
  return error instanceof Error ? error.message : String(error);
7729
7817
  }
7730
7818
  const _zcw7I4pYH8OiCfaDcjy_x7I6IH1tLDQR3W_yRZgP6E = defineNitroPlugin(async (nitro) => {
7731
- const { studioUrl, token, configPath, resolvedConfigPath, retryInterval, heartbeatInterval, root, allowAll, allowWrite, allowPublish, poolSize, hasSecret } = resolveStudioRuntimeConfig(process$1.env);
7819
+ const { studioUrl, token, configPath, resolvedConfigPath, retryInterval, heartbeatInterval, root, allowAll, allowWrite, poolSize, hasSecret } = resolveStudioRuntimeConfig(process$1.env);
7732
7820
  if (!token) {
7733
7821
  logger.warn("KUBB_AGENT_TOKEN not set", "cannot authenticate with studio");
7734
7822
  return null;
@@ -7747,7 +7835,6 @@ const _zcw7I4pYH8OiCfaDcjy_x7I6IH1tLDQR3W_yRZgP6E = defineNitroPlugin(async (nit
7747
7835
  resolvedConfigPath,
7748
7836
  allowAll,
7749
7837
  allowWrite,
7750
- allowPublish,
7751
7838
  root,
7752
7839
  retryInterval,
7753
7840
  heartbeatInterval,