var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
  if (typeof require !== "undefined") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x + '" is not supported');
});
var __commonJS = (cb, mod) => function __require2() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));

// src/typespec/node_modules/.pnpm/pluralize@8.0.0/node_modules/pluralize/pluralize.js
var require_pluralize = __commonJS({
  "src/typespec/node_modules/.pnpm/pluralize@8.0.0/node_modules/pluralize/pluralize.js"(exports, module) {
    (function(root, pluralize2) {
      if (typeof __require === "function" && typeof exports === "object" && typeof module === "object") {
        module.exports = pluralize2();
      } else if (typeof define === "function" && define.amd) {
        define(function() {
          return pluralize2();
        });
      } else {
        root.pluralize = pluralize2();
      }
    })(exports, function() {
      var pluralRules = [];
      var singularRules = [];
      var uncountables = {};
      var irregularPlurals = {};
      var irregularSingles = {};
      function sanitizeRule(rule) {
        if (typeof rule === "string") {
          return new RegExp("^" + rule + "$", "i");
        }
        return rule;
      }
      function restoreCase(word, token) {
        if (word === token) return token;
        if (word === word.toLowerCase()) return token.toLowerCase();
        if (word === word.toUpperCase()) return token.toUpperCase();
        if (word[0] === word[0].toUpperCase()) {
          return token.charAt(0).toUpperCase() + token.substr(1).toLowerCase();
        }
        return token.toLowerCase();
      }
      function interpolate(str, args) {
        return str.replace(/\$(\d{1,2})/g, function(match, index) {
          return args[index] || "";
        });
      }
      function replace(word, rule) {
        return word.replace(rule[0], function(match, index) {
          var result = interpolate(rule[1], arguments);
          if (match === "") {
            return restoreCase(word[index - 1], result);
          }
          return restoreCase(match, result);
        });
      }
      function sanitizeWord(token, word, rules2) {
        if (!token.length || uncountables.hasOwnProperty(token)) {
          return word;
        }
        var len = rules2.length;
        while (len--) {
          var rule = rules2[len];
          if (rule[0].test(word)) return replace(word, rule);
        }
        return word;
      }
      function replaceWord(replaceMap, keepMap, rules2) {
        return function(word) {
          var token = word.toLowerCase();
          if (keepMap.hasOwnProperty(token)) {
            return restoreCase(word, token);
          }
          if (replaceMap.hasOwnProperty(token)) {
            return restoreCase(word, replaceMap[token]);
          }
          return sanitizeWord(token, word, rules2);
        };
      }
      function checkWord(replaceMap, keepMap, rules2, bool) {
        return function(word) {
          var token = word.toLowerCase();
          if (keepMap.hasOwnProperty(token)) return true;
          if (replaceMap.hasOwnProperty(token)) return false;
          return sanitizeWord(token, token, rules2) === token;
        };
      }
      function pluralize2(word, count, inclusive) {
        var pluralized = count === 1 ? pluralize2.singular(word) : pluralize2.plural(word);
        return (inclusive ? count + " " : "") + pluralized;
      }
      pluralize2.plural = replaceWord(
        irregularSingles,
        irregularPlurals,
        pluralRules
      );
      pluralize2.isPlural = checkWord(
        irregularSingles,
        irregularPlurals,
        pluralRules
      );
      pluralize2.singular = replaceWord(
        irregularPlurals,
        irregularSingles,
        singularRules
      );
      pluralize2.isSingular = checkWord(
        irregularPlurals,
        irregularSingles,
        singularRules
      );
      pluralize2.addPluralRule = function(rule, replacement) {
        pluralRules.push([sanitizeRule(rule), replacement]);
      };
      pluralize2.addSingularRule = function(rule, replacement) {
        singularRules.push([sanitizeRule(rule), replacement]);
      };
      pluralize2.addUncountableRule = function(word) {
        if (typeof word === "string") {
          uncountables[word.toLowerCase()] = true;
          return;
        }
        pluralize2.addPluralRule(word, "$0");
        pluralize2.addSingularRule(word, "$0");
      };
      pluralize2.addIrregularRule = function(single, plural) {
        plural = plural.toLowerCase();
        single = single.toLowerCase();
        irregularSingles[single] = plural;
        irregularPlurals[plural] = single;
      };
      [
        // Pronouns.
        ["I", "we"],
        ["me", "us"],
        ["he", "they"],
        ["she", "they"],
        ["them", "them"],
        ["myself", "ourselves"],
        ["yourself", "yourselves"],
        ["itself", "themselves"],
        ["herself", "themselves"],
        ["himself", "themselves"],
        ["themself", "themselves"],
        ["is", "are"],
        ["was", "were"],
        ["has", "have"],
        ["this", "these"],
        ["that", "those"],
        // Words ending in with a consonant and `o`.
        ["echo", "echoes"],
        ["dingo", "dingoes"],
        ["volcano", "volcanoes"],
        ["tornado", "tornadoes"],
        ["torpedo", "torpedoes"],
        // Ends with `us`.
        ["genus", "genera"],
        ["viscus", "viscera"],
        // Ends with `ma`.
        ["stigma", "stigmata"],
        ["stoma", "stomata"],
        ["dogma", "dogmata"],
        ["lemma", "lemmata"],
        ["schema", "schemata"],
        ["anathema", "anathemata"],
        // Other irregular rules.
        ["ox", "oxen"],
        ["axe", "axes"],
        ["die", "dice"],
        ["yes", "yeses"],
        ["foot", "feet"],
        ["eave", "eaves"],
        ["goose", "geese"],
        ["tooth", "teeth"],
        ["quiz", "quizzes"],
        ["human", "humans"],
        ["proof", "proofs"],
        ["carve", "carves"],
        ["valve", "valves"],
        ["looey", "looies"],
        ["thief", "thieves"],
        ["groove", "grooves"],
        ["pickaxe", "pickaxes"],
        ["passerby", "passersby"]
      ].forEach(function(rule) {
        return pluralize2.addIrregularRule(rule[0], rule[1]);
      });
      [
        [/s?$/i, "s"],
        [/[^\u0000-\u007F]$/i, "$0"],
        [/([^aeiou]ese)$/i, "$1"],
        [/(ax|test)is$/i, "$1es"],
        [/(alias|[^aou]us|t[lm]as|gas|ris)$/i, "$1es"],
        [/(e[mn]u)s?$/i, "$1s"],
        [/([^l]ias|[aeiou]las|[ejzr]as|[iu]am)$/i, "$1"],
        [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, "$1i"],
        [/(alumn|alg|vertebr)(?:a|ae)$/i, "$1ae"],
        [/(seraph|cherub)(?:im)?$/i, "$1im"],
        [/(her|at|gr)o$/i, "$1oes"],
        [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i, "$1a"],
        [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i, "$1a"],
        [/sis$/i, "ses"],
        [/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i, "$1$2ves"],
        [/([^aeiouy]|qu)y$/i, "$1ies"],
        [/([^ch][ieo][ln])ey$/i, "$1ies"],
        [/(x|ch|ss|sh|zz)$/i, "$1es"],
        [/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i, "$1ices"],
        [/\b((?:tit)?m|l)(?:ice|ouse)$/i, "$1ice"],
        [/(pe)(?:rson|ople)$/i, "$1ople"],
        [/(child)(?:ren)?$/i, "$1ren"],
        [/eaux$/i, "$0"],
        [/m[ae]n$/i, "men"],
        ["thou", "you"]
      ].forEach(function(rule) {
        return pluralize2.addPluralRule(rule[0], rule[1]);
      });
      [
        [/s$/i, ""],
        [/(ss)$/i, "$1"],
        [/(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i, "$1fe"],
        [/(ar|(?:wo|[ae])l|[eo][ao])ves$/i, "$1f"],
        [/ies$/i, "y"],
        [/\b([pl]|zomb|(?:neck|cross)?t|coll|faer|food|gen|goon|group|lass|talk|goal|cut)ies$/i, "$1ie"],
        [/\b(mon|smil)ies$/i, "$1ey"],
        [/\b((?:tit)?m|l)ice$/i, "$1ouse"],
        [/(seraph|cherub)im$/i, "$1"],
        [/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|t[lm]as|gas|(?:her|at|gr)o|[aeiou]ris)(?:es)?$/i, "$1"],
        [/(analy|diagno|parenthe|progno|synop|the|empha|cri|ne)(?:sis|ses)$/i, "$1sis"],
        [/(movie|twelve|abuse|e[mn]u)s$/i, "$1"],
        [/(test)(?:is|es)$/i, "$1is"],
        [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, "$1us"],
        [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i, "$1um"],
        [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i, "$1on"],
        [/(alumn|alg|vertebr)ae$/i, "$1a"],
        [/(cod|mur|sil|vert|ind)ices$/i, "$1ex"],
        [/(matr|append)ices$/i, "$1ix"],
        [/(pe)(rson|ople)$/i, "$1rson"],
        [/(child)ren$/i, "$1"],
        [/(eau)x?$/i, "$1"],
        [/men$/i, "man"]
      ].forEach(function(rule) {
        return pluralize2.addSingularRule(rule[0], rule[1]);
      });
      [
        // Singular words with no plurals.
        "adulthood",
        "advice",
        "agenda",
        "aid",
        "aircraft",
        "alcohol",
        "ammo",
        "analytics",
        "anime",
        "athletics",
        "audio",
        "bison",
        "blood",
        "bream",
        "buffalo",
        "butter",
        "carp",
        "cash",
        "chassis",
        "chess",
        "clothing",
        "cod",
        "commerce",
        "cooperation",
        "corps",
        "debris",
        "diabetes",
        "digestion",
        "elk",
        "energy",
        "equipment",
        "excretion",
        "expertise",
        "firmware",
        "flounder",
        "fun",
        "gallows",
        "garbage",
        "graffiti",
        "hardware",
        "headquarters",
        "health",
        "herpes",
        "highjinks",
        "homework",
        "housework",
        "information",
        "jeans",
        "justice",
        "kudos",
        "labour",
        "literature",
        "machinery",
        "mackerel",
        "mail",
        "media",
        "mews",
        "moose",
        "music",
        "mud",
        "manga",
        "news",
        "only",
        "personnel",
        "pike",
        "plankton",
        "pliers",
        "police",
        "pollution",
        "premises",
        "rain",
        "research",
        "rice",
        "salmon",
        "scissors",
        "series",
        "sewage",
        "shambles",
        "shrimp",
        "software",
        "species",
        "staff",
        "swine",
        "tennis",
        "traffic",
        "transportation",
        "trout",
        "tuna",
        "wealth",
        "welfare",
        "whiting",
        "wildebeest",
        "wildlife",
        "you",
        /pok[eé]mon$/i,
        // Regexes.
        /[^aeiou]ese$/i,
        // "chinese", "japanese"
        /deer$/i,
        // "deer", "reindeer"
        /fish$/i,
        // "fish", "blowfish", "angelfish"
        /measles$/i,
        /o[iu]s$/i,
        // "carnivorous"
        /pox$/i,
        // "chickpox", "smallpox"
        /sheep$/i
      ].forEach(pluralize2.addUncountableRule);
      return pluralize2;
    });
  }
});

// src/typespec/packages/typespec-client-generator-core/dist/src/index.js
var src_exports = {};
__export(src_exports, {
  $access: () => $access,
  $alternateType: () => $alternateType,
  $apiVersion: () => $apiVersion,
  $client: () => $client,
  $clientApiVersions: () => $clientApiVersions,
  $clientDoc: () => $clientDoc,
  $clientInitialization: () => $clientInitialization,
  $clientLocation: () => $clientLocation,
  $clientName: () => $clientName,
  $clientNamespace: () => $clientNamespace,
  $convenientAPI: () => $convenientAPI,
  $decorators: () => $decorators,
  $deserializeEmptyStringAsNull: () => $deserializeEmptyStringAsNull,
  $flattenProperty: () => $flattenProperty,
  $legacyHierarchyBuilding: () => $legacyHierarchyBuilding,
  $lib: () => $lib,
  $linter: () => $linter,
  $onEmit: () => $onEmit,
  $operationGroup: () => $operationGroup,
  $override: () => $override,
  $paramAlias: () => $paramAlias,
  $protocolAPI: () => $protocolAPI,
  $responseAsBool: () => $responseAsBool,
  $scope: () => $scope,
  $usage: () => $usage,
  $useSystemTextJsonConverter: () => $useSystemTextJsonConverter,
  BrandedSdkEmitterOptions: () => BrandedSdkEmitterOptions,
  InitializedByFlags: () => InitializedByFlags,
  UnbrandedSdkEmitterOptions: () => UnbrandedSdkEmitterOptions,
  UsageFlags: () => UsageFlags,
  addEncodeInfo: () => addEncodeInfo,
  createDiagnostic: () => createDiagnostic,
  createSdkContext: () => createSdkContext,
  createStateSymbol: () => createStateSymbol,
  createTCGCContext: () => createTCGCContext,
  getAccess: () => getAccess,
  getAccessOverride: () => getAccessOverride,
  getAllModels: () => getAllModels,
  getAllModelsWithDiagnostics: () => getAllModelsWithDiagnostics,
  getAllReferencedTypes: () => getAllReferencedTypes,
  getAlternateType: () => getAlternateType,
  getClient: () => getClient,
  getClientDocExplicit: () => getClientDocExplicit,
  getClientInitializationOptions: () => getClientInitializationOptions,
  getClientLocation: () => getClientLocation,
  getClientNameOverride: () => getClientNameOverride,
  getClientNamespace: () => getClientNamespace,
  getClientType: () => getClientType,
  getClientTypeWithDiagnostics: () => getClientTypeWithDiagnostics,
  getCrossLanguageDefinitionId: () => getCrossLanguageDefinitionId,
  getCrossLanguagePackageId: () => getCrossLanguagePackageId,
  getDefaultApiVersion: () => getDefaultApiVersion,
  getEffectivePayloadType: () => getEffectivePayloadType,
  getExplicitClientApiVersions: () => getExplicitClientApiVersions,
  getGeneratedName: () => getGeneratedName,
  getHttpOperationExamples: () => getHttpOperationExamples,
  getHttpOperationParameter: () => getHttpOperationParameter,
  getHttpOperationWithCache: () => getHttpOperationWithCache,
  getIsApiVersion: () => getIsApiVersion,
  getKnownScalars: () => getKnownScalars,
  getLegacyHierarchyBuilding: () => getLegacyHierarchyBuilding,
  getLibraryName: () => getLibraryName,
  getNamespaceFromType: () => getNamespaceFromType,
  getOperationGroup: () => getOperationGroup,
  getOverriddenClientMethod: () => getOverriddenClientMethod,
  getParamAlias: () => getParamAlias,
  getPropertyNames: () => getPropertyNames,
  getResponseAsBool: () => getResponseAsBool,
  getSdkArrayOrDict: () => getSdkArrayOrDict,
  getSdkArrayOrDictWithDiagnostics: () => getSdkArrayOrDictWithDiagnostics,
  getSdkBuiltInType: () => getSdkBuiltInType,
  getSdkConstant: () => getSdkConstant,
  getSdkCredentialParameter: () => getSdkCredentialParameter,
  getSdkDurationType: () => getSdkDurationType,
  getSdkEnum: () => getSdkEnum,
  getSdkEnumValue: () => getSdkEnumValue,
  getSdkModel: () => getSdkModel,
  getSdkModelPropertyType: () => getSdkModelPropertyType,
  getSdkModelPropertyTypeBase: () => getSdkModelPropertyTypeBase,
  getSdkModelWithDiagnostics: () => getSdkModelWithDiagnostics,
  getSdkTuple: () => getSdkTuple,
  getSdkTupleWithDiagnostics: () => getSdkTupleWithDiagnostics,
  getSdkUnion: () => getSdkUnion,
  getSdkUnionEnum: () => getSdkUnionEnum,
  getSdkUnionEnumWithDiagnostics: () => getSdkUnionEnumWithDiagnostics,
  getSdkUnionWithDiagnostics: () => getSdkUnionWithDiagnostics,
  getTypeSpecBuiltInType: () => getTypeSpecBuiltInType,
  getUsage: () => getUsage,
  getUsageOverride: () => getUsageOverride,
  getWireName: () => getWireName,
  handleAllTypes: () => handleAllTypes,
  isApiVersion: () => isApiVersion,
  isAzureCoreModel: () => isAzureCoreModel,
  isHttpMetadata: () => isHttpMetadata,
  isInScope: () => isInScope,
  isOperationGroup: () => isOperationGroup,
  isPagedResultModel: () => isPagedResultModel,
  isReadOnly: () => isReadOnly,
  isSdkBuiltInKind: () => isSdkBuiltInKind,
  isSdkDateTimeEncodings: () => isSdkDateTimeEncodings,
  isSdkFloatKind: () => isSdkFloatKind,
  isSdkIntKind: () => isSdkIntKind,
  listAllServiceNamespaces: () => listAllServiceNamespaces,
  listClients: () => listClients,
  listOperationGroups: () => listOperationGroups,
  listOperationsInOperationGroup: () => listOperationsInOperationGroup,
  namespace: () => namespace,
  reportDiagnostic: () => reportDiagnostic,
  resolveOperationId: () => resolveOperationId,
  shouldFlattenProperty: () => shouldFlattenProperty,
  shouldGenerateConvenient: () => shouldGenerateConvenient,
  shouldGenerateProtocol: () => shouldGenerateProtocol,
  updateUsageOrAccess: () => updateUsageOrAccess
});

// src/typespec/packages/typespec-client-generator-core/dist/src/context.js
import { createDiagnosticCollector as createDiagnosticCollector9, emitFile, listServices as listServices2, resolvePath as resolvePath2 } from "@typespec/compiler";
import { getVersions as getVersions4 } from "@typespec/versioning";

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/nodes/identity.js
var ALIAS = Symbol.for("yaml.alias");
var DOC = Symbol.for("yaml.document");
var MAP = Symbol.for("yaml.map");
var PAIR = Symbol.for("yaml.pair");
var SCALAR = Symbol.for("yaml.scalar");
var SEQ = Symbol.for("yaml.seq");
var NODE_TYPE = Symbol.for("yaml.node.type");
var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS;
var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC;
var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP;
var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR;
var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR;
var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ;
function isCollection(node) {
  if (node && typeof node === "object")
    switch (node[NODE_TYPE]) {
      case MAP:
      case SEQ:
        return true;
    }
  return false;
}
function isNode(node) {
  if (node && typeof node === "object")
    switch (node[NODE_TYPE]) {
      case ALIAS:
      case MAP:
      case SCALAR:
      case SEQ:
        return true;
    }
  return false;
}
var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/visit.js
var BREAK = Symbol("break visit");
var SKIP = Symbol("skip children");
var REMOVE = Symbol("remove node");
function visit(node, visitor) {
  const visitor_ = initVisitor(visitor);
  if (isDocument(node)) {
    const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));
    if (cd === REMOVE)
      node.contents = null;
  } else
    visit_(null, node, visitor_, Object.freeze([]));
}
visit.BREAK = BREAK;
visit.SKIP = SKIP;
visit.REMOVE = REMOVE;
function visit_(key, node, visitor, path) {
  const ctrl = callVisitor(key, node, visitor, path);
  if (isNode(ctrl) || isPair(ctrl)) {
    replaceNode(key, path, ctrl);
    return visit_(key, ctrl, visitor, path);
  }
  if (typeof ctrl !== "symbol") {
    if (isCollection(node)) {
      path = Object.freeze(path.concat(node));
      for (let i = 0; i < node.items.length; ++i) {
        const ci = visit_(i, node.items[i], visitor, path);
        if (typeof ci === "number")
          i = ci - 1;
        else if (ci === BREAK)
          return BREAK;
        else if (ci === REMOVE) {
          node.items.splice(i, 1);
          i -= 1;
        }
      }
    } else if (isPair(node)) {
      path = Object.freeze(path.concat(node));
      const ck = visit_("key", node.key, visitor, path);
      if (ck === BREAK)
        return BREAK;
      else if (ck === REMOVE)
        node.key = null;
      const cv = visit_("value", node.value, visitor, path);
      if (cv === BREAK)
        return BREAK;
      else if (cv === REMOVE)
        node.value = null;
    }
  }
  return ctrl;
}
async function visitAsync(node, visitor) {
  const visitor_ = initVisitor(visitor);
  if (isDocument(node)) {
    const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));
    if (cd === REMOVE)
      node.contents = null;
  } else
    await visitAsync_(null, node, visitor_, Object.freeze([]));
}
visitAsync.BREAK = BREAK;
visitAsync.SKIP = SKIP;
visitAsync.REMOVE = REMOVE;
async function visitAsync_(key, node, visitor, path) {
  const ctrl = await callVisitor(key, node, visitor, path);
  if (isNode(ctrl) || isPair(ctrl)) {
    replaceNode(key, path, ctrl);
    return visitAsync_(key, ctrl, visitor, path);
  }
  if (typeof ctrl !== "symbol") {
    if (isCollection(node)) {
      path = Object.freeze(path.concat(node));
      for (let i = 0; i < node.items.length; ++i) {
        const ci = await visitAsync_(i, node.items[i], visitor, path);
        if (typeof ci === "number")
          i = ci - 1;
        else if (ci === BREAK)
          return BREAK;
        else if (ci === REMOVE) {
          node.items.splice(i, 1);
          i -= 1;
        }
      }
    } else if (isPair(node)) {
      path = Object.freeze(path.concat(node));
      const ck = await visitAsync_("key", node.key, visitor, path);
      if (ck === BREAK)
        return BREAK;
      else if (ck === REMOVE)
        node.key = null;
      const cv = await visitAsync_("value", node.value, visitor, path);
      if (cv === BREAK)
        return BREAK;
      else if (cv === REMOVE)
        node.value = null;
    }
  }
  return ctrl;
}
function initVisitor(visitor) {
  if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) {
    return Object.assign({
      Alias: visitor.Node,
      Map: visitor.Node,
      Scalar: visitor.Node,
      Seq: visitor.Node
    }, visitor.Value && {
      Map: visitor.Value,
      Scalar: visitor.Value,
      Seq: visitor.Value
    }, visitor.Collection && {
      Map: visitor.Collection,
      Seq: visitor.Collection
    }, visitor);
  }
  return visitor;
}
function callVisitor(key, node, visitor, path) {
  if (typeof visitor === "function")
    return visitor(key, node, path);
  if (isMap(node))
    return visitor.Map?.(key, node, path);
  if (isSeq(node))
    return visitor.Seq?.(key, node, path);
  if (isPair(node))
    return visitor.Pair?.(key, node, path);
  if (isScalar(node))
    return visitor.Scalar?.(key, node, path);
  if (isAlias(node))
    return visitor.Alias?.(key, node, path);
  return void 0;
}
function replaceNode(key, path, node) {
  const parent = path[path.length - 1];
  if (isCollection(parent)) {
    parent.items[key] = node;
  } else if (isPair(parent)) {
    if (key === "key")
      parent.key = node;
    else
      parent.value = node;
  } else if (isDocument(parent)) {
    parent.contents = node;
  } else {
    const pt = isAlias(parent) ? "alias" : "scalar";
    throw new Error(`Cannot replace node with ${pt} parent`);
  }
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/doc/directives.js
var escapeChars = {
  "!": "%21",
  ",": "%2C",
  "[": "%5B",
  "]": "%5D",
  "{": "%7B",
  "}": "%7D"
};
var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]);
var Directives = class _Directives {
  constructor(yaml, tags) {
    this.docStart = null;
    this.docEnd = false;
    this.yaml = Object.assign({}, _Directives.defaultYaml, yaml);
    this.tags = Object.assign({}, _Directives.defaultTags, tags);
  }
  clone() {
    const copy = new _Directives(this.yaml, this.tags);
    copy.docStart = this.docStart;
    return copy;
  }
  /**
   * During parsing, get a Directives instance for the current document and
   * update the stream state according to the current version's spec.
   */
  atDocument() {
    const res = new _Directives(this.yaml, this.tags);
    switch (this.yaml.version) {
      case "1.1":
        this.atNextDocument = true;
        break;
      case "1.2":
        this.atNextDocument = false;
        this.yaml = {
          explicit: _Directives.defaultYaml.explicit,
          version: "1.2"
        };
        this.tags = Object.assign({}, _Directives.defaultTags);
        break;
    }
    return res;
  }
  /**
   * @param onError - May be called even if the action was successful
   * @returns `true` on success
   */
  add(line, onError) {
    if (this.atNextDocument) {
      this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" };
      this.tags = Object.assign({}, _Directives.defaultTags);
      this.atNextDocument = false;
    }
    const parts = line.trim().split(/[ \t]+/);
    const name = parts.shift();
    switch (name) {
      case "%TAG": {
        if (parts.length !== 2) {
          onError(0, "%TAG directive should contain exactly two parts");
          if (parts.length < 2)
            return false;
        }
        const [handle, prefix] = parts;
        this.tags[handle] = prefix;
        return true;
      }
      case "%YAML": {
        this.yaml.explicit = true;
        if (parts.length !== 1) {
          onError(0, "%YAML directive should contain exactly one part");
          return false;
        }
        const [version] = parts;
        if (version === "1.1" || version === "1.2") {
          this.yaml.version = version;
          return true;
        } else {
          const isValid = /^\d+\.\d+$/.test(version);
          onError(6, `Unsupported YAML version ${version}`, isValid);
          return false;
        }
      }
      default:
        onError(0, `Unknown directive ${name}`, true);
        return false;
    }
  }
  /**
   * Resolves a tag, matching handles to those defined in %TAG directives.
   *
   * @returns Resolved tag, which may also be the non-specific tag `'!'` or a
   *   `'!local'` tag, or `null` if unresolvable.
   */
  tagName(source, onError) {
    if (source === "!")
      return "!";
    if (source[0] !== "!") {
      onError(`Not a valid tag: ${source}`);
      return null;
    }
    if (source[1] === "<") {
      const verbatim = source.slice(2, -1);
      if (verbatim === "!" || verbatim === "!!") {
        onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);
        return null;
      }
      if (source[source.length - 1] !== ">")
        onError("Verbatim tags must end with a >");
      return verbatim;
    }
    const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);
    if (!suffix)
      onError(`The ${source} tag has no suffix`);
    const prefix = this.tags[handle];
    if (prefix) {
      try {
        return prefix + decodeURIComponent(suffix);
      } catch (error) {
        onError(String(error));
        return null;
      }
    }
    if (handle === "!")
      return source;
    onError(`Could not resolve tag: ${source}`);
    return null;
  }
  /**
   * Given a fully resolved tag, returns its printable string form,
   * taking into account current tag prefixes and defaults.
   */
  tagString(tag) {
    for (const [handle, prefix] of Object.entries(this.tags)) {
      if (tag.startsWith(prefix))
        return handle + escapeTagName(tag.substring(prefix.length));
    }
    return tag[0] === "!" ? tag : `!<${tag}>`;
  }
  toString(doc) {
    const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : [];
    const tagEntries = Object.entries(this.tags);
    let tagNames;
    if (doc && tagEntries.length > 0 && isNode(doc.contents)) {
      const tags = {};
      visit(doc.contents, (_key, node) => {
        if (isNode(node) && node.tag)
          tags[node.tag] = true;
      });
      tagNames = Object.keys(tags);
    } else
      tagNames = [];
    for (const [handle, prefix] of tagEntries) {
      if (handle === "!!" && prefix === "tag:yaml.org,2002:")
        continue;
      if (!doc || tagNames.some((tn) => tn.startsWith(prefix)))
        lines.push(`%TAG ${handle} ${prefix}`);
    }
    return lines.join("\n");
  }
};
Directives.defaultYaml = { explicit: false, version: "1.2" };
Directives.defaultTags = { "!!": "tag:yaml.org,2002:" };

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/doc/anchors.js
function anchorIsValid(anchor) {
  if (/[\x00-\x19\s,[\]{}]/.test(anchor)) {
    const sa = JSON.stringify(anchor);
    const msg = `Anchor must not contain whitespace or control characters: ${sa}`;
    throw new Error(msg);
  }
  return true;
}
function anchorNames(root) {
  const anchors = /* @__PURE__ */ new Set();
  visit(root, {
    Value(_key, node) {
      if (node.anchor)
        anchors.add(node.anchor);
    }
  });
  return anchors;
}
function findNewAnchor(prefix, exclude) {
  for (let i = 1; true; ++i) {
    const name = `${prefix}${i}`;
    if (!exclude.has(name))
      return name;
  }
}
function createNodeAnchors(doc, prefix) {
  const aliasObjects = [];
  const sourceObjects = /* @__PURE__ */ new Map();
  let prevAnchors = null;
  return {
    onAnchor: (source) => {
      aliasObjects.push(source);
      prevAnchors ?? (prevAnchors = anchorNames(doc));
      const anchor = findNewAnchor(prefix, prevAnchors);
      prevAnchors.add(anchor);
      return anchor;
    },
    /**
     * With circular references, the source node is only resolved after all
     * of its child nodes are. This is why anchors are set only after all of
     * the nodes have been created.
     */
    setAnchors: () => {
      for (const source of aliasObjects) {
        const ref = sourceObjects.get(source);
        if (typeof ref === "object" && ref.anchor && (isScalar(ref.node) || isCollection(ref.node))) {
          ref.node.anchor = ref.anchor;
        } else {
          const error = new Error("Failed to resolve repeated object (this should not happen)");
          error.source = source;
          throw error;
        }
      }
    },
    sourceObjects
  };
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/doc/applyReviver.js
function applyReviver(reviver, obj, key, val) {
  if (val && typeof val === "object") {
    if (Array.isArray(val)) {
      for (let i = 0, len = val.length; i < len; ++i) {
        const v0 = val[i];
        const v1 = applyReviver(reviver, val, String(i), v0);
        if (v1 === void 0)
          delete val[i];
        else if (v1 !== v0)
          val[i] = v1;
      }
    } else if (val instanceof Map) {
      for (const k of Array.from(val.keys())) {
        const v0 = val.get(k);
        const v1 = applyReviver(reviver, val, k, v0);
        if (v1 === void 0)
          val.delete(k);
        else if (v1 !== v0)
          val.set(k, v1);
      }
    } else if (val instanceof Set) {
      for (const v0 of Array.from(val)) {
        const v1 = applyReviver(reviver, val, v0, v0);
        if (v1 === void 0)
          val.delete(v0);
        else if (v1 !== v0) {
          val.delete(v0);
          val.add(v1);
        }
      }
    } else {
      for (const [k, v0] of Object.entries(val)) {
        const v1 = applyReviver(reviver, val, k, v0);
        if (v1 === void 0)
          delete val[k];
        else if (v1 !== v0)
          val[k] = v1;
      }
    }
  }
  return reviver.call(obj, key, val);
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/nodes/toJS.js
function toJS(value, arg, ctx) {
  if (Array.isArray(value))
    return value.map((v, i) => toJS(v, String(i), ctx));
  if (value && typeof value.toJSON === "function") {
    if (!ctx || !hasAnchor(value))
      return value.toJSON(arg, ctx);
    const data = { aliasCount: 0, count: 1, res: void 0 };
    ctx.anchors.set(value, data);
    ctx.onCreate = (res2) => {
      data.res = res2;
      delete ctx.onCreate;
    };
    const res = value.toJSON(arg, ctx);
    if (ctx.onCreate)
      ctx.onCreate(res);
    return res;
  }
  if (typeof value === "bigint" && !ctx?.keep)
    return Number(value);
  return value;
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/nodes/Node.js
var NodeBase = class {
  constructor(type) {
    Object.defineProperty(this, NODE_TYPE, { value: type });
  }
  /** Create a copy of this node.  */
  clone() {
    const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
    if (this.range)
      copy.range = this.range.slice();
    return copy;
  }
  /** A plain JavaScript representation of this node. */
  toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
    if (!isDocument(doc))
      throw new TypeError("A document argument is required");
    const ctx = {
      anchors: /* @__PURE__ */ new Map(),
      doc,
      keep: true,
      mapAsMap: mapAsMap === true,
      mapKeyWarned: false,
      maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
    };
    const res = toJS(this, "", ctx);
    if (typeof onAnchor === "function")
      for (const { count, res: res2 } of ctx.anchors.values())
        onAnchor(res2, count);
    return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res;
  }
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/nodes/Alias.js
var Alias = class extends NodeBase {
  constructor(source) {
    super(ALIAS);
    this.source = source;
    Object.defineProperty(this, "tag", {
      set() {
        throw new Error("Alias nodes cannot have tags");
      }
    });
  }
  /**
   * Resolve the value of this alias within `doc`, finding the last
   * instance of the `source` anchor before this node.
   */
  resolve(doc, ctx) {
    let nodes;
    if (ctx?.aliasResolveCache) {
      nodes = ctx.aliasResolveCache;
    } else {
      nodes = [];
      visit(doc, {
        Node: (_key, node) => {
          if (isAlias(node) || hasAnchor(node))
            nodes.push(node);
        }
      });
      if (ctx)
        ctx.aliasResolveCache = nodes;
    }
    let found = void 0;
    for (const node of nodes) {
      if (node === this)
        break;
      if (node.anchor === this.source)
        found = node;
    }
    return found;
  }
  toJSON(_arg, ctx) {
    if (!ctx)
      return { source: this.source };
    const { anchors, doc, maxAliasCount } = ctx;
    const source = this.resolve(doc, ctx);
    if (!source) {
      const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
      throw new ReferenceError(msg);
    }
    let data = anchors.get(source);
    if (!data) {
      toJS(source, null, ctx);
      data = anchors.get(source);
    }
    if (!data || data.res === void 0) {
      const msg = "This should not happen: Alias anchor was not resolved?";
      throw new ReferenceError(msg);
    }
    if (maxAliasCount >= 0) {
      data.count += 1;
      if (data.aliasCount === 0)
        data.aliasCount = getAliasCount(doc, source, anchors);
      if (data.count * data.aliasCount > maxAliasCount) {
        const msg = "Excessive alias count indicates a resource exhaustion attack";
        throw new ReferenceError(msg);
      }
    }
    return data.res;
  }
  toString(ctx, _onComment, _onChompKeep) {
    const src = `*${this.source}`;
    if (ctx) {
      anchorIsValid(this.source);
      if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {
        const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
        throw new Error(msg);
      }
      if (ctx.implicitKey)
        return `${src} `;
    }
    return src;
  }
};
function getAliasCount(doc, node, anchors) {
  if (isAlias(node)) {
    const source = node.resolve(doc);
    const anchor = anchors && source && anchors.get(source);
    return anchor ? anchor.count * anchor.aliasCount : 0;
  } else if (isCollection(node)) {
    let count = 0;
    for (const item of node.items) {
      const c = getAliasCount(doc, item, anchors);
      if (c > count)
        count = c;
    }
    return count;
  } else if (isPair(node)) {
    const kc = getAliasCount(doc, node.key, anchors);
    const vc = getAliasCount(doc, node.value, anchors);
    return Math.max(kc, vc);
  }
  return 1;
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/nodes/Scalar.js
var isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object";
var Scalar = class extends NodeBase {
  constructor(value) {
    super(SCALAR);
    this.value = value;
  }
  toJSON(arg, ctx) {
    return ctx?.keep ? this.value : toJS(this.value, arg, ctx);
  }
  toString() {
    return String(this.value);
  }
};
Scalar.BLOCK_FOLDED = "BLOCK_FOLDED";
Scalar.BLOCK_LITERAL = "BLOCK_LITERAL";
Scalar.PLAIN = "PLAIN";
Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE";
Scalar.QUOTE_SINGLE = "QUOTE_SINGLE";

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/doc/createNode.js
var defaultTagPrefix = "tag:yaml.org,2002:";
function findTagObject(value, tagName, tags) {
  if (tagName) {
    const match = tags.filter((t) => t.tag === tagName);
    const tagObj = match.find((t) => !t.format) ?? match[0];
    if (!tagObj)
      throw new Error(`Tag ${tagName} not found`);
    return tagObj;
  }
  return tags.find((t) => t.identify?.(value) && !t.format);
}
function createNode(value, tagName, ctx) {
  if (isDocument(value))
    value = value.contents;
  if (isNode(value))
    return value;
  if (isPair(value)) {
    const map2 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx);
    map2.items.push(value);
    return map2;
  }
  if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) {
    value = value.valueOf();
  }
  const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx;
  let ref = void 0;
  if (aliasDuplicateObjects && value && typeof value === "object") {
    ref = sourceObjects.get(value);
    if (ref) {
      ref.anchor ?? (ref.anchor = onAnchor(value));
      return new Alias(ref.anchor);
    } else {
      ref = { anchor: null, node: null };
      sourceObjects.set(value, ref);
    }
  }
  if (tagName?.startsWith("!!"))
    tagName = defaultTagPrefix + tagName.slice(2);
  let tagObj = findTagObject(value, tagName, schema4.tags);
  if (!tagObj) {
    if (value && typeof value.toJSON === "function") {
      value = value.toJSON();
    }
    if (!value || typeof value !== "object") {
      const node2 = new Scalar(value);
      if (ref)
        ref.node = node2;
      return node2;
    }
    tagObj = value instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value) ? schema4[SEQ] : schema4[MAP];
  }
  if (onTagObj) {
    onTagObj(tagObj);
    delete ctx.onTagObj;
  }
  const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar(value);
  if (tagName)
    node.tag = tagName;
  else if (!tagObj.default)
    node.tag = tagObj.tag;
  if (ref)
    ref.node = node;
  return node;
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/nodes/Collection.js
function collectionFromPath(schema4, path, value) {
  let v = value;
  for (let i = path.length - 1; i >= 0; --i) {
    const k = path[i];
    if (typeof k === "number" && Number.isInteger(k) && k >= 0) {
      const a = [];
      a[k] = v;
      v = a;
    } else {
      v = /* @__PURE__ */ new Map([[k, v]]);
    }
  }
  return createNode(v, void 0, {
    aliasDuplicateObjects: false,
    keepUndefined: false,
    onAnchor: () => {
      throw new Error("This should not happen, please report a bug.");
    },
    schema: schema4,
    sourceObjects: /* @__PURE__ */ new Map()
  });
}
var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done;
var Collection = class extends NodeBase {
  constructor(type, schema4) {
    super(type);
    Object.defineProperty(this, "schema", {
      value: schema4,
      configurable: true,
      enumerable: false,
      writable: true
    });
  }
  /**
   * Create a copy of this collection.
   *
   * @param schema - If defined, overwrites the original's schema
   */
  clone(schema4) {
    const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
    if (schema4)
      copy.schema = schema4;
    copy.items = copy.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema4) : it);
    if (this.range)
      copy.range = this.range.slice();
    return copy;
  }
  /**
   * Adds a value to the collection. For `!!map` and `!!omap` the value must
   * be a Pair instance or a `{ key, value }` object, which may not have a key
   * that already exists in the map.
   */
  addIn(path, value) {
    if (isEmptyPath(path))
      this.add(value);
    else {
      const [key, ...rest] = path;
      const node = this.get(key, true);
      if (isCollection(node))
        node.addIn(rest, value);
      else if (node === void 0 && this.schema)
        this.set(key, collectionFromPath(this.schema, rest, value));
      else
        throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
    }
  }
  /**
   * Removes a value from the collection.
   * @returns `true` if the item was found and removed.
   */
  deleteIn(path) {
    const [key, ...rest] = path;
    if (rest.length === 0)
      return this.delete(key);
    const node = this.get(key, true);
    if (isCollection(node))
      return node.deleteIn(rest);
    else
      throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
  }
  /**
   * Returns item at `key`, or `undefined` if not found. By default unwraps
   * scalar values from their surrounding node; to disable set `keepScalar` to
   * `true` (collections are always returned intact).
   */
  getIn(path, keepScalar) {
    const [key, ...rest] = path;
    const node = this.get(key, true);
    if (rest.length === 0)
      return !keepScalar && isScalar(node) ? node.value : node;
    else
      return isCollection(node) ? node.getIn(rest, keepScalar) : void 0;
  }
  hasAllNullValues(allowScalar) {
    return this.items.every((node) => {
      if (!isPair(node))
        return false;
      const n = node.value;
      return n == null || allowScalar && isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag;
    });
  }
  /**
   * Checks if the collection includes a value with the key `key`.
   */
  hasIn(path) {
    const [key, ...rest] = path;
    if (rest.length === 0)
      return this.has(key);
    const node = this.get(key, true);
    return isCollection(node) ? node.hasIn(rest) : false;
  }
  /**
   * Sets a value in this collection. For `!!set`, `value` needs to be a
   * boolean to add/remove the item from the set.
   */
  setIn(path, value) {
    const [key, ...rest] = path;
    if (rest.length === 0) {
      this.set(key, value);
    } else {
      const node = this.get(key, true);
      if (isCollection(node))
        node.setIn(rest, value);
      else if (node === void 0 && this.schema)
        this.set(key, collectionFromPath(this.schema, rest, value));
      else
        throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
    }
  }
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/stringify/stringifyComment.js
var stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#");
function indentComment(comment, indent) {
  if (/^\n+$/.test(comment))
    return comment.substring(1);
  return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;
}
var lineComment = (str, indent, comment) => str.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment;

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/stringify/foldFlowLines.js
var FOLD_FLOW = "flow";
var FOLD_BLOCK = "block";
var FOLD_QUOTED = "quoted";
function foldFlowLines(text2, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
  if (!lineWidth || lineWidth < 0)
    return text2;
  if (lineWidth < minContentWidth)
    minContentWidth = 0;
  const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
  if (text2.length <= endStep)
    return text2;
  const folds = [];
  const escapedFolds = {};
  let end = lineWidth - indent.length;
  if (typeof indentAtStart === "number") {
    if (indentAtStart > lineWidth - Math.max(2, minContentWidth))
      folds.push(0);
    else
      end = lineWidth - indentAtStart;
  }
  let split2 = void 0;
  let prev = void 0;
  let overflow = false;
  let i = -1;
  let escStart = -1;
  let escEnd = -1;
  if (mode === FOLD_BLOCK) {
    i = consumeMoreIndentedLines(text2, i, indent.length);
    if (i !== -1)
      end = i + endStep;
  }
  for (let ch; ch = text2[i += 1]; ) {
    if (mode === FOLD_QUOTED && ch === "\\") {
      escStart = i;
      switch (text2[i + 1]) {
        case "x":
          i += 3;
          break;
        case "u":
          i += 5;
          break;
        case "U":
          i += 9;
          break;
        default:
          i += 1;
      }
      escEnd = i;
    }
    if (ch === "\n") {
      if (mode === FOLD_BLOCK)
        i = consumeMoreIndentedLines(text2, i, indent.length);
      end = i + indent.length + endStep;
      split2 = void 0;
    } else {
      if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== "	") {
        const next = text2[i + 1];
        if (next && next !== " " && next !== "\n" && next !== "	")
          split2 = i;
      }
      if (i >= end) {
        if (split2) {
          folds.push(split2);
          end = split2 + endStep;
          split2 = void 0;
        } else if (mode === FOLD_QUOTED) {
          while (prev === " " || prev === "	") {
            prev = ch;
            ch = text2[i += 1];
            overflow = true;
          }
          const j = i > escEnd + 1 ? i - 2 : escStart - 1;
          if (escapedFolds[j])
            return text2;
          folds.push(j);
          escapedFolds[j] = true;
          end = j + endStep;
          split2 = void 0;
        } else {
          overflow = true;
        }
      }
    }
    prev = ch;
  }
  if (overflow && onOverflow)
    onOverflow();
  if (folds.length === 0)
    return text2;
  if (onFold)
    onFold();
  let res = text2.slice(0, folds[0]);
  for (let i2 = 0; i2 < folds.length; ++i2) {
    const fold = folds[i2];
    const end2 = folds[i2 + 1] || text2.length;
    if (fold === 0)
      res = `
${indent}${text2.slice(0, end2)}`;
    else {
      if (mode === FOLD_QUOTED && escapedFolds[fold])
        res += `${text2[fold]}\\`;
      res += `
${indent}${text2.slice(fold + 1, end2)}`;
    }
  }
  return res;
}
function consumeMoreIndentedLines(text2, i, indent) {
  let end = i;
  let start = i + 1;
  let ch = text2[start];
  while (ch === " " || ch === "	") {
    if (i < start + indent) {
      ch = text2[++i];
    } else {
      do {
        ch = text2[++i];
      } while (ch && ch !== "\n");
      end = i;
      start = i + 1;
      ch = text2[start];
    }
  }
  return end;
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/stringify/stringifyString.js
var getFoldOptions = (ctx, isBlock) => ({
  indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,
  lineWidth: ctx.options.lineWidth,
  minContentWidth: ctx.options.minContentWidth
});
var containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str);
function lineLengthOverLimit(str, lineWidth, indentLength) {
  if (!lineWidth || lineWidth < 0)
    return false;
  const limit = lineWidth - indentLength;
  const strLen = str.length;
  if (strLen <= limit)
    return false;
  for (let i = 0, start = 0; i < strLen; ++i) {
    if (str[i] === "\n") {
      if (i - start > limit)
        return true;
      start = i + 1;
      if (strLen - start <= limit)
        return false;
    }
  }
  return true;
}
function doubleQuotedString(value, ctx) {
  const json2 = JSON.stringify(value);
  if (ctx.options.doubleQuotedAsJSON)
    return json2;
  const { implicitKey } = ctx;
  const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
  const indent = ctx.indent || (containsDocumentMarker(value) ? "  " : "");
  let str = "";
  let start = 0;
  for (let i = 0, ch = json2[i]; ch; ch = json2[++i]) {
    if (ch === " " && json2[i + 1] === "\\" && json2[i + 2] === "n") {
      str += json2.slice(start, i) + "\\ ";
      i += 1;
      start = i;
      ch = "\\";
    }
    if (ch === "\\")
      switch (json2[i + 1]) {
        case "u":
          {
            str += json2.slice(start, i);
            const code = json2.substr(i + 2, 4);
            switch (code) {
              case "0000":
                str += "\\0";
                break;
              case "0007":
                str += "\\a";
                break;
              case "000b":
                str += "\\v";
                break;
              case "001b":
                str += "\\e";
                break;
              case "0085":
                str += "\\N";
                break;
              case "00a0":
                str += "\\_";
                break;
              case "2028":
                str += "\\L";
                break;
              case "2029":
                str += "\\P";
                break;
              default:
                if (code.substr(0, 2) === "00")
                  str += "\\x" + code.substr(2);
                else
                  str += json2.substr(i, 6);
            }
            i += 5;
            start = i + 1;
          }
          break;
        case "n":
          if (implicitKey || json2[i + 2] === '"' || json2.length < minMultiLineLength) {
            i += 1;
          } else {
            str += json2.slice(start, i) + "\n\n";
            while (json2[i + 2] === "\\" && json2[i + 3] === "n" && json2[i + 4] !== '"') {
              str += "\n";
              i += 2;
            }
            str += indent;
            if (json2[i + 2] === " ")
              str += "\\";
            i += 1;
            start = i + 1;
          }
          break;
        default:
          i += 1;
      }
  }
  str = start ? str + json2.slice(start) : json2;
  return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx, false));
}
function singleQuotedString(value, ctx) {
  if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes("\n") || /[ \t]\n|\n[ \t]/.test(value))
    return doubleQuotedString(value, ctx);
  const indent = ctx.indent || (containsDocumentMarker(value) ? "  " : "");
  const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&
${indent}`) + "'";
  return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false));
}
function quotedString(value, ctx) {
  const { singleQuote } = ctx.options;
  let qs;
  if (singleQuote === false)
    qs = doubleQuotedString;
  else {
    const hasDouble = value.includes('"');
    const hasSingle = value.includes("'");
    if (hasDouble && !hasSingle)
      qs = singleQuotedString;
    else if (hasSingle && !hasDouble)
      qs = doubleQuotedString;
    else
      qs = singleQuote ? singleQuotedString : doubleQuotedString;
  }
  return qs(value, ctx);
}
var blockEndNewlines;
try {
  blockEndNewlines = new RegExp("(^|(?<!\n))\n+(?!\n|$)", "g");
} catch {
  blockEndNewlines = /\n+(?!\n|$)/g;
}
function blockString({ comment, type, value }, ctx, onComment, onChompKeep) {
  const { blockQuote, commentString, lineWidth } = ctx.options;
  if (!blockQuote || /\n[\t ]+$/.test(value)) {
    return quotedString(value, ctx);
  }
  const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? "  " : "");
  const literal = blockQuote === "literal" ? true : blockQuote === "folded" || type === Scalar.BLOCK_FOLDED ? false : type === Scalar.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, lineWidth, indent.length);
  if (!value)
    return literal ? "|\n" : ">\n";
  let chomp;
  let endStart;
  for (endStart = value.length; endStart > 0; --endStart) {
    const ch = value[endStart - 1];
    if (ch !== "\n" && ch !== "	" && ch !== " ")
      break;
  }
  let end = value.substring(endStart);
  const endNlPos = end.indexOf("\n");
  if (endNlPos === -1) {
    chomp = "-";
  } else if (value === end || endNlPos !== end.length - 1) {
    chomp = "+";
    if (onChompKeep)
      onChompKeep();
  } else {
    chomp = "";
  }
  if (end) {
    value = value.slice(0, -end.length);
    if (end[end.length - 1] === "\n")
      end = end.slice(0, -1);
    end = end.replace(blockEndNewlines, `$&${indent}`);
  }
  let startWithSpace = false;
  let startEnd;
  let startNlPos = -1;
  for (startEnd = 0; startEnd < value.length; ++startEnd) {
    const ch = value[startEnd];
    if (ch === " ")
      startWithSpace = true;
    else if (ch === "\n")
      startNlPos = startEnd;
    else
      break;
  }
  let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
  if (start) {
    value = value.substring(start.length);
    start = start.replace(/\n+/g, `$&${indent}`);
  }
  const indentSize = indent ? "2" : "1";
  let header = (startWithSpace ? indentSize : "") + chomp;
  if (comment) {
    header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " "));
    if (onComment)
      onComment();
  }
  if (!literal) {
    const foldedValue = value.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`);
    let literalFallback = false;
    const foldOptions = getFoldOptions(ctx, true);
    if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) {
      foldOptions.onOverflow = () => {
        literalFallback = true;
      };
    }
    const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions);
    if (!literalFallback)
      return `>${header}
${indent}${body}`;
  }
  value = value.replace(/\n+/g, `$&${indent}`);
  return `|${header}
${indent}${start}${value}${end}`;
}
function plainString(item, ctx, onComment, onChompKeep) {
  const { type, value } = item;
  const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
  if (implicitKey && value.includes("\n") || inFlow && /[[\]{},]/.test(value)) {
    return quotedString(value, ctx);
  }
  if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
    return implicitKey || inFlow || !value.includes("\n") ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep);
  }
  if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value.includes("\n")) {
    return blockString(item, ctx, onComment, onChompKeep);
  }
  if (containsDocumentMarker(value)) {
    if (indent === "") {
      ctx.forceBlockIndent = true;
      return blockString(item, ctx, onComment, onChompKeep);
    } else if (implicitKey && indent === indentStep) {
      return quotedString(value, ctx);
    }
  }
  const str = value.replace(/\n+/g, `$&
${indent}`);
  if (actualString) {
    const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str);
    const { compat, tags } = ctx.doc.schema;
    if (tags.some(test) || compat?.some(test))
      return quotedString(value, ctx);
  }
  return implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx, false));
}
function stringifyString(item, ctx, onComment, onChompKeep) {
  const { implicitKey, inFlow } = ctx;
  const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) });
  let { type } = item;
  if (type !== Scalar.QUOTE_DOUBLE) {
    if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
      type = Scalar.QUOTE_DOUBLE;
  }
  const _stringify = (_type) => {
    switch (_type) {
      case Scalar.BLOCK_FOLDED:
      case Scalar.BLOCK_LITERAL:
        return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep);
      case Scalar.QUOTE_DOUBLE:
        return doubleQuotedString(ss.value, ctx);
      case Scalar.QUOTE_SINGLE:
        return singleQuotedString(ss.value, ctx);
      case Scalar.PLAIN:
        return plainString(ss, ctx, onComment, onChompKeep);
      default:
        return null;
    }
  };
  let res = _stringify(type);
  if (res === null) {
    const { defaultKeyType, defaultStringType } = ctx.options;
    const t = implicitKey && defaultKeyType || defaultStringType;
    res = _stringify(t);
    if (res === null)
      throw new Error(`Unsupported default string type ${t}`);
  }
  return res;
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/stringify/stringify.js
function createStringifyContext(doc, options) {
  const opt = Object.assign({
    blockQuote: true,
    commentString: stringifyComment,
    defaultKeyType: null,
    defaultStringType: "PLAIN",
    directives: null,
    doubleQuotedAsJSON: false,
    doubleQuotedMinMultiLineLength: 40,
    falseStr: "false",
    flowCollectionPadding: true,
    indentSeq: true,
    lineWidth: 80,
    minContentWidth: 20,
    nullStr: "null",
    simpleKeys: false,
    singleQuote: null,
    trueStr: "true",
    verifyAliasOrder: true
  }, doc.schema.toStringOptions, options);
  let inFlow;
  switch (opt.collectionStyle) {
    case "block":
      inFlow = false;
      break;
    case "flow":
      inFlow = true;
      break;
    default:
      inFlow = null;
  }
  return {
    anchors: /* @__PURE__ */ new Set(),
    doc,
    flowCollectionPadding: opt.flowCollectionPadding ? " " : "",
    indent: "",
    indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : "  ",
    inFlow,
    options: opt
  };
}
function getTagObject(tags, item) {
  if (item.tag) {
    const match = tags.filter((t) => t.tag === item.tag);
    if (match.length > 0)
      return match.find((t) => t.format === item.format) ?? match[0];
  }
  let tagObj = void 0;
  let obj;
  if (isScalar(item)) {
    obj = item.value;
    let match = tags.filter((t) => t.identify?.(obj));
    if (match.length > 1) {
      const testMatch = match.filter((t) => t.test);
      if (testMatch.length > 0)
        match = testMatch;
    }
    tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format);
  } else {
    obj = item;
    tagObj = tags.find((t) => t.nodeClass && obj instanceof t.nodeClass);
  }
  if (!tagObj) {
    const name = obj?.constructor?.name ?? (obj === null ? "null" : typeof obj);
    throw new Error(`Tag not resolved for ${name} value`);
  }
  return tagObj;
}
function stringifyProps(node, tagObj, { anchors, doc }) {
  if (!doc.directives)
    return "";
  const props = [];
  const anchor = (isScalar(node) || isCollection(node)) && node.anchor;
  if (anchor && anchorIsValid(anchor)) {
    anchors.add(anchor);
    props.push(`&${anchor}`);
  }
  const tag = node.tag ?? (tagObj.default ? null : tagObj.tag);
  if (tag)
    props.push(doc.directives.tagString(tag));
  return props.join(" ");
}
function stringify(item, ctx, onComment, onChompKeep) {
  if (isPair(item))
    return item.toString(ctx, onComment, onChompKeep);
  if (isAlias(item)) {
    if (ctx.doc.directives)
      return item.toString(ctx);
    if (ctx.resolvedAliases?.has(item)) {
      throw new TypeError(`Cannot stringify circular structure without alias nodes`);
    } else {
      if (ctx.resolvedAliases)
        ctx.resolvedAliases.add(item);
      else
        ctx.resolvedAliases = /* @__PURE__ */ new Set([item]);
      item = item.resolve(ctx.doc);
    }
  }
  let tagObj = void 0;
  const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o });
  tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));
  const props = stringifyProps(node, tagObj, ctx);
  if (props.length > 0)
    ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;
  const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep);
  if (!props)
    return str;
  return isScalar(node) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props}
${ctx.indent}${str}`;
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/stringify/stringifyPair.js
function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
  const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
  let keyComment = isNode(key) && key.comment || null;
  if (simpleKeys) {
    if (keyComment) {
      throw new Error("With simple keys, key nodes cannot have comments");
    }
    if (isCollection(key) || !isNode(key) && typeof key === "object") {
      const msg = "With simple keys, collection cannot be used as a key value";
      throw new Error(msg);
    }
  }
  let explicitKey = !simpleKeys && (!key || keyComment && value == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object"));
  ctx = Object.assign({}, ctx, {
    allNullValues: false,
    implicitKey: !explicitKey && (simpleKeys || !allNullValues),
    indent: indent + indentStep
  });
  let keyCommentDone = false;
  let chompKeep = false;
  let str = stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true);
  if (!explicitKey && !ctx.inFlow && str.length > 1024) {
    if (simpleKeys)
      throw new Error("With simple keys, single line scalar must not span more than 1024 characters");
    explicitKey = true;
  }
  if (ctx.inFlow) {
    if (allNullValues || value == null) {
      if (keyCommentDone && onComment)
        onComment();
      return str === "" ? "?" : explicitKey ? `? ${str}` : str;
    }
  } else if (allNullValues && !simpleKeys || value == null && explicitKey) {
    str = `? ${str}`;
    if (keyComment && !keyCommentDone) {
      str += lineComment(str, ctx.indent, commentString(keyComment));
    } else if (chompKeep && onChompKeep)
      onChompKeep();
    return str;
  }
  if (keyCommentDone)
    keyComment = null;
  if (explicitKey) {
    if (keyComment)
      str += lineComment(str, ctx.indent, commentString(keyComment));
    str = `? ${str}
${indent}:`;
  } else {
    str = `${str}:`;
    if (keyComment)
      str += lineComment(str, ctx.indent, commentString(keyComment));
  }
  let vsb, vcb, valueComment;
  if (isNode(value)) {
    vsb = !!value.spaceBefore;
    vcb = value.commentBefore;
    valueComment = value.comment;
  } else {
    vsb = false;
    vcb = null;
    valueComment = null;
    if (value && typeof value === "object")
      value = doc.createNode(value);
  }
  ctx.implicitKey = false;
  if (!explicitKey && !keyComment && isScalar(value))
    ctx.indentAtStart = str.length + 1;
  chompKeep = false;
  if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value) && !value.flow && !value.tag && !value.anchor) {
    ctx.indent = ctx.indent.substring(2);
  }
  let valueCommentDone = false;
  const valueStr = stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true);
  let ws = " ";
  if (keyComment || vsb || vcb) {
    ws = vsb ? "\n" : "";
    if (vcb) {
      const cs = commentString(vcb);
      ws += `
${indentComment(cs, ctx.indent)}`;
    }
    if (valueStr === "" && !ctx.inFlow) {
      if (ws === "\n")
        ws = "\n\n";
    } else {
      ws += `
${ctx.indent}`;
    }
  } else if (!explicitKey && isCollection(value)) {
    const vs0 = valueStr[0];
    const nl0 = valueStr.indexOf("\n");
    const hasNewline = nl0 !== -1;
    const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;
    if (hasNewline || !flow) {
      let hasPropsLine = false;
      if (hasNewline && (vs0 === "&" || vs0 === "!")) {
        let sp0 = valueStr.indexOf(" ");
        if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") {
          sp0 = valueStr.indexOf(" ", sp0 + 1);
        }
        if (sp0 === -1 || nl0 < sp0)
          hasPropsLine = true;
      }
      if (!hasPropsLine)
        ws = `
${ctx.indent}`;
    }
  } else if (valueStr === "" || valueStr[0] === "\n") {
    ws = "";
  }
  str += ws + valueStr;
  if (ctx.inFlow) {
    if (valueCommentDone && onComment)
      onComment();
  } else if (valueComment && !valueCommentDone) {
    str += lineComment(str, ctx.indent, commentString(valueComment));
  } else if (chompKeep && onChompKeep) {
    onChompKeep();
  }
  return str;
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/log.js
function warn(logLevel, warning) {
  if (logLevel === "debug" || logLevel === "warn") {
    console.warn(warning);
  }
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js
var MERGE_KEY = "<<";
var merge = {
  identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY,
  default: "key",
  tag: "tag:yaml.org,2002:merge",
  test: /^<<$/,
  resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), {
    addToJSMap: addMergeToJSMap
  }),
  stringify: () => MERGE_KEY
};
var isMergeKey = (ctx, key) => (merge.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge.tag && tag.default);
function addMergeToJSMap(ctx, map2, value) {
  value = ctx && isAlias(value) ? value.resolve(ctx.doc) : value;
  if (isSeq(value))
    for (const it of value.items)
      mergeValue(ctx, map2, it);
  else if (Array.isArray(value))
    for (const it of value)
      mergeValue(ctx, map2, it);
  else
    mergeValue(ctx, map2, value);
}
function mergeValue(ctx, map2, value) {
  const source = ctx && isAlias(value) ? value.resolve(ctx.doc) : value;
  if (!isMap(source))
    throw new Error("Merge sources must be maps or map aliases");
  const srcMap = source.toJSON(null, ctx, Map);
  for (const [key, value2] of srcMap) {
    if (map2 instanceof Map) {
      if (!map2.has(key))
        map2.set(key, value2);
    } else if (map2 instanceof Set) {
      map2.add(key);
    } else if (!Object.prototype.hasOwnProperty.call(map2, key)) {
      Object.defineProperty(map2, key, {
        value: value2,
        writable: true,
        enumerable: true,
        configurable: true
      });
    }
  }
  return map2;
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/nodes/addPairToJSMap.js
function addPairToJSMap(ctx, map2, { key, value }) {
  if (isNode(key) && key.addToJSMap)
    key.addToJSMap(ctx, map2, value);
  else if (isMergeKey(ctx, key))
    addMergeToJSMap(ctx, map2, value);
  else {
    const jsKey = toJS(key, "", ctx);
    if (map2 instanceof Map) {
      map2.set(jsKey, toJS(value, jsKey, ctx));
    } else if (map2 instanceof Set) {
      map2.add(jsKey);
    } else {
      const stringKey = stringifyKey(key, jsKey, ctx);
      const jsValue = toJS(value, stringKey, ctx);
      if (stringKey in map2)
        Object.defineProperty(map2, stringKey, {
          value: jsValue,
          writable: true,
          enumerable: true,
          configurable: true
        });
      else
        map2[stringKey] = jsValue;
    }
  }
  return map2;
}
function stringifyKey(key, jsKey, ctx) {
  if (jsKey === null)
    return "";
  if (typeof jsKey !== "object")
    return String(jsKey);
  if (isNode(key) && ctx?.doc) {
    const strCtx = createStringifyContext(ctx.doc, {});
    strCtx.anchors = /* @__PURE__ */ new Set();
    for (const node of ctx.anchors.keys())
      strCtx.anchors.add(node.anchor);
    strCtx.inFlow = true;
    strCtx.inStringifyKey = true;
    const strKey = key.toString(strCtx);
    if (!ctx.mapKeyWarned) {
      let jsonStr = JSON.stringify(strKey);
      if (jsonStr.length > 40)
        jsonStr = jsonStr.substring(0, 36) + '..."';
      warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
      ctx.mapKeyWarned = true;
    }
    return strKey;
  }
  return JSON.stringify(jsKey);
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/nodes/Pair.js
function createPair(key, value, ctx) {
  const k = createNode(key, void 0, ctx);
  const v = createNode(value, void 0, ctx);
  return new Pair(k, v);
}
var Pair = class _Pair {
  constructor(key, value = null) {
    Object.defineProperty(this, NODE_TYPE, { value: PAIR });
    this.key = key;
    this.value = value;
  }
  clone(schema4) {
    let { key, value } = this;
    if (isNode(key))
      key = key.clone(schema4);
    if (isNode(value))
      value = value.clone(schema4);
    return new _Pair(key, value);
  }
  toJSON(_, ctx) {
    const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {};
    return addPairToJSMap(ctx, pair, this);
  }
  toString(ctx, onComment, onChompKeep) {
    return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this);
  }
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/stringify/stringifyCollection.js
function stringifyCollection(collection, ctx, options) {
  const flow = ctx.inFlow ?? collection.flow;
  const stringify4 = flow ? stringifyFlowCollection : stringifyBlockCollection;
  return stringify4(collection, ctx, options);
}
function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
  const { indent, options: { commentString } } = ctx;
  const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
  let chompKeep = false;
  const lines = [];
  for (let i = 0; i < items.length; ++i) {
    const item = items[i];
    let comment2 = null;
    if (isNode(item)) {
      if (!chompKeep && item.spaceBefore)
        lines.push("");
      addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
      if (item.comment)
        comment2 = item.comment;
    } else if (isPair(item)) {
      const ik = isNode(item.key) ? item.key : null;
      if (ik) {
        if (!chompKeep && ik.spaceBefore)
          lines.push("");
        addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
      }
    }
    chompKeep = false;
    let str2 = stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true);
    if (comment2)
      str2 += lineComment(str2, itemIndent, commentString(comment2));
    if (chompKeep && comment2)
      chompKeep = false;
    lines.push(blockItemPrefix + str2);
  }
  let str;
  if (lines.length === 0) {
    str = flowChars.start + flowChars.end;
  } else {
    str = lines[0];
    for (let i = 1; i < lines.length; ++i) {
      const line = lines[i];
      str += line ? `
${indent}${line}` : "\n";
    }
  }
  if (comment) {
    str += "\n" + indentComment(commentString(comment), indent);
    if (onComment)
      onComment();
  } else if (chompKeep && onChompKeep)
    onChompKeep();
  return str;
}
function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {
  const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;
  itemIndent += indentStep;
  const itemCtx = Object.assign({}, ctx, {
    indent: itemIndent,
    inFlow: true,
    type: null
  });
  let reqNewline = false;
  let linesAtValue = 0;
  const lines = [];
  for (let i = 0; i < items.length; ++i) {
    const item = items[i];
    let comment = null;
    if (isNode(item)) {
      if (item.spaceBefore)
        lines.push("");
      addCommentBefore(ctx, lines, item.commentBefore, false);
      if (item.comment)
        comment = item.comment;
    } else if (isPair(item)) {
      const ik = isNode(item.key) ? item.key : null;
      if (ik) {
        if (ik.spaceBefore)
          lines.push("");
        addCommentBefore(ctx, lines, ik.commentBefore, false);
        if (ik.comment)
          reqNewline = true;
      }
      const iv = isNode(item.value) ? item.value : null;
      if (iv) {
        if (iv.comment)
          comment = iv.comment;
        if (iv.commentBefore)
          reqNewline = true;
      } else if (item.value == null && ik?.comment) {
        comment = ik.comment;
      }
    }
    if (comment)
      reqNewline = true;
    let str = stringify(item, itemCtx, () => comment = null);
    if (i < items.length - 1)
      str += ",";
    if (comment)
      str += lineComment(str, itemIndent, commentString(comment));
    if (!reqNewline && (lines.length > linesAtValue || str.includes("\n")))
      reqNewline = true;
    lines.push(str);
    linesAtValue = lines.length;
  }
  const { start, end } = flowChars;
  if (lines.length === 0) {
    return start + end;
  } else {
    if (!reqNewline) {
      const len = lines.reduce((sum, line) => sum + line.length + 2, 2);
      reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;
    }
    if (reqNewline) {
      let str = start;
      for (const line of lines)
        str += line ? `
${indentStep}${indent}${line}` : "\n";
      return `${str}
${indent}${end}`;
    } else {
      return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`;
    }
  }
}
function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {
  if (comment && chompKeep)
    comment = comment.replace(/^\n+/, "");
  if (comment) {
    const ic = indentComment(commentString(comment), indent);
    lines.push(ic.trimStart());
  }
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/nodes/YAMLMap.js
function findPair(items, key) {
  const k = isScalar(key) ? key.value : key;
  for (const it of items) {
    if (isPair(it)) {
      if (it.key === key || it.key === k)
        return it;
      if (isScalar(it.key) && it.key.value === k)
        return it;
    }
  }
  return void 0;
}
var YAMLMap = class extends Collection {
  static get tagName() {
    return "tag:yaml.org,2002:map";
  }
  constructor(schema4) {
    super(MAP, schema4);
    this.items = [];
  }
  /**
   * A generic collection parsing method that can be extended
   * to other node classes that inherit from YAMLMap
   */
  static from(schema4, obj, ctx) {
    const { keepUndefined, replacer } = ctx;
    const map2 = new this(schema4);
    const add = (key, value) => {
      if (typeof replacer === "function")
        value = replacer.call(obj, key, value);
      else if (Array.isArray(replacer) && !replacer.includes(key))
        return;
      if (value !== void 0 || keepUndefined)
        map2.items.push(createPair(key, value, ctx));
    };
    if (obj instanceof Map) {
      for (const [key, value] of obj)
        add(key, value);
    } else if (obj && typeof obj === "object") {
      for (const key of Object.keys(obj))
        add(key, obj[key]);
    }
    if (typeof schema4.sortMapEntries === "function") {
      map2.items.sort(schema4.sortMapEntries);
    }
    return map2;
  }
  /**
   * Adds a value to the collection.
   *
   * @param overwrite - If not set `true`, using a key that is already in the
   *   collection will throw. Otherwise, overwrites the previous value.
   */
  add(pair, overwrite) {
    let _pair;
    if (isPair(pair))
      _pair = pair;
    else if (!pair || typeof pair !== "object" || !("key" in pair)) {
      _pair = new Pair(pair, pair?.value);
    } else
      _pair = new Pair(pair.key, pair.value);
    const prev = findPair(this.items, _pair.key);
    const sortEntries = this.schema?.sortMapEntries;
    if (prev) {
      if (!overwrite)
        throw new Error(`Key ${_pair.key} already set`);
      if (isScalar(prev.value) && isScalarValue(_pair.value))
        prev.value.value = _pair.value;
      else
        prev.value = _pair.value;
    } else if (sortEntries) {
      const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0);
      if (i === -1)
        this.items.push(_pair);
      else
        this.items.splice(i, 0, _pair);
    } else {
      this.items.push(_pair);
    }
  }
  delete(key) {
    const it = findPair(this.items, key);
    if (!it)
      return false;
    const del = this.items.splice(this.items.indexOf(it), 1);
    return del.length > 0;
  }
  get(key, keepScalar) {
    const it = findPair(this.items, key);
    const node = it?.value;
    return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0;
  }
  has(key) {
    return !!findPair(this.items, key);
  }
  set(key, value) {
    this.add(new Pair(key, value), true);
  }
  /**
   * @param ctx - Conversion context, originally set in Document#toJS()
   * @param {Class} Type - If set, forces the returned collection type
   * @returns Instance of Type, Map, or Object
   */
  toJSON(_, ctx, Type) {
    const map2 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {};
    if (ctx?.onCreate)
      ctx.onCreate(map2);
    for (const item of this.items)
      addPairToJSMap(ctx, map2, item);
    return map2;
  }
  toString(ctx, onComment, onChompKeep) {
    if (!ctx)
      return JSON.stringify(this);
    for (const item of this.items) {
      if (!isPair(item))
        throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
    }
    if (!ctx.allNullValues && this.hasAllNullValues(false))
      ctx = Object.assign({}, ctx, { allNullValues: true });
    return stringifyCollection(this, ctx, {
      blockItemPrefix: "",
      flowChars: { start: "{", end: "}" },
      itemIndent: ctx.indent || "",
      onChompKeep,
      onComment
    });
  }
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/common/map.js
var map = {
  collection: "map",
  default: true,
  nodeClass: YAMLMap,
  tag: "tag:yaml.org,2002:map",
  resolve(map2, onError) {
    if (!isMap(map2))
      onError("Expected a mapping for this tag");
    return map2;
  },
  createNode: (schema4, obj, ctx) => YAMLMap.from(schema4, obj, ctx)
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/nodes/YAMLSeq.js
var YAMLSeq = class extends Collection {
  static get tagName() {
    return "tag:yaml.org,2002:seq";
  }
  constructor(schema4) {
    super(SEQ, schema4);
    this.items = [];
  }
  add(value) {
    this.items.push(value);
  }
  /**
   * Removes a value from the collection.
   *
   * `key` must contain a representation of an integer for this to succeed.
   * It may be wrapped in a `Scalar`.
   *
   * @returns `true` if the item was found and removed.
   */
  delete(key) {
    const idx = asItemIndex(key);
    if (typeof idx !== "number")
      return false;
    const del = this.items.splice(idx, 1);
    return del.length > 0;
  }
  get(key, keepScalar) {
    const idx = asItemIndex(key);
    if (typeof idx !== "number")
      return void 0;
    const it = this.items[idx];
    return !keepScalar && isScalar(it) ? it.value : it;
  }
  /**
   * Checks if the collection includes a value with the key `key`.
   *
   * `key` must contain a representation of an integer for this to succeed.
   * It may be wrapped in a `Scalar`.
   */
  has(key) {
    const idx = asItemIndex(key);
    return typeof idx === "number" && idx < this.items.length;
  }
  /**
   * Sets a value in this collection. For `!!set`, `value` needs to be a
   * boolean to add/remove the item from the set.
   *
   * If `key` does not contain a representation of an integer, this will throw.
   * It may be wrapped in a `Scalar`.
   */
  set(key, value) {
    const idx = asItemIndex(key);
    if (typeof idx !== "number")
      throw new Error(`Expected a valid index, not ${key}.`);
    const prev = this.items[idx];
    if (isScalar(prev) && isScalarValue(value))
      prev.value = value;
    else
      this.items[idx] = value;
  }
  toJSON(_, ctx) {
    const seq2 = [];
    if (ctx?.onCreate)
      ctx.onCreate(seq2);
    let i = 0;
    for (const item of this.items)
      seq2.push(toJS(item, String(i++), ctx));
    return seq2;
  }
  toString(ctx, onComment, onChompKeep) {
    if (!ctx)
      return JSON.stringify(this);
    return stringifyCollection(this, ctx, {
      blockItemPrefix: "- ",
      flowChars: { start: "[", end: "]" },
      itemIndent: (ctx.indent || "") + "  ",
      onChompKeep,
      onComment
    });
  }
  static from(schema4, obj, ctx) {
    const { replacer } = ctx;
    const seq2 = new this(schema4);
    if (obj && Symbol.iterator in Object(obj)) {
      let i = 0;
      for (let it of obj) {
        if (typeof replacer === "function") {
          const key = obj instanceof Set ? it : String(i++);
          it = replacer.call(obj, key, it);
        }
        seq2.items.push(createNode(it, void 0, ctx));
      }
    }
    return seq2;
  }
};
function asItemIndex(key) {
  let idx = isScalar(key) ? key.value : key;
  if (idx && typeof idx === "string")
    idx = Number(idx);
  return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null;
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/common/seq.js
var seq = {
  collection: "seq",
  default: true,
  nodeClass: YAMLSeq,
  tag: "tag:yaml.org,2002:seq",
  resolve(seq2, onError) {
    if (!isSeq(seq2))
      onError("Expected a sequence for this tag");
    return seq2;
  },
  createNode: (schema4, obj, ctx) => YAMLSeq.from(schema4, obj, ctx)
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/common/string.js
var string = {
  identify: (value) => typeof value === "string",
  default: true,
  tag: "tag:yaml.org,2002:str",
  resolve: (str) => str,
  stringify(item, ctx, onComment, onChompKeep) {
    ctx = Object.assign({ actualString: true }, ctx);
    return stringifyString(item, ctx, onComment, onChompKeep);
  }
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/common/null.js
var nullTag = {
  identify: (value) => value == null,
  createNode: () => new Scalar(null),
  default: true,
  tag: "tag:yaml.org,2002:null",
  test: /^(?:~|[Nn]ull|NULL)?$/,
  resolve: () => new Scalar(null),
  stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/core/bool.js
var boolTag = {
  identify: (value) => typeof value === "boolean",
  default: true,
  tag: "tag:yaml.org,2002:bool",
  test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
  resolve: (str) => new Scalar(str[0] === "t" || str[0] === "T"),
  stringify({ source, value }, ctx) {
    if (source && boolTag.test.test(source)) {
      const sv = source[0] === "t" || source[0] === "T";
      if (value === sv)
        return source;
    }
    return value ? ctx.options.trueStr : ctx.options.falseStr;
  }
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/stringify/stringifyNumber.js
function stringifyNumber({ format, minFractionDigits, tag, value }) {
  if (typeof value === "bigint")
    return String(value);
  const num = typeof value === "number" ? value : Number(value);
  if (!isFinite(num))
    return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf";
  let n = JSON.stringify(value);
  if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^\d/.test(n)) {
    let i = n.indexOf(".");
    if (i < 0) {
      i = n.length;
      n += ".";
    }
    let d = minFractionDigits - (n.length - i - 1);
    while (d-- > 0)
      n += "0";
  }
  return n;
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/core/float.js
var floatNaN = {
  identify: (value) => typeof value === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
  resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
  stringify: stringifyNumber
};
var floatExp = {
  identify: (value) => typeof value === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  format: "EXP",
  test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
  resolve: (str) => parseFloat(str),
  stringify(node) {
    const num = Number(node.value);
    return isFinite(num) ? num.toExponential() : stringifyNumber(node);
  }
};
var float = {
  identify: (value) => typeof value === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,
  resolve(str) {
    const node = new Scalar(parseFloat(str));
    const dot = str.indexOf(".");
    if (dot !== -1 && str[str.length - 1] === "0")
      node.minFractionDigits = str.length - dot - 1;
    return node;
  },
  stringify: stringifyNumber
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/core/int.js
var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value);
var intResolve = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix);
function intStringify(node, radix, prefix) {
  const { value } = node;
  if (intIdentify(value) && value >= 0)
    return prefix + value.toString(radix);
  return stringifyNumber(node);
}
var intOct = {
  identify: (value) => intIdentify(value) && value >= 0,
  default: true,
  tag: "tag:yaml.org,2002:int",
  format: "OCT",
  test: /^0o[0-7]+$/,
  resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),
  stringify: (node) => intStringify(node, 8, "0o")
};
var int = {
  identify: intIdentify,
  default: true,
  tag: "tag:yaml.org,2002:int",
  test: /^[-+]?[0-9]+$/,
  resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
  stringify: stringifyNumber
};
var intHex = {
  identify: (value) => intIdentify(value) && value >= 0,
  default: true,
  tag: "tag:yaml.org,2002:int",
  format: "HEX",
  test: /^0x[0-9a-fA-F]+$/,
  resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
  stringify: (node) => intStringify(node, 16, "0x")
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/core/schema.js
var schema = [
  map,
  seq,
  string,
  nullTag,
  boolTag,
  intOct,
  int,
  intHex,
  floatNaN,
  floatExp,
  float
];

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/json/schema.js
function intIdentify2(value) {
  return typeof value === "bigint" || Number.isInteger(value);
}
var stringifyJSON = ({ value }) => JSON.stringify(value);
var jsonScalars = [
  {
    identify: (value) => typeof value === "string",
    default: true,
    tag: "tag:yaml.org,2002:str",
    resolve: (str) => str,
    stringify: stringifyJSON
  },
  {
    identify: (value) => value == null,
    createNode: () => new Scalar(null),
    default: true,
    tag: "tag:yaml.org,2002:null",
    test: /^null$/,
    resolve: () => null,
    stringify: stringifyJSON
  },
  {
    identify: (value) => typeof value === "boolean",
    default: true,
    tag: "tag:yaml.org,2002:bool",
    test: /^true$|^false$/,
    resolve: (str) => str === "true",
    stringify: stringifyJSON
  },
  {
    identify: intIdentify2,
    default: true,
    tag: "tag:yaml.org,2002:int",
    test: /^-?(?:0|[1-9][0-9]*)$/,
    resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
    stringify: ({ value }) => intIdentify2(value) ? value.toString() : JSON.stringify(value)
  },
  {
    identify: (value) => typeof value === "number",
    default: true,
    tag: "tag:yaml.org,2002:float",
    test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
    resolve: (str) => parseFloat(str),
    stringify: stringifyJSON
  }
];
var jsonError = {
  default: true,
  tag: "",
  test: /^/,
  resolve(str, onError) {
    onError(`Unresolved plain scalar ${JSON.stringify(str)}`);
    return str;
  }
};
var schema2 = [map, seq].concat(jsonScalars, jsonError);

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js
var binary = {
  identify: (value) => value instanceof Uint8Array,
  // Buffer inherits from Uint8Array
  default: false,
  tag: "tag:yaml.org,2002:binary",
  /**
   * Returns a Buffer in node and an Uint8Array in browsers
   *
   * To use the resulting buffer as an image, you'll want to do something like:
   *
   *   const blob = new Blob([buffer], { type: 'image/jpeg' })
   *   document.querySelector('#photo').src = URL.createObjectURL(blob)
   */
  resolve(src, onError) {
    if (typeof atob === "function") {
      const str = atob(src.replace(/[\n\r]/g, ""));
      const buffer = new Uint8Array(str.length);
      for (let i = 0; i < str.length; ++i)
        buffer[i] = str.charCodeAt(i);
      return buffer;
    } else {
      onError("This environment does not support reading binary tags; either Buffer or atob is required");
      return src;
    }
  },
  stringify({ comment, type, value }, ctx, onComment, onChompKeep) {
    if (!value)
      return "";
    const buf = value;
    let str;
    if (typeof btoa === "function") {
      let s = "";
      for (let i = 0; i < buf.length; ++i)
        s += String.fromCharCode(buf[i]);
      str = btoa(s);
    } else {
      throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");
    }
    type ?? (type = Scalar.BLOCK_LITERAL);
    if (type !== Scalar.QUOTE_DOUBLE) {
      const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
      const n = Math.ceil(str.length / lineWidth);
      const lines = new Array(n);
      for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {
        lines[i] = str.substr(o, lineWidth);
      }
      str = lines.join(type === Scalar.BLOCK_LITERAL ? "\n" : " ");
    }
    return stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);
  }
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js
function resolvePairs(seq2, onError) {
  if (isSeq(seq2)) {
    for (let i = 0; i < seq2.items.length; ++i) {
      let item = seq2.items[i];
      if (isPair(item))
        continue;
      else if (isMap(item)) {
        if (item.items.length > 1)
          onError("Each pair must have its own sequence indicator");
        const pair = item.items[0] || new Pair(new Scalar(null));
        if (item.commentBefore)
          pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore}
${pair.key.commentBefore}` : item.commentBefore;
        if (item.comment) {
          const cn = pair.value ?? pair.key;
          cn.comment = cn.comment ? `${item.comment}
${cn.comment}` : item.comment;
        }
        item = pair;
      }
      seq2.items[i] = isPair(item) ? item : new Pair(item);
    }
  } else
    onError("Expected a sequence for this tag");
  return seq2;
}
function createPairs(schema4, iterable, ctx) {
  const { replacer } = ctx;
  const pairs2 = new YAMLSeq(schema4);
  pairs2.tag = "tag:yaml.org,2002:pairs";
  let i = 0;
  if (iterable && Symbol.iterator in Object(iterable))
    for (let it of iterable) {
      if (typeof replacer === "function")
        it = replacer.call(iterable, String(i++), it);
      let key, value;
      if (Array.isArray(it)) {
        if (it.length === 2) {
          key = it[0];
          value = it[1];
        } else
          throw new TypeError(`Expected [key, value] tuple: ${it}`);
      } else if (it && it instanceof Object) {
        const keys = Object.keys(it);
        if (keys.length === 1) {
          key = keys[0];
          value = it[key];
        } else {
          throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);
        }
      } else {
        key = it;
      }
      pairs2.items.push(createPair(key, value, ctx));
    }
  return pairs2;
}
var pairs = {
  collection: "seq",
  default: false,
  tag: "tag:yaml.org,2002:pairs",
  resolve: resolvePairs,
  createNode: createPairs
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js
var YAMLOMap = class _YAMLOMap extends YAMLSeq {
  constructor() {
    super();
    this.add = YAMLMap.prototype.add.bind(this);
    this.delete = YAMLMap.prototype.delete.bind(this);
    this.get = YAMLMap.prototype.get.bind(this);
    this.has = YAMLMap.prototype.has.bind(this);
    this.set = YAMLMap.prototype.set.bind(this);
    this.tag = _YAMLOMap.tag;
  }
  /**
   * If `ctx` is given, the return type is actually `Map<unknown, unknown>`,
   * but TypeScript won't allow widening the signature of a child method.
   */
  toJSON(_, ctx) {
    if (!ctx)
      return super.toJSON(_);
    const map2 = /* @__PURE__ */ new Map();
    if (ctx?.onCreate)
      ctx.onCreate(map2);
    for (const pair of this.items) {
      let key, value;
      if (isPair(pair)) {
        key = toJS(pair.key, "", ctx);
        value = toJS(pair.value, key, ctx);
      } else {
        key = toJS(pair, "", ctx);
      }
      if (map2.has(key))
        throw new Error("Ordered maps must not include duplicate keys");
      map2.set(key, value);
    }
    return map2;
  }
  static from(schema4, iterable, ctx) {
    const pairs2 = createPairs(schema4, iterable, ctx);
    const omap2 = new this();
    omap2.items = pairs2.items;
    return omap2;
  }
};
YAMLOMap.tag = "tag:yaml.org,2002:omap";
var omap = {
  collection: "seq",
  identify: (value) => value instanceof Map,
  nodeClass: YAMLOMap,
  default: false,
  tag: "tag:yaml.org,2002:omap",
  resolve(seq2, onError) {
    const pairs2 = resolvePairs(seq2, onError);
    const seenKeys = [];
    for (const { key } of pairs2.items) {
      if (isScalar(key)) {
        if (seenKeys.includes(key.value)) {
          onError(`Ordered maps must not include duplicate keys: ${key.value}`);
        } else {
          seenKeys.push(key.value);
        }
      }
    }
    return Object.assign(new YAMLOMap(), pairs2);
  },
  createNode: (schema4, iterable, ctx) => YAMLOMap.from(schema4, iterable, ctx)
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js
function boolStringify({ value, source }, ctx) {
  const boolObj = value ? trueTag : falseTag;
  if (source && boolObj.test.test(source))
    return source;
  return value ? ctx.options.trueStr : ctx.options.falseStr;
}
var trueTag = {
  identify: (value) => value === true,
  default: true,
  tag: "tag:yaml.org,2002:bool",
  test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
  resolve: () => new Scalar(true),
  stringify: boolStringify
};
var falseTag = {
  identify: (value) => value === false,
  default: true,
  tag: "tag:yaml.org,2002:bool",
  test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,
  resolve: () => new Scalar(false),
  stringify: boolStringify
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/yaml-1.1/float.js
var floatNaN2 = {
  identify: (value) => typeof value === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
  resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
  stringify: stringifyNumber
};
var floatExp2 = {
  identify: (value) => typeof value === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  format: "EXP",
  test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
  resolve: (str) => parseFloat(str.replace(/_/g, "")),
  stringify(node) {
    const num = Number(node.value);
    return isFinite(num) ? num.toExponential() : stringifyNumber(node);
  }
};
var float2 = {
  identify: (value) => typeof value === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
  resolve(str) {
    const node = new Scalar(parseFloat(str.replace(/_/g, "")));
    const dot = str.indexOf(".");
    if (dot !== -1) {
      const f = str.substring(dot + 1).replace(/_/g, "");
      if (f[f.length - 1] === "0")
        node.minFractionDigits = f.length;
    }
    return node;
  },
  stringify: stringifyNumber
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/yaml-1.1/int.js
var intIdentify3 = (value) => typeof value === "bigint" || Number.isInteger(value);
function intResolve2(str, offset, radix, { intAsBigInt }) {
  const sign = str[0];
  if (sign === "-" || sign === "+")
    offset += 1;
  str = str.substring(offset).replace(/_/g, "");
  if (intAsBigInt) {
    switch (radix) {
      case 2:
        str = `0b${str}`;
        break;
      case 8:
        str = `0o${str}`;
        break;
      case 16:
        str = `0x${str}`;
        break;
    }
    const n2 = BigInt(str);
    return sign === "-" ? BigInt(-1) * n2 : n2;
  }
  const n = parseInt(str, radix);
  return sign === "-" ? -1 * n : n;
}
function intStringify2(node, radix, prefix) {
  const { value } = node;
  if (intIdentify3(value)) {
    const str = value.toString(radix);
    return value < 0 ? "-" + prefix + str.substr(1) : prefix + str;
  }
  return stringifyNumber(node);
}
var intBin = {
  identify: intIdentify3,
  default: true,
  tag: "tag:yaml.org,2002:int",
  format: "BIN",
  test: /^[-+]?0b[0-1_]+$/,
  resolve: (str, _onError, opt) => intResolve2(str, 2, 2, opt),
  stringify: (node) => intStringify2(node, 2, "0b")
};
var intOct2 = {
  identify: intIdentify3,
  default: true,
  tag: "tag:yaml.org,2002:int",
  format: "OCT",
  test: /^[-+]?0[0-7_]+$/,
  resolve: (str, _onError, opt) => intResolve2(str, 1, 8, opt),
  stringify: (node) => intStringify2(node, 8, "0")
};
var int2 = {
  identify: intIdentify3,
  default: true,
  tag: "tag:yaml.org,2002:int",
  test: /^[-+]?[0-9][0-9_]*$/,
  resolve: (str, _onError, opt) => intResolve2(str, 0, 10, opt),
  stringify: stringifyNumber
};
var intHex2 = {
  identify: intIdentify3,
  default: true,
  tag: "tag:yaml.org,2002:int",
  format: "HEX",
  test: /^[-+]?0x[0-9a-fA-F_]+$/,
  resolve: (str, _onError, opt) => intResolve2(str, 2, 16, opt),
  stringify: (node) => intStringify2(node, 16, "0x")
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/yaml-1.1/set.js
var YAMLSet = class _YAMLSet extends YAMLMap {
  constructor(schema4) {
    super(schema4);
    this.tag = _YAMLSet.tag;
  }
  add(key) {
    let pair;
    if (isPair(key))
      pair = key;
    else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null)
      pair = new Pair(key.key, null);
    else
      pair = new Pair(key, null);
    const prev = findPair(this.items, pair.key);
    if (!prev)
      this.items.push(pair);
  }
  /**
   * If `keepPair` is `true`, returns the Pair matching `key`.
   * Otherwise, returns the value of that Pair's key.
   */
  get(key, keepPair) {
    const pair = findPair(this.items, key);
    return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair;
  }
  set(key, value) {
    if (typeof value !== "boolean")
      throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
    const prev = findPair(this.items, key);
    if (prev && !value) {
      this.items.splice(this.items.indexOf(prev), 1);
    } else if (!prev && value) {
      this.items.push(new Pair(key));
    }
  }
  toJSON(_, ctx) {
    return super.toJSON(_, ctx, Set);
  }
  toString(ctx, onComment, onChompKeep) {
    if (!ctx)
      return JSON.stringify(this);
    if (this.hasAllNullValues(true))
      return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);
    else
      throw new Error("Set items must all have null values");
  }
  static from(schema4, iterable, ctx) {
    const { replacer } = ctx;
    const set2 = new this(schema4);
    if (iterable && Symbol.iterator in Object(iterable))
      for (let value of iterable) {
        if (typeof replacer === "function")
          value = replacer.call(iterable, value, value);
        set2.items.push(createPair(value, null, ctx));
      }
    return set2;
  }
};
YAMLSet.tag = "tag:yaml.org,2002:set";
var set = {
  collection: "map",
  identify: (value) => value instanceof Set,
  nodeClass: YAMLSet,
  default: false,
  tag: "tag:yaml.org,2002:set",
  createNode: (schema4, iterable, ctx) => YAMLSet.from(schema4, iterable, ctx),
  resolve(map2, onError) {
    if (isMap(map2)) {
      if (map2.hasAllNullValues(true))
        return Object.assign(new YAMLSet(), map2);
      else
        onError("Set items must all have null values");
    } else
      onError("Expected a mapping for this tag");
    return map2;
  }
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js
function parseSexagesimal(str, asBigInt) {
  const sign = str[0];
  const parts = sign === "-" || sign === "+" ? str.substring(1) : str;
  const num = (n) => asBigInt ? BigInt(n) : Number(n);
  const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num(60) + num(p), num(0));
  return sign === "-" ? num(-1) * res : res;
}
function stringifySexagesimal(node) {
  let { value } = node;
  let num = (n) => n;
  if (typeof value === "bigint")
    num = (n) => BigInt(n);
  else if (isNaN(value) || !isFinite(value))
    return stringifyNumber(node);
  let sign = "";
  if (value < 0) {
    sign = "-";
    value *= num(-1);
  }
  const _60 = num(60);
  const parts = [value % _60];
  if (value < 60) {
    parts.unshift(0);
  } else {
    value = (value - parts[0]) / _60;
    parts.unshift(value % _60);
    if (value >= 60) {
      value = (value - parts[0]) / _60;
      parts.unshift(value);
    }
  }
  return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, "");
}
var intTime = {
  identify: (value) => typeof value === "bigint" || Number.isInteger(value),
  default: true,
  tag: "tag:yaml.org,2002:int",
  format: "TIME",
  test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
  resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),
  stringify: stringifySexagesimal
};
var floatTime = {
  identify: (value) => typeof value === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  format: "TIME",
  test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,
  resolve: (str) => parseSexagesimal(str, false),
  stringify: stringifySexagesimal
};
var timestamp = {
  identify: (value) => value instanceof Date,
  default: true,
  tag: "tag:yaml.org,2002:timestamp",
  // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
  // may be omitted altogether, resulting in a date format. In such a case, the time part is
  // assumed to be 00:00:00Z (start of day, UTC).
  test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),
  resolve(str) {
    const match = str.match(timestamp.test);
    if (!match)
      throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");
    const [, year, month, day, hour, minute, second] = match.map(Number);
    const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0;
    let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
    const tz = match[8];
    if (tz && tz !== "Z") {
      let d = parseSexagesimal(tz, false);
      if (Math.abs(d) < 30)
        d *= 60;
      date -= 6e4 * d;
    }
    return new Date(date);
  },
  stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? ""
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js
var schema3 = [
  map,
  seq,
  string,
  nullTag,
  trueTag,
  falseTag,
  intBin,
  intOct2,
  int2,
  intHex2,
  floatNaN2,
  floatExp2,
  float2,
  binary,
  merge,
  omap,
  pairs,
  set,
  intTime,
  floatTime,
  timestamp
];

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/tags.js
var schemas = /* @__PURE__ */ new Map([
  ["core", schema],
  ["failsafe", [map, seq, string]],
  ["json", schema2],
  ["yaml11", schema3],
  ["yaml-1.1", schema3]
]);
var tagsByName = {
  binary,
  bool: boolTag,
  float,
  floatExp,
  floatNaN,
  floatTime,
  int,
  intHex,
  intOct,
  intTime,
  map,
  merge,
  null: nullTag,
  omap,
  pairs,
  seq,
  set,
  timestamp
};
var coreKnownTags = {
  "tag:yaml.org,2002:binary": binary,
  "tag:yaml.org,2002:merge": merge,
  "tag:yaml.org,2002:omap": omap,
  "tag:yaml.org,2002:pairs": pairs,
  "tag:yaml.org,2002:set": set,
  "tag:yaml.org,2002:timestamp": timestamp
};
function getTags(customTags, schemaName, addMergeTag) {
  const schemaTags = schemas.get(schemaName);
  if (schemaTags && !customTags) {
    return addMergeTag && !schemaTags.includes(merge) ? schemaTags.concat(merge) : schemaTags.slice();
  }
  let tags = schemaTags;
  if (!tags) {
    if (Array.isArray(customTags))
      tags = [];
    else {
      const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", ");
      throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`);
    }
  }
  if (Array.isArray(customTags)) {
    for (const tag of customTags)
      tags = tags.concat(tag);
  } else if (typeof customTags === "function") {
    tags = customTags(tags.slice());
  }
  if (addMergeTag)
    tags = tags.concat(merge);
  return tags.reduce((tags2, tag) => {
    const tagObj = typeof tag === "string" ? tagsByName[tag] : tag;
    if (!tagObj) {
      const tagName = JSON.stringify(tag);
      const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", ");
      throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`);
    }
    if (!tags2.includes(tagObj))
      tags2.push(tagObj);
    return tags2;
  }, []);
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/schema/Schema.js
var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
var Schema = class _Schema {
  constructor({ compat, customTags, merge: merge2, resolveKnownTags, schema: schema4, sortMapEntries, toStringDefaults }) {
    this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null;
    this.name = typeof schema4 === "string" && schema4 || "core";
    this.knownTags = resolveKnownTags ? coreKnownTags : {};
    this.tags = getTags(customTags, this.name, merge2);
    this.toStringOptions = toStringDefaults ?? null;
    Object.defineProperty(this, MAP, { value: map });
    Object.defineProperty(this, SCALAR, { value: string });
    Object.defineProperty(this, SEQ, { value: seq });
    this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null;
  }
  clone() {
    const copy = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this));
    copy.tags = this.tags.slice();
    return copy;
  }
};

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/stringify/stringifyDocument.js
function stringifyDocument(doc, options) {
  const lines = [];
  let hasDirectives = options.directives === true;
  if (options.directives !== false && doc.directives) {
    const dir = doc.directives.toString(doc);
    if (dir) {
      lines.push(dir);
      hasDirectives = true;
    } else if (doc.directives.docStart)
      hasDirectives = true;
  }
  if (hasDirectives)
    lines.push("---");
  const ctx = createStringifyContext(doc, options);
  const { commentString } = ctx.options;
  if (doc.commentBefore) {
    if (lines.length !== 1)
      lines.unshift("");
    const cs = commentString(doc.commentBefore);
    lines.unshift(indentComment(cs, ""));
  }
  let chompKeep = false;
  let contentComment = null;
  if (doc.contents) {
    if (isNode(doc.contents)) {
      if (doc.contents.spaceBefore && hasDirectives)
        lines.push("");
      if (doc.contents.commentBefore) {
        const cs = commentString(doc.contents.commentBefore);
        lines.push(indentComment(cs, ""));
      }
      ctx.forceBlockIndent = !!doc.comment;
      contentComment = doc.contents.comment;
    }
    const onChompKeep = contentComment ? void 0 : () => chompKeep = true;
    let body = stringify(doc.contents, ctx, () => contentComment = null, onChompKeep);
    if (contentComment)
      body += lineComment(body, "", commentString(contentComment));
    if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") {
      lines[lines.length - 1] = `--- ${body}`;
    } else
      lines.push(body);
  } else {
    lines.push(stringify(doc.contents, ctx));
  }
  if (doc.directives?.docEnd) {
    if (doc.comment) {
      const cs = commentString(doc.comment);
      if (cs.includes("\n")) {
        lines.push("...");
        lines.push(indentComment(cs, ""));
      } else {
        lines.push(`... ${cs}`);
      }
    } else {
      lines.push("...");
    }
  } else {
    let dc = doc.comment;
    if (dc && chompKeep)
      dc = dc.replace(/^\n+/, "");
    if (dc) {
      if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "")
        lines.push("");
      lines.push(indentComment(commentString(dc), ""));
    }
  }
  return lines.join("\n") + "\n";
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/doc/Document.js
var Document = class _Document {
  constructor(value, replacer, options) {
    this.commentBefore = null;
    this.comment = null;
    this.errors = [];
    this.warnings = [];
    Object.defineProperty(this, NODE_TYPE, { value: DOC });
    let _replacer = null;
    if (typeof replacer === "function" || Array.isArray(replacer)) {
      _replacer = replacer;
    } else if (options === void 0 && replacer) {
      options = replacer;
      replacer = void 0;
    }
    const opt = Object.assign({
      intAsBigInt: false,
      keepSourceTokens: false,
      logLevel: "warn",
      prettyErrors: true,
      strict: true,
      stringKeys: false,
      uniqueKeys: true,
      version: "1.2"
    }, options);
    this.options = opt;
    let { version } = opt;
    if (options?._directives) {
      this.directives = options._directives.atDocument();
      if (this.directives.yaml.explicit)
        version = this.directives.yaml.version;
    } else
      this.directives = new Directives({ version });
    this.setSchema(version, options);
    this.contents = value === void 0 ? null : this.createNode(value, _replacer, options);
  }
  /**
   * Create a deep copy of this Document and its contents.
   *
   * Custom Node values that inherit from `Object` still refer to their original instances.
   */
  clone() {
    const copy = Object.create(_Document.prototype, {
      [NODE_TYPE]: { value: DOC }
    });
    copy.commentBefore = this.commentBefore;
    copy.comment = this.comment;
    copy.errors = this.errors.slice();
    copy.warnings = this.warnings.slice();
    copy.options = Object.assign({}, this.options);
    if (this.directives)
      copy.directives = this.directives.clone();
    copy.schema = this.schema.clone();
    copy.contents = isNode(this.contents) ? this.contents.clone(copy.schema) : this.contents;
    if (this.range)
      copy.range = this.range.slice();
    return copy;
  }
  /** Adds a value to the document. */
  add(value) {
    if (assertCollection(this.contents))
      this.contents.add(value);
  }
  /** Adds a value to the document. */
  addIn(path, value) {
    if (assertCollection(this.contents))
      this.contents.addIn(path, value);
  }
  /**
   * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
   *
   * If `node` already has an anchor, `name` is ignored.
   * Otherwise, the `node.anchor` value will be set to `name`,
   * or if an anchor with that name is already present in the document,
   * `name` will be used as a prefix for a new unique anchor.
   * If `name` is undefined, the generated anchor will use 'a' as a prefix.
   */
  createAlias(node, name) {
    if (!node.anchor) {
      const prev = anchorNames(this);
      node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
      !name || prev.has(name) ? findNewAnchor(name || "a", prev) : name;
    }
    return new Alias(node.anchor);
  }
  createNode(value, replacer, options) {
    let _replacer = void 0;
    if (typeof replacer === "function") {
      value = replacer.call({ "": value }, "", value);
      _replacer = replacer;
    } else if (Array.isArray(replacer)) {
      const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number;
      const asStr = replacer.filter(keyToStr).map(String);
      if (asStr.length > 0)
        replacer = replacer.concat(asStr);
      _replacer = replacer;
    } else if (options === void 0 && replacer) {
      options = replacer;
      replacer = void 0;
    }
    const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};
    const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors(
      this,
      // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
      anchorPrefix || "a"
    );
    const ctx = {
      aliasDuplicateObjects: aliasDuplicateObjects ?? true,
      keepUndefined: keepUndefined ?? false,
      onAnchor,
      onTagObj,
      replacer: _replacer,
      schema: this.schema,
      sourceObjects
    };
    const node = createNode(value, tag, ctx);
    if (flow && isCollection(node))
      node.flow = true;
    setAnchors();
    return node;
  }
  /**
   * Convert a key and a value into a `Pair` using the current schema,
   * recursively wrapping all values as `Scalar` or `Collection` nodes.
   */
  createPair(key, value, options = {}) {
    const k = this.createNode(key, null, options);
    const v = this.createNode(value, null, options);
    return new Pair(k, v);
  }
  /**
   * Removes a value from the document.
   * @returns `true` if the item was found and removed.
   */
  delete(key) {
    return assertCollection(this.contents) ? this.contents.delete(key) : false;
  }
  /**
   * Removes a value from the document.
   * @returns `true` if the item was found and removed.
   */
  deleteIn(path) {
    if (isEmptyPath(path)) {
      if (this.contents == null)
        return false;
      this.contents = null;
      return true;
    }
    return assertCollection(this.contents) ? this.contents.deleteIn(path) : false;
  }
  /**
   * Returns item at `key`, or `undefined` if not found. By default unwraps
   * scalar values from their surrounding node; to disable set `keepScalar` to
   * `true` (collections are always returned intact).
   */
  get(key, keepScalar) {
    return isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0;
  }
  /**
   * Returns item at `path`, or `undefined` if not found. By default unwraps
   * scalar values from their surrounding node; to disable set `keepScalar` to
   * `true` (collections are always returned intact).
   */
  getIn(path, keepScalar) {
    if (isEmptyPath(path))
      return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents;
    return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0;
  }
  /**
   * Checks if the document includes a value with the key `key`.
   */
  has(key) {
    return isCollection(this.contents) ? this.contents.has(key) : false;
  }
  /**
   * Checks if the document includes a value at `path`.
   */
  hasIn(path) {
    if (isEmptyPath(path))
      return this.contents !== void 0;
    return isCollection(this.contents) ? this.contents.hasIn(path) : false;
  }
  /**
   * Sets a value in this document. For `!!set`, `value` needs to be a
   * boolean to add/remove the item from the set.
   */
  set(key, value) {
    if (this.contents == null) {
      this.contents = collectionFromPath(this.schema, [key], value);
    } else if (assertCollection(this.contents)) {
      this.contents.set(key, value);
    }
  }
  /**
   * Sets a value in this document. For `!!set`, `value` needs to be a
   * boolean to add/remove the item from the set.
   */
  setIn(path, value) {
    if (isEmptyPath(path)) {
      this.contents = value;
    } else if (this.contents == null) {
      this.contents = collectionFromPath(this.schema, Array.from(path), value);
    } else if (assertCollection(this.contents)) {
      this.contents.setIn(path, value);
    }
  }
  /**
   * Change the YAML version and schema used by the document.
   * A `null` version disables support for directives, explicit tags, anchors, and aliases.
   * It also requires the `schema` option to be given as a `Schema` instance value.
   *
   * Overrides all previously set schema options.
   */
  setSchema(version, options = {}) {
    if (typeof version === "number")
      version = String(version);
    let opt;
    switch (version) {
      case "1.1":
        if (this.directives)
          this.directives.yaml.version = "1.1";
        else
          this.directives = new Directives({ version: "1.1" });
        opt = { resolveKnownTags: false, schema: "yaml-1.1" };
        break;
      case "1.2":
      case "next":
        if (this.directives)
          this.directives.yaml.version = version;
        else
          this.directives = new Directives({ version });
        opt = { resolveKnownTags: true, schema: "core" };
        break;
      case null:
        if (this.directives)
          delete this.directives;
        opt = null;
        break;
      default: {
        const sv = JSON.stringify(version);
        throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
      }
    }
    if (options.schema instanceof Object)
      this.schema = options.schema;
    else if (opt)
      this.schema = new Schema(Object.assign(opt, options));
    else
      throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
  }
  // json & jsonArg are only used from toJSON()
  toJS({ json: json2, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
    const ctx = {
      anchors: /* @__PURE__ */ new Map(),
      doc: this,
      keep: !json2,
      mapAsMap: mapAsMap === true,
      mapKeyWarned: false,
      maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
    };
    const res = toJS(this.contents, jsonArg ?? "", ctx);
    if (typeof onAnchor === "function")
      for (const { count, res: res2 } of ctx.anchors.values())
        onAnchor(res2, count);
    return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res;
  }
  /**
   * A JSON representation of the document `contents`.
   *
   * @param jsonArg Used by `JSON.stringify` to indicate the array index or
   *   property name.
   */
  toJSON(jsonArg, onAnchor) {
    return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
  }
  /** A YAML representation of the document. */
  toString(options = {}) {
    if (this.errors.length > 0)
      throw new Error("Document with errors cannot be stringified");
    if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {
      const s = JSON.stringify(options.indent);
      throw new Error(`"indent" option must be a positive integer, not ${s}`);
    }
    return stringifyDocument(this, options);
  }
};
function assertCollection(contents) {
  if (isCollection(contents))
    return true;
  throw new Error("Expected a YAML collection as document contents");
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/parse/cst-visit.js
var BREAK2 = Symbol("break visit");
var SKIP2 = Symbol("skip children");
var REMOVE2 = Symbol("remove item");
function visit2(cst, visitor) {
  if ("type" in cst && cst.type === "document")
    cst = { start: cst.start, value: cst.value };
  _visit(Object.freeze([]), cst, visitor);
}
visit2.BREAK = BREAK2;
visit2.SKIP = SKIP2;
visit2.REMOVE = REMOVE2;
visit2.itemAtPath = (cst, path) => {
  let item = cst;
  for (const [field, index] of path) {
    const tok = item?.[field];
    if (tok && "items" in tok) {
      item = tok.items[index];
    } else
      return void 0;
  }
  return item;
};
visit2.parentCollection = (cst, path) => {
  const parent = visit2.itemAtPath(cst, path.slice(0, -1));
  const field = path[path.length - 1][0];
  const coll = parent?.[field];
  if (coll && "items" in coll)
    return coll;
  throw new Error("Parent collection not found");
};
function _visit(path, item, visitor) {
  let ctrl = visitor(item, path);
  if (typeof ctrl === "symbol")
    return ctrl;
  for (const field of ["key", "value"]) {
    const token = item[field];
    if (token && "items" in token) {
      for (let i = 0; i < token.items.length; ++i) {
        const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor);
        if (typeof ci === "number")
          i = ci - 1;
        else if (ci === BREAK2)
          return BREAK2;
        else if (ci === REMOVE2) {
          token.items.splice(i, 1);
          i -= 1;
        }
      }
      if (typeof ctrl === "function" && field === "key")
        ctrl = ctrl(item, path);
    }
  }
  return typeof ctrl === "function" ? ctrl(item, path) : ctrl;
}

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/parse/lexer.js
var hexDigits = new Set("0123456789ABCDEFabcdef");
var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");
var flowIndicatorChars = new Set(",[]{}");
var invalidAnchorChars = new Set(" ,[]{}\n\r	");

// src/typespec/node_modules/.pnpm/yaml@2.8.1/node_modules/yaml/browser/dist/public-api.js
function stringify3(value, replacer, options) {
  let _replacer = null;
  if (typeof replacer === "function" || Array.isArray(replacer)) {
    _replacer = replacer;
  } else if (options === void 0 && replacer) {
    options = replacer;
  }
  if (typeof options === "string")
    options = options.length;
  if (typeof options === "number") {
    const indent = Math.round(options);
    options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent };
  }
  if (value === void 0) {
    const { keepUndefined } = options ?? replacer ?? {};
    if (!keepUndefined)
      return void 0;
  }
  if (isDocument(value) && !_replacer)
    return value.toString(options);
  return new Document(value, _replacer, options).toString(options);
}

// src/typespec/packages/typespec-client-generator-core/dist/src/cache.js
import { getNamespaceFullName as getNamespaceFullName4, isService as isService3, isTemplateDeclaration as isTemplateDeclaration3, isTemplateDeclarationOrInstance } from "@typespec/compiler";

// src/typespec/packages/typespec-client-generator-core/dist/src/decorators.js
import { getDiscriminator as getDiscriminator2, getNamespaceFullName as getNamespaceFullName3, ignoreDiagnostics as ignoreDiagnostics4, isService as isService2, isTemplateDeclaration as isTemplateDeclaration2 } from "@typespec/compiler";
import { SyntaxKind } from "@typespec/compiler/ast";
import { $ as $3 } from "@typespec/compiler/typekit";

// src/typespec/packages/typespec-client-generator-core/dist/src/interfaces.js
var UsageFlags;
(function(UsageFlags2) {
  UsageFlags2[UsageFlags2["None"] = 0] = "None";
  UsageFlags2[UsageFlags2["Input"] = 2] = "Input";
  UsageFlags2[UsageFlags2["Output"] = 4] = "Output";
  UsageFlags2[UsageFlags2["ApiVersionEnum"] = 8] = "ApiVersionEnum";
  UsageFlags2[UsageFlags2["JsonMergePatch"] = 16] = "JsonMergePatch";
  UsageFlags2[UsageFlags2["MultipartFormData"] = 32] = "MultipartFormData";
  UsageFlags2[UsageFlags2["Spread"] = 64] = "Spread";
  UsageFlags2[UsageFlags2["Json"] = 256] = "Json";
  UsageFlags2[UsageFlags2["Xml"] = 512] = "Xml";
  UsageFlags2[UsageFlags2["Exception"] = 1024] = "Exception";
  UsageFlags2[UsageFlags2["LroInitial"] = 2048] = "LroInitial";
  UsageFlags2[UsageFlags2["LroPolling"] = 4096] = "LroPolling";
  UsageFlags2[UsageFlags2["LroFinalEnvelope"] = 8192] = "LroFinalEnvelope";
})(UsageFlags || (UsageFlags = {}));
var InitializedByFlags;
(function(InitializedByFlags2) {
  InitializedByFlags2[InitializedByFlags2["Default"] = 0] = "Default";
  InitializedByFlags2[InitializedByFlags2["Individually"] = 1] = "Individually";
  InitializedByFlags2[InitializedByFlags2["Parent"] = 2] = "Parent";
})(InitializedByFlags || (InitializedByFlags = {}));
var SdkIntKindsEnum;
(function(SdkIntKindsEnum2) {
  SdkIntKindsEnum2["numeric"] = "numeric";
  SdkIntKindsEnum2["integer"] = "integer";
  SdkIntKindsEnum2["safeint"] = "safeint";
  SdkIntKindsEnum2["int8"] = "int8";
  SdkIntKindsEnum2["int16"] = "int16";
  SdkIntKindsEnum2["int32"] = "int32";
  SdkIntKindsEnum2["int64"] = "int64";
  SdkIntKindsEnum2["uint8"] = "uint8";
  SdkIntKindsEnum2["uint16"] = "uint16";
  SdkIntKindsEnum2["uint32"] = "uint32";
  SdkIntKindsEnum2["uint64"] = "uint64";
})(SdkIntKindsEnum || (SdkIntKindsEnum = {}));
var SdkFloatingPointKindsEnum;
(function(SdkFloatingPointKindsEnum2) {
  SdkFloatingPointKindsEnum2["float"] = "float";
  SdkFloatingPointKindsEnum2["float32"] = "float32";
  SdkFloatingPointKindsEnum2["float64"] = "float64";
})(SdkFloatingPointKindsEnum || (SdkFloatingPointKindsEnum = {}));
var SdkFixedPointKindsEnum;
(function(SdkFixedPointKindsEnum2) {
  SdkFixedPointKindsEnum2["decimal"] = "decimal";
  SdkFixedPointKindsEnum2["decimal128"] = "decimal128";
})(SdkFixedPointKindsEnum || (SdkFixedPointKindsEnum = {}));
var SdkGenericBuiltInStringKindsEnum;
(function(SdkGenericBuiltInStringKindsEnum2) {
  SdkGenericBuiltInStringKindsEnum2["string"] = "string";
  SdkGenericBuiltInStringKindsEnum2["url"] = "url";
})(SdkGenericBuiltInStringKindsEnum || (SdkGenericBuiltInStringKindsEnum = {}));
var SdkBuiltInKindsMiscellaneousEnum;
(function(SdkBuiltInKindsMiscellaneousEnum2) {
  SdkBuiltInKindsMiscellaneousEnum2["bytes"] = "bytes";
  SdkBuiltInKindsMiscellaneousEnum2["boolean"] = "boolean";
  SdkBuiltInKindsMiscellaneousEnum2["plainDate"] = "plainDate";
  SdkBuiltInKindsMiscellaneousEnum2["plainTime"] = "plainTime";
  SdkBuiltInKindsMiscellaneousEnum2["unknown"] = "unknown";
})(SdkBuiltInKindsMiscellaneousEnum || (SdkBuiltInKindsMiscellaneousEnum = {}));
function getKnownScalars() {
  const retval = {};
  const typespecNamespace = Object.keys(SdkBuiltInKindsMiscellaneousEnum).concat(Object.keys(SdkIntKindsEnum)).concat(Object.keys(SdkFloatingPointKindsEnum)).concat(Object.keys(SdkFixedPointKindsEnum)).concat(Object.keys(SdkGenericBuiltInStringKindsEnum));
  for (const kind of typespecNamespace) {
    if (!isSdkBuiltInKind(kind))
      continue;
    retval[`TypeSpec.${kind}`] = kind;
  }
  return retval;
}
function isSdkBuiltInKind(kind) {
  return kind in SdkBuiltInKindsMiscellaneousEnum || isSdkIntKind(kind) || isSdkFloatKind(kind) || isSdkFixedPointKind(kind) || kind in SdkGenericBuiltInStringKindsEnum;
}
function isSdkIntKind(kind) {
  return kind in SdkIntKindsEnum;
}
function isSdkFloatKind(kind) {
  return kind in SdkFloatingPointKindsEnum;
}
function isSdkFixedPointKind(kind) {
  return kind in SdkFixedPointKindsEnum;
}
var SdkDateTimeEncodingsConst = ["rfc3339", "rfc7231", "unixTimestamp"];
function isSdkDateTimeEncodings(encoding) {
  return SdkDateTimeEncodingsConst.includes(encoding);
}

// src/typespec/packages/typespec-client-generator-core/dist/src/internal-utils.js
import { compilerAssert as compilerAssert2, createDiagnosticCollector as createDiagnosticCollector4, getDeprecationDetails, getDoc, getLifecycleVisibilityEnum as getLifecycleVisibilityEnum2, getNamespaceFullName as getNamespaceFullName2, getVisibilityForClass as getVisibilityForClass2, ignoreDiagnostics as ignoreDiagnostics3, isNeverType as isNeverType2, isNullType, isVoidType, listServices } from "@typespec/compiler";
import { unsafe_mutateSubgraphWithNamespace } from "@typespec/compiler/experimental";
import { $ as $2 } from "@typespec/compiler/typekit";
import { getAddedOnVersions, getRemovedOnVersions, getVersioningMutators, getVersions as getVersions3 } from "@typespec/versioning";

// src/typespec/packages/typespec-client-generator-core/dist/src/http.js
import { compilerAssert, createDiagnosticCollector as createDiagnosticCollector3, getEncode as getEncode2, getSummary as getSummary2, isErrorModel as isErrorModel2 } from "@typespec/compiler";
import { $ } from "@typespec/compiler/typekit";
import { Visibility as Visibility2, getCookieParamOptions, getHeaderFieldName, getHeaderFieldOptions, getPathParamName, getQueryParamName, getQueryParamOptions, isBody, isCookieParam, isHeader as isHeader2, isPathParam, isQueryParam } from "@typespec/http";
import { getStreamMetadata } from "@typespec/http/experimental";

// src/typespec/node_modules/.pnpm/change-case@5.4.4/node_modules/change-case/dist/index.js
var SPLIT_LOWER_UPPER_RE = /([\p{Ll}\d])(\p{Lu})/gu;
var SPLIT_UPPER_UPPER_RE = /(\p{Lu})([\p{Lu}][\p{Ll}])/gu;
var SPLIT_SEPARATE_NUMBER_RE = /(\d)\p{Ll}|(\p{L})\d/u;
var DEFAULT_STRIP_REGEXP = /[^\p{L}\d]+/giu;
var SPLIT_REPLACE_VALUE = "$1\0$2";
var DEFAULT_PREFIX_SUFFIX_CHARACTERS = "";
function split(value) {
  let result = value.trim();
  result = result.replace(SPLIT_LOWER_UPPER_RE, SPLIT_REPLACE_VALUE).replace(SPLIT_UPPER_UPPER_RE, SPLIT_REPLACE_VALUE);
  result = result.replace(DEFAULT_STRIP_REGEXP, "\0");
  let start = 0;
  let end = result.length;
  while (result.charAt(start) === "\0")
    start++;
  if (start === end)
    return [];
  while (result.charAt(end - 1) === "\0")
    end--;
  return result.slice(start, end).split(/\0/g);
}
function splitSeparateNumbers(value) {
  const words = split(value);
  for (let i = 0; i < words.length; i++) {
    const word = words[i];
    const match = SPLIT_SEPARATE_NUMBER_RE.exec(word);
    if (match) {
      const offset = match.index + (match[1] ?? match[2]).length;
      words.splice(i, 1, word.slice(0, offset), word.slice(offset));
    }
  }
  return words;
}
function camelCase(input, options) {
  const [prefix, words, suffix] = splitPrefixSuffix(input, options);
  const lower = lowerFactory(options?.locale);
  const upper = upperFactory(options?.locale);
  const transform = options?.mergeAmbiguousCharacters ? capitalCaseTransformFactory(lower, upper) : pascalCaseTransformFactory(lower, upper);
  return prefix + words.map((word, index) => {
    if (index === 0)
      return lower(word);
    return transform(word, index);
  }).join(options?.delimiter ?? "") + suffix;
}
function pascalCase(input, options) {
  const [prefix, words, suffix] = splitPrefixSuffix(input, options);
  const lower = lowerFactory(options?.locale);
  const upper = upperFactory(options?.locale);
  const transform = options?.mergeAmbiguousCharacters ? capitalCaseTransformFactory(lower, upper) : pascalCaseTransformFactory(lower, upper);
  return prefix + words.map(transform).join(options?.delimiter ?? "") + suffix;
}
function lowerFactory(locale) {
  return locale === false ? (input) => input.toLowerCase() : (input) => input.toLocaleLowerCase(locale);
}
function upperFactory(locale) {
  return locale === false ? (input) => input.toUpperCase() : (input) => input.toLocaleUpperCase(locale);
}
function capitalCaseTransformFactory(lower, upper) {
  return (word) => `${upper(word[0])}${lower(word.slice(1))}`;
}
function pascalCaseTransformFactory(lower, upper) {
  return (word, index) => {
    const char0 = word[0];
    const initial = index > 0 && char0 >= "0" && char0 <= "9" ? "_" + char0 : upper(char0);
    return initial + lower(word.slice(1));
  };
}
function splitPrefixSuffix(input, options = {}) {
  const splitFn = options.split ?? (options.separateNumbers ? splitSeparateNumbers : split);
  const prefixCharacters = options.prefixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;
  const suffixCharacters = options.suffixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;
  let prefixIndex = 0;
  let suffixIndex = input.length;
  while (prefixIndex < input.length) {
    const char = input.charAt(prefixIndex);
    if (!prefixCharacters.includes(char))
      break;
    prefixIndex++;
  }
  while (suffixIndex > prefixIndex) {
    const index = suffixIndex - 1;
    const char = input.charAt(index);
    if (!suffixCharacters.includes(char))
      break;
    suffixIndex = index;
  }
  return [
    input.slice(0, prefixIndex),
    splitFn(input.slice(prefixIndex, suffixIndex)),
    input.slice(suffixIndex)
  ];
}

// src/typespec/packages/typespec-client-generator-core/dist/src/lib.js
import { createTypeSpecLibrary, paramMessage } from "@typespec/compiler";
var UnbrandedSdkEmitterOptions = {
  "generate-protocol-methods": {
    "generate-protocol-methods": {
      type: "boolean",
      nullable: true,
      description: "When set to `true`, the emitter will generate low-level protocol methods for each service operation if `@protocolAPI` is not set for an operation. Default value is `true`."
    }
  },
  "generate-convenience-methods": {
    "generate-convenience-methods": {
      type: "boolean",
      nullable: true,
      description: "When set to `true`, the emitter will generate convenience methods for each service operation if `@convenientAPI` is not set for an operation. Default value is `true`."
    }
  },
  "api-version": {
    "api-version": {
      type: "string",
      nullable: true,
      description: "Use this flag if you would like to generate the sdk only for a specific version. Default value is the latest version. Also accepts values `latest` and `all`."
    }
  },
  license: {
    license: {
      type: "object",
      additionalProperties: false,
      nullable: true,
      required: ["name"],
      properties: {
        name: {
          type: "string",
          nullable: false,
          description: "License name. The config is required. Predefined license are: MIT License, Apache License 2.0, BSD 3-Clause License, MPL 2.0, GPL-3.0, LGPL-3.0. For other license, you need to configure all the other license config manually."
        },
        company: {
          type: "string",
          nullable: true,
          description: "License company name. It will be used in copyright sentences."
        },
        link: {
          type: "string",
          nullable: true,
          description: "License link."
        },
        header: {
          type: "string",
          nullable: true,
          description: "License header. It will be used in the header comment of generated client code."
        },
        description: {
          type: "string",
          nullable: true,
          description: "License description. The full license text."
        }
      },
      description: "License information for the generated client code."
    }
  }
};
var UnbrandedSdkEmitterOptionsInterfaceSchema = {
  type: "object",
  additionalProperties: false,
  properties: {
    ...UnbrandedSdkEmitterOptions["generate-protocol-methods"],
    ...UnbrandedSdkEmitterOptions["generate-convenience-methods"],
    ...UnbrandedSdkEmitterOptions["api-version"],
    ...UnbrandedSdkEmitterOptions["license"]
  }
};
var BrandedSdkEmitterOptions = {
  "examples-dir": {
    "examples-dir": {
      type: "string",
      nullable: true,
      format: "absolute-path",
      description: "Specifies the directory where the emitter will look for example files. If the flag isn\u2019t set, the emitter defaults to using an `examples` directory located at the project root."
    }
  },
  namespace: {
    namespace: {
      type: "string",
      nullable: true,
      description: "Specifies the namespace you want to override for namespaces set in the spec. With this config, all namespace for the spec types will default to it."
    }
  }
};
var BrandedSdkEmitterOptionsSchema = {
  type: "object",
  additionalProperties: false,
  properties: {
    ...UnbrandedSdkEmitterOptionsInterfaceSchema.properties,
    ...BrandedSdkEmitterOptions["examples-dir"],
    ...BrandedSdkEmitterOptions["namespace"]
  }
};
var TCGCEmitterOptionsSchema = {
  type: "object",
  additionalProperties: false,
  properties: {
    "emitter-name": {
      type: "string",
      nullable: true,
      description: "Set `emitter-name` to output TCGC code models for specific language's emitter."
    },
    ...BrandedSdkEmitterOptionsSchema.properties
  }
};
var $lib = createTypeSpecLibrary({
  name: "@azure-tools/typespec-client-generator-core",
  diagnostics: {
    "multiple-services": {
      severity: "warning",
      messages: {
        default: "Multiple services found. Only the first service will be used; others will be ignored."
      }
    },
    "client-service": {
      severity: "warning",
      messages: {
        default: paramMessage`Client "${"name"}" is not inside a service namespace. Use @client({service: MyServiceNS})`
      }
    },
    "union-null": {
      severity: "warning",
      messages: {
        default: "Cannot have a union containing only null types."
      }
    },
    "union-circular": {
      severity: "warning",
      messages: {
        default: "Cannot have a union containing self."
      }
    },
    "invalid-access": {
      severity: "error",
      messages: {
        default: `Access value must be "public" or "internal".`
      }
    },
    "invalid-usage": {
      severity: "error",
      messages: {
        default: `Usage value must be one of: 2 (input), 4 (output), 256 (json), or 512 (xml).`
      }
    },
    "conflicting-multipart-model-usage": {
      severity: "error",
      messages: {
        default: paramMessage`Model '${"modelName"}' cannot be used as both multipart/form-data input and regular body input. You can create a separate model with name 'model ${"modelName"}FormData' extends ${"modelName"} {}`
      }
    },
    "discriminator-not-constant": {
      severity: "error",
      messages: {
        default: paramMessage`Discriminator ${"discriminator"} has to be constant`
      }
    },
    "discriminator-not-string": {
      severity: "warning",
      messages: {
        default: paramMessage`Value of discriminator ${"discriminator"} has to be a string, not ${"discriminatorValue"}`
      }
    },
    "wrong-client-decorator": {
      severity: "warning",
      messages: {
        default: "@client or @operationGroup should decorate namespace or interface in client.tsp"
      }
    },
    "unsupported-kind": {
      severity: "warning",
      messages: {
        default: paramMessage`Unsupported kind ${"kind"}`
      }
    },
    "server-param-not-path": {
      severity: "error",
      messages: {
        default: paramMessage`Template argument ${"templateArgumentName"} is not a path parameter, it is a ${"templateArgumentType"}. It has to be a path.`
      }
    },
    "unexpected-http-param-type": {
      severity: "error",
      messages: {
        default: paramMessage`Expected parameter "${"paramName"}" to be of type "${"expectedType"}", but instead it is of type "${"actualType"}"`
      }
    },
    "multiple-response-types": {
      severity: "warning",
      messages: {
        default: paramMessage`Multiple response types found in operation ${"operation"}. Some emitters might not support returning all of these response types`
      }
    },
    "no-corresponding-method-param": {
      severity: "error",
      messages: {
        default: paramMessage`Missing HTTP operation parameter "${"paramName"}" in method "${"methodName"}". Please check the method definition.`
      }
    },
    "unsupported-protocol": {
      severity: "error",
      messages: {
        default: "Currently we only support HTTP and HTTPS protocols"
      }
    },
    "no-emitter-name": {
      severity: "warning",
      messages: {
        default: "Can not find name for your emitter, please check your emitter name."
      }
    },
    "unsupported-generic-decorator-arg-type": {
      severity: "warning",
      messages: {
        default: paramMessage`Can not parse the arg type for decorator "${"decoratorName"}".`
      }
    },
    "empty-client-name": {
      severity: "warning",
      messages: {
        default: `Cannot pass an empty value to the @clientName decorator`
      }
    },
    "override-parameters-mismatch": {
      severity: "error",
      messages: {
        default: paramMessage`Method "${"methodName"}" is not directly referencing the same parameters as in the original operation. The original method has parameters "${"originalParameters"}", while the override method has parameters "${"overrideParameters"}".`
      }
    },
    "duplicate-client-name": {
      severity: "error",
      messages: {
        default: paramMessage`Client name: "${"name"}" is duplicated in language scope: "${"scope"}"`,
        nonDecorator: paramMessage`Client name: "${"name"}" is defined somewhere causing naming conflicts in language scope: "${"scope"}"`
      }
    },
    "duplicate-client-name-warning": {
      severity: "warning",
      messages: {
        default: paramMessage`Client name: "${"name"}" is duplicated in language scope: "${"scope"}"`,
        nonDecorator: paramMessage`Client name: "${"name"}" is defined somewhere causing naming conflicts in language scope: "${"scope"}"`
      }
    },
    "client-name-ineffective": {
      severity: "warning",
      messages: {
        default: paramMessage`Application of @clientName decorator to ${"name"} is not effective`,
        override: paramMessage`Application of @clientName decorator to ${"name"} is not effective because it is applied to the override method. Please apply it on the original method definition "${"originalMethodName"}" instead.`
      }
    },
    "example-loading": {
      severity: "warning",
      messages: {
        default: paramMessage`Skipped loading invalid example file: ${"filename"}. Error: ${"error"}`,
        noDirectory: paramMessage`Skipping example loading from ${"directory"} because there was an error reading the directory.`,
        noOperationId: paramMessage`Skipping example file ${"filename"} because it does not contain an operationId and/or title.`
      }
    },
    "duplicate-example-file": {
      severity: "error",
      messages: {
        default: paramMessage`Example file ${"filename"} uses duplicate title '${"title"}' for operationId '${"operationId"}'`
      }
    },
    "example-value-no-mapping": {
      severity: "warning",
      messages: {
        default: paramMessage`Value in example file '${"relativePath"}' does not follow its definition:\n${"value"}`
      }
    },
    "flatten-polymorphism": {
      severity: "error",
      messages: {
        default: `Cannot flatten property of polymorphic type.`
      }
    },
    "conflict-access-override": {
      severity: "warning",
      messages: {
        default: `@access override conflicts with the access calculated from operation or other @access override.`
      }
    },
    "duplicate-decorator": {
      severity: "warning",
      messages: {
        default: paramMessage`Decorator ${"decoratorName"} cannot be used twice on the same declaration with same scope.`
      }
    },
    "empty-client-namespace": {
      severity: "warning",
      messages: {
        default: `Cannot pass an empty value to the @clientNamespace decorator`
      }
    },
    "unexpected-pageable-operation-return-type": {
      severity: "error",
      messages: {
        default: `The response object for the pageable operation is either not a paging model, or is not correctly decorated with @nextLink and @items.`
      }
    },
    "invalid-alternate-type": {
      severity: "error",
      messages: {
        default: paramMessage`Invalid alternate type. If the source type is Scalar, the alternate type must also be Scalar. Found alternate type kind: '${"kindName"}'`
      }
    },
    "invalid-initialized-by": {
      severity: "error",
      messages: {
        default: paramMessage`Invalid 'initializedBy' value. ${"message"}`
      }
    },
    "invalid-deserializeEmptyStringAsNull-target-type": {
      severity: "error",
      messages: {
        default: "@deserializeEmptyStringAsNull can only be applied to `ModelProperty` of type 'string' or a `Scalar` derived from 'string'."
      }
    },
    "api-version-not-string": {
      severity: "warning",
      messages: {
        default: `Api version must be a string or a string enum`
      }
    },
    "invalid-encode-for-collection-format": {
      severity: "warning",
      messages: {
        default: "Only encode of `ArrayEncoding.pipeDelimited` and `ArrayEncoding.spaceDelimited` is supported for collection format."
      }
    },
    "no-discriminated-unions": {
      severity: "error",
      messages: {
        default: "Discriminated unions are not supported. Please redefine the type using model with hierarchy and `@discriminator` decorator."
      }
    },
    "non-head-bool-response-decorator": {
      severity: "warning",
      messages: {
        default: paramMessage`@responseAsBool decorator can only be used on HEAD operations. Will ignore decorator on ${"operationName"}.`
      }
    },
    "unsupported-http-file-body": {
      severity: "error",
      messages: {
        default: "File body is not supported for HTTP operations. Please use bytes instead."
      }
    },
    "require-versioned-service": {
      severity: "warning",
      description: "Require a versioned service to use this decorator",
      messages: {
        default: paramMessage`Service "${"serviceName"}" must be versioned if you want to apply the "${"decoratorName"}" decorator`
      }
    },
    "missing-service-versions": {
      severity: "warning",
      description: "Missing service versions",
      messages: {
        default: paramMessage`The @clientApiVersions decorator is missing one or more versions defined in ${"serviceName"}. Client API must support all service versions to ensure compatibility. Missing versions: ${"missingVersions"}. Please update the client API to support all required service versions.`
      }
    },
    "invalid-client-doc-mode": {
      severity: "error",
      messages: {
        default: paramMessage`Invalid mode '${"mode"}' for @clientDoc decorator. Valid values are "append" or "replace".`
      }
    },
    "multiple-param-alias": {
      severity: "warning",
      messages: {
        default: paramMessage`Multiple param aliases applied to '${"originalName"}'. Only the first one '${"firstParamAlias"}' will be used.`
      }
    },
    "client-location-conflict": {
      severity: "warning",
      messages: {
        default: "When there is `@client` or `@operationGroup` decorator, `@clientLocation` decorator will be ignored.",
        operationToOperation: "`@clientLocation` cannot be used to move an operation to another operation. Operations can only be moved to interfaces or namespaces.",
        modelPropertyToClientInitialization: paramMessage`There is already a parameter called '${"parameterName"}' in the client initialization.`,
        modelPropertyToString: "`@clientLocation` can only move model properties to interfaces or namespaces."
      }
    },
    "client-location-wrong-type": {
      severity: "warning",
      messages: {
        default: "`@clientLocation` could only move operation to the interface or namespace belong to the root namespace with `@service`."
      }
    },
    "client-location-duplicate": {
      severity: "warning",
      messages: {
        default: "`@clientLocation`'s target should not duplicate with defined namespace or interface under `@service` namespace."
      }
    },
    "legacy-hierarchy-building-conflict": {
      severity: "warning",
      messages: {
        default: paramMessage`@hierarchyBuilding decorator causes conflicts in inherited properties. Please check that the model ${"childModel"} has the same properties as ${"parentModel"} in the spec.`
      }
    },
    "legacy-hierarchy-building-circular-reference": {
      severity: "error",
      messages: {
        default: "@hierarchyBuilding decorator causes recursive base type reference."
      }
    }
  },
  emitter: {
    options: TCGCEmitterOptionsSchema
  }
});
var { reportDiagnostic, createDiagnostic, createStateSymbol } = $lib;

// src/typespec/packages/typespec-client-generator-core/dist/src/media-types.js
var json = "json";
var xml = "xml";
var application = "application";
var text = "text";
function parseMediaType(mediaType) {
  if (mediaType) {
    const parsed = /(application|audio|font|example|image|message|model|multipart|text|video|x-(?:[0-9A-Za-z!#$%&'*+.^_`|~-]+))\/([0-9A-Za-z!#$%&'*.^_`|~-]+)\s*(?:\+([0-9A-Za-z!#$%&'*.^_`|~-]+))?\s*(?:;.\s*(\S*))?/g.exec(mediaType);
    if (parsed) {
      return {
        type: parsed[1],
        subtype: parsed[2],
        suffix: parsed[3],
        parameter: parsed[4]
      };
    }
  }
  return void 0;
}
function isMediaTypeTextPlain(mediaType) {
  const mt = parseMediaType(mediaType);
  return mt ? mt.type === text && mt.subtype === "plain" : false;
}
function isMediaTypeOctetStream(mediaType) {
  const mt = parseMediaType(mediaType);
  return mt ? mt.type === application && mt.subtype === "octet-stream" : false;
}
function isMediaTypeJson(mediaType) {
  const mt = parseMediaType(mediaType);
  return mt ? (mt.subtype === json || mt.suffix === json) && (mt.type === application || mt.type === text) : false;
}
function isMediaTypeXml(mediaType) {
  const mt = parseMediaType(mediaType);
  return mt ? (mt.subtype === xml || mt.suffix === xml) && (mt.type === application || mt.type === text) : false;
}

// src/typespec/packages/typespec-client-generator-core/dist/src/public-utils.js
import { createDiagnosticCollector, getEffectiveModelType, getFriendlyName, getNamespaceFullName, ignoreDiagnostics, isGlobalNamespace, isService, resolveEncodedName } from "@typespec/compiler";
import { getHttpOperation, getHttpPart, isMetadata, isVisible } from "@typespec/http";
import { getOperationId } from "@typespec/openapi";
import { getVersions } from "@typespec/versioning";
var import_pluralize = __toESM(require_pluralize(), 1);
function getDefaultApiVersion(context, serviceNamespace) {
  try {
    const versions = getVersions(context.program, serviceNamespace)[1].getVersions();
    removeVersionsLargerThanExplicitlySpecified(context, versions);
    return versions[versions.length - 1];
  } catch (e) {
    return void 0;
  }
}
function isModelProperty(type) {
  return type && typeof type === "object" && "kind" in type && type.kind === "ModelProperty";
}
function isApiVersion(context, type) {
  if (isModelProperty(type)) {
    const override = getIsApiVersion(context, type);
    if (override !== void 0) {
      return override;
    }
  }
  return isModelProperty(type) && type.type === context.getPackageVersionEnum() || type.name.toLowerCase().includes("apiversion") || type.name.toLowerCase().includes("api-version");
}
function getEffectivePayloadType(context, type, visibility) {
  const program = context.program;
  if (type.name) {
    return type;
  }
  const effective = getEffectiveModelType(program, type, (t) => !isMetadata(context.program, t) && !hasNoneVisibility(context, t) && (visibility === void 0 || isVisible(program, t, visibility)));
  if (effective.name) {
    return effective;
  }
  return type;
}
function getPropertyNames(context, property) {
  return [getLibraryName(context, property), getWireName(context, property)];
}
function getLibraryName(context, type, scope) {
  const emitterSpecificName = getClientNameOverride(context, type, scope);
  if (emitterSpecificName && emitterSpecificName !== type.name)
    return emitterSpecificName;
  const friendlyName = getFriendlyName(context.program, type);
  if (friendlyName)
    return friendlyName;
  if (typeof type.name === "string" && type.name !== "" && type.kind === "Model" && type.templateMapper?.args) {
    const generatedName = context.__generatedNames.get(type);
    if (generatedName)
      return generatedName;
    return resolveDuplicateGenearatedName(context, type, type.name + type.templateMapper.args.filter((arg) => "kind" in arg && (arg.kind === "Model" || arg.kind === "Enum" || arg.kind === "Union") && arg.name !== void 0 && arg.name.length > 0).map((arg) => pascalCase(arg.name)).join(""));
  }
  return typeof type.name === "string" ? type.name : "";
}
function getWireName(context, type) {
  const encodedName = resolveEncodedName(context.program, type, "application/json");
  if (encodedName !== type.name)
    return encodedName;
  return type.name;
}
function getCrossLanguageDefinitionId(context, type, operation, appendNamespace = true) {
  let retval = type.name || "anonymous";
  let namespace2 = type.kind === "ModelProperty" ? type.model?.namespace : type.namespace;
  switch (type.kind) {
    // Enum and Scalar will always have a name
    case "Union":
    case "Model":
      if (type.name) {
        break;
      }
      const contextPath = operation ? getContextPath(context, operation, type) : findContextPath(context, type);
      const namingPart = contextPath.slice(findLastNonAnonymousNode(contextPath));
      if (namingPart[0]?.type?.kind === "Model" || namingPart[0]?.type?.kind === "Union" || namingPart[0]?.type?.kind === "Operation") {
        namespace2 = namingPart[0]?.type?.namespace;
      }
      retval = namingPart.map((x) => x.type?.kind === "Model" || x.type?.kind === "Union" ? x.type.name || x.name : x.name || "anonymous").join(".") + "." + retval;
      break;
    case "ModelProperty":
      if (type.model) {
        if (type.model === operation?.parameters) {
          retval = `${getCrossLanguageDefinitionId(context, operation, void 0, false)}.${retval}`;
        } else {
          retval = `${getCrossLanguageDefinitionId(context, type.model, operation, false)}.${retval}`;
        }
      }
      break;
    case "Operation":
      if (type.interface) {
        retval = `${getCrossLanguageDefinitionId(context, type.interface, void 0, false)}.${retval}`;
      }
      break;
  }
  if (appendNamespace && namespace2 && getNamespaceFullName(namespace2)) {
    retval = `${getNamespaceFullName(namespace2)}.${retval}`;
  }
  return retval;
}
function getCrossLanguagePackageId(context) {
  const diagnostics = createDiagnosticCollector();
  const serviceNamespaces = listAllServiceNamespaces(context);
  if (serviceNamespaces.length === 0)
    return diagnostics.wrap("");
  return diagnostics.wrap(getNamespaceFullName(serviceNamespaces[0]));
}
function getGeneratedName(context, type, operation) {
  const generatedName = context.__generatedNames.get(type);
  if (generatedName)
    return generatedName;
  const contextPath = operation ? getContextPath(context, operation, type) : findContextPath(context, type);
  const createdName = buildNameFromContextPaths(context, type, contextPath);
  return createdName;
}
function findContextPath(context, type) {
  for (const currNamespace of listAllUserDefinedNamespaces(context)) {
    for (const model of currNamespace.models.values()) {
      if ([...model.properties.values()].filter((p) => !isMetadata(context.program, p)).length === 0)
        continue;
      const result = getContextPath(context, model, type);
      if (result.length > 0) {
        return result;
      }
    }
  }
  for (const client of listClients(context)) {
    for (const operation of listOperationsInOperationGroup(context, client)) {
      const result = getContextPath(context, operation, type);
      if (result.length > 0) {
        return result;
      }
    }
    for (const og of listOperationGroups(context, client, true)) {
      for (const operation of listOperationsInOperationGroup(context, og)) {
        const result = getContextPath(context, operation, type);
        if (result.length > 0) {
          return result;
        }
      }
    }
  }
  return [];
}
function getContextPath(context, root, typeToFind) {
  const visited = /* @__PURE__ */ new Set();
  let result;
  if (root.kind === "Operation") {
    const httpOperation = getHttpOperationWithCache(context, root);
    if (httpOperation.parameters.body) {
      visited.clear();
      result = [{ name: root.name, type: root }];
      const bodyType = getHttpBodyType(httpOperation.parameters.body);
      if (dfsModelProperties(typeToFind, bodyType, "Request")) {
        return result;
      }
      if (httpOperation.parameters.body.bodyKind === "multipart") {
        for (const part of httpOperation.parameters.body.parts) {
          visited.clear();
          result = [{ name: root.name, type: root }];
          if (part.partKind === "model" && dfsModelProperties(typeToFind, part.body.type, `Request${pascalCase(part.name)}`)) {
            return result;
          }
        }
      }
    }
    for (const parameter of Object.values(httpOperation.parameters.parameters)) {
      visited.clear();
      result = [{ name: root.name, type: root }];
      if (dfsModelProperties(typeToFind, parameter.param.type, `Request${pascalCase(parameter.name)}`)) {
        return result;
      }
    }
    for (const response of httpOperation.responses) {
      for (const innerResponse of response.responses) {
        if (innerResponse.body?.type) {
          visited.clear();
          result = [{ name: root.name, type: root }];
          if (dfsModelProperties(typeToFind, innerResponse.body.type, "Response", true)) {
            return result;
          }
          if (innerResponse.body?.bodyKind === "multipart") {
            for (const part of innerResponse.body.parts) {
              visited.clear();
              result = [{ name: root.name, type: root }];
              if (part.partKind === "model" && dfsModelProperties(typeToFind, part.body.type, `Request${pascalCase(part.name)}`)) {
                return result;
              }
            }
          }
        }
        const headers = getHttpOperationResponseHeaders(innerResponse);
        if (headers) {
          for (const header of Object.values(headers)) {
            visited.clear();
            result = [{ name: root.name, type: root }];
            if (dfsModelProperties(typeToFind, header.type, `Response${pascalCase(header.name)}`)) {
              return result;
            }
          }
        }
      }
    }
    const overriddenClientMethod = getOverriddenClientMethod(context, root);
    visited.clear();
    result = [{ name: root.name, type: root }];
    if (dfsModelProperties(typeToFind, overriddenClientMethod ?? root.parameters, "Parameter")) {
      return result;
    }
  } else {
    visited.clear();
    result = [];
    if (dfsModelProperties(typeToFind, root, root.name)) {
      return result;
    }
  }
  return [];
  function dfsModelProperties(expectedType, currentType, displayName, needFindEffectiveType = false) {
    if (currentType == null || visited.has(currentType)) {
      return false;
    }
    if (!["Model", "Union", "String", "Number", "Boolean"].includes(currentType.kind)) {
      return false;
    }
    visited.add(currentType);
    if (currentType === expectedType) {
      result.push({ name: displayName, type: currentType });
      return true;
    } else if (currentType.kind === "Model") {
      const typeWrappedByHttpPart = getHttpPart(context.program, currentType);
      if (typeWrappedByHttpPart) {
        return dfsModelProperties(expectedType, typeWrappedByHttpPart.type, displayName);
      }
      if (currentType.indexer && currentType.properties.size === 0 && (currentType.indexer.key.name === "string" && currentType.name === "Record" || currentType.indexer.key.name === "integer")) {
        const dictOrArrayItemType = currentType.indexer.value;
        return dfsModelProperties(expectedType, dictOrArrayItemType, import_pluralize.default.singular(displayName));
      }
      if (needFindEffectiveType) {
        currentType = getEffectiveModelType(context.program, currentType);
      }
      result.push({ name: displayName, type: currentType });
      for (const property of currentType.properties.values()) {
        const result2 = dfsModelProperties(expectedType, property.type, property.name);
        if (result2)
          return true;
      }
      if (currentType.sourceModel?.kind === "Model" && currentType.sourceModel?.name === "Record") {
        const result2 = dfsModelProperties(expectedType, currentType.sourceModel.indexer.value, "AdditionalProperty");
        if (result2)
          return true;
      }
      if (currentType.indexer) {
        const result2 = dfsModelProperties(expectedType, currentType.indexer.value, "AdditionalProperty");
        if (result2)
          return true;
      }
      const baseModel = currentType.baseModel;
      if (baseModel) {
        if (baseModel.name === "Record") {
          const result2 = dfsModelProperties(expectedType, baseModel.indexer.value, "AdditionalProperty");
          if (result2)
            return true;
        }
      }
      result.pop();
      if (baseModel) {
        const result2 = dfsModelProperties(expectedType, baseModel, baseModel.name);
        if (result2)
          return true;
      }
      for (const derivedModel of currentType.derivedModels) {
        const result2 = dfsModelProperties(expectedType, derivedModel, derivedModel.name);
        if (result2)
          return true;
      }
      return false;
    } else if (currentType.kind === "Union") {
      for (const unionType of currentType.variants.values()) {
        const result2 = dfsModelProperties(expectedType, unionType.type, displayName);
        if (result2)
          return true;
      }
      return false;
    } else {
      return false;
    }
  }
}
function findLastNonAnonymousNode(contextPath) {
  let lastNonAnonymousModelNodeIndex = contextPath.length - 1;
  while (lastNonAnonymousModelNodeIndex >= 0) {
    const currType = contextPath[lastNonAnonymousModelNodeIndex].type;
    if ((currType.kind === "Model" || currType.kind === "Union" || currType.kind === "Operation") && currType.name) {
      break;
    } else {
      --lastNonAnonymousModelNodeIndex;
    }
  }
  return lastNonAnonymousModelNodeIndex;
}
function buildNameFromContextPaths(context, type, contextPath) {
  if (contextPath.length === 0) {
    return "";
  }
  const lastNonAnonymousNodeIndex = findLastNonAnonymousNode(contextPath);
  let createName = "";
  for (let j = lastNonAnonymousNodeIndex; j < contextPath.length; j++) {
    const currContextPathType = contextPath[j]?.type;
    if (currContextPathType?.kind === "String" || currContextPathType?.kind === "Number" || currContextPathType?.kind === "Boolean") {
      createName = `${createName}${pascalCase(contextPath[j].name)}`;
    } else if (!currContextPathType?.name || currContextPathType.kind === "Operation") {
      createName = `${createName}${pascalCase(contextPath[j].name)}`;
    } else {
      createName = `${createName}${currContextPathType.name}`;
    }
  }
  createName = resolveDuplicateGenearatedName(context, type, createName);
  return createName;
}
function getHttpOperationWithCache(context, operation) {
  if (context.__httpOperationCache?.has(operation)) {
    return context.__httpOperationCache.get(operation);
  }
  const httpOperation = ignoreDiagnostics(getHttpOperation(context.program, operation));
  context.__httpOperationCache.set(operation, httpOperation);
  return httpOperation;
}
function getHttpOperationExamples(context, operation) {
  return context.__httpOperationExamples.get(operation) ?? [];
}
function isAzureCoreModel(t) {
  return t.__raw !== void 0 && isAzureCoreTspModel(t.__raw);
}
function isPagedResultModel(context, t) {
  return context.__pagedResultSet.has(t);
}
function getHttpOperationParameter(method, param) {
  const operation = method.operation;
  for (const p of operation.parameters) {
    for (const cp of p.correspondingMethodParams) {
      if (cp === param) {
        return p;
      }
    }
  }
  if (operation.bodyParam) {
    for (const cp of operation.bodyParam.correspondingMethodParams) {
      if (cp === param) {
        if (operation.bodyParam.type.kind === "model" && operation.bodyParam.type !== param.type) {
          return operation.bodyParam.type.properties.find((p) => p.kind === "property" && p.name === param.name);
        }
        return operation.bodyParam;
      }
    }
  }
  return void 0;
}
function listAllServiceNamespaces(context) {
  const serviceNamespaces = [];
  for (const ns of listAllUserDefinedNamespaces(context)) {
    if (isService(context.program, ns)) {
      serviceNamespaces.push(ns);
    }
  }
  return serviceNamespaces;
}
function resolveOperationId(context, operation, honorRenaming = false) {
  const { program } = context;
  const explicitOperationId = getOperationId(program, operation);
  if (explicitOperationId) {
    return explicitOperationId;
  }
  const operationName = honorRenaming ? getLibraryName(context, operation) : operation.name;
  let operationInterface = operation.interface;
  let operationNamespace = operation.namespace;
  const clientLocation = getClientLocation(context, operation);
  if (!hasExplicitClientOrOperationGroup(context) && clientLocation) {
    if (typeof clientLocation === "string") {
      return `${clientLocation}_${operationName}`;
    }
    if (clientLocation.kind === "Interface") {
      operationInterface = clientLocation;
    } else {
      operationInterface = void 0;
      operationNamespace = clientLocation;
    }
  }
  if (operationInterface) {
    return `${honorRenaming ? getLibraryName(context, operationInterface) : operationInterface.name}_${operationName}`;
  }
  if (operationNamespace === void 0 || isGlobalNamespace(program, operationNamespace) || isService(program, operationNamespace)) {
    return operationName;
  }
  return `${honorRenaming ? getLibraryName(context, operationNamespace) : operationNamespace.name}_${operationName}`;
}
function isHttpMetadata(context, property) {
  return property.__raw !== void 0 && isMetadata(context.program, property.__raw);
}
function getNamespaceFromType(type) {
  if (type === void 0) {
    return void 0;
  }
  if (type.kind === "SdkOperationGroup" || type.kind === "SdkClient") {
    const rawType = type.type;
    if (rawType === void 0) {
      return void 0;
    }
    if (rawType.kind === "Namespace") {
      return rawType;
    }
    return rawType.namespace;
  }
  if ("namespace" in type) {
    return type.namespace;
  }
  return void 0;
}

// src/typespec/packages/typespec-client-generator-core/dist/src/types.js
import { getLroMetadata, getUnionAsEnum } from "@azure-tools/typespec-azure-core";
import { createDiagnosticCollector as createDiagnosticCollector2, getDiscriminator, getEncode, getLifecycleVisibilityEnum, getSummary, getVisibilityForClass, ignoreDiagnostics as ignoreDiagnostics2, isArrayModelType, isErrorModel, isNeverType, isTemplateDeclaration, resolveEncodedName as resolveEncodedName2 } from "@typespec/compiler";
import { Visibility, getAuthentication, getServers, isHeader, isOrExtendsHttpFile, isStatusCode } from "@typespec/http";
import { isStream } from "@typespec/streams";
import { getVersions as getVersions2 } from "@typespec/versioning";
import { getNs, isAttribute, isUnwrapped } from "@typespec/xml";
function getTypeSpecBuiltInType(context, kind) {
  const global = context.getMutatedGlobalNamespace();
  const typeSpecNamespace = global.namespaces.get("TypeSpec");
  const type = typeSpecNamespace.scalars.get(kind);
  return getSdkBuiltInType(context, type);
}
function getUnknownType(context, type) {
  const diagnostics = createDiagnosticCollector2();
  const unknownType = {
    ...diagnostics.pipe(getSdkTypeBaseHelper(context, type, "unknown")),
    name: getLibraryName(context, type),
    encode: void 0,
    crossLanguageDefinitionId: ""
  };
  return diagnostics.wrap(unknownType);
}
function addEncodeInfo(context, type, propertyType, defaultContentType) {
  const diagnostics = createDiagnosticCollector2();
  const innerType = propertyType.kind === "nullable" ? propertyType.type : propertyType;
  const encodeData = getEncode(context.program, type);
  if (innerType.kind === "duration") {
    if (!encodeData)
      return diagnostics.wrap(void 0);
    innerType.encode = encodeData.encoding;
    innerType.wireType = diagnostics.pipe(getClientTypeWithDiagnostics(context, encodeData.type));
  }
  if (innerType.kind === "utcDateTime" || innerType.kind === "offsetDateTime") {
    if (encodeData) {
      innerType.encode = encodeData.encoding;
      innerType.wireType = diagnostics.pipe(getClientTypeWithDiagnostics(context, encodeData.type));
    } else if (type.kind === "ModelProperty" && isHeader(context.program, type)) {
      innerType.encode = "rfc7231";
    }
  }
  if (innerType.kind === "bytes") {
    if (encodeData) {
      innerType.encode = encodeData.encoding;
    } else if (type.kind === "Scalar" || !defaultContentType) {
      innerType.encode = "base64";
    } else if (!isMediaTypeJson(defaultContentType) && !isMediaTypeXml(defaultContentType) && !isMediaTypeTextPlain(defaultContentType)) {
      innerType.encode = "bytes";
    }
  }
  if (isSdkIntKind(innerType.kind)) {
    if (encodeData) {
      if (encodeData?.encoding) {
        innerType.encode = encodeData.encoding;
      }
      if (encodeData?.type) {
        innerType.encode = getSdkBuiltInType(context, encodeData.type).kind;
      }
    }
  }
  return diagnostics.wrap(void 0);
}
function getScalarKind(context, scalar) {
  if (context.program.checker.isStdType(scalar)) {
    return scalar.name;
  }
  if (scalar.baseScalar === void 0) {
    return "unknown";
  }
  return getScalarKind(context, scalar.baseScalar);
}
function getSdkBuiltInTypeWithDiagnostics(context, type, kind) {
  const diagnostics = createDiagnosticCollector2();
  const stdType = {
    ...diagnostics.pipe(getSdkTypeBaseHelper(context, type, kind)),
    name: getLibraryName(context, type),
    doc: getClientDoc(context, type),
    summary: getSummary(context.program, type),
    baseType: type.baseScalar && !context.program.checker.isStdType(type) ? diagnostics.pipe(getSdkBuiltInTypeWithDiagnostics(context, type.baseScalar, kind)) : void 0,
    crossLanguageDefinitionId: getCrossLanguageDefinitionId(context, type)
  };
  addEncodeInfo(context, type, stdType);
  return diagnostics.wrap(stdType);
}
function getEncodeInfoForDateTimeOrDuration(context, encodeData, baseType) {
  const encode = encodeData?.encoding;
  const wireType = encodeData?.type ? getClientType(context, encodeData.type) : void 0;
  if (encode || wireType) {
    return [encode, wireType];
  }
  return [baseType?.encode, baseType?.wireType];
}
function getSdkDateTimeType(context, type, kind) {
  const diagnostics = createDiagnosticCollector2();
  const baseType = type.baseScalar && !context.program.checker.isStdType(type) ? diagnostics.pipe(getSdkDateTimeType(context, type.baseScalar, kind)) : void 0;
  const [encode, wireType] = getEncodeInfoForDateTimeOrDuration(context, getEncode(context.program, type), baseType);
  return diagnostics.wrap({
    ...diagnostics.pipe(getSdkTypeBaseHelper(context, type, kind)),
    name: getLibraryName(context, type),
    encode: encode ?? "rfc3339",
    wireType: wireType ?? getTypeSpecBuiltInType(context, "string"),
    baseType,
    doc: getClientDoc(context, type),
    summary: getSummary(context.program, type),
    crossLanguageDefinitionId: getCrossLanguageDefinitionId(context, type)
  });
}
function getSdkDateTimeOrDurationOrBuiltInType(context, type) {
  const kind = getScalarKind(context, type);
  if (kind === "utcDateTime" || kind === "offsetDateTime") {
    return getSdkDateTimeType(context, type, kind);
  }
  if (kind === "duration") {
    return getSdkDurationTypeWithDiagnostics(context, type, kind);
  }
  return getSdkBuiltInTypeWithDiagnostics(context, type, kind);
}
function getSdkTypeForLiteral(context, type) {
  let kind;
  if (type.kind === "String") {
    kind = "string";
  } else if (type.kind === "Boolean") {
    kind = "boolean";
  } else {
    kind = intOrFloat(type.value);
  }
  return getTypeSpecBuiltInType(context, kind);
}
function getSdkTypeForIntrinsic(context, type) {
  const kind = "unknown";
  const diagnostics = createDiagnosticCollector2();
  return {
    ...diagnostics.pipe(getSdkTypeBaseHelper(context, type, kind)),
    name: getLibraryName(context, type),
    crossLanguageDefinitionId: "",
    encode: kind
  };
}
function getSdkBuiltInType(context, type) {
  switch (type.kind) {
    case "Scalar":
      return ignoreDiagnostics2(getSdkDateTimeOrDurationOrBuiltInType(context, type));
    case "Intrinsic":
      return getSdkTypeForIntrinsic(context, type);
    case "String":
    case "Number":
    case "Boolean":
      return getSdkTypeForLiteral(context, type);
  }
}
function getSdkDurationType(context, type) {
  return ignoreDiagnostics2(getSdkDurationTypeWithDiagnostics(context, type, "duration"));
}
function getSdkDurationTypeWithDiagnostics(context, type, kind) {
  const diagnostics = createDiagnosticCollector2();
  const baseType = type.baseScalar && !context.program.checker.isStdType(type) ? diagnostics.pipe(getSdkDurationTypeWithDiagnostics(context, type.baseScalar, kind)) : void 0;
  const [encode, wireType] = getEncodeInfoForDateTimeOrDuration(context, getEncode(context.program, type), baseType);
  return diagnostics.wrap({
    ...diagnostics.pipe(getSdkTypeBaseHelper(context, type, kind)),
    name: getLibraryName(context, type),
    encode: encode ?? "ISO8601",
    wireType: wireType ?? getTypeSpecBuiltInType(context, "string"),
    baseType,
    doc: getClientDoc(context, type),
    summary: getSummary(context.program, type),
    crossLanguageDefinitionId: getCrossLanguageDefinitionId(context, type)
  });
}
function getSdkArrayOrDict(context, type, operation) {
  return ignoreDiagnostics2(getSdkArrayOrDictWithDiagnostics(context, type, operation));
}
function getSdkArrayOrDictWithDiagnostics(context, type, operation) {
  const diagnostics = createDiagnosticCollector2();
  if (type.indexer !== void 0 && type.properties.size === 0) {
    if (!isNeverType(type.indexer.key)) {
      let sdkType = context.__arrayDictionaryCache.get(type);
      if (!sdkType) {
        const name = type.indexer.key.name;
        if (name === "string" && type.name === "Record") {
          if (type.sourceModel?.kind === "Model" && type.sourceModel?.name === "Record") {
            return diagnostics.wrap(void 0);
          } else {
            sdkType = {
              ...diagnostics.pipe(getSdkTypeBaseHelper(context, type, "dict")),
              keyType: diagnostics.pipe(getClientTypeWithDiagnostics(context, type.indexer.key, operation)),
              valueType: diagnostics.pipe(getUnknownType(context, type))
              // set unknown for cache
            };
          }
        } else if (name === "integer") {
          sdkType = {
            ...diagnostics.pipe(getSdkTypeBaseHelper(context, type, "array")),
            name: getLibraryName(context, type),
            valueType: diagnostics.pipe(getUnknownType(context, type)),
            // set unknown for cache
            crossLanguageDefinitionId: getCrossLanguageDefinitionId(context, type, operation)
          };
        } else {
          return diagnostics.wrap(void 0);
        }
        context.__arrayDictionaryCache.set(type, sdkType);
        sdkType.valueType = diagnostics.pipe(getClientTypeWithDiagnostics(context, type.indexer.value, operation));
      }
      return diagnostics.wrap(sdkType);
    }
  }
  return diagnostics.wrap(void 0);
}
function getSdkTuple(context, type, operation) {
  return ignoreDiagnostics2(getSdkTupleWithDiagnostics(context, type, operation));
}
function getSdkTupleWithDiagnostics(context, type, operation) {
  const diagnostics = createDiagnosticCollector2();
  return diagnostics.wrap({
    ...diagnostics.pipe(getSdkTypeBaseHelper(context, type, "tuple")),
    valueTypes: type.values.map((x) => diagnostics.pipe(getClientTypeWithDiagnostics(context, x, operation)))
  });
}
function getSdkUnion(context, type, operation) {
  return ignoreDiagnostics2(getSdkUnionWithDiagnostics(context, type, operation));
}
function getSdkUnionWithDiagnostics(context, type, operation) {
  let retval = context.__referencedTypeCache.get(type);
  const diagnostics = createDiagnosticCollector2();
  if (!retval) {
    const nonNullOptions = getNonNullOptions(type);
    const nullOption = getNullOption(type);
    if (nonNullOptions.length === 0) {
      diagnostics.add(createDiagnostic({ code: "union-null", target: type }));
      retval = diagnostics.pipe(getEmptyUnionType(context, type, operation));
      updateReferencedTypeMap(context, type, retval);
    } else if (checkUnionCircular(type)) {
      diagnostics.add(createDiagnostic({ code: "union-circular", target: type }));
      retval = diagnostics.pipe(getEmptyUnionType(context, type, operation));
      updateReferencedTypeMap(context, type, retval);
    } else {
      const namespace2 = getClientNamespace(context, type);
      if (nonNullOptions.length === 1 && nullOption !== void 0) {
        retval = {
          ...diagnostics.pipe(getSdkTypeBaseHelper(context, type, "nullable")),
          name: getLibraryName(context, type) || getGeneratedName(context, type, operation),
          isGeneratedName: !type.name,
          crossLanguageDefinitionId: getCrossLanguageDefinitionId(context, type),
          type: diagnostics.pipe(getUnknownType(context, type)),
          access: "public",
          usage: UsageFlags.None,
          namespace: namespace2
        };
        updateReferencedTypeMap(context, type, retval);
        retval.type = diagnostics.pipe(getClientTypeWithDiagnostics(context, nonNullOptions[0], operation));
      } else if (
        // judge if the union can be converted to enum
        // if language does not need flatten union as enum
        // filter the case that union is composed of union or enum
        context.flattenUnionAsEnum || ![...type.variants.values()].some((variant) => {
          return variant.type.kind === "Union" || variant.type.kind === "Enum";
        })
      ) {
        const unionAsEnum = diagnostics.pipe(getUnionAsEnum(type));
        if (unionAsEnum) {
          retval = diagnostics.pipe(getSdkUnionEnumWithDiagnostics(context, unionAsEnum, operation));
          if (nullOption !== void 0) {
            retval = {
              ...diagnostics.pipe(getSdkTypeBaseHelper(context, type, "nullable")),
              name: getLibraryName(context, type) || getGeneratedName(context, type, operation),
              isGeneratedName: !type.name,
              crossLanguageDefinitionId: getCrossLanguageDefinitionId(context, type),
              type: retval,
              access: "public",
              usage: UsageFlags.None,
              namespace: namespace2
            };
          }
          updateReferencedTypeMap(context, type, retval);
        }
      }
      if (retval === void 0) {
        retval = {
          ...diagnostics.pipe(getSdkTypeBaseHelper(context, type, "union")),
          name: getLibraryName(context, type) || getGeneratedName(context, type, operation),
          isGeneratedName: nullOption !== void 0 ? true : !type.name,
          // if nullable, always set inner union type as generated name
          namespace: namespace2,
          variantTypes: [],
          crossLanguageDefinitionId: getCrossLanguageDefinitionId(context, type, operation),
          access: "public",
          usage: UsageFlags.None
        };
        if (nullOption !== void 0) {
          retval = {
            ...diagnostics.pipe(getSdkTypeBaseHelper(context, type, "nullable")),
            name: getLibraryName(context, type) || getGeneratedName(context, type, operation),
            isGeneratedName: !type.name,
            crossLanguageDefinitionId: getCrossLanguageDefinitionId(context, type),
            type: retval,
            access: "public",
            usage: UsageFlags.None,
            namespace: namespace2
          };
        }
        updateReferencedTypeMap(context, type, retval);
        const variantTypes = nonNullOptions.map((x) => diagnostics.pipe(getClientTypeWithDiagnostics(context, x, operation)));
        if (retval.kind === "nullable" && retval.type.kind === "union") {
          retval.type.variantTypes = variantTypes;
        } else if (retval.kind === "union") {
          retval.variantTypes = variantTypes;
        }
      }
    }
  }
  return diagnostics.wrap(retval);
}
function getEmptyUnionType(context, type, operation) {
  const diagnostics = createDiagnosticCollector2();
  const namespace2 = getClientNamespace(context, type);
  return diagnostics.wrap({
    ...diagnostics.pipe(getSdkTypeBaseHelper(context, type, "union")),
    name: getLibraryName(context, type) || getGeneratedName(context, type, operation),
    isGeneratedName: !type.name,
    namespace: namespace2,
    clientNamespace: namespace2,
    variantTypes: [],
    crossLanguageDefinitionId: getCrossLanguageDefinitionId(context, type, operation),
    access: "public",
    usage: UsageFlags.None
  });
}
function checkUnionCircular(type) {
  const visited = /* @__PURE__ */ new Set();
  const stack = [type];
  while (stack.length > 0) {
    const current = stack.pop();
    if (visited.has(current)) {
      return true;
    }
    visited.add(current);
    for (const variant of current.variants.values()) {
      if (variant.type.kind === "Union") {
        stack.push(variant.type);
      }
    }
  }
  return false;
}
function getSdkConstantWithDiagnostics(context, type, operation) {
  const diagnostics = createDiagnosticCollector2();
  switch (type.kind) {
    case "Number":
    case "String":
    case "Boolean":
      const valueType = getSdkTypeForLiteral(context, type);
      return diagnostics.wrap({
        ...diagnostics.pipe(getSdkTypeBaseHelper(context, type, "constant")),
        value: type.value,
        valueType,
        name: getGeneratedName(context, type, operation),
        isGeneratedName: true
      });
  }
}
function getSdkConstant(context, type, operation) {
  return ignoreDiagnostics2(getSdkConstantWithDiagnostics(context, type, operation));
}
function addDiscriminatorToModelType(context, type, model) {
  const discriminator = getDiscriminator(context.program, type);
  const diagnostics = createDiagnosticCollector2();
  if (discriminator) {
    let discriminatorType = void 0;
    for (let i = 0; i < model.properties.length; i++) {
      const property = model.properties[i];
      if (property.kind === "property" && property.__raw?.name === discriminator.propertyName) {
        discriminatorType = property.type;
        break;
      }
    }
    let discriminatorProperty;
    for (const childModel of type.derivedModels) {
      if (isTemplateDeclaration(childModel))
        continue;
      const childModelSdkType = diagnostics.pipe(getSdkModelWithDiagnostics(context, childModel));
      for (const property of childModelSdkType.properties) {
        if (property.kind === "property") {
          if (property.__raw?.name === discriminator?.propertyName) {
            if (property.type.kind !== "constant" && property.type.kind !== "enumvalue") {
              diagnostics.add(createDiagnostic({
                code: "discriminator-not-constant",
                target: childModel,
                format: { discriminator: property.name }
              }));
            } else if (typeof property.type.value !== "string") {
              diagnostics.add(createDiagnostic({
                code: "discriminator-not-string",
                target: type,
                format: {
                  discriminator: property.name,
                  discriminatorValue: String(property.type.value)
                }
              }));
            } else {
              if (property.type.kind === "constant" && discriminatorType?.kind === "enum") {
                for (const value of discriminatorType.values) {
                  if (value.value === property.type.value) {
                    property.type = value;
                  }
                }
              }
              childModelSdkType.discriminatorValue = property.type.value;
              property.discriminator = true;
              if (model.discriminatedSubtypes === void 0) {
                model.discriminatedSubtypes = {};
              }
              model.discriminatedSubtypes[property.type.value] = childModelSdkType;
              discriminatorProperty = property;
            }
          }
        }
      }
    }
    for (let i = 0; i < model.properties.length; i++) {
      const property = model.properties[i];
      if (property.kind === "property" && property.__raw?.name === discriminator.propertyName) {
        property.discriminator = true;
        model.discriminatorProperty = property;
        return diagnostics.wrap(void 0);
      }
    }
    if (discriminatorProperty) {
      if (discriminatorProperty.type.kind === "constant") {
        discriminatorType = { ...discriminatorProperty.type.valueType };
      } else if (discriminatorProperty.type.kind === "enumvalue") {
        discriminatorType = discriminatorProperty.type.enumType;
      }
    } else {
      discriminatorType = getTypeSpecBuiltInType(context, "string");
    }
    const name = discriminatorProperty ? discriminatorProperty.name : discriminator.propertyName;
    const discriminatorPropertyType = {
      kind: "property",
      doc: `Discriminator property for ${model.name}.`,
      optional: false,
      discriminator: true,
      serializedName: discriminatorProperty ? discriminatorProperty.serializedName : discriminator.propertyName,
      serializationOptions: {},
      type: discriminatorType,
      name,
      isGeneratedName: false,
      onClient: false,
      apiVersions: discriminatorProperty ? getAvailableApiVersions(context, discriminatorProperty.__raw, type) : getAvailableApiVersions(context, type, type),
      isApiVersionParam: false,
      isMultipartFileInput: false,
      // discriminator property cannot be a file
      flatten: false,
      // discriminator properties can not be flattened
      crossLanguageDefinitionId: `${model.crossLanguageDefinitionId}.${name}`,
      decorators: [],
      access: "public"
    };
    model.properties.splice(0, 0, discriminatorPropertyType);
    model.discriminatorProperty = discriminatorPropertyType;
  }
  return diagnostics.wrap(void 0);
}
function getSdkModel(context, type, operation) {
  return ignoreDiagnostics2(getSdkModelWithDiagnostics(context, type, operation));
}
function getSdkModelWithDiagnostics(context, type, operation) {
  const diagnostics = createDiagnosticCollector2();
  let sdkType = context.__referencedTypeCache.get(type);
  if (!sdkType) {
    const name = getLibraryName(context, type) || getGeneratedName(context, type, operation);
    sdkType = {
      ...diagnostics.pipe(getSdkTypeBaseHelper(context, type, "model")),
      name,
      isGeneratedName: !type.name,
      namespace: getClientNamespace(context, type),
      doc: getClientDoc(context, type),
      summary: getSummary(context.program, type),
      properties: [],
      additionalProperties: void 0,
      // going to set additional properties in the next few lines when we look at base model
      access: "public",
      usage: UsageFlags.None,
      crossLanguageDefinitionId: getCrossLanguageDefinitionId(context, type, operation),
      apiVersions: getAvailableApiVersions(context, type, type.namespace),
      serializationOptions: {}
    };
    updateReferencedTypeMap(context, type, sdkType);
    if (type.sourceModel?.kind === "Model" && type.sourceModel?.name === "Record") {
      sdkType.additionalProperties = diagnostics.pipe(getClientTypeWithDiagnostics(context, type.sourceModel.indexer.value, operation));
    }
    if (type.indexer) {
      sdkType.additionalProperties = diagnostics.pipe(getClientTypeWithDiagnostics(context, type.indexer.value, operation));
    }
    if (operation) {
      const requestBody = getHttpOperationWithCache(context, operation).parameters.body;
      const multipartResponseBodies = getHttpOperationWithCache(context, operation).responses.map((response) => response.responses.map((r) => r.body)).flatMap((x) => x).filter((x) => x?.bodyKind === "multipart");
      if (requestBody && requestBody.bodyKind === "multipart" && getHttpBodyType(requestBody) === type) {
        diagnostics.pipe(addMultipartPropertiesToModelType(context, sdkType, requestBody, operation));
      } else if (multipartResponseBodies.length > 0) {
        multipartResponseBodies.map((body) => getHttpBodyType(body) === type ? diagnostics.pipe(addMultipartPropertiesToModelType(context, sdkType, body, operation)) : void 0);
      } else {
        diagnostics.pipe(addPropertiesToModelType(context, type, sdkType, operation));
      }
    } else {
      diagnostics.pipe(addPropertiesToModelType(context, type, sdkType, operation));
    }
    const rawBaseModel = getLegacyHierarchyBuilding(context, type) || type.baseModel;
    if (rawBaseModel) {
      sdkType.baseModel = context.__referencedTypeCache.get(rawBaseModel);
      if (sdkType.baseModel === void 0) {
        const baseModel = diagnostics.pipe(getClientTypeWithDiagnostics(context, rawBaseModel, operation));
        if (baseModel.kind === "dict") {
          sdkType.additionalProperties = baseModel.valueType;
        } else {
          sdkType.baseModel = baseModel;
        }
      }
    }
    diagnostics.pipe(addDiscriminatorToModelType(context, type, sdkType));
    updateReferencedTypeMap(context, type, sdkType);
  }
  return diagnostics.wrap(sdkType);
}
function getSdkEnumValueType(context, values) {
  const diagnostics = createDiagnosticCollector2();
  let kind = "string";
  for (const value of values) {
    if (typeof value === "number") {
      kind = intOrFloat(value);
      if (kind === "float32") {
        break;
      }
    } else if (typeof value === "string") {
      kind = "string";
      break;
    }
  }
  return diagnostics.wrap(getTypeSpecBuiltInType(context, kind));
}
function getUnionAsEnumValueType(context, union) {
  const diagnostics = createDiagnosticCollector2();
  const nonNullOptions = getNonNullOptions(union);
  for (const option of nonNullOptions) {
    if (option.kind === "Union") {
      const ret = diagnostics.pipe(getUnionAsEnumValueType(context, option));
      if (ret)
        return diagnostics.wrap(ret);
    } else if (option.kind === "Scalar") {
      const ret = diagnostics.pipe(getClientTypeWithDiagnostics(context, option));
      return diagnostics.wrap(ret);
    }
  }
  return diagnostics.wrap(void 0);
}
function getSdkEnumValue(context, enumType, type) {
  return ignoreDiagnostics2(getSdkEnumValueWithDiagnostics(context, enumType, type));
}
function getSdkEnumValueWithDiagnostics(context, enumType, type) {
  const diagnostics = createDiagnosticCollector2();
  return diagnostics.wrap({
    ...diagnostics.pipe(getSdkTypeBaseHelper(context, type, "enumvalue")),
    name: getLibraryName(context, type),
    value: type.value ?? type.name,
    doc: getClientDoc(context, type),
    summary: getSummary(context.program, type),
    enumType,
    valueType: enumType.valueType
  });
}
function getSdkEnum(context, type, operation) {
  return ignoreDiagnostics2(getSdkEnumWithDiagnostics(context, type, operation));
}
function getSdkEnumWithDiagnostics(context, type, operation) {
  const diagnostics = createDiagnosticCollector2();
  let sdkType = context.__referencedTypeCache.get(type);
  if (!sdkType) {
    sdkType = {
      ...diagnostics.pipe(getSdkTypeBaseHelper(context, type, "enum")),
      name: getLibraryName(context, type),
      isGeneratedName: false,
      namespace: getClientNamespace(context, type),
      doc: getClientDoc(context, type),
      summary: getSummary(context.program, type),
      valueType: diagnostics.pipe(getSdkEnumValueType(context, [...type.members.values()].map((v) => v.value))),
      values: [],
      isFixed: true,
      // enums are always fixed after we switch to use union to represent extensible enum
      isFlags: false,
      usage: UsageFlags.None,
      // We will add usage as we loop through the operations
      access: "public",
      // Dummy value until we update models map
      crossLanguageDefinitionId: getCrossLanguageDefinitionId(context, type, operation),
      apiVersions: getAvailableApiVersions(context, type, type.namespace),
      isUnionAsEnum: false
    };
    for (const member of type.members.values()) {
      sdkType.values.push(diagnostics.pipe(getSdkEnumValueWithDiagnostics(context, sdkType, member)));
    }
  }
  updateReferencedTypeMap(context, type, sdkType);
  return diagnostics.wrap(sdkType);
}
function getSdkUnionEnumValues(context, type, enumType) {
  const diagnostics = createDiagnosticCollector2();
  const values = [];
  for (const member of type.flattenedMembers.values()) {
    const name = getLibraryName(context, member.type);
    values.push({
      ...diagnostics.pipe(getSdkTypeBaseHelper(context, member.type, "enumvalue")),
      name: name ? name : `${member.value}`,
      doc: getClientDoc(context, member.type),
      summary: getSummary(context.program, member.type),
      value: member.value,
      valueType: enumType.valueType,
      enumType
    });
  }
  return diagnostics.wrap(values);
}
function getSdkUnionEnum(context, type, operation) {
  return ignoreDiagnostics2(getSdkUnionEnumWithDiagnostics(context, type, operation));
}
function getSdkUnionEnumWithDiagnostics(context, type, operation) {
  const diagnostics = createDiagnosticCollector2();
  const union = type.union;
  const name = getLibraryName(context, type.union) || getGeneratedName(context, union, operation);
  const sdkType = {
    ...diagnostics.pipe(getSdkTypeBaseHelper(context, type.union, "enum")),
    name,
    isGeneratedName: !type.union.name,
    namespace: getClientNamespace(context, type.union),
    doc: getClientDoc(context, union),
    summary: getSummary(context.program, union),
    valueType: diagnostics.pipe(getUnionAsEnumValueType(context, type.union)) ?? diagnostics.pipe(getSdkEnumValueType(context, [...type.flattenedMembers.values()].map((v) => v.value))),
    values: [],
    isFixed: !type.open,
    isFlags: false,
    usage: UsageFlags.None,
    // We will add usage as we loop through the operations
    access: "public",
    // Dummy value until we update models map
    crossLanguageDefinitionId: getCrossLanguageDefinitionId(context, union, operation),
    apiVersions: getAvailableApiVersions(context, type.union, type.union.namespace),
    isUnionAsEnum: true
  };
  sdkType.values = diagnostics.pipe(getSdkUnionEnumValues(context, type, sdkType));
  return diagnostics.wrap(sdkType);
}
function getClientTypeWithDiagnostics(context, type, operation) {
  const diagnostics = createDiagnosticCollector2();
  let retval = void 0;
  switch (type.kind) {
    case "String":
    case "Number":
    case "Boolean":
      retval = diagnostics.pipe(getSdkConstantWithDiagnostics(context, type));
      break;
    case "Tuple":
      retval = diagnostics.pipe(getSdkTupleWithDiagnostics(context, type, operation));
      break;
    case "Model":
      retval = diagnostics.pipe(getSdkArrayOrDictWithDiagnostics(context, type, operation));
      if (retval === void 0) {
        retval = diagnostics.pipe(getSdkModelWithDiagnostics(context, type, operation));
      }
      break;
    case "Intrinsic":
      retval = getSdkTypeForIntrinsic(context, type);
      break;
    case "Scalar":
      retval = diagnostics.pipe(getSdkDateTimeOrDurationOrBuiltInType(context, getAlternateType(context, type) ?? type));
      break;
    case "Enum":
      retval = diagnostics.pipe(getSdkEnumWithDiagnostics(context, type, operation));
      break;
    case "Union":
      retval = diagnostics.pipe(getSdkUnionWithDiagnostics(context, type, operation));
      break;
    case "ModelProperty":
      const alternateType = getAlternateType(context, type);
      retval = diagnostics.pipe(getClientTypeWithDiagnostics(context, alternateType ?? type.type, operation));
      diagnostics.pipe(addEncodeInfo(context, alternateType ?? type, retval));
      break;
    case "UnionVariant":
      const unionType = diagnostics.pipe(getClientTypeWithDiagnostics(context, type.union, operation));
      if (unionType.kind === "enum") {
        retval = unionType.values.find((x) => x.name === getLibraryName(context, type));
      } else {
        retval = diagnostics.pipe(getClientTypeWithDiagnostics(context, type.type, operation));
      }
      break;
    case "EnumMember":
      const enumType = diagnostics.pipe(getSdkEnumWithDiagnostics(context, type.enum, operation));
      retval = diagnostics.pipe(getSdkEnumValueWithDiagnostics(context, enumType, type));
      break;
    default:
      retval = diagnostics.pipe(getUnknownType(context, type));
      diagnostics.add(createDiagnostic({ code: "unsupported-kind", target: type, format: { kind: type.kind } }));
  }
  return diagnostics.wrap(retval);
}
function getClientType(context, type, operation) {
  return ignoreDiagnostics2(getClientTypeWithDiagnostics(context, type, operation));
}
function isReadOnly(property) {
  if (property.visibility && property.visibility.includes(Visibility.Read) && property.visibility.length === 1) {
    return true;
  }
  return false;
}
function getSdkVisibility(context, type) {
  const lifecycle = getLifecycleVisibilityEnum(context.program);
  const visibility = getVisibilityForClass(context.program, type, lifecycle);
  if (visibility) {
    const result = [];
    if (lifecycle.members.get("Read") && visibility.has(lifecycle.members.get("Read"))) {
      result.push(Visibility.Read);
    }
    if (lifecycle.members.get("Create") && visibility.has(lifecycle.members.get("Create"))) {
      result.push(Visibility.Create);
    }
    if (lifecycle.members.get("Update") && visibility.has(lifecycle.members.get("Update"))) {
      result.push(Visibility.Update);
    }
    if (lifecycle.members.get("Delete") && visibility.has(lifecycle.members.get("Delete"))) {
      result.push(Visibility.Delete);
    }
    if (lifecycle.members.get("Query") && visibility.has(lifecycle.members.get("Query"))) {
      result.push(Visibility.Query);
    }
    return result;
  }
  return void 0;
}
function getSdkCredentialType(context, client, authentication) {
  const credentialTypes = [];
  for (const option of authentication.options) {
    for (const scheme of option.schemes) {
      credentialTypes.push({
        __raw: client.service,
        kind: "credential",
        scheme,
        decorators: []
      });
    }
  }
  if (credentialTypes.length > 1) {
    const namespace2 = getClientNamespace(context, client.service);
    return {
      __raw: client.service,
      kind: "union",
      variantTypes: credentialTypes,
      name: createGeneratedName(context, client.service, "CredentialUnion"),
      isGeneratedName: true,
      namespace: namespace2,
      clientNamespace: namespace2,
      crossLanguageDefinitionId: `${getCrossLanguageDefinitionId(context, client.service)}.CredentialUnion`,
      decorators: [],
      access: "public",
      usage: UsageFlags.None
    };
  }
  return credentialTypes[0];
}
function getSdkCredentialParameter(context, client) {
  const auth = getAuthentication(context.program, client.service);
  if (!auth)
    return void 0;
  return {
    type: getSdkCredentialType(context, client, auth),
    kind: "credential",
    name: "credential",
    isGeneratedName: true,
    doc: "Credential used to authenticate requests to the service.",
    apiVersions: getAvailableApiVersions(context, client.service, client.type),
    onClient: true,
    optional: false,
    isApiVersionParam: false,
    crossLanguageDefinitionId: `${getCrossLanguageDefinitionId(context, client.service)}.credential`,
    decorators: [],
    access: "public"
  };
}
function getSdkModelPropertyTypeBase(context, type, operation) {
  const diagnostics = createDiagnosticCollector2();
  const apiVersions = getAvailableApiVersions(context, type, operation || type.model);
  const alternateType = getAlternateType(context, type);
  const propertyType = diagnostics.pipe(getClientTypeWithDiagnostics(context, alternateType ?? type.type, operation));
  diagnostics.pipe(addEncodeInfo(context, alternateType ?? type, propertyType));
  const name = getPropertyNames(context, type)[0];
  const onClient = isOnClient(context, type, operation, apiVersions.length > 0);
  return diagnostics.wrap({
    __raw: type,
    doc: getClientDoc(context, type),
    summary: getSummary(context.program, type),
    apiVersions,
    type: propertyType,
    name,
    isGeneratedName: false,
    optional: type.optional,
    ...updateWithApiVersionInformation(context, type, operation ? context.getClientForOperation(operation) : void 0),
    onClient,
    crossLanguageDefinitionId: getCrossLanguageDefinitionId(context, type, operation),
    decorators: diagnostics.pipe(getTypeDecorators(context, type)),
    visibility: getSdkVisibility(context, type),
    access: getAccess(context, type)
  });
}
function isFilePart(context, type) {
  if (type.kind === "array") {
    return isFilePart(context, type.valueType);
  } else if (type.kind === "bytes") {
    return true;
  } else if (type.kind === "model") {
    if (type.__raw && isOrExtendsHttpFile(context.program, type.__raw)) {
      return true;
    }
  }
  return false;
}
function getSdkModelPropertyType(context, type, operation) {
  const diagnostics = createDiagnosticCollector2();
  let property = context.__modelPropertyCache?.get(type);
  if (!property) {
    property = {
      ...diagnostics.pipe(getSdkModelPropertyTypeBase(context, type, operation)),
      kind: "property",
      optional: type.optional,
      discriminator: false,
      serializedName: getPropertyNames(context, type)[1],
      isMultipartFileInput: false,
      flatten: shouldFlattenProperty(context, type),
      serializationOptions: {}
    };
    context.__modelPropertyCache.set(type, property);
  }
  return diagnostics.wrap(property);
}
function addPropertiesToModelType(context, type, sdkType, operation) {
  const diagnostics = createDiagnosticCollector2();
  for (const property of type.properties.values()) {
    if (isStatusCode(context.program, property) || isNeverOrVoidType(property.type) || hasNoneVisibility(context, property)) {
      continue;
    }
    const clientProperty = diagnostics.pipe(getSdkModelPropertyType(context, property, operation));
    sdkType.properties.push(clientProperty);
  }
  return diagnostics.wrap(void 0);
}
function addMultipartPropertiesToModelType(context, sdkType, body, operation) {
  const diagnostics = createDiagnosticCollector2();
  for (const part of body.parts) {
    const clientProperty = diagnostics.pipe(getSdkModelPropertyType(context, part.property, operation));
    const bodyType = getHttpBodyType(part.body);
    if (clientProperty.type.kind === "array") {
      clientProperty.type.valueType = diagnostics.pipe(getClientTypeWithDiagnostics(context, bodyType, operation));
    } else {
      clientProperty.type = diagnostics.pipe(getClientTypeWithDiagnostics(context, bodyType, operation));
    }
    clientProperty.serializationOptions.multipart = {
      isFilePart: isFilePart(context, clientProperty.type),
      isMulti: part.multi,
      filename: part.filename ? diagnostics.pipe(getSdkModelPropertyType(context, part.filename, operation)) : void 0,
      contentType: part.body.contentTypeProperty ? diagnostics.pipe(getSdkModelPropertyType(context, part.body.contentTypeProperty, operation)) : void 0,
      defaultContentTypes: part.body.contentTypes,
      name: part.name,
      headers: part.headers.map((header) => {
        return diagnostics.pipe(getSdkHttpParameter(context, header.property));
      })
    };
    clientProperty.serializedName = clientProperty.serializationOptions.multipart.name;
    clientProperty.isMultipartFileInput = clientProperty.serializationOptions.multipart.isFilePart;
    clientProperty.multipartOptions = clientProperty.serializationOptions.multipart;
    sdkType.properties.push(clientProperty);
  }
  return diagnostics.wrap(void 0);
}
function updateReferencedTypeMap(context, type, sdkType) {
  if (sdkType.kind !== "model" && sdkType.kind !== "enum" && sdkType.kind !== "union" && sdkType.kind !== "nullable") {
    return;
  }
  context.__referencedTypeCache.set(type, sdkType);
}
function updateUsageOrAccess(context, value, type, options) {
  const diagnostics = createDiagnosticCollector2();
  options = options ?? {};
  options.seenTypes = options.seenTypes ?? /* @__PURE__ */ new Set();
  options.propagation = options?.propagation ?? true;
  options.ignoreSubTypeStack = options.ignoreSubTypeStack ?? [];
  if (!type)
    return diagnostics.wrap(void 0);
  if (options.seenTypes.has(type)) {
    options.skipFirst = false;
    return diagnostics.wrap(void 0);
  }
  if (type.kind === "array" || type.kind === "dict") {
    diagnostics.pipe(updateUsageOrAccess(context, value, type.valueType, options));
    return diagnostics.wrap(void 0);
  }
  if (type.kind === "enumvalue") {
    diagnostics.pipe(updateUsageOrAccess(context, value, type.enumType, options));
    return diagnostics.wrap(void 0);
  }
  if (type.kind !== "model" && type.kind !== "enum" && type.kind !== "union" && type.kind !== "nullable") {
    return diagnostics.wrap(void 0);
  }
  if (options.ignoreSubTypeStack.length === 0 || !options.ignoreSubTypeStack.at(-1)) {
    options.seenTypes.add(type);
  }
  if (!options.skipFirst) {
    if (typeof value === "number") {
      type.usage |= value;
    } else {
      if (options.isOverride) {
        if (value === "internal" && type.access === "public" && type.__accessSet) {
          diagnostics.add(createDiagnostic({
            code: "conflict-access-override",
            target: type.__raw
          }));
        } else {
          type.access = value;
        }
      } else {
        if (!type.__accessSet || type.access !== "public") {
          type.access = value;
        }
      }
      type.__accessSet = true;
    }
  } else {
    options.skipFirst = false;
    if (typeof value !== "number") {
      type.__accessSet = true;
    }
  }
  if (type.kind === "enum")
    return diagnostics.wrap(void 0);
  if (type.kind === "union") {
    for (const unionType of type.variantTypes) {
      diagnostics.pipe(updateUsageOrAccess(context, value, unionType, options));
    }
    return diagnostics.wrap(void 0);
  }
  if (type.kind === "nullable") {
    diagnostics.pipe(updateUsageOrAccess(context, value, type.type, options));
    return diagnostics.wrap(void 0);
  }
  if (!options.propagation)
    return diagnostics.wrap(void 0);
  if (type.baseModel) {
    options.ignoreSubTypeStack.push(true);
    if (context.disableUsageAccessPropagationToBase && type.baseModel.discriminatorProperty === void 0) {
      options.skipFirst = true;
    }
    diagnostics.pipe(updateUsageOrAccess(context, value, type.baseModel, options));
    options.ignoreSubTypeStack.pop();
  }
  if (type.discriminatedSubtypes && (options.ignoreSubTypeStack.length === 0 || !options.ignoreSubTypeStack.at(-1))) {
    for (const discriminatedSubtype of Object.values(type.discriminatedSubtypes)) {
      options.ignoreSubTypeStack.push(false);
      diagnostics.pipe(updateUsageOrAccess(context, value, discriminatedSubtype, options));
      options.ignoreSubTypeStack.pop();
    }
  }
  if (type.additionalProperties) {
    options.ignoreSubTypeStack.push(false);
    diagnostics.pipe(updateUsageOrAccess(context, value, type.additionalProperties, options));
    options.ignoreSubTypeStack.pop();
  }
  for (const property of type.properties) {
    options.ignoreSubTypeStack.push(false);
    if (property.kind === "property" && isReadOnly(property) && value === UsageFlags.Input) {
      continue;
    }
    if (typeof value === "number") {
      diagnostics.pipe(updateUsageOrAccess(context, value, property.type, options));
    } else {
      let propertyAccess = value;
      if (property.__raw) {
        const propertyAccessOverride = getAccessOverride(context, property.__raw);
        if (propertyAccessOverride) {
          propertyAccess = propertyAccessOverride;
        }
      }
      diagnostics.pipe(updateUsageOrAccess(context, propertyAccess, property.type, options));
    }
    options.ignoreSubTypeStack.pop();
  }
  return diagnostics.wrap(void 0);
}
function updateTypesFromOperation(context, operation) {
  const diagnostics = createDiagnosticCollector2();
  const program = context.program;
  const httpOperation = getHttpOperationWithCache(context, operation);
  const generateConvenient = shouldGenerateConvenient(context, operation);
  const overriddenClientMethod = getOverriddenClientMethod(context, operation);
  for (const param of (overriddenClientMethod ?? operation).parameters.properties.values()) {
    if (isNeverOrVoidType(param.type))
      continue;
    if (httpOperation.parameters.body?.property === param)
      continue;
    if (param.type.kind === "Model" && isStream(program, param.type))
      continue;
    const sdkType = diagnostics.pipe(getClientTypeWithDiagnostics(context, param.type, operation));
    if (generateConvenient) {
      diagnostics.pipe(updateUsageOrAccess(context, UsageFlags.Input, sdkType));
    }
    const access = getAccessOverride(context, operation) ?? "public";
    diagnostics.pipe(updateUsageOrAccess(context, access, sdkType));
  }
  for (const param of httpOperation.parameters.parameters) {
    if (isNeverOrVoidType(param.param.type))
      continue;
    const sdkType = diagnostics.pipe(getClientTypeWithDiagnostics(context, param.param.type, operation));
    if (generateConvenient) {
      diagnostics.pipe(updateUsageOrAccess(context, UsageFlags.Input, sdkType));
    }
    const access = getAccessOverride(context, operation) ?? "public";
    diagnostics.pipe(updateUsageOrAccess(context, access, sdkType));
  }
  const httpBody = httpOperation.parameters.body;
  if (httpBody && !isNeverOrVoidType(httpBody.type)) {
    const spread = isHttpBodySpread(httpBody);
    const sdkType = diagnostics.pipe(getClientTypeWithDiagnostics(context, getHttpBodyType(httpBody), operation));
    const multipartRequest = httpBody.bodyKind === "multipart";
    if (generateConvenient) {
      if (spread && sdkType.kind === "model") {
        updateUsageOrAccess(context, UsageFlags.Spread, sdkType, { propagation: false });
        updateUsageOrAccess(context, UsageFlags.Input, sdkType, { skipFirst: true });
      } else {
        updateUsageOrAccess(context, UsageFlags.Input, sdkType);
      }
      if (httpBody.contentTypes.some((x) => isMediaTypeJson(x))) {
        diagnostics.pipe(updateUsageOrAccess(context, UsageFlags.Json, sdkType));
      }
      if (httpBody.contentTypes.some((x) => isMediaTypeXml(x))) {
        diagnostics.pipe(updateUsageOrAccess(context, UsageFlags.Xml, sdkType));
      }
      if (httpBody.contentTypes.includes("application/merge-patch+json")) {
        diagnostics.pipe(updateUsageOrAccess(context, UsageFlags.JsonMergePatch, sdkType));
      }
      if (multipartRequest) {
        diagnostics.pipe(updateUsageOrAccess(context, UsageFlags.MultipartFormData, sdkType, {
          propagation: false
        }));
      }
      updateSerializationOptions(context, sdkType, httpBody.contentTypes);
      if (sdkType.kind === "model") {
        const isUsedInMultipart = (sdkType.usage & UsageFlags.MultipartFormData) > 0;
        const isUsedInOthers = (sdkType.usage & UsageFlags.Json | sdkType.usage & UsageFlags.Xml) > 0;
        if (!multipartRequest && isUsedInMultipart || multipartRequest && isUsedInOthers) {
          diagnostics.add(createDiagnostic({
            code: "conflicting-multipart-model-usage",
            target: httpBody.type,
            format: {
              modelName: sdkType.name
            }
          }));
        }
      }
    }
    const access = getAccessOverride(context, operation) ?? "public";
    diagnostics.pipe(updateUsageOrAccess(context, access, sdkType));
  }
  const lroMetaData = getLroMetadata(program, operation);
  for (const response of httpOperation.responses) {
    for (const innerResponse of response.responses) {
      if (innerResponse.body?.type && !isNeverOrVoidType(innerResponse.body.type)) {
        const body = innerResponse.body.type.kind === "Model" ? getEffectivePayloadType(context, innerResponse.body.type, Visibility.Read) : innerResponse.body.type;
        const sdkType = diagnostics.pipe(getClientTypeWithDiagnostics(context, body, operation));
        if (generateConvenient) {
          if (response.statusCodes === "*" || isErrorModel(context.program, body)) {
            diagnostics.pipe(updateUsageOrAccess(context, UsageFlags.Exception, sdkType));
          } else if (lroMetaData !== void 0) {
            diagnostics.pipe(updateUsageOrAccess(context, UsageFlags.LroInitial, sdkType));
          } else {
            diagnostics.pipe(updateUsageOrAccess(context, UsageFlags.Output, sdkType));
          }
          if (innerResponse.body.contentTypes.some((x) => isMediaTypeJson(x))) {
            diagnostics.pipe(updateUsageOrAccess(context, UsageFlags.Json, sdkType));
          }
          if (innerResponse.body.contentTypes.some((x) => isMediaTypeXml(x))) {
            diagnostics.pipe(updateUsageOrAccess(context, UsageFlags.Xml, sdkType));
          }
          if (innerResponse.body.bodyKind === "multipart") {
            diagnostics.pipe(updateUsageOrAccess(context, UsageFlags.MultipartFormData, sdkType, {
              propagation: false
            }));
          }
          updateSerializationOptions(context, sdkType, innerResponse.body.contentTypes);
        }
        const access = getAccessOverride(context, operation) ?? "public";
        diagnostics.pipe(updateUsageOrAccess(context, access, sdkType));
      }
      const headers = getHttpOperationResponseHeaders(innerResponse);
      if (headers) {
        for (const header of Object.values(headers)) {
          if (isNeverOrVoidType(header.type))
            continue;
          const sdkType = diagnostics.pipe(getClientTypeWithDiagnostics(context, header.type, operation));
          if (generateConvenient) {
            diagnostics.pipe(updateUsageOrAccess(context, UsageFlags.Output, sdkType));
          }
          const access = getAccessOverride(context, operation) ?? "public";
          diagnostics.pipe(updateUsageOrAccess(context, access, sdkType));
        }
      }
    }
  }
  if (lroMetaData && generateConvenient) {
    updateUsageOrAccessForLroComponent(lroMetaData.finalResult, UsageFlags.Output);
    updateUsageOrAccessForLroComponent(lroMetaData.finalEnvelopeResult, UsageFlags.LroFinalEnvelope);
    updateUsageOrAccessForLroComponent(lroMetaData.pollingInfo.responseModel, UsageFlags.LroPolling);
  }
  return diagnostics.wrap(void 0);
  function updateUsageOrAccessForLroComponent(model, usage) {
    if (model === void 0 || model === "void")
      return;
    const sdkType = diagnostics.pipe(getClientTypeWithDiagnostics(context, model, operation));
    diagnostics.pipe(updateUsageOrAccess(context, usage, sdkType));
    const access = getAccessOverride(context, operation) ?? "public";
    diagnostics.pipe(updateUsageOrAccess(context, access, sdkType));
    updateSerializationOptions(context, sdkType, ["application/json"]);
  }
}
function updateAccessOverride(context) {
  const diagnostics = createDiagnosticCollector2();
  for (const sdkType of context.__referencedTypeCache.values()) {
    const accessOverride = getAccessOverride(context, sdkType.__raw);
    if (!sdkType.__accessSet && accessOverride === void 0) {
      diagnostics.pipe(updateUsageOrAccess(context, "public", sdkType));
    }
  }
  for (const sdkType of context.__referencedTypeCache.values()) {
    const accessOverride = getAccessOverride(context, sdkType.__raw);
    if (accessOverride) {
      diagnostics.pipe(updateUsageOrAccess(context, accessOverride, sdkType, { isOverride: true }));
    }
  }
  return diagnostics.wrap(void 0);
}
function updateUsageOverride(context) {
  const diagnostics = createDiagnosticCollector2();
  for (const sdkType of context.__referencedTypeCache.values()) {
    const usageOverride = getUsageOverride(context, sdkType.__raw);
    if (usageOverride) {
      diagnostics.pipe(updateUsageOrAccess(context, usageOverride, sdkType, { isOverride: true }));
      if (usageOverride & UsageFlags.Json) {
        updateSerializationOptions(context, sdkType, ["application/json"]);
      }
      if (usageOverride & UsageFlags.Xml) {
        updateSerializationOptions(context, sdkType, ["application/xml"]);
      }
    }
  }
  return diagnostics.wrap(void 0);
}
function updateSpreadModelUsageAndAccess(context) {
  for (const [_, sdkType] of context.__referencedTypeCache.entries()) {
    if (sdkType.kind === "model" && (sdkType.usage & UsageFlags.Spread) > 0 && (sdkType.usage & (UsageFlags.Input | UsageFlags.Output)) === 0) {
      sdkType.access = "internal";
    }
  }
}
function handleLegacyHierarchyBuilding(context) {
  const diagnostics = createDiagnosticCollector2();
  for (const sdkType of context.__referencedTypeCache.values()) {
    if (sdkType.kind !== "model" || !sdkType.baseModel)
      continue;
    const legacyHierarchyBuilding = getLegacyHierarchyBuilding(context, sdkType.__raw);
    const visited = /* @__PURE__ */ new Set();
    visited.add(sdkType.__raw);
    let current = legacyHierarchyBuilding;
    while (current) {
      if (visited.has(current)) {
        diagnostics.add(createDiagnostic({
          code: "legacy-hierarchy-building-circular-reference",
          target: sdkType.__raw
        }));
        return diagnostics.wrap(void 0);
      }
      visited.add(current);
      const changedBase = getLegacyHierarchyBuilding(context, current);
      if (changedBase === void 0) {
        current = current.baseModel;
      } else {
        current = changedBase;
      }
    }
    if (legacyHierarchyBuilding && sdkType.discriminatorValue) {
      let currBaseModel = sdkType.baseModel;
      while (currBaseModel) {
        if (!currBaseModel.discriminatedSubtypes) {
          currBaseModel.discriminatedSubtypes = {};
        }
        currBaseModel.discriminatedSubtypes[sdkType.discriminatorValue] = sdkType;
        currBaseModel.discriminatorProperty = currBaseModel.properties.find((p) => p.discriminator);
        currBaseModel = currBaseModel.baseModel;
      }
      sdkType.properties = sdkType.properties.filter((property) => {
        return property.discriminator || !legacyHierarchyBuilding.properties.has(property.__raw.name);
      });
    }
  }
  return diagnostics.wrap(void 0);
}
function handleServiceOrphanType(context, type) {
  const diagnostics = createDiagnosticCollector2();
  if ((type.kind === "Model" || type.kind === "Union") && isTemplateDeclaration(type)) {
    return diagnostics.wrap(void 0);
  }
  const sdkType = diagnostics.pipe(getClientTypeWithDiagnostics(context, type));
  diagnostics.pipe(updateUsageOrAccess(context, UsageFlags.None, sdkType));
  updateSerializationOptions(context, sdkType, []);
  return diagnostics.wrap(void 0);
}
function filterOutTypes(context, filter) {
  const result = new Array();
  for (const sdkType of context.__referencedTypeCache.values()) {
    if ((sdkType.usage & filter) === 0) {
      continue;
    }
    if (!result.includes(sdkType)) {
      result.push(sdkType);
    }
  }
  return result;
}
function getAllModelsWithDiagnostics(context, options = {}) {
  const diagnostics = createDiagnosticCollector2();
  return diagnostics.wrap(filterOutTypes(context, getFilterNumber(options)).filter((x) => x.kind === "model" || x.kind === "enum"));
}
function getAllModels(context, options = {}) {
  return ignoreDiagnostics2(getAllModelsWithDiagnostics(context, options));
}
function getFilterNumber(options = {}) {
  options = { input: true, output: true, ...options };
  let filter = 0;
  if (options.input && options.output) {
    filter = Number.MAX_SAFE_INTEGER;
  } else if (options.input) {
    filter += UsageFlags.Input;
  } else if (options.output) {
    filter += UsageFlags.Output;
  }
  return filter;
}
function getAllReferencedTypes(context, options = {}) {
  return filterOutTypes(context, getFilterNumber(options));
}
function handleAllTypes(context) {
  const diagnostics = createDiagnosticCollector2();
  for (const client of listClients(context)) {
    for (const operation of listOperationsInOperationGroup(context, client)) {
      diagnostics.pipe(updateTypesFromOperation(context, operation));
    }
    for (const sc of listOperationGroups(context, client, true)) {
      for (const operation of listOperationsInOperationGroup(context, sc)) {
        diagnostics.pipe(updateTypesFromOperation(context, operation));
      }
    }
    const servers = getServers(context.program, client.service);
    if (servers !== void 0 && servers[0].parameters !== void 0) {
      for (const param of servers[0].parameters.values()) {
        const sdkType = diagnostics.pipe(getClientTypeWithDiagnostics(context, param));
        diagnostics.pipe(updateUsageOrAccess(context, UsageFlags.Input, sdkType));
      }
    }
    const [_, versionMap] = getVersions2(context.program, client.service);
    if (versionMap && versionMap.getVersions()[0]) {
      let sdkVersionsEnum;
      const explicitApiVersions = getExplicitClientApiVersions(context, client.service);
      if (explicitApiVersions) {
        sdkVersionsEnum = diagnostics.pipe(getSdkEnumWithDiagnostics(context, explicitApiVersions));
      } else {
        sdkVersionsEnum = diagnostics.pipe(getSdkEnumWithDiagnostics(context, versionMap.getVersions()[0].enumMember.enum));
      }
      filterApiVersionsInEnum(context, client, sdkVersionsEnum);
      diagnostics.pipe(updateUsageOrAccess(context, UsageFlags.ApiVersionEnum, sdkVersionsEnum));
    }
  }
  const userDefinedNamespaces = listAllUserDefinedNamespaces(context);
  for (const currNamespace of userDefinedNamespaces) {
    const namespaces = [currNamespace];
    while (namespaces.length) {
      const namespace2 = namespaces.pop();
      for (const model of namespace2.models.values()) {
        diagnostics.pipe(handleServiceOrphanType(context, model));
      }
      for (const enumType of namespace2.enums.values()) {
        diagnostics.pipe(handleServiceOrphanType(context, enumType));
      }
      for (const unionType of namespace2.unions.values()) {
        diagnostics.pipe(handleServiceOrphanType(context, unionType));
      }
      namespaces.push(...namespace2.namespaces.values());
    }
  }
  diagnostics.pipe(updateAccessOverride(context));
  diagnostics.pipe(updateUsageOverride(context));
  updateSpreadModelUsageAndAccess(context);
  diagnostics.pipe(handleLegacyHierarchyBuilding(context));
  resolveConflictGeneratedName(context);
  return diagnostics.wrap(void 0);
}
function updateSerializationOptions(context, type, contentTypes, options) {
  options = options ?? {};
  options.seenTypes = options.seenTypes ?? /* @__PURE__ */ new Set();
  options.propagation = options?.propagation ?? true;
  options.ignoreSubTypeStack = options.ignoreSubTypeStack ?? [];
  if (options.seenTypes.has(type)) {
    return;
  }
  if (type.kind === "array" || type.kind === "dict") {
    updateSerializationOptions(context, type.valueType, contentTypes, options);
    return;
  }
  if (type.kind !== "model" && type.kind !== "union" && type.kind !== "nullable")
    return;
  if (options.ignoreSubTypeStack.length === 0 || !options.ignoreSubTypeStack.at(-1)) {
    options.seenTypes.add(type);
  }
  if (type.kind === "union") {
    for (const unionType of type.variantTypes) {
      updateSerializationOptions(context, unionType, contentTypes, options);
    }
    return;
  }
  if (type.kind === "nullable") {
    updateSerializationOptions(context, type.type, contentTypes, options);
    return;
  }
  setSerializationOptions(context, type, contentTypes);
  for (const property of type.properties) {
    if (property.kind === "property") {
      setSerializationOptions(context, property, contentTypes);
    }
  }
  if (type.baseModel) {
    options.ignoreSubTypeStack.push(true);
    updateSerializationOptions(context, type.baseModel, contentTypes, options);
    options.ignoreSubTypeStack.pop();
  }
  if (type.discriminatedSubtypes && (options.ignoreSubTypeStack.length === 0 || !options.ignoreSubTypeStack.at(-1))) {
    for (const discriminatedSubtype of Object.values(type.discriminatedSubtypes)) {
      options.ignoreSubTypeStack.push(false);
      updateSerializationOptions(context, discriminatedSubtype, contentTypes, options);
      options.ignoreSubTypeStack.pop();
    }
  }
  if (type.additionalProperties) {
    options.ignoreSubTypeStack.push(false);
    updateSerializationOptions(context, type.additionalProperties, contentTypes, options);
    options.ignoreSubTypeStack.pop();
  }
  for (const property of type.properties) {
    options.ignoreSubTypeStack.push(false);
    updateSerializationOptions(context, property.type, contentTypes, options);
    options.ignoreSubTypeStack.pop();
  }
  return;
}
function setSerializationOptions(context, type, contentTypes) {
  for (const contentType of contentTypes) {
    if (isMediaTypeJson(contentType) && !type.serializationOptions.json) {
      updateJsonSerializationOptions(context, type);
    }
    if (isMediaTypeXml(contentType) && !type.serializationOptions.xml) {
      updateXmlSerializationOptions(context, type);
    }
  }
  if (!type.serializationOptions.json && type.__raw && hasExplicitlyDefinedJsonSerializationInfo(context, type.__raw)) {
    updateJsonSerializationOptions(context, type);
  }
  if (!type.serializationOptions.xml && type.__raw && hasExplicitlyDefinedXmlSerializationInfo(context, type.__raw)) {
    updateXmlSerializationOptions(context, type);
  }
  const defaultContentTypes = type.serializationOptions.multipart?.defaultContentTypes;
  if (defaultContentTypes && type.kind === "property" && type.type.kind === "model") {
    for (const prop of type.type.properties) {
      if (prop.kind === "property") {
        setSerializationOptions(context, prop, defaultContentTypes);
      }
    }
  }
}
function updateJsonSerializationOptions(context, type) {
  type.serializationOptions.json = {
    name: type.__raw?.kind === "Model" || type.__raw?.kind === "ModelProperty" ? resolveEncodedName2(context.program, type.__raw, "application/json") : type.name
  };
}
function updateXmlSerializationOptions(context, type) {
  type.serializationOptions.xml = {
    name: type.__raw?.kind === "Model" || type.__raw?.kind === "ModelProperty" ? resolveEncodedName2(context.program, type.__raw, "application/xml") : type.name,
    attribute: type.__raw?.kind === "ModelProperty" && isAttribute(context.program, type.__raw),
    ns: type.__raw ? getNs(context.program, type.__raw) : void 0,
    unwrapped: type.__raw?.kind === "ModelProperty" && isUnwrapped(context.program, type.__raw)
  };
  if (type.__raw?.kind === "ModelProperty" && type.__raw.type.kind === "Model" && isArrayModelType(context.program, type.__raw.type)) {
    if (!type.serializationOptions.xml.unwrapped) {
      const itemType = type.__raw.type.indexer.value;
      if ("name" in itemType) {
        type.serializationOptions.xml.itemsName = resolveEncodedName2(context.program, itemType, "application/xml");
        type.serializationOptions.xml.itemsNs = getNs(context.program, itemType);
      } else {
        type.serializationOptions.xml.itemsName = type.serializationOptions.xml.name;
        type.serializationOptions.xml.itemsNs = type.serializationOptions.xml.ns;
      }
    } else {
      type.serializationOptions.xml.itemsName = type.serializationOptions.xml.name;
      type.serializationOptions.xml.itemsNs = type.serializationOptions.xml.ns;
    }
  }
}
function hasExplicitlyDefinedXmlSerializationInfo(context, type) {
  if (type.kind === "Model" || type.kind === "ModelProperty" || type.kind === "Scalar") {
    if (type.decorators && type.decorators.some((d) => d.definition?.namespace.name === "Xml")) {
      return true;
    }
    const xmlName = resolveEncodedName2(context.program, type, "application/xml");
    if (xmlName && xmlName !== type.name) {
      return true;
    }
  }
  if (type.kind === "ModelProperty" && type.type.kind === "Model" && isArrayModelType(context.program, type.type)) {
    const itemType = type.type.indexer.value;
    if (itemType && hasExplicitlyDefinedXmlSerializationInfo(context, itemType)) {
      return true;
    }
  }
  return false;
}
function hasExplicitlyDefinedJsonSerializationInfo(context, type) {
  if (type.kind === "ModelProperty") {
    const jsonName = resolveEncodedName2(context.program, type, "application/json");
    if (jsonName && jsonName !== type.name) {
      return true;
    }
  }
  return false;
}

// src/typespec/packages/typespec-client-generator-core/dist/src/http.js
function getSdkHttpOperation(context, httpOperation, methodParameters) {
  const tk = $(context.program);
  const diagnostics = createDiagnosticCollector3();
  const { responses, exceptions } = diagnostics.pipe(getSdkHttpResponseAndExceptions(context, httpOperation));
  if (getResponseAsBool(context, httpOperation.operation)) {
    for (const response of responses) {
      response.type = getSdkConstant(context, tk.literal.createBoolean(true));
    }
    const fourOFourResponse = exceptions.find((e) => e.statusCodes === 404);
    if (fourOFourResponse) {
      fourOFourResponse.type = getSdkConstant(context, tk.literal.createBoolean(false));
      responses.push({
        ...fourOFourResponse,
        statusCodes: 404
      });
      exceptions.splice(exceptions.indexOf(fourOFourResponse), 1);
    } else {
      responses.push({
        kind: "http",
        statusCodes: 404,
        type: getSdkConstant(context, tk.literal.createBoolean(false)),
        apiVersions: getAvailableApiVersions(context, httpOperation.operation, httpOperation.operation),
        headers: [],
        __raw: (responses[0] || exceptions[0]).__raw
      });
    }
  }
  const successResponsesWithBodies = responses.filter((r) => r.type);
  const parameters = diagnostics.pipe(getSdkHttpParameters(context, httpOperation, methodParameters, successResponsesWithBodies[0]));
  filterOutUselessPathParameters(context, httpOperation, methodParameters);
  return diagnostics.wrap({
    __raw: httpOperation,
    kind: "http",
    path: httpOperation.path,
    uriTemplate: httpOperation.uriTemplate,
    verb: httpOperation.verb,
    ...parameters,
    responses,
    exceptions
  });
}
function isSdkHttpParameter(context, type) {
  const program = context.program;
  return isPathParam(program, type) || isQueryParam(program, type) || isHeader2(program, type) || isBody(program, type) || isCookieParam(program, type);
}
function getSdkHttpParameters(context, httpOperation, methodParameters, responseBody) {
  const diagnostics = createDiagnosticCollector3();
  const retval = {
    parameters: [],
    bodyParam: void 0
  };
  retval.parameters = httpOperation.parameters.parameters.filter((x) => !isNeverOrVoidType(x.param.type)).map((x) => diagnostics.pipe(getSdkHttpParameter(context, x.param, httpOperation.operation, x, x.type)));
  const headerParams = retval.parameters.filter((x) => x.kind === "header");
  const tspBody = httpOperation.parameters.body;
  const correspondingMethodParams = [];
  if (tspBody) {
    if (tspBody.bodyKind === "file") {
      diagnostics.add(createDiagnostic({
        code: "unsupported-http-file-body",
        target: tspBody.property ?? tspBody.type
      }));
      return diagnostics.wrap(retval);
    }
    if (tspBody.property && !isNeverOrVoidType(tspBody.property.type)) {
      const bodyParam = diagnostics.pipe(getSdkHttpParameter(context, tspBody.property, httpOperation.operation, void 0, "body"));
      if (bodyParam.kind !== "body") {
        diagnostics.add(createDiagnostic({
          code: "unexpected-http-param-type",
          target: tspBody.property,
          format: {
            paramName: tspBody.property.name,
            expectedType: "body",
            actualType: bodyParam.kind
          }
        }));
        return diagnostics.wrap(retval);
      }
      retval.bodyParam = bodyParam;
    } else if (!isNeverOrVoidType(tspBody.type)) {
      const type = diagnostics.pipe(getClientTypeWithDiagnostics(context, getHttpBodyType(tspBody), httpOperation.operation));
      const name = camelCase(type.name ?? "body");
      retval.bodyParam = {
        kind: "body",
        name,
        isGeneratedName: true,
        serializedName: "",
        doc: getClientDoc(context, tspBody.type),
        summary: getSummary2(context.program, tspBody.type),
        onClient: false,
        contentTypes: [],
        defaultContentType: "application/json",
        // actual content type info is added later
        isApiVersionParam: false,
        apiVersions: getAvailableApiVersions(context, tspBody.type, httpOperation.operation),
        type,
        optional: isHttpBodySpread(tspBody) ? false : tspBody.property?.optional ?? false,
        // optional is always false for spread body
        correspondingMethodParams,
        crossLanguageDefinitionId: `${getCrossLanguageDefinitionId(context, httpOperation.operation)}.body`,
        decorators: diagnostics.pipe(getTypeDecorators(context, tspBody.type)),
        access: "public"
      };
    }
    if (retval.bodyParam) {
      retval.bodyParam.correspondingMethodParams = diagnostics.pipe(getCorrespondingMethodParams(context, httpOperation.operation, methodParameters, retval.bodyParam));
      addContentTypeInfoToBodyParam(context, httpOperation, retval.bodyParam);
      if (getStreamMetadata(context.program, httpOperation.parameters)) {
        retval.bodyParam.type = diagnostics.pipe(getStreamAsBytes(context, retval.bodyParam.type.__raw));
        retval.bodyParam.correspondingMethodParams.map((p) => p.type = retval.bodyParam.type);
      }
    }
  }
  if (retval.bodyParam && !headerParams.some((h) => isContentTypeHeader(h))) {
    const contentTypeBase = {
      ...createContentTypeOrAcceptHeader(context, httpOperation, retval.bodyParam),
      doc: `Body parameter's content type. Known values are ${retval.bodyParam.contentTypes}`
    };
    if (!methodParameters.some((m) => m.name === "contentType")) {
      methodParameters.push({
        ...contentTypeBase,
        kind: "method"
      });
    }
    retval.parameters.push({
      ...contentTypeBase,
      kind: "header",
      serializedName: "Content-Type",
      correspondingMethodParams
    });
  }
  if (responseBody && !headerParams.some((h) => isAcceptHeader(h))) {
    const acceptBase = {
      ...createContentTypeOrAcceptHeader(context, httpOperation, responseBody)
    };
    if (!methodParameters.some((m) => m.name === "accept")) {
      methodParameters.push({
        ...acceptBase,
        kind: "method"
      });
    }
    retval.parameters.push({
      ...acceptBase,
      kind: "header",
      serializedName: "Accept",
      correspondingMethodParams
    });
  }
  for (const param of retval.parameters) {
    param.correspondingMethodParams = diagnostics.pipe(getCorrespondingMethodParams(context, httpOperation.operation, methodParameters, param));
  }
  return diagnostics.wrap(retval);
}
function createContentTypeOrAcceptHeader(context, httpOperation, bodyObject) {
  const name = bodyObject.kind === "body" ? "contentType" : "accept";
  let type = getTypeSpecBuiltInType(context, "string");
  if (bodyObject.contentTypes && bodyObject.contentTypes.length === 1 && (isMediaTypeJson(bodyObject.contentTypes[0]) || isMediaTypeTextPlain(bodyObject.contentTypes[0]) || isMediaTypeOctetStream(bodyObject.contentTypes[0]) || name === "accept")) {
    type = {
      kind: "constant",
      value: bodyObject.contentTypes[0],
      valueType: type,
      name: `${httpOperation.operation.name}ContentType`,
      isGeneratedName: true,
      decorators: []
    };
  }
  const optional = bodyObject.kind === "body" ? bodyObject.optional : false;
  return {
    type,
    name,
    isGeneratedName: true,
    apiVersions: bodyObject.apiVersions,
    isApiVersionParam: false,
    onClient: false,
    optional,
    crossLanguageDefinitionId: `${getCrossLanguageDefinitionId(context, httpOperation.operation)}.${name}`,
    decorators: [],
    access: "public"
  };
}
function addContentTypeInfoToBodyParam(context, httpOperation, bodyParam) {
  const diagnostics = createDiagnosticCollector3();
  const tspBody = httpOperation.parameters.body;
  if (!tspBody)
    return diagnostics.diagnostics;
  const contentTypes = tspBody.contentTypes;
  compilerAssert(contentTypes.length > 0, "contentTypes should not be empty");
  const defaultContentType = contentTypes.includes("application/json") ? "application/json" : contentTypes[0];
  bodyParam.contentTypes = contentTypes;
  bodyParam.defaultContentType = defaultContentType;
  diagnostics.pipe(addEncodeInfo(context, bodyParam.__raw, bodyParam.type, defaultContentType));
  if (bodyParam.correspondingMethodParams.length === 1) {
    const methodBodyParam = bodyParam.correspondingMethodParams[0];
    diagnostics.pipe(addEncodeInfo(context, methodBodyParam.__raw, methodBodyParam.type, bodyParam.defaultContentType));
  }
  return diagnostics.diagnostics;
}
function getSdkHttpParameter(context, param, operation, httpParam, location) {
  const diagnostics = createDiagnosticCollector3();
  const base = diagnostics.pipe(getSdkModelPropertyTypeBase(context, param, operation));
  const program = context.program;
  if (isPathParam(context.program, param) || location === "path") {
    return diagnostics.wrap({
      ...base,
      kind: "path",
      explode: httpParam?.explode ?? false,
      style: httpParam?.style ?? "simple",
      // url type need allow reserved
      allowReserved: httpParam?.allowReserved ?? $(program).type.isAssignableTo(param.type, $(program).builtin.url, param.type),
      serializedName: getPathParamName(program, param) ?? base.name,
      correspondingMethodParams: [],
      optional: param.optional
    });
  }
  if (isCookieParam(context.program, param) || location === "cookie") {
    return diagnostics.wrap({
      ...base,
      kind: "cookie",
      serializedName: getCookieParamOptions(program, param)?.name ?? base.name,
      correspondingMethodParams: [],
      optional: param.optional
    });
  }
  if (isBody(context.program, param) || location === "body") {
    return diagnostics.wrap({
      ...base,
      kind: "body",
      serializedName: param.name === "" ? "body" : getWireName(context, param),
      contentTypes: ["application/json"],
      defaultContentType: "application/json",
      optional: param.optional,
      correspondingMethodParams: []
    });
  }
  const headerQueryBase = {
    ...base,
    optional: param.optional,
    collectionFormat: diagnostics.pipe(getCollectionFormat(context, param)),
    correspondingMethodParams: []
  };
  if (isQueryParam(context.program, param) || location === "query") {
    return diagnostics.wrap({
      ...headerQueryBase,
      kind: "query",
      serializedName: getQueryParamName(program, param) ?? base.name,
      explode: httpParam?.explode
    });
  }
  if (!(isHeader2(context.program, param) || location === "header")) {
    diagnostics.add(createDiagnostic({
      code: "unexpected-http-param-type",
      target: param,
      format: {
        paramName: param.name,
        expectedType: "path, query, header, or body",
        actualType: param.kind
      }
    }));
  }
  return diagnostics.wrap({
    ...headerQueryBase,
    kind: "header",
    serializedName: getHeaderFieldName(program, param) ?? base.name
  });
}
function getSdkHttpResponseAndExceptions(context, httpOperation) {
  const tk = $(context.program);
  const diagnostics = createDiagnosticCollector3();
  const responses = [];
  const exceptions = [];
  for (const response of httpOperation.responses) {
    const headers = [];
    let body;
    let type;
    let contentTypes = [];
    for (const innerResponse of response.responses) {
      const defaultContentType = innerResponse.body?.contentTypes.includes("application/json") ? "application/json" : innerResponse.body?.contentTypes[0];
      for (const header of getHttpOperationResponseHeaders(innerResponse)) {
        if (isNeverOrVoidType(header.type))
          continue;
        headers.push({
          ...diagnostics.pipe(getSdkModelPropertyTypeBase(context, header, httpOperation.operation)),
          __raw: header,
          kind: "responseheader",
          serializedName: getHeaderFieldName(context.program, header)
        });
        context.__responseHeaderCache.set(header, headers[headers.length - 1]);
      }
      if (innerResponse.body && !isNeverOrVoidType(innerResponse.body.type)) {
        if (body && body !== innerResponse.body.type) {
          diagnostics.add(createDiagnostic({
            code: "multiple-response-types",
            target: innerResponse.body.type,
            format: {
              operation: httpOperation.operation.name
            }
          }));
          body = tk.union.create([body, innerResponse.body.type]);
        } else if (!body) {
          body = innerResponse.body.type;
        }
        contentTypes = contentTypes.concat(innerResponse.body.contentTypes);
        body = body.kind === "Model" ? getEffectivePayloadType(context, body, Visibility2.Read) : body;
        if (getStreamMetadata(context.program, innerResponse)) {
          type = diagnostics.pipe(getStreamAsBytes(context, innerResponse.body.type));
        } else {
          type = diagnostics.pipe(getClientTypeWithDiagnostics(context, body, httpOperation.operation));
          if (innerResponse.body.property) {
            addEncodeInfo(context, innerResponse.body.property, type, defaultContentType);
          }
        }
      }
    }
    const sdkResponse = {
      __raw: response,
      type,
      headers,
      contentTypes: contentTypes.length > 0 ? contentTypes : void 0,
      defaultContentType: contentTypes.includes("application/json") ? "application/json" : contentTypes[0],
      apiVersions: getAvailableApiVersions(context, httpOperation.operation, httpOperation.operation),
      description: response.description
    };
    if (response.statusCodes === "*" || isErrorModel2(context.program, response.type) || body && isErrorModel2(context.program, body)) {
      exceptions.push({
        ...sdkResponse,
        kind: "http",
        statusCodes: response.statusCodes
      });
    } else {
      responses.push({
        ...sdkResponse,
        kind: "http",
        statusCodes: response.statusCodes
      });
    }
  }
  return diagnostics.wrap({ responses, exceptions });
}
function getCorrespondingMethodParams(context, operation, methodParameters, serviceParam) {
  const diagnostics = createDiagnosticCollector3();
  if (serviceParam.onClient) {
    if (serviceParam.__raw) {
      const correspondingClientParam = getCorrespondingClientParam(context, serviceParam.__raw, operation);
      if (correspondingClientParam)
        return diagnostics.wrap([correspondingClientParam]);
    }
    const clientParams = context.__clientParametersCache.get(context.getClientForOperation(operation));
    if (clientParams && serviceParam.isApiVersionParam && serviceParam.onClient) {
      const existingApiVersion = clientParams.find((x) => isApiVersion(context, x.__raw));
      if (!existingApiVersion) {
        diagnostics.add(createDiagnostic({
          code: "no-corresponding-method-param",
          target: operation,
          format: {
            paramName: "apiVersion",
            methodName: operation.name
          }
        }));
        return diagnostics.wrap([]);
      }
      return diagnostics.wrap(existingApiVersion ? [existingApiVersion] : []);
    }
    if (clientParams && isSubscriptionId(context, serviceParam)) {
      const subId = clientParams.find((x) => isSubscriptionId(context, x));
      if (!subId) {
        diagnostics.add(createDiagnostic({
          code: "no-corresponding-method-param",
          target: operation,
          format: {
            paramName: "subscriptionId",
            methodName: operation.name
          }
        }));
        return diagnostics.wrap([]);
      }
      return diagnostics.wrap(subId ? [subId] : []);
    }
  }
  const directMapping = findMapping(context, methodParameters, serviceParam);
  if (directMapping) {
    return diagnostics.wrap([directMapping]);
  }
  if (serviceParam.kind === "body" && serviceParam.type.kind === "model") {
    const retVal = [];
    let optionalSkip = 0;
    for (const serviceParamProp of serviceParam.type.properties) {
      const propertyMapping = findMapping(context, methodParameters, serviceParamProp);
      if (propertyMapping) {
        retVal.push(propertyMapping);
      } else if (serviceParamProp.optional) {
        optionalSkip++;
      }
    }
    if (retVal.length + optionalSkip === serviceParam.type.properties.length) {
      return diagnostics.wrap(retVal);
    }
  }
  if (!serviceParam.optional) {
    diagnostics.add(createDiagnostic({
      code: "no-corresponding-method-param",
      target: operation,
      format: {
        paramName: serviceParam.name,
        methodName: operation.name
      }
    }));
  }
  return diagnostics.wrap([]);
}
function findMapping(context, methodParameters, serviceParam) {
  const queue = [...methodParameters];
  const visited = /* @__PURE__ */ new Set();
  while (queue.length > 0) {
    const methodParam = queue.shift();
    if (methodParam.__raw && serviceParam.__raw && compareModelProperties(context, methodParam.__raw, serviceParam.__raw)) {
      return methodParam;
    }
    if (serviceParam.kind === "header" && serviceParam.serializedName === "Content-Type" && methodParam.name === "contentType") {
      return methodParam;
    }
    if (serviceParam.kind === "header" && serviceParam.serializedName === "Accept" && methodParam.name === "accept") {
      return methodParam;
    }
    if (serviceParam.kind === "body" && serviceParam.type === methodParam.type) {
      return methodParam;
    }
    if (methodParam.type.kind === "model" && !visited.has(methodParam.type)) {
      visited.add(methodParam.type);
      let current = methodParam.type;
      while (current) {
        for (const prop of methodParam.type.properties) {
          queue.push(prop);
        }
        current = current.baseModel;
      }
    }
  }
  return void 0;
}
function filterOutUselessPathParameters(context, httpOperation, methodParameters) {
  for (let i = 0; i < methodParameters.length; i++) {
    const param = methodParameters[i];
    if (param.__raw && isPathParam(context.program, param.__raw) && httpOperation.parameters.parameters.filter((p) => p.type === "path" && p.name === (getPathParamName(context.program, param.__raw) ?? param.name)).length === 0) {
      methodParameters.splice(i, 1);
      i--;
    }
  }
}
function getCollectionFormat(context, type) {
  const diagnostics = createDiagnosticCollector3();
  const program = context.program;
  if (isHeader2(program, type)) {
    return getFormatFromExplodeOrEncode(context, type, getHeaderFieldOptions(program, type).explode);
  } else if (isQueryParam(program, type)) {
    return getFormatFromExplodeOrEncode(context, type, getQueryParamOptions(program, type)?.explode);
  }
  return diagnostics.wrap(void 0);
}
function getFormatFromExplodeOrEncode(context, type, explode) {
  const diagnostics = createDiagnosticCollector3();
  if ($(context.program).array.is(type.type)) {
    if (explode) {
      return diagnostics.wrap("multi");
    }
    const encode = getEncode2(context.program, type);
    if (encode) {
      if (encode?.encoding === "ArrayEncoding.pipeDelimited") {
        return diagnostics.wrap("pipes");
      }
      if (encode?.encoding === "ArrayEncoding.spaceDelimited") {
        return diagnostics.wrap("ssv");
      }
      diagnostics.add(createDiagnostic({
        code: "invalid-encode-for-collection-format",
        target: type
      }));
    }
    return diagnostics.wrap("csv");
  }
  return diagnostics.wrap(void 0);
}

// src/typespec/packages/typespec-client-generator-core/dist/src/internal-utils.js
var AllScopes = Symbol.for("@azure-core/typespec-client-generator-core/all-scopes");
var clientNameKey = createStateSymbol("clientName");
var clientNamespaceKey = createStateSymbol("clientNamespace");
var negationScopesKey = createStateSymbol("negationScopes");
var scopeKey = createStateSymbol("scope");
var clientKey = createStateSymbol("client");
var operationGroupKey = createStateSymbol("operationGroup");
var clientLocationKey = createStateSymbol("clientLocation");
var omitOperation = createStateSymbol("omitOperation");
var overrideKey = createStateSymbol("override");
function hasExplicitClientOrOperationGroup(context) {
  return listScopedDecoratorData(context, clientKey).size > 0 || listScopedDecoratorData(context, operationGroupKey).size > 0;
}
function listScopedDecoratorData(context, key, languageScope) {
  const scope = languageScope ?? context.emitterName;
  const retval = /* @__PURE__ */ new Map();
  for (const [type, data] of context.program.stateMap(key).entries()) {
    if (data[scope]) {
      retval.set(type, data[scope]);
    } else if (data[negationScopesKey]) {
      if (data[negationScopesKey].includes(scope)) {
        continue;
      } else {
        retval.set(type, data[AllScopes]);
      }
    } else if (data[AllScopes]) {
      retval.set(type, data[AllScopes]);
    }
  }
  return retval;
}
function getScopedDecoratorData(context, key, target, languageScope) {
  const retval = context.program.stateMap(key).get(target);
  if (retval === void 0)
    return retval;
  if (languageScope === AllScopes) {
    return retval[languageScope];
  }
  if (languageScope === void 0 || typeof languageScope === "string") {
    const scope = languageScope ?? context.emitterName;
    if (Object.keys(retval).includes(scope))
      return retval[scope];
    const negationScopes = retval[negationScopesKey];
    if (negationScopes !== void 0 && negationScopes.includes(scope)) {
      return void 0;
    }
  }
  return retval[AllScopes];
}
function parseEmitterName(program, emitterName) {
  const diagnostics = createDiagnosticCollector4();
  if (!emitterName) {
    diagnostics.add(createDiagnostic({
      code: "no-emitter-name",
      format: {},
      target: program.getGlobalNamespaceType()
    }));
    return diagnostics.wrap("none");
  }
  const regex = /(?:cadl|typespec|client|server)-([^\\/-]*)/;
  const match = emitterName.match(regex);
  if (!match || match.length < 2)
    return diagnostics.wrap("none");
  const language = match[1];
  if (["typescript", "ts"].includes(language))
    return diagnostics.wrap("javascript");
  return diagnostics.wrap(language);
}
function updateWithApiVersionInformation(context, type, client) {
  const isApiVersionParam = isApiVersion(context, type);
  return {
    isApiVersionParam,
    clientDefaultValue: isApiVersionParam && client ? context.__clientApiVersionDefaultValueCache.get(client) : void 0
  };
}
function filterApiVersionsWithDecorators(context, type, apiVersions) {
  const addedOnVersions = getAddedOnVersions(context.program, type)?.map((x) => x.value) ?? [];
  const removedOnVersions = getRemovedOnVersions(context.program, type)?.map((x) => x.value) ?? [];
  let added = addedOnVersions.length ? false : true;
  let addedCounter = 0;
  let removeCounter = 0;
  const retval = [];
  for (let i = 0; i < apiVersions.length; i++) {
    const version = apiVersions[i];
    if (addedCounter < addedOnVersions.length && version === addedOnVersions[addedCounter]) {
      added = true;
      addedCounter++;
    }
    if (removeCounter < removedOnVersions.length && version === removedOnVersions[removeCounter]) {
      added = false;
      removeCounter++;
    }
    if (added) {
      if (context.apiVersion === void 0 || context.apiVersion === "latest" || context.apiVersion === "all" || apiVersions.indexOf(context.apiVersion) >= i) {
        retval.push(version);
      }
    }
  }
  return retval;
}
function getAvailableApiVersions(context, type, wrapper) {
  let wrapperApiVersions = [];
  if (wrapper) {
    wrapperApiVersions = context.getApiVersionsForType(wrapper);
  }
  const allApiVersions = getVersions3(context.program, type)[1]?.getVersions().map((x) => x.value) || [];
  const apiVersions = wrapperApiVersions.length ? wrapperApiVersions : allApiVersions;
  if (!apiVersions)
    return [];
  const explicitlyDecorated = filterApiVersionsWithDecorators(context, type, apiVersions);
  if (explicitlyDecorated.length) {
    context.setApiVersionsForType(type, explicitlyDecorated);
    return explicitlyDecorated;
  }
  context.setApiVersionsForType(type, wrapperApiVersions);
  return context.getApiVersionsForType(type);
}
function getHashForType(type) {
  if (type.kind === "array" || type.kind === "dict") {
    return `${type.kind}[${getHashForType(type.valueType)}]`;
  }
  if (type.kind === "enum" || type.kind === "model" || type.kind === "enumvalue")
    return type.name;
  if (type.kind === "union") {
    return type.variantTypes.map((x) => getHashForType(x)).join("|");
  }
  return type.kind;
}
function getSdkTypeBaseHelper(context, type, kind) {
  const diagnostics = createDiagnosticCollector4();
  return diagnostics.wrap({
    __raw: type,
    deprecation: getDeprecationDetails(context.program, type)?.message,
    kind,
    decorators: diagnostics.pipe(getTypeDecorators(context, type))
  });
}
function getNamespacePrefix(namespace2) {
  return namespace2 ? getNamespaceFullName2(namespace2) + "." : "";
}
function getTypeDecorators(context, type) {
  const diagnostics = createDiagnosticCollector4();
  const retval = [];
  if ("decorators" in type) {
    for (const decorator of type.decorators) {
      if (decorator.definition) {
        const decoratorName = `${getNamespacePrefix(decorator.definition?.namespace)}${decorator.definition?.name}`;
        if (!context.decoratorsAllowList || !context.decoratorsAllowList.some((x) => new RegExp(x).test(decoratorName))) {
          continue;
        }
        const decoratorInfo = {
          name: decoratorName,
          arguments: {}
        };
        for (let i = 0; i < decorator.args.length; i++) {
          decoratorInfo.arguments[decorator.definition.parameters[i].name] = diagnostics.pipe(getDecoratorArgValue(context, decorator.args[i].jsValue, type, decoratorName));
        }
        retval.push(decoratorInfo);
      }
    }
  }
  return diagnostics.wrap(retval);
}
function getDecoratorArgValue(context, arg, type, decoratorName) {
  const diagnostics = createDiagnosticCollector4();
  if (typeof arg === "object" && arg !== null && "kind" in arg) {
    if (arg.kind === "EnumMember") {
      return diagnostics.wrap(diagnostics.pipe(getClientTypeWithDiagnostics(context, arg)));
    }
    if (arg.kind === "String" || arg.kind === "Number" || arg.kind === "Boolean") {
      return diagnostics.wrap(arg.value);
    }
    diagnostics.add(createDiagnostic({
      code: "unsupported-generic-decorator-arg-type",
      target: type,
      format: { decoratorName }
    }));
    return diagnostics.wrap(void 0);
  }
  return diagnostics.wrap(arg);
}
function intOrFloat(value) {
  return value.toString().indexOf(".") === -1 ? "int32" : "float32";
}
function isAzureCoreTspModel(t) {
  return (t.kind === "Model" || t.kind === "Enum" || t.kind === "Union") && t.namespace !== void 0 && ["Azure.Core", "Azure.Core.Foundations"].includes(getNamespaceFullName2(t.namespace));
}
function isAcceptHeader(param) {
  return param.kind === "header" && param.serializedName.toLowerCase() === "accept";
}
function isContentTypeHeader(param) {
  return param.kind === "header" && param.serializedName.toLowerCase() === "content-type";
}
function getNonNullOptions(type) {
  return [...type.variants.values()].map((x) => x.type).filter((t) => !isNullType(t));
}
function getNullOption(type) {
  return [...type.variants.values()].map((x) => x.type).filter((t) => isNullType(t))[0];
}
function getAllResponseBodiesAndNonBodyExists(responses) {
  const allResponseBodies = [];
  let nonBodyExists = false;
  for (const response of responses) {
    if (response.type) {
      allResponseBodies.push(response.type);
    } else {
      nonBodyExists = true;
    }
  }
  return { allResponseBodies, nonBodyExists };
}
function createGeneratedName(context, type, suffix) {
  return `${getCrossLanguageDefinitionId(context, type).split(".").at(-1)}${suffix}`;
}
function isSubscriptionId(context, parameter) {
  return Boolean(context.arm) && parameter.name === "subscriptionId";
}
function isNeverOrVoidType(type) {
  return isNeverType2(type) || isVoidType(type);
}
function getHttpOperationResponseHeaders(response) {
  const headers = response.headers ? Object.values(response.headers) : [];
  if (response.body?.contentTypeProperty) {
    headers.push(response.body.contentTypeProperty);
  }
  return headers;
}
function removeVersionsLargerThanExplicitlySpecified(context, versions) {
  if (context.apiVersion !== void 0 && context.apiVersion !== "latest" && context.apiVersion !== "all") {
    const index = versions.findIndex((version) => version.value === context.apiVersion);
    if (index >= 0) {
      versions.splice(index + 1, versions.length - index - 1);
    }
  }
}
function filterApiVersionsInEnum(context, client, sdkVersionsEnum) {
  removeVersionsLargerThanExplicitlySpecified(context, sdkVersionsEnum.values);
  const defaultApiVersion = getDefaultApiVersion(context, client.service);
  if (!context.previewStringRegex.test(defaultApiVersion?.value || "")) {
    sdkVersionsEnum.values = sdkVersionsEnum.values.filter((v) => typeof v.value === "string" && !context.previewStringRegex.test(v.value));
  }
}
function twoParamsEquivalent(context, param1, param2) {
  if (!param1 || !param2) {
    return false;
  }
  return param1.type === param2.type && (param1.name === param2.name || getParamAlias(context, param1) === param2.name || param1.name === getParamAlias(context, param2));
}
function isHttpBodySpread(httpBody) {
  return httpBody.bodyKind !== "file" && httpBody.property === void 0;
}
function getHttpBodyType(httpBody) {
  const type = httpBody.type;
  if (isHttpBodySpread(httpBody) && type.kind === "Model") {
    if (type.sourceModels.length === 1 && type.sourceModels[0].usage === "spread") {
      const innerModel = type.sourceModels[0].model;
      if (innerModel.name !== "" && innerModel.properties.size === type.properties.size) {
        return innerModel;
      }
      if (innerModel.sourceModels.length === 1 && innerModel.sourceModels[0].usage === "spread" && innerModel.sourceModels[0].model.name !== "" && innerModel.sourceModels[0].model.properties.size === type.properties.size) {
        return innerModel.sourceModels[0].model;
      }
    }
    return type;
  }
  return type;
}
function isOnClient(context, type, operation, versioning) {
  const clientLocation = getClientLocation(context, type);
  if (operation && clientLocation === operation) {
    return false;
  }
  return isSubscriptionId(context, type) || isApiVersion(context, type) && versioning || operation !== void 0 && getCorrespondingClientParam(context, type, operation) !== void 0;
}
function getCorrespondingClientParam(context, type, operation) {
  const clientParams = [];
  let client = context.getClientForOperation(operation);
  while (client) {
    const clientParamsForClient = context.__clientParametersCache.get(client);
    if (clientParamsForClient) {
      clientParams.push(...clientParamsForClient);
    }
    if (client.kind === "SdkClient") {
      break;
    }
    client = client.parent;
  }
  const correspondingClientParam = clientParams?.find((x) => twoParamsEquivalent(context, x.__raw, type));
  if (correspondingClientParam)
    return correspondingClientParam;
  return void 0;
}
function getValueTypeValue(value) {
  switch (value.valueKind) {
    case "ArrayValue":
      return value.values.map((x) => getValueTypeValue(x));
    case "BooleanValue":
    case "StringValue":
    case "NullValue":
      return value.value;
    case "NumericValue":
      return value.value.asNumber();
    case "EnumValue":
      return value.value.value ?? value.value.name;
    case "ObjectValue":
      return Object.fromEntries([...value.properties.keys()].map((x) => [
        x,
        getValueTypeValue(value.properties.get(x).value)
      ]));
    case "ScalarValue":
      return void 0;
  }
}
function hasNoneVisibility(context, type) {
  const lifecycle = getLifecycleVisibilityEnum2(context.program);
  const visibility = getVisibilityForClass2(context.program, type, lifecycle);
  return visibility.size === 0;
}
function listAllNamespaces(context, namespace2, retval) {
  if (!retval) {
    retval = [];
  }
  if (retval.includes(namespace2))
    return retval;
  retval.push(namespace2);
  for (const ns of namespace2.namespaces.values()) {
    listAllNamespaces(context, ns, retval);
  }
  return retval;
}
function listAllUserDefinedNamespaces(context) {
  return listAllNamespaces(context, context.getMutatedGlobalNamespace()).filter((ns) => $2(context.program).type.isUserDefined(ns));
}
function findRootSourceProperty(property) {
  while (property.sourceProperty) {
    property = property.sourceProperty;
  }
  return property;
}
function getStreamAsBytes(context, type) {
  const diagnostics = createDiagnosticCollector4();
  const unknownType = {
    ...diagnostics.pipe(getSdkTypeBaseHelper(context, type, "bytes")),
    name: "bytes",
    encode: "bytes",
    crossLanguageDefinitionId: ""
  };
  return diagnostics.wrap(unknownType);
}
function getVersioningMutator(context, service, apiVersion) {
  const versionMutator = getVersioningMutators(context.program, service);
  compilerAssert2(versionMutator !== void 0 && versionMutator.kind !== "transient", "Versioning service should not get undefined or transient versioning mutator");
  const mutators = versionMutator.snapshots.filter((snapshot) => apiVersion === snapshot.version.value).map((x) => x.mutator);
  compilerAssert2(mutators.length === 1, "One api version should not get multiple mutators");
  return mutators[0];
}
function handleVersioningMutationForGlobalNamespace(context) {
  const globalNamespace = context.program.getGlobalNamespaceType();
  const allApiVersions = context.getPackageVersions();
  if (allApiVersions.length === 0 || context.apiVersion === "all")
    return globalNamespace;
  const mutator = getVersioningMutator(context, listServices(context.program)[0].type, allApiVersions[allApiVersions.length - 1]);
  const subgraph = unsafe_mutateSubgraphWithNamespace(context.program, [mutator], globalNamespace);
  compilerAssert2(subgraph.type.kind === "Namespace", "Should not have mutated to another type");
  return subgraph.type;
}
function resolveDuplicateGenearatedName(context, type, createName) {
  let duplicateCount = 1;
  const rawCreateName = createName;
  const generatedNames = [...context.__generatedNames.values()];
  while (generatedNames.includes(createName)) {
    createName = `${rawCreateName}${duplicateCount++}`;
  }
  context.__generatedNames.set(type, createName);
  return createName;
}
function resolveConflictGeneratedName(context) {
  const userDefinedNames = [...context.__referencedTypeCache.values()].filter((x) => !x.isGeneratedName).map((x) => x.name);
  const generatedNames = [...context.__generatedNames.values()];
  for (const sdkType of context.__referencedTypeCache.values()) {
    if (sdkType.__raw && sdkType.isGeneratedName && userDefinedNames.includes(sdkType.name)) {
      const rawName = sdkType.name;
      let duplicateCount = 1;
      let createName = `${rawName}${duplicateCount++}`;
      while (userDefinedNames.includes(createName) || generatedNames.includes(createName)) {
        createName = `${rawName}${duplicateCount++}`;
      }
      sdkType.name = createName;
      context.__generatedNames.set(sdkType.__raw, createName);
      generatedNames.push(createName);
    }
  }
}
function getClientDoc(context, target) {
  const clientDocExplicit = getClientDocExplicit(context, target);
  const baseDoc = getDoc(context.program, target);
  if (clientDocExplicit) {
    switch (clientDocExplicit.mode) {
      case "append":
        return baseDoc ? `${baseDoc}
${clientDocExplicit.documentation}` : clientDocExplicit.documentation;
      case "replace":
        return clientDocExplicit.documentation;
    }
  }
  return baseDoc;
}
function compareModelProperties(context, modelPropA, modelPropB) {
  if (!modelPropA || !modelPropB)
    return false;
  if (modelPropA.name !== modelPropB.name || modelPropA.type !== modelPropB.type)
    return false;
  if (!context)
    return true;
  if (!isSdkHttpParameter(context, modelPropA) || !isSdkHttpParameter(context, modelPropB))
    return true;
  const sdkA = ignoreDiagnostics3(getSdkHttpParameter(context, modelPropA));
  const sdkB = ignoreDiagnostics3(getSdkHttpParameter(context, modelPropB));
  return sdkA.kind === sdkB.kind && sdkA.serializedName === sdkB.serializedName;
}
function findEntriesWithTarget(context, stateKey, targetValue, sourceKind) {
  const results = [];
  for (const [type, target] of listScopedDecoratorData(context, stateKey)) {
    if (sourceKind && type.kind !== sourceKind) {
      continue;
    }
    if (target === targetValue) {
      results.push(type);
    }
  }
  return results;
}

// src/typespec/packages/typespec-client-generator-core/dist/src/decorators.js
var namespace = "Azure.ClientGenerator.Core";
function setScopedDecoratorData(context, decorator, key, target, value, scope) {
  const targetEntry = context.program.stateMap(key).get(target);
  if (!scope) {
    if (targetEntry && targetEntry[AllScopes]) {
      targetEntry[AllScopes] = value;
    } else {
      const newObject = Object.fromEntries([[AllScopes, value]]);
      context.program.stateMap(key).set(target, !targetEntry ? newObject : { ...targetEntry, ...newObject });
    }
    return;
  }
  const [negationScopes, scopes] = parseScopes(context, scope);
  if (negationScopes !== void 0 && negationScopes.length > 0) {
    const newObject = scopes !== void 0 && scopes.length > 0 ? Object.fromEntries([AllScopes, ...scopes].map((scope2) => [scope2, value])) : Object.fromEntries([[AllScopes, value]]);
    newObject[negationScopesKey] = negationScopes;
    context.program.stateMap(key).set(target, newObject);
    if (targetEntry !== void 0) {
      const existingScopes = Object.getOwnPropertyNames(targetEntry);
      const intersections = existingScopes.filter((x) => negationScopes.includes(x));
      if (intersections !== void 0 && intersections.length > 0) {
        for (const scopeToKeep of intersections) {
          newObject[scopeToKeep] = targetEntry[scopeToKeep];
        }
      }
    }
  } else if (scopes !== void 0 && scopes.length > 0) {
    const newObject = Object.fromEntries(scopes.map((scope2) => [scope2, value]));
    context.program.stateMap(key).set(target, !targetEntry ? newObject : { ...targetEntry, ...newObject });
  }
}
function parseScopes(context, scope) {
  if (scope === void 0) {
    return [void 0, void 0];
  }
  const negationScopeRegex = new RegExp(/!\((.*?)\)/);
  const negationScopeMatch = scope.match(negationScopeRegex);
  if (negationScopeMatch) {
    return [negationScopeMatch[1].split(",").map((s) => s.trim()), void 0];
  }
  const splitScopes = scope.split(",").map((s) => s.trim());
  const negationScopes = [];
  const scopes = [];
  for (const s of splitScopes) {
    if (s.startsWith("!")) {
      negationScopes.push(s.slice(1));
    } else {
      scopes.push(s);
    }
  }
  return [negationScopes, scopes];
}
var $client = (context, target, options, scope) => {
  if (context.decoratorTarget.kind === SyntaxKind.AugmentDecoratorStatement) {
    reportDiagnostic(context.program, {
      code: "wrong-client-decorator",
      target: context.decoratorTarget
    });
    return;
  }
  const explicitName = options?.kind === "Model" ? options?.properties.get("name")?.type : void 0;
  const name = explicitName?.kind === "String" ? explicitName.value : target.name;
  let service = options?.kind === "Model" ? options?.properties.get("service")?.type : void 0;
  if (service?.kind !== "Namespace") {
    service = findClientService(context.program, target);
  }
  if (service === void 0 || service.kind !== "Namespace" || !judgeService(context.program, service)) {
    reportDiagnostic(context.program, {
      code: "client-service",
      format: { name },
      target: context.decoratorTarget
    });
    return;
  }
  const client = {
    kind: "SdkClient",
    name,
    service,
    type: target,
    crossLanguageDefinitionId: `${getNamespaceFullName3(service)}.${name}`,
    subOperationGroups: []
  };
  setScopedDecoratorData(context, $client, clientKey, target, client, scope);
};
function judgeService(program, type) {
  return isService2(program, type) || type.decorators.some((d) => d.definition?.name === "@service" && d.definition?.namespace.name === "TypeSpec");
}
function findClientService(program, client) {
  let current = client;
  while (current) {
    if (judgeService(program, current)) {
      return current;
    }
    current = current.namespace;
  }
  return void 0;
}
function getClient(context, type) {
  for (const client of listClients(context)) {
    if (client.type === type) {
      return client;
    }
  }
  return void 0;
}
function listClients(context) {
  return context.getClients();
}
var $operationGroup = (context, target, scope) => {
  if (context.decoratorTarget.kind === SyntaxKind.AugmentDecoratorStatement) {
    reportDiagnostic(context.program, {
      code: "wrong-client-decorator",
      target: context.decoratorTarget
    });
    return;
  }
  setScopedDecoratorData(context, $operationGroup, operationGroupKey, target, {
    kind: "SdkOperationGroup",
    type: target
  }, scope);
};
function isOperationGroup(context, type) {
  if (hasExplicitClientOrOperationGroup(context)) {
    return getScopedDecoratorData(context, operationGroupKey, type) !== void 0;
  }
  if (type.kind === "Interface" && !isTemplateDeclaration2(type)) {
    return true;
  }
  if (type.kind === "Namespace" && !type.decorators.some((t) => t.decorator.name === "$service")) {
    return true;
  }
  return false;
}
function getOperationGroup(context, type) {
  const operationGroup = context.getClientOrOperationGroup(type);
  return operationGroup?.kind === "SdkOperationGroup" ? operationGroup : void 0;
}
function listOperationGroups(context, group, ignoreHierarchy = false) {
  if (!ignoreHierarchy)
    return group.subOperationGroups;
  const groups = [...group.subOperationGroups];
  let current = 0;
  while (current < groups.length) {
    const operationGroup = groups[current];
    if (operationGroup.subOperationGroups) {
      groups.push(...operationGroup.subOperationGroups);
    }
    current++;
  }
  return groups;
}
function listOperationsInOperationGroup(context, group, ignoreHierarchy = false) {
  if (!ignoreHierarchy)
    return context.getOperationsForClient(group);
  const groups = [...group.subOperationGroups];
  const operations = [...context.getOperationsForClient(group)];
  while (groups.length > 0) {
    const operationGroup = groups.shift();
    if (operationGroup.subOperationGroups) {
      groups.push(...operationGroup.subOperationGroups);
    }
    operations.push(...context.getOperationsForClient(operationGroup));
  }
  return operations;
}
var protocolAPIKey = createStateSymbol("protocolAPI");
var $protocolAPI = (context, entity, value, scope) => {
  setScopedDecoratorData(context, $protocolAPI, protocolAPIKey, entity, value, scope);
};
var convenientAPIKey = createStateSymbol("convenientAPI");
var $convenientAPI = (context, entity, value, scope) => {
  setScopedDecoratorData(context, $convenientAPI, convenientAPIKey, entity, value, scope);
};
function shouldGenerateProtocol(context, entity) {
  const value = getScopedDecoratorData(context, protocolAPIKey, entity);
  return value ?? Boolean(context.generateProtocolMethods);
}
function shouldGenerateConvenient(context, entity) {
  const value = getScopedDecoratorData(context, convenientAPIKey, entity);
  return value ?? Boolean(context.generateConvenienceMethods);
}
var usageKey = createStateSymbol("usage");
var $usage = (context, entity, value, scope) => {
  const isValidValue = (value2) => {
    return value2 === UsageFlags.Input || value2 === UsageFlags.Output || value2 === UsageFlags.Json || value2 === UsageFlags.Xml;
  };
  let newUsage = 0;
  if (value.kind === "EnumMember") {
    if (typeof value.value === "number" && isValidValue(value.value)) {
      newUsage = value.value;
    } else {
      reportDiagnostic(context.program, {
        code: "invalid-usage",
        format: {},
        target: entity
      });
      return;
    }
  } else {
    for (const variant of value.variants.values()) {
      if (variant.type.kind === "EnumMember" && typeof variant.type.value === "number") {
        if (isValidValue(variant.type.value)) {
          newUsage |= variant.type.value;
        }
      } else {
        reportDiagnostic(context.program, {
          code: "invalid-usage",
          format: {},
          target: entity
        });
        return;
      }
    }
    if (newUsage === 0) {
      reportDiagnostic(context.program, {
        code: "invalid-usage",
        format: {},
        target: entity
      });
      return;
    }
  }
  const existingUsage = getScopedDecoratorData(context, usageKey, entity) || 0;
  const combinedUsage = existingUsage | newUsage;
  setScopedDecoratorData(context, $usage, usageKey, entity, combinedUsage, scope);
};
function getUsageOverride(context, entity) {
  const usageFlags = getScopedDecoratorData(context, usageKey, entity);
  if (usageFlags || entity.namespace === void 0)
    return usageFlags;
  return getScopedDecoratorData(context, usageKey, entity.namespace);
}
function getUsage(context, entity) {
  switch (entity.kind) {
    case "Union":
      const type = getSdkUnion(context, entity);
      if (type.kind === "enum" || type.kind === "union" || type.kind === "nullable") {
        return type.usage;
      }
      return UsageFlags.None;
    case "Model":
      return getSdkModel(context, entity).usage;
    case "Enum":
      return getSdkEnum(context, entity).usage;
  }
}
var accessKey = createStateSymbol("access");
var $access = (context, entity, value, scope) => {
  if (typeof value.value !== "string" || value.value !== "public" && value.value !== "internal") {
    reportDiagnostic(context.program, {
      code: "invalid-access",
      format: {},
      target: entity
    });
    return;
  }
  setScopedDecoratorData(context, $access, accessKey, entity, value.value, scope);
};
function getAccessOverride(context, entity) {
  const accessOverride = getScopedDecoratorData(context, accessKey, entity);
  if (!accessOverride && entity.kind !== "ModelProperty" && entity.namespace) {
    return getAccessOverride(context, entity.namespace);
  }
  return accessOverride;
}
function getAccess(context, entity) {
  const override = getAccessOverride(context, entity);
  if (override || entity.kind === "Operation" || entity.kind === "ModelProperty") {
    return override || "public";
  }
  switch (entity.kind) {
    case "Model":
      return getSdkModel(context, entity).access;
    case "Enum":
      return getSdkEnum(context, entity).access;
    case "Union": {
      const type = getSdkUnion(context, entity);
      if (type.kind === "enum" || type.kind === "union" || type.kind === "nullable") {
        return type.access;
      }
      return "public";
    }
  }
}
var flattenPropertyKey = createStateSymbol("flattenProperty");
var $flattenProperty = (context, target, scope) => {
  if (getDiscriminator2(context.program, target.type)) {
    reportDiagnostic(context.program, {
      code: "flatten-polymorphism",
      format: {},
      target
    });
    return;
  }
  setScopedDecoratorData(context, $flattenProperty, flattenPropertyKey, target, true, scope);
};
function shouldFlattenProperty(context, target) {
  return getScopedDecoratorData(context, flattenPropertyKey, target) ?? false;
}
var $clientName = (context, entity, value, scope) => {
  if (entity.kind === "Model" || entity.kind === "Operation") {
    const target = context.decoratorTarget;
    if (target.kind === SyntaxKind.AugmentDecoratorStatement) {
      if (ignoreDiagnostics4(context.program.checker.resolveTypeReference(target.targetType))?.node !== entity.node) {
        return;
      }
    }
    if (target.kind === SyntaxKind.DecoratorExpression) {
      if (target.parent !== entity.node) {
        return;
      }
    }
  }
  if (value.trim() === "") {
    reportDiagnostic(context.program, {
      code: "empty-client-name",
      format: {},
      target: entity
    });
    return;
  }
  setScopedDecoratorData(context, $clientName, clientNameKey, entity, value, scope);
};
function getClientNameOverride(context, entity, languageScope) {
  return getScopedDecoratorData(context, clientNameKey, entity, languageScope);
}
function collectParams(properties, params = []) {
  properties.forEach((value, key) => {
    if (params.filter((x) => compareModelProperties(void 0, x, value)).length === 0) {
      if (value.type.kind === "Model") {
        collectParams(value.type.properties, params);
      } else {
        params.push(findRootSourceProperty(value));
      }
    }
  });
  return params;
}
var $override = (context, original, override, scope) => {
  context.program.stateMap(omitOperation).set(override, true);
  const originalParams = collectParams(original.parameters.properties).sort((a, b) => a.name.localeCompare(b.name));
  const overrideParams = collectParams(override.parameters.properties).sort((a, b) => a.name.localeCompare(b.name));
  let parametersMatch = true;
  let index = 0;
  for (const originalParam of originalParams) {
    if (index > overrideParams.length - 1) {
      if (!originalParam.optional) {
        parametersMatch = false;
        break;
      } else {
        continue;
      }
    }
    if (!compareModelProperties(void 0, originalParam, overrideParams[index])) {
      if (!originalParam.optional) {
        parametersMatch = false;
        break;
      } else {
        continue;
      }
    }
    const overrideParam = overrideParams[index];
    overrideParam.decorators.filter((d) => d.decorator.name === "$alternateType").map((d) => context.call($alternateType, originalParam, d.args[0].value, d.args[1]?.jsValue));
    index++;
  }
  if (!parametersMatch) {
    reportDiagnostic(context.program, {
      code: "override-parameters-mismatch",
      target: context.decoratorTarget,
      format: {
        methodName: original.name,
        originalParameters: originalParams.map((x) => x.name).join(`", "`),
        overrideParameters: overrideParams.map((x) => x.name).join(`", "`)
      }
    });
  }
  setScopedDecoratorData(context, $override, overrideKey, original, override, scope);
};
function getOverriddenClientMethod(context, entity) {
  return getScopedDecoratorData(context, overrideKey, entity);
}
var alternateTypeKey = createStateSymbol("alternateType");
var $alternateType = (context, source, alternate, scope) => {
  if (source.kind === "Scalar" && alternate.kind !== "Scalar") {
    reportDiagnostic(context.program, {
      code: "invalid-alternate-type",
      format: {
        kindName: alternate.kind
      },
      target: alternate
    });
    return;
  }
  setScopedDecoratorData(context, $alternateType, alternateTypeKey, source, alternate, scope);
};
function getAlternateType(context, source) {
  return getScopedDecoratorData(context, alternateTypeKey, source);
}
var $useSystemTextJsonConverter = (context, entity, scope) => {
};
var clientInitializationKey = createStateSymbol("clientInitialization");
var $clientInitialization = (context, target, options, scope) => {
  if (options.kind === "Model") {
    if (options.properties.get("initializedBy")) {
      const value = options.properties.get("initializedBy").type;
      const isValidValue = (value2) => value2 === 1 || value2 === 2;
      if (value.kind === "EnumMember") {
        if (typeof value.value !== "number" || !isValidValue(value.value)) {
          reportDiagnostic(context.program, {
            code: "invalid-initialized-by",
            format: { message: "Please use `InitializedBy` enum to set the value." },
            target
          });
          return;
        }
      } else if (value.kind === "Union") {
        for (const variant of value.variants.values()) {
          if (variant.type.kind !== "EnumMember" || typeof variant.type.value !== "number" || !isValidValue(variant.type.value)) {
            reportDiagnostic(context.program, {
              code: "invalid-initialized-by",
              format: { message: "Please use `InitializedBy` enum to set the value." },
              target
            });
            return;
          }
        }
      }
    }
    setScopedDecoratorData(context, $clientInitialization, clientInitializationKey, target, options, scope);
  }
};
function getClientInitializationOptions(context, entity) {
  const options = getScopedDecoratorData(context, clientInitializationKey, entity);
  if (options && options.properties.get("initializedBy") === void 0 && options.properties.get("parameters") === void 0) {
    return {
      parameters: options
    };
  }
  let initializedBy = void 0;
  if (options?.properties.get("initializedBy")) {
    if (options.properties.get("initializedBy").type.kind === "EnumMember") {
      initializedBy = options.properties.get("initializedBy").type.value;
    } else if (options.properties.get("initializedBy").type.kind === "Union") {
      initializedBy = 0;
      for (const variant of options.properties.get("initializedBy").type.variants.values()) {
        initializedBy |= variant.type.value;
      }
    }
  }
  let parametersModel = options?.properties.get("parameters")?.type;
  const movedParameters = findEntriesWithTarget(context, clientLocationKey, entity, "ModelProperty");
  const tk = $3(context.program);
  if (movedParameters.length > 0) {
    if (parametersModel) {
      for (const movedParameter of movedParameters) {
        parametersModel.properties.set(movedParameter.name, movedParameter);
      }
    } else {
      parametersModel = tk.model.create({
        name: "ClientInitializationParameters",
        properties: {
          ...Object.fromEntries(movedParameters.map((movedParameter) => [movedParameter.name, movedParameter]))
        }
      });
    }
  }
  return {
    parameters: parametersModel,
    initializedBy
  };
}
var paramAliasKey = createStateSymbol("paramAlias");
var $paramAlias = (context, original, paramAlias, scope) => {
  const paramAliasDec = context.program.stateMap(paramAliasKey).get(original);
  const paramAliasVal = paramAliasDec?.[scope || AllScopes] ?? paramAliasDec?.[AllScopes];
  if (paramAliasVal) {
    reportDiagnostic(context.program, {
      code: "multiple-param-alias",
      format: {
        originalName: original.name,
        firstParamAlias: paramAliasVal
      },
      target: context.decoratorTarget
    });
    return;
  }
  setScopedDecoratorData(context, $paramAlias, paramAliasKey, original, paramAlias, scope);
};
function getParamAlias(context, original) {
  return getScopedDecoratorData(context, paramAliasKey, original);
}
var apiVersionKey = createStateSymbol("apiVersion");
var $apiVersion = (context, target, value, scope) => {
  setScopedDecoratorData(context, $apiVersion, apiVersionKey, target, value ?? true, scope);
};
function getIsApiVersion(context, param) {
  return getScopedDecoratorData(context, apiVersionKey, param);
}
var $clientNamespace = (context, entity, value, scope) => {
  if (value.trim() === "") {
    reportDiagnostic(context.program, {
      code: "empty-client-namespace",
      format: {},
      target: entity
    });
    return;
  }
  setScopedDecoratorData(context, $clientNamespace, clientNamespaceKey, entity, value, scope);
};
function findNamespaceOverlapClosestToRoot(override, userDefinedNamespaces) {
  for (const namespace2 of userDefinedNamespaces) {
    if (override.includes(namespace2.name)) {
      return namespace2;
    }
  }
  return void 0;
}
function getClientNamespace(context, entity) {
  const override = getScopedDecoratorData(context, clientNamespaceKey, entity);
  if (override) {
    const userDefinedNamespace = findNamespaceOverlapClosestToRoot(override, listAllUserDefinedNamespaces(context));
    if (userDefinedNamespace && context.namespaceFlag) {
      return override.replace(userDefinedNamespace.name, context.namespaceFlag);
    }
    return override;
  }
  if (!entity.namespace) {
    return "";
  }
  if (entity.kind === "Namespace") {
    return getNamespaceFullNameWithOverride(context, entity);
  }
  return getNamespaceFullNameWithOverride(context, entity.namespace);
}
function getNamespaceFullNameWithOverride(context, namespace2) {
  const segments = [];
  let current = namespace2;
  let isOverridden = false;
  while (current && current.name !== "") {
    const override = getScopedDecoratorData(context, clientNamespaceKey, current);
    if (override) {
      segments.unshift(override);
      isOverridden = true;
      break;
    }
    segments.unshift(current.name);
    current = current.namespace;
  }
  const joinedSegments = segments.join(".");
  if (isOverridden) {
    const userDefinedNamespace = findNamespaceOverlapClosestToRoot(joinedSegments, listAllUserDefinedNamespaces(context));
    if (userDefinedNamespace && context.namespaceFlag) {
      return joinedSegments.replace(userDefinedNamespace.name, context.namespaceFlag);
    }
    return joinedSegments;
  }
  if (context.namespaceFlag)
    return context.namespaceFlag;
  return joinedSegments;
}
var $scope = (context, entity, scope) => {
  const [negationScopes, scopes] = parseScopes(context, scope);
  if (negationScopes !== void 0 && negationScopes.length > 0) {
    setScopedDecoratorData(context, $scope, negationScopesKey, entity, negationScopes);
  }
  if (scopes !== void 0 && scopes.length > 0) {
    const targetEntry = context.program.stateMap(scopeKey).get(entity);
    setScopedDecoratorData(context, $scope, scopeKey, entity, !targetEntry ? scopes : [...Object.values(targetEntry), ...scopes]);
  }
};
var clientApiVersionsKey = createStateSymbol("clientApiVersions");
var $clientApiVersions = (context, target, value, scope) => {
  setScopedDecoratorData(context, $clientApiVersions, clientApiVersionsKey, target, value, scope);
};
function getExplicitClientApiVersions(context, target) {
  return getScopedDecoratorData(context, clientApiVersionsKey, target);
}
var $deserializeEmptyStringAsNull = (context, target, scope) => {
  if (target.type.kind !== "Scalar") {
    reportDiagnostic(context.program, {
      code: "invalid-deserializeEmptyStringAsNull-target-type",
      format: {},
      target
    });
    return;
  }
  if (target.type.name !== "string") {
    let scalarType = target.type;
    while (scalarType.baseScalar !== void 0) {
      scalarType = scalarType.baseScalar;
    }
    if (scalarType.name !== "string") {
      reportDiagnostic(context.program, {
        code: "invalid-deserializeEmptyStringAsNull-target-type",
        format: {},
        target
      });
      return;
    }
  }
};
var responseAsBoolKey = createStateSymbol("responseAsBool");
var $responseAsBool = (context, target, scope) => {
  if (!target.decorators.some((d) => d.definition?.name === "@head")) {
    reportDiagnostic(context.program, {
      code: "non-head-bool-response-decorator",
      format: {
        operationName: target.name
      },
      target
    });
    return;
  }
  setScopedDecoratorData(context, $responseAsBool, responseAsBoolKey, target, true, scope);
};
function getResponseAsBool(context, target) {
  return getScopedDecoratorData(context, responseAsBoolKey, target);
}
var clientDocKey = createStateSymbol("clientDoc");
var $clientDoc = (context, target, documentation, mode, scope) => {
  const docMode = mode.value;
  if (docMode !== "append" && docMode !== "replace") {
    reportDiagnostic(context.program, {
      code: "invalid-client-doc-mode",
      format: { mode: docMode },
      target: context.decoratorTarget
    });
    return;
  }
  const docData = {
    documentation,
    mode: docMode
  };
  setScopedDecoratorData(context, $clientDoc, clientDocKey, target, docData, scope);
};
function getClientDocExplicit(context, target) {
  return getScopedDecoratorData(context, clientDocKey, target);
}
var $clientLocation = (context, source, target, scope) => {
  if (source.kind === "Operation") {
    if (typeof target !== "string" && target.kind === "Operation") {
      reportDiagnostic(context.program, {
        code: "client-location-conflict",
        format: { operationName: source.name },
        target: context.decoratorTarget,
        messageId: "operationToOperation"
      });
      return;
    }
  } else if (source.kind === "ModelProperty") {
    if (typeof target !== "string" && (target.kind === "Interface" || target.kind === "Namespace")) {
      const clientInitializationParams = target.decorators.filter((d) => d.decorator.name === "$clientInitialization").map((d) => d.args[0].value).filter((a) => a.entityKind === "Type" && a.kind === "Model").filter((model) => model.properties.has(source.name)).map((model) => model.properties.get(source.name));
      if (clientInitializationParams.length > 0) {
        reportDiagnostic(context.program, {
          code: "client-location-conflict",
          format: { parameterName: source.name },
          target: context.decoratorTarget,
          messageId: "modelPropertyToClientInitialization"
        });
        return;
      }
    }
    if (typeof target === "string") {
      reportDiagnostic(context.program, {
        code: "client-location-conflict",
        format: { parameterName: source.name },
        target: context.decoratorTarget,
        messageId: "modelPropertyToString"
      });
      return;
    }
  }
  setScopedDecoratorData(context, $clientLocation, clientLocationKey, source, target, scope);
};
function getClientLocation(context, input) {
  if (input.kind === "Operation" && hasExplicitClientOrOperationGroup(context)) {
    return void 0;
  }
  return getScopedDecoratorData(context, clientLocationKey, input);
}
var legacyHierarchyBuildingKey = createStateSymbol("legacyHierarchyBuilding");
function isPropertySuperset(target, value) {
  for (const name of value.properties.keys()) {
    if (!target.properties.has(name)) {
      return false;
    }
    const targetProperty = target.properties.get(name);
    const valueProperty = value.properties.get(name);
    if (targetProperty.sourceProperty !== valueProperty.sourceProperty) {
      return false;
    }
  }
  return true;
}
var $legacyHierarchyBuilding = (context, target, value, scope) => {
  if (!isPropertySuperset(target, value)) {
    reportDiagnostic(context.program, {
      code: "legacy-hierarchy-building-conflict",
      format: {
        childModel: target.name,
        parentModel: value.name
      },
      target: context.decoratorTarget
    });
    return;
  }
  setScopedDecoratorData(context, $legacyHierarchyBuilding, legacyHierarchyBuildingKey, target, value, scope);
};
function getLegacyHierarchyBuilding(context, target) {
  if (!context.enableLegacyHierarchyBuilding)
    return void 0;
  return getScopedDecoratorData(context, legacyHierarchyBuildingKey, target);
}
function isInScope(context, entity) {
  const scopes = getScopedDecoratorData(context, scopeKey, entity);
  const negationScopes = getScopedDecoratorData(context, negationScopesKey, entity);
  if (scopes !== void 0) {
    if (scopes.includes(context.emitterName)) {
      return true;
    }
    if (negationScopes === void 0) {
      return false;
    }
  }
  if (negationScopes !== void 0 && negationScopes.includes(context.emitterName)) {
    return false;
  }
  return true;
}

// src/typespec/packages/typespec-client-generator-core/dist/src/cache.js
function prepareClientAndOperationCache(context) {
  context.__rawClientsOperationGroupsCache = /* @__PURE__ */ new Map();
  context.__operationToClientCache = /* @__PURE__ */ new Map();
  context.__clientToOperationsCache = /* @__PURE__ */ new Map();
  const clients = getOrCreateClients(context);
  for (const client of clients) {
    const groups = [];
    if (client.type.kind === "Namespace") {
      for (const subItem of client.type.namespaces.values()) {
        const og = createOperationGroup(context, subItem, `${client.name}`, client);
        if (og) {
          groups.push(og);
        }
      }
      for (const subItem of client.type.interfaces.values()) {
        if (isTemplateDeclaration3(subItem)) {
          continue;
        }
        const og = createOperationGroup(context, subItem, `${client.name}`, client);
        if (og) {
          groups.push(og);
        }
      }
    }
    context.__rawClientsOperationGroupsCache.set(client.type, client);
    client.subOperationGroups = groups;
    context.__clientToOperationsCache.set(client, []);
  }
  if (!hasExplicitClientOrOperationGroup(context)) {
    const newOperationGroupNames = /* @__PURE__ */ new Set();
    [...listScopedDecoratorData(context, clientLocationKey).values()].map((target) => {
      if (typeof target === "string") {
        if (clients[0].subOperationGroups.some((og) => og.type && getLibraryName(context, og.type) === target)) {
          return;
        }
        newOperationGroupNames.add(target);
      }
    });
    for (const ogName of newOperationGroupNames) {
      const og = {
        kind: "SdkOperationGroup",
        groupPath: `${clients[0].name}.${ogName}`,
        service: clients[0].service,
        subOperationGroups: [],
        parent: clients[0]
      };
      context.__rawClientsOperationGroupsCache.set(ogName, og);
      clients[0].subOperationGroups.push(og);
      context.__clientToOperationsCache.set(og, []);
    }
  }
  const queue = [...clients];
  while (queue.length > 0) {
    const group = queue.shift();
    if (group.type) {
      const operations = [...group.type.operations.values()];
      if (group.type.kind === "Namespace" && hasExplicitClientOrOperationGroup(context)) {
        const innerQueue = [group.type];
        while (innerQueue.length > 0) {
          const ns = innerQueue.shift();
          for (const subNs of ns.namespaces.values()) {
            if (!context.__rawClientsOperationGroupsCache.has(subNs)) {
              operations.push(...subNs.operations.values());
              innerQueue.push(subNs);
            }
          }
          for (const iface of ns.interfaces.values()) {
            if (!context.__rawClientsOperationGroupsCache.has(iface)) {
              operations.push(...iface.operations.values());
            }
          }
        }
      }
      for (const op of operations) {
        if (!isInScope(context, op)) {
          continue;
        }
        if (!isTemplateDeclarationOrInstance(op) && !context.program.stateMap(omitOperation).get(op)) {
          let pushGroup = group;
          const clientLocation = getClientLocation(context, op);
          if (clientLocation) {
            if (context.__rawClientsOperationGroupsCache.has(clientLocation)) {
              pushGroup = context.__rawClientsOperationGroupsCache.get(clientLocation);
            } else {
              if (typeof clientLocation !== "string") {
                reportDiagnostic(context.program, {
                  code: "client-location-wrong-type",
                  target: op
                });
              } else {
                reportDiagnostic(context.program, {
                  code: "client-location-duplicate",
                  target: clients[0].type
                });
              }
            }
          }
          context.__clientToOperationsCache.get(pushGroup).push(op);
          context.__operationToClientCache.set(op, pushGroup);
        }
      }
    }
    queue.push(...group.subOperationGroups);
  }
  if (!hasExplicitClientOrOperationGroup(context)) {
    const removeEmptyGroups = (group) => {
      group.subOperationGroups = group.subOperationGroups.filter((subGroup) => {
        const keep = removeEmptyGroups(subGroup);
        if (!keep) {
          context.__rawClientsOperationGroupsCache.delete(subGroup.type);
        }
        return keep;
      });
      const hasOperations = context.__clientToOperationsCache.get(group).length > 0;
      const hasSubGroups = group.subOperationGroups?.length > 0;
      return hasOperations || hasSubGroups;
    };
    for (const client of clients) {
      const keepClient = removeEmptyGroups(client);
      if (!keepClient) {
        context.__rawClientsOperationGroupsCache.delete(client.type);
        context.__clientToOperationsCache.delete(client);
      }
    }
  }
}
function getOrCreateClients(context) {
  const namespaces = listAllUserDefinedNamespaces(context);
  const explicitClients = [];
  for (const ns of namespaces) {
    if (getScopedDecoratorData(context, clientKey, ns)) {
      explicitClients.push(getScopedDecoratorData(context, clientKey, ns));
    }
    for (const i of ns.interfaces.values()) {
      if (getScopedDecoratorData(context, clientKey, i)) {
        explicitClients.push(getScopedDecoratorData(context, clientKey, i));
      }
    }
  }
  if (explicitClients.length > 0) {
    if (explicitClients.some((client) => isArm(client.service))) {
      context.arm = true;
    }
    return explicitClients;
  }
  const serviceNamespaces = namespaces.filter((ns) => isService3(context.program, ns));
  if (serviceNamespaces.length >= 1) {
    const service = serviceNamespaces.shift();
    serviceNamespaces.map((ns) => {
      reportDiagnostic(context.program, {
        code: "multiple-services",
        target: ns
      });
    });
    let originalName = service.name;
    const clientNameOverride = getClientNameOverride(context, service);
    if (clientNameOverride) {
      originalName = clientNameOverride;
    } else {
      originalName = service.name;
    }
    const clientName = originalName.endsWith("Client") ? originalName : `${originalName}Client`;
    context.arm = isArm(service);
    return [
      {
        kind: "SdkClient",
        name: clientName,
        service,
        type: service,
        crossLanguageDefinitionId: getNamespaceFullName4(service),
        subOperationGroups: []
      }
    ];
  }
  return [];
}
function createOperationGroup(context, type, groupPathPrefix, parent) {
  let operationGroup;
  const service = findOperationGroupService(context.program, type, context.emitterName) ?? type;
  if (!isService3(context.program, service)) {
    reportDiagnostic(context.program, {
      code: "client-service",
      format: { name: type.name },
      target: type
    });
  }
  if (hasExplicitClientOrOperationGroup(context)) {
    operationGroup = getScopedDecoratorData(context, operationGroupKey, type);
    if (operationGroup) {
      operationGroup.groupPath = `${groupPathPrefix}.${getLibraryName(context, type)}`;
      operationGroup.service = service;
      operationGroup.subOperationGroups = [];
      operationGroup.parent = parent;
      if (type.kind === "Namespace") {
        operationGroup.subOperationGroups = buildHierarchyOfOperationGroups(context, type, operationGroup.groupPath, operationGroup) ?? [];
      }
    }
  } else {
    if (type.kind !== "Interface" || !isTemplateDeclaration3(type)) {
      operationGroup = {
        kind: "SdkOperationGroup",
        type,
        groupPath: `${groupPathPrefix}.${getLibraryName(context, type)}`,
        service,
        subOperationGroups: [],
        parent
      };
    }
    if (operationGroup && type.kind === "Namespace") {
      operationGroup.subOperationGroups = buildHierarchyOfOperationGroups(context, type, operationGroup.groupPath, operationGroup) ?? [];
    }
  }
  if (operationGroup) {
    context.__rawClientsOperationGroupsCache.set(operationGroup.type, operationGroup);
    context.__clientToOperationsCache.set(operationGroup, []);
  }
  return operationGroup;
}
function findOperationGroupService(program, client, scope) {
  let current = client;
  while (current) {
    if (isService3(program, current)) {
      return current;
    }
    const client2 = program.stateMap(clientKey).get(current);
    if (client2 && (client2[scope] || client2[AllScopes])) {
      return (client2[scope] ?? client2[AllScopes]).service;
    }
    current = current.namespace;
  }
  return void 0;
}
function buildHierarchyOfOperationGroups(context, type, groupPathPrefix, parent) {
  const subOperationGroups = [];
  type.namespaces.forEach((ns) => {
    const subOperationGroup = createOperationGroup(context, ns, groupPathPrefix, parent);
    if (subOperationGroup) {
      subOperationGroups.push(subOperationGroup);
    }
  });
  type.interfaces.forEach((i) => {
    const subOperationGroup = createOperationGroup(context, i, groupPathPrefix, parent);
    if (subOperationGroup) {
      subOperationGroups.push(subOperationGroup);
    }
  });
  if (subOperationGroups.length > 0) {
    return subOperationGroups;
  }
  return void 0;
}
function isArm(service) {
  return service.decorators.some((decorator) => decorator.decorator.name === "$armProviderNamespace");
}

// src/typespec/packages/typespec-client-generator-core/dist/src/configs.js
var defaultDecoratorsAllowList = [
  "TypeSpec\\.Xml\\..*",
  "Azure\\.Core\\.@useFinalStateVia",
  "Autorest\\.@example"
];

// src/typespec/packages/typespec-client-generator-core/dist/src/example.js
import { NoTarget, createDiagnosticCollector as createDiagnosticCollector5, getAnyExtensionFromPath, getRelativePathFromDirectory, joinPaths, normalizePath, resolvePath } from "@typespec/compiler";
async function checkExamplesDirExists(host, dir) {
  try {
    return (await host.stat(dir)).isDirectory();
  } catch (err) {
    return false;
  }
}
async function loadExamples(context, apiVersion) {
  const diagnostics = createDiagnosticCollector5();
  const examplesBaseDir = context.examplesDir ?? resolvePath(context.program.projectRoot, "examples");
  const exampleDir = apiVersion ? resolvePath(examplesBaseDir, apiVersion) : resolvePath(examplesBaseDir);
  if (!await checkExamplesDirExists(context.program.host, exampleDir)) {
    if (context.examplesDir) {
      diagnostics.add(createDiagnostic({
        code: "example-loading",
        messageId: "noDirectory",
        format: { directory: exampleDir },
        target: NoTarget
      }));
    }
    return diagnostics.wrap(/* @__PURE__ */ new Map());
  }
  const map2 = /* @__PURE__ */ new Map();
  const exampleFiles = await searchExampleJsonFiles(context.program, exampleDir);
  for (const fileName of exampleFiles) {
    try {
      const exampleFile = await context.program.host.readFile(resolvePath(exampleDir, fileName));
      const example = JSON.parse(exampleFile.text);
      if (!example.operationId || !example.title) {
        diagnostics.add(createDiagnostic({
          code: "example-loading",
          messageId: "noOperationId",
          format: { filename: fileName },
          target: NoTarget
        }));
        continue;
      }
      if (!map2.has(example.operationId.toLowerCase())) {
        map2.set(example.operationId.toLowerCase(), {});
      }
      const examples = map2.get(example.operationId.toLowerCase());
      if (example.title in examples) {
        diagnostics.add(createDiagnostic({
          code: "duplicate-example-file",
          target: NoTarget,
          format: {
            filename: fileName,
            operationId: example.operationId,
            title: example.title
          }
        }));
      }
      examples[example.title] = {
        relativePath: apiVersion ? resolvePath(apiVersion, fileName) : fileName,
        data: example
      };
    } catch (err) {
      diagnostics.add(createDiagnostic({
        code: "example-loading",
        messageId: "default",
        format: { filename: fileName, error: err?.toString() ?? "" },
        target: NoTarget
      }));
    }
  }
  return diagnostics.wrap(map2);
}
async function searchExampleJsonFiles(program, exampleDir) {
  const host = program.host;
  const exampleFiles = [];
  async function recursiveSearch(dir) {
    const fileItems = await host.readDir(dir);
    for (const item of fileItems) {
      const fullPath = joinPaths(dir, item);
      const relativePath = getRelativePathFromDirectory(exampleDir, fullPath, false);
      if ((await host.stat(fullPath)).isDirectory()) {
        await recursiveSearch(fullPath);
      } else if ((await host.stat(fullPath)).isFile() && getAnyExtensionFromPath(item) === ".json") {
        exampleFiles.push(normalizePath(relativePath));
      }
    }
  }
  await recursiveSearch(exampleDir);
  return exampleFiles;
}
async function handleClientExamples(context, client) {
  const diagnostics = createDiagnosticCollector5();
  const packageVersions = context.getPackageVersions();
  const examples = diagnostics.pipe(await loadExamples(context, packageVersions[packageVersions.length - 1]));
  const clientQueue = [client];
  while (clientQueue.length > 0) {
    const client2 = clientQueue.pop();
    if (client2.children) {
      clientQueue.push(...client2.children);
    }
    for (const method of client2.methods) {
      let operation = method.__raw;
      while (operation && operation.templateMapper === void 0) {
        let operationId = resolveOperationId(context, operation, true).toLowerCase();
        if (examples.has(operationId)) {
          diagnostics.pipe(handleMethodExamples(context, method, examples.get(operationId)));
          break;
        }
        operationId = resolveOperationId(context, operation, false).toLowerCase();
        if (examples.has(operationId)) {
          diagnostics.pipe(handleMethodExamples(context, method, examples.get(operationId)));
          break;
        }
        operation = operation.sourceOperation;
      }
    }
  }
  return diagnostics.wrap(void 0);
}
function handleMethodExamples(context, method, examples) {
  const diagnostics = createDiagnosticCollector5();
  if (method.operation.kind === "http") {
    diagnostics.pipe(handleHttpOperationExamples(method.operation, examples));
    if (method.operation.examples) {
      context.__httpOperationExamples.set(method.operation.__raw, method.operation.examples);
    }
  }
  return diagnostics.wrap(void 0);
}
function handleHttpOperationExamples(operation, examples) {
  const diagnostics = createDiagnosticCollector5();
  operation.examples = [];
  for (const [title, example] of Object.entries(examples)) {
    const operationExample = {
      kind: "http",
      name: title,
      doc: title,
      filePath: example.relativePath,
      parameters: diagnostics.pipe(handleHttpParameters(operation.bodyParam ? [...operation.parameters, operation.bodyParam] : operation.parameters, example.data, example.relativePath)),
      responses: diagnostics.pipe(handleHttpResponses(operation.responses, example.data, example.relativePath)),
      rawExample: example.data
    };
    operation.examples.push(operationExample);
  }
  operation.examples.sort((a, b) => a.filePath > b.filePath ? 1 : -1);
  return diagnostics.wrap(void 0);
}
function handleHttpParameters(parameters, example, relativePath) {
  const diagnostics = createDiagnosticCollector5();
  const parameterExamples = [];
  if ("parameters" in example && typeof example.parameters === "object" && example.parameters !== null) {
    for (const name of Object.keys(example.parameters)) {
      let parameter = parameters.find((p) => p.serializedName === name);
      if (!parameter) {
        parameter = parameters.find((p) => p.name === name && p.kind === "body");
      }
      if (!parameter && name === "body") {
        parameter = parameters.find((p) => p.kind === "body");
      }
      if (parameter) {
        const value = diagnostics.pipe(getSdkTypeExample(parameter.type, example.parameters[name], relativePath));
        if (value) {
          parameterExamples.push({
            parameter,
            value
          });
        }
      } else {
        addExampleValueNoMappingDignostic(diagnostics, { [name]: example.parameters[name] }, relativePath);
      }
    }
  }
  return diagnostics.wrap(parameterExamples);
}
function handleHttpResponses(responses, example, relativePath) {
  const diagnostics = createDiagnosticCollector5();
  const responseExamples = [];
  if ("responses" in example && typeof example.responses === "object" && example.responses !== null) {
    for (const code of Object.keys(example.responses)) {
      const statusCode = parseInt(code, 10);
      let found = false;
      for (const response of responses) {
        const responseCode = response.statusCodes;
        if (responseCode === statusCode) {
          responseExamples.push(diagnostics.pipe(handleHttpResponse(response, statusCode, example.responses[code], relativePath)));
          found = true;
          break;
        } else if (typeof responseCode === "object" && responseCode !== null && responseCode.start <= statusCode && responseCode.end >= statusCode) {
          responseExamples.push(diagnostics.pipe(handleHttpResponse(response, statusCode, example.responses[code], relativePath)));
          found = true;
          break;
        }
      }
      if (!found) {
        addExampleValueNoMappingDignostic(diagnostics, { [code]: example.responses[code] }, relativePath);
      }
    }
  }
  return diagnostics.wrap(responseExamples);
}
function handleHttpResponse(response, statusCode, example, relativePath) {
  const diagnostics = createDiagnosticCollector5();
  const responseExample = {
    response,
    statusCode,
    headers: []
  };
  if (typeof example === "object" && example !== null) {
    for (const name of Object.keys(example)) {
      if (name === "description") {
        continue;
      } else if (name === "body") {
        if (response.type) {
          responseExample.bodyValue = diagnostics.pipe(getSdkTypeExample(response.type, example.body, relativePath));
        } else {
          addExampleValueNoMappingDignostic(diagnostics, { body: example.body }, relativePath);
        }
      } else if (name === "headers") {
        for (const subName of Object.keys(example.headers)) {
          const header = response.headers.find((p) => p.serializedName === subName);
          if (header) {
            const value = diagnostics.pipe(getSdkTypeExample(header.type, example[name][subName], relativePath));
            if (value) {
              responseExample.headers.push({
                header,
                value
              });
            }
          } else {
            addExampleValueNoMappingDignostic(diagnostics, { [subName]: example[name][subName] }, relativePath);
          }
        }
      } else {
        addExampleValueNoMappingDignostic(diagnostics, { [name]: example[name] }, relativePath);
      }
    }
  }
  return diagnostics.wrap(responseExample);
}
function getSdkTypeExample(type, example, relativePath) {
  const diagnostics = createDiagnosticCollector5();
  if (example === null && type.kind !== "nullable" && type.kind !== "unknown") {
    return diagnostics.wrap(void 0);
  }
  if (isSdkIntKind(type.kind) || isSdkFloatKind(type.kind)) {
    return getSdkBaseTypeExample("number", type, example, relativePath);
  } else {
    switch (type.kind) {
      case "string":
      case "bytes":
        return getSdkBaseTypeExample("string", type, example, relativePath);
      case "boolean":
        return getSdkBaseTypeExample("boolean", type, example, relativePath);
      case "url":
      case "plainDate":
      case "plainTime":
        return getSdkBaseTypeExample("string", type, example, relativePath);
      case "nullable":
        if (example === null) {
          return diagnostics.wrap({
            kind: "null",
            type,
            value: null
          });
        } else {
          return getSdkTypeExample(type.type, example, relativePath);
        }
      case "unknown":
        return diagnostics.wrap({
          kind: "unknown",
          type,
          value: example
        });
      case "constant":
        if (example === type.value) {
          return getSdkBaseTypeExample(typeof type.value, type, example, relativePath);
        } else {
          addExampleValueNoMappingDignostic(diagnostics, example, relativePath);
          return diagnostics.wrap(void 0);
        }
      case "enum":
        if (type.values.some((v) => v.value === example) || !type.isFixed) {
          return getSdkBaseTypeExample(typeof example, type, example, relativePath);
        } else {
          addExampleValueNoMappingDignostic(diagnostics, example, relativePath);
          return diagnostics.wrap(void 0);
        }
      case "enumvalue":
        if (type.value === example) {
          return getSdkBaseTypeExample(typeof example, type, example, relativePath);
        } else {
          addExampleValueNoMappingDignostic(diagnostics, example, relativePath);
          return diagnostics.wrap(void 0);
        }
      case "utcDateTime":
      case "offsetDateTime":
      case "duration":
        const inner = diagnostics.pipe(getSdkTypeExample(type.wireType, example, relativePath));
        if (inner) {
          inner.type = type;
        }
        return diagnostics.wrap(inner);
      case "union":
        return diagnostics.wrap({
          kind: "union",
          type,
          value: example
        });
      case "array":
        return getSdkArrayExample(type, example, relativePath);
      case "dict":
        return getSdkDictionaryExample(type, example, relativePath);
      case "model":
        return getSdkModelExample(type, example, relativePath);
    }
  }
  return diagnostics.wrap(void 0);
}
function tryConvertStringToNumber(value) {
  if (typeof value !== "string" || value.trim() === "") {
    return void 0;
  }
  const num = Number(value.trim());
  if (isNaN(num) || !isFinite(num)) {
    return void 0;
  }
  return num;
}
function tryConvertStringToBoolean(value) {
  if (typeof value !== "string") {
    return void 0;
  }
  const lowerValue = value.toLowerCase().trim();
  if (lowerValue === "true") {
    return true;
  } else if (lowerValue === "false") {
    return false;
  }
  return void 0;
}
function getSdkBaseTypeExample(kind, type, example, relativePath) {
  const diagnostics = createDiagnosticCollector5();
  if (typeof example === kind) {
    return diagnostics.wrap({
      kind,
      type,
      value: example
    });
  }
  if (typeof example === "string") {
    if (kind === "number") {
      const convertedNumber = tryConvertStringToNumber(example);
      if (convertedNumber !== void 0) {
        return diagnostics.wrap({
          kind,
          type,
          value: convertedNumber
        });
      }
    } else if (kind === "boolean") {
      const convertedBoolean = tryConvertStringToBoolean(example);
      if (convertedBoolean !== void 0) {
        return diagnostics.wrap({
          kind,
          type,
          value: convertedBoolean
        });
      }
    }
  }
  addExampleValueNoMappingDignostic(diagnostics, example, relativePath);
  return diagnostics.wrap(void 0);
}
function getSdkArrayExample(type, example, relativePath) {
  const diagnostics = createDiagnosticCollector5();
  if (Array.isArray(example)) {
    const arrayExample = [];
    for (const item of example) {
      const result = diagnostics.pipe(getSdkTypeExample(type.valueType, item, relativePath));
      if (result) {
        arrayExample.push(result);
      }
    }
    return diagnostics.wrap({
      kind: "array",
      type,
      value: arrayExample
    });
  } else {
    addExampleValueNoMappingDignostic(diagnostics, example, relativePath);
    return diagnostics.wrap(void 0);
  }
}
function getSdkDictionaryExample(type, example, relativePath) {
  const diagnostics = createDiagnosticCollector5();
  if (typeof example === "object") {
    const dictionaryExample = {};
    for (const key of Object.keys(example)) {
      const result = diagnostics.pipe(getSdkTypeExample(type.valueType, example[key], relativePath));
      if (result) {
        dictionaryExample[key] = result;
      }
    }
    return diagnostics.wrap({
      kind: "dict",
      type,
      value: dictionaryExample
    });
  } else {
    addExampleValueNoMappingDignostic(diagnostics, example, relativePath);
    return diagnostics.wrap(void 0);
  }
}
function getSdkModelExample(type, example, relativePath) {
  const diagnostics = createDiagnosticCollector5();
  if (typeof example === "object") {
    if (type.discriminatorProperty) {
      if (type.discriminatorProperty.name in example) {
        if (type.discriminatedSubtypes && example[type.discriminatorProperty.name] in type.discriminatedSubtypes) {
          return getSdkModelExample(type.discriminatedSubtypes[example[type.discriminatorProperty.name]], example, relativePath);
        }
      } else {
        addExampleValueNoMappingDignostic(diagnostics, example, relativePath);
        return diagnostics.wrap(void 0);
      }
    }
    let additionalPropertiesType;
    const additionalProperties = /* @__PURE__ */ new Map();
    const additionalPropertiesExample = {};
    const properties = /* @__PURE__ */ new Map();
    const propertiesExample = {};
    const modelQueue = [type];
    while (modelQueue.length > 0) {
      const model = modelQueue.pop();
      for (const property of model.properties) {
        if (property.kind === "property" && property.serializationOptions.json?.name && !properties.has(property.serializationOptions.json.name)) {
          properties.set(property.serializationOptions.json.name, property);
        }
      }
      if (model.additionalProperties && additionalPropertiesType === void 0) {
        additionalPropertiesType = model.additionalProperties;
      }
      if (model.baseModel) {
        modelQueue.push(model.baseModel);
      }
    }
    for (const name of Object.keys(example)) {
      const property = properties.get(name);
      if (property) {
        const result = diagnostics.pipe(getSdkTypeExample(property.type, example[name], relativePath));
        if (result) {
          propertiesExample[name] = result;
        }
      } else {
        additionalProperties[name] = example[name];
      }
    }
    if (Object.keys(additionalProperties).length > 0) {
      if (additionalPropertiesType) {
        for (const [name, value] of Object.entries(additionalProperties)) {
          const result = diagnostics.pipe(getSdkTypeExample(additionalPropertiesType, value, relativePath));
          if (result) {
            additionalPropertiesExample[name] = result;
          }
        }
      } else {
        addExampleValueNoMappingDignostic(diagnostics, additionalProperties, relativePath);
      }
    }
    return diagnostics.wrap({
      kind: "model",
      type,
      value: propertiesExample,
      additionalPropertiesValue: Object.keys(additionalPropertiesExample).length > 0 ? additionalPropertiesExample : void 0
    });
  } else {
    addExampleValueNoMappingDignostic(diagnostics, example, relativePath);
    return diagnostics.wrap(void 0);
  }
}
function addExampleValueNoMappingDignostic(diagnostics, value, relativePath) {
  diagnostics.add(createDiagnostic({
    code: "example-value-no-mapping",
    target: NoTarget,
    format: {
      value: JSON.stringify(value),
      relativePath
    }
  }));
}

// src/typespec/packages/typespec-client-generator-core/dist/src/package.js
import { createDiagnosticCollector as createDiagnosticCollector8, ignoreDiagnostics as ignoreDiagnostics6 } from "@typespec/compiler";

// src/typespec/packages/typespec-client-generator-core/dist/src/clients.js
import { createDiagnosticCollector as createDiagnosticCollector7, getDoc as getDoc2, getSummary as getSummary4 } from "@typespec/compiler";
import { $ as $5 } from "@typespec/compiler/typekit";
import { getServers as getServers2 } from "@typespec/http";

// src/typespec/packages/typespec-client-generator-core/dist/src/methods.js
import { getLroMetadata as getLroMetadata2, getPagedResult, getParameterizedNextLinkArguments } from "@azure-tools/typespec-azure-core";
import { createDiagnosticCollector as createDiagnosticCollector6, getSummary as getSummary3, ignoreDiagnostics as ignoreDiagnostics5, isList } from "@typespec/compiler";
import { $ as $4 } from "@typespec/compiler/typekit";
import { isHeader as isHeader3 } from "@typespec/http";
function getSdkServiceOperation(context, operation, methodParameters) {
  const diagnostics = createDiagnosticCollector6();
  const httpOperation = getHttpOperationWithCache(context, operation);
  if (httpOperation) {
    const sdkHttpOperation = diagnostics.pipe(getSdkHttpOperation(context, httpOperation, methodParameters));
    return diagnostics.wrap(sdkHttpOperation);
  }
  diagnostics.add(createDiagnostic({
    code: "unsupported-protocol",
    target: operation,
    format: {}
  }));
  return diagnostics.wrap(void 0);
}
function getSdkLroPagingServiceMethod(context, operation, client) {
  const diagnostics = createDiagnosticCollector6();
  return diagnostics.wrap({
    ...diagnostics.pipe(getSdkLroServiceMethod(context, operation, client)),
    ...diagnostics.pipe(getSdkPagingServiceMethod(context, operation, client)),
    kind: "lropaging"
  });
}
function getPageSizeParameterSegments(baseServiceMethod) {
  function recurseToFindPageSizeParameterInModel(param, model) {
    for (const prop of model.properties) {
      if (prop.__raw && prop.__raw.decorators.find((d) => d.definition?.name === "@pageSize")) {
        return [param, prop];
      }
      if (prop.type.kind === "model") {
        const nested = recurseToFindPageSizeParameterInModel(param, prop.type);
        if (nested.length > 0) {
          return nested;
        }
      }
    }
    return [];
  }
  for (const p of baseServiceMethod.parameters) {
    if (p.__raw && p.__raw.decorators.find((d) => d.definition?.name === "@pageSize")) {
      return [p];
    }
    if (p.type.kind === "model") {
      return recurseToFindPageSizeParameterInModel(p, p.type);
    }
  }
  return [];
}
function getSdkPagingServiceMethod(context, operation, client) {
  const diagnostics = createDiagnosticCollector6();
  const baseServiceMethod = diagnostics.pipe(getSdkBasicServiceMethod(context, operation, client));
  let responseType = baseServiceMethod.response.type;
  if (responseType?.kind === "nullable") {
    responseType = responseType.type;
  }
  if (isList(context.program, operation)) {
    const pagingMetadata = $4(context.program).operation.getPagingMetadata(getOverriddenClientMethod(context, operation) ?? operation);
    if (responseType?.__raw?.kind !== "Model" || responseType.kind !== "model" || !pagingMetadata) {
      diagnostics.add(createDiagnostic({
        code: "unexpected-pageable-operation-return-type",
        target: operation,
        format: {
          operationName: operation.name
        }
      }));
      return diagnostics.wrap({
        ...baseServiceMethod,
        kind: "paging",
        pagingMetadata: {}
      });
    }
    const resultSegments = mapFirstSegmentForResultSegments(pagingMetadata.output.pageItems.path, baseServiceMethod.response);
    const nextLinkSegments2 = mapFirstSegmentForResultSegments(pagingMetadata.output.nextLink?.path, baseServiceMethod.response);
    const continuationTokenResponseSegments = mapFirstSegmentForResultSegments(pagingMetadata.output.continuationToken?.path, baseServiceMethod.response);
    baseServiceMethod.response.resultSegments = resultSegments?.map((resultSegment) => context.__modelPropertyCache.get(resultSegment));
    context.__pagedResultSet.add(responseType);
    baseServiceMethod.response.type = diagnostics.pipe(getClientTypeWithDiagnostics(context, pagingMetadata.output.pageItems.property.type, operation));
    return diagnostics.wrap({
      ...baseServiceMethod,
      kind: "paging",
      pagingMetadata: {
        __raw: pagingMetadata,
        nextLinkSegments: nextLinkSegments2?.map((segment) => context.__responseHeaderCache.get(segment) ?? context.__modelPropertyCache.get(segment)),
        continuationTokenParameterSegments: pagingMetadata.input.continuationToken?.path.map((r) => context.__methodParameterCache.get(r) ?? context.__modelPropertyCache.get(r)),
        continuationTokenResponseSegments: continuationTokenResponseSegments?.map((segment) => context.__responseHeaderCache.get(segment) ?? context.__modelPropertyCache.get(segment)),
        pageItemsSegments: baseServiceMethod.response.resultSegments,
        pageSizeParameterSegments: getPageSizeParameterSegments(baseServiceMethod),
        nextLinkReInjectedParametersSegments: pagingMetadata.output.nextLink?.property.type.kind === "Scalar" ? (getParameterizedNextLinkArguments(context.program, pagingMetadata.output.nextLink.property.type) ?? []).map((t) => getPropertySegmentsFromModelOrParameters(baseServiceMethod.parameters, (p) => p.__raw?.kind === "ModelProperty" && findRootSourceProperty(p.__raw) === findRootSourceProperty(t))) : void 0
      }
    });
  }
  const pagedMetadata = getPagedResult(context.program, operation);
  if (responseType?.__raw?.kind !== "Model" || responseType.kind !== "model" || !pagedMetadata.itemsProperty) {
    diagnostics.add(createDiagnostic({
      code: "unexpected-pageable-operation-return-type",
      target: operation,
      format: {
        operationName: operation.name
      }
    }));
    return diagnostics.wrap({
      ...baseServiceMethod,
      kind: "paging",
      pagingMetadata: {}
    });
  }
  context.__pagedResultSet.add(responseType);
  baseServiceMethod.response.type = diagnostics.pipe(getClientTypeWithDiagnostics(context, pagedMetadata.itemsProperty.type));
  baseServiceMethod.response.resultSegments = getPropertySegmentsFromModelOrParameters(responseType, (p) => p.__raw === pagedMetadata.itemsProperty);
  let nextLinkSegments = void 0;
  let nextLinkReInjectedParametersSegments = void 0;
  if (pagedMetadata.nextLinkProperty) {
    if (isHeader3(context.program, pagedMetadata.nextLinkProperty)) {
      nextLinkSegments = baseServiceMethod.operation.responses.map((r) => r.headers).flat().filter((h) => h.__raw?.kind === "ModelProperty" && findRootSourceProperty(h.__raw) === findRootSourceProperty(pagedMetadata.nextLinkProperty));
    } else {
      nextLinkSegments = getPropertySegmentsFromModelOrParameters(responseType, (p) => p.__raw === pagedMetadata.nextLinkProperty);
    }
    if (pagedMetadata.nextLinkProperty.type.kind === "Scalar") {
      nextLinkReInjectedParametersSegments = (getParameterizedNextLinkArguments(context.program, pagedMetadata.nextLinkProperty.type) ?? []).map((t) => getPropertySegmentsFromModelOrParameters(baseServiceMethod.parameters, (p) => p.__raw?.kind === "ModelProperty" && findRootSourceProperty(p.__raw) === findRootSourceProperty(t)));
    }
  }
  return diagnostics.wrap({
    ...baseServiceMethod,
    __raw_paged_metadata: pagedMetadata,
    kind: "paging",
    nextLinkOperation: pagedMetadata?.nextLinkOperation ? diagnostics.pipe(getSdkServiceOperation(context, pagedMetadata.nextLinkOperation, baseServiceMethod.parameters)) : void 0,
    pagingMetadata: {
      __raw: pagedMetadata,
      nextLinkSegments,
      nextLinkOperation: pagedMetadata?.nextLinkOperation ? diagnostics.pipe(getSdkServiceMethod(context, pagedMetadata.nextLinkOperation, client)) : void 0,
      nextLinkReInjectedParametersSegments,
      pageItemsSegments: baseServiceMethod.response.resultSegments
    }
  });
}
function mapFirstSegmentForResultSegments(resultSegments, response) {
  if (resultSegments === void 0 || response === void 0)
    return void 0;
  const responseModel = response.type?.kind === "model" ? response.type : response.type?.kind === "nullable" && response.type.type.kind === "model" ? response.type.type : void 0;
  if (resultSegments.length > 0 && responseModel) {
    for (let i = 0; i < resultSegments.length; i++) {
      const segment = resultSegments[i];
      let current = responseModel;
      while (current) {
        for (const property of current.properties ?? []) {
          if (property.__raw && findRootSourceProperty(property.__raw) === findRootSourceProperty(segment)) {
            return [property.__raw, ...resultSegments.slice(i + 1)];
          }
        }
        current = current.baseModel;
      }
    }
  }
  return resultSegments;
}
function getPropertySegmentsFromModelOrParameters(source, predicate) {
  const queue = [];
  if (!Array.isArray(source)) {
    if (source.baseModel) {
      const baseResult = getPropertySegmentsFromModelOrParameters(source.baseModel, predicate);
      if (baseResult)
        return baseResult;
    }
  }
  for (const prop of Array.isArray(source) ? source : source.properties.values()) {
    if (predicate(prop)) {
      return [prop];
    }
    if (prop.type.kind === "model") {
      queue.push({ model: prop.type, path: [prop] });
    }
  }
  while (queue.length > 0) {
    const { model, path } = queue.shift();
    for (const prop of model.properties.values()) {
      if (predicate(prop)) {
        return path.concat(prop);
      }
      if (prop.type.kind === "model") {
        queue.push({ model: prop.type, path: path.concat(prop) });
      }
    }
  }
  return void 0;
}
function getSdkLroServiceMethod(context, operation, client) {
  const diagnostics = createDiagnosticCollector6();
  const metadata = getServiceMethodLroMetadata(context, operation, client);
  const baseServiceMethod = diagnostics.pipe(getSdkBasicServiceMethod(context, operation, client));
  baseServiceMethod.response.type = metadata.finalResponse?.result;
  baseServiceMethod.response.resultSegments = metadata.finalResponse?.resultSegments;
  return diagnostics.wrap({
    ...baseServiceMethod,
    kind: "lro",
    __raw_lro_metadata: metadata.__raw,
    lroMetadata: metadata,
    operation: diagnostics.pipe(getSdkServiceOperation(context, metadata.__raw.operation, baseServiceMethod.parameters))
  });
}
function getServiceMethodLroMetadata(context, operation, client) {
  const rawMetadata = getLroMetadata2(context.program, operation);
  if (rawMetadata === void 0) {
    return void 0;
  }
  let finalEnvelopeResult = void 0;
  const diagnostics = createDiagnosticCollector6();
  if (rawMetadata.finalEnvelopeResult === "void") {
    finalEnvelopeResult = "void";
  } else if (rawMetadata.finalEnvelopeResult) {
    finalEnvelopeResult = getSdkModel(context, rawMetadata.finalEnvelopeResult);
  }
  return {
    __raw: rawMetadata,
    finalStateVia: rawMetadata.finalStateVia,
    finalResponse: getFinalResponse(),
    finalStep: getSdkLroServiceFinalStep(context, rawMetadata.finalStep),
    pollingStep: {
      responseBody: diagnostics.pipe(getClientTypeWithDiagnostics(context, rawMetadata.pollingInfo.responseModel))
    },
    operation: ignoreDiagnostics5(getSdkBasicServiceMethod(context, rawMetadata.operation, client)).operation,
    logicalResult: getSdkModel(context, rawMetadata.logicalResult),
    statusMonitorStep: getStatusMonitorStep(context, rawMetadata.statusMonitorStep),
    pollingInfo: getPollingInfo(context, rawMetadata.pollingInfo),
    envelopeResult: getSdkModel(context, rawMetadata.envelopeResult),
    logicalPath: rawMetadata.logicalPath,
    finalEnvelopeResult,
    finalResultPath: rawMetadata.finalResultPath
  };
  function getSdkLroServiceFinalStep(context2, step) {
    if (!step)
      return void 0;
    switch (step.kind) {
      case "finalOperationLink": {
        return {
          kind: "finalOperationLink",
          target: getSdkOperationLink(context2, step.target)
        };
      }
      case "finalOperationReference": {
        return {
          kind: "finalOperationReference",
          target: getSdkOperationReference(context2, step.target, client)
        };
      }
      case "pollingSuccessProperty": {
        return {
          kind: "pollingSuccessProperty",
          responseModel: getSdkModel(context2, step.responseModel),
          target: ignoreDiagnostics5(getSdkModelPropertyType(context2, step.target)),
          sourceProperty: step.sourceProperty ? ignoreDiagnostics5(getSdkModelPropertyType(context2, step.sourceProperty)) : void 0
        };
      }
      case "noPollingResult": {
        return {
          kind: "noPollingResult",
          responseModel: void 0
        };
      }
    }
  }
  function getStatusMonitorStep(context2, statusMonitorStep) {
    if (!statusMonitorStep)
      return void 0;
    if (statusMonitorStep.kind === "nextOperationLink") {
      return {
        kind: "nextOperationLink",
        responseModel: getSdkModel(context2, statusMonitorStep.responseModel),
        target: getSdkOperationLink(context2, statusMonitorStep.target)
      };
    }
    return {
      kind: "nextOperationReference",
      responseModel: getSdkModel(context2, statusMonitorStep.responseModel),
      target: getSdkOperationReference(context2, statusMonitorStep.target, client)
    };
  }
  function getSdkOperationLink(context2, link) {
    return {
      kind: "link",
      location: link.location,
      property: ignoreDiagnostics5(getSdkModelPropertyType(context2, link.property))
    };
  }
  function getSdkOperationReference(context2, reference, client2) {
    const parameters = /* @__PURE__ */ new Map();
    for (const [key, p] of reference.parameters?.entries() ?? []) {
      parameters.set(key, {
        sourceKind: p.sourceKind,
        source: ignoreDiagnostics5(getSdkModelPropertyType(context2, p.source)),
        target: ignoreDiagnostics5(getSdkModelPropertyType(context2, p.target))
      });
    }
    return {
      kind: "reference",
      operation: ignoreDiagnostics5(getSdkBasicServiceMethod(context2, reference.operation, client2)).operation,
      parameterMap: reference.parameterMap,
      parameters,
      link: reference.link ? getSdkOperationLink(context2, reference.link) : void 0
    };
  }
  function getPollingInfo(context2, pollingInfo) {
    const resultProperty = pollingInfo.resultProperty ? ignoreDiagnostics5(getSdkModelPropertyType(context2, pollingInfo.resultProperty)) : void 0;
    const errorProperty = pollingInfo.errorProperty ? ignoreDiagnostics5(getSdkModelPropertyType(context2, pollingInfo.errorProperty)) : void 0;
    return {
      kind: "pollingOperationStep",
      responseModel: getSdkModel(context2, pollingInfo.responseModel),
      terminationStatus: getTerminationStatus(context2, pollingInfo.terminationStatus),
      resultProperty,
      errorProperty
    };
  }
  function getTerminationStatus(context2, terminationStatus) {
    switch (terminationStatus.kind) {
      case "status-code":
        return terminationStatus;
      case "model-property":
        return {
          ...terminationStatus,
          property: ignoreDiagnostics5(getSdkModelPropertyType(context2, terminationStatus.property))
        };
    }
  }
  function getFinalResponse() {
    if (rawMetadata?.finalEnvelopeResult === void 0 || rawMetadata.finalEnvelopeResult === "void") {
      return void 0;
    }
    const envelopeResult = diagnostics.pipe(getClientTypeWithDiagnostics(context, rawMetadata.finalEnvelopeResult));
    const result = diagnostics.pipe(getClientTypeWithDiagnostics(context, rawMetadata.finalResult));
    const resultPath = rawMetadata.finalResultPath;
    let sdkProperty = void 0;
    for (const property of envelopeResult.properties) {
      if (property.__raw === void 0 || property.kind !== "property") {
        continue;
      }
      if (property.__raw?.name === resultPath) {
        sdkProperty = property;
        break;
      }
    }
    return {
      envelopeResult,
      result,
      resultSegments: sdkProperty !== void 0 ? [sdkProperty] : void 0
    };
  }
}
function getSdkMethodResponse(context, operation, sdkOperation, client) {
  const responses = sdkOperation.responses;
  const { allResponseBodies, nonBodyExists } = getAllResponseBodiesAndNonBodyExists(responses);
  const responseTypes = new Set(allResponseBodies.map((x) => getHashForType(x)));
  let type = void 0;
  if (getResponseAsBool(context, operation)) {
    type = getSdkBuiltInType(context, $4(context.program).builtin.boolean);
  } else {
    if (responseTypes.size > 1) {
      type = {
        __raw: operation,
        kind: "union",
        access: "public",
        usage: UsageFlags.Output,
        variantTypes: allResponseBodies,
        name: createGeneratedName(context, operation, "UnionResponse"),
        isGeneratedName: true,
        namespace: client.namespace,
        crossLanguageDefinitionId: `${getCrossLanguageDefinitionId(context, operation)}.UnionResponse`,
        decorators: []
      };
    } else if (responseTypes.size === 1) {
      type = allResponseBodies[0];
    }
    if (nonBodyExists && type) {
      type = {
        kind: "nullable",
        name: createGeneratedName(context, operation, "NullableResponse"),
        crossLanguageDefinitionId: `${getCrossLanguageDefinitionId(context, operation)}.NullableResponse`,
        isGeneratedName: true,
        type,
        decorators: [],
        access: "public",
        usage: UsageFlags.Output,
        namespace: client.namespace
      };
    }
  }
  return {
    kind: "method",
    type
  };
}
function getSdkBasicServiceMethod(context, operation, client) {
  const diagnostics = createDiagnosticCollector6();
  const methodParameters = [];
  const apiVersions = getAvailableApiVersions(context, operation, client.__raw.type ?? client.__raw.service);
  let clientParams = context.__clientParametersCache.get(client.__raw);
  if (!clientParams) {
    clientParams = [];
    context.__clientParametersCache.set(client.__raw, clientParams);
  }
  const override = getOverriddenClientMethod(context, operation);
  const params = (override ?? operation).parameters.properties.values();
  for (const param of params) {
    if (isNeverOrVoidType(param.type))
      continue;
    const sdkMethodParam = diagnostics.pipe(getSdkMethodParameter(context, param, operation));
    if (sdkMethodParam.onClient) {
      if (sdkMethodParam.isApiVersionParam) {
        if (!clientParams.find((x) => x.isApiVersionParam)) {
          clientParams.push(sdkMethodParam);
        }
      } else if (isSubscriptionId(context, param)) {
        if (!clientParams.find((x) => isSubscriptionId(context, x))) {
          clientParams.push(sdkMethodParam);
        }
      }
    } else {
      methodParameters.push(sdkMethodParam);
    }
  }
  const serviceOperation = diagnostics.pipe(getSdkServiceOperation(context, operation, methodParameters));
  const response = getSdkMethodResponse(context, operation, serviceOperation, client);
  const name = getLibraryName(context, operation);
  return diagnostics.wrap({
    __raw: operation,
    kind: "basic",
    name,
    access: getAccess(context, operation) ?? "public",
    parameters: methodParameters,
    doc: getClientDoc(context, operation),
    summary: getSummary3(context.program, operation),
    operation: serviceOperation,
    response,
    apiVersions,
    crossLanguageDefinitionId: getCrossLanguageDefinitionId(context, operation),
    decorators: diagnostics.pipe(getTypeDecorators(context, operation)),
    generateConvenient: shouldGenerateConvenient(context, operation),
    generateProtocol: shouldGenerateProtocol(context, operation),
    isOverride: override !== void 0
  });
}
function getSdkServiceMethod(context, operation, client) {
  const lro = getLroMetadata2(context.program, operation);
  const paging = getPagedResult(context.program, operation) || isList(context.program, operation);
  if (lro && paging) {
    return getSdkLroPagingServiceMethod(context, operation, client);
  } else if (paging) {
    return getSdkPagingServiceMethod(context, operation, client);
  } else if (lro) {
    return getSdkLroServiceMethod(context, operation, client);
  }
  return getSdkBasicServiceMethod(context, operation, client);
}
function getSdkMethodParameter(context, type, operation) {
  const diagnostics = createDiagnosticCollector6();
  let property = context.__methodParameterCache?.get(type);
  if (!property) {
    if (operation) {
      const correspondingClientParam = getCorrespondingClientParam(context, type, operation);
      if (correspondingClientParam)
        return diagnostics.wrap(correspondingClientParam);
    }
    property = {
      ...diagnostics.pipe(getSdkModelPropertyTypeBase(context, type, operation)),
      kind: "method"
    };
    context.__methodParameterCache.set(type, property);
  }
  return diagnostics.wrap(property);
}
function createSdkMethods(context, client, sdkClientType) {
  const diagnostics = createDiagnosticCollector6();
  const retval = [];
  for (const operation of listOperationsInOperationGroup(context, client)) {
    retval.push(diagnostics.pipe(getSdkServiceMethod(context, operation, sdkClientType)));
  }
  for (const operationGroup of listOperationGroups(context, client)) {
    const operationGroupClient = diagnostics.pipe(createSdkClientType(context, operationGroup, sdkClientType));
    if (sdkClientType.children) {
      sdkClientType.children.push(operationGroupClient);
    } else {
      sdkClientType.children = [operationGroupClient];
    }
  }
  return diagnostics.wrap(retval);
}

// src/typespec/packages/typespec-client-generator-core/dist/src/clients.js
function getEndpointTypeFromSingleServer(context, client, server) {
  const diagnostics = createDiagnosticCollector7();
  const templateArguments = [];
  const defaultOverridableEndpointType = {
    kind: "endpoint",
    serverUrl: "{endpoint}",
    templateArguments: [
      {
        name: "endpoint",
        isGeneratedName: true,
        doc: "Service host",
        kind: "path",
        onClient: true,
        explode: false,
        style: "simple",
        allowReserved: true,
        optional: false,
        serializedName: "endpoint",
        correspondingMethodParams: [],
        type: getSdkBuiltInType(context, $5(context.program).builtin.url),
        isApiVersionParam: false,
        apiVersions: context.getApiVersionsForType(client.__raw.type ?? client.__raw.service),
        crossLanguageDefinitionId: `${getCrossLanguageDefinitionId(context, client.__raw.service)}.endpoint`,
        decorators: [],
        access: "public"
      }
    ],
    decorators: []
  };
  const types = [];
  if (!server)
    return diagnostics.wrap([defaultOverridableEndpointType]);
  for (const param of server.parameters.values()) {
    const sdkParam = diagnostics.pipe(getSdkHttpParameter(context, param, void 0, void 0, "path"));
    if (sdkParam.kind === "path") {
      templateArguments.push(sdkParam);
      sdkParam.onClient = true;
      if (param.defaultValue) {
        sdkParam.clientDefaultValue = getValueTypeValue(param.defaultValue);
      }
      const apiVersionInfo = updateWithApiVersionInformation(context, param, client.__raw);
      sdkParam.isApiVersionParam = apiVersionInfo.isApiVersionParam;
      if (sdkParam.isApiVersionParam && apiVersionInfo.clientDefaultValue) {
        sdkParam.clientDefaultValue = apiVersionInfo.clientDefaultValue;
      }
      sdkParam.apiVersions = getAvailableApiVersions(context, param, client.__raw.type);
      sdkParam.crossLanguageDefinitionId = `${getCrossLanguageDefinitionId(context, client.__raw.service)}.${param.name}`;
    } else {
      diagnostics.add(createDiagnostic({
        code: "server-param-not-path",
        target: param,
        format: {
          templateArgumentName: sdkParam.name,
          templateArgumentType: sdkParam.kind
        }
      }));
    }
  }
  const isOverridable = templateArguments.length === 1 && server.url.startsWith("{") && server.url.endsWith("}");
  if (templateArguments.length === 0) {
    types.push(defaultOverridableEndpointType);
    types[0].templateArguments[0].clientDefaultValue = server.url;
  } else {
    types.push({
      kind: "endpoint",
      serverUrl: server.url,
      templateArguments,
      decorators: []
    });
    if (!isOverridable) {
      types.push(defaultOverridableEndpointType);
    }
  }
  return diagnostics.wrap(types);
}
function getSdkEndpointParameter(context, client) {
  const diagnostics = createDiagnosticCollector7();
  const rawClient = client.__raw;
  const servers = getServers2(context.program, client.__raw.service);
  const types = [];
  if (servers === void 0) {
    types.push(...diagnostics.pipe(getEndpointTypeFromSingleServer(context, client, void 0)));
  } else {
    for (const server of servers) {
      types.push(...diagnostics.pipe(getEndpointTypeFromSingleServer(context, client, server)));
    }
  }
  let type;
  if (types.length > 1) {
    type = {
      kind: "union",
      access: "public",
      usage: UsageFlags.None,
      variantTypes: types,
      name: createGeneratedName(context, rawClient.service, "Endpoint"),
      isGeneratedName: true,
      crossLanguageDefinitionId: `${getCrossLanguageDefinitionId(context, rawClient.service)}.Endpoint`,
      namespace: getClientNamespace(context, rawClient.service),
      decorators: []
    };
  } else {
    type = types[0];
  }
  return diagnostics.wrap({
    kind: "endpoint",
    type,
    name: "endpoint",
    isGeneratedName: true,
    doc: "Service host",
    onClient: true,
    urlEncode: false,
    apiVersions: context.getApiVersionsForType(rawClient.type ?? rawClient.service),
    optional: false,
    isApiVersionParam: false,
    crossLanguageDefinitionId: `${getCrossLanguageDefinitionId(context, rawClient.service)}.endpoint`,
    decorators: [],
    access: "public"
  });
}
function createSdkClientType(context, client, parent) {
  const diagnostics = createDiagnosticCollector7();
  const sdkClientType = {
    __raw: client,
    kind: "client",
    name: client.kind === "SdkClient" ? client.name : client.groupPath.split(".").at(-1),
    doc: client.type ? getClientDoc(context, client.type) : void 0,
    summary: client.type ? getSummary4(context.program, client.type) : void 0,
    methods: [],
    apiVersions: context.getApiVersionsForType(client.type ?? client.service),
    namespace: getClientNamespace(context, client.type ?? client.service),
    clientInitialization: diagnostics.pipe(createSdkClientInitializationType(context, client)),
    decorators: client.type ? diagnostics.pipe(getTypeDecorators(context, client.type)) : [],
    parent,
    // if it is client, the crossLanguageDefinitionId is the ${namespace}, if it is operation group, the crosslanguageDefinitionId is the %{namespace}.%{operationGroupName}
    crossLanguageDefinitionId: getCrossLanguageDefinitionId(context, client.type ?? client.service)
  };
  sdkClientType.methods = diagnostics.pipe(createSdkMethods(context, client, sdkClientType));
  addDefaultClientParameters(context, sdkClientType);
  return diagnostics.wrap(sdkClientType);
}
function addDefaultClientParameters(context, client) {
  const diagnostics = createDiagnosticCollector7();
  const defaultClientParamters = [];
  defaultClientParamters.push(diagnostics.pipe(getSdkEndpointParameter(context, client)));
  const credentialParam = getSdkCredentialParameter(context, client.__raw);
  if (credentialParam) {
    defaultClientParamters.push(credentialParam);
  }
  let apiVersionParam = context.__clientParametersCache.get(client.__raw)?.find((x) => x.isApiVersionParam);
  if (!apiVersionParam) {
    for (const sc of listOperationGroups(context, client.__raw, true)) {
      apiVersionParam = context.__clientParametersCache.get(sc)?.find((x) => x.isApiVersionParam);
      if (apiVersionParam)
        break;
    }
  }
  if (apiVersionParam) {
    defaultClientParamters.push(apiVersionParam);
  }
  let subId = context.__clientParametersCache.get(client.__raw)?.find((x) => isSubscriptionId(context, x));
  if (!subId && context.arm) {
    for (const sc of listOperationGroups(context, client.__raw, true)) {
      subId = context.__clientParametersCache.get(sc)?.find((x) => isSubscriptionId(context, x));
      if (subId)
        break;
    }
  }
  if (subId) {
    defaultClientParamters.push(subId);
  }
  client.clientInitialization.parameters = [
    ...defaultClientParamters,
    ...client.clientInitialization.parameters
  ];
}
function createSdkClientInitializationType(context, client) {
  const diagnostics = createDiagnosticCollector7();
  const name = `${client.kind === "SdkClient" ? client.name : client.groupPath.split(".").at(-1)}Options`;
  const result = {
    kind: "clientinitialization",
    doc: "Initialization for the client",
    parameters: [],
    initializedBy: client.kind === "SdkClient" ? InitializedByFlags.Individually : InitializedByFlags.Default,
    name,
    isGeneratedName: true,
    decorators: []
  };
  if (client.type) {
    const initializationOptions = getClientInitializationOptions(context, client.type);
    if (initializationOptions?.parameters) {
      result.doc = getDoc2(context.program, initializationOptions.parameters);
      result.summary = getSummary4(context.program, initializationOptions.parameters);
      result.name = initializationOptions.parameters.name === "" ? name : initializationOptions.parameters.name;
      result.isGeneratedName = initializationOptions.parameters.name === "" ? true : false;
      result.decorators = diagnostics.pipe(getTypeDecorators(context, initializationOptions.parameters));
      result.__raw = initializationOptions.parameters;
      for (const parameter of initializationOptions.parameters.properties.values()) {
        const clientParameter = diagnostics.pipe(getSdkMethodParameter(context, parameter));
        clientParameter.onClient = true;
        result.parameters.push(clientParameter);
      }
    }
    if (initializationOptions?.initializedBy) {
      if (client.kind === "SdkClient" && (initializationOptions.initializedBy & InitializedByFlags.Parent) === InitializedByFlags.Parent) {
        diagnostics.add(createDiagnostic({
          code: "invalid-initialized-by",
          target: client.type,
          format: {
            message: "First level client must have `InitializedBy.individually` specified in `initializedBy`."
          }
        }));
      } else if (client.kind === "SdkOperationGroup" && initializationOptions.initializedBy === InitializedByFlags.Individually) {
        diagnostics.add(createDiagnostic({
          code: "invalid-initialized-by",
          target: client.type,
          format: {
            message: "Sub client must have `InitializedBy.parent` or `InitializedBy.individually | InitializedBy.parent` specified in `initializedBy`."
          }
        }));
      } else {
        result.initializedBy = initializationOptions.initializedBy;
      }
    }
    if (initializationOptions?.parameters) {
      let clientParams = context.__clientParametersCache.get(client);
      if (!clientParams) {
        clientParams = [];
        context.__clientParametersCache.set(client, clientParams);
      }
      for (const param of result.parameters) {
        if (param.kind === "method")
          clientParams.push(param);
      }
    }
  }
  return diagnostics.wrap(result);
}

// src/typespec/packages/typespec-client-generator-core/dist/src/license.js
var licenseMap = {
  "MIT License": {
    name: "MIT License",
    link: "https://mit-license.org",
    company: "",
    header: `Copyright (c) <company>. All rights reserved.
Licensed under the MIT License.`,
    description: `Copyright (c) <company>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the \u201CSoftware\u201D), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED \u201CAS IS\u201D, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.`
  },
  "Apache License 2.0": {
    name: "Apache License 2.0",
    link: "https://www.apache.org/licenses/LICENSE-2.0",
    company: "",
    header: `Copyright (c) <company>. All rights reserved.
Licensed under the Apache License, Version 2.0.`,
    description: `Copyright (c) <company>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.`
  },
  "BSD 3-Clause License": {
    name: "BSD 3-Clause License",
    link: "https://opensource.org/licenses/BSD-3-Clause",
    company: "",
    header: `Copyright (c) <company>. All rights reserved.
Licensed under the BSD 3-Clause License.`,
    description: `Copyright (c) <company>

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the
   names of its contributors may be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.`
  },
  "MPL 2.0": {
    name: "MPL 2.0",
    link: "https://www.mozilla.org/en-US/MPL/2.0/",
    company: "",
    header: `Copyright (c) <company>. All rights reserved.
Licensed under the Mozilla Public License, v. 2.0.`,
    description: `Copyright (c) <company>

This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.`
  },
  "GPL-3.0": {
    name: "GPL-3.0",
    link: "https://www.gnu.org/licenses/gpl-3.0.html",
    company: "",
    header: `Copyright (c) <company>. All rights reserved.
Licensed under the version 3 of the GNU General Public License.`,
    description: `Copyright (c) <company>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.`
  },
  "LGPL-3.0": {
    name: "LGPL-3.0",
    link: "https://www.gnu.org/licenses/lgpl-3.0.html",
    company: "",
    header: `Copyright (c) <company>. All rights reserved.
Licensed under the version 3 of the GNU Lesser General Public License.`,
    description: `Copyright (c) <company>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.`
  }
};
function getLicenseInfo(context) {
  if (!context.license) {
    return void 0;
  }
  if (!Object.keys(licenseMap).includes(context.license.name)) {
    return {
      name: context.license.name,
      company: context.license.company ?? "",
      link: context.license.link ?? "",
      header: context.license.header ?? "",
      description: context.license.description ?? ""
    };
  }
  const licenseInfo = licenseMap[context.license.name];
  return {
    name: licenseInfo.name,
    company: context.license.company ?? "",
    link: context.license.link ?? licenseInfo.link,
    header: context.license.header ?? licenseInfo.header.replace("<company>", context.license.company ?? ""),
    description: context.license.description ?? licenseInfo.description.replace("<company>", context.license.company ?? "")
  };
}

// src/typespec/packages/typespec-client-generator-core/dist/src/package.js
function createSdkPackage(context) {
  const diagnostics = createDiagnosticCollector8();
  populateApiVersionInformation(context);
  diagnostics.pipe(handleAllTypes(context));
  const crossLanguagePackageId = diagnostics.pipe(getCrossLanguagePackageId(context));
  const allReferencedTypes = getAllReferencedTypes(context);
  const versions = context.getPackageVersions();
  const sdkPackage = {
    clients: listClients(context).map((c) => diagnostics.pipe(createSdkClientType(context, c))),
    models: allReferencedTypes.filter((x) => x.kind === "model"),
    enums: allReferencedTypes.filter((x) => x.kind === "enum"),
    unions: allReferencedTypes.filter((x) => x.kind === "union" || x.kind === "nullable"),
    crossLanguagePackageId,
    namespaces: [],
    licenseInfo: getLicenseInfo(context),
    metadata: {
      apiVersion: context.apiVersion === "all" ? "all" : versions[versions.length - 1]
    }
  };
  organizeNamespaces(context, sdkPackage);
  return diagnostics.wrap(sdkPackage);
}
function organizeNamespaces(context, sdkPackage) {
  const clients = [...sdkPackage.clients];
  while (clients.length > 0) {
    const client = clients.shift();
    getSdkNamespace(context, sdkPackage, client).clients.push(client);
    if (client.children && client.children.length > 0) {
      clients.push(...client.children);
    }
  }
  for (const model of sdkPackage.models) {
    getSdkNamespace(context, sdkPackage, model).models.push(model);
  }
  for (const enumType of sdkPackage.enums) {
    getSdkNamespace(context, sdkPackage, enumType).enums.push(enumType);
  }
  for (const unionType of sdkPackage.unions) {
    getSdkNamespace(context, sdkPackage, unionType).unions.push(unionType);
  }
}
function getSdkNamespace(context, sdkPackage, type) {
  if (!("namespace" in type)) {
    return sdkPackage;
  }
  const namespace2 = type.namespace;
  const segments = namespace2.split(".");
  let current = sdkPackage;
  let fullName = "";
  for (const segment of segments) {
    fullName = fullName === "" ? segment : `${fullName}.${segment}`;
    const ns = current.namespaces.find((ns2) => ns2.name === segment);
    if (ns === void 0) {
      const rawNamespace = getNamespaceFromType(type.__raw);
      const newNs = {
        __raw: rawNamespace,
        name: segment,
        fullName,
        clients: [],
        models: [],
        enums: [],
        unions: [],
        namespaces: [],
        decorators: rawNamespace ? ignoreDiagnostics6(getTypeDecorators(context, rawNamespace)) : []
      };
      current.namespaces.push(newNs);
      current = newNs;
    } else {
      current = ns;
    }
  }
  return current;
}
function populateApiVersionInformation(context) {
  if (context.__rawClientsOperationGroupsCache === void 0) {
    prepareClientAndOperationCache(context);
  }
  for (const clientOperationGroup of context.__rawClientsOperationGroupsCache.values()) {
    context.setApiVersionsForType(clientOperationGroup.type ?? clientOperationGroup.service, filterApiVersionsWithDecorators(context, clientOperationGroup.type ?? clientOperationGroup.service, context.getPackageVersions()));
    const clientApiVersions = context.getApiVersionsForType(clientOperationGroup.type ?? clientOperationGroup.service);
    context.__clientApiVersionDefaultValueCache.set(clientOperationGroup, clientApiVersions[clientApiVersions.length - 1]);
  }
}

// src/typespec/packages/typespec-client-generator-core/dist/src/context.js
function createTCGCContext(program, emitterName, options) {
  const diagnostics = createDiagnosticCollector9();
  return {
    program,
    diagnostics: diagnostics.diagnostics,
    emitterName: diagnostics.pipe(parseEmitterName(program, emitterName ?? program.emitters[0]?.metadata?.name)),
    previewStringRegex: /-preview$/,
    disableUsageAccessPropagationToBase: false,
    generateProtocolMethods: true,
    generateConvenienceMethods: true,
    __referencedTypeCache: /* @__PURE__ */ new Map(),
    __arrayDictionaryCache: /* @__PURE__ */ new Map(),
    __methodParameterCache: /* @__PURE__ */ new Map(),
    __modelPropertyCache: /* @__PURE__ */ new Map(),
    __responseHeaderCache: /* @__PURE__ */ new Map(),
    __generatedNames: /* @__PURE__ */ new Map(),
    __httpOperationCache: /* @__PURE__ */ new Map(),
    __clientParametersCache: /* @__PURE__ */ new Map(),
    __tspTypeToApiVersions: /* @__PURE__ */ new Map(),
    __clientApiVersionDefaultValueCache: /* @__PURE__ */ new Map(),
    __knownScalars: getKnownScalars(),
    __httpOperationExamples: /* @__PURE__ */ new Map(),
    __pagedResultSet: /* @__PURE__ */ new Set(),
    getMutatedGlobalNamespace() {
      if (options?.mutateNamespace === false) {
        return program.getGlobalNamespaceType();
      }
      let globalNamespace = this.__mutatedGlobalNamespace;
      if (!globalNamespace) {
        globalNamespace = handleVersioningMutationForGlobalNamespace(this);
        this.__mutatedGlobalNamespace = globalNamespace;
      }
      return globalNamespace;
    },
    getApiVersionsForType(type) {
      return this.__tspTypeToApiVersions.get(type) ?? [];
    },
    setApiVersionsForType(type, apiVersions) {
      const existingApiVersions = this.__tspTypeToApiVersions.get(type) ?? [];
      const mergedApiVersions = [...existingApiVersions];
      for (const apiVersion of apiVersions) {
        if (!mergedApiVersions.includes(apiVersion)) {
          mergedApiVersions.push(apiVersion);
        }
      }
      this.__tspTypeToApiVersions.set(type, mergedApiVersions);
    },
    getPackageVersions() {
      if (this.__packageVersions) {
        return this.__packageVersions;
      }
      const service = listServices2(program)[0];
      if (!service) {
        this.__packageVersions = [];
        return this.__packageVersions;
      }
      const versions = getVersions4(program, service.type)[1]?.getVersions();
      if (!versions) {
        this.__packageVersions = [];
        return this.__packageVersions;
      }
      removeVersionsLargerThanExplicitlySpecified(this, versions);
      this.__packageVersions = versions.map((version) => version.value);
      return this.__packageVersions;
    },
    getPackageVersionEnum() {
      if (this.__packageVersionEnum) {
        return this.__packageVersionEnum;
      }
      const namespaces = listAllServiceNamespaces(this);
      if (namespaces.length === 0) {
        return void 0;
      }
      return getVersions4(this.program, namespaces[0])[1]?.getVersions()?.[0].enumMember.enum;
    },
    getClients() {
      if (!this.__rawClientsOperationGroupsCache) {
        prepareClientAndOperationCache(this);
      }
      return Array.from(this.__rawClientsOperationGroupsCache.values()).filter((item) => item.kind === "SdkClient");
    },
    getClientOrOperationGroup(type) {
      if (!this.__rawClientsOperationGroupsCache) {
        prepareClientAndOperationCache(this);
      }
      return this.__rawClientsOperationGroupsCache.get(type);
    },
    getOperationsForClient(client) {
      if (!this.__clientToOperationsCache) {
        prepareClientAndOperationCache(this);
      }
      return this.__clientToOperationsCache.get(client);
    },
    getClientForOperation(operation) {
      if (!this.__operationToClientCache) {
        prepareClientAndOperationCache(this);
      }
      return this.__operationToClientCache.get(operation);
    }
  };
}
async function createSdkContext(context, emitterName, options) {
  const diagnostics = createDiagnosticCollector9();
  const tcgcContext = createTCGCContext(context.program, emitterName ?? context.options["emitter-name"]);
  const generateProtocolMethods = context.options["generate-protocol-methods"] ?? tcgcContext.generateProtocolMethods;
  const generateConvenienceMethods = context.options["generate-convenience-methods"] ?? tcgcContext.generateConvenienceMethods;
  const sdkContext = {
    ...tcgcContext,
    emitContext: context,
    sdkPackage: void 0,
    generateProtocolMethods,
    generateConvenienceMethods,
    examplesDir: context.options["examples-dir"],
    namespaceFlag: context.options["namespace"],
    apiVersion: context.options["api-version"],
    license: context.options["license"],
    decoratorsAllowList: [...defaultDecoratorsAllowList, ...options?.additionalDecorators ?? []],
    previewStringRegex: options?.versioning?.previewStringRegex || tcgcContext.previewStringRegex,
    disableUsageAccessPropagationToBase: options?.disableUsageAccessPropagationToBase ?? false,
    flattenUnionAsEnum: options?.flattenUnionAsEnum ?? true,
    enableLegacyHierarchyBuilding: options?.enableLegacyHierarchyBuilding ?? true
  };
  sdkContext.sdkPackage = diagnostics.pipe(createSdkPackage(sdkContext));
  for (const client of sdkContext.sdkPackage.clients) {
    diagnostics.pipe(await handleClientExamples(sdkContext, client));
  }
  sdkContext.diagnostics = sdkContext.diagnostics.concat(diagnostics.diagnostics);
  if (options?.exportTCGCoutput) {
    await exportTCGCOutput(sdkContext);
  }
  return sdkContext;
}
async function exportTCGCOutput(context) {
  await emitFile(context.program, {
    path: resolvePath2(context.emitContext.emitterOutputDir, "tcgc-output.yaml"),
    content: stringify3(context.sdkPackage, (k, v) => {
      if (typeof k === "string" && k.startsWith("__")) {
        return void 0;
      }
      if (k === "scheme") {
        const { model, ...rest } = v;
        return rest;
      }
      if (k === "rawExample") {
        return void 0;
      }
      return v;
    }, { lineWidth: 0 })
  });
}
async function $onEmit(context) {
  if (!context.program.compilerOptions.noEmit) {
    const sdkContext = await createSdkContext(context, void 0, { exportTCGCoutput: true });
    context.program.reportDiagnostics(sdkContext.diagnostics);
  }
}

// src/typespec/packages/typespec-client-generator-core/dist/src/linter.js
import { defineLinter } from "@typespec/compiler";

// src/typespec/packages/typespec-client-generator-core/dist/src/rules/no-unnamed-types.rule.js
import { createRule, paramMessage as paramMessage2 } from "@typespec/compiler";
var noUnnamedTypesRule = createRule({
  name: "no-unnamed-types",
  description: "Requires types to be named rather than defined anonymously or inline.",
  severity: "warning",
  url: "https://azure.github.io/typespec-azure/docs/libraries/typespec-client-generator-core/rules/no-unnamed-types",
  messages: {
    default: paramMessage2`Anonymous ${"type"} with generated name "${"generatedName"}" detected. Define this ${"type"} separately with a proper name to improve code readability and reusability.`
  },
  create(context) {
    const tcgcContext = createTCGCContext(context.program, "@azure-tools/typespec-client-generator-core", {
      mutateNamespace: false
    });
    createSdkPackage(tcgcContext);
    return {
      model: (model) => {
        const createdModel = tcgcContext.__referencedTypeCache.get(model);
        if (createdModel && createdModel.kind === "model" && createdModel.properties.length > 0 && createdModel.usage !== UsageFlags.None && (createdModel.usage & UsageFlags.LroInitial) === 0 && (createdModel.usage & UsageFlags.MultipartFormData) === 0 && createdModel.isGeneratedName) {
          context.reportDiagnostic({
            target: model,
            format: {
              type: "model",
              generatedName: createdModel.name
            }
          });
        }
      },
      union: (union) => {
        const createdUnion = tcgcContext.__referencedTypeCache.get(union);
        const unionToCheck = getUnionType(createdUnion);
        if (unionToCheck && unionToCheck.usage !== UsageFlags.None && unionToCheck.isGeneratedName && !allVariantsBuiltIn(unionToCheck)) {
          context.reportDiagnostic({
            target: union,
            format: {
              type: "union",
              generatedName: unionToCheck.name
            }
          });
        }
      }
    };
  }
});
function getUnionType(union) {
  if (!union) {
    return void 0;
  }
  if (union.kind === "nullable") {
    const inner = union.type;
    if (inner.kind === "union" || inner.kind === "model" || inner.kind === "enum") {
      return inner;
    }
    return void 0;
  }
  return union;
}
function allVariantsBuiltIn(union) {
  if (union.kind !== "union") {
    return false;
  }
  return union.variantTypes.every((variant) => {
    return isSdkBuiltInKind(variant.kind);
  });
}

// src/typespec/packages/typespec-client-generator-core/dist/src/rules/property-name-conflict.rule.js
import { createRule as createRule2, paramMessage as paramMessage3 } from "@typespec/compiler";
var propertyNameConflictRule = createRule2({
  name: "property-name-conflict",
  description: "Avoid naming conflicts between a property and a model of the same name.",
  severity: "warning",
  url: "https://azure.github.io/typespec-azure/docs/libraries/typespec-client-generator-core/rules/property-name-conflict",
  messages: {
    default: paramMessage3`Property '${"propertyName"}' having the same name as its enclosing model will cause problems with C# code generation. Consider renaming the property directly or using the @clientName("newName", "csharp") decorator to rename the property for C#.`
  },
  create(context) {
    const tcgcContext = createTCGCContext(context.program, "@azure-tools/typespec-client-generator-core", {
      mutateNamespace: false
    });
    return {
      modelProperty: (property) => {
        const model = property.model;
        if (!model)
          return;
        const modelName = getLibraryName(tcgcContext, model, "csharp").toLocaleLowerCase();
        const propertyName = getLibraryName(tcgcContext, property, "csharp").toLocaleLowerCase();
        if (propertyName === modelName) {
          context.reportDiagnostic({
            format: { propertyName },
            target: property
          });
        }
        return;
      }
    };
  }
});

// src/typespec/packages/typespec-client-generator-core/dist/src/rules/require-client-suffix.rule.js
import { createRule as createRule3, paramMessage as paramMessage4 } from "@typespec/compiler";
var requireClientSuffixRule = createRule3({
  name: "require-client-suffix",
  description: "Client names should end with 'Client'.",
  severity: "warning",
  url: "https://azure.github.io/typespec-azure/docs/libraries/typespec-client-generator-core/rules/require-client-suffix",
  messages: {
    default: paramMessage4`Client name "${"name"}" must end with Client. Use @client({name: "...Client"}`
  },
  create(context) {
    const tcgcContext = createTCGCContext(context.program, "@azure-tools/typespec-client-generator-core", {
      mutateNamespace: false
    });
    return {
      namespace: (namespace2) => {
        const sdkClient = getClient(tcgcContext, namespace2);
        if (sdkClient && !sdkClient.name.endsWith("Client")) {
          context.reportDiagnostic({
            target: namespace2,
            format: {
              name: sdkClient.name
            }
          });
        }
      },
      interface: (interfaceType) => {
        const sdkClient = getClient(tcgcContext, interfaceType);
        if (sdkClient && !sdkClient.name.endsWith("Client")) {
          context.reportDiagnostic({
            target: interfaceType,
            format: {
              name: sdkClient.name
            }
          });
        }
      }
    };
  }
});

// src/typespec/packages/typespec-client-generator-core/dist/src/linter.js
var rules = [requireClientSuffixRule, propertyNameConflictRule, noUnnamedTypesRule];
var csharpRules = [propertyNameConflictRule];
var $linter = defineLinter({
  rules,
  ruleSets: {
    "best-practices:csharp": {
      enable: {
        ...Object.fromEntries(csharpRules.map((rule) => [
          `@azure-tools/typespec-client-generator-core/${rule.name}`,
          true
        ]))
      }
    }
  }
});

// src/typespec/packages/typespec-client-generator-core/dist/src/tsp-index.js
var tsp_index_exports = {};
__export(tsp_index_exports, {
  $decorators: () => $decorators,
  $lib: () => $lib,
  $onValidate: () => $onValidate
});

// src/typespec/packages/typespec-client-generator-core/dist/src/validations/clients.js
function validateClients(context) {
}

// src/typespec/packages/typespec-client-generator-core/dist/src/validations/http.js
function validateHttp(context) {
}

// src/typespec/packages/typespec-client-generator-core/dist/src/validations/methods.js
function validateMethods(context) {
  validateNoClientLocationWithClientOrOperationGroup(context);
  validateClientNameNotOnOverriddenMethods(context);
}
function validateNoClientLocationWithClientOrOperationGroup(context) {
  if (context.program.stateMap(clientLocationKey) && hasExplicitClientOrOperationGroup(context)) {
    for (const [op, _] of context.program.stateMap(clientLocationKey)) {
      reportDiagnostic(context.program, {
        code: "client-location-conflict",
        target: op
      });
    }
  }
}
function validateClientNameNotOnOverriddenMethods(context) {
  for (const [original, override] of listScopedDecoratorData(context, overrideKey)) {
    const clientNameOverride = getClientNameOverride(context, override);
    if (clientNameOverride) {
      reportDiagnostic(context.program, {
        code: "client-name-ineffective",
        messageId: "override",
        target: override,
        format: {
          name: clientNameOverride,
          originalMethodName: original.kind === "Operation" ? original.name : "<unknown>"
        }
      });
    }
  }
}

// src/typespec/packages/typespec-client-generator-core/dist/src/validations/package.js
import { getNamespaceFullName as getNamespaceFullName5 } from "@typespec/compiler";
import { getVersions as getVersions5 } from "@typespec/versioning";
function validatePackage(context) {
  validateNamespaces(context);
}
function validateNamespaces(context) {
  for (const namespace2 of listAllUserDefinedNamespaces(context)) {
    validateDecoratorsAppliedToVersionedService(context, namespace2);
    validateClientApiVersionsIncludesAllServiceVersions(context, namespace2);
  }
}
function validateDecoratorsAppliedToVersionedService(context, namespace2) {
  const versions = getVersions5(context.program, namespace2)[1];
  if (versions === void 0 && getExplicitClientApiVersions(context, namespace2)) {
    reportDiagnostic(context.program, {
      code: "require-versioned-service",
      format: {
        serviceName: getNamespaceFullName5(namespace2),
        decoratorName: "@clientApiVersions"
      },
      target: namespace2
    });
  }
}
function validateClientApiVersionsIncludesAllServiceVersions(context, namespace2) {
  const versions = getVersions5(context.program, namespace2)[1];
  if (versions === void 0) {
    return;
  }
  const clientApiVersionsEnum = getExplicitClientApiVersions(context, namespace2);
  if (clientApiVersionsEnum === void 0) {
    return;
  }
  const clientApiVersions = [...clientApiVersionsEnum.members.values()].map((x) => x.value ?? x.name);
  const missingVersions = versions.getVersions().map((x) => x.value).filter((version) => !clientApiVersions.includes(version));
  if (missingVersions.length > 0) {
    reportDiagnostic(context.program, {
      code: "missing-service-versions",
      format: {
        serviceName: getNamespaceFullName5(namespace2),
        missingVersions: missingVersions.join(", ")
      },
      target: namespace2
    });
  }
}

// src/typespec/packages/typespec-client-generator-core/dist/src/validations/types.js
import { unsafe_Realm } from "@typespec/compiler/experimental";
import { DuplicateTracker } from "@typespec/compiler/utils";
function validateTypes(context) {
  validateClientNames(context);
  validateNoDiscriminatedUnions(context);
}
function validateNoDiscriminatedUnions(context) {
  if (context.program.stateMap(Symbol.for("TypeSpec.discriminated"))) {
    for (const [type, _] of context.program.stateMap(Symbol.for("TypeSpec.discriminated"))) {
      reportDiagnostic(context.program, {
        code: "no-discriminated-unions",
        target: type
      });
    }
  }
}
function validateClientNames(tcgcContext) {
  const languageScopes = getDefinedLanguageScopes(tcgcContext.program);
  const needToConsiderClientLocation = !hasExplicitClientOrOperationGroup(tcgcContext);
  for (const scope of languageScopes) {
    const moved = /* @__PURE__ */ new Set();
    const movedTo = /* @__PURE__ */ new Map();
    const newClients = /* @__PURE__ */ new Map();
    if (needToConsiderClientLocation) {
      for (const [type, target] of listScopedDecoratorData(tcgcContext, clientLocationKey, scope).entries()) {
        if (unsafe_Realm.realmForType.has(type)) {
          continue;
        }
        if (type.kind === "Operation") {
          moved.add(type);
          if (typeof target === "string") {
            if (!newClients.has(target)) {
              newClients.set(target, [type]);
            } else {
              newClients.get(target).push(type);
            }
          } else {
            if (!movedTo.has(target)) {
              movedTo.set(target, [type]);
            } else {
              movedTo.get(target).push(type);
            }
          }
        }
      }
    }
    validateClientNamesPerNamespace(tcgcContext, scope, moved, movedTo, tcgcContext.program.getGlobalNamespaceType());
    [...newClients.values()].map((operations) => {
      validateClientNamesCore(tcgcContext, scope, operations);
    });
  }
}
function getDefinedLanguageScopes(program) {
  const languageScopes = /* @__PURE__ */ new Set();
  const impacted = [...program.stateMap(clientNameKey).values()];
  impacted.push(...program.stateMap(clientLocationKey).values());
  for (const value of impacted) {
    if (value[AllScopes]) {
      languageScopes.add(AllScopes);
    }
    for (const languageScope of Object.keys(value)) {
      languageScopes.add(languageScope);
    }
  }
  return languageScopes;
}
function* adjustOperations(iterator, moved, movedTo, container) {
  for (const operation of iterator) {
    if (moved.has(operation)) {
      continue;
    } else {
      yield operation;
    }
  }
  if (movedTo.has(container)) {
    for (const operation of movedTo.get(container)) {
      yield operation;
    }
  }
}
function validateClientNamesPerNamespace(tcgcContext, scope, moved, movedTo, namespace2) {
  validateClientNamesCore(tcgcContext, scope, [
    ...namespace2.models.values(),
    ...namespace2.enums.values(),
    ...namespace2.unions.values()
  ]);
  validateClientNamesCore(tcgcContext, scope, adjustOperations(namespace2.operations.values(), moved, movedTo, namespace2));
  for (const item of namespace2.interfaces.values()) {
    validateClientNamesCore(tcgcContext, scope, adjustOperations(item.operations.values(), moved, movedTo, item));
  }
  validateClientNamesCore(tcgcContext, scope, namespace2.interfaces.values());
  validateClientNamesCore(tcgcContext, scope, namespace2.scalars.values());
  validateClientNamesCore(tcgcContext, scope, namespace2.namespaces.values());
  for (const model of namespace2.models.values()) {
    validateClientNamesCore(tcgcContext, scope, model.properties.values());
  }
  for (const item of namespace2.enums.values()) {
    validateClientNamesCore(tcgcContext, scope, item.members.values());
  }
  for (const item of namespace2.unions.values()) {
    validateClientNamesCore(tcgcContext, scope, item.variants.values());
  }
  for (const item of namespace2.namespaces.values()) {
    validateClientNamesPerNamespace(tcgcContext, scope, moved, movedTo, item);
  }
}
function validateClientNamesCore(tcgcContext, scope, items) {
  const duplicateTracker = new DuplicateTracker();
  for (const item of items) {
    const clientName = getClientNameOverride(tcgcContext, item, scope);
    if (clientName !== void 0) {
      const clientNameDecorator = item.decorators.find((x) => x.definition?.name === "@clientName");
      if (clientNameDecorator?.node !== void 0) {
        duplicateTracker.track(clientName, [item, clientNameDecorator.node]);
      }
    } else {
      if (item.name !== void 0 && typeof item.name === "string") {
        duplicateTracker.track(item.name, item);
      }
    }
  }
  reportDuplicateClientNames(tcgcContext.program, duplicateTracker, scope);
}
function reportDuplicateClientNames(program, duplicateTracker, scope) {
  for (const [name, duplicates] of duplicateTracker.entries()) {
    for (const item of duplicates) {
      const scopeStr = scope === AllScopes ? "AllScopes" : scope;
      if (Array.isArray(item)) {
        if (scope === "csharp" && item[0].kind === "Operation") {
          reportDiagnostic(program, {
            code: "duplicate-client-name-warning",
            format: { name, scope: scopeStr },
            target: item[1]
          });
        } else {
          reportDiagnostic(program, {
            code: "duplicate-client-name",
            format: { name, scope: scopeStr },
            target: item[1]
          });
        }
      } else {
        if (scope === "csharp" && item.kind === "Operation") {
          reportDiagnostic(program, {
            code: "duplicate-client-name-warning",
            messageId: "nonDecorator",
            format: { name, scope: scopeStr },
            target: item
          });
        } else {
          reportDiagnostic(program, {
            code: "duplicate-client-name",
            messageId: "nonDecorator",
            format: { name, scope: scopeStr },
            target: item
          });
        }
      }
    }
  }
}

// src/typespec/packages/typespec-client-generator-core/dist/src/validate.js
function $onValidate(program) {
  const tcgcContext = createTCGCContext(program, "@azure-tools/typespec-client-generator-core");
  validatePackage(tcgcContext);
  validateClients(tcgcContext);
  validateMethods(tcgcContext);
  validateHttp(tcgcContext);
  validateTypes(tcgcContext);
}

// src/typespec/packages/typespec-client-generator-core/dist/src/tsp-index.js
var $decorators = {
  "Azure.ClientGenerator.Core": {
    clientName: $clientName,
    convenientAPI: $convenientAPI,
    protocolAPI: $protocolAPI,
    client: $client,
    operationGroup: $operationGroup,
    usage: $usage,
    access: $access,
    override: $override,
    useSystemTextJsonConverter: $useSystemTextJsonConverter,
    clientInitialization: $clientInitialization,
    paramAlias: $paramAlias,
    apiVersion: $apiVersion,
    clientNamespace: $clientNamespace,
    alternateType: $alternateType,
    scope: $scope,
    clientApiVersions: $clientApiVersions,
    deserializeEmptyStringAsNull: $deserializeEmptyStringAsNull,
    responseAsBool: $responseAsBool,
    clientDoc: $clientDoc,
    clientLocation: $clientLocation
  },
  "Azure.ClientGenerator.Core.Legacy": {
    hierarchyBuilding: $legacyHierarchyBuilding,
    flattenProperty: $flattenProperty
  }
};

// virtual:virtual:entry.js
var TypeSpecJSSources = {
  "dist/src/index.js": src_exports,
  "dist/src/tsp-index.js": tsp_index_exports
};
var TypeSpecSources = {
  "package.json": '{"name":"@azure-tools/typespec-client-generator-core","version":"0.60.0","author":"Microsoft Corporation","description":"TypeSpec Data Plane Generation library","homepage":"https://azure.github.io/typespec-azure","readme":"https://github.com/Microsoft/typespec/blob/main/README.md","license":"MIT","repository":{"type":"git","url":"git+https://github.com/Azure/typespec-azure.git"},"bugs":{"url":"https://github.com/Azure/typespec-azure/issues"},"keywords":["typespec","sdk","ClientGenerator"],"main":"dist/src/index.js","tspMain":"./lib/main.tsp","exports":{".":{"types":"./dist/src/index.d.ts","typespec":"./lib/main.tsp","default":"./dist/src/index.js"},"./testing":{"types":"./dist/src/testing/index.d.ts","default":"./dist/src/testing/index.js"}},"type":"module","engines":{"node":">=20.0.0"},"scripts":{"clean":"rimraf ./dist ./temp","build":"npm run gen-extern-signature && tsc -p . && npm run lint-typespec-library","watch":"tsc -p . --watch","gen-extern-signature":"tspd --enable-experimental gen-extern-signature .","lint-typespec-library":"tsp compile . --warn-as-error --import @typespec/library-linter --no-emit","test":"vitest run","test:watch":"vitest -w","test:ui":"vitest --ui","test:ci":"vitest run --coverage  --reporter=junit --reporter=default","lint":"eslint .  --max-warnings=0","lint:fix":"eslint . --fix ","regen-docs":"tspd doc .  --enable-experimental --llmstxt --output-dir ../../website/src/content/docs/docs/libraries/typespec-client-generator-core/reference"},"files":["lib/*.tsp","dist/**","!dist/test/**"],"dependencies":{"change-case":"~5.4.4","pluralize":"^8.0.0","yaml":"~2.8.0"},"peerDependencies":{"@azure-tools/typespec-azure-core":"workspace:^","@typespec/compiler":"workspace:^","@typespec/events":"workspace:^","@typespec/http":"workspace:^","@typespec/openapi":"workspace:^","@typespec/rest":"workspace:^","@typespec/sse":"workspace:^","@typespec/streams":"workspace:^","@typespec/versioning":"workspace:^","@typespec/xml":"workspace:^"},"devDependencies":{"@azure-tools/typespec-azure-core":"workspace:^","@azure-tools/typespec-azure-resource-manager":"workspace:^","@types/node":"~24.3.0","@types/pluralize":"^0.0.33","@typespec/compiler":"workspace:^","@typespec/events":"workspace:^","@typespec/http":"workspace:^","@typespec/library-linter":"workspace:^","@typespec/openapi":"workspace:^","@typespec/prettier-plugin-typespec":"workspace:^","@typespec/rest":"workspace:^","@typespec/sse":"workspace:^","@typespec/streams":"workspace:^","@typespec/tspd":"workspace:^","@typespec/xml":"workspace:^","@vitest/coverage-v8":"^3.1.2","@vitest/ui":"^3.1.2","c8":"^10.1.3","rimraf":"~6.0.1","typescript":"~5.9.2","vitest":"^3.1.2"}}',
  "../../core/packages/compiler/lib/intrinsics.tsp": 'import "../dist/src/lib/intrinsic/tsp-index.js";\nimport "./prototypes.tsp";\n\n// This file contains all the intrinsic types of typespec. Everything here will always be loaded\nnamespace TypeSpec;\n\n/**\n * Represent a byte array\n */\nscalar bytes;\n\n/**\n * A numeric type\n */\nscalar numeric;\n\n/**\n * A whole number. This represent any `integer` value possible.\n * It is commonly represented as `BigInteger` in some languages.\n */\nscalar integer extends numeric;\n\n/**\n * A number with decimal value\n */\nscalar float extends numeric;\n\n/**\n * A 64-bit integer. (`-9,223,372,036,854,775,808` to `9,223,372,036,854,775,807`)\n */\nscalar int64 extends integer;\n\n/**\n * A 32-bit integer. (`-2,147,483,648` to `2,147,483,647`)\n */\nscalar int32 extends int64;\n\n/**\n * A 16-bit integer. (`-32,768` to `32,767`)\n */\nscalar int16 extends int32;\n\n/**\n * A 8-bit integer. (`-128` to `127`)\n */\nscalar int8 extends int16;\n\n/**\n * A 64-bit unsigned integer (`0` to `18,446,744,073,709,551,615`)\n */\nscalar uint64 extends integer;\n\n/**\n * A 32-bit unsigned integer (`0` to `4,294,967,295`)\n */\nscalar uint32 extends uint64;\n\n/**\n * A 16-bit unsigned integer (`0` to `65,535`)\n */\nscalar uint16 extends uint32;\n\n/**\n * A 8-bit unsigned integer (`0` to `255`)\n */\nscalar uint8 extends uint16;\n\n/**\n * An integer that can be serialized to JSON (`\u22129007199254740991 (\u2212(2^53 \u2212 1))` to `9007199254740991 (2^53 \u2212 1)` )\n */\nscalar safeint extends int64;\n\n/**\n * A 64 bit floating point number. (`\xB15.0 \xD7 10^\u2212324` to `\xB11.7 \xD7 10^308`)\n */\nscalar float64 extends float;\n\n/**\n * A 32 bit floating point number. (`\xB11.5 x 10^\u221245` to `\xB13.4 x 10^38`)\n */\nscalar float32 extends float64;\n\n/**\n * A decimal number with any length and precision. This represent any `decimal` value possible.\n * It is commonly represented as `BigDecimal` in some languages.\n */\nscalar decimal extends numeric;\n\n/**\n * A 128-bit decimal number.\n */\nscalar decimal128 extends decimal;\n\n/**\n * A sequence of textual characters.\n */\nscalar string;\n\n/**\n * A date on a calendar without a time zone, e.g. "April 10th"\n */\nscalar plainDate {\n  /**\n   * Create a plain date from an ISO 8601 string.\n   * @example\n   *\n   * ```tsp\n   * const date = plainDate.fromISO("2024-05-06");\n   * ```\n   */\n  init fromISO(value: string);\n}\n\n/**\n * A time on a clock without a time zone, e.g. "3:00 am"\n */\nscalar plainTime {\n  /**\n   * Create a plain time from an ISO 8601 string.\n   * @example\n   *\n   * ```tsp\n   * const time = plainTime.fromISO("12:34");\n   * ```\n   */\n  init fromISO(value: string);\n}\n\n/**\n * An instant in coordinated universal time (UTC)"\n */\nscalar utcDateTime {\n  /**\n   * Create a date from an ISO 8601 string.\n   * @example\n   *\n   * ```tsp\n   * const time = utcDateTime.fromISO("2024-05-06T12:20-12Z");\n   * ```\n   */\n  init fromISO(value: string);\n}\n\n/**\n * A date and time in a particular time zone, e.g. "April 10th at 3:00am in PST"\n */\nscalar offsetDateTime {\n  /**\n   * Create a date from an ISO 8601 string.\n   * @example\n   *\n   * ```tsp\n   * const time = offsetDateTime.fromISO("2024-05-06T12:20-12-0700");\n   * ```\n   */\n  init fromISO(value: string);\n}\n\n/**\n * A duration/time period. e.g 5s, 10h\n */\nscalar duration {\n  /**\n   * Create a duration from an ISO 8601 string.\n   * @example\n   *\n   * ```tsp\n   * const time = duration.fromISO("P1Y1D");\n   * ```\n   */\n  init fromISO(value: string);\n}\n\n/**\n * Boolean with `true` and `false` values.\n */\nscalar boolean;\n\n/**\n * @dev Array model type, equivalent to `Element[]`\n * @template Element The type of the array elements\n */\n@indexer(integer, Element)\nmodel Array<Element> {}\n\n/**\n * @dev Model with string properties where all the properties have type `Property`\n * @template Element The type of the properties\n */\n@indexer(string, Element)\nmodel Record<Element> {}\n',
  "../../core/packages/compiler/lib/prototypes.tsp": "namespace TypeSpec.Prototypes;\n\nextern dec getter(target: unknown);\n\nnamespace Types {\n  interface ModelProperty {\n    @getter type(): unknown;\n  }\n\n  interface Operation {\n    @getter returnType(): unknown;\n    @getter parameters(): unknown;\n  }\n\n  interface Array<TElementType> {\n    @getter elementType(): TElementType;\n  }\n}\n",
  "../../core/packages/compiler/lib/std/main.tsp": '// TypeSpec standard library. Everything in here can be omitted by using `--nostdlib` cli flag or `nostdlib` in the config.\nimport "./types.tsp";\nimport "./decorators.tsp";\nimport "./reflection.tsp";\nimport "./visibility.tsp";\n',
  "../../core/packages/compiler/lib/std/types.tsp": 'namespace TypeSpec;\n\n/**\n * Represent a 32-bit unix timestamp datetime with 1s of granularity.\n * It measures time by the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970.\n */\n@encode("unixTimestamp", int32)\nscalar unixTimestamp32 extends utcDateTime;\n\n/**\n * Represent a URL string as described by https://url.spec.whatwg.org/\n */\nscalar url extends string;\n\n/**\n * Represents a collection of optional properties.\n *\n * @template Source An object whose spread properties are all optional.\n */\n@doc("The template for adding optional properties.")\n@withOptionalProperties\nmodel OptionalProperties<Source> {\n  ...Source;\n}\n\n/**\n * Represents a collection of updateable properties.\n *\n * @template Source An object whose spread properties are all updateable.\n */\n@doc("The template for adding updateable properties.")\n@withUpdateableProperties\nmodel UpdateableProperties<Source> {\n  ...Source;\n}\n\n/**\n * Represents a collection of omitted properties.\n *\n * @template Source An object whose properties are spread.\n * @template Keys The property keys to omit.\n */\n@doc("The template for omitting properties.")\n@withoutOmittedProperties(Keys)\nmodel OmitProperties<Source, Keys extends string> {\n  ...Source;\n}\n\n/**\n * Represents a collection of properties with only the specified keys included.\n *\n * @template Source An object whose properties are spread.\n * @template Keys The property keys to include.\n */\n@doc("The template for picking properties.")\n@withPickedProperties(Keys)\nmodel PickProperties<Source, Keys extends string> {\n  ...Source;\n}\n\n/**\n * Represents a collection of properties with default values omitted.\n *\n * @template Source An object whose spread property defaults are all omitted.\n */\n@withoutDefaultValues\nmodel OmitDefaults<Source> {\n  ...Source;\n}\n\n/**\n * Applies a visibility setting to a collection of properties.\n *\n * @template Source An object whose properties are spread.\n * @template Visibility The visibility to apply to all properties.\n */\n@doc("The template for setting the default visibility of key properties.")\n@withDefaultKeyVisibility(Visibility)\nmodel DefaultKeyVisibility<Source, Visibility extends valueof Reflection.EnumMember> {\n  ...Source;\n}\n',
  "../../core/packages/compiler/lib/std/decorators.tsp": 'import "../../dist/src/lib/tsp-index.js";\n\nusing TypeSpec.Reflection;\n\nnamespace TypeSpec;\n\n/**\n * Typically a short, single-line description.\n * @param summary Summary string.\n *\n * @example\n * ```typespec\n * @summary("This is a pet")\n * model Pet {}\n * ```\n */\nextern dec summary(target: unknown, summary: valueof string);\n\n/**\n * Attach a documentation string. Content support CommonMark markdown formatting.\n * @param doc Documentation string\n * @param formatArgs Record with key value pair that can be interpolated in the doc.\n *\n * @example\n * ```typespec\n * @doc("Represent a Pet available in the PetStore")\n * model Pet {}\n * ```\n */\nextern dec doc(target: unknown, doc: valueof string, formatArgs?: {});\n\n/**\n * Attach a documentation string to describe the successful return types of an operation.\n * If an operation returns a union of success and errors it only describes the success. See `@errorsDoc` for error documentation.\n * @param doc Documentation string\n *\n * @example\n * ```typespec\n * @returnsDoc("Returns doc")\n * op get(): Pet | NotFound;\n * ```\n */\nextern dec returnsDoc(target: Operation, doc: valueof string);\n\n/**\n * Attach a documentation string to describe the error return types of an operation.\n * If an operation returns a union of success and errors it only describes the errors. See `@returnsDoc` for success documentation.\n * @param doc Documentation string\n *\n * @example\n * ```typespec\n * @errorsDoc("Errors doc")\n * op get(): Pet | NotFound;\n * ```\n */\nextern dec errorsDoc(target: Operation, doc: valueof string);\n\n/**\n * Service options.\n */\nmodel ServiceOptions {\n  /**\n   * Title of the service.\n   */\n  title?: string;\n}\n\n/**\n * Mark this namespace as describing a service and configure service properties.\n * @param options Optional configuration for the service.\n *\n * @example\n * ```typespec\n * @service\n * namespace PetStore;\n * ```\n *\n * @example Setting service title\n * ```typespec\n * @service(#{title: "Pet store"})\n * namespace PetStore;\n * ```\n */\nextern dec service(target: Namespace, options?: valueof ServiceOptions);\n\n/**\n * Specify that this model is an error type. Operations return error types when the operation has failed.\n *\n * @example\n * ```typespec\n * @error\n * model PetStoreError {\n *   code: string;\n *   message: string;\n * }\n * ```\n */\nextern dec error(target: Model);\n\n/**\n * Applies a media type hint to a TypeSpec type. Emitters and libraries may choose to use this hint to determine how a\n * type should be serialized. For example, the `@typespec/http` library will use the media type hint of the response\n * body type as a default `Content-Type` if one is not explicitly specified in the operation.\n *\n * Media types (also known as MIME types) are defined by RFC 6838. The media type hint should be a valid media type\n * string as defined by the RFC, but the decorator does not enforce or validate this constraint.\n *\n * Notes: the applied media type is _only_ a hint. It may be overridden or not used at all. Media type hints are\n * inherited by subtypes. If a media type hint is applied to a model, it will be inherited by all other models that\n * `extend` it unless they delcare their own media type hint.\n *\n * @param mediaType The media type hint to apply to the target type.\n *\n * @example create a model that serializes as XML by default\n *\n * ```tsp\n * @mediaTypeHint("application/xml")\n * model Example {\n *   @visibility(Lifecycle.Read)\n *   id: string;\n *\n *   name: string;\n * }\n * ```\n */\nextern dec mediaTypeHint(target: Model | Scalar | Enum | Union, mediaType: valueof string);\n\n// Cannot apply this to the scalar itself. Needs to be applied here so that we don\'t crash nostdlib scenarios\n@@mediaTypeHint(TypeSpec.bytes, "application/octet-stream");\n\n// @@mediaTypeHint(TypeSpec.string "text/plain") -- This is hardcoded in the compiler to avoid circularity\n// between the initialization of the string scalar and the `valueof string` required to call the\n// `mediaTypeHint` decorator.\n\n/**\n * Specify a known data format hint for this string type. For example `uuid`, `uri`, etc.\n * This differs from the `@pattern` decorator which is meant to specify a regular expression while `@format` accepts a known format name.\n * The format names are open ended and are left to emitter to interpret.\n *\n * @param format format name.\n *\n * @example\n * ```typespec\n * @format("uuid")\n * scalar uuid extends string;\n * ```\n */\nextern dec format(target: string | ModelProperty, format: valueof string);\n\n/**\n * Specify the the pattern this string should respect using simple regular expression syntax.\n * The following syntax is allowed: alternations (`|`), quantifiers (`?`, `*`, `+`, and `{ }`), wildcard (`.`), and grouping parentheses.\n * Advanced features like look-around, capture groups, and references are not supported.\n *\n * This decorator may optionally provide a custom validation _message_. Emitters may choose to use the message to provide\n * context when pattern validation fails. For the sake of consistency, the message should be a phrase that describes in\n * plain language what sort of content the pattern attempts to validate. For example, a complex regular expression that\n * validates a GUID string might have a message like "Must be a valid GUID."\n *\n * @param pattern Regular expression.\n * @param validationMessage Optional validation message that may provide context when validation fails.\n *\n * @example\n * ```typespec\n * @pattern("[a-z]+", "Must be a string consisting of only lower case letters and of at least one character.")\n * scalar LowerAlpha extends string;\n * ```\n */\nextern dec pattern(\n  target: string | bytes | ModelProperty,\n  pattern: valueof string,\n  validationMessage?: valueof string\n);\n\n/**\n * Specify the minimum length this string type should be.\n * @param value Minimum length\n *\n * @example\n * ```typespec\n * @minLength(2)\n * scalar Username extends string;\n * ```\n */\nextern dec minLength(target: string | ModelProperty, value: valueof integer);\n\n/**\n * Specify the maximum length this string type should be.\n * @param value Maximum length\n *\n * @example\n * ```typespec\n * @maxLength(20)\n * scalar Username extends string;\n * ```\n */\nextern dec maxLength(target: string | ModelProperty, value: valueof integer);\n\n/**\n * Specify the minimum number of items this array should have.\n * @param value Minimum number\n *\n * @example\n * ```typespec\n * @minItems(1)\n * model Endpoints is string[];\n * ```\n */\nextern dec minItems(target: unknown[] | ModelProperty, value: valueof integer);\n\n/**\n * Specify the maximum number of items this array should have.\n * @param value Maximum number\n *\n * @example\n * ```typespec\n * @maxItems(5)\n * model Endpoints is string[];\n * ```\n */\nextern dec maxItems(target: unknown[] | ModelProperty, value: valueof integer);\n\n/**\n * Specify the minimum value this numeric type should be.\n * @param value Minimum value\n *\n * @example\n * ```typespec\n * @minValue(18)\n * scalar Age is int32;\n * ```\n */\nextern dec minValue(target: numeric | ModelProperty, value: valueof numeric);\n\n/**\n * Specify the maximum value this numeric type should be.\n * @param value Maximum value\n *\n * @example\n * ```typespec\n * @maxValue(200)\n * scalar Age is int32;\n * ```\n */\nextern dec maxValue(target: numeric | ModelProperty, value: valueof numeric);\n\n/**\n * Specify the minimum value this numeric type should be, exclusive of the given\n * value.\n * @param value Minimum value\n *\n * @example\n * ```typespec\n * @minValueExclusive(0)\n * scalar distance is float64;\n * ```\n */\nextern dec minValueExclusive(target: numeric | ModelProperty, value: valueof numeric);\n\n/**\n * Specify the maximum value this numeric type should be, exclusive of the given\n * value.\n * @param value Maximum value\n *\n * @example\n * ```typespec\n * @maxValueExclusive(50)\n * scalar distance is float64;\n * ```\n */\nextern dec maxValueExclusive(target: numeric | ModelProperty, value: valueof numeric);\n\n/**\n * Mark this string as a secret value that should be treated carefully to avoid exposure\n *\n * @example\n * ```typespec\n * @secret\n * scalar Password is string;\n * ```\n */\nextern dec secret(target: string | ModelProperty);\n\n/**\n * Attaches a tag to an operation, interface, or namespace. Multiple `@tag` decorators can be specified to attach multiple tags to a TypeSpec element.\n * @param tag Tag value\n */\nextern dec tag(target: Namespace | Interface | Operation, tag: valueof string);\n\n/**\n * Specifies how a templated type should name their instances.\n * @param name name the template instance should take\n * @param formatArgs Model with key value used to interpolate the name\n *\n * @example\n * ```typespec\n * @friendlyName("{name}List", T)\n * model List<Item> {\n *   value: Item[];\n *   nextLink: string;\n * }\n * ```\n */\nextern dec friendlyName(target: unknown, name: valueof string, formatArgs?: unknown);\n\n/**\n * Mark a model property as the key to identify instances of that type\n * @param altName Name of the property. If not specified, the decorated property name is used.\n *\n * @example\n * ```typespec\n * model Pet {\n *   @key id: string;\n * }\n * ```\n */\nextern dec key(target: ModelProperty, altName?: valueof string);\n\n/**\n * Specify this operation is an overload of the given operation.\n * @param overloadbase Base operation that should be a union of all overloads\n *\n * @example\n * ```typespec\n * op upload(data: string | bytes, @header contentType: "text/plain" | "application/octet-stream"): void;\n * @overload(upload)\n * op uploadString(data: string, @header contentType: "text/plain" ): void;\n * @overload(upload)\n * op uploadBytes(data: bytes, @header contentType: "application/octet-stream"): void;\n * ```\n */\nextern dec overload(target: Operation, overloadbase: Operation);\n\n/**\n * Provide an alternative name for this type when serialized to the given mime type.\n * @param mimeType Mime type this should apply to. The mime type should be a known mime type as described here https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types without any suffix (e.g. `+json`)\n * @param name Alternative name\n *\n * @example\n *\n * ```typespec\n * model Certificate {\n *   @encodedName("application/json", "exp")\n *   @encodedName("application/xml", "expiry")\n *   expireAt: int32;\n * }\n * ```\n *\n * @example Invalid values\n *\n * ```typespec\n * @encodedName("application/merge-patch+json", "exp")\n *              ^ error cannot use subtype\n * ```\n */\nextern dec encodedName(target: unknown, mimeType: valueof string, name: valueof string);\n\n/**\n * Options for `@discriminated` decorator.\n */\nmodel DiscriminatedOptions {\n  /**\n   * How is the discriminated union serialized.\n   * @default object\n   */\n  envelope?: "object" | "none";\n\n  /** Name of the discriminator property */\n  discriminatorPropertyName?: string;\n\n  /** Name of the property envelopping the data */\n  envelopePropertyName?: string;\n}\n\n/**\n * Specify that this union is discriminated.\n * @param options Options to configure the serialization of the discriminated union.\n *\n * @example\n *\n * ```typespec\n * @discriminated\n * union Pet{ cat: Cat, dog: Dog }\n *\n * model Cat { name: string, meow: boolean }\n * model Dog { name: string, bark: boolean }\n * ```\n * Serialized as:\n * ```json\n * {\n *   "kind": "cat",\n *   "value": {\n *     "name": "Whiskers",\n *     "meow": true\n *   }\n * },\n * {\n *   "kind": "dog",\n *   "value": {\n *     "name": "Rex",\n *     "bark": false\n *   }\n * }\n * ```\n *\n * @example Custom property names\n *\n * ```typespec\n * @discriminated(#{discriminatorPropertyName: "dataKind", envelopePropertyName: "data"})\n * union Pet{ cat: Cat, dog: Dog }\n *\n * model Cat { name: string, meow: boolean }\n * model Dog { name: string, bark: boolean }\n * ```\n * Serialized as:\n * ```json\n * {\n *   "dataKind": "cat",\n *   "data": {\n *     "name": "Whiskers",\n *     "meow": true\n *   }\n * },\n * {\n *   "dataKind": "dog",\n *   "data": {\n *     "name": "Rex",\n *     "bark": false\n *   }\n * }\n * ```\n */\nextern dec discriminated(target: Union, options?: valueof DiscriminatedOptions);\n\n/**\n * Specify the property to be used to discriminate this type.\n * @param propertyName The property name to use for discrimination\n *\n * @example\n *\n * ```typespec\n * @discriminator("kind")\n * model Pet{ kind: string }\n *\n * model Cat extends Pet {kind: "cat", meow: boolean}\n * model Dog extends Pet  {kind: "dog", bark: boolean}\n * ```\n */\nextern dec discriminator(target: Model, propertyName: valueof string);\n\n/**\n * Known encoding to use on utcDateTime or offsetDateTime\n */\nenum DateTimeKnownEncoding {\n  /**\n   * RFC 3339 standard. https://www.ietf.org/rfc/rfc3339.txt\n   * Encode to string.\n   */\n  rfc3339: "rfc3339",\n\n  /**\n   * RFC 7231 standard. https://www.ietf.org/rfc/rfc7231.txt\n   * Encode to string.\n   */\n  rfc7231: "rfc7231",\n\n  /**\n   * Encode a datetime to a unix timestamp.\n   * Unix timestamps are represented as an integer number of seconds since the Unix epoch and usually encoded as an int32.\n   */\n  unixTimestamp: "unixTimestamp",\n}\n\n/**\n * Known encoding to use on duration\n */\nenum DurationKnownEncoding {\n  /**\n   * ISO8601 duration\n   */\n  ISO8601: "ISO8601",\n\n  /**\n   * Encode to integer or float\n   */\n  seconds: "seconds",\n}\n\n/**\n * Known encoding to use on bytes\n */\nenum BytesKnownEncoding {\n  /**\n   * Encode to Base64\n   */\n  base64: "base64",\n\n  /**\n   * Encode to Base64 Url\n   */\n  base64url: "base64url",\n}\n\n/**\n * Encoding for serializing arrays\n */\nenum ArrayEncoding {\n  /** Each values of the array is separated by a | */\n  pipeDelimited,\n\n  /** Each values of the array is separated by a <space> */\n  spaceDelimited,\n}\n\n/**\n * Specify how to encode the target type.\n * @param encodingOrEncodeAs Known name of an encoding or a scalar type to encode as(Only for numeric types to encode as string).\n * @param encodedAs What target type is this being encoded as. Default to string.\n *\n * @example offsetDateTime encoded with rfc7231\n *\n * ```tsp\n * @encode("rfc7231")\n * scalar myDateTime extends offsetDateTime;\n * ```\n *\n * @example utcDateTime encoded with unixTimestamp\n *\n * ```tsp\n * @encode("unixTimestamp", int32)\n * scalar myDateTime extends unixTimestamp;\n * ```\n *\n * @example encode numeric type to string\n *\n * ```tsp\n * model Pet {\n *   @encode(string) id: int64;\n * }\n * ```\n */\nextern dec encode(\n  target: Scalar | ModelProperty,\n  encodingOrEncodeAs: (valueof string | EnumMember) | Scalar,\n  encodedAs?: Scalar\n);\n\n/** Options for example decorators */\nmodel ExampleOptions {\n  /** The title of the example */\n  title?: string;\n\n  /** Description of the example */\n  description?: string;\n}\n\n/**\n * Provide an example value for a data type.\n *\n * @param example Example value.\n * @param options Optional metadata for the example.\n *\n * @example\n *\n * ```tsp\n * @example(#{name: "Fluffy", age: 2})\n * model Pet {\n *  name: string;\n *  age: int32;\n * }\n * ```\n */\nextern dec example(\n  target: Model | Enum | Scalar | Union | ModelProperty | UnionVariant,\n  example: valueof unknown,\n  options?: valueof ExampleOptions\n);\n\n/**\n * Operation example configuration.\n */\nmodel OperationExample {\n  /** Example request body. */\n  parameters?: unknown;\n\n  /** Example response body. */\n  returnType?: unknown;\n}\n\n/**\n * Provide example values for an operation\'s parameters and corresponding return type.\n *\n * @param example Example value.\n * @param options Optional metadata for the example.\n *\n * @example\n *\n * ```tsp\n * @opExample(#{parameters: #{name: "Fluffy", age: 2}, returnType: #{name: "Fluffy", age: 2, id: "abc"})\n * op createPet(pet: Pet): Pet;\n * ```\n */\nextern dec opExample(\n  target: Operation,\n  example: valueof OperationExample,\n  options?: valueof ExampleOptions\n);\n\n/**\n * Returns the model with required properties removed.\n */\nextern dec withOptionalProperties(target: Model);\n\n/**\n * Returns the model with any default values removed.\n */\nextern dec withoutDefaultValues(target: Model);\n\n/**\n * Returns the model with the given properties omitted.\n * @param omit List of properties to omit\n */\nextern dec withoutOmittedProperties(target: Model, omit: string | Union);\n\n/**\n * Returns the model with only the given properties included.\n * @param pick List of properties to include\n */\nextern dec withPickedProperties(target: Model, pick: string | Union);\n\n//---------------------------------------------------------------------------\n// Paging\n//---------------------------------------------------------------------------\n\n/**\n * Mark this operation as a `list` operation that returns a paginated list of items.\n */\nextern dec list(target: Operation);\n\n/**\n * Pagination property defining the number of items to skip.\n * @example\n * ```tsp\n * model Page<T> {\n *   @pageItems items: T[];\n * }\n * @list op listPets(@offset skip: int32, @pageSize pageSize: int8): Page<Pet>;\n * ```\n */\nextern dec offset(target: ModelProperty);\n\n/**\n * Pagination property defining the page index.\n *\n * @example\n * ```tsp\n * model Page<T> {\n *   @pageItems items: T[];\n * }\n * @list op listPets(@pageIndex page: int32, @pageSize pageSize: int8): Page<Pet>;\n * ```\n */\nextern dec pageIndex(target: ModelProperty);\n\n/**\n * Specify the pagination parameter that controls the maximum number of items to include in a page.\n *\n * @example\n * ```tsp\n * model Page<T> {\n *   @pageItems items: T[];\n * }\n * @list op listPets(@pageIndex page: int32, @pageSize pageSize: int8): Page<Pet>;\n * ```\n */\nextern dec pageSize(target: ModelProperty);\n\n/**\n * Specify the the property that contains the array of page items.\n *\n * @example\n * ```tsp\n * model Page<T> {\n *   @pageItems items: T[];\n * }\n * @list op listPets(@pageIndex page: int32, @pageSize pageSize: int8): Page<Pet>;\n * ```\n */\nextern dec pageItems(target: ModelProperty);\n\n/**\n * Pagination property defining the token to get to the next page.\n * It MUST be specified both on the request parameter and the response.\n *\n * @example\n * ```tsp\n * model Page<T> {\n *   @pageItems items: T[];\n *   @continuationToken continuationToken: string;\n * }\n * @list op listPets(@continuationToken continuationToken: string): Page<Pet>;\n * ```\n */\nextern dec continuationToken(target: ModelProperty);\n\n/**\n * Pagination property defining a link to the next page.\n *\n * It is expected that navigating to the link will return the same set of responses as the operation that returned the current page.\n *\n * @example\n * ```tsp\n * model Page<T> {\n *   @pageItems items: T[];\n *   @nextLink next: url;\n *   @prevLink prev: url;\n *   @firstLink first: url;\n *   @lastLink last: url;\n * }\n * @list op listPets(): Page<Pet>;\n * ```\n */\nextern dec nextLink(target: ModelProperty);\n\n/**\n * Pagination property defining a link to the previous page.\n *\n * It is expected that navigating to the link will return the same set of responses as the operation that returned the current page.\n *\n * @example\n * ```tsp\n * model Page<T> {\n *   @pageItems items: T[];\n *   @nextLink next: url;\n *   @prevLink prev: url;\n *   @firstLink first: url;\n *   @lastLink last: url;\n * }\n * @list op listPets(): Page<Pet>;\n * ```\n */\nextern dec prevLink(target: ModelProperty);\n\n/**\n * Pagination property defining a link to the first page.\n *\n * It is expected that navigating to the link will return the same set of responses as the operation that returned the current page.\n *\n * @example\n * ```tsp\n * model Page<T> {\n *   @pageItems items: T[];\n *   @nextLink next: url;\n *   @prevLink prev: url;\n *   @firstLink first: url;\n *   @lastLink last: url;\n * }\n * @list op listPets(): Page<Pet>;\n * ```\n */\nextern dec firstLink(target: ModelProperty);\n\n/**\n * Pagination property defining a link to the last page.\n *\n * It is expected that navigating to the link will return the same set of responses as the operation that returned the current page.\n *\n * @example\n * ```tsp\n * model Page<T> {\n *   @pageItems items: T[];\n *   @nextLink next: url;\n *   @prevLink prev: url;\n *   @firstLink first: url;\n *   @lastLink last: url;\n * }\n * @list op listPets(): Page<Pet>;\n * ```\n */\nextern dec lastLink(target: ModelProperty);\n\n//---------------------------------------------------------------------------\n// Debugging\n//---------------------------------------------------------------------------\n\n/**\n * A debugging decorator used to inspect a type.\n * @param text Custom text to log\n */\nextern dec inspectType(target: unknown, text: valueof string);\n\n/**\n * A debugging decorator used to inspect a type name.\n * @param text Custom text to log\n */\nextern dec inspectTypeName(target: unknown, text: valueof string);\n',
  "../../core/packages/compiler/lib/std/reflection.tsp": "namespace TypeSpec.Reflection;\n\nmodel Enum {}\nmodel EnumMember {}\nmodel Interface {}\nmodel Model {}\nmodel ModelProperty {}\nmodel Namespace {}\nmodel Operation {}\nmodel Scalar {}\nmodel Union {}\nmodel UnionVariant {}\nmodel StringTemplate {}\n",
  "../../core/packages/compiler/lib/std/visibility.tsp": '// Copyright (c) Microsoft Corporation\n// Licensed under the MIT license.\n\nimport "../../dist/src/lib/tsp-index.js";\n\nusing TypeSpec.Reflection;\n\nnamespace TypeSpec;\n\n/**\n * Sets the visibility modifiers that are active on a property, indicating that it is only considered to be present\n * (or "visible") in contexts that select for the given modifiers.\n *\n * A property without any visibility settings applied for any visibility class (e.g. `Lifecycle`) is considered to have\n * the default visibility settings for that class.\n *\n * If visibility for the property has already been set for a visibility class (for example, using `@invisible` or\n * `@removeVisibility`), this decorator will **add** the specified visibility modifiers to the property.\n *\n * See: [Visibility](https://typespec.io/docs/language-basics/visibility)\n *\n * The `@typespec/http` library uses `Lifecycle` visibility to determine which properties are included in the request or\n * response bodies of HTTP operations. By default, it uses the following visibility settings:\n *\n * - For the return type of operations, properties are included if they have `Lifecycle.Read` visibility.\n * - For POST operation parameters, properties are included if they have `Lifecycle.Create` visibility.\n * - For PUT operation parameters, properties are included if they have `Lifecycle.Create` or `Lifecycle.Update` visibility.\n * - For PATCH operation parameters, properties are included if they have `Lifecycle.Update` visibility.\n * - For DELETE operation parameters, properties are included if they have `Lifecycle.Delete` visibility.\n * - For GET or HEAD operation parameters, properties are included if they have `Lifecycle.Query` visibility.\n *\n * By default, properties have all five Lifecycle visibility modifiers enabled, so a property is visible in all contexts\n * by default.\n *\n * The default settings may be overridden using the `@returnTypeVisibility` and `@parameterVisibility` decorators.\n *\n * See also: [Automatic visibility](https://typespec.io/docs/libraries/http/operations#automatic-visibility)\n *\n * @param visibilities List of visibilities which apply to this property.\n *\n * @example\n *\n * ```typespec\n * model Dog {\n *   // The service will generate an ID, so you don\'t need to send it.\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   // The service will store this secret name, but won\'t ever return it.\n *   @visibility(Lifecycle.Create, Lifecycle.Update)\n *   secretName: string;\n *\n *   // The regular name has all vi\n *   name: string;\n * }\n * ```\n */\nextern dec visibility(target: ModelProperty, ...visibilities: valueof EnumMember[]);\n\n/**\n * Indicates that a property is not visible in the given visibility class.\n *\n * This decorator removes all active visibility modifiers from the property within\n * the given visibility class, making it invisible to any context that selects for\n * visibility modifiers within that class.\n *\n * @param visibilityClass The visibility class to make the property invisible within.\n *\n * @example\n * ```typespec\n * model Example {\n *   @invisible(Lifecycle)\n *   hidden_property: string;\n * }\n * ```\n */\nextern dec invisible(target: ModelProperty, visibilityClass: Enum);\n\n/**\n * Removes visibility modifiers from a property.\n *\n * If the visibility modifiers for a visibility class have not been initialized,\n * this decorator will use the default visibility modifiers for the visibility\n * class as the default modifier set.\n *\n * @param target The property to remove visibility from.\n * @param visibilities The visibility modifiers to remove from the target property.\n *\n * @example\n * ```typespec\n * model Example {\n *   // This property will have all Lifecycle visibilities except the Read\n *   // visibility, since it is removed.\n *   @removeVisibility(Lifecycle.Read)\n *   secret_property: string;\n * }\n * ```\n */\nextern dec removeVisibility(target: ModelProperty, ...visibilities: valueof EnumMember[]);\n\n/**\n * Removes properties that do not have at least one of the given visibility modifiers\n * active.\n *\n * If no visibility modifiers are supplied, this decorator has no effect.\n *\n * See also: [Automatic visibility](https://typespec.io/docs/libraries/http/operations#automatic-visibility)\n *\n * When using an emitter that applies visibility automatically, it is generally\n * not necessary to use this decorator.\n *\n * @param visibilities List of visibilities that apply to this property.\n *\n * @example\n * ```typespec\n * model Dog {\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   @visibility(Lifecycle.Create, Lifecycle.Update)\n *   secretName: string;\n *\n *   name: string;\n * }\n *\n * // The spread operator will copy all the properties of Dog into DogRead,\n * // and @withVisibility will then remove those that are not visible with\n * // create or update visibility.\n * //\n * // In this case, the id property is removed, and the name and secretName\n * // properties are kept.\n * @withVisibility(Lifecycle.Create, Lifecycle.Update)\n * model DogCreateOrUpdate {\n *   ...Dog;\n * }\n *\n * // In this case the id and name properties are kept and the secretName property\n * // is removed.\n * @withVisibility(Lifecycle.Read)\n * model DogRead {\n *   ...Dog;\n * }\n * ```\n */\nextern dec withVisibility(target: Model, ...visibilities: valueof EnumMember[]);\n\n/**\n * Set the visibility of key properties in a model if not already set.\n *\n * This will set the visibility modifiers of all key properties in the model if the visibility is not already _explicitly_ set,\n * but will not change the visibility of any properties that have visibility set _explicitly_, even if the visibility\n * is the same as the default visibility.\n *\n * Visibility may be set explicitly using any of the following decorators:\n *\n * - `@visibility`\n * - `@removeVisibility`\n * - `@invisible`\n *\n * @param visibility The desired default visibility value. If a key property already has visibility set, it will not be changed.\n */\nextern dec withDefaultKeyVisibility(target: Model, visibility: valueof EnumMember);\n\n/**\n * Declares the visibility constraint of the parameters of a given operation.\n *\n * A parameter or property nested within a parameter will be visible if it has _any_ of the visibilities\n * in the list.\n *\n * It is invalid to call this decorator with no visibility modifiers.\n *\n * @param visibilities List of visibility modifiers that apply to the parameters of this operation.\n */\nextern dec parameterVisibility(target: Operation, ...visibilities: valueof EnumMember[]);\n\n/**\n * Declares the visibility constraint of the return type of a given operation.\n *\n * A property within the return type of the operation will be visible if it has _any_ of the visibilities\n * in the list.\n *\n * It is invalid to call this decorator with no visibility modifiers.\n *\n * @param visibilities List of visibility modifiers that apply to the return type of this operation.\n */\nextern dec returnTypeVisibility(target: Operation, ...visibilities: valueof EnumMember[]);\n\n/**\n * Returns the model with non-updateable properties removed.\n */\nextern dec withUpdateableProperties(target: Model);\n\n/**\n * Declares the default visibility modifiers for a visibility class.\n *\n * The default modifiers are used when a property does not have any visibility decorators\n * applied to it.\n *\n * The modifiers passed to this decorator _MUST_ be members of the target Enum.\n *\n * @param visibilities the list of modifiers to use as the default visibility modifiers.\n */\nextern dec defaultVisibility(target: Enum, ...visibilities: valueof EnumMember[]);\n\n/**\n * A visibility class for resource lifecycle phases.\n *\n * These visibilities control whether a property is visible during the various phases of a resource\'s lifecycle.\n *\n * @example\n * ```typespec\n * model Dog {\n *  @visibility(Lifecycle.Read)\n *  id: int32;\n *\n *  @visibility(Lifecycle.Create, Lifecycle.Update)\n *  secretName: string;\n *\n *  name: string;\n * }\n * ```\n *\n * In this example, the `id` property is only visible during the read phase, and the `secretName` property is only visible\n * during the create and update phases. This means that the server will return the `id` property when returning a `Dog`,\n * but the client will not be able to set or update it. In contrast, the `secretName` property can be set when creating\n * or updating a `Dog`, but the server will never return it. The `name` property has no visibility modifiers and is\n * therefore visible in all phases.\n */\nenum Lifecycle {\n  /**\n   * The property is visible when a resource is being created.\n   */\n  Create,\n\n  /**\n   * The property is visible when a resource is being read.\n   */\n  Read,\n\n  /**\n   * The property is visible when a resource is being updated.\n   */\n  Update,\n\n  /**\n   * The property is visible when a resource is being deleted.\n   */\n  Delete,\n\n  /**\n   * The property is visible when a resource is being queried.\n   *\n   * In HTTP APIs, this visibility applies to parameters of GET or HEAD operations.\n   */\n  Query,\n}\n\n/**\n * A visibility filter, used to specify which properties should be included when\n * using the `withVisibilityFilter` decorator.\n *\n * The filter matches any property with ALL of the following:\n * - If the `any` key is present, the property must have at least one of the specified visibilities.\n * - If the `all` key is present, the property must have all of the specified visibilities.\n * - If the `none` key is present, the property must have none of the specified visibilities.\n */\nmodel VisibilityFilter {\n  any?: EnumMember[];\n  all?: EnumMember[];\n  none?: EnumMember[];\n}\n\n/**\n * Applies the given visibility filter to the properties of the target model.\n *\n * This transformation is recursive, so it will also apply the filter to any nested\n * or referenced models that are the types of any properties in the `target`.\n *\n * If a `nameTemplate` is provided, newly-created type instances will be named according\n * to the template. See the `@friendlyName` decorator for more information on the template\n * syntax. The transformed type is provided as the argument to the template.\n *\n * @param target The model to apply the visibility filter to.\n * @param filter The visibility filter to apply to the properties of the target model.\n * @param nameTemplate The name template to use when renaming new model instances.\n *\n * @example\n * ```typespec\n * model Dog {\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   name: string;\n * }\n *\n * @withVisibilityFilter(#{ all: #[Lifecycle.Read] })\n * model DogRead {\n *  ...Dog\n * }\n * ```\n */\nextern dec withVisibilityFilter(\n  target: Model,\n  filter: valueof VisibilityFilter,\n  nameTemplate?: valueof string\n);\n\n/**\n * Transforms the `target` model to include only properties that are visible during the\n * "Update" lifecycle phase.\n *\n * Any nested models of optional properties will be transformed into the "CreateOrUpdate"\n * lifecycle phase instead of the "Update" lifecycle phase, so that nested models may be\n * fully updated.\n *\n * If a `nameTemplate` is provided, newly-created type instances will be named according\n * to the template. See the `@friendlyName` decorator for more information on the template\n * syntax. The transformed type is provided as the argument to the template.\n *\n * @param target The model to apply the transformation to.\n * @param nameTemplate The name template to use when renaming new model instances.\n *\n * @example\n * ```typespec\n * model Dog {\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   @visibility(Lifecycle.Create, Lifecycle.Update)\n *   secretName: string;\n *\n *   name: string;\n * }\n *\n * @withLifecycleUpdate\n * model DogUpdate {\n *   ...Dog\n * }\n * ```\n */\nextern dec withLifecycleUpdate(target: Model, nameTemplate?: valueof string);\n\n/**\n * A copy of the input model `T` with only the properties that are visible during the\n * "Create" resource lifecycle phase.\n *\n * This transformation is recursive, and will include only properties that have the\n * `Lifecycle.Create` visibility modifier.\n *\n * If a `NameTemplate` is provided, the new model will be named according to the template.\n * The template uses the same syntax as the `@friendlyName` decorator.\n *\n * @template T The model to transform.\n * @template NameTemplate The name template to use for the new model.\n *\n *  * @example\n * ```typespec\n * model Dog {\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   name: string;\n * }\n *\n * // This model has only the `name` field.\n * model CreateDog is Create<Dog>;\n * ```\n */\n@doc("")\n@friendlyName(NameTemplate, T)\n@withVisibilityFilter(#{ all: #[Lifecycle.Create] }, NameTemplate)\nmodel Create<T extends Reflection.Model, NameTemplate extends valueof string = "Create{name}"> {\n  ...T;\n}\n\n/**\n * A copy of the input model `T` with only the properties that are visible during the\n * "Read" resource lifecycle phase.\n *\n * The "Read" lifecycle phase is used for properties returned by operations that read data, like\n * HTTP GET operations.\n *\n * This transformation is recursive, and will include only properties that have the\n * `Lifecycle.Read` visibility modifier.\n *\n * If a `NameTemplate` is provided, the new model will be named according to the template.\n * The template uses the same syntax as the `@friendlyName` decorator.\n *\n * @template T The model to transform.\n * @template NameTemplate The name template to use for the new model.\n *\n *  * @example\n * ```typespec\n * model Dog {\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   @visibility(Lifecycle.Create, Lifecycle.Update)\n *   secretName: string;\n *\n *   name: string;\n * }\n *\n * // This model has the `id` and `name` fields, but not `secretName`.\n * model ReadDog is Read<Dog>;\n * ```\n */\n@doc("")\n@friendlyName(NameTemplate, T)\n@withVisibilityFilter(#{ all: #[Lifecycle.Read] }, NameTemplate)\nmodel Read<T extends Reflection.Model, NameTemplate extends valueof string = "Read{name}"> {\n  ...T;\n}\n\n/**\n * A copy of the input model `T` with only the properties that are visible during the\n * "Update" resource lifecycle phase.\n *\n * The "Update" lifecycle phase is used for properties passed as parameters to operations\n * that update data, like HTTP PATCH operations.\n *\n * This transformation will include only the properties that have the `Lifecycle.Update`\n * visibility modifier, and the types of all properties will be replaced with the\n * equivalent `CreateOrUpdate` transformation.\n *\n * If a `NameTemplate` is provided, the new model will be named according to the template.\n * The template uses the same syntax as the `@friendlyName` decorator.\n *\n * @template T The model to transform.\n * @template NameTemplate The name template to use for the new model.\n *\n *  * @example\n * ```typespec\n * model Dog {\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   @visibility(Lifecycle.Create, Lifecycle.Update)\n *   secretName: string;\n *\n *   name: string;\n * }\n *\n * // This model will have the `secretName` and `name` fields, but not the `id` field.\n * model UpdateDog is Update<Dog>;\n * ```\n */\n@doc("")\n@friendlyName(NameTemplate, T)\n@withLifecycleUpdate(NameTemplate)\nmodel Update<T extends Reflection.Model, NameTemplate extends valueof string = "Update{name}"> {\n  ...T;\n}\n\n/**\n * A copy of the input model `T` with only the properties that are visible during the\n * "Create" or "Update" resource lifecycle phases.\n *\n * The "CreateOrUpdate" lifecycle phase is used by default for properties passed as parameters to operations\n * that can create _or_ update data, like HTTP PUT operations.\n *\n * This transformation is recursive, and will include only properties that have the\n * `Lifecycle.Create` or `Lifecycle.Update` visibility modifier.\n *\n * If a `NameTemplate` is provided, the new model will be named according to the template.\n * The template uses the same syntax as the `@friendlyName` decorator.\n *\n * @template T The model to transform.\n * @template NameTemplate The name template to use for the new model.\n *\n *  * @example\n * ```typespec\n * model Dog {\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   @visibility(Lifecycle.Create)\n *   immutableSecret: string;\n *\n *   @visibility(Lifecycle.Create, Lifecycle.Update)\n *   secretName: string;\n *\n *   name: string;\n * }\n *\n * // This model will have the `immutableSecret`, `secretName`, and `name` fields, but not the `id` field.\n * model CreateOrUpdateDog is CreateOrUpdate<Dog>;\n * ```\n */\n@doc("")\n@friendlyName(NameTemplate, T)\n@withVisibilityFilter(#{ any: #[Lifecycle.Create, Lifecycle.Update] }, NameTemplate)\nmodel CreateOrUpdate<\n  T extends Reflection.Model,\n  NameTemplate extends valueof string = "CreateOrUpdate{name}"\n> {\n  ...T;\n}\n\n/**\n * A copy of the input model `T` with only the properties that are visible during the\n * "Delete" resource lifecycle phase.\n *\n * The "Delete" lifecycle phase is used for properties passed as parameters to operations\n * that delete data, like HTTP DELETE operations.\n *\n * This transformation is recursive, and will include only properties that have the\n * `Lifecycle.Delete` visibility modifier.\n *\n * If a `NameTemplate` is provided, the new model will be named according to the template.\n * The template uses the same syntax as the `@friendlyName` decorator.\n *\n * @template T The model to transform.\n * @template NameTemplate The name template to use for the new model.\n *\n *  * @example\n * ```typespec\n * model Dog {\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   // Set when the Dog is removed from our data store. This happens when the\n *   // Dog is re-homed to a new owner.\n *   @visibility(Lifecycle.Delete)\n *   nextOwner: string;\n *\n *   name: string;\n * }\n *\n * // This model will have the `nextOwner` and `name` fields, but not the `id` field.\n * model DeleteDog is Delete<Dog>;\n * ```\n */\n@doc("")\n@friendlyName(NameTemplate, T)\n@withVisibilityFilter(#{ all: #[Lifecycle.Delete] }, NameTemplate)\nmodel Delete<T extends Reflection.Model, NameTemplate extends valueof string = "Delete{name}"> {\n  ...T;\n}\n\n/**\n * A copy of the input model `T` with only the properties that are visible during the\n * "Query" resource lifecycle phase.\n *\n * The "Query" lifecycle phase is used for properties passed as parameters to operations\n * that read data, like HTTP GET or HEAD operations. This should not be confused for\n * the `@query` decorator, which specifies that the property is transmitted in the\n * query string of an HTTP request.\n *\n * This transformation is recursive, and will include only properties that have the\n * `Lifecycle.Query` visibility modifier.\n *\n * If a `NameTemplate` is provided, the new model will be named according to the template.\n * The template uses the same syntax as the `@friendlyName` decorator.\n *\n * @template T The model to transform.\n * @template NameTemplate The name template to use for the new model.\n *\n *  * @example\n * ```typespec\n * model Dog {\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   // When getting information for a Dog, you can set this field to true to include\n *   // some extra information about the Dog\'s pedigree that is normally not returned.\n *   // Alternatively, you could just use a separate option parameter to get this\n *   // information.\n *   @visibility(Lifecycle.Query)\n *   includePedigree?: boolean;\n *\n *   name: string;\n *\n *   // Only included if `includePedigree` is set to true in the request.\n *   @visibility(Lifecycle.Read)\n *   pedigree?: string;\n * }\n *\n * // This model will have the `includePedigree` and `name` fields, but not `id` or `pedigree`.\n * model QueryDog is Query<Dog>;\n * ```\n */\n@doc("")\n@friendlyName(NameTemplate, T)\n@withVisibilityFilter(#{ all: #[Lifecycle.Query] }, NameTemplate)\nmodel Query<T extends Reflection.Model, NameTemplate extends valueof string = "Query{name}"> {\n  ...T;\n}\n',
  "lib/main.tsp": 'import "./decorators.tsp";\nimport "./augmentCore.tsp";\nimport "./legacy.tsp";\nimport "../dist/src/tsp-index.js";\n',
  "lib/decorators.tsp": 'using Reflection;\n\nnamespace Azure.ClientGenerator.Core;\n\n/**\n * Changes the name of a client, method, parameter, union, model, enum, model property, etc. generated in the client SDK.\n * @param target The type you want to rename.\n * @param rename The rename you want applied to the object.\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n *\n * @example Rename a model\n * ```typespec\n * @clientName("RenamedModel")\n * model TestModel {\n *  prop: string;\n * }\n * ```\n *\n * @example Rename a model property\n * ```typespec\n * model TestModel {\n *  @clientName("renamedProp")\n *  prop: string;\n * }\n * ```\n *\n * @example Rename a parameter\n * ```typespec\n * op example(@clientName("renamedParameter") parameter: string): void;\n * ```\n *\n * @example Rename an operation\n * ```typespec\n * @clientName("nameInClient")\n * op example(): void;\n * ```\n *\n * @example Rename an operation for different language emitters\n * ```typespec\n * @clientName("nameForJava", "java")\n * @clientName("name_for_python", "python")\n * @clientName("nameForCsharp", "csharp")\n * @clientName("nameForJavascript", "javascript")\n * op example(): void;\n * ```\n *\n */\nextern dec clientName(target: unknown, rename: valueof string, scope?: valueof string);\n\n/**\n * Whether you want to generate an operation as a convenient method.\n * @param target The target operation.\n * @param flag Whether to generate the operation as a convenience method or not.\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n *\n * @example\n * ```typespec\n * @convenientAPI(false)\n * op test: void;\n * ```\n */\nextern dec convenientAPI(target: Operation, flag?: valueof boolean, scope?: valueof string);\n\n/**\n * Whether you want to generate an operation as a protocol method.\n * @param target The target operation.\n * @param flag Whether to generate the operation as a protocol method or not.\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n *\n * @example\n * ```typespec\n * @protocolAPI(false)\n * op test: void;\n * ```\n */\nextern dec protocolAPI(target: Operation, flag?: valueof boolean, scope?: valueof string);\n\n/**\n * Define the client generated in the client SDK.\n * If there is any `@client` definition or `@operationGroup` definition, then each `@client` is a root client and each `@operationGroup` is a sub client with hierarchy.\n * This decorator cannot be used along with `@clientLocation`. This decorator cannot be used as augmentation.\n * @param target The target namespace or interface that you want to define as a client.\n * @param options Optional configuration for the service.\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n *\n * @example Basic client definition\n * ```typespec\n * namespace MyService {}\n *\n * @client({service: MyService})\n * interface MyInterface {}\n * ```\n *\n * @example Changing client name\n * ```typespec\n * namespace MyService {}\n *\n * @client({service: MyService, name: "MySpecialClient"})\n * interface MyInterface {}\n * ```\n *\n * @example\n */\nextern dec client(target: Namespace | Interface, options?: ClientOptions, scope?: valueof string);\n\n/**\n * Client customization options.\n */\nmodel ClientOptions {\n  /**\n   * The service that this client is generated for. If not specified, TCGC will look up the first parent namespace decorated with `@service` for the target.\n   * The namespace should be decorated with `@service`.\n   */\n  service?: Namespace;\n\n  /**\n   * The name of the client. If not specified, the default name will be `<Name of the target>Client`.\n   */\n  name?: string;\n}\n\n/**\n * Define the sub client generated in the client SDK.\n * If there is any `@client` definition or `@operationGroup` definition, then each `@client` is a root client and each `@operationGroup` is a sub client with hierarchy.\n * This decorator cannot be used along with `@clientLocation`. This decorator cannot be used as augmentation.\n * @param target The target namespace or interface that you want to define as a sub client.\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n *\n * @example\n * ```typespec\n * @operationGroup\n * interface MyInterface{}\n * ```\n */\nextern dec operationGroup(target: Namespace | Interface, scope?: valueof string);\n\n/**\n * Usage value.\n */\nenum Usage {\n  /**\n   * Used in request\n   */\n  input: 2,\n\n  /**\n   * Used in response\n   */\n  output: 4,\n\n  /**\n   * Used with JSON content type\n   */\n  json: 256,\n\n  /**\n   * Used with XML content type\n   */\n  xml: 512,\n}\n\n/**\n * Add usage for models/enums.\n * A model/enum\'s default usage info is always calculated by the operations that use it.\n * You can use this decorator to add additional usage info.\n * When setting usage for namespaces,\n * the usage info will be propagated to the models defined in the namespace.\n * If the model has a usage override, the model override takes precedence.\n * For example, with operation definition `op test(): OutputModel`,\n * the model `OutputModel` has default usage `Usage.output`.\n * After adding decorator `@@usage(OutputModel, Usage.input | Usage.json)`,\n * the final usage result for `OutputModel` is `Usage.input | Usage.output | Usage.json`.\n * The usage info for models will be propagated to models\' properties,\n * parent models, discriminated sub models.\n * @param target The target type you want to extend usage.\n * @param value The usage info you want to add for this model. It can be a single value of `Usage` enum value or a combination of `Usage` enum values using bitwise OR.\n * For example, `Usage.input | Usage.output | Usage.json`.\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n *\n * @example Add usage for model\n * ```typespec\n * op test(): OutputModel;\n *\n * // The resolved usage  for `OutputModel` is `Usage.input | Usage.output | Usage.json`\n * @usage(Usage.input | Usage.json)\n * model OutputModel {\n *   prop: string\n * }\n * ```\n *\n * @example Propagation of usage, all usage will be propagated to the parent model, discriminated sub models, and model properties.\n * ```typespec\n * // The resolved usage  for `Fish` is `Usage.input | Usage.output | Usage.json`\n * @discriminator("kind")\n * model Fish {\n *   age: int32;\n * }\n *\n * // The resolved usage  for `Shark` is `Usage.input | Usage.output | Usage.json`\n * @discriminator("sharktype")\n * @usage(Usage.input | Usage.json)\n * model Shark extends Fish {\n *   kind: "shark";\n *   origin: Origin;\n * }\n *\n * // The resolved usage  for `Salmon` is `Usage.output | Usage.json`\n * model Salmon extends Fish {\n *   kind: "salmon";\n * }\n *\n * // The resolved usage  for `SawShark` is `Usage.input | Usage.output | Usage.json`\n * model SawShark extends Shark {\n *   sharktype: "saw";\n * }\n *\n * // The resolved usage  for `Origin` is `Usage.input | Usage.output | Usage.json`\n * model Origin {\n *   country: string;\n *   city: string;\n *   manufacture: string;\n * }\n *\n * @get\n * op getModel(): Fish;\n * ```\n */\nextern dec usage(\n  target: Model | Enum | Union | Namespace,\n  value: EnumMember | Union,\n  scope?: valueof string\n);\n\n/**\n * Access value.\n */\nenum Access {\n  /**\n   * Open to user\n   */\n  public: "public",\n\n  /**\n   * Hide from user\n   */\n  internal: "internal",\n}\n\n/**\n * Override access for operations, models, enums and model properties.\n * When setting access for namespaces,\n * the access info will be propagated to the models and operations defined in the namespace.\n * If the model has an access override, the model override takes precedence.\n * When setting access for an operation,\n * it will influence the access info for models/enums that are used by this operation.\n * Models/enums that are used in any operations with `@access(Access.public)` will be set to access "public"\n * Models/enums that are only used in operations with `@access(Access.internal)` will be set to access "internal".\n * The access info for models will be propagated to models\' properties,\n * parent models, discriminated sub models.\n * The override access should not be narrower than the access calculated by operation,\n * and different override access should not conflict with each other,\n * otherwise a warning will be added to the diagnostics list.\n * Model property\'s access will default to public unless there is an override.\n * @param target The target type you want to override access info.\n * @param value The access info you want to set for this model or operation. It should be one of the `Access` enum values, either `Access.public` or `Access.internal`.\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n *\n * @example Set access\n * ```typespec\n * // Access.internal\n * @access(Access.internal)\n * model ModelToHide {\n *   prop: string;\n * }\n * // Access.internal\n * @access(Access.internal)\n * op test: void;\n * ```\n * @example Access propagation\n * ```typespec\n * // Access.internal\n * @discriminator("kind")\n * model Fish {\n *   age: int32;\n * }\n *\n * // Access.internal\n * @discriminator("sharktype")\n * model Shark extends Fish {\n *   kind: "shark";\n *   origin: Origin;\n * }\n *\n * // Access.internal\n * model Salmon extends Fish {\n *   kind: "salmon";\n * }\n *\n * // Access.internal\n * model SawShark extends Shark {\n *   sharktype: "saw";\n * }\n *\n * // Access.internal\n * model Origin {\n *   country: string;\n *   city: string;\n *   manufacture: string;\n * }\n *\n * // Access.internal\n * @get\n * @access(Access.internal)\n * op getModel(): Fish;\n * ```\n * @example Access influence from operation\n * ```typespec\n * // Access.internal\n * model Test1 {\n * }\n *\n * // Access.internal\n * @access(Access.internal)\n * @route("/func1")\n * op func1(\n *   @body body: Test1\n * ): void;\n *\n * // Access.public\n * model Test2 {\n * }\n *\n * // Access.public\n * @route("/func2")\n * op func2(\n *   @body body: Test2\n * ): void;\n *\n * // Access.public\n * model Test3 {\n * }\n *\n * // Access.public\n * @access(Access.public)\n * @route("/func3")\n * op func3(\n *   @body body: Test3\n * ): void;\n *\n * // Access.public\n * model Test4 {\n * }\n *\n * // Access.internal\n * @access(Access.internal)\n * @route("/func4")\n * op func4(\n *   @body body: Test4\n * ): void;\n *\n * // Access.public\n * @route("/func5")\n * op func5(\n *   @body body: Test4\n * ): void;\n *\n * // Access.public\n * model Test5 {\n * }\n *\n * // Access.internal\n * @access(Access.internal)\n * @route("/func6")\n * op func6(\n *   @body body: Test5\n * ): void;\n *\n * // Access.public\n * @route("/func7")\n * op func7(\n *   @body body: Test5\n * ): void;\n *\n * // Access.public\n * @access(Access.public)\n * @route("/func8")\n * op func8(\n *   @body body: Test5\n * ): void;\n * ```\n */\nextern dec access(\n  target: ModelProperty | Model | Operation | Enum | Union | Namespace,\n  value: EnumMember,\n  scope?: valueof string\n);\n\n/**\n * Customize a method\'s signature in the generated client SDK.\n * Currently, only parameter signature customization is supported.\n * This decorator allows you to specify a different method signature for the client SDK than the original definition.\n * @param target: The target operation that you want to override.\n * @param override: The override method definition that specifies the exact client method you want\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n *\n * @example Customize parameters into an option bag\n * ```typespec\n * // main.tsp\n * @service\n * namespace MyService;\n *\n * op myOperation(foo: string, bar: string): void; // by default, we generate the method signature as `op myOperation(foo: string, bar: string)`;\n *\n * // client.tsp\n * namespace MyCustomizations;\n *\n * model Params {\n *  foo: string;\n *  bar: string;\n * }\n *\n * op myOperationCustomization(params: MyService.Params): void;\n *\n * @@override(MyService.myOperation, myOperationCustomization); // method signature is now `op myOperation(params: Params)`\n * ```\n *\n * @example Customize a parameter to be required\n * ```typespec\n * // main.tsp\n * @service\n * namespace MyService;\n *\n * op myOperation(foo: string, bar?: string): void; // by default, we generate the method signature as `op myOperation(foo: string, bar?: string)`;\n *\n * // client.tsp\n * namespace MyCustomizations;\n *\n * op myOperationCustomization(foo: string, bar: string): void;\n *\n * @@override(MyService.myOperation, myOperationCustomization)\n *\n * // method signature is now `op myOperation(params: Params)` just for csharp // method signature is now `op myOperation(foo: string, bar: string)`\n * ```\n */\nextern dec override(target: Operation, override: Operation, scope?: valueof string);\n\n/**\n * Whether a model needs the custom JSON converter, this is only used for backward compatibility for csharp.\n * @param target The target model that you want to set the custom JSON converter.\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n *\n * @example\n * ```typespec\n * @useSystemTextJsonConverter\n * model MyModel {\n *   prop: string;\n * }\n * ```\n */\nextern dec useSystemTextJsonConverter(target: Model, scope?: valueof string);\n\n/**\n * InitializedBy value.\n */\nenum InitializedBy {\n  /**\n   * The client could be initialized individually.\n   */\n  individually: 1,\n\n  /**\n   * The client could be initialized by parent client.\n   */\n  parent: 2,\n}\n\n/**\n * Allows customization of how clients are initialized in the generated SDK.\n * By default, the root client is initialized independently, while sub clients are initialized through their parent client.\n * Initialization parameters typically include endpoint, credential, and API version.\n * With `@clientInitialization` decorator, you can elevate operation level parameters to client level, and set how the client is initialized.\n * This decorator can be combined with `@paramAlias` decorator to change the parameter name in client initialization.\n * @param target The target client that you want to customize client initialization for.\n * @param options The options for client initialization. You can use `ClientInitializationOptions` model to set the options.\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n *\n * @example Add client initialization parameters\n * ```typespec\n * // main.tsp\n * namespace MyService;\n *\n * op upload(blobName: string): void;\n * op download(blobName: string): void;\n *\n * // client.tsp\n * namespace MyCustomizations;\n * model MyServiceClientOptions {\n *   blobName: string;\n * }\n *\n * @@clientInitialization(MyService, {parameters: MyServiceClientOptions})\n * // The generated client will have `blobName` in its initialization method. We will also\n * // elevate the existing `blobName` parameter from method level to client level.\n * ```\n */\nextern dec clientInitialization(\n  target: Namespace | Interface,\n  options: ClientInitializationOptions,\n  scope?: valueof string\n);\n\n/**\n * Client initialization customization options.\n */\nmodel ClientInitializationOptions {\n  /**\n   * Redefine the client initialization parameters you would like to add to the client. All the model properties should have corresponding operation level parameters.\n   * By default, we apply endpoint, credential, and API version parameters. If you specify a parameters model, we will append the properties of the model to the parameters list of the client initialization.\n   */\n  parameters?: Model;\n\n  /**\n   * Determines how the client can be initialized. Use `InitializedBy` enum to set the value. The value can be `InitializedBy.individually`, `InitializedBy.parent` or `InitializedBy.individually | InitializedBy.parent`.\n   */\n  initializedBy?: EnumMember | Union;\n}\n\n/**\n * Alias the name of a client parameter to a different name. This permits you to have a different name for the parameter in client initialization and the original parameter in the operation.\n * @param target The target model property that you want to alias.\n * @param paramAlias The alias name you want to apply to the target model property.\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n *\n * @example Elevate an operation parameter to client level and alias it to a different name\n * ```typespec\n * // main.tsp\n * namespace MyService;\n *\n * op upload(blobName: string): void;\n *\n * // client.tsp\n * namespace MyCustomizations;\n * model MyServiceClientOptions {\n *   blob: string;\n * }\n *\n * @@clientInitialization(MyService, MyServiceClientOptions)\n * @@paramAlias(MyServiceClientOptions.blob, "blobName")\n *\n * // The generated client will have `blobName` in it. We will also\n * // elevate the existing `blob` parameter to the client level.\n * ```\n */\nextern dec paramAlias(target: ModelProperty, paramAlias: valueof string, scope?: valueof string);\n\n/**\n * Changes the namespace of a client, model, enum or union generated in the client SDK.\n * By default, the client namespace for them will follow the TypeSpec namespace.\n * @param target The type you want to change the namespace for.\n * @param rename The rename you want applied to the object\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n *\n * @example Change a namespace to a different name\n * ```typespec\n * @clientNamespace("ContosoClient")\n * namespace Contoso;\n * ```\n *\n * @example Move a model to a different namespace\n * ```typespec\n * @clientNamespace("ContosoClient.Models")\n * model Test {\n *  prop: string;\n * }\n * ```\n */\nextern dec clientNamespace(\n  target: Namespace | Interface | Model | Enum | Union,\n  rename: valueof string,\n  scope?: valueof string\n);\n\n/**\n * Set an alternate type for a model property, Scalar, or function parameter. Note that `@encode` will be overridden by the one defined in the alternate type.\n * When the source type is `Scalar`, the alternate type must be `Scalar`.\n * @param target The source type to which the alternate type will be applied.\n * @param alternate The alternate type to apply to the target.\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n * @example Change a model property to a different type\n * ```typespec\n * model Foo {\n *    date: utcDateTime;\n * }\n * @@alternateType(Foo.date, string);\n * ```\n *\n * @example Change a Scalar type to a different type\n * ```typespec\n * scalar storageDateTime extends utcDateTime;\n * @@alternateType(storageDateTime, string, "python");\n * ```\n *\n * @example Change a function parameter to a different type\n * ```typespec\n * op test(@param @alternateType(string) date: utcDateTime): void;\n * ```\n *\n * @example Change a model property to a different type with language specific alternate type\n * ```typespec\n * model Test {\n *   @alternateType(unknown)\n *   thumbprint?: string;\n *\n *   @alternateType(AzureLocation[], "csharp")\n *   locations: string[];\n * }\n * ```\n */\nextern dec alternateType(\n  target: ModelProperty | Scalar,\n  alternate: unknown,\n  scope?: valueof string\n);\n\n/**\n * Define the scope of an operation.\n * By default, the operation will be applied to all language emitters.\n * This decorator allows you to omit the operation from certain languages or apply it to specific languages.\n * @param target The target operation that you want to scope.\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n *\n * @example Omit an operation from a specific language\n * ```typespec\n * @scope("!csharp")\n * op test: void;\n * ```\n *\n * @example Apply an operation to specific languages\n * ```typespec\n * @scope("go")\n * op test: void;\n * ```\n */\nextern dec scope(target: Operation, scope?: valueof string);\n\n/**\n * Specify whether a parameter is an API version parameter or not.\n * By default, we detect an API version parameter by matching the parameter name with `api-version` or `apiversion`, or if the type is referenced by the `@versioned` decorator.\n * Since API versions are a client parameter, we will also elevate this parameter up onto the client.\n * This decorator allows you to explicitly specify whether a parameter should be treated as an API version parameter or not.\n * @param target The target parameter that you want to mark as an API version parameter.\n * @param value If true, we will treat this parameter as an api-version parameter. If false, we will not. Default is true.\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n *\n * @example Mark a parameter as an API version parameter\n * ```typespec\n * namespace Contoso;\n *\n * op test(\n *   @apiVersion\n *   @header("x-ms-version")\n *   version: string\n * ): void;\n * ```\n *\n * @example Mark a parameter as not presenting an API version parameter\n * ```typespec\n * namespace Contoso;\n * op test(\n *   @apiVersion(false)\n *   @query\n *   api-version: string\n * ): void;\n * ```\n */\nextern dec apiVersion(target: ModelProperty, value?: valueof boolean, scope?: valueof string);\n\n/**\n * Specify additional API versions that the client can support. These versions should include those defined by the service\'s versioning configuration.\n * This decorator is useful for extending the API version enum exposed by the client.\n * It is particularly beneficial when generating a complete API version enum without requiring the entire specification to be annotated with versioning decorators, as the generation process does not depend on versioning details.\n * @param target The target client for which you want to define additional API versions.\n * @param value If true, we will treat this parameter as an api-version parameter. If false, we will not. Default is true.\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n *\n * @example Add additional API versions to a client\n * ```typespec\n * // main.tsp\n * @versioned(Versions)\n * namespace Contoso {\n *  enum Versions { v4, v5 }\n * }\n *\n * // client.tsp\n *\n * enum ClientApiVersions { v1, v2, v3, ...Contoso.Versions }\n *\n * @@clientApiVersions(Contoso, ClientApiVersions)\n * ```\n */\nextern dec clientApiVersions(target: Namespace, value: Enum, scope?: valueof string);\n\n/**\n * Indicates that a model property of type `string` or a `Scalar` type derived from `string` should be deserialized as `null` when its value is an empty string (`""`).\n * @param target The target type that you want to apply this deserialization behavior to.\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n *\n * @example\n * ```typespec\n *\n * model MyModel {\n *   scalar stringlike extends string;\n *\n *   @deserializeEmptyStringAsNull\n *   prop: string;\n *\n *   @deserializeEmptyStringAsNull\n *   prop: stringlike;\n * }\n * ```\n */\nextern dec deserializeEmptyStringAsNull(target: ModelProperty, scope?: valueof string);\n\n/**\n * Indicates that a HEAD operation should be modeled as Response<bool>.\n * 404 will not raise an error, instead the service method will return `false`.\n * 2xx will return `true`. Everything else will still raise an error.\n * @param target The target operation that you want to apply this behavior to.\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n *\n * @example\n * ```typespec\n * @responseAsBool\n * @head\n * op headOperation(): void;\n * ```\n */\nextern dec responseAsBool(target: Operation, scope?: valueof string);\n\n/**\n * Change the operation location in the client. If the target client is not defined, use `string` to indicate a new client name. For this usage, the decorator cannot be used along with `@client` or `@operationGroup` decorators.\n * Change the parameter location to operation or client. For this usage, the decorator cannot be used in the parameter defined in  `@clientInitialization` decorator.\n * @param source The operation to change location for.\n * @param target The target `Namespace`, `Interface` or a string which can indicate the client.\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n * \n * @example Move to existing sub client\n * ```typespec\n * @service\n * namespace MoveToExistingSubClient;\n * \n * interface UserOperations {\n *   @route("/user")\n *   @get\n *   getUser(): void;\n\n *   @route("/user")\n *   @delete\n *   @clientLocation(AdminOperations)\n *   deleteUser(): void; // This operation will be moved to AdminOperations sub client.\n * }\n\n * interface AdminOperations {\n *   @route("/admin")\n *   @get\n *   getAdminInfo(): void;\n * }\n * ```\n * \n * @example Move to new sub client\n * ```typespec\n * @service\n * namespace MoveToNewSubClient;\n * \n * interface ProductOperations {\n *   @route("/products")\n *   @get\n *   listProducts(): void;\n *\n *   @route("/products/archive")\n *   @post\n *   @clientLocation("ArchiveOperations")\n *   archiveProduct(): void; // This operation will be moved to a new sub client named ArchiveOperations.\n * }\n * ```\n * \n * @example Move operation to root client\n * ```typespec\n * @service\n * namespace MoveToRootClient;\n * \n * interface ResourceOperations {\n *   @route("/resource")\n *   @get\n *   getResource(): void;\n * \n *   @route("/health")\n *   @get\n *   @clientLocation(MoveToRootClient)\n *   getHealthStatus(): void; // This operation will be moved to the root client of MoveToRootClient namespace.\n * }\n *\n * ```\n *\n * @example Move parameter from operation to client\n * ```typespec\n * @service\n * namespace MyClient;\n * \n * getHealthStatus(\n *   @clientLocation(MyClient) // This parameter will be moved to the `.clientInitialization` parameters of `MyClient`. It will not appear on the operation-level.\n *   clientId: string\n * ): void;\n * ```\n * \n * @example Move parameter from client to operation\n * ```typespec\n * // client.tsp\n * \n * @@clientLocation(CommonTypes.SubscriptionIdParameter.subscriptionId, get); // This will keep the `subscriptionId` parameter on the operation level instead of applying TCGC\'s default logic of elevating `subscriptionId` to client.\n * ```\n */\nextern dec clientLocation(\n  source: Operation | ModelProperty,\n  target: Interface | Namespace | Operation | (valueof string),\n  scope?: valueof string\n);\n\n/**\n * Defines how client documentation should be applied\n */\nenum DocumentationMode {\n  /**\n   * Append client documentation to the existing doc\n   */\n  append: "append",\n\n  /**\n   * Replace the existing doc with client documentation\n   */\n  replace: "replace",\n}\n\n/**\n * Override documentation for a type in client libraries. This allows you to\n * provide client-specific documentation that differs from the original documentation.\n * @param target The target type (operation, model, enum, etc.) for which you want to apply client-specific documentation.\n * @param documentation The client-specific documentation to apply\n * @param mode Specifies how to apply the documentation (append or replace)\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n *\n * @example Replacing documentation\n * ```typespec\n * @doc("This is service documentation")\n * @clientDoc("This is client-specific documentation", DocumentationMode.replace)\n * op myOperation(): void;\n * ```\n *\n * @example Appending documentation\n * ```typespec\n * @doc("This is service documentation.")\n * @clientDoc("This additional note is for client libraries only.", DocumentationMode.append)\n * model MyModel {\n *   prop: string;\n * }\n * ```\n *\n * @example Language-specific documentation\n * ```typespec\n * @doc("This is service documentation")\n * @clientDoc("Python-specific documentation", DocumentationMode.replace, "python")\n * @clientDoc("JavaScript-specific documentation", DocumentationMode.replace, "javascript")\n * op myOperation(): void;\n * ```\n */\nextern dec clientDoc(\n  target: unknown,\n  documentation: valueof string,\n  mode: EnumMember,\n  scope?: valueof string\n);\n',
  "lib/augmentCore.tsp": "",
  "lib/legacy.tsp": 'using Reflection;\n\nnamespace Azure.ClientGenerator.Core.Legacy;\n\n/**\n * Adds support for client-level multiple levels of inheritance.\n *\n * This decorator will update the models returned from TCGC to include the multi-level inheritance information.\n *\n * It could be used in the scenario where the discriminated models have multiple levels of inheritance, which is not supported by pure TypeSpec.\n *\n * This decorator is considered legacy functionality and may be deprecated in future releases.\n *\n * @param target The target model that will gain legacy inheritance behavior\n * @param value The model whose properties should be inherited from\n * @param scope Optional parameter to specify which language emitters this applies to\n *\n * @example Build multiple levels inheritance for discriminated models.\n *\n * ```typespec\n * @discriminator("type")\n * model Vehicle {\n *   type: string;\n * }\n *\n * alias CarProperties = {\n *  make: string;\n *  model: string;\n *  year: int32;\n * }\n *\n * model Car extends Vehicle {\n *   type: "car";\n *   ...CarProperties;\n * }\n *\n * @Azure.ClientGenerator.Core.Legacy.hierarchyBuilding(Car)\n * model SportsCar extends Vehicle {\n *   type: "sports";\n *   ...CarProperties;\n *   topSpeed: int32;\n * }\n *\n * ```\n */\nextern dec hierarchyBuilding(target: Model, value: Model, scope?: valueof string);\n\n/**\n * Set whether a model property should be flattened or not.\n * This decorator is not recommended to use for green field services.\n * @param target The target model property that you want to flatten.\n * @param scope Specifies the target language emitters that the decorator should apply. If not set, the decorator will be applied to all language emitters by default.\n * You can use "!" to exclude specific languages, for example: !(java, python) or !java, !python.\n *\n * @example\n * ```typespec\n * model Foo {\n *    @flattenProperty\n *    prop: Bar;\n * }\n * model Bar {\n * }\n * ```\n */\nextern dec flattenProperty(target: ModelProperty, scope?: valueof string);\n'
};
var _TypeSpecLibrary_ = {
  jsSourceFiles: TypeSpecJSSources,
  typespecSourceFiles: TypeSpecSources
};
export {
  $access,
  $alternateType,
  $apiVersion,
  $client,
  $clientApiVersions,
  $clientDoc,
  $clientInitialization,
  $clientLocation,
  $clientName,
  $clientNamespace,
  $convenientAPI,
  $decorators,
  $deserializeEmptyStringAsNull,
  $flattenProperty,
  $legacyHierarchyBuilding,
  $lib,
  $linter,
  $onEmit,
  $operationGroup,
  $override,
  $paramAlias,
  $protocolAPI,
  $responseAsBool,
  $scope,
  $usage,
  $useSystemTextJsonConverter,
  BrandedSdkEmitterOptions,
  InitializedByFlags,
  UnbrandedSdkEmitterOptions,
  UsageFlags,
  _TypeSpecLibrary_,
  addEncodeInfo,
  createDiagnostic,
  createSdkContext,
  createStateSymbol,
  createTCGCContext,
  getAccess,
  getAccessOverride,
  getAllModels,
  getAllModelsWithDiagnostics,
  getAllReferencedTypes,
  getAlternateType,
  getClient,
  getClientDocExplicit,
  getClientInitializationOptions,
  getClientLocation,
  getClientNameOverride,
  getClientNamespace,
  getClientType,
  getClientTypeWithDiagnostics,
  getCrossLanguageDefinitionId,
  getCrossLanguagePackageId,
  getDefaultApiVersion,
  getEffectivePayloadType,
  getExplicitClientApiVersions,
  getGeneratedName,
  getHttpOperationExamples,
  getHttpOperationParameter,
  getHttpOperationWithCache,
  getIsApiVersion,
  getKnownScalars,
  getLegacyHierarchyBuilding,
  getLibraryName,
  getNamespaceFromType,
  getOperationGroup,
  getOverriddenClientMethod,
  getParamAlias,
  getPropertyNames,
  getResponseAsBool,
  getSdkArrayOrDict,
  getSdkArrayOrDictWithDiagnostics,
  getSdkBuiltInType,
  getSdkConstant,
  getSdkCredentialParameter,
  getSdkDurationType,
  getSdkEnum,
  getSdkEnumValue,
  getSdkModel,
  getSdkModelPropertyType,
  getSdkModelPropertyTypeBase,
  getSdkModelWithDiagnostics,
  getSdkTuple,
  getSdkTupleWithDiagnostics,
  getSdkUnion,
  getSdkUnionEnum,
  getSdkUnionEnumWithDiagnostics,
  getSdkUnionWithDiagnostics,
  getTypeSpecBuiltInType,
  getUsage,
  getUsageOverride,
  getWireName,
  handleAllTypes,
  isApiVersion,
  isAzureCoreModel,
  isHttpMetadata,
  isInScope,
  isOperationGroup,
  isPagedResultModel,
  isReadOnly,
  isSdkBuiltInKind,
  isSdkDateTimeEncodings,
  isSdkFloatKind,
  isSdkIntKind,
  listAllServiceNamespaces,
  listClients,
  listOperationGroups,
  listOperationsInOperationGroup,
  namespace,
  reportDiagnostic,
  resolveOperationId,
  shouldFlattenProperty,
  shouldGenerateConvenient,
  shouldGenerateProtocol,
  updateUsageOrAccess
};
