@hey-api/shared 0.4.8 → 0.5.0

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.mjs CHANGED
@@ -330,6 +330,15 @@ function isPlainObject(value) {
330
330
  const proto = Object.getPrototypeOf(value);
331
331
  return proto === Object.prototype || proto === null;
332
332
  }
333
+ function deepMerge(target, source) {
334
+ if (isPlainObject(target) && isPlainObject(source)) {
335
+ const result = { ...target };
336
+ for (const key of Object.keys(source)) if (key in target) result[key] = deepMerge(target[key], source[key]);
337
+ else result[key] = source[key];
338
+ return result;
339
+ }
340
+ return source;
341
+ }
333
342
  //#endregion
334
343
  //#region src/normalize/opaque.ts
335
344
  const OPAQUE = Symbol("opaque");
@@ -421,15 +430,20 @@ function resolveTable(input, table, { ancestor = {}, context = {}, resolvedCasca
421
430
  }
422
431
  function collectDeps(spec, resolved, deps) {
423
432
  const { $dependencies } = spec;
424
- if ($dependencies) for (const key of $dependencies) {
425
- const value = resolved[key];
426
- if (value && typeof value === "string") deps.add(value);
427
- }
433
+ if ($dependencies) for (const key of $dependencies) addDependencyValue(resolved[key], deps);
428
434
  for (const [key, specVal] of Object.entries(spec)) {
429
435
  if (key.startsWith("$")) continue;
430
436
  if (isPlainObject(specVal) && isPlainObject(resolved[key])) collectDeps(specVal, resolved[key], deps);
431
437
  }
432
438
  }
439
+ function addDependencyValue(value, deps) {
440
+ if (!value) return;
441
+ if (typeof value === "string") {
442
+ deps.add(value);
443
+ return;
444
+ }
445
+ if (Array.isArray(value)) for (const item of value) addDependencyValue(item, deps);
446
+ }
433
447
  function resolveField(defaultVal, currentVal, key, { ancestor, context, resolvedCascade, specAncestor }) {
434
448
  if (isCoercer(defaultVal)) return defaultVal[COERCER](currentVal, context);
435
449
  if (isPlainObject(defaultVal)) {
@@ -975,26 +989,26 @@ const graph = {
975
989
  };
976
990
  //#endregion
977
991
  //#region src/ir/parameter.ts
978
- const getPaginationSchema = ({ context, parameter }) => {
992
+ function getPaginationSchema({ context, parameter }) {
979
993
  if (!parameter.pagination) return;
980
994
  if (parameter.pagination === true) return parameter.schema;
981
995
  let schema = parameter.schema;
982
996
  if (schema.$ref) schema = context.resolveIrRef(schema.$ref);
983
997
  return schema.properties[parameter.pagination];
984
- };
985
- const hasParameterGroupObjectRequired = (parameterGroup) => {
998
+ }
999
+ function hasParameterGroupObjectRequired(parameterGroup) {
986
1000
  for (const name in parameterGroup) if (parameterGroup[name].required) return true;
987
1001
  return false;
988
- };
989
- const hasParametersObjectRequired = (parameters) => {
1002
+ }
1003
+ function hasParametersObjectRequired(parameters) {
990
1004
  if (!parameters) return false;
991
1005
  if (hasParameterGroupObjectRequired(parameters.cookie)) return true;
992
1006
  if (hasParameterGroupObjectRequired(parameters.header)) return true;
993
1007
  if (hasParameterGroupObjectRequired(parameters.path)) return true;
994
1008
  if (hasParameterGroupObjectRequired(parameters.query)) return true;
995
1009
  return false;
996
- };
997
- const parameterWithPagination = ({ context, parameters }) => {
1010
+ }
1011
+ function parameterWithPagination({ context, parameters }) {
998
1012
  if (!parameters) return;
999
1013
  for (const name in parameters.cookie) {
1000
1014
  const parameter = parameters.cookie[name];
@@ -1040,7 +1054,7 @@ const parameterWithPagination = ({ context, parameters }) => {
1040
1054
  })
1041
1055
  };
1042
1056
  }
1043
- };
1057
+ }
1044
1058
  //#endregion
1045
1059
  //#region src/ir/schema.ts
1046
1060
  /**
@@ -1114,13 +1128,15 @@ function addItemsToSchema({ items, logicalOperator = "or", mutateSchemaOneItem =
1114
1128
  }
1115
1129
  //#endregion
1116
1130
  //#region src/ir/operation.ts
1117
- const hasOperationDataRequired = (operation) => {
1131
+ function hasOperationDataRequired(operation) {
1118
1132
  if (hasParametersObjectRequired(operation.parameters)) return true;
1119
1133
  if (operation.body?.required) return true;
1120
1134
  return false;
1121
- };
1122
- const createOperationKey = ({ method, path }) => `${method.toUpperCase()} ${path}`;
1123
- const operationPagination = ({ context, operation }) => {
1135
+ }
1136
+ function createOperationKey({ method, path }) {
1137
+ return `${method.toUpperCase()} ${path}`;
1138
+ }
1139
+ function operationPagination({ context, operation }) {
1124
1140
  const body = operation.body;
1125
1141
  if (!body || !body.pagination) return parameterWithPagination({
1126
1142
  context,
@@ -1143,8 +1159,8 @@ const operationPagination = ({ context, operation }) => {
1143
1159
  name: body.pagination,
1144
1160
  schema: paginationProp
1145
1161
  };
1146
- };
1147
- const statusCodeToGroup = ({ statusCode }) => {
1162
+ }
1163
+ function statusCodeToGroup({ statusCode }) {
1148
1164
  switch (statusCode) {
1149
1165
  case "1XX": return "1XX";
1150
1166
  case "2XX": return "2XX";
@@ -1154,8 +1170,8 @@ const statusCodeToGroup = ({ statusCode }) => {
1154
1170
  case "default": return "default";
1155
1171
  default: return `${statusCode[0]}XX`;
1156
1172
  }
1157
- };
1158
- const operationResponsesMap = (operation) => {
1173
+ }
1174
+ function operationResponsesMap(operation) {
1159
1175
  const result = {};
1160
1176
  if (!operation.responses) return result;
1161
1177
  const errors = {
@@ -1227,7 +1243,7 @@ const operationResponsesMap = (operation) => {
1227
1243
  if (Object.keys(responseUnion).length && responseUnion.type !== "unknown") result.response = responseUnion;
1228
1244
  }
1229
1245
  return result;
1230
- };
1246
+ }
1231
1247
  //#endregion
1232
1248
  //#region src/utils/naming/naming.ts
1233
1249
  const uppercaseRegExp = /[\p{Lu}]/u;
@@ -1985,13 +2001,6 @@ var SymbolFactory = class {
1985
2001
  }
1986
2002
  return result;
1987
2003
  }
1988
- external(resource, meta = {}) {
1989
- return this.project.symbols.reference({
1990
- ...meta,
1991
- category: "external",
1992
- resource
1993
- });
1994
- }
1995
2004
  isRegistered(identifier) {
1996
2005
  return this.project.symbols.isRegistered(identifier);
1997
2006
  }
@@ -2038,12 +2047,12 @@ var SymbolFactory = class {
2038
2047
  //#endregion
2039
2048
  //#region src/plugins/shared/utils/instance.ts
2040
2049
  function defaultGetFilePath(symbol) {
2041
- if (!symbol.meta?.pluginName || typeof symbol.meta.pluginName !== "string") return;
2042
- if (symbol.meta.pluginName.startsWith("@hey-api/client-")) return "client";
2043
- if (symbol.meta.pluginName === "@hey-api/typescript") return "types";
2044
- if (symbol.meta.pluginName === "@hey-api/python-sdk") return "sdk";
2045
- if (symbol.meta.pluginName.startsWith("@hey-api/")) return symbol.meta.pluginName.split("/")[1];
2046
- return symbol.meta.pluginName;
2050
+ if (!symbol.meta?.plugin || typeof symbol.meta.plugin !== "string") return;
2051
+ if (symbol.meta.plugin.startsWith("@hey-api/client-")) return "client";
2052
+ if (symbol.meta.plugin === "@hey-api/typescript") return "types";
2053
+ if (symbol.meta.plugin === "@hey-api/python-sdk") return "sdk";
2054
+ if (symbol.meta.plugin.startsWith("@hey-api/")) return symbol.meta.plugin.split("/")[1];
2055
+ return symbol.meta.plugin;
2047
2056
  }
2048
2057
  const defaultGetKind = (operation) => {
2049
2058
  switch (operation.method) {
@@ -2063,6 +2072,8 @@ var PluginInstance = class {
2063
2072
  eventHooks;
2064
2073
  gen;
2065
2074
  handler;
2075
+ /** External symbols imported from other modules. */
2076
+ imports;
2066
2077
  name;
2067
2078
  /**
2068
2079
  * The package metadata and utilities for the current context, constructed
@@ -2073,12 +2084,10 @@ var PluginInstance = class {
2073
2084
  package;
2074
2085
  /** Factory for creating and managing symbols. */
2075
2086
  symbolFactory;
2076
- /** Symbols declared in the plugin config. */
2077
- symbols;
2078
- external;
2087
+ /** Metadata merged into every symbol this plugin creates. */
2088
+ symbolMeta;
2079
2089
  isSymbolRegistered;
2080
2090
  querySymbol;
2081
- querySymbols;
2082
2091
  referenceSymbol;
2083
2092
  constructor(props) {
2084
2093
  this.api = props.api ?? {};
@@ -2089,18 +2098,21 @@ var PluginInstance = class {
2089
2098
  this.handler = props.handler;
2090
2099
  this.name = props.name;
2091
2100
  this.package = props.context.package;
2092
- this.eventHooks = SymbolFactory.buildEventHooks([this.config["~hooks"]?.events, this.context.config.parser.hooks.events]);
2101
+ this.symbolMeta = props.symbolMeta;
2102
+ this.eventHooks = SymbolFactory.buildEventHooks([
2103
+ this.config["~hooks"]?.events,
2104
+ this.config.$hooks?.events,
2105
+ this.context.config.parser.hooks.events
2106
+ ]);
2093
2107
  this.symbolFactory = new SymbolFactory({
2094
2108
  eventHooks: this.eventHooks,
2095
2109
  plugin: this,
2096
2110
  project: this.gen
2097
2111
  });
2098
- this.external = this.symbolFactory.external.bind(this.symbolFactory);
2099
2112
  this.isSymbolRegistered = this.symbolFactory.isRegistered.bind(this.symbolFactory);
2100
2113
  this.querySymbol = this.symbolFactory.query.bind(this.symbolFactory);
2101
- this.querySymbols = this.symbolFactory.queryAll.bind(this.symbolFactory);
2102
2114
  this.referenceSymbol = this.symbolFactory.reference.bind(this.symbolFactory);
2103
- this.symbols = props.symbols?.(this) ?? {};
2115
+ this.imports = props.imports?.(this) ?? {};
2104
2116
  }
2105
2117
  forEach(...args) {
2106
2118
  if (!this.context.graph) throw new Error("No graph available in context");
@@ -2194,8 +2206,10 @@ var PluginInstance = class {
2194
2206
  getHooks(selector, ...customHooks) {
2195
2207
  const result = [];
2196
2208
  for (const hook of customHooks) if (hook) result.push(hook);
2197
- const local = selector(this.config["~hooks"] ?? {});
2209
+ const local = selector(this.config.$hooks ?? {});
2198
2210
  if (local) result.push(local);
2211
+ const localDeprecated = selector(this.config["~hooks"] ?? {});
2212
+ if (localDeprecated) result.push(localDeprecated);
2199
2213
  const global = selector(this.context.config.parser.hooks);
2200
2214
  if (global) result.push(global);
2201
2215
  return result;
@@ -2257,12 +2271,6 @@ var PluginInstance = class {
2257
2271
  return result;
2258
2272
  }
2259
2273
  /**
2260
- * Alias for `symbol()` method with single argument.
2261
- */
2262
- registerSymbol(symbol) {
2263
- return this.symbol(symbol.name, symbol);
2264
- }
2265
- /**
2266
2274
  * Executes plugin's handler function.
2267
2275
  */
2268
2276
  async run() {
@@ -2270,15 +2278,25 @@ var PluginInstance = class {
2270
2278
  await this.handler({ plugin: this });
2271
2279
  for (const hook of this.eventHooks["plugin:handler:after"]) hook({ plugin: this });
2272
2280
  }
2273
- symbol(name, symbol = {}) {
2281
+ symbol(nameOrSymbol, symbolArg = {}) {
2282
+ let name;
2283
+ let symbol;
2284
+ if (typeof nameOrSymbol === "object") {
2285
+ const { name: _name, ...rest } = nameOrSymbol;
2286
+ name = _name;
2287
+ symbol = rest;
2288
+ } else {
2289
+ name = nameOrSymbol;
2290
+ symbol = symbolArg;
2291
+ }
2292
+ const meta = !symbol.external && this.symbolMeta ? this.symbolMeta(symbol) : {};
2293
+ Object.assign(meta, symbol.meta);
2294
+ if (!symbol.external) meta.plugin = path.isAbsolute(this.name) ? "custom" : this.name;
2274
2295
  return this.symbolFactory.register(name, {
2275
2296
  ...symbol,
2276
2297
  getExportFromFilePath: symbol.getExportFromFilePath ?? this.getSymbolExportFromFilePath.bind(this),
2277
2298
  getFilePath: symbol.getFilePath ?? this.getSymbolFilePath.bind(this),
2278
- meta: {
2279
- ...symbol.external ? {} : { pluginName: path.isAbsolute(this.name) ? "custom" : this.name },
2280
- ...symbol.meta
2281
- }
2299
+ meta
2282
2300
  });
2283
2301
  }
2284
2302
  /**
@@ -2289,7 +2307,7 @@ var PluginInstance = class {
2289
2307
  symbolOnce(name, symbol = {}) {
2290
2308
  if (symbol.external) return this.symbol(name, symbol);
2291
2309
  if (symbol.meta) {
2292
- const existing = this.querySymbols(symbol.meta).find((s) => s.name === name);
2310
+ const existing = this.symbolFactory.queryAll(symbol.meta).find((s) => s.name === name);
2293
2311
  if (existing) return existing;
2294
2312
  }
2295
2313
  return this.symbol(name, symbol);
@@ -2329,6 +2347,8 @@ var PluginInstance = class {
2329
2347
  isOperationKind(operation, kind) {
2330
2348
  const method = kind === "query" ? "isQuery" : "isMutation";
2331
2349
  const hooks = [
2350
+ this.config.$hooks?.operations?.[method],
2351
+ this.config.$hooks?.operations?.getKind,
2332
2352
  this.config["~hooks"]?.operations?.[method],
2333
2353
  this.config["~hooks"]?.operations?.getKind,
2334
2354
  this.context.config.parser.hooks.operations?.[method],
@@ -2350,25 +2370,15 @@ var Context = class {
2350
2370
  * is a mix of user-provided and default values.
2351
2371
  */
2352
2372
  config;
2353
- /**
2354
- * The code generation project instance used to manage files, symbols,
2355
- */
2373
+ /** The code generation project instance used to manage files, symbols, */
2356
2374
  gen;
2357
- /**
2358
- * The dependency graph built from the intermediate representation.
2359
- */
2375
+ /** The dependency graph built from the intermediate representation. */
2360
2376
  graph;
2361
- /**
2362
- * Intents declared by plugins.
2363
- */
2377
+ /** Intents declared by plugins. */
2364
2378
  intents = [];
2365
- /**
2366
- * Intermediate representation model obtained from `spec`.
2367
- */
2379
+ /** Intermediate representation model obtained from `spec`. */
2368
2380
  ir = {};
2369
- /**
2370
- * Logger instance.
2371
- */
2381
+ /** Logger instance. */
2372
2382
  logger;
2373
2383
  /**
2374
2384
  * The package metadata and utilities for the current context, constructed
@@ -2383,9 +2393,7 @@ var Context = class {
2383
2393
  * their configured name from the config.
2384
2394
  */
2385
2395
  plugins = {};
2386
- /**
2387
- * Resolved specification from `input`.
2388
- */
2396
+ /** Resolved specification from `input`. */
2389
2397
  spec;
2390
2398
  constructor({ config, dependencies, logger, project, spec }) {
2391
2399
  this.config = config;
@@ -2421,8 +2429,9 @@ var Context = class {
2421
2429
  dependencies: plugin.dependencies ?? /* @__PURE__ */ new Set(),
2422
2430
  gen: this.gen,
2423
2431
  handler: plugin.handler,
2432
+ imports: plugin.imports,
2424
2433
  name: plugin.name,
2425
- symbols: plugin.symbols
2434
+ symbolMeta: plugin.symbolMeta
2426
2435
  });
2427
2436
  this.plugins[instance.name] = instance;
2428
2437
  return instance;
@@ -4497,7 +4506,7 @@ function getPaginationKeywordsRegExp(pagination) {
4497
4506
  * property may be a boolean, number, or integer. This function converts the string
4498
4507
  * key to the correct runtime value and IR type.
4499
4508
  */
4500
- const convertDiscriminatorValue = (value, propertyType) => {
4509
+ function convertDiscriminatorValue(value, propertyType) {
4501
4510
  switch (propertyType) {
4502
4511
  case "boolean": {
4503
4512
  const lowerValue = value.toLowerCase();
@@ -4546,13 +4555,58 @@ const convertDiscriminatorValue = (value, propertyType) => {
4546
4555
  type: "string"
4547
4556
  };
4548
4557
  }
4549
- };
4550
- const discriminatorValues = ($ref, mapping, shouldUseRefAsValue) => {
4558
+ }
4559
+ function discriminatorValues($ref, mapping, shouldUseRefAsValue) {
4551
4560
  const values = [];
4552
4561
  for (const name in mapping) if (mapping[name] === $ref) values.push(name);
4553
4562
  if (!values.length && (!shouldUseRefAsValue || shouldUseRefAsValue())) return [refToName($ref)];
4554
4563
  return values;
4555
- };
4564
+ }
4565
+ function buildDiscriminatedUnion({ parentSchema, resolveIrRef, schemas }) {
4566
+ const discriminatorKey = parentSchema.discriminator?.propertyName;
4567
+ if (!discriminatorKey) return null;
4568
+ const members = [];
4569
+ for (const schema of schemas) {
4570
+ if (schema.type === "null" || schema.const === null) continue;
4571
+ const ref = schema.$ref;
4572
+ if (!ref) return null;
4573
+ let resolved;
4574
+ try {
4575
+ resolved = resolveIrRef(ref);
4576
+ } catch {
4577
+ return null;
4578
+ }
4579
+ if (!resolved) return null;
4580
+ let effective = resolved;
4581
+ while (effective.$ref && !effective.type && !effective.properties && !effective.items) try {
4582
+ const next = resolveIrRef(effective.$ref);
4583
+ if (!next) break;
4584
+ effective = next;
4585
+ } catch {
4586
+ break;
4587
+ }
4588
+ const discriminatorProp = effective.properties?.[discriminatorKey];
4589
+ const needsExtend = discriminatorProp?.const === void 0;
4590
+ const isObjectLike = effective.type === "object" || effective.logicalOperator === "and";
4591
+ if (needsExtend && !isObjectLike) return null;
4592
+ const values = discriminatorValues(ref, parentSchema.discriminator.mapping);
4593
+ if (!values.length) return null;
4594
+ const propType = discriminatorProp?.type;
4595
+ for (const value of values) {
4596
+ const discriminatedValue = propType && propType !== "string" ? convertDiscriminatorValue(value, propType).const : value;
4597
+ members.push({
4598
+ discriminatedValue,
4599
+ needsExtend,
4600
+ ref
4601
+ });
4602
+ }
4603
+ }
4604
+ if (!members.length) return null;
4605
+ return {
4606
+ discriminatorKey,
4607
+ members
4608
+ };
4609
+ }
4556
4610
  //#endregion
4557
4611
  //#region src/openApi/2.0.x/parser/schema.ts
4558
4612
  function getSchemaType$1(schema) {
@@ -5301,6 +5355,31 @@ const parameterToIrParameter$2 = ({ $ref, context, parameter }) => {
5301
5355
  //#endregion
5302
5356
  //#region src/utils/url.ts
5303
5357
  const parseUrlRegExp = /^(([^:/?#]+):)?((\/\/)?([^:/?#]*)(:?([^/?#]*)))?([^?#]*)(\?([^#]*))?(#(.*))?/;
5358
+ /**
5359
+ * Resolve the base URL value based on the plugin configuration.
5360
+ *
5361
+ * The `baseUrl` config option can be:
5362
+ * - `false` to disable using the base URL
5363
+ * - a string to use as the base URL
5364
+ * - a number to pick a server from the IR `servers` array
5365
+ */
5366
+ function resolveBaseUrl(baseUrl, ir) {
5367
+ if (baseUrl === false) return;
5368
+ if (typeof baseUrl === "string") return baseUrl;
5369
+ return (ir.servers ?? [])[typeof baseUrl === "number" ? baseUrl : 0]?.url;
5370
+ }
5371
+ /**
5372
+ * Resolve the base URL string if it's a valid URL or path.
5373
+ */
5374
+ function getBaseUrl(config, ir) {
5375
+ const baseUrl = resolveBaseUrl(config, ir);
5376
+ if (baseUrl === void 0) return;
5377
+ if (baseUrl.includes("{")) return;
5378
+ const url = parseUrl(baseUrl);
5379
+ if (url.protocol && url.host) return baseUrl;
5380
+ if (baseUrl !== "/" && baseUrl.startsWith("/")) return baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
5381
+ return baseUrl;
5382
+ }
5304
5383
  function parseUrl(value) {
5305
5384
  const errorResponse = {
5306
5385
  host: "",
@@ -6014,30 +6093,12 @@ function parseAnyOf$1({ context, schema, state }) {
6014
6093
  const schemaItems = [];
6015
6094
  const schemaType = getSchemaType(schema);
6016
6095
  const compositionSchemas = schema.anyOf;
6017
- const discriminatorPropertyType = schema.discriminator ? findDiscriminatorPropertyType$1({
6018
- context,
6019
- propertyName: schema.discriminator.propertyName,
6020
- schemas: compositionSchemas
6021
- }) : void 0;
6022
6096
  for (const compositionSchema of compositionSchemas) {
6023
- let irCompositionSchema = schemaToIrSchema$1({
6097
+ const irCompositionSchema = schemaToIrSchema$1({
6024
6098
  context,
6025
6099
  schema: compositionSchema,
6026
6100
  state
6027
6101
  });
6028
- if (schema.discriminator && irCompositionSchema.$ref) {
6029
- const valueSchemas = discriminatorValues(irCompositionSchema.$ref, schema.discriminator.mapping).map((value) => convertDiscriminatorValue(value, discriminatorPropertyType));
6030
- irCompositionSchema = {
6031
- items: [{
6032
- properties: { [schema.discriminator.propertyName]: valueSchemas.length > 1 ? {
6033
- items: valueSchemas,
6034
- logicalOperator: "or"
6035
- } : valueSchemas[0] },
6036
- type: "object"
6037
- }, irCompositionSchema],
6038
- logicalOperator: "and"
6039
- };
6040
- }
6041
6102
  schemaItems.push(irCompositionSchema);
6042
6103
  }
6043
6104
  if (schema.nullable) schemaItems.push({ type: "null" });
@@ -6060,7 +6121,10 @@ function parseAnyOf$1({ context, schema, state }) {
6060
6121
  logicalOperator: "and"
6061
6122
  };
6062
6123
  }
6063
- if (schema.discriminator && irSchema.logicalOperator === "or") irSchema.discriminator = { propertyName: schema.discriminator.propertyName };
6124
+ if (schema.discriminator && irSchema.logicalOperator === "or") irSchema.discriminator = {
6125
+ ...schema.discriminator.mapping && { mapping: schema.discriminator.mapping },
6126
+ propertyName: schema.discriminator.propertyName
6127
+ };
6064
6128
  return irSchema;
6065
6129
  }
6066
6130
  function parseEnum$1({ context, schema, state }) {
@@ -6109,31 +6173,12 @@ function parseOneOf$1({ context, schema, state }) {
6109
6173
  let schemaItems = [];
6110
6174
  const schemaType = getSchemaType(schema);
6111
6175
  const compositionSchemas = schema.oneOf;
6112
- const discriminatorPropertyType = schema.discriminator ? findDiscriminatorPropertyType$1({
6113
- context,
6114
- propertyName: schema.discriminator.propertyName,
6115
- schemas: compositionSchemas
6116
- }) : void 0;
6117
6176
  for (const compositionSchema of compositionSchemas) {
6118
- let irCompositionSchema = schemaToIrSchema$1({
6177
+ const irCompositionSchema = schemaToIrSchema$1({
6119
6178
  context,
6120
6179
  schema: compositionSchema,
6121
6180
  state
6122
6181
  });
6123
- if (schema.discriminator && irCompositionSchema.$ref) {
6124
- const valueSchemas = discriminatorValues(irCompositionSchema.$ref, schema.discriminator.mapping).map((value) => convertDiscriminatorValue(value, discriminatorPropertyType));
6125
- irCompositionSchema = {
6126
- items: [{
6127
- properties: { [schema.discriminator.propertyName]: valueSchemas.length > 1 ? {
6128
- items: valueSchemas,
6129
- logicalOperator: "or"
6130
- } : valueSchemas[0] },
6131
- required: [schema.discriminator.propertyName],
6132
- type: "object"
6133
- }, irCompositionSchema],
6134
- logicalOperator: "and"
6135
- };
6136
- }
6137
6182
  if (irCompositionSchema.logicalOperator === "or" && irCompositionSchema.type !== "array" && irCompositionSchema.items) schemaItems = schemaItems.concat(irCompositionSchema.items);
6138
6183
  else schemaItems.push(irCompositionSchema);
6139
6184
  }
@@ -6157,7 +6202,10 @@ function parseOneOf$1({ context, schema, state }) {
6157
6202
  logicalOperator: "and"
6158
6203
  };
6159
6204
  }
6160
- if (schema.discriminator && irSchema.logicalOperator === "or") irSchema.discriminator = { propertyName: schema.discriminator.propertyName };
6205
+ if (schema.discriminator && irSchema.logicalOperator === "or") irSchema.discriminator = {
6206
+ ...schema.discriminator.mapping && { mapping: schema.discriminator.mapping },
6207
+ propertyName: schema.discriminator.propertyName
6208
+ };
6161
6209
  return irSchema;
6162
6210
  }
6163
6211
  function parseRef$1({ context, schema, state }) {
@@ -7430,30 +7478,12 @@ function parseAnyOf({ context, schema, state }) {
7430
7478
  const schemaItems = [];
7431
7479
  const schemaTypes = getSchemaTypes(schema);
7432
7480
  const compositionSchemas = schema.anyOf;
7433
- const discriminatorPropertyType = schema.discriminator ? findDiscriminatorPropertyType({
7434
- context,
7435
- propertyName: schema.discriminator.propertyName,
7436
- schemas: compositionSchemas
7437
- }) : void 0;
7438
7481
  for (const compositionSchema of compositionSchemas) {
7439
- let irCompositionSchema = schemaToIrSchema({
7482
+ const irCompositionSchema = schemaToIrSchema({
7440
7483
  context,
7441
7484
  schema: compositionSchema,
7442
7485
  state
7443
7486
  });
7444
- if (schema.discriminator && irCompositionSchema.$ref) {
7445
- const valueSchemas = discriminatorValues(irCompositionSchema.$ref, schema.discriminator.mapping).map((value) => convertDiscriminatorValue(value, discriminatorPropertyType));
7446
- irCompositionSchema = {
7447
- items: [{
7448
- properties: { [schema.discriminator.propertyName]: valueSchemas.length > 1 ? {
7449
- items: valueSchemas,
7450
- logicalOperator: "or"
7451
- } : valueSchemas[0] },
7452
- type: "object"
7453
- }, irCompositionSchema],
7454
- logicalOperator: "and"
7455
- };
7456
- }
7457
7487
  schemaItems.push(irCompositionSchema);
7458
7488
  }
7459
7489
  if (schemaTypes.includes("null")) schemaItems.push({ type: "null" });
@@ -7476,7 +7506,10 @@ function parseAnyOf({ context, schema, state }) {
7476
7506
  logicalOperator: "and"
7477
7507
  };
7478
7508
  }
7479
- if (schema.discriminator && irSchema.logicalOperator === "or") irSchema.discriminator = { propertyName: schema.discriminator.propertyName };
7509
+ if (schema.discriminator && irSchema.logicalOperator === "or") irSchema.discriminator = {
7510
+ ...schema.discriminator.mapping && { mapping: schema.discriminator.mapping },
7511
+ propertyName: schema.discriminator.propertyName
7512
+ };
7480
7513
  return irSchema;
7481
7514
  }
7482
7515
  function parseEnum({ context, schema, state }) {
@@ -7528,31 +7561,12 @@ function parseOneOf({ context, schema, state }) {
7528
7561
  let schemaItems = [];
7529
7562
  const schemaTypes = getSchemaTypes(schema);
7530
7563
  const compositionSchemas = schema.oneOf;
7531
- const discriminatorPropertyType = schema.discriminator ? findDiscriminatorPropertyType({
7532
- context,
7533
- propertyName: schema.discriminator.propertyName,
7534
- schemas: compositionSchemas
7535
- }) : void 0;
7536
7564
  for (const compositionSchema of compositionSchemas) {
7537
- let irCompositionSchema = schemaToIrSchema({
7565
+ const irCompositionSchema = schemaToIrSchema({
7538
7566
  context,
7539
7567
  schema: compositionSchema,
7540
7568
  state
7541
7569
  });
7542
- if (schema.discriminator && irCompositionSchema.$ref) {
7543
- const valueSchemas = discriminatorValues(irCompositionSchema.$ref, schema.discriminator.mapping).map((value) => convertDiscriminatorValue(value, discriminatorPropertyType));
7544
- irCompositionSchema = {
7545
- items: [{
7546
- properties: { [schema.discriminator.propertyName]: valueSchemas.length > 1 ? {
7547
- items: valueSchemas,
7548
- logicalOperator: "or"
7549
- } : valueSchemas[0] },
7550
- required: [schema.discriminator.propertyName],
7551
- type: "object"
7552
- }, irCompositionSchema],
7553
- logicalOperator: "and"
7554
- };
7555
- }
7556
7570
  if (irCompositionSchema.logicalOperator === "or" && irCompositionSchema.type !== "array" && irCompositionSchema.items) schemaItems = schemaItems.concat(irCompositionSchema.items);
7557
7571
  else schemaItems.push(irCompositionSchema);
7558
7572
  }
@@ -7576,7 +7590,10 @@ function parseOneOf({ context, schema, state }) {
7576
7590
  logicalOperator: "and"
7577
7591
  };
7578
7592
  }
7579
- if (schema.discriminator && irSchema.logicalOperator === "or") irSchema.discriminator = { propertyName: schema.discriminator.propertyName };
7593
+ if (schema.discriminator && irSchema.logicalOperator === "or") irSchema.discriminator = {
7594
+ ...schema.discriminator.mapping && { mapping: schema.discriminator.mapping },
7595
+ propertyName: schema.discriminator.propertyName
7596
+ };
7580
7597
  return irSchema;
7581
7598
  }
7582
7599
  function parseRef({ context, schema, state }) {
@@ -8807,37 +8824,7 @@ async function patchOpenApiSpec({ patchOptions, spec: _spec }) {
8807
8824
  }
8808
8825
  }
8809
8826
  //#endregion
8810
- //#region src/plugins/duplicate.ts
8811
- function stableStringify(value) {
8812
- return JSON.stringify(value, (_, v) => {
8813
- if (typeof v === "function") return `[function:${v.toString()}]`;
8814
- if (v && typeof v === "object" && !Array.isArray(v)) return Object.fromEntries(Object.entries(v).sort(([a], [b]) => a.localeCompare(b)));
8815
- return v;
8816
- });
8817
- }
8818
- function normalizePluginEntry(plugin) {
8819
- if (typeof plugin === "string") return {
8820
- name: plugin,
8821
- serialized: "{}"
8822
- };
8823
- const { name, ...config } = plugin;
8824
- return {
8825
- name,
8826
- serialized: stableStringify(config)
8827
- };
8828
- }
8829
- function warnOnConflictingDuplicatePlugins(plugins) {
8830
- const seen = /* @__PURE__ */ new Map();
8831
- for (const plugin of plugins) {
8832
- const { name, serialized } = normalizePluginEntry(plugin);
8833
- if (!name) continue;
8834
- const previous = seen.get(name);
8835
- if (previous !== void 0 && previous !== serialized) log.warn(`Plugin "${name}" is configured multiple times. Only the last instance will take effect.`);
8836
- seen.set(name, serialized);
8837
- }
8838
- }
8839
- //#endregion
8840
- //#region src/plugins/shared/utils/config.ts
8827
+ //#region src/plugins/config.ts
8841
8828
  function definePluginConfig(pluginConfig) {
8842
8829
  return (userConfig) => ({
8843
8830
  ...pluginConfig,
@@ -8854,12 +8841,137 @@ function definePluginConfig(pluginConfig) {
8854
8841
  name: pluginConfig.name
8855
8842
  });
8856
8843
  }
8844
+ function isPluginClient(plugin) {
8845
+ if (typeof plugin === "string") return plugin.startsWith("@hey-api/client");
8846
+ return plugin.name.startsWith("@hey-api/client") || Array.isArray(plugin.tags) && plugin.tags.includes("client");
8847
+ }
8848
+ function resolvePluginsConfig({ defaultPluginConfigs, dependencies, userPlugins, userPluginsConfig }) {
8849
+ const circularReferenceTracker = /* @__PURE__ */ new Set();
8850
+ const pluginOrder = /* @__PURE__ */ new Set();
8851
+ const plugins = {};
8852
+ const warnedMessages = /* @__PURE__ */ new Set();
8853
+ function dfs(name) {
8854
+ if (circularReferenceTracker.has(name)) throw new Error(`Circular reference detected at '${name}'`);
8855
+ if (pluginOrder.has(name)) return;
8856
+ circularReferenceTracker.add(name);
8857
+ const defaultPlugin = defaultPluginConfigs[name];
8858
+ const userPlugin = userPluginsConfig[name];
8859
+ if (!defaultPlugin && !userPlugin) throw new Error(`unknown plugin "${name}" - do you need to register a custom plugin with this name?`);
8860
+ const configTable = defaultPlugin?.config ?? userPlugin?.config ?? {};
8861
+ const userConfig = defaultPlugin && userPlugin?.config ? userPlugin.config : {};
8862
+ const pluginContext = {
8863
+ package: dependencyFactory(dependencies),
8864
+ resolveTag(tag, options = {}) {
8865
+ const { defaultPlugin, fallback = false, warn: warnMessage } = options;
8866
+ for (const userPlugin of userPlugins) if ((defaultPluginConfigs[userPlugin] || userPluginsConfig[userPlugin])?.tags?.includes(tag) && userPlugin !== name) return userPlugin;
8867
+ if (defaultPlugin) {
8868
+ if ((defaultPluginConfigs[defaultPlugin] || userPluginsConfig[defaultPlugin])?.tags?.includes(tag) && defaultPlugin !== name) return defaultPlugin;
8869
+ }
8870
+ if (warnMessage && !warnedMessages.has(warnMessage)) {
8871
+ warnedMessages.add(warnMessage);
8872
+ log.warn(warnMessage);
8873
+ }
8874
+ return fallback;
8875
+ }
8876
+ };
8877
+ const finalConfig = defineConfig(configTable)(userConfig, pluginContext);
8878
+ const finalDependencies = new Set([...defaultPlugin?.dependencies || [], ...userPlugin?.dependencies || []]);
8879
+ const plugin = {
8880
+ ...defaultPlugin,
8881
+ ...userPlugin,
8882
+ config: finalConfig,
8883
+ dependencies: finalDependencies
8884
+ };
8885
+ collectDeps(configTable, finalConfig, finalDependencies);
8886
+ for (const dependency of plugin.dependencies) dfs(dependency);
8887
+ circularReferenceTracker.delete(name);
8888
+ pluginOrder.add(name);
8889
+ plugins[name] = plugin;
8890
+ }
8891
+ for (const name of userPlugins) dfs(name);
8892
+ return {
8893
+ pluginOrder: Array.from(pluginOrder),
8894
+ plugins
8895
+ };
8896
+ }
8897
+ function resolvePlugins({ defaultPluginConfigs, defaultPlugins, dependencies, userConfig }) {
8898
+ const userPluginsConfig = {};
8899
+ const rawPresetPlugins = (userConfig.presets ?? []).flatMap((preset) => preset.plugins ?? []);
8900
+ const rawUserPlugins = userConfig.plugins ?? [];
8901
+ const rawPlugins = [...rawPresetPlugins, ...rawUserPlugins.length ? rawUserPlugins : defaultPlugins].filter((plugin) => typeof plugin === "string" && plugin || typeof plugin !== "string" && plugin.name);
8902
+ const mergedPlugins = [];
8903
+ const seenNames = /* @__PURE__ */ new Map();
8904
+ for (const plugin of rawPlugins) {
8905
+ if (typeof plugin === "string") {
8906
+ if (!seenNames.has(plugin)) {
8907
+ seenNames.set(plugin, {
8908
+ index: mergedPlugins.length,
8909
+ value: plugin
8910
+ });
8911
+ mergedPlugins.push(plugin);
8912
+ }
8913
+ continue;
8914
+ }
8915
+ if (!plugin?.name) continue;
8916
+ const name = plugin.name;
8917
+ if (!seenNames.has(name)) {
8918
+ seenNames.set(name, {
8919
+ index: mergedPlugins.length,
8920
+ value: plugin
8921
+ });
8922
+ mergedPlugins.push(plugin);
8923
+ continue;
8924
+ }
8925
+ const prev = seenNames.get(name);
8926
+ if (typeof prev.value === "string") {
8927
+ seenNames.set(name, {
8928
+ index: prev.index,
8929
+ value: { ...plugin }
8930
+ });
8931
+ mergedPlugins[prev.index] = { ...plugin };
8932
+ continue;
8933
+ }
8934
+ const mergedObj = deepMerge(prev.value, plugin);
8935
+ seenNames.set(name, {
8936
+ index: prev.index,
8937
+ value: mergedObj
8938
+ });
8939
+ mergedPlugins[prev.index] = mergedObj;
8940
+ }
8941
+ if (mergedPlugins.length > 0 && mergedPlugins.every((plugin) => isPluginClient(plugin))) {
8942
+ for (const name of [...defaultPlugins].reverse()) if (!seenNames.has(name)) mergedPlugins.unshift(name);
8943
+ }
8944
+ return resolvePluginsConfig({
8945
+ defaultPluginConfigs,
8946
+ dependencies,
8947
+ userPlugins: mergedPlugins.map((plugin) => {
8948
+ if (typeof plugin === "string") return plugin;
8949
+ const pluginName = plugin.name;
8950
+ if (pluginName) if (plugin.handler) userPluginsConfig[pluginName] = plugin;
8951
+ else {
8952
+ userPluginsConfig[pluginName] = { config: { ...plugin } };
8953
+ delete userPluginsConfig[pluginName].config.name;
8954
+ }
8955
+ return pluginName;
8956
+ }).filter(Boolean),
8957
+ userPluginsConfig
8958
+ });
8959
+ }
8960
+ //#endregion
8961
+ //#region src/plugins/helper.ts
8962
+ function pluginHelper(name) {
8963
+ return (config) => ({
8964
+ ...config,
8965
+ name
8966
+ });
8967
+ }
8857
8968
  //#endregion
8858
8969
  //#region src/plugins/symbol.ts
8859
8970
  /**
8860
- * Helper function to build the input for symbol registration, applying naming hooks if provided.
8971
+ * Function to build the input for symbol registration, applying naming hooks if provided.
8861
8972
  */
8862
8973
  function buildSymbolIn({ plugin, ...ctx }) {
8974
+ const priority = defaultPriorityFromPath(ctx.path);
8863
8975
  const hooks = plugin.getHooks((hooks) => hooks.symbols?.getName);
8864
8976
  for (const hook of hooks) {
8865
8977
  const result = hook(ctx);
@@ -8867,18 +8979,29 @@ function buildSymbolIn({ plugin, ...ctx }) {
8867
8979
  const name = result(ctx);
8868
8980
  if (name) return {
8869
8981
  meta: ctx.meta,
8870
- name
8982
+ name,
8983
+ priority
8871
8984
  };
8872
8985
  } else if (typeof result === "string") return {
8873
8986
  meta: ctx.meta,
8874
- name: ctx.naming ? applyNaming(result, ctx.naming) : result
8987
+ name: ctx.naming ? applyNaming(result, ctx.naming) : result,
8988
+ priority
8875
8989
  };
8876
8990
  }
8877
8991
  return {
8878
8992
  meta: ctx.meta,
8879
- name: ctx.naming ? applyNaming(ctx.name, ctx.naming) : ctx.name
8993
+ name: ctx.naming ? applyNaming(ctx.name, ctx.naming) : ctx.name,
8994
+ priority
8880
8995
  };
8881
8996
  }
8997
+ const MAX_PRIORITY_FROM_PATH = 100;
8998
+ /**
8999
+ * Derives naming priority from path depth.
9000
+ */
9001
+ function defaultPriorityFromPath(path) {
9002
+ if (!path?.length) return;
9003
+ return Math.max(0, MAX_PRIORITY_FROM_PATH - path.length);
9004
+ }
8882
9005
  //#endregion
8883
9006
  //#region src/plugins/validator.ts
8884
9007
  /**
@@ -9049,6 +9172,6 @@ function pathToName(path, options) {
9049
9172
  return names.join("-");
9050
9173
  }
9051
9174
  //#endregion
9052
- export { COERCER, ConfigError, ConfigValidationError, Context, HeyApiError, InputError, IntentContext, JobError, MinHeap, OperationPath, OperationStrategy, PluginInstance, SymbolFactory, addItemsToSchema, applyNaming, buildGraph, buildSymbolIn, checkNodeVersion, childContext, coerce, collectDeps, compileInputPath, createOperationKey, createSchemaProcessor, createSchemaWalker, debugTools, deduplicateSchema, defaultPaginationKeywords, defineConfig, definePluginConfig, dependencyFactory, encodeJsonPointerSegment, ensureDirSync, escapeComment, findPackageJson, findTsConfigPath, getInput, getInputError, getLogs, getParser, getSpec, hasOperationDataRequired, hasParameterGroupObjectRequired, hasParametersObjectRequired, heyApiRegistryBaseUrl, inputToApiRegistry, isCoercer, isEnvironment, isPlainObject, isTopLevelComponent, jsonPointerToPath, loadPackageJson, logCrashReport, logInputPaths, normalizeJsonPointer, openGitHubIssueWithCrashReport, operationPagination, operationResponsesMap, outputHeaderToPrefix, parameterWithPagination, parseOpenApiSpec, parseUrl, parseV2_0_X, parseV3_0_X, parseV3_1_X, patchOpenApiSpec, pathToJsonPointer, pathToName, postprocessOutput, printCliIntro, printCrashReport, refToName, requestValidatorLayers, resolveNaming, resolveRef, resolveValidatorLayer, satisfies, shouldReportCrash, sourceConfig, statusCodeToGroup, toCase, utils, warnOnConflictingDuplicatePlugins };
9175
+ export { COERCER, ConfigError, ConfigValidationError, Context, HeyApiError, InputError, IntentContext, JobError, MinHeap, OperationPath, OperationStrategy, PluginInstance, SymbolFactory, addItemsToSchema, applyNaming, buildDiscriminatedUnion, buildGraph, buildSymbolIn, checkNodeVersion, childContext, coerce, collectDeps, compileInputPath, convertDiscriminatorValue, createOperationKey, createSchemaProcessor, createSchemaWalker, debugTools, deduplicateSchema, deepMerge, defaultPaginationKeywords, defineConfig, definePluginConfig, dependencyFactory, discriminatorValues, encodeJsonPointerSegment, ensureDirSync, escapeComment, findPackageJson, findTsConfigPath, getBaseUrl, getInput, getInputError, getLogs, getParser, getSpec, hasOperationDataRequired, hasParameterGroupObjectRequired, hasParametersObjectRequired, heyApiRegistryBaseUrl, inputToApiRegistry, isCoercer, isEnvironment, isPlainObject, isTopLevelComponent, jsonPointerToPath, loadPackageJson, logCrashReport, logInputPaths, normalizeJsonPointer, openGitHubIssueWithCrashReport, operationPagination, operationResponsesMap, outputHeaderToPrefix, parameterWithPagination, parseOpenApiSpec, parseUrl, parseV2_0_X, parseV3_0_X, parseV3_1_X, patchOpenApiSpec, pathToJsonPointer, pathToName, pluginHelper, postprocessOutput, printCliIntro, printCrashReport, refToName, requestValidatorLayers, resolveNaming, resolvePlugins, resolveRef, resolveValidatorLayer, satisfies, shouldReportCrash, sourceConfig, statusCodeToGroup, toCase, utils };
9053
9176
 
9054
9177
  //# sourceMappingURL=index.mjs.map