{
  "version": 3,
  "sources": ["../../../cli/node_modules/semver/internal/constants.js", "../../../cli/node_modules/semver/internal/debug.js", "../../../cli/node_modules/semver/internal/re.js", "../../../cli/node_modules/semver/internal/parse-options.js", "../../../cli/node_modules/semver/internal/identifiers.js", "../../../cli/node_modules/semver/classes/semver.js", "../../../cli/node_modules/semver/functions/parse.js", "../../../cli/node_modules/semver/functions/valid.js", "../../../cli/node_modules/semver/functions/clean.js", "../../../cli/node_modules/semver/functions/inc.js", "../../../cli/node_modules/semver/functions/diff.js", "../../../cli/node_modules/semver/functions/major.js", "../../../cli/node_modules/semver/functions/minor.js", "../../../cli/node_modules/semver/functions/patch.js", "../../../cli/node_modules/semver/functions/prerelease.js", "../../../cli/node_modules/semver/functions/compare.js", "../../../cli/node_modules/semver/functions/rcompare.js", "../../../cli/node_modules/semver/functions/compare-loose.js", "../../../cli/node_modules/semver/functions/compare-build.js", "../../../cli/node_modules/semver/functions/sort.js", "../../../cli/node_modules/semver/functions/rsort.js", "../../../cli/node_modules/semver/functions/gt.js", "../../../cli/node_modules/semver/functions/lt.js", "../../../cli/node_modules/semver/functions/eq.js", "../../../cli/node_modules/semver/functions/neq.js", "../../../cli/node_modules/semver/functions/gte.js", "../../../cli/node_modules/semver/functions/lte.js", "../../../cli/node_modules/semver/functions/cmp.js", "../../../cli/node_modules/semver/functions/coerce.js", "../../../cli/node_modules/semver/functions/truncate.js", "../../../cli/node_modules/semver/internal/lrucache.js", "../../../cli/node_modules/semver/classes/range.js", "../../../cli/node_modules/semver/classes/comparator.js", "../../../cli/node_modules/semver/functions/satisfies.js", "../../../cli/node_modules/semver/ranges/to-comparators.js", "../../../cli/node_modules/semver/ranges/max-satisfying.js", "../../../cli/node_modules/semver/ranges/min-satisfying.js", "../../../cli/node_modules/semver/ranges/min-version.js", "../../../cli/node_modules/semver/ranges/valid.js", "../../../cli/node_modules/semver/ranges/outside.js", "../../../cli/node_modules/semver/ranges/gtr.js", "../../../cli/node_modules/semver/ranges/ltr.js", "../../../cli/node_modules/semver/ranges/intersects.js", "../../../cli/node_modules/semver/ranges/simplify.js", "../../../cli/node_modules/semver/ranges/subset.js", "../../../cli/node_modules/semver/index.js", "../../../cli/src/index.ts", "../../../cli/src/agent.ts", "../../../cli/src/util/client.ts", "../../../cli/src/storage.ts", "../../../cli/src/utils.ts", "../../../../node_modules/jose/dist/node/esm/runtime/base64url.js", "../../../../node_modules/jose/dist/node/esm/lib/buffer_utils.js", "../../../../node_modules/jose/dist/node/esm/util/errors.js", "../../../../node_modules/jose/dist/node/esm/runtime/is_key_object.js", "../../../../node_modules/jose/dist/node/esm/runtime/webcrypto.js", "../../../../node_modules/jose/dist/node/esm/lib/crypto_key.js", "../../../../node_modules/jose/dist/node/esm/lib/invalid_key_input.js", "../../../../node_modules/jose/dist/node/esm/runtime/is_key_like.js", "../../../../node_modules/jose/dist/node/esm/lib/is_disjoint.js", "../../../../node_modules/jose/dist/node/esm/lib/is_object.js", "../../../../node_modules/jose/dist/node/esm/runtime/get_named_curve.js", "../../../../node_modules/jose/dist/node/esm/lib/is_jwk.js", "../../../../node_modules/jose/dist/node/esm/runtime/check_key_length.js", "../../../../node_modules/jose/dist/node/esm/lib/check_key_type.js", "../../../../node_modules/jose/dist/node/esm/lib/validate_crit.js", "../../../../node_modules/jose/dist/node/esm/runtime/dsa_digest.js", "../../../../node_modules/jose/dist/node/esm/runtime/node_key.js", "../../../../node_modules/jose/dist/node/esm/runtime/sign.js", "../../../../node_modules/jose/dist/node/esm/runtime/hmac_digest.js", "../../../../node_modules/jose/dist/node/esm/runtime/get_sign_verify_key.js", "../../../../node_modules/jose/dist/node/esm/lib/epoch.js", "../../../../node_modules/jose/dist/node/esm/lib/secs.js", "../../../../node_modules/jose/dist/node/esm/jws/flattened/sign.js", "../../../../node_modules/jose/dist/node/esm/jws/compact/sign.js", "../../../../node_modules/jose/dist/node/esm/jwt/produce.js", "../../../../node_modules/jose/dist/node/esm/jwt/sign.js", "../../../cli/src/auth.ts", "../../../cli/src/util/color.ts", "../../../cli/src/aws/utils.ts", "../../../cli/src/aws/terminal.ts", "../../../cli/src/aws/describe.ts", "../../../cli/src/aws/init.ts", "../../../cli/src/aws/list.ts", "../../../cli/src/aws/update-app.ts", "../../../cli/src/aws/update-bucket-policies.ts", "../../../cli/src/aws/update-config.ts", "../../../cli/src/aws/update-server.ts", "../../../cli/src/aws/index.ts", "../../../cli/src/bots.ts", "../../../cli/src/bulk.ts", "../../../cli/src/hl7.ts", "../../../hl7/src/base.ts", "../../../hl7/src/client.ts", "../../../hl7/src/connection.ts", "../../../hl7/src/constants.ts", "../../../hl7/src/events.ts", "../../../hl7/src/server.ts", "../../../cli/src/profiles.ts", "../../../cli/src/project.ts", "../../../cli/src/rest.ts"],
  "sourcesContent": ["'use strict'\n\n// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0'\n\nconst MAX_LENGTH = 256\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n/* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16\n\n// Max safe length for a build identifier. The max length minus 6 characters for\n// the shortest version with a build 0.0.0+BUILD.\nconst MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6\n\nconst RELEASE_TYPES = [\n  'major',\n  'premajor',\n  'minor',\n  'preminor',\n  'patch',\n  'prepatch',\n  'prerelease',\n]\n\nmodule.exports = {\n  MAX_LENGTH,\n  MAX_SAFE_COMPONENT_LENGTH,\n  MAX_SAFE_BUILD_LENGTH,\n  MAX_SAFE_INTEGER,\n  RELEASE_TYPES,\n  SEMVER_SPEC_VERSION,\n  FLAG_INCLUDE_PRERELEASE: 0b001,\n  FLAG_LOOSE: 0b010,\n}\n", "'use strict'\n\nconst debug = (\n  typeof process === 'object' &&\n  process.env &&\n  process.env.NODE_DEBUG &&\n  /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n  : () => {}\n\nmodule.exports = debug\n", "'use strict'\n\nconst {\n  MAX_SAFE_COMPONENT_LENGTH,\n  MAX_SAFE_BUILD_LENGTH,\n  MAX_LENGTH,\n} = require('./constants')\nconst debug = require('./debug')\nexports = module.exports = {}\n\n// The actual regexps go on exports.re\nconst re = exports.re = []\nconst safeRe = exports.safeRe = []\nconst src = exports.src = []\nconst safeSrc = exports.safeSrc = []\nconst t = exports.t = {}\nlet R = 0\n\nconst LETTERDASHNUMBER = '[a-zA-Z0-9-]'\n\n// Replace some greedy regex tokens to prevent regex dos issues. These regex are\n// used internally via the safeRe object since all inputs in this library get\n// normalized first to trim and collapse all extra whitespace. The original\n// regexes are exported for userland consumption and lower level usage. A\n// future breaking change could export the safer regex only with a note that\n// all input should have extra whitespace removed.\nconst safeRegexReplacements = [\n  ['\\\\s', 1],\n  ['\\\\d', MAX_LENGTH],\n  [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],\n]\n\nconst makeSafeRegex = (value) => {\n  for (const [token, max] of safeRegexReplacements) {\n    value = value\n      .split(`${token}*`).join(`${token}{0,${max}}`)\n      .split(`${token}+`).join(`${token}{1,${max}}`)\n  }\n  return value\n}\n\nconst createToken = (name, value, isGlobal) => {\n  const safe = makeSafeRegex(value)\n  const index = R++\n  debug(name, index, value)\n  t[name] = index\n  src[index] = value\n  safeSrc[index] = safe\n  re[index] = new RegExp(value, isGlobal ? 'g' : undefined)\n  safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)\n}\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\ncreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*')\ncreateToken('NUMERICIDENTIFIERLOOSE', '\\\\d+')\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\ncreateToken('NONNUMERICIDENTIFIER', `\\\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ncreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n                   `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n                   `(${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n                        `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n                        `(${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n// Non-numeric identifiers include numeric identifiers but can be longer.\n// Therefore non-numeric identifiers must go first.\n\ncreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ncreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`)\n\ncreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ncreateToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ncreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n}(?:\\\\.${src[t.BUILDIDENTIFIER]})*))`)\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups.  The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\ncreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n}${src[t.PRERELEASE]}?${\n  src[t.BUILD]}?`)\n\ncreateToken('FULL', `^${src[t.FULLPLAIN]}$`)\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\ncreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n}${src[t.PRERELEASELOOSE]}?${\n  src[t.BUILD]}?`)\n\ncreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)\n\ncreateToken('GTLT', '((?:<|>)?=?)')\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifier, meaning \"any version\"\n// Only the first item is strictly required.\ncreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`)\ncreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`)\n\ncreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n                   `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n                   `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n                   `(?:${src[t.PRERELEASE]})?${\n                     src[t.BUILD]}?` +\n                   `)?)?`)\n\ncreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n                        `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n                        `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n                        `(?:${src[t.PRERELEASELOOSE]})?${\n                          src[t.BUILD]}?` +\n                        `)?)?`)\n\ncreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`)\ncreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ncreateToken('COERCEPLAIN', `${'(^|[^\\\\d])' +\n              '(\\\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +\n              `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n              `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)\ncreateToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\\\d])`)\ncreateToken('COERCEFULL', src[t.COERCEPLAIN] +\n              `(?:${src[t.PRERELEASE]})?` +\n              `(?:${src[t.BUILD]})?` +\n              `(?:$|[^\\\\d])`)\ncreateToken('COERCERTL', src[t.COERCE], true)\ncreateToken('COERCERTLFULL', src[t.COERCEFULL], true)\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ncreateToken('LONETILDE', '(?:~>?)')\n\ncreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true)\nexports.tildeTrimReplace = '$1~'\n\ncreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ncreateToken('LONECARET', '(?:\\\\^)')\n\ncreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true)\nexports.caretTrimReplace = '$1^'\n\ncreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ncreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`)\ncreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.FULLPLAIN]})$|^$`)\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\ncreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)\nexports.comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\ncreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n                   `\\\\s+-\\\\s+` +\n                   `(${src[t.XRANGEPLAIN]})` +\n                   `\\\\s*$`)\n\ncreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n                        `\\\\s+-\\\\s+` +\n                        `(${src[t.XRANGEPLAINLOOSE]})` +\n                        `\\\\s*$`)\n\n// Star ranges basically just allow anything at all.\ncreateToken('STAR', '(<|>)?=?\\\\s*\\\\*')\n// >=0.0.0 is like a star\ncreateToken('GTE0', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$')\ncreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$')\n", "'use strict'\n\n// parse out just the options we care about\nconst looseOption = Object.freeze({ loose: true })\nconst emptyOpts = Object.freeze({ })\nconst parseOptions = options => {\n  if (!options) {\n    return emptyOpts\n  }\n\n  if (typeof options !== 'object') {\n    return looseOption\n  }\n\n  return options\n}\nmodule.exports = parseOptions\n", "'use strict'\n\nconst numeric = /^[0-9]+$/\nconst compareIdentifiers = (a, b) => {\n  if (typeof a === 'number' && typeof b === 'number') {\n    return a === b ? 0 : a < b ? -1 : 1\n  }\n\n  const anum = numeric.test(a)\n  const bnum = numeric.test(b)\n\n  if (anum && bnum) {\n    a = +a\n    b = +b\n  }\n\n  return a === b ? 0\n    : (anum && !bnum) ? -1\n    : (bnum && !anum) ? 1\n    : a < b ? -1\n    : 1\n}\n\nconst rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)\n\nmodule.exports = {\n  compareIdentifiers,\n  rcompareIdentifiers,\n}\n", "'use strict'\n\nconst debug = require('../internal/debug')\nconst { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst parseOptions = require('../internal/parse-options')\nconst { compareIdentifiers } = require('../internal/identifiers')\n\nconst isPrereleaseIdentifier = (prerelease, identifier) => {\n  const identifiers = identifier.split('.')\n  if (identifiers.length > prerelease.length) {\n    return false\n  }\n\n  for (let i = 0; i < identifiers.length; i++) {\n    if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) {\n      return false\n    }\n  }\n\n  return true\n}\n\nclass SemVer {\n  constructor (version, options) {\n    options = parseOptions(options)\n\n    if (version instanceof SemVer) {\n      if (version.loose === !!options.loose &&\n        version.includePrerelease === !!options.includePrerelease) {\n        return version\n      } else {\n        version = version.version\n      }\n    } else if (typeof version !== 'string') {\n      throw new TypeError(`Invalid version. Must be a string. Got type \"${typeof version}\".`)\n    }\n\n    if (version.length > MAX_LENGTH) {\n      throw new TypeError(\n        `version is longer than ${MAX_LENGTH} characters`\n      )\n    }\n\n    debug('SemVer', version, options)\n    this.options = options\n    this.loose = !!options.loose\n    // this isn't actually relevant for versions, but keep it so that we\n    // don't run into trouble passing this.options around.\n    this.includePrerelease = !!options.includePrerelease\n\n    const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])\n\n    if (!m) {\n      throw new TypeError(`Invalid Version: ${version}`)\n    }\n\n    this.raw = version\n\n    // these are actually numbers\n    this.major = +m[1]\n    this.minor = +m[2]\n    this.patch = +m[3]\n\n    if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n      throw new TypeError('Invalid major version')\n    }\n\n    if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n      throw new TypeError('Invalid minor version')\n    }\n\n    if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n      throw new TypeError('Invalid patch version')\n    }\n\n    // numberify any prerelease numeric ids\n    if (!m[4]) {\n      this.prerelease = []\n    } else {\n      this.prerelease = m[4].split('.').map((id) => {\n        if (/^[0-9]+$/.test(id)) {\n          const num = +id\n          if (num >= 0 && num < MAX_SAFE_INTEGER) {\n            return num\n          }\n        }\n        return id\n      })\n    }\n\n    this.build = m[5] ? m[5].split('.') : []\n    this.format()\n  }\n\n  format () {\n    this.version = `${this.major}.${this.minor}.${this.patch}`\n    if (this.prerelease.length) {\n      this.version += `-${this.prerelease.join('.')}`\n    }\n    return this.version\n  }\n\n  toString () {\n    return this.version\n  }\n\n  compare (other) {\n    debug('SemVer.compare', this.version, this.options, other)\n    if (!(other instanceof SemVer)) {\n      if (typeof other === 'string' && other === this.version) {\n        return 0\n      }\n      other = new SemVer(other, this.options)\n    }\n\n    if (other.version === this.version) {\n      return 0\n    }\n\n    return this.compareMain(other) || this.comparePre(other)\n  }\n\n  compareMain (other) {\n    if (!(other instanceof SemVer)) {\n      other = new SemVer(other, this.options)\n    }\n\n    if (this.major < other.major) {\n      return -1\n    }\n    if (this.major > other.major) {\n      return 1\n    }\n    if (this.minor < other.minor) {\n      return -1\n    }\n    if (this.minor > other.minor) {\n      return 1\n    }\n    if (this.patch < other.patch) {\n      return -1\n    }\n    if (this.patch > other.patch) {\n      return 1\n    }\n    return 0\n  }\n\n  comparePre (other) {\n    if (!(other instanceof SemVer)) {\n      other = new SemVer(other, this.options)\n    }\n\n    // NOT having a prerelease is > having one\n    if (this.prerelease.length && !other.prerelease.length) {\n      return -1\n    } else if (!this.prerelease.length && other.prerelease.length) {\n      return 1\n    } else if (!this.prerelease.length && !other.prerelease.length) {\n      return 0\n    }\n\n    let i = 0\n    do {\n      const a = this.prerelease[i]\n      const b = other.prerelease[i]\n      debug('prerelease compare', i, a, b)\n      if (a === undefined && b === undefined) {\n        return 0\n      } else if (b === undefined) {\n        return 1\n      } else if (a === undefined) {\n        return -1\n      } else if (a === b) {\n        continue\n      } else {\n        return compareIdentifiers(a, b)\n      }\n    } while (++i)\n  }\n\n  compareBuild (other) {\n    if (!(other instanceof SemVer)) {\n      other = new SemVer(other, this.options)\n    }\n\n    let i = 0\n    do {\n      const a = this.build[i]\n      const b = other.build[i]\n      debug('build compare', i, a, b)\n      if (a === undefined && b === undefined) {\n        return 0\n      } else if (b === undefined) {\n        return 1\n      } else if (a === undefined) {\n        return -1\n      } else if (a === b) {\n        continue\n      } else {\n        return compareIdentifiers(a, b)\n      }\n    } while (++i)\n  }\n\n  // preminor will bump the version up to the next minor release, and immediately\n  // down to pre-release. premajor and prepatch work the same way.\n  inc (release, identifier, identifierBase) {\n    if (release.startsWith('pre')) {\n      if (!identifier && identifierBase === false) {\n        throw new Error('invalid increment argument: identifier is empty')\n      }\n      // Avoid an invalid semver results\n      if (identifier) {\n        const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE])\n        if (!match || match[1] !== identifier) {\n          throw new Error(`invalid identifier: ${identifier}`)\n        }\n      }\n    }\n\n    switch (release) {\n      case 'premajor':\n        this.prerelease.length = 0\n        this.patch = 0\n        this.minor = 0\n        this.major++\n        this.inc('pre', identifier, identifierBase)\n        break\n      case 'preminor':\n        this.prerelease.length = 0\n        this.patch = 0\n        this.minor++\n        this.inc('pre', identifier, identifierBase)\n        break\n      case 'prepatch':\n        // If this is already a prerelease, it will bump to the next version\n        // drop any prereleases that might already exist, since they are not\n        // relevant at this point.\n        this.prerelease.length = 0\n        this.inc('patch', identifier, identifierBase)\n        this.inc('pre', identifier, identifierBase)\n        break\n      // If the input is a non-prerelease version, this acts the same as\n      // prepatch.\n      case 'prerelease':\n        if (this.prerelease.length === 0) {\n          this.inc('patch', identifier, identifierBase)\n        }\n        this.inc('pre', identifier, identifierBase)\n        break\n      case 'release':\n        if (this.prerelease.length === 0) {\n          throw new Error(`version ${this.raw} is not a prerelease`)\n        }\n        this.prerelease.length = 0\n        break\n\n      case 'major':\n        // If this is a pre-major version, bump up to the same major version.\n        // Otherwise increment major.\n        // 1.0.0-5 bumps to 1.0.0\n        // 1.1.0 bumps to 2.0.0\n        if (\n          this.minor !== 0 ||\n          this.patch !== 0 ||\n          this.prerelease.length === 0\n        ) {\n          this.major++\n        }\n        this.minor = 0\n        this.patch = 0\n        this.prerelease = []\n        break\n      case 'minor':\n        // If this is a pre-minor version, bump up to the same minor version.\n        // Otherwise increment minor.\n        // 1.2.0-5 bumps to 1.2.0\n        // 1.2.1 bumps to 1.3.0\n        if (this.patch !== 0 || this.prerelease.length === 0) {\n          this.minor++\n        }\n        this.patch = 0\n        this.prerelease = []\n        break\n      case 'patch':\n        // If this is not a pre-release version, it will increment the patch.\n        // If it is a pre-release it will bump up to the same patch version.\n        // 1.2.0-5 patches to 1.2.0\n        // 1.2.0 patches to 1.2.1\n        if (this.prerelease.length === 0) {\n          this.patch++\n        }\n        this.prerelease = []\n        break\n      // This probably shouldn't be used publicly.\n      // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.\n      case 'pre': {\n        const base = Number(identifierBase) ? 1 : 0\n\n        if (this.prerelease.length === 0) {\n          this.prerelease = [base]\n        } else {\n          let i = this.prerelease.length\n          while (--i >= 0) {\n            if (typeof this.prerelease[i] === 'number') {\n              this.prerelease[i]++\n              i = -2\n            }\n          }\n          if (i === -1) {\n            // didn't increment anything\n            if (identifier === this.prerelease.join('.') && identifierBase === false) {\n              throw new Error('invalid increment argument: identifier already exists')\n            }\n            this.prerelease.push(base)\n          }\n        }\n        if (identifier) {\n          // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n          // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n          let prerelease = [identifier, base]\n          if (identifierBase === false) {\n            prerelease = [identifier]\n          }\n          if (isPrereleaseIdentifier(this.prerelease, identifier)) {\n            const prereleaseBase = this.prerelease[identifier.split('.').length]\n            if (isNaN(prereleaseBase)) {\n              this.prerelease = prerelease\n            }\n          } else {\n            this.prerelease = prerelease\n          }\n        }\n        break\n      }\n      default:\n        throw new Error(`invalid increment argument: ${release}`)\n    }\n    this.raw = this.format()\n    if (this.build.length) {\n      this.raw += `+${this.build.join('.')}`\n    }\n    return this\n  }\n}\n\nmodule.exports = SemVer\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = (version, options, throwErrors = false) => {\n  if (version instanceof SemVer) {\n    return version\n  }\n  try {\n    return new SemVer(version, options)\n  } catch (er) {\n    if (!throwErrors) {\n      return null\n    }\n    throw er\n  }\n}\n\nmodule.exports = parse\n", "'use strict'\n\nconst parse = require('./parse')\nconst valid = (version, options) => {\n  const v = parse(version, options)\n  return v ? v.version : null\n}\nmodule.exports = valid\n", "'use strict'\n\nconst parse = require('./parse')\nconst clean = (version, options) => {\n  const s = parse(version.trim().replace(/^[=v]+/, ''), options)\n  return s ? s.version : null\n}\nmodule.exports = clean\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\n\nconst inc = (version, release, options, identifier, identifierBase) => {\n  if (typeof (options) === 'string') {\n    identifierBase = identifier\n    identifier = options\n    options = undefined\n  }\n\n  try {\n    return new SemVer(\n      version instanceof SemVer ? version.version : version,\n      options\n    ).inc(release, identifier, identifierBase).version\n  } catch (er) {\n    return null\n  }\n}\nmodule.exports = inc\n", "'use strict'\n\nconst parse = require('./parse.js')\n\nconst diff = (version1, version2) => {\n  const v1 = parse(version1, null, true)\n  const v2 = parse(version2, null, true)\n  const comparison = v1.compare(v2)\n\n  if (comparison === 0) {\n    return null\n  }\n\n  const v1Higher = comparison > 0\n  const highVersion = v1Higher ? v1 : v2\n  const lowVersion = v1Higher ? v2 : v1\n  const highHasPre = !!highVersion.prerelease.length\n  const lowHasPre = !!lowVersion.prerelease.length\n\n  if (lowHasPre && !highHasPre) {\n    // Going from prerelease -> no prerelease requires some special casing\n\n    // If the low version has only a major, then it will always be a major\n    // Some examples:\n    // 1.0.0-1 -> 1.0.0\n    // 1.0.0-1 -> 1.1.1\n    // 1.0.0-1 -> 2.0.0\n    if (!lowVersion.patch && !lowVersion.minor) {\n      return 'major'\n    }\n\n    // If the main part has no difference\n    if (lowVersion.compareMain(highVersion) === 0) {\n      if (lowVersion.minor && !lowVersion.patch) {\n        return 'minor'\n      }\n      return 'patch'\n    }\n  }\n\n  // add the `pre` prefix if we are going to a prerelease version\n  const prefix = highHasPre ? 'pre' : ''\n\n  if (v1.major !== v2.major) {\n    return prefix + 'major'\n  }\n\n  if (v1.minor !== v2.minor) {\n    return prefix + 'minor'\n  }\n\n  if (v1.patch !== v2.patch) {\n    return prefix + 'patch'\n  }\n\n  // high and low are prereleases\n  return 'prerelease'\n}\n\nmodule.exports = diff\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst major = (a, loose) => new SemVer(a, loose).major\nmodule.exports = major\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst minor = (a, loose) => new SemVer(a, loose).minor\nmodule.exports = minor\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst patch = (a, loose) => new SemVer(a, loose).patch\nmodule.exports = patch\n", "'use strict'\n\nconst parse = require('./parse')\nconst prerelease = (version, options) => {\n  const parsed = parse(version, options)\n  return (parsed && parsed.prerelease.length) ? parsed.prerelease : null\n}\nmodule.exports = prerelease\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compare = (a, b, loose) =>\n  new SemVer(a, loose).compare(new SemVer(b, loose))\n\nmodule.exports = compare\n", "'use strict'\n\nconst compare = require('./compare')\nconst rcompare = (a, b, loose) => compare(b, a, loose)\nmodule.exports = rcompare\n", "'use strict'\n\nconst compare = require('./compare')\nconst compareLoose = (a, b) => compare(a, b, true)\nmodule.exports = compareLoose\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compareBuild = (a, b, loose) => {\n  const versionA = new SemVer(a, loose)\n  const versionB = new SemVer(b, loose)\n  return versionA.compare(versionB) || versionA.compareBuild(versionB)\n}\nmodule.exports = compareBuild\n", "'use strict'\n\nconst compareBuild = require('./compare-build')\nconst sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))\nmodule.exports = sort\n", "'use strict'\n\nconst compareBuild = require('./compare-build')\nconst rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))\nmodule.exports = rsort\n", "'use strict'\n\nconst compare = require('./compare')\nconst gt = (a, b, loose) => compare(a, b, loose) > 0\nmodule.exports = gt\n", "'use strict'\n\nconst compare = require('./compare')\nconst lt = (a, b, loose) => compare(a, b, loose) < 0\nmodule.exports = lt\n", "'use strict'\n\nconst compare = require('./compare')\nconst eq = (a, b, loose) => compare(a, b, loose) === 0\nmodule.exports = eq\n", "'use strict'\n\nconst compare = require('./compare')\nconst neq = (a, b, loose) => compare(a, b, loose) !== 0\nmodule.exports = neq\n", "'use strict'\n\nconst compare = require('./compare')\nconst gte = (a, b, loose) => compare(a, b, loose) >= 0\nmodule.exports = gte\n", "'use strict'\n\nconst compare = require('./compare')\nconst lte = (a, b, loose) => compare(a, b, loose) <= 0\nmodule.exports = lte\n", "'use strict'\n\nconst eq = require('./eq')\nconst neq = require('./neq')\nconst gt = require('./gt')\nconst gte = require('./gte')\nconst lt = require('./lt')\nconst lte = require('./lte')\n\nconst cmp = (a, op, b, loose) => {\n  switch (op) {\n    case '===':\n      if (typeof a === 'object') {\n        a = a.version\n      }\n      if (typeof b === 'object') {\n        b = b.version\n      }\n      return a === b\n\n    case '!==':\n      if (typeof a === 'object') {\n        a = a.version\n      }\n      if (typeof b === 'object') {\n        b = b.version\n      }\n      return a !== b\n\n    case '':\n    case '=':\n    case '==':\n      return eq(a, b, loose)\n\n    case '!=':\n      return neq(a, b, loose)\n\n    case '>':\n      return gt(a, b, loose)\n\n    case '>=':\n      return gte(a, b, loose)\n\n    case '<':\n      return lt(a, b, loose)\n\n    case '<=':\n      return lte(a, b, loose)\n\n    default:\n      throw new TypeError(`Invalid operator: ${op}`)\n  }\n}\nmodule.exports = cmp\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = require('./parse')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst coerce = (version, options) => {\n  if (version instanceof SemVer) {\n    return version\n  }\n\n  if (typeof version === 'number') {\n    version = String(version)\n  }\n\n  if (typeof version !== 'string') {\n    return null\n  }\n\n  options = options || {}\n\n  let match = null\n  if (!options.rtl) {\n    match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])\n  } else {\n    // Find the right-most coercible string that does not share\n    // a terminus with a more left-ward coercible string.\n    // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'\n    // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'\n    //\n    // Walk through the string checking with a /g regexp\n    // Manually set the index so as to pick up overlapping matches.\n    // Stop when we get a match that ends at the string end, since no\n    // coercible string can be more right-ward without the same terminus.\n    const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]\n    let next\n    while ((next = coerceRtlRegex.exec(version)) &&\n        (!match || match.index + match[0].length !== version.length)\n    ) {\n      if (!match ||\n            next.index + next[0].length !== match.index + match[0].length) {\n        match = next\n      }\n      coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length\n    }\n    // leave it in a clean state\n    coerceRtlRegex.lastIndex = -1\n  }\n\n  if (match === null) {\n    return null\n  }\n\n  const major = match[2]\n  const minor = match[3] || '0'\n  const patch = match[4] || '0'\n  const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''\n  const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''\n\n  return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)\n}\nmodule.exports = coerce\n", "'use strict'\n\nconst parse = require('./parse')\nconst constants = require('../internal/constants')\nconst SemVer = require('../classes/semver')\n\nconst truncate = (version, truncation, options) => {\n  if (!constants.RELEASE_TYPES.includes(truncation)) {\n    return null\n  }\n\n  const clonedVersion = cloneInputVersion(version, options)\n  return clonedVersion && doTruncation(clonedVersion, truncation)\n}\n\nconst cloneInputVersion = (version, options) => {\n  const versionStringToParse = (\n    version instanceof SemVer ? version.version : version\n  )\n\n  return parse(versionStringToParse, options)\n}\n\nconst doTruncation = (version, truncation) => {\n  if (isPrerelease(truncation)) {\n    return version.version\n  }\n\n  version.prerelease = []\n\n  switch (truncation) {\n    case 'major':\n      version.minor = 0\n      version.patch = 0\n      break\n    case 'minor':\n      version.patch = 0\n      break\n  }\n\n  return version.format()\n}\n\nconst isPrerelease = (type) => {\n  return type.startsWith('pre')\n}\n\nmodule.exports = truncate\n", "'use strict'\n\nclass LRUCache {\n  constructor () {\n    this.max = 1000\n    this.map = new Map()\n  }\n\n  get (key) {\n    const value = this.map.get(key)\n    if (value === undefined) {\n      return undefined\n    } else {\n      // Remove the key from the map and add it to the end\n      this.map.delete(key)\n      this.map.set(key, value)\n      return value\n    }\n  }\n\n  delete (key) {\n    return this.map.delete(key)\n  }\n\n  set (key, value) {\n    const deleted = this.delete(key)\n\n    if (!deleted && value !== undefined) {\n      // If cache is full, delete the least recently used item\n      if (this.map.size >= this.max) {\n        const firstKey = this.map.keys().next().value\n        this.delete(firstKey)\n      }\n\n      this.map.set(key, value)\n    }\n\n    return this\n  }\n}\n\nmodule.exports = LRUCache\n", "'use strict'\n\nconst SPACE_CHARACTERS = /\\s+/g\n\n// hoisted class for cyclic dependency\nclass Range {\n  constructor (range, options) {\n    options = parseOptions(options)\n\n    if (range instanceof Range) {\n      if (\n        range.loose === !!options.loose &&\n        range.includePrerelease === !!options.includePrerelease\n      ) {\n        return range\n      } else {\n        return new Range(range.raw, options)\n      }\n    }\n\n    if (range instanceof Comparator) {\n      // just put it in the set and return\n      this.raw = range.value\n      this.set = [[range]]\n      this.formatted = undefined\n      return this\n    }\n\n    this.options = options\n    this.loose = !!options.loose\n    this.includePrerelease = !!options.includePrerelease\n\n    // First reduce all whitespace as much as possible so we do not have to rely\n    // on potentially slow regexes like \\s*. This is then stored and used for\n    // future error messages as well.\n    this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')\n\n    // First, split on ||\n    this.set = this.raw\n      .split('||')\n      // map the range to a 2d array of comparators\n      .map(r => this.parseRange(r.trim()))\n      // throw out any comparator lists that are empty\n      // this generally means that it was not a valid range, which is allowed\n      // in loose mode, but will still throw if the WHOLE range is invalid.\n      .filter(c => c.length)\n\n    if (!this.set.length) {\n      throw new TypeError(`Invalid SemVer Range: ${this.raw}`)\n    }\n\n    // if we have any that are not the null set, throw out null sets.\n    if (this.set.length > 1) {\n      // keep the first one, in case they're all null sets\n      const first = this.set[0]\n      this.set = this.set.filter(c => !isNullSet(c[0]))\n      if (this.set.length === 0) {\n        this.set = [first]\n      } else if (this.set.length > 1) {\n        // if we have any that are *, then the range is just *\n        for (const c of this.set) {\n          if (c.length === 1 && isAny(c[0])) {\n            this.set = [c]\n            break\n          }\n        }\n      }\n    }\n\n    this.formatted = undefined\n  }\n\n  get range () {\n    if (this.formatted === undefined) {\n      this.formatted = ''\n      for (let i = 0; i < this.set.length; i++) {\n        if (i > 0) {\n          this.formatted += '||'\n        }\n        const comps = this.set[i]\n        for (let k = 0; k < comps.length; k++) {\n          if (k > 0) {\n            this.formatted += ' '\n          }\n          this.formatted += comps[k].toString().trim()\n        }\n      }\n    }\n    return this.formatted\n  }\n\n  format () {\n    return this.range\n  }\n\n  toString () {\n    return this.range\n  }\n\n  parseRange (range) {\n    // strip build metadata so it can't bleed into the version\n    range = range.replace(BUILDSTRIPRE, '')\n\n    // memoize range parsing for performance.\n    // this is a very hot path, and fully deterministic.\n    const memoOpts =\n      (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |\n      (this.options.loose && FLAG_LOOSE)\n    const memoKey = memoOpts + ':' + range\n    const cached = cache.get(memoKey)\n    if (cached) {\n      return cached\n    }\n\n    const loose = this.options.loose\n    // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n    const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n    range = range.replace(hr, hyphenReplace(this.options.includePrerelease))\n    debug('hyphen replace', range)\n\n    // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n    range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n    debug('comparator trim', range)\n\n    // `~ 1.2.3` => `~1.2.3`\n    range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n    debug('tilde trim', range)\n\n    // `^ 1.2.3` => `^1.2.3`\n    range = range.replace(re[t.CARETTRIM], caretTrimReplace)\n    debug('caret trim', range)\n\n    // At this point, the range is completely trimmed and\n    // ready to be split into comparators.\n\n    let rangeList = range\n      .split(' ')\n      .map(comp => parseComparator(comp, this.options))\n      .join(' ')\n      .split(/\\s+/)\n      // >=0.0.0 is equivalent to *\n      .map(comp => replaceGTE0(comp, this.options))\n\n    if (loose) {\n      // in loose mode, throw out any that are not valid comparators\n      rangeList = rangeList.filter(comp => {\n        debug('loose invalid filter', comp, this.options)\n        return !!comp.match(re[t.COMPARATORLOOSE])\n      })\n    }\n    debug('range list', rangeList)\n\n    // if any comparators are the null set, then replace with JUST null set\n    // if more than one comparator, remove any * comparators\n    // also, don't include the same comparator more than once\n    const rangeMap = new Map()\n    const comparators = rangeList.map(comp => new Comparator(comp, this.options))\n    for (const comp of comparators) {\n      if (isNullSet(comp)) {\n        return [comp]\n      }\n      rangeMap.set(comp.value, comp)\n    }\n    if (rangeMap.size > 1 && rangeMap.has('')) {\n      rangeMap.delete('')\n    }\n\n    const result = [...rangeMap.values()]\n    cache.set(memoKey, result)\n    return result\n  }\n\n  intersects (range, options) {\n    if (!(range instanceof Range)) {\n      throw new TypeError('a Range is required')\n    }\n\n    return this.set.some((thisComparators) => {\n      return (\n        isSatisfiable(thisComparators, options) &&\n        range.set.some((rangeComparators) => {\n          return (\n            isSatisfiable(rangeComparators, options) &&\n            thisComparators.every((thisComparator) => {\n              return rangeComparators.every((rangeComparator) => {\n                return thisComparator.intersects(rangeComparator, options)\n              })\n            })\n          )\n        })\n      )\n    })\n  }\n\n  // if ANY of the sets match ALL of its comparators, then pass\n  test (version) {\n    if (!version) {\n      return false\n    }\n\n    if (typeof version === 'string') {\n      try {\n        version = new SemVer(version, this.options)\n      } catch (er) {\n        return false\n      }\n    }\n\n    for (let i = 0; i < this.set.length; i++) {\n      if (testSet(this.set[i], version, this.options)) {\n        return true\n      }\n    }\n    return false\n  }\n}\n\nmodule.exports = Range\n\nconst LRU = require('../internal/lrucache')\nconst cache = new LRU()\n\nconst parseOptions = require('../internal/parse-options')\nconst Comparator = require('./comparator')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst {\n  safeRe: re,\n  src,\n  t,\n  comparatorTrimReplace,\n  tildeTrimReplace,\n  caretTrimReplace,\n} = require('../internal/re')\nconst { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')\n\n// unbounded global build-metadata stripper used by parseRange\nconst BUILDSTRIPRE = new RegExp(src[t.BUILD], 'g')\n\nconst isNullSet = c => c.value === '<0.0.0-0'\nconst isAny = c => c.value === ''\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nconst isSatisfiable = (comparators, options) => {\n  let result = true\n  const remainingComparators = comparators.slice()\n  let testComparator = remainingComparators.pop()\n\n  while (result && remainingComparators.length) {\n    result = remainingComparators.every((otherComparator) => {\n      return testComparator.intersects(otherComparator, options)\n    })\n\n    testComparator = remainingComparators.pop()\n  }\n\n  return result\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nconst parseComparator = (comp, options) => {\n  comp = comp.replace(re[t.BUILD], '')\n  debug('comp', comp, options)\n  comp = replaceCarets(comp, options)\n  debug('caret', comp)\n  comp = replaceTildes(comp, options)\n  debug('tildes', comp)\n  comp = replaceXRanges(comp, options)\n  debug('xrange', comp)\n  comp = replaceStars(comp, options)\n  debug('stars', comp)\n  return comp\n}\n\nconst isX = id => !id || id.toLowerCase() === 'x' || id === '*'\n\nconst invalidXRangeOrder = (M, m, p) => (\n  (isX(M) && !isX(m)) ||\n  (isX(m) && p && !isX(p))\n)\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\n// ~0.0.1 --> >=0.0.1 <0.1.0-0\nconst replaceTildes = (comp, options) => {\n  return comp\n    .trim()\n    .split(/\\s+/)\n    .map((c) => replaceTilde(c, options))\n    .join(' ')\n}\n\nconst replaceTilde = (comp, options) => {\n  const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n  // if we're including prereleases in the match, then the lower bound is\n  // -0, the lowest possible prerelease value, just like x-ranges and carets.\n  // this keeps `~1.2` equivalent to the `1.2.x` x-range it's documented as.\n  const z = options.includePrerelease ? '-0' : ''\n  return comp.replace(r, (_, M, m, p, pr) => {\n    debug('tilde', comp, _, M, m, p, pr)\n    let ret\n\n    if (isX(M)) {\n      ret = ''\n    } else if (isX(m)) {\n      ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n    } else if (isX(p)) {\n      // ~1.2 == >=1.2.0 <1.3.0-0\n      ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n    } else if (pr) {\n      debug('replaceTilde pr', pr)\n      ret = `>=${M}.${m}.${p}-${pr\n      } <${M}.${+m + 1}.0-0`\n    } else {\n      // ~1.2.3 == >=1.2.3 <1.3.0-0\n      ret = `>=${M}.${m}.${p\n      } <${M}.${+m + 1}.0-0`\n    }\n\n    debug('tilde return', ret)\n    return ret\n  })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n// ^1.2.3 --> >=1.2.3 <2.0.0-0\n// ^1.2.0 --> >=1.2.0 <2.0.0-0\n// ^0.0.1 --> >=0.0.1 <0.0.2-0\n// ^0.1.0 --> >=0.1.0 <0.2.0-0\nconst replaceCarets = (comp, options) => {\n  return comp\n    .trim()\n    .split(/\\s+/)\n    .map((c) => replaceCaret(c, options))\n    .join(' ')\n}\n\nconst replaceCaret = (comp, options) => {\n  debug('caret', comp, options)\n  const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n  const z = options.includePrerelease ? '-0' : ''\n  return comp.replace(r, (_, M, m, p, pr) => {\n    debug('caret', comp, _, M, m, p, pr)\n    let ret\n\n    if (isX(M)) {\n      ret = ''\n    } else if (isX(m)) {\n      ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n    } else if (isX(p)) {\n      if (M === '0') {\n        ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n      } else {\n        ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`\n      }\n    } else if (pr) {\n      debug('replaceCaret pr', pr)\n      if (M === '0') {\n        if (m === '0') {\n          ret = `>=${M}.${m}.${p}-${pr\n          } <${M}.${m}.${+p + 1}-0`\n        } else {\n          ret = `>=${M}.${m}.${p}-${pr\n          } <${M}.${+m + 1}.0-0`\n        }\n      } else {\n        ret = `>=${M}.${m}.${p}-${pr\n        } <${+M + 1}.0.0-0`\n      }\n    } else {\n      debug('no pr')\n      if (M === '0') {\n        if (m === '0') {\n          ret = `>=${M}.${m}.${p\n          } <${M}.${m}.${+p + 1}-0`\n        } else {\n          ret = `>=${M}.${m}.${p\n          } <${M}.${+m + 1}.0-0`\n        }\n      } else {\n        ret = `>=${M}.${m}.${p\n        } <${+M + 1}.0.0-0`\n      }\n    }\n\n    debug('caret return', ret)\n    return ret\n  })\n}\n\nconst replaceXRanges = (comp, options) => {\n  debug('replaceXRanges', comp, options)\n  return comp\n    .split(/\\s+/)\n    .map((c) => replaceXRange(c, options))\n    .join(' ')\n}\n\nconst replaceXRange = (comp, options) => {\n  comp = comp.trim()\n  const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n  return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n    debug('xRange', comp, ret, gtlt, M, m, p, pr)\n    if (invalidXRangeOrder(M, m, p)) {\n      return comp\n    }\n\n    const xM = isX(M)\n    const xm = xM || isX(m)\n    const xp = xm || isX(p)\n    const anyX = xp\n\n    if (gtlt === '=' && anyX) {\n      gtlt = ''\n    }\n\n    // if we're including prereleases in the match, then we need\n    // to fix this to -0, the lowest possible prerelease value\n    pr = options.includePrerelease ? '-0' : ''\n\n    if (xM) {\n      if (gtlt === '>' || gtlt === '<') {\n        // nothing is allowed\n        ret = '<0.0.0-0'\n      } else {\n        // nothing is forbidden\n        ret = '*'\n      }\n    } else if (gtlt && anyX) {\n      // we know patch is an x, because we have any x at all.\n      // replace X with 0\n      if (xm) {\n        m = 0\n      }\n      p = 0\n\n      if (gtlt === '>') {\n        // >1 => >=2.0.0\n        // >1.2 => >=1.3.0\n        gtlt = '>='\n        if (xm) {\n          M = +M + 1\n          m = 0\n          p = 0\n        } else {\n          m = +m + 1\n          p = 0\n        }\n      } else if (gtlt === '<=') {\n        // <=0.7.x is actually <0.8.0, since any 0.7.x should\n        // pass.  Similarly, <=7.x is actually <8.0.0, etc.\n        gtlt = '<'\n        if (xm) {\n          M = +M + 1\n        } else {\n          m = +m + 1\n        }\n      }\n\n      if (gtlt === '<') {\n        pr = '-0'\n      }\n\n      ret = `${gtlt + M}.${m}.${p}${pr}`\n    } else if (xm) {\n      ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`\n    } else if (xp) {\n      ret = `>=${M}.${m}.0${pr\n      } <${M}.${+m + 1}.0-0`\n    }\n\n    debug('xRange return', ret)\n\n    return ret\n  })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nconst replaceStars = (comp, options) => {\n  debug('replaceStars', comp, options)\n  // Looseness is ignored here.  star is always as loose as it gets!\n  return comp\n    .trim()\n    .replace(re[t.STAR], '')\n}\n\nconst replaceGTE0 = (comp, options) => {\n  debug('replaceGTE0', comp, options)\n  return comp\n    .trim()\n    .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n}\n\n// This function is passed to string.replace(re[t.HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\n// TODO build?\nconst hyphenReplace = incPr => ($0,\n  from, fM, fm, fp, fpr, fb,\n  to, tM, tm, tp, tpr) => {\n  if (isX(fM)) {\n    from = ''\n  } else if (isX(fm)) {\n    from = `>=${fM}.0.0${incPr ? '-0' : ''}`\n  } else if (isX(fp)) {\n    from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`\n  } else if (fpr) {\n    from = `>=${from}`\n  } else {\n    from = `>=${from}${incPr ? '-0' : ''}`\n  }\n\n  if (isX(tM)) {\n    to = ''\n  } else if (isX(tm)) {\n    to = `<${+tM + 1}.0.0-0`\n  } else if (isX(tp)) {\n    to = `<${tM}.${+tm + 1}.0-0`\n  } else if (tpr) {\n    to = `<=${tM}.${tm}.${tp}-${tpr}`\n  } else if (incPr) {\n    to = `<${tM}.${tm}.${+tp + 1}-0`\n  } else {\n    to = `<=${to}`\n  }\n\n  return `${from} ${to}`.trim()\n}\n\nconst testSet = (set, version, options) => {\n  for (let i = 0; i < set.length; i++) {\n    if (!set[i].test(version)) {\n      return false\n    }\n  }\n\n  if (version.prerelease.length && !options.includePrerelease) {\n    // Find the set of versions that are allowed to have prereleases\n    // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n    // That should allow `1.2.3-pr.2` to pass.\n    // However, `1.2.4-alpha.notready` should NOT be allowed,\n    // even though it's within the range set by the comparators.\n    for (let i = 0; i < set.length; i++) {\n      debug(set[i].semver)\n      if (set[i].semver === Comparator.ANY) {\n        continue\n      }\n\n      if (set[i].semver.prerelease.length > 0) {\n        const allowed = set[i].semver\n        if (allowed.major === version.major &&\n            allowed.minor === version.minor &&\n            allowed.patch === version.patch) {\n          return true\n        }\n      }\n    }\n\n    // Version has a -pre, but it's not one of the ones we like.\n    return false\n  }\n\n  return true\n}\n", "'use strict'\n\nconst ANY = Symbol('SemVer ANY')\n// hoisted class for cyclic dependency\nclass Comparator {\n  static get ANY () {\n    return ANY\n  }\n\n  constructor (comp, options) {\n    options = parseOptions(options)\n\n    if (comp instanceof Comparator) {\n      if (comp.loose === !!options.loose) {\n        return comp\n      } else {\n        comp = comp.value\n      }\n    }\n\n    comp = comp.trim().split(/\\s+/).join(' ')\n    debug('comparator', comp, options)\n    this.options = options\n    this.loose = !!options.loose\n    this.parse(comp)\n\n    if (this.semver === ANY) {\n      this.value = ''\n    } else {\n      this.value = this.operator + this.semver.version\n    }\n\n    debug('comp', this)\n  }\n\n  parse (comp) {\n    const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n    const m = comp.match(r)\n\n    if (!m) {\n      throw new TypeError(`Invalid comparator: ${comp}`)\n    }\n\n    this.operator = m[1] !== undefined ? m[1] : ''\n    if (this.operator === '=') {\n      this.operator = ''\n    }\n\n    // if it literally is just '>' or '' then allow anything.\n    if (!m[2]) {\n      this.semver = ANY\n    } else {\n      this.semver = new SemVer(m[2], this.options.loose)\n    }\n  }\n\n  toString () {\n    return this.value\n  }\n\n  test (version) {\n    debug('Comparator.test', version, this.options.loose)\n\n    if (this.semver === ANY || version === ANY) {\n      return true\n    }\n\n    if (typeof version === 'string') {\n      try {\n        version = new SemVer(version, this.options)\n      } catch (er) {\n        return false\n      }\n    }\n\n    return cmp(version, this.operator, this.semver, this.options)\n  }\n\n  intersects (comp, options) {\n    if (!(comp instanceof Comparator)) {\n      throw new TypeError('a Comparator is required')\n    }\n\n    if (this.operator === '') {\n      if (this.value === '') {\n        return true\n      }\n      return new Range(comp.value, options).test(this.value)\n    } else if (comp.operator === '') {\n      if (comp.value === '') {\n        return true\n      }\n      return new Range(this.value, options).test(comp.semver)\n    }\n\n    options = parseOptions(options)\n\n    // Special cases where nothing can possibly be lower\n    if (options.includePrerelease &&\n      (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {\n      return false\n    }\n    if (!options.includePrerelease &&\n      (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {\n      return false\n    }\n\n    // Same direction increasing (> or >=)\n    if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {\n      return true\n    }\n    // Same direction decreasing (< or <=)\n    if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {\n      return true\n    }\n    // same SemVer and both sides are inclusive (<= or >=)\n    if (\n      (this.semver.version === comp.semver.version) &&\n      this.operator.includes('=') && comp.operator.includes('=')) {\n      return true\n    }\n    // opposite directions less than\n    if (cmp(this.semver, '<', comp.semver, options) &&\n      this.operator.startsWith('>') && comp.operator.startsWith('<')) {\n      return true\n    }\n    // opposite directions greater than\n    if (cmp(this.semver, '>', comp.semver, options) &&\n      this.operator.startsWith('<') && comp.operator.startsWith('>')) {\n      return true\n    }\n    return false\n  }\n}\n\nmodule.exports = Comparator\n\nconst parseOptions = require('../internal/parse-options')\nconst { safeRe: re, t } = require('../internal/re')\nconst cmp = require('../functions/cmp')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst Range = require('./range')\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst satisfies = (version, range, options) => {\n  try {\n    range = new Range(range, options)\n  } catch (er) {\n    return false\n  }\n  return range.test(version)\n}\nmodule.exports = satisfies\n", "'use strict'\n\nconst Range = require('../classes/range')\n\n// Mostly just for testing and legacy API reasons\nconst toComparators = (range, options) =>\n  new Range(range, options).set\n    .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))\n\nmodule.exports = toComparators\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\n\nconst maxSatisfying = (versions, range, options) => {\n  let max = null\n  let maxSV = null\n  let rangeObj = null\n  try {\n    rangeObj = new Range(range, options)\n  } catch (er) {\n    return null\n  }\n  versions.forEach((v) => {\n    if (rangeObj.test(v)) {\n      // satisfies(v, range, options)\n      if (!max || maxSV.compare(v) === -1) {\n        // compare(max, v, true)\n        max = v\n        maxSV = new SemVer(max, options)\n      }\n    }\n  })\n  return max\n}\nmodule.exports = maxSatisfying\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst minSatisfying = (versions, range, options) => {\n  let min = null\n  let minSV = null\n  let rangeObj = null\n  try {\n    rangeObj = new Range(range, options)\n  } catch (er) {\n    return null\n  }\n  versions.forEach((v) => {\n    if (rangeObj.test(v)) {\n      // satisfies(v, range, options)\n      if (!min || minSV.compare(v) === 1) {\n        // compare(min, v, true)\n        min = v\n        minSV = new SemVer(min, options)\n      }\n    }\n  })\n  return min\n}\nmodule.exports = minSatisfying\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst gt = require('../functions/gt')\n\nconst minVersion = (range, loose) => {\n  range = new Range(range, loose)\n\n  let minver = new SemVer('0.0.0')\n  if (range.test(minver)) {\n    return minver\n  }\n\n  minver = new SemVer('0.0.0-0')\n  if (range.test(minver)) {\n    return minver\n  }\n\n  minver = null\n  for (let i = 0; i < range.set.length; ++i) {\n    const comparators = range.set[i]\n\n    let setMin = null\n    comparators.forEach((comparator) => {\n      // Clone to avoid manipulating the comparator's semver object.\n      const compver = new SemVer(comparator.semver.version)\n      switch (comparator.operator) {\n        case '>':\n          if (compver.prerelease.length === 0) {\n            compver.patch++\n          } else {\n            compver.prerelease.push(0)\n          }\n          compver.raw = compver.format()\n          /* fallthrough */\n        case '':\n        case '>=':\n          if (!setMin || gt(compver, setMin)) {\n            setMin = compver\n          }\n          break\n        case '<':\n        case '<=':\n          /* Ignore maximum versions */\n          break\n        /* istanbul ignore next */\n        default:\n          throw new Error(`Unexpected operation: ${comparator.operator}`)\n      }\n    })\n    if (setMin && (!minver || gt(minver, setMin))) {\n      minver = setMin\n    }\n  }\n\n  if (minver && range.test(minver)) {\n    return minver\n  }\n\n  return null\n}\nmodule.exports = minVersion\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst validRange = (range, options) => {\n  try {\n    // Return '*' instead of '' so that truthiness works.\n    // This will throw if it's invalid anyway\n    return new Range(range, options).range || '*'\n  } catch (er) {\n    return null\n  }\n}\nmodule.exports = validRange\n", "'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Comparator = require('../classes/comparator')\nconst { ANY } = Comparator\nconst Range = require('../classes/range')\nconst satisfies = require('../functions/satisfies')\nconst gt = require('../functions/gt')\nconst lt = require('../functions/lt')\nconst lte = require('../functions/lte')\nconst gte = require('../functions/gte')\n\nconst outside = (version, range, hilo, options) => {\n  version = new SemVer(version, options)\n  range = new Range(range, options)\n\n  let gtfn, ltefn, ltfn, comp, ecomp\n  switch (hilo) {\n    case '>':\n      gtfn = gt\n      ltefn = lte\n      ltfn = lt\n      comp = '>'\n      ecomp = '>='\n      break\n    case '<':\n      gtfn = lt\n      ltefn = gte\n      ltfn = gt\n      comp = '<'\n      ecomp = '<='\n      break\n    default:\n      throw new TypeError('Must provide a hilo val of \"<\" or \">\"')\n  }\n\n  // If it satisfies the range it is not outside\n  if (satisfies(version, range, options)) {\n    return false\n  }\n\n  // From now on, variable terms are as if we're in \"gtr\" mode.\n  // but note that everything is flipped for the \"ltr\" function.\n\n  for (let i = 0; i < range.set.length; ++i) {\n    const comparators = range.set[i]\n\n    let high = null\n    let low = null\n\n    comparators.forEach((comparator) => {\n      if (comparator.semver === ANY) {\n        comparator = new Comparator('>=0.0.0')\n      }\n      high = high || comparator\n      low = low || comparator\n      if (gtfn(comparator.semver, high.semver, options)) {\n        high = comparator\n      } else if (ltfn(comparator.semver, low.semver, options)) {\n        low = comparator\n      }\n    })\n\n    // If the edge version comparator has a operator then our version\n    // isn't outside it\n    if (high.operator === comp || high.operator === ecomp) {\n      return false\n    }\n\n    // If the lowest version comparator has an operator and our version\n    // is less than it then it isn't higher than the range\n    if ((!low.operator || low.operator === comp) &&\n        ltefn(version, low.semver)) {\n      return false\n    } else if (low.operator === ecomp && ltfn(version, low.semver)) {\n      return false\n    }\n  }\n  return true\n}\n\nmodule.exports = outside\n", "'use strict'\n\n// Determine if version is greater than all the versions possible in the range.\nconst outside = require('./outside')\nconst gtr = (version, range, options) => outside(version, range, '>', options)\nmodule.exports = gtr\n", "'use strict'\n\nconst outside = require('./outside')\n// Determine if version is less than all the versions possible in the range\nconst ltr = (version, range, options) => outside(version, range, '<', options)\nmodule.exports = ltr\n", "'use strict'\n\nconst Range = require('../classes/range')\nconst intersects = (r1, r2, options) => {\n  r1 = new Range(r1, options)\n  r2 = new Range(r2, options)\n  return r1.intersects(r2, options)\n}\nmodule.exports = intersects\n", "'use strict'\n\n// given a set of versions and a range, create a \"simplified\" range\n// that includes the same versions that the original range does\n// If the original range is shorter than the simplified one, return that.\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\nmodule.exports = (versions, range, options) => {\n  const set = []\n  let first = null\n  let prev = null\n  const v = versions.sort((a, b) => compare(a, b, options))\n  for (const version of v) {\n    const included = satisfies(version, range, options)\n    if (included) {\n      prev = version\n      if (!first) {\n        first = version\n      }\n    } else {\n      if (prev) {\n        set.push([first, prev])\n      }\n      prev = null\n      first = null\n    }\n  }\n  if (first) {\n    set.push([first, null])\n  }\n\n  const ranges = []\n  for (const [min, max] of set) {\n    if (min === max) {\n      ranges.push(min)\n    } else if (!max && min === v[0]) {\n      ranges.push('*')\n    } else if (!max) {\n      ranges.push(`>=${min}`)\n    } else if (min === v[0]) {\n      ranges.push(`<=${max}`)\n    } else {\n      ranges.push(`${min} - ${max}`)\n    }\n  }\n  const simplified = ranges.join(' || ')\n  const original = typeof range.raw === 'string' ? range.raw : String(range)\n  return simplified.length < original.length ? simplified : range\n}\n", "'use strict'\n\nconst Range = require('../classes/range.js')\nconst Comparator = require('../classes/comparator.js')\nconst { ANY } = Comparator\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\n\n// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:\n// - Every simple range `r1, r2, ...` is a null set, OR\n// - Every simple range `r1, r2, ...` which is not a null set is a subset of\n//   some `R1, R2, ...`\n//\n// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:\n// - If c is only the ANY comparator\n//   - If C is only the ANY comparator, return true\n//   - Else if in prerelease mode, return false\n//   - else replace c with `[>=0.0.0]`\n// - If C is only the ANY comparator\n//   - if in prerelease mode, return true\n//   - else replace C with `[>=0.0.0]`\n// - Let EQ be the set of = comparators in c\n// - If EQ is more than one, return true (null set)\n// - Let GT be the highest > or >= comparator in c\n// - Let LT be the lowest < or <= comparator in c\n// - If GT and LT, and GT.semver > LT.semver, return true (null set)\n// - If any C is a = range, and GT or LT are set, return false\n// - If EQ\n//   - If GT, and EQ does not satisfy GT, return true (null set)\n//   - If LT, and EQ does not satisfy LT, return true (null set)\n//   - If EQ satisfies every C, return true\n//   - Else return false\n// - If GT\n//   - If GT.semver is lower than any > or >= comp in C, return false\n//   - If GT is >=, and GT.semver does not satisfy every C, return false\n//   - If GT.semver has a prerelease, and not in prerelease mode\n//     - If no C has a prerelease and the GT.semver tuple, return false\n// - If LT\n//   - If LT.semver is greater than any < or <= comp in C, return false\n//   - If LT is <=, and LT.semver does not satisfy every C, return false\n//   - If LT.semver has a prerelease, and not in prerelease mode\n//     - If no C has a prerelease and the LT.semver tuple, return false\n// - Else return true\n\nconst subset = (sub, dom, options = {}) => {\n  if (sub === dom) {\n    return true\n  }\n\n  sub = new Range(sub, options)\n  dom = new Range(dom, options)\n  let sawNonNull = false\n\n  OUTER: for (const simpleSub of sub.set) {\n    for (const simpleDom of dom.set) {\n      const isSub = simpleSubset(simpleSub, simpleDom, options)\n      sawNonNull = sawNonNull || isSub !== null\n      if (isSub) {\n        continue OUTER\n      }\n    }\n    // the null set is a subset of everything, but null simple ranges in\n    // a complex range should be ignored.  so if we saw a non-null range,\n    // then we know this isn't a subset, but if EVERY simple range was null,\n    // then it is a subset.\n    if (sawNonNull) {\n      return false\n    }\n  }\n  return true\n}\n\nconst minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]\nconst minimumVersion = [new Comparator('>=0.0.0')]\n\nconst simpleSubset = (sub, dom, options) => {\n  if (sub === dom) {\n    return true\n  }\n\n  if (sub.length === 1 && sub[0].semver === ANY) {\n    if (dom.length === 1 && dom[0].semver === ANY) {\n      return true\n    } else if (options.includePrerelease) {\n      sub = minimumVersionWithPreRelease\n    } else {\n      sub = minimumVersion\n    }\n  }\n\n  if (dom.length === 1 && dom[0].semver === ANY) {\n    if (options.includePrerelease) {\n      return true\n    } else {\n      dom = minimumVersion\n    }\n  }\n\n  const eqSet = new Set()\n  let gt, lt\n  for (const c of sub) {\n    if (c.operator === '>' || c.operator === '>=') {\n      gt = higherGT(gt, c, options)\n    } else if (c.operator === '<' || c.operator === '<=') {\n      lt = lowerLT(lt, c, options)\n    } else {\n      eqSet.add(c.semver)\n    }\n  }\n\n  if (eqSet.size > 1) {\n    return null\n  }\n\n  let gtltComp\n  if (gt && lt) {\n    gtltComp = compare(gt.semver, lt.semver, options)\n    if (gtltComp > 0) {\n      return null\n    } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {\n      return null\n    }\n  }\n\n  // will iterate one or zero times\n  for (const eq of eqSet) {\n    if (gt && !satisfies(eq, String(gt), options)) {\n      return null\n    }\n\n    if (lt && !satisfies(eq, String(lt), options)) {\n      return null\n    }\n\n    for (const c of dom) {\n      if (!satisfies(eq, String(c), options)) {\n        return false\n      }\n    }\n\n    return true\n  }\n\n  let higher, lower\n  let hasDomLT, hasDomGT\n  // if the subset has a prerelease, we need a comparator in the superset\n  // with the same tuple and a prerelease, or it's not a subset\n  let needDomLTPre = lt &&\n    !options.includePrerelease &&\n    lt.semver.prerelease.length ? lt.semver : false\n  let needDomGTPre = gt &&\n    !options.includePrerelease &&\n    gt.semver.prerelease.length ? gt.semver : false\n  // exception: <1.2.3-0 is the same as <1.2.3\n  if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&\n      lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {\n    needDomLTPre = false\n  }\n\n  for (const c of dom) {\n    hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='\n    hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='\n    if (gt) {\n      if (needDomGTPre) {\n        if (c.semver.prerelease && c.semver.prerelease.length &&\n            c.semver.major === needDomGTPre.major &&\n            c.semver.minor === needDomGTPre.minor &&\n            c.semver.patch === needDomGTPre.patch) {\n          needDomGTPre = false\n        }\n      }\n      if (c.operator === '>' || c.operator === '>=') {\n        higher = higherGT(gt, c, options)\n        if (higher === c && higher !== gt) {\n          return false\n        }\n      } else if (gt.operator === '>=' && !c.test(gt.semver)) {\n        return false\n      }\n    }\n    if (lt) {\n      if (needDomLTPre) {\n        if (c.semver.prerelease && c.semver.prerelease.length &&\n            c.semver.major === needDomLTPre.major &&\n            c.semver.minor === needDomLTPre.minor &&\n            c.semver.patch === needDomLTPre.patch) {\n          needDomLTPre = false\n        }\n      }\n      if (c.operator === '<' || c.operator === '<=') {\n        lower = lowerLT(lt, c, options)\n        if (lower === c && lower !== lt) {\n          return false\n        }\n      } else if (lt.operator === '<=' && !c.test(lt.semver)) {\n        return false\n      }\n    }\n    if (!c.operator && (lt || gt) && gtltComp !== 0) {\n      return false\n    }\n  }\n\n  // if there was a < or >, and nothing in the dom, then must be false\n  // UNLESS it was limited by another range in the other direction.\n  // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0\n  if (gt && hasDomLT && !lt && gtltComp !== 0) {\n    return false\n  }\n\n  if (lt && hasDomGT && !gt && gtltComp !== 0) {\n    return false\n  }\n\n  // we needed a prerelease range in a specific tuple, but didn't get one\n  // then this isn't a subset.  eg >=1.2.3-pre is not a subset of >=1.0.0,\n  // because it includes prereleases in the 1.2.3 tuple\n  if (needDomGTPre || needDomLTPre) {\n    return false\n  }\n\n  return true\n}\n\n// >=1.2.3 is lower than >1.2.3\nconst higherGT = (a, b, options) => {\n  if (!a) {\n    return b\n  }\n  const comp = compare(a.semver, b.semver, options)\n  return comp > 0 ? a\n    : comp < 0 ? b\n    : b.operator === '>' && a.operator === '>=' ? b\n    : a\n}\n\n// <=1.2.3 is higher than <1.2.3\nconst lowerLT = (a, b, options) => {\n  if (!a) {\n    return b\n  }\n  const comp = compare(a.semver, b.semver, options)\n  return comp < 0 ? a\n    : comp > 0 ? b\n    : b.operator === '<' && a.operator === '<=' ? b\n    : a\n}\n\nmodule.exports = subset\n", "'use strict'\n\n// just pre-load all the stuff that index.js lazily exports\nconst internalRe = require('./internal/re')\nconst constants = require('./internal/constants')\nconst SemVer = require('./classes/semver')\nconst identifiers = require('./internal/identifiers')\nconst parse = require('./functions/parse')\nconst valid = require('./functions/valid')\nconst clean = require('./functions/clean')\nconst inc = require('./functions/inc')\nconst diff = require('./functions/diff')\nconst major = require('./functions/major')\nconst minor = require('./functions/minor')\nconst patch = require('./functions/patch')\nconst prerelease = require('./functions/prerelease')\nconst compare = require('./functions/compare')\nconst rcompare = require('./functions/rcompare')\nconst compareLoose = require('./functions/compare-loose')\nconst compareBuild = require('./functions/compare-build')\nconst sort = require('./functions/sort')\nconst rsort = require('./functions/rsort')\nconst gt = require('./functions/gt')\nconst lt = require('./functions/lt')\nconst eq = require('./functions/eq')\nconst neq = require('./functions/neq')\nconst gte = require('./functions/gte')\nconst lte = require('./functions/lte')\nconst cmp = require('./functions/cmp')\nconst coerce = require('./functions/coerce')\nconst truncate = require('./functions/truncate')\nconst Comparator = require('./classes/comparator')\nconst Range = require('./classes/range')\nconst satisfies = require('./functions/satisfies')\nconst toComparators = require('./ranges/to-comparators')\nconst maxSatisfying = require('./ranges/max-satisfying')\nconst minSatisfying = require('./ranges/min-satisfying')\nconst minVersion = require('./ranges/min-version')\nconst validRange = require('./ranges/valid')\nconst outside = require('./ranges/outside')\nconst gtr = require('./ranges/gtr')\nconst ltr = require('./ranges/ltr')\nconst intersects = require('./ranges/intersects')\nconst simplifyRange = require('./ranges/simplify')\nconst subset = require('./ranges/subset')\nmodule.exports = {\n  parse,\n  valid,\n  clean,\n  inc,\n  diff,\n  major,\n  minor,\n  patch,\n  prerelease,\n  compare,\n  rcompare,\n  compareLoose,\n  compareBuild,\n  sort,\n  rsort,\n  gt,\n  lt,\n  eq,\n  neq,\n  gte,\n  lte,\n  cmp,\n  coerce,\n  truncate,\n  Comparator,\n  Range,\n  satisfies,\n  toComparators,\n  maxSatisfying,\n  minSatisfying,\n  minVersion,\n  validRange,\n  outside,\n  gtr,\n  ltr,\n  intersects,\n  simplifyRange,\n  subset,\n  SemVer,\n  re: internalRe.re,\n  src: internalRe.src,\n  tokens: internalRe.t,\n  SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,\n  RELEASE_TYPES: constants.RELEASE_TYPES,\n  compareIdentifiers: identifiers.compareIdentifiers,\n  rcompareIdentifiers: identifiers.rcompareIdentifiers,\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { MEDPLUM_VERSION, normalizeErrorString } from '@medplum/core';\nimport { CommanderError, Option } from 'commander';\nimport dotenv from 'dotenv';\nimport { agent } from './agent';\nimport { login, token, whoami } from './auth';\nimport { buildAwsCommand } from './aws/index';\nimport { bot, createBotDeprecate, deployBotDeprecate, saveBotDeprecate } from './bots';\nimport { bulk } from './bulk';\nimport { hl7 } from './hl7';\nimport { profile } from './profiles';\nimport { project } from './project';\nimport { deleteObject, get, patch, post, put } from './rest';\nimport { addSubcommand, MedplumCommand } from './utils';\n\nexport async function main(argv: string[]): Promise<void> {\n  const index = new MedplumCommand('medplum')\n    .description('Command to access Medplum CLI')\n    .option('--client-id <clientId>', 'FHIR server client id')\n    .option('--client-secret <clientSecret>', 'FHIR server client secret')\n    .option('--base-url <baseUrl>', 'FHIR server base URL, must be absolute')\n    .option('--token-url <tokenUrl>', 'FHIR server token URL, absolute or relative to base URL')\n    .option('--authorize-url <authorizeUrl>', 'FHIR server authorize URL, absolute or relative to base URL')\n    .option('--fhir-url, --fhir-url-path <fhirUrlPath>', 'FHIR server URL, absolute or relative to base URL')\n    .option('--scope <scope>', 'JWT scope')\n    .option('--access-token <accessToken>', 'Access token for token exchange authentication')\n    .option('--callback-url <callbackUrl>', 'Callback URL for authorization code flow')\n    .option('--subject <subject>', 'Subject for JWT authentication')\n    .option('--audience <audience>', 'Audience for JWT authentication')\n    .option('--issuer <issuer>', 'Issuer for JWT authentication')\n    .option('--private-key-path <privateKeyPath>', 'Private key path for JWT assertion')\n    .option('-p, --profile <profile>', 'Profile name')\n    .option('-v --verbose', 'Verbose output')\n    .addOption(\n      new Option('--auth-type <authType>', 'Type of authentication').choices([\n        'basic',\n        'client-credentials',\n        'authorization-code',\n        'jwt-bearer',\n        'token-exchange',\n        'jwt-assertion',\n      ])\n    )\n    .on('option:verbose', () => {\n      process.env.VERBOSE = '1';\n    });\n\n  // Configure CLI\n  index.exitOverride();\n  index.version(MEDPLUM_VERSION);\n  index.configureHelp({ showGlobalOptions: true });\n\n  // Auth commands\n  addSubcommand(index, login);\n  addSubcommand(index, whoami);\n  addSubcommand(index, token);\n\n  // REST commands\n  addSubcommand(index, get);\n  addSubcommand(index, post);\n  addSubcommand(index, patch);\n  addSubcommand(index, put);\n  addSubcommand(index, deleteObject);\n\n  // Project\n  addSubcommand(index, project);\n\n  // Bulk Commands\n  addSubcommand(index, bulk);\n\n  // Bot Commands\n  addSubcommand(index, bot);\n\n  // Agent Commands\n  addSubcommand(index, agent);\n\n  // Deprecated Bot Commands\n  addSubcommand(index, saveBotDeprecate);\n  addSubcommand(index, deployBotDeprecate);\n  addSubcommand(index, createBotDeprecate);\n\n  // Profile Commands\n  addSubcommand(index, profile);\n\n  // AWS commands\n  addSubcommand(index, buildAwsCommand());\n\n  // HL7 commands\n  addSubcommand(index, hl7);\n\n  try {\n    await index.parseAsync(argv);\n  } catch (err) {\n    handleError(err as Error);\n  }\n}\n\nexport function handleError(err: Error | CommanderError): void {\n  let exitCode = 1;\n  let shouldPrint = true;\n  if (err instanceof CommanderError) {\n    // We return if not in verbose mode for CommanderErrors\n    // Since commander.js will already log the error to console for us\n    // Previously we didn't have this guard here and it would always double print errors\n    if (!process.env.VERBOSE) {\n      shouldPrint = false;\n    }\n    exitCode = err.exitCode;\n  }\n  if (exitCode !== 0 && shouldPrint) {\n    writeErrorToStderr(err, !!process.env.VERBOSE);\n    const cause = err.cause;\n    if (process.env.VERBOSE) {\n      if (Array.isArray(cause)) {\n        for (const err of cause as Error[]) {\n          writeErrorToStderr(err, true);\n        }\n      } else if (cause instanceof Error) {\n        writeErrorToStderr(cause, true);\n      }\n    }\n  }\n  process.exit(exitCode);\n}\n\nfunction writeErrorToStderr(err: unknown, verbose = false): void {\n  if (verbose) {\n    console.error(err);\n    return;\n  }\n  if (err instanceof CommanderError) {\n    process.stderr.write(`${normalizeErrorString(err)}\\n`);\n  } else {\n    process.stderr.write(`Error: ${normalizeErrorString(err)}\\n`);\n  }\n}\n\nexport async function run(): Promise<void> {\n  dotenv.config({ quiet: true });\n  await main(process.argv);\n}\n\nif (import.meta.main) {\n  run().catch((err) => {\n    console.error('Unhandled error:', normalizeErrorString(err));\n    process.exit(1);\n  });\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type {\n  AgentChannelStats,\n  AgentStats,\n  AgentStatValue,\n  IssueSeverity,\n  MedplumClient,\n  MedplumClientOptions,\n  WithId,\n} from '@medplum/core';\nimport { ContentType, EMPTY, isOk, isUUID, normalizeErrorString } from '@medplum/core';\nimport type { Agent, Bundle, OperationOutcome, Parameters, ParametersParameter, Reference } from '@medplum/fhirtypes';\nimport { Option } from 'commander';\nimport { createMedplumClient } from './util/client';\nimport { addSubcommand, MedplumCommand } from './utils';\n\nexport type ValidIdsOrCriteria = { type: 'ids'; ids: string[] } | { type: 'criteria'; criteria: string };\n\nexport type ParsedParametersMap<R extends string[], O extends string[]> = Record<R[number], string> &\n  Record<O[number], string | undefined>;\n\nexport type ParamNames<R extends string[], O extends string[] = []> = {\n  required: R;\n  optional?: O;\n};\n\nexport type AgentBulkOpResponse<T extends Parameters | OperationOutcome = Parameters | OperationOutcome> = {\n  agent: WithId<Agent>;\n  result: T;\n};\n\nexport type CallAgentBulkOperationArgs<T extends Record<string, unknown>, R extends Parameters | OperationOutcome> = {\n  operation: string;\n  agentIds: string[];\n  options: MedplumClientOptions & { criteria: string; output?: 'json' };\n  params?: Record<string, string | boolean | number>;\n  parseSuccessfulResponse: (response: AgentBulkOpResponse<R>) => T;\n  renderSuccessfulRows?: (rows: T[]) => void;\n};\n\nexport type FailedRow = {\n  id: string;\n  name: string;\n  severity: IssueSeverity;\n  code: string;\n  details: string;\n};\n\nexport type StatusRow = {\n  id: string;\n  name: string;\n  enabledStatus: string;\n  connectionStatus: string;\n  version: string;\n  statusLastUpdated: string;\n};\n\nconst agentStatusCommand = new MedplumCommand('status').aliases(['info', 'list', 'ls']);\nconst agentPingCommand = new MedplumCommand('ping');\nconst agentPushCommand = new MedplumCommand('push');\nconst agentReloadConfigCommand = new MedplumCommand('reload-config');\nconst agentUpgradeCommand = new MedplumCommand('upgrade');\nconst agentStatsCommand = new MedplumCommand('stats');\n\nexport const agent = new MedplumCommand('agent');\naddSubcommand(agent, agentStatusCommand);\naddSubcommand(agent, agentPingCommand);\naddSubcommand(agent, agentPushCommand);\naddSubcommand(agent, agentReloadConfigCommand);\naddSubcommand(agent, agentUpgradeCommand);\naddSubcommand(agent, agentStatsCommand);\n\nagentStatusCommand\n  .description('Get the status of a specified agent')\n  .argument('[agentIds...]', 'The ID(s) of the agent(s) to get the status of')\n  .option(\n    '--criteria <criteria>',\n    'An optional FHIR search criteria to resolve the agent to get the status of. Mutually exclusive with [agentIds...] arg'\n  )\n  .addOption(\n    new Option('--output <format>', 'An optional output format, defaults to table')\n      .choices(['table', 'json'])\n      .default('table')\n  )\n  .action(async (agentIds, options) => {\n    await callAgentBulkOperation({\n      operation: '$bulk-status',\n      agentIds,\n      options,\n      parseSuccessfulResponse: (response: AgentBulkOpResponse<Parameters>) => {\n        const statusEntry = parseParameterValues(response.result, {\n          required: ['status', 'version'],\n          optional: ['lastUpdated'],\n        });\n\n        return {\n          id: response.agent.id,\n          name: response.agent.name,\n          enabledStatus: response.agent.status,\n          version: statusEntry.version,\n          connectionStatus: statusEntry.status,\n          statusLastUpdated: statusEntry.lastUpdated ?? 'N/A',\n        } satisfies StatusRow;\n      },\n    });\n  });\n\nagentPingCommand\n  .description('Ping a host from a specified agent')\n  .argument('<ipOrDomain>', 'The IPv4 address or domain name to ping')\n  .argument(\n    '[agentId]',\n    'Conditionally optional ID of the agent to ping from. Mutually exclusive with --criteria <criteria> option'\n  )\n  .option('--count <count>', 'An optional amount of pings to issue before returning results', '1')\n  .option(\n    '--criteria <criteria>',\n    'An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg'\n  )\n  .action(async (ipOrDomain, agentId, options) => {\n    const medplum = await createMedplumClient(options);\n    const agentRef = await resolveAgentReference(medplum, agentId, options);\n\n    const count = Number.parseInt(options.count, 10);\n    if (Number.isNaN(count)) {\n      throw new Error('--count <count> must be an integer if specified');\n    }\n\n    try {\n      const pingResult = (await medplum.pushToAgent(agentRef, ipOrDomain, `PING ${count}`, ContentType.PING, true, {\n        maxRetries: 0,\n      })) as string;\n      console.info(pingResult);\n    } catch (err) {\n      throw new Error('Unexpected response from agent while pinging', { cause: err });\n    }\n  });\n\nagentPushCommand\n  .description('Push a message to a target device via a specified agent')\n  .argument('<deviceId>', 'The ID of the device to push the message to')\n  .argument('<message>', 'The message to send to the destination device')\n  .argument(\n    '[agentId]',\n    'Conditionally optional ID of the agent to send the message from. Mutually exclusive with --criteria <criteria> option'\n  )\n  .option('--content-type <contentType>', 'The content type of the message', ContentType.HL7_V2)\n  .option('--no-wait', 'Tells the server not to wait for a response from the destination device')\n  .option(\n    '--criteria <criteria>',\n    'An optional FHIR search criteria to resolve the agent to ping from. Mutually exclusive with [agentId] arg'\n  )\n  .action(async (deviceId, message, agentId, options) => {\n    const medplum = await createMedplumClient(options);\n    const agentRef = await resolveAgentReference(medplum, agentId, options);\n\n    let pushResult: string;\n    try {\n      pushResult = (await medplum.pushToAgent(\n        agentRef,\n        { reference: `Device/${deviceId}` },\n        message,\n        options.contentType,\n        options.wait !== false,\n        { maxRetries: 0 }\n      )) as string;\n    } catch (err) {\n      throw new Error('Unexpected response from agent while pushing message to agent', { cause: err });\n    }\n\n    console.info(pushResult);\n  });\n\nagentReloadConfigCommand\n  .description('Reload the config for the specified agent(s)')\n  .argument(\n    '[agentIds...]',\n    'The ID(s) of the agent(s) for which the config should be reloaded. Mutually exclusive with --criteria <criteria> flag'\n  )\n  .option(\n    '--criteria <criteria>',\n    'An optional FHIR search criteria to resolve the agent(s) for which to notify to reload their config. Mutually exclusive with [agentIds...] arg'\n  )\n  .addOption(\n    new Option('--output <format>', 'An optional output format, defaults to table')\n      .choices(['table', 'json'])\n      .default('table')\n  )\n  .action(async (agentIds, options) => {\n    await callAgentBulkOperation({\n      operation: '$reload-config',\n      agentIds,\n      options,\n      parseSuccessfulResponse: (response: AgentBulkOpResponse<OperationOutcome>) => {\n        return {\n          id: response.agent.id,\n          name: response.agent.name,\n        };\n      },\n    });\n  });\n\nagentUpgradeCommand\n  .description('Upgrade the version for the specified agent(s)')\n  .argument(\n    '[agentIds...]',\n    'The ID(s) of the agent(s) that should be upgraded. Mutually exclusive with --criteria <criteria> flag'\n  )\n  .option(\n    '--criteria <criteria>',\n    'An optional FHIR search criteria to resolve the agent(s) to upgrade. Mutually exclusive with [agentIds...] arg'\n  )\n  .option(\n    '--agentVersion <version>',\n    'An optional agent version to upgrade to. Defaults to the latest version if flag not included'\n  )\n  .option('--force', 'Forces an upgrade when a pending upgrade is in an inconsistent state. Use with caution.')\n  .addOption(\n    new Option('--output <format>', 'An optional output format, defaults to table')\n      .choices(['table', 'json'])\n      .default('table')\n  )\n  .action(async (agentIds, options) => {\n    const params: Record<string, string | boolean | number> = {};\n    if (options.agentVersion) {\n      params.version = options.agentVersion;\n    }\n    if (options.force) {\n      params.force = true;\n    }\n\n    await callAgentBulkOperation({\n      operation: '$upgrade',\n      agentIds,\n      options,\n      params,\n      parseSuccessfulResponse: (response: AgentBulkOpResponse<OperationOutcome>) => {\n        return {\n          id: response.agent.id,\n          name: response.agent.name,\n          version: options.agentVersion ?? 'latest',\n        };\n      },\n    });\n  });\n\nagentStatsCommand\n  .description('Get runtime statistics for the specified agent(s)')\n  .argument(\n    '[agentIds...]',\n    'The ID(s) of the agent(s) to get stats for. Mutually exclusive with --criteria <criteria> flag'\n  )\n  .option(\n    '--criteria <criteria>',\n    'An optional FHIR search criteria to resolve the agent(s) to get stats for. Mutually exclusive with [agentIds...] arg'\n  )\n  .addOption(\n    new Option('--output <format>', 'An optional output format, defaults to table')\n      .choices(['table', 'json'])\n      .default('table')\n  )\n  .action(async (agentIds, options) => {\n    await callAgentBulkOperation({\n      operation: '$stats',\n      agentIds,\n      options,\n      parseSuccessfulResponse: (response: AgentBulkOpResponse<Parameters>) => {\n        const { stats } = parseParameterValues(response.result, { required: ['stats'] });\n        let parsed: AgentStats | undefined;\n        try {\n          parsed = JSON.parse(stats) as AgentStats;\n        } catch (err) {\n          console.error(`Failed to parse stats for agent ${response.agent.id}: ${normalizeErrorString(err)}`);\n        }\n        return {\n          id: response.agent.id,\n          name: response.agent.name,\n          stats: parsed,\n        };\n      },\n      renderSuccessfulRows: (rows) => {\n        for (let i = 0; i < rows.length; i++) {\n          if (i > 0) {\n            console.info();\n          }\n          renderAgentStats(rows[i]);\n        }\n      },\n    });\n  });\n\nconst SUMMARY_STAT_KEYS = [\n  'live',\n  'ping',\n  'hl7ConnectionsOpen',\n  'hl7ClientCount',\n  'hl7QueueDepth',\n  'webSocketQueueDepth',\n  'outstandingHeartbeats',\n] as const satisfies readonly (keyof AgentStats)[];\n\nfunction formatStatValue(value: AgentStatValue | undefined): string {\n  if (value === null || value === undefined) {\n    return '';\n  }\n  if (typeof value === 'object') {\n    return JSON.stringify(value);\n  }\n  return value.toString();\n}\n\nfunction buildChannelStatsRows(\n  entries: Record<string, AgentChannelStats> | undefined\n): Record<string, number | string>[] {\n  if (!entries) {\n    return [];\n  }\n  return Object.entries(entries)\n    .filter(([, value]) => value?.rtt)\n    .map(([name, value]) => ({\n      name,\n      count: value.rtt.count,\n      pending: value.rtt.pendingCount,\n      'min (ms)': value.rtt.min,\n      'avg (ms)': value.rtt.average,\n      'max (ms)': value.rtt.max,\n      'p50 (ms)': value.rtt.p50,\n      'p95 (ms)': value.rtt.p95,\n      'p99 (ms)': value.rtt.p99,\n    }));\n}\n\nfunction renderAgentStats(row: { id: string; name?: string; stats: AgentStats | undefined }): void {\n  const heading = row.name ? `${row.name} (${row.id})` : row.id;\n  console.info(`Agent: ${heading}`);\n  if (!row.stats) {\n    console.info('  (stats unavailable)');\n    return;\n  }\n\n  const summary: Record<string, string> = {};\n  for (const key of SUMMARY_STAT_KEYS) {\n    summary[key] = formatStatValue(row.stats[key]);\n  }\n  const knownKeys = new Set<string>([...SUMMARY_STAT_KEYS, 'channelStats', 'clientStats']);\n  for (const [key, value] of Object.entries(row.stats)) {\n    if (!knownKeys.has(key)) {\n      summary[key] = formatStatValue(value);\n    }\n  }\n  console.table(summary);\n\n  const channelRows = buildChannelStatsRows(row.stats.channelStats);\n  if (channelRows.length) {\n    console.info('Channel Stats:');\n    console.table(channelRows);\n  }\n\n  const clientRows = buildChannelStatsRows(row.stats.clientStats);\n  if (clientRows.length) {\n    console.info('Client Stats:');\n    console.table(clientRows);\n  }\n}\n\nexport async function callAgentBulkOperation<\n  T extends Record<string, unknown>,\n  R extends Parameters | OperationOutcome,\n>({\n  operation,\n  agentIds,\n  options,\n  params = {},\n  parseSuccessfulResponse,\n  renderSuccessfulRows,\n}: CallAgentBulkOperationArgs<T, R>): Promise<void> {\n  const normalized = parseEitherIdsOrCriteria(agentIds, options);\n  const medplum = await createMedplumClient(options);\n  const usedCriteria = normalized.type === 'criteria' ? normalized.criteria : `Agent?_id=${normalized.ids.join(',')}`;\n  const searchParams = new URLSearchParams(usedCriteria.split('?')[1]);\n  for (const [paramName, paramVal] of Object.entries(params)) {\n    searchParams.append(paramName, paramVal.toString());\n  }\n\n  let result: Bundle<Parameters> | Parameters | OperationOutcome;\n  try {\n    const url = medplum.fhirUrl('Agent', operation);\n    url.search = searchParams.toString();\n    result = await medplum.get(url, {\n      cache: 'reload',\n    });\n  } catch (err) {\n    throw new Error(`Operation '${operation}' failed`, { cause: err });\n  }\n\n  if (options.output === 'json') {\n    console.info(JSON.stringify(result, null, 2));\n    return;\n  }\n\n  const successfulResponses = [] as AgentBulkOpResponse<R>[];\n  const failedResponses = [] as AgentBulkOpResponse<OperationOutcome>[];\n\n  switch (result.resourceType) {\n    case 'Bundle': {\n      const responses = parseAgentBulkOpBundle(result);\n      for (const response of responses) {\n        if (response.result.resourceType === 'Parameters' || isOk(response.result)) {\n          successfulResponses.push(response as AgentBulkOpResponse<R>);\n        } else {\n          failedResponses.push(response as AgentBulkOpResponse<OperationOutcome>);\n        }\n      }\n      break;\n    }\n    case 'Parameters':\n    case 'OperationOutcome': {\n      const agent = await medplum.searchOne('Agent', searchParams, { cache: 'reload' });\n      if (!agent) {\n        throw new Error('Agent not found');\n      }\n      if (result.resourceType === 'Parameters') {\n        successfulResponses.push({ agent, result } as AgentBulkOpResponse<R>);\n      } else {\n        failedResponses.push({ agent, result });\n      }\n      break;\n    }\n    default:\n      throw new Error(`Invalid result received for '${operation}' operation: ${JSON.stringify(result)}`);\n  }\n\n  const successfulRows = [] as T[];\n  for (const response of successfulResponses) {\n    const row = parseSuccessfulResponse(response);\n    successfulRows.push(row);\n  }\n\n  const failedRows = [] as FailedRow[];\n  for (const response of failedResponses) {\n    const outcome = response.result;\n    const issue = outcome.issue?.[0];\n    const row = {\n      id: response.agent.id,\n      name: response.agent.name,\n      severity: issue.severity,\n      code: issue.code,\n      details: issue.details?.text ?? 'No details to show',\n    } satisfies FailedRow;\n    failedRows.push(row);\n  }\n\n  console.info(`\\n${successfulRows.length} successful response(s):\\n`);\n  if (renderSuccessfulRows) {\n    if (successfulRows.length) {\n      renderSuccessfulRows(successfulRows);\n    } else {\n      console.info('No successful responses received');\n    }\n  } else {\n    console.table(successfulRows.length ? successfulRows : 'No successful responses received');\n  }\n  console.info();\n\n  if (failedRows.length) {\n    console.info(`${failedRows.length} failed response(s):`);\n    console.info();\n    console.table(failedRows);\n  }\n}\n\nexport async function resolveAgentReference(\n  medplum: MedplumClient,\n  agentId: string | undefined,\n  options: Record<string, string>\n): Promise<Reference<Agent>> {\n  if (!(agentId || options.criteria)) {\n    throw new Error('This command requires either an [agentId] or a --criteria <criteria> flag');\n  }\n  if (agentId && options.criteria) {\n    throw new Error(\n      'Ambiguous arguments and options combination; [agentId] arg and --criteria <criteria> flag are mutually exclusive'\n    );\n  }\n\n  let usedId: string;\n  if (agentId) {\n    usedId = agentId;\n  } else {\n    assertValidAgentCriteria(options.criteria);\n    const result = await medplum.search('Agent', `${options.criteria.split('?')[1]}&_count=2`);\n    if (!result?.entry?.length) {\n      throw new Error('Could not find an agent matching the provided criteria');\n    }\n    if (result.entry.length !== 1) {\n      throw new Error(\n        'Found more than one agent matching this criteria. This operation requires the criteria to resolve to exactly one agent'\n      );\n    }\n    usedId = result.entry[0].resource?.id as string;\n  }\n\n  return { reference: `Agent/${usedId}` };\n}\n\nexport function parseAgentBulkOpBundle(bundle: Bundle<Parameters>): AgentBulkOpResponse[] {\n  const responses = [];\n  for (const entry of bundle.entry ?? EMPTY) {\n    if (!entry.resource) {\n      throw new Error('No Parameter resource found in entry');\n    }\n    responses.push(parseAgentBulkOpParameters(entry.resource));\n  }\n  return responses;\n}\n\nexport function parseAgentBulkOpParameters(params: Parameters): AgentBulkOpResponse {\n  const agent = params.parameter?.find((p) => p.name === 'agent')?.resource as WithId<Agent>;\n  if (!agent) {\n    throw new Error(\"Agent bulk operation response missing 'agent'\");\n  }\n  if (agent.resourceType !== 'Agent') {\n    throw new Error(`Agent bulk operation returned 'agent' with type '${agent.resourceType}'`);\n  }\n  const result = params.parameter?.find((p) => p.name === 'result')?.resource;\n  if (!result) {\n    throw new Error(\"Agent bulk operation response missing result'\");\n  }\n  if (!(result.resourceType === 'Parameters' || result.resourceType === 'OperationOutcome')) {\n    throw new Error(`Agent bulk operation returned 'result' with type '${result.resourceType}'`);\n  }\n  return { agent, result };\n}\n\nexport function parseParameterValues<const R extends string[], const O extends string[] = []>(\n  params: Parameters,\n  paramNames: ParamNames<R, O>\n): ParsedParametersMap<R, O> {\n  const map = {} as ParsedParametersMap<R, O>;\n  const requiredParams = paramNames.required;\n  const optionalParams = paramNames.optional;\n\n  for (const paramName of requiredParams) {\n    const paramsParam = params.parameter?.find((p) => p.name === paramName);\n    if (!paramsParam) {\n      throw new Error(`Failed to find parameter '${paramName}'`);\n    }\n    let valueProp: string | undefined;\n    for (const prop in paramsParam) {\n      // This technically could lead to parsing invalid values (ie. valueAbc123) but for now we can pretend this always works\n      if (prop.startsWith('value')) {\n        if (valueProp) {\n          throw new Error(`Found multiple values for parameter '${paramName}'`);\n        }\n        valueProp = prop;\n      }\n    }\n    if (!valueProp) {\n      throw new Error(`Failed to find a value for parameter '${paramName}'`);\n    }\n\n    // @ts-expect-error ParsedParameterMap expects key to be T[number], which it is, but unable to be inferred in for-of loop\n    map[paramName] = paramsParam[valueProp] as string;\n  }\n\n  if (optionalParams?.length) {\n    for (const paramName of optionalParams) {\n      const paramsParam = params.parameter?.find((p) => p.name === paramName);\n      if (!paramsParam) {\n        continue;\n      }\n      const value = extractValueFromParametersParameter(paramName, paramsParam);\n      // @ts-expect-error ParsedParameterMap expects key to be T[number], which it is, but unable to be inferred in for-of loop\n      map[paramName] = value;\n    }\n  }\n\n  return map;\n}\n\nexport function extractValueFromParametersParameter(paramName: string, paramsParam: ParametersParameter): string {\n  let valueProp: string | undefined;\n  for (const prop in paramsParam) {\n    // This technically could lead to parsing invalid values (ie. valueAbc123) but for now we can pretend this always works\n    if (prop.startsWith('value')) {\n      if (valueProp) {\n        throw new Error(`Found multiple values for parameter '${paramName}'`);\n      }\n      valueProp = prop;\n    }\n  }\n  if (!valueProp) {\n    throw new Error(`Failed to find a value for parameter '${paramName}'`);\n  }\n  // @ts-expect-error valueProp is any string but it should only be choice-of-type `value[x]`\n  return paramsParam[valueProp] as string;\n}\n\nexport function parseEitherIdsOrCriteria(agentIds: string[], options: { criteria: string }): ValidIdsOrCriteria {\n  if (!Array.isArray(agentIds)) {\n    throw new Error('Invalid agent IDs array');\n  }\n  if (agentIds.length) {\n    // Check that options.criteria is not defined\n    if (options.criteria) {\n      throw new Error(\n        'Ambiguous arguments and options combination; [agentIds...] arg and --criteria <criteria> flag are mutually exclusive'\n      );\n    }\n    for (const id of agentIds) {\n      if (!isUUID(id)) {\n        throw new Error(`Input '${id}' is not a valid agentId`);\n      }\n    }\n    return { type: 'ids', ids: agentIds };\n  }\n  if (options.criteria) {\n    assertValidAgentCriteria(options.criteria);\n    return { type: 'criteria', criteria: options.criteria };\n  }\n\n  throw new Error('Either an [agentId...] arg or a --criteria <criteria> flag is required');\n}\n\nfunction assertValidAgentCriteria(criteria: string): void {\n  const invalidCriteriaMsg =\n    \"Criteria must be formatted as a string containing the resource type (Agent) followed by a '?' and valid URL search query params, eg. `Agent?name=Test Agent`\";\n  if (typeof criteria !== 'string') {\n    throw new Error(invalidCriteriaMsg);\n  }\n  const [resourceType, queryStr] = criteria.split('?');\n  if (resourceType !== 'Agent' || !queryStr) {\n    throw new Error(invalidCriteriaMsg);\n  }\n  try {\n    // eslint-disable-next-line no-new\n    new URLSearchParams(queryStr);\n  } catch (err) {\n    throw new Error(invalidCriteriaMsg, { cause: err });\n  }\n  if (!queryStr.includes('=')) {\n    throw new Error(invalidCriteriaMsg, { cause: new Error('Query string lacks at least one `=`') });\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClientOptions } from '@medplum/core';\nimport { MedplumClient } from '@medplum/core';\nimport { FileSystemStorage } from '../storage';\nimport type { Profile } from '../utils';\n\nexport async function createMedplumClient(\n  options: MedplumClientOptions & { profile?: string },\n  setupCredentials = true\n): Promise<MedplumClient> {\n  const profileName = options.profile ?? 'default';\n\n  const storage = new FileSystemStorage(profileName);\n  const profile = storage.getObject('options') as Profile;\n  if (profileName !== 'default' && !profile) {\n    throw new Error(`Profile \"${profileName}\" does not exist`);\n  }\n\n  const { baseUrl, fhirUrlPath, accessToken, tokenUrl, authorizeUrl, clientId, clientSecret } = getClientValues(\n    options,\n    storage\n  );\n  const fetchApi = options.fetch ?? fetch;\n\n  // Validate base URL if non-default is specified\n  if (options.baseUrl && options.baseUrl !== 'https://api.medplum.com/') {\n    await validateBaseUrl(options.baseUrl, fetchApi);\n  }\n\n  const medplumClient = new MedplumClient({\n    fetch: fetchApi,\n    baseUrl,\n    tokenUrl,\n    fhirUrlPath,\n    authorizeUrl,\n    storage,\n    onUnauthenticated,\n    verbose: options.verbose,\n  });\n\n  // In most commands, we want to automatically set up credentials.\n  // However, in some cases such as \"login\", we don't want to do that.\n  // Setup credentials if the user does not explicitly disable it.\n  if (setupCredentials) {\n    if (accessToken) {\n      // If the access token is provided, use it.\n      medplumClient.setAccessToken(accessToken);\n    } else if (clientId && clientSecret) {\n      // If the client ID and secret are provided, use them.\n      medplumClient.setBasicAuth(clientId, clientSecret);\n      if (profile?.authType !== 'basic') {\n        // Unless the user explicitly specified basic auth, start the client login.\n        await medplumClient.startClientLogin(clientId, clientSecret);\n      }\n    }\n  }\n\n  return medplumClient;\n}\n\nfunction getClientValues(options: MedplumClientOptions, storage: FileSystemStorage): MedplumClientOptions {\n  const storageOptions = storage.getObject('options') as MedplumClientOptions;\n  const baseUrl =\n    options.baseUrl ?? storageOptions?.baseUrl ?? process.env['MEDPLUM_BASE_URL'] ?? 'https://api.medplum.com/';\n  const fhirUrlPath = options.fhirUrlPath ?? storageOptions?.fhirUrlPath ?? process.env['MEDPLUM_FHIR_URL_PATH'];\n  const accessToken = options.accessToken ?? storageOptions?.accessToken ?? process.env['MEDPLUM_CLIENT_ACCESS_TOKEN'];\n  const tokenUrl = options.tokenUrl ?? storageOptions?.tokenUrl ?? process.env['MEDPLUM_TOKEN_URL'];\n  const authorizeUrl = options.authorizeUrl ?? storageOptions?.authorizeUrl ?? process.env['MEDPLUM_AUTHORIZE_URL'];\n\n  const clientId = options.clientId ?? storageOptions?.clientId ?? process.env['MEDPLUM_CLIENT_ID'];\n  const clientSecret = options.clientSecret ?? storageOptions?.clientSecret ?? process.env['MEDPLUM_CLIENT_SECRET'];\n\n  return { baseUrl, fhirUrlPath, accessToken, tokenUrl, authorizeUrl, clientId, clientSecret };\n}\n\nasync function validateBaseUrl(\n  baseUrl: string,\n  fetchApi: (input: string, init?: RequestInit) => Promise<Response>\n): Promise<void> {\n  try {\n    const url = new URL('healthcheck', baseUrl).toString();\n    const response = await fetchApi(url);\n    if (!response.ok) {\n      throw new Error(`Healthcheck returned status ${response.status}`);\n    }\n    const data = (await response.json()) as { ok?: unknown };\n    if (data.ok === true) {\n      return;\n    }\n    throw new Error('Healthcheck response does not have \"ok\": true');\n  } catch (err) {\n    const message = err instanceof Error ? err.message : String(err);\n    throw new Error(`Failed to validate base URL \"${baseUrl}\": ${message}`);\n  }\n}\n\nexport function onUnauthenticated(): void {\n  console.log('Unauthenticated: run `npx medplum login` to sign in');\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ClientStorage } from '@medplum/core';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { resolve } from 'node:path';\n\nexport class FileSystemStorage extends ClientStorage {\n  private readonly dirName: string;\n  private readonly fileName: string;\n\n  constructor(profile: string) {\n    super();\n    this.dirName = resolve(homedir(), '.medplum');\n    this.fileName = resolve(this.dirName, profile + '.json');\n  }\n\n  clear(): void {\n    this.writeFile({});\n  }\n\n  getString(key: string): string | undefined {\n    return this.readFile()?.[key];\n  }\n\n  setString(key: string, value: string | undefined): void {\n    const data = this.readFile() ?? {};\n    if (value) {\n      data[key] = value;\n    } else {\n      delete data[key];\n    }\n    this.writeFile(data);\n  }\n\n  getObject<T>(key: string): T | undefined {\n    const str = this.getString(key);\n    return str ? (JSON.parse(str) as T) : undefined;\n  }\n\n  setObject<T>(key: string, value: T): void {\n    this.setString(key, value ? JSON.stringify(value) : undefined);\n  }\n\n  private readFile(): Record<string, string> | undefined {\n    if (existsSync(this.fileName)) {\n      return JSON.parse(readFileSync(this.fileName, 'utf8'));\n    }\n    return undefined;\n  }\n\n  private writeFile(data: Record<string, string>): void {\n    if (!existsSync(this.dirName)) {\n      mkdirSync(this.dirName);\n    }\n    writeFileSync(this.fileName, JSON.stringify(data, null, 2), 'utf8');\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient, WithId } from '@medplum/core';\nimport { ContentType, encodeBase64, OAuthSigningAlgorithm } from '@medplum/core';\nimport type { Bot, Extension, OperationOutcome } from '@medplum/fhirtypes';\nimport { Command } from 'commander';\nimport { SignJWT } from 'jose';\nimport { createHmac, createPrivateKey, randomBytes } from 'node:crypto';\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { basename, extname, resolve } from 'node:path';\nimport { isPromise } from 'node:util/types';\nimport { extract } from 'tar';\nimport { FileSystemStorage } from './storage';\n\nexport interface MedplumConfig {\n  baseUrl?: string;\n  clientId?: string;\n  googleClientId?: string;\n  recaptchaSiteKey?: string;\n  registerEnabled?: boolean;\n  bots?: MedplumBotConfig[];\n}\n\nexport interface MedplumBotConfig {\n  readonly name: string;\n  readonly id: string;\n  readonly source: string;\n  readonly dist?: string;\n}\n\nexport interface Profile {\n  readonly name?: string;\n  readonly authType?: string;\n  readonly baseUrl?: string;\n  readonly clientId?: string;\n  readonly clientSecret?: string;\n  readonly tokenUrl?: string;\n  readonly authorizeUrl?: string;\n  readonly fhirUrlPath?: string;\n  readonly scope?: string;\n  readonly accessToken?: string;\n  readonly callbackUrl?: string;\n  readonly subject?: string;\n  readonly audience?: string;\n  readonly issuer?: string;\n  readonly privateKeyPath?: string;\n}\n\nexport function prettyPrint(input: unknown): void {\n  console.log(JSON.stringify(input, null, 2));\n}\n\nexport async function saveBot(medplum: MedplumClient, botConfig: MedplumBotConfig, bot: Bot): Promise<void> {\n  const codePath = botConfig.source;\n  const code = readFileContents(codePath);\n  if (!code) {\n    return;\n  }\n\n  console.log('Saving source code...');\n  const sourceCode = await medplum.createAttachment({\n    data: code,\n    filename: basename(codePath),\n    contentType: getCodeContentType(codePath),\n  });\n\n  console.log('Updating bot...');\n  const updateResult = await medplum.updateResource({\n    ...bot,\n    sourceCode,\n  });\n  console.log('Success! New bot version: ' + updateResult.meta?.versionId);\n}\n\nexport async function deployBot(medplum: MedplumClient, botConfig: MedplumBotConfig, bot: WithId<Bot>): Promise<void> {\n  const codePath = botConfig.dist ?? botConfig.source;\n  const code = readFileContents(codePath);\n  if (!code) {\n    return;\n  }\n\n  console.log('Deploying bot...');\n  const deployResult = await medplum.post<OperationOutcome>(medplum.fhirUrl('Bot', bot.id, '$deploy'), {\n    code,\n    filename: basename(codePath),\n  });\n  console.log('Deploy result: ' + deployResult.issue?.[0]?.details?.text);\n}\n\nexport async function createBot(\n  medplum: MedplumClient,\n  botName: string,\n  projectId: string,\n  sourceFile: string,\n  distFile: string,\n  runtimeVersion?: string,\n  writeConfig?: boolean\n): Promise<void> {\n  const body = {\n    name: botName,\n    description: '',\n    runtimeVersion,\n  };\n  const newBot = await medplum.post<WithId<Bot>>('admin/projects/' + projectId + '/bot', body);\n  const bot = await medplum.readResource('Bot', newBot.id);\n\n  const botConfig = {\n    name: botName,\n    id: newBot.id,\n    source: sourceFile,\n    dist: distFile,\n  };\n\n  await saveBot(medplum, botConfig, bot);\n  await deployBot(medplum, botConfig, bot);\n  console.log(`Success! Bot created: ${bot.id}`);\n\n  if (writeConfig) {\n    addBotToConfig(botConfig);\n  }\n}\n\nexport function readBotConfigs(botName: string): MedplumBotConfig[] {\n  const regExBotName = new RegExp('^' + escapeRegex(botName).replaceAll(String.raw`\\*`, '.*') + '$');\n  const botConfigs = readConfig()?.bots?.filter((b) => regExBotName.test(b.name));\n  if (!botConfigs) {\n    return [];\n  }\n  return botConfigs;\n}\n\n/**\n * Returns the config file name.\n * @param tagName - Optional environment tag name.\n * @param options - Optional command line options.\n * @returns The config file name.\n */\nexport function getConfigFileName(tagName?: string, options?: Record<string, any>): string {\n  if (options?.file) {\n    return options.file;\n  }\n  const parts = ['medplum'];\n  if (tagName) {\n    parts.push(tagName);\n  }\n  parts.push('config');\n  if (options?.server) {\n    parts.push('server');\n  }\n  parts.push('json');\n  return parts.join('.');\n}\n\n/**\n * Writes a config file to disk.\n * @param configFileName - The config file name.\n * @param config - The config file contents.\n */\nexport function writeConfig(configFileName: string, config: Record<string, any>): void {\n  writeFileSync(resolve(configFileName), JSON.stringify(config, undefined, 2), 'utf-8');\n}\n\nexport function readConfig(tagName?: string, options?: { file?: string }): MedplumConfig | undefined {\n  const fileName = getConfigFileName(tagName, options);\n  const content = readFileContents(fileName);\n  if (!content) {\n    return undefined;\n  }\n  return JSON.parse(content);\n}\n\nexport function readServerConfig(tagName?: string): Record<string, string | number> | undefined {\n  const content = readFileContents(getConfigFileName(tagName, { server: true }));\n  if (!content) {\n    return undefined;\n  }\n  return JSON.parse(content);\n}\n\nfunction readFileContents(fileName: string): string {\n  const path = resolve(fileName);\n  if (!existsSync(path)) {\n    return '';\n  }\n  return readFileSync(path, 'utf8');\n}\n\nfunction addBotToConfig(botConfig: MedplumBotConfig): void {\n  const config = readConfig() ?? {};\n  if (!config.bots) {\n    config.bots = [];\n  }\n  config.bots.push(botConfig);\n  writeFileSync('medplum.config.json', JSON.stringify(config, null, 2), 'utf8');\n  console.log(`Bot added to config: ${botConfig.id}`);\n}\n\nfunction escapeRegex(str: string): string {\n  return str.replaceAll(/[/\\-\\\\^$*+?.()|[\\]{}]/g, '\\\\$&');\n}\n\n/**\n * Creates a safe tar extractor that limits the number of files and total size.\n *\n * Expanding archive files without controlling resource consumption is security-sensitive\n *\n * See: https://sonarcloud.io/organizations/medplum/rules?open=typescript%3AS5042&rule_key=typescript%3AS5042\n * @param destinationDir - The destination directory where all files will be extracted.\n * @returns A tar file extractor.\n */\nexport function safeTarExtractor(destinationDir: string): NodeJS.WritableStream {\n  const MAX_FILES = 100;\n  const MAX_SIZE = 10 * 1024 * 1024; // 10 MB\n\n  let fileCount = 0;\n  let totalSize = 0;\n\n  return extract({\n    cwd: destinationDir,\n    filter: (_path, entry) => {\n      fileCount++;\n      if (fileCount > MAX_FILES) {\n        throw new Error('Tar extractor reached max number of files');\n      }\n\n      totalSize += entry.size;\n      if (totalSize > MAX_SIZE) {\n        throw new Error('Tar extractor reached max size');\n      }\n\n      return true;\n    },\n  });\n}\n\nexport function getUnsupportedExtension(): Extension {\n  return {\n    url: 'http://hl7.org/fhir/StructureDefinition/data-absent-reason',\n    valueCode: 'unsupported',\n  };\n}\n\nexport function getCodeContentType(filename: string): string {\n  const ext = extname(filename).toLowerCase();\n  if (['.cjs', '.mjs', '.js'].includes(ext)) {\n    return ContentType.JAVASCRIPT;\n  }\n  if (['.cts', '.mts', '.ts'].includes(ext)) {\n    return ContentType.TYPESCRIPT;\n  }\n  return ContentType.TEXT;\n}\n\nexport function saveProfile(profileName: string, options: Profile): Profile {\n  const storage = new FileSystemStorage(profileName);\n  const optionsObject = { name: profileName, ...options };\n  storage.setObject('options', optionsObject);\n  return optionsObject;\n}\n\nexport function loadProfile(profileName: string): Profile {\n  const storage = new FileSystemStorage(profileName);\n  return storage.getObject('options') as Profile;\n}\n\nexport function profileExists(storage: FileSystemStorage, profile: string): boolean {\n  if (profile === 'default') {\n    return true;\n  }\n  const optionsObject = storage.getObject('options');\n  if (!optionsObject) {\n    return false;\n  }\n  return true;\n}\n\nexport async function jwtBearerLogin(medplum: MedplumClient, profile: Profile): Promise<void> {\n  const header = {\n    typ: 'JWT',\n    alg: OAuthSigningAlgorithm.HS256,\n  };\n\n  const currentTimestamp = Math.floor(Date.now() / 1000);\n  const data = {\n    aud: `${profile.baseUrl}${profile.audience}`,\n    iss: profile.issuer,\n    sub: profile.subject,\n    nbf: currentTimestamp,\n    iat: currentTimestamp,\n    exp: currentTimestamp + 604800, // expiry time is 7 days from time of creation\n  };\n  const encodedHeader = encodeBase64(JSON.stringify(header));\n  const encodedData = encodeBase64(JSON.stringify(data));\n  const token = `${encodedHeader}.${encodedData}`;\n  const signature = createHmac('sha256', profile.clientSecret as string)\n    .update(token)\n    .digest('base64url');\n  const signedToken = `${token}.${signature}`;\n  await medplum.startJwtBearerLogin(profile.clientId as string, signedToken, profile.scope ?? '');\n}\n\nexport async function jwtAssertionLogin(medplum: MedplumClient, profile: Profile): Promise<void> {\n  const privateKey = createPrivateKey(readFileSync(resolve(profile.privateKeyPath as string)));\n  const jwt = await new SignJWT({})\n    .setProtectedHeader({ typ: 'JWT', alg: OAuthSigningAlgorithm.RS384 })\n    .setIssuer(profile.clientId as string)\n    .setSubject(profile.clientId as string)\n    .setAudience(`${profile.baseUrl}${profile.audience}`)\n    .setJti(randomBytes(16).toString('hex'))\n    .setIssuedAt()\n    .setExpirationTime('5m')\n    .sign(privateKey);\n  await medplum.startJwtAssertionLogin(jwt);\n}\n\n/**\n * Attaches the provided subcommand to the provided parent command.\n *\n * We use this rather than directly calling the `addCommand` method on the parent command because we need\n * to modify some additional settings on each command before adding them to the parent.\n *\n * @param command - The parent command.\n * @param subcommand - The command to attach to the provided parent command.\n */\nexport function addSubcommand(command: Command, subcommand: Command): void {\n  subcommand.configureHelp({ showGlobalOptions: true });\n  command.addCommand(subcommand);\n}\n\nexport class MedplumCommand extends Command {\n  action(fn: (...args: any[]) => void | Promise<void>): this {\n    // This is the only way to get both global and local options propagated to all subcommands automatically\n    // Otherwise you have to call `command.optsWithGlobals()` within every function to get merged global and local options\n    const wrappedFn = withMergedOptions(this, fn);\n    // @ts-expect-error Access to hidden member\n    // This is the function that gets called when a command is executed\n    // We overwrite it with the wrapped version\n    super._actionHandler = wrappedFn;\n    return this;\n  }\n\n  /**\n   * We use this method to reset the option state\n   * Which is not cleared between executions of the main function during tests\n   *\n   * This is because all of our subcommands are declared in the global scope\n   *\n   * Rather than re-architect the entire CLI package, I added this to make sure all options are reset between executions of main\n   */\n  resetOptionDefaults(): void {\n    // @ts-expect-error Overriding private field\n    this._optionValues = {};\n    for (const option of this.options) {\n      // So we also set options that default to false\n      // We explicitly check strict equality to undefined\n      if (option.defaultValue !== undefined) {\n        // We use the attributeName since that's the camelCase'd name that is used to access options\n        // @ts-expect-error Overriding private field\n        this._optionValues[option.attributeName()] = option.defaultValue;\n      }\n    }\n  }\n}\n\nexport function withMergedOptions(\n  command: MedplumCommand,\n  fn: ((...args: any[]) => Promise<void>) | ((...args: any[]) => void)\n): (args: any[]) => Promise<void> {\n  // The .action callback takes an extra parameter which is the command or options.\n  return async (args: any[]): Promise<void> => {\n    const expectedArgsCount = command.registeredArguments.length;\n    const actionArgs = args.slice(0, expectedArgsCount);\n    actionArgs[expectedArgsCount] = command.optsWithGlobals();\n    try {\n      const result: Promise<void> | void = fn(...actionArgs);\n      if (isPromise(result)) {\n        await result;\n      }\n    } finally {\n      // We want to always make sure to reset the options to default at the end of each execution,\n      // We do it in a finally block in case the command errors\n      command.resetOptionDefaults();\n    }\n  };\n}\n", "import { Buffer } from 'node:buffer';\nimport { decoder } from '../lib/buffer_utils.js';\nfunction normalize(input) {\n    let encoded = input;\n    if (encoded instanceof Uint8Array) {\n        encoded = decoder.decode(encoded);\n    }\n    return encoded;\n}\nconst encode = (input) => Buffer.from(input).toString('base64url');\nexport const decodeBase64 = (input) => new Uint8Array(Buffer.from(input, 'base64'));\nexport const encodeBase64 = (input) => Buffer.from(input).toString('base64');\nexport { encode };\nexport const decode = (input) => new Uint8Array(Buffer.from(normalize(input), 'base64url'));\n", "import digest from '../runtime/digest.js';\nexport const encoder = new TextEncoder();\nexport const decoder = new TextDecoder();\nconst MAX_INT32 = 2 ** 32;\nexport function concat(...buffers) {\n    const size = buffers.reduce((acc, { length }) => acc + length, 0);\n    const buf = new Uint8Array(size);\n    let i = 0;\n    for (const buffer of buffers) {\n        buf.set(buffer, i);\n        i += buffer.length;\n    }\n    return buf;\n}\nexport function p2s(alg, p2sInput) {\n    return concat(encoder.encode(alg), new Uint8Array([0]), p2sInput);\n}\nfunction writeUInt32BE(buf, value, offset) {\n    if (value < 0 || value >= MAX_INT32) {\n        throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);\n    }\n    buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset);\n}\nexport function uint64be(value) {\n    const high = Math.floor(value / MAX_INT32);\n    const low = value % MAX_INT32;\n    const buf = new Uint8Array(8);\n    writeUInt32BE(buf, high, 0);\n    writeUInt32BE(buf, low, 4);\n    return buf;\n}\nexport function uint32be(value) {\n    const buf = new Uint8Array(4);\n    writeUInt32BE(buf, value);\n    return buf;\n}\nexport function lengthAndInput(input) {\n    return concat(uint32be(input.length), input);\n}\nexport async function concatKdf(secret, bits, value) {\n    const iterations = Math.ceil((bits >> 3) / 32);\n    const res = new Uint8Array(iterations * 32);\n    for (let iter = 0; iter < iterations; iter++) {\n        const buf = new Uint8Array(4 + secret.length + value.length);\n        buf.set(uint32be(iter + 1));\n        buf.set(secret, 4);\n        buf.set(value, 4 + secret.length);\n        res.set(await digest('sha256', buf), iter * 32);\n    }\n    return res.slice(0, bits >> 3);\n}\n", "export class JOSEError extends Error {\n    static code = 'ERR_JOSE_GENERIC';\n    code = 'ERR_JOSE_GENERIC';\n    constructor(message, options) {\n        super(message, options);\n        this.name = this.constructor.name;\n        Error.captureStackTrace?.(this, this.constructor);\n    }\n}\nexport class JWTClaimValidationFailed extends JOSEError {\n    static code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n    code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n    claim;\n    reason;\n    payload;\n    constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n        super(message, { cause: { claim, reason, payload } });\n        this.claim = claim;\n        this.reason = reason;\n        this.payload = payload;\n    }\n}\nexport class JWTExpired extends JOSEError {\n    static code = 'ERR_JWT_EXPIRED';\n    code = 'ERR_JWT_EXPIRED';\n    claim;\n    reason;\n    payload;\n    constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n        super(message, { cause: { claim, reason, payload } });\n        this.claim = claim;\n        this.reason = reason;\n        this.payload = payload;\n    }\n}\nexport class JOSEAlgNotAllowed extends JOSEError {\n    static code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n    code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n}\nexport class JOSENotSupported extends JOSEError {\n    static code = 'ERR_JOSE_NOT_SUPPORTED';\n    code = 'ERR_JOSE_NOT_SUPPORTED';\n}\nexport class JWEDecryptionFailed extends JOSEError {\n    static code = 'ERR_JWE_DECRYPTION_FAILED';\n    code = 'ERR_JWE_DECRYPTION_FAILED';\n    constructor(message = 'decryption operation failed', options) {\n        super(message, options);\n    }\n}\nexport class JWEInvalid extends JOSEError {\n    static code = 'ERR_JWE_INVALID';\n    code = 'ERR_JWE_INVALID';\n}\nexport class JWSInvalid extends JOSEError {\n    static code = 'ERR_JWS_INVALID';\n    code = 'ERR_JWS_INVALID';\n}\nexport class JWTInvalid extends JOSEError {\n    static code = 'ERR_JWT_INVALID';\n    code = 'ERR_JWT_INVALID';\n}\nexport class JWKInvalid extends JOSEError {\n    static code = 'ERR_JWK_INVALID';\n    code = 'ERR_JWK_INVALID';\n}\nexport class JWKSInvalid extends JOSEError {\n    static code = 'ERR_JWKS_INVALID';\n    code = 'ERR_JWKS_INVALID';\n}\nexport class JWKSNoMatchingKey extends JOSEError {\n    static code = 'ERR_JWKS_NO_MATCHING_KEY';\n    code = 'ERR_JWKS_NO_MATCHING_KEY';\n    constructor(message = 'no applicable key found in the JSON Web Key Set', options) {\n        super(message, options);\n    }\n}\nexport class JWKSMultipleMatchingKeys extends JOSEError {\n    [Symbol.asyncIterator];\n    static code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n    code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n    constructor(message = 'multiple matching keys found in the JSON Web Key Set', options) {\n        super(message, options);\n    }\n}\nexport class JWKSTimeout extends JOSEError {\n    static code = 'ERR_JWKS_TIMEOUT';\n    code = 'ERR_JWKS_TIMEOUT';\n    constructor(message = 'request timed out', options) {\n        super(message, options);\n    }\n}\nexport class JWSSignatureVerificationFailed extends JOSEError {\n    static code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n    code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n    constructor(message = 'signature verification failed', options) {\n        super(message, options);\n    }\n}\n", "import * as util from 'node:util';\nexport default (obj) => util.types.isKeyObject(obj);\n", "import * as crypto from 'node:crypto';\nimport * as util from 'node:util';\nconst webcrypto = crypto.webcrypto;\nexport default webcrypto;\nexport const isCryptoKey = (key) => util.types.isCryptoKey(key);\n", "function unusable(name, prop = 'algorithm.name') {\n    return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);\n}\nfunction isAlgorithm(algorithm, name) {\n    return algorithm.name === name;\n}\nfunction getHashLength(hash) {\n    return parseInt(hash.name.slice(4), 10);\n}\nfunction getNamedCurve(alg) {\n    switch (alg) {\n        case 'ES256':\n            return 'P-256';\n        case 'ES384':\n            return 'P-384';\n        case 'ES512':\n            return 'P-521';\n        default:\n            throw new Error('unreachable');\n    }\n}\nfunction checkUsage(key, usages) {\n    if (usages.length && !usages.some((expected) => key.usages.includes(expected))) {\n        let msg = 'CryptoKey does not support this operation, its usages must include ';\n        if (usages.length > 2) {\n            const last = usages.pop();\n            msg += `one of ${usages.join(', ')}, or ${last}.`;\n        }\n        else if (usages.length === 2) {\n            msg += `one of ${usages[0]} or ${usages[1]}.`;\n        }\n        else {\n            msg += `${usages[0]}.`;\n        }\n        throw new TypeError(msg);\n    }\n}\nexport function checkSigCryptoKey(key, alg, ...usages) {\n    switch (alg) {\n        case 'HS256':\n        case 'HS384':\n        case 'HS512': {\n            if (!isAlgorithm(key.algorithm, 'HMAC'))\n                throw unusable('HMAC');\n            const expected = parseInt(alg.slice(2), 10);\n            const actual = getHashLength(key.algorithm.hash);\n            if (actual !== expected)\n                throw unusable(`SHA-${expected}`, 'algorithm.hash');\n            break;\n        }\n        case 'RS256':\n        case 'RS384':\n        case 'RS512': {\n            if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5'))\n                throw unusable('RSASSA-PKCS1-v1_5');\n            const expected = parseInt(alg.slice(2), 10);\n            const actual = getHashLength(key.algorithm.hash);\n            if (actual !== expected)\n                throw unusable(`SHA-${expected}`, 'algorithm.hash');\n            break;\n        }\n        case 'PS256':\n        case 'PS384':\n        case 'PS512': {\n            if (!isAlgorithm(key.algorithm, 'RSA-PSS'))\n                throw unusable('RSA-PSS');\n            const expected = parseInt(alg.slice(2), 10);\n            const actual = getHashLength(key.algorithm.hash);\n            if (actual !== expected)\n                throw unusable(`SHA-${expected}`, 'algorithm.hash');\n            break;\n        }\n        case 'EdDSA': {\n            if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') {\n                throw unusable('Ed25519 or Ed448');\n            }\n            break;\n        }\n        case 'Ed25519': {\n            if (!isAlgorithm(key.algorithm, 'Ed25519'))\n                throw unusable('Ed25519');\n            break;\n        }\n        case 'ES256':\n        case 'ES384':\n        case 'ES512': {\n            if (!isAlgorithm(key.algorithm, 'ECDSA'))\n                throw unusable('ECDSA');\n            const expected = getNamedCurve(alg);\n            const actual = key.algorithm.namedCurve;\n            if (actual !== expected)\n                throw unusable(expected, 'algorithm.namedCurve');\n            break;\n        }\n        default:\n            throw new TypeError('CryptoKey does not support this operation');\n    }\n    checkUsage(key, usages);\n}\nexport function checkEncCryptoKey(key, alg, ...usages) {\n    switch (alg) {\n        case 'A128GCM':\n        case 'A192GCM':\n        case 'A256GCM': {\n            if (!isAlgorithm(key.algorithm, 'AES-GCM'))\n                throw unusable('AES-GCM');\n            const expected = parseInt(alg.slice(1, 4), 10);\n            const actual = key.algorithm.length;\n            if (actual !== expected)\n                throw unusable(expected, 'algorithm.length');\n            break;\n        }\n        case 'A128KW':\n        case 'A192KW':\n        case 'A256KW': {\n            if (!isAlgorithm(key.algorithm, 'AES-KW'))\n                throw unusable('AES-KW');\n            const expected = parseInt(alg.slice(1, 4), 10);\n            const actual = key.algorithm.length;\n            if (actual !== expected)\n                throw unusable(expected, 'algorithm.length');\n            break;\n        }\n        case 'ECDH': {\n            switch (key.algorithm.name) {\n                case 'ECDH':\n                case 'X25519':\n                case 'X448':\n                    break;\n                default:\n                    throw unusable('ECDH, X25519, or X448');\n            }\n            break;\n        }\n        case 'PBES2-HS256+A128KW':\n        case 'PBES2-HS384+A192KW':\n        case 'PBES2-HS512+A256KW':\n            if (!isAlgorithm(key.algorithm, 'PBKDF2'))\n                throw unusable('PBKDF2');\n            break;\n        case 'RSA-OAEP':\n        case 'RSA-OAEP-256':\n        case 'RSA-OAEP-384':\n        case 'RSA-OAEP-512': {\n            if (!isAlgorithm(key.algorithm, 'RSA-OAEP'))\n                throw unusable('RSA-OAEP');\n            const expected = parseInt(alg.slice(9), 10) || 1;\n            const actual = getHashLength(key.algorithm.hash);\n            if (actual !== expected)\n                throw unusable(`SHA-${expected}`, 'algorithm.hash');\n            break;\n        }\n        default:\n            throw new TypeError('CryptoKey does not support this operation');\n    }\n    checkUsage(key, usages);\n}\n", "function message(msg, actual, ...types) {\n    types = types.filter(Boolean);\n    if (types.length > 2) {\n        const last = types.pop();\n        msg += `one of type ${types.join(', ')}, or ${last}.`;\n    }\n    else if (types.length === 2) {\n        msg += `one of type ${types[0]} or ${types[1]}.`;\n    }\n    else {\n        msg += `of type ${types[0]}.`;\n    }\n    if (actual == null) {\n        msg += ` Received ${actual}`;\n    }\n    else if (typeof actual === 'function' && actual.name) {\n        msg += ` Received function ${actual.name}`;\n    }\n    else if (typeof actual === 'object' && actual != null) {\n        if (actual.constructor?.name) {\n            msg += ` Received an instance of ${actual.constructor.name}`;\n        }\n    }\n    return msg;\n}\nexport default (actual, ...types) => {\n    return message('Key must be ', actual, ...types);\n};\nexport function withAlg(alg, actual, ...types) {\n    return message(`Key for the ${alg} algorithm must be `, actual, ...types);\n}\n", "import webcrypto, { isCryptoKey } from './webcrypto.js';\nimport isKeyObject from './is_key_object.js';\nexport default (key) => isKeyObject(key) || isCryptoKey(key);\nconst types = ['KeyObject'];\nif (globalThis.CryptoKey || webcrypto?.CryptoKey) {\n    types.push('CryptoKey');\n}\nexport { types };\n", "const isDisjoint = (...headers) => {\n    const sources = headers.filter(Boolean);\n    if (sources.length === 0 || sources.length === 1) {\n        return true;\n    }\n    let acc;\n    for (const header of sources) {\n        const parameters = Object.keys(header);\n        if (!acc || acc.size === 0) {\n            acc = new Set(parameters);\n            continue;\n        }\n        for (const parameter of parameters) {\n            if (acc.has(parameter)) {\n                return false;\n            }\n            acc.add(parameter);\n        }\n    }\n    return true;\n};\nexport default isDisjoint;\n", "function isObjectLike(value) {\n    return typeof value === 'object' && value !== null;\n}\nexport default function isObject(input) {\n    if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {\n        return false;\n    }\n    if (Object.getPrototypeOf(input) === null) {\n        return true;\n    }\n    let proto = input;\n    while (Object.getPrototypeOf(proto) !== null) {\n        proto = Object.getPrototypeOf(proto);\n    }\n    return Object.getPrototypeOf(input) === proto;\n}\n", "import { KeyObject } from 'node:crypto';\nimport { JOSENotSupported } from '../util/errors.js';\nimport { isCryptoKey } from './webcrypto.js';\nimport isKeyObject from './is_key_object.js';\nimport invalidKeyInput from '../lib/invalid_key_input.js';\nimport { types } from './is_key_like.js';\nimport { isJWK } from '../lib/is_jwk.js';\nexport const weakMap = new WeakMap();\nconst namedCurveToJOSE = (namedCurve) => {\n    switch (namedCurve) {\n        case 'prime256v1':\n            return 'P-256';\n        case 'secp384r1':\n            return 'P-384';\n        case 'secp521r1':\n            return 'P-521';\n        case 'secp256k1':\n            return 'secp256k1';\n        default:\n            throw new JOSENotSupported('Unsupported key curve for this operation');\n    }\n};\nconst getNamedCurve = (kee, raw) => {\n    let key;\n    if (isCryptoKey(kee)) {\n        key = KeyObject.from(kee);\n    }\n    else if (isKeyObject(kee)) {\n        key = kee;\n    }\n    else if (isJWK(kee)) {\n        return kee.crv;\n    }\n    else {\n        throw new TypeError(invalidKeyInput(kee, ...types));\n    }\n    if (key.type === 'secret') {\n        throw new TypeError('only \"private\" or \"public\" type keys can be used for this operation');\n    }\n    switch (key.asymmetricKeyType) {\n        case 'ed25519':\n        case 'ed448':\n            return `Ed${key.asymmetricKeyType.slice(2)}`;\n        case 'x25519':\n        case 'x448':\n            return `X${key.asymmetricKeyType.slice(1)}`;\n        case 'ec': {\n            const namedCurve = key.asymmetricKeyDetails.namedCurve;\n            if (raw) {\n                return namedCurve;\n            }\n            return namedCurveToJOSE(namedCurve);\n        }\n        default:\n            throw new TypeError('Invalid asymmetric key type for this operation');\n    }\n};\nexport default getNamedCurve;\n", "import isObject from './is_object.js';\nexport function isJWK(key) {\n    return isObject(key) && typeof key.kty === 'string';\n}\nexport function isPrivateJWK(key) {\n    return key.kty !== 'oct' && typeof key.d === 'string';\n}\nexport function isPublicJWK(key) {\n    return key.kty !== 'oct' && typeof key.d === 'undefined';\n}\nexport function isSecretJWK(key) {\n    return isJWK(key) && key.kty === 'oct' && typeof key.k === 'string';\n}\n", "import { KeyObject } from 'node:crypto';\nexport default (key, alg) => {\n    let modulusLength;\n    try {\n        if (key instanceof KeyObject) {\n            modulusLength = key.asymmetricKeyDetails?.modulusLength;\n        }\n        else {\n            modulusLength = Buffer.from(key.n, 'base64url').byteLength << 3;\n        }\n    }\n    catch { }\n    if (typeof modulusLength !== 'number' || modulusLength < 2048) {\n        throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);\n    }\n};\n", "import { withAlg as invalidKeyInput } from './invalid_key_input.js';\nimport isKeyLike, { types } from '../runtime/is_key_like.js';\nimport * as jwk from './is_jwk.js';\nconst tag = (key) => key?.[Symbol.toStringTag];\nconst jwkMatchesOp = (alg, key, usage) => {\n    if (key.use !== undefined && key.use !== 'sig') {\n        throw new TypeError('Invalid key for this operation, when present its use must be sig');\n    }\n    if (key.key_ops !== undefined && key.key_ops.includes?.(usage) !== true) {\n        throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${usage}`);\n    }\n    if (key.alg !== undefined && key.alg !== alg) {\n        throw new TypeError(`Invalid key for this operation, when present its alg must be ${alg}`);\n    }\n    return true;\n};\nconst symmetricTypeCheck = (alg, key, usage, allowJwk) => {\n    if (key instanceof Uint8Array)\n        return;\n    if (allowJwk && jwk.isJWK(key)) {\n        if (jwk.isSecretJWK(key) && jwkMatchesOp(alg, key, usage))\n            return;\n        throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present`);\n    }\n    if (!isKeyLike(key)) {\n        throw new TypeError(invalidKeyInput(alg, key, ...types, 'Uint8Array', allowJwk ? 'JSON Web Key' : null));\n    }\n    if (key.type !== 'secret') {\n        throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type \"secret\"`);\n    }\n};\nconst asymmetricTypeCheck = (alg, key, usage, allowJwk) => {\n    if (allowJwk && jwk.isJWK(key)) {\n        switch (usage) {\n            case 'sign':\n                if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))\n                    return;\n                throw new TypeError(`JSON Web Key for this operation be a private JWK`);\n            case 'verify':\n                if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage))\n                    return;\n                throw new TypeError(`JSON Web Key for this operation be a public JWK`);\n        }\n    }\n    if (!isKeyLike(key)) {\n        throw new TypeError(invalidKeyInput(alg, key, ...types, allowJwk ? 'JSON Web Key' : null));\n    }\n    if (key.type === 'secret') {\n        throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type \"secret\"`);\n    }\n    if (usage === 'sign' && key.type === 'public') {\n        throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type \"private\"`);\n    }\n    if (usage === 'decrypt' && key.type === 'public') {\n        throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type \"private\"`);\n    }\n    if (key.algorithm && usage === 'verify' && key.type === 'private') {\n        throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type \"public\"`);\n    }\n    if (key.algorithm && usage === 'encrypt' && key.type === 'private') {\n        throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type \"public\"`);\n    }\n};\nfunction checkKeyType(allowJwk, alg, key, usage) {\n    const symmetric = alg.startsWith('HS') ||\n        alg === 'dir' ||\n        alg.startsWith('PBES2') ||\n        /^A\\d{3}(?:GCM)?KW$/.test(alg);\n    if (symmetric) {\n        symmetricTypeCheck(alg, key, usage, allowJwk);\n    }\n    else {\n        asymmetricTypeCheck(alg, key, usage, allowJwk);\n    }\n}\nexport default checkKeyType.bind(undefined, false);\nexport const checkKeyTypeWithJwk = checkKeyType.bind(undefined, true);\n", "import { JOSENotSupported } from '../util/errors.js';\nfunction validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {\n    if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {\n        throw new Err('\"crit\" (Critical) Header Parameter MUST be integrity protected');\n    }\n    if (!protectedHeader || protectedHeader.crit === undefined) {\n        return new Set();\n    }\n    if (!Array.isArray(protectedHeader.crit) ||\n        protectedHeader.crit.length === 0 ||\n        protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) {\n        throw new Err('\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present');\n    }\n    let recognized;\n    if (recognizedOption !== undefined) {\n        recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);\n    }\n    else {\n        recognized = recognizedDefault;\n    }\n    for (const parameter of protectedHeader.crit) {\n        if (!recognized.has(parameter)) {\n            throw new JOSENotSupported(`Extension Header Parameter \"${parameter}\" is not recognized`);\n        }\n        if (joseHeader[parameter] === undefined) {\n            throw new Err(`Extension Header Parameter \"${parameter}\" is missing`);\n        }\n        if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {\n            throw new Err(`Extension Header Parameter \"${parameter}\" MUST be integrity protected`);\n        }\n    }\n    return new Set(protectedHeader.crit);\n}\nexport default validateCrit;\n", "import { JOSENotSupported } from '../util/errors.js';\nexport default function dsaDigest(alg) {\n    switch (alg) {\n        case 'PS256':\n        case 'RS256':\n        case 'ES256':\n        case 'ES256K':\n            return 'sha256';\n        case 'PS384':\n        case 'RS384':\n        case 'ES384':\n            return 'sha384';\n        case 'PS512':\n        case 'RS512':\n        case 'ES512':\n            return 'sha512';\n        case 'Ed25519':\n        case 'EdDSA':\n            return undefined;\n        default:\n            throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n    }\n}\n", "import { constants, KeyObject } from 'node:crypto';\nimport getNamedCurve from './get_named_curve.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport checkKeyLength from './check_key_length.js';\nconst ecCurveAlgMap = new Map([\n    ['ES256', 'P-256'],\n    ['ES256K', 'secp256k1'],\n    ['ES384', 'P-384'],\n    ['ES512', 'P-521'],\n]);\nexport default function keyForCrypto(alg, key) {\n    let asymmetricKeyType;\n    let asymmetricKeyDetails;\n    let isJWK;\n    if (key instanceof KeyObject) {\n        asymmetricKeyType = key.asymmetricKeyType;\n        asymmetricKeyDetails = key.asymmetricKeyDetails;\n    }\n    else {\n        isJWK = true;\n        switch (key.kty) {\n            case 'RSA':\n                asymmetricKeyType = 'rsa';\n                break;\n            case 'EC':\n                asymmetricKeyType = 'ec';\n                break;\n            case 'OKP': {\n                if (key.crv === 'Ed25519') {\n                    asymmetricKeyType = 'ed25519';\n                    break;\n                }\n                if (key.crv === 'Ed448') {\n                    asymmetricKeyType = 'ed448';\n                    break;\n                }\n                throw new TypeError('Invalid key for this operation, its crv must be Ed25519 or Ed448');\n            }\n            default:\n                throw new TypeError('Invalid key for this operation, its kty must be RSA, OKP, or EC');\n        }\n    }\n    let options;\n    switch (alg) {\n        case 'Ed25519':\n            if (asymmetricKeyType !== 'ed25519') {\n                throw new TypeError(`Invalid key for this operation, its asymmetricKeyType must be ed25519`);\n            }\n            break;\n        case 'EdDSA':\n            if (!['ed25519', 'ed448'].includes(asymmetricKeyType)) {\n                throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448');\n            }\n            break;\n        case 'RS256':\n        case 'RS384':\n        case 'RS512':\n            if (asymmetricKeyType !== 'rsa') {\n                throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa');\n            }\n            checkKeyLength(key, alg);\n            break;\n        case 'PS256':\n        case 'PS384':\n        case 'PS512':\n            if (asymmetricKeyType === 'rsa-pss') {\n                const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = asymmetricKeyDetails;\n                const length = parseInt(alg.slice(-3), 10);\n                if (hashAlgorithm !== undefined &&\n                    (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm)) {\n                    throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of \"alg\" ${alg}`);\n                }\n                if (saltLength !== undefined && saltLength > length >> 3) {\n                    throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of \"alg\" ${alg}`);\n                }\n            }\n            else if (asymmetricKeyType !== 'rsa') {\n                throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss');\n            }\n            checkKeyLength(key, alg);\n            options = {\n                padding: constants.RSA_PKCS1_PSS_PADDING,\n                saltLength: constants.RSA_PSS_SALTLEN_DIGEST,\n            };\n            break;\n        case 'ES256':\n        case 'ES256K':\n        case 'ES384':\n        case 'ES512': {\n            if (asymmetricKeyType !== 'ec') {\n                throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ec');\n            }\n            const actual = getNamedCurve(key);\n            const expected = ecCurveAlgMap.get(alg);\n            if (actual !== expected) {\n                throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${expected}, got ${actual}`);\n            }\n            options = { dsaEncoding: 'ieee-p1363' };\n            break;\n        }\n        default:\n            throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n    }\n    if (isJWK) {\n        return { format: 'jwk', key, ...options };\n    }\n    return options ? { ...options, key } : key;\n}\n", "import * as crypto from 'node:crypto';\nimport { promisify } from 'node:util';\nimport nodeDigest from './dsa_digest.js';\nimport hmacDigest from './hmac_digest.js';\nimport nodeKey from './node_key.js';\nimport getSignKey from './get_sign_verify_key.js';\nconst oneShotSign = promisify(crypto.sign);\nconst sign = async (alg, key, data) => {\n    const k = getSignKey(alg, key, 'sign');\n    if (alg.startsWith('HS')) {\n        const hmac = crypto.createHmac(hmacDigest(alg), k);\n        hmac.update(data);\n        return hmac.digest();\n    }\n    return oneShotSign(nodeDigest(alg), data, nodeKey(alg, k));\n};\nexport default sign;\n", "import { JOSENotSupported } from '../util/errors.js';\nexport default function hmacDigest(alg) {\n    switch (alg) {\n        case 'HS256':\n            return 'sha256';\n        case 'HS384':\n            return 'sha384';\n        case 'HS512':\n            return 'sha512';\n        default:\n            throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n    }\n}\n", "import { KeyObject, createSecretKey } from 'node:crypto';\nimport { isCryptoKey } from './webcrypto.js';\nimport { checkSigCryptoKey } from '../lib/crypto_key.js';\nimport invalidKeyInput from '../lib/invalid_key_input.js';\nimport { types } from './is_key_like.js';\nimport * as jwk from '../lib/is_jwk.js';\nexport default function getSignVerifyKey(alg, key, usage) {\n    if (key instanceof Uint8Array) {\n        if (!alg.startsWith('HS')) {\n            throw new TypeError(invalidKeyInput(key, ...types));\n        }\n        return createSecretKey(key);\n    }\n    if (key instanceof KeyObject) {\n        return key;\n    }\n    if (isCryptoKey(key)) {\n        checkSigCryptoKey(key, alg, usage);\n        return KeyObject.from(key);\n    }\n    if (jwk.isJWK(key)) {\n        if (alg.startsWith('HS')) {\n            return createSecretKey(Buffer.from(key.k, 'base64url'));\n        }\n        return key;\n    }\n    throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array', 'JSON Web Key'));\n}\n", "export default (date) => Math.floor(date.getTime() / 1000);\n", "const minute = 60;\nconst hour = minute * 60;\nconst day = hour * 24;\nconst week = day * 7;\nconst year = day * 365.25;\nconst REGEX = /^(\\+|\\-)? ?(\\d+|\\d+\\.\\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;\nexport default (str) => {\n    const matched = REGEX.exec(str);\n    if (!matched || (matched[4] && matched[1])) {\n        throw new TypeError('Invalid time period format');\n    }\n    const value = parseFloat(matched[2]);\n    const unit = matched[3].toLowerCase();\n    let numericDate;\n    switch (unit) {\n        case 'sec':\n        case 'secs':\n        case 'second':\n        case 'seconds':\n        case 's':\n            numericDate = Math.round(value);\n            break;\n        case 'minute':\n        case 'minutes':\n        case 'min':\n        case 'mins':\n        case 'm':\n            numericDate = Math.round(value * minute);\n            break;\n        case 'hour':\n        case 'hours':\n        case 'hr':\n        case 'hrs':\n        case 'h':\n            numericDate = Math.round(value * hour);\n            break;\n        case 'day':\n        case 'days':\n        case 'd':\n            numericDate = Math.round(value * day);\n            break;\n        case 'week':\n        case 'weeks':\n        case 'w':\n            numericDate = Math.round(value * week);\n            break;\n        default:\n            numericDate = Math.round(value * year);\n            break;\n    }\n    if (matched[1] === '-' || matched[4] === 'ago') {\n        return -numericDate;\n    }\n    return numericDate;\n};\n", "import { encode as base64url } from '../../runtime/base64url.js';\nimport sign from '../../runtime/sign.js';\nimport isDisjoint from '../../lib/is_disjoint.js';\nimport { JWSInvalid } from '../../util/errors.js';\nimport { encoder, decoder, concat } from '../../lib/buffer_utils.js';\nimport { checkKeyTypeWithJwk } from '../../lib/check_key_type.js';\nimport validateCrit from '../../lib/validate_crit.js';\nexport class FlattenedSign {\n    _payload;\n    _protectedHeader;\n    _unprotectedHeader;\n    constructor(payload) {\n        if (!(payload instanceof Uint8Array)) {\n            throw new TypeError('payload must be an instance of Uint8Array');\n        }\n        this._payload = payload;\n    }\n    setProtectedHeader(protectedHeader) {\n        if (this._protectedHeader) {\n            throw new TypeError('setProtectedHeader can only be called once');\n        }\n        this._protectedHeader = protectedHeader;\n        return this;\n    }\n    setUnprotectedHeader(unprotectedHeader) {\n        if (this._unprotectedHeader) {\n            throw new TypeError('setUnprotectedHeader can only be called once');\n        }\n        this._unprotectedHeader = unprotectedHeader;\n        return this;\n    }\n    async sign(key, options) {\n        if (!this._protectedHeader && !this._unprotectedHeader) {\n            throw new JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()');\n        }\n        if (!isDisjoint(this._protectedHeader, this._unprotectedHeader)) {\n            throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');\n        }\n        const joseHeader = {\n            ...this._protectedHeader,\n            ...this._unprotectedHeader,\n        };\n        const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, this._protectedHeader, joseHeader);\n        let b64 = true;\n        if (extensions.has('b64')) {\n            b64 = this._protectedHeader.b64;\n            if (typeof b64 !== 'boolean') {\n                throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n            }\n        }\n        const { alg } = joseHeader;\n        if (typeof alg !== 'string' || !alg) {\n            throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n        }\n        checkKeyTypeWithJwk(alg, key, 'sign');\n        let payload = this._payload;\n        if (b64) {\n            payload = encoder.encode(base64url(payload));\n        }\n        let protectedHeader;\n        if (this._protectedHeader) {\n            protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader)));\n        }\n        else {\n            protectedHeader = encoder.encode('');\n        }\n        const data = concat(protectedHeader, encoder.encode('.'), payload);\n        const signature = await sign(alg, key, data);\n        const jws = {\n            signature: base64url(signature),\n            payload: '',\n        };\n        if (b64) {\n            jws.payload = decoder.decode(payload);\n        }\n        if (this._unprotectedHeader) {\n            jws.header = this._unprotectedHeader;\n        }\n        if (this._protectedHeader) {\n            jws.protected = decoder.decode(protectedHeader);\n        }\n        return jws;\n    }\n}\n", "import { FlattenedSign } from '../flattened/sign.js';\nexport class CompactSign {\n    _flattened;\n    constructor(payload) {\n        this._flattened = new FlattenedSign(payload);\n    }\n    setProtectedHeader(protectedHeader) {\n        this._flattened.setProtectedHeader(protectedHeader);\n        return this;\n    }\n    async sign(key, options) {\n        const jws = await this._flattened.sign(key, options);\n        if (jws.payload === undefined) {\n            throw new TypeError('use the flattened module for creating JWS with b64: false');\n        }\n        return `${jws.protected}.${jws.payload}.${jws.signature}`;\n    }\n}\n", "import epoch from '../lib/epoch.js';\nimport isObject from '../lib/is_object.js';\nimport secs from '../lib/secs.js';\nfunction validateInput(label, input) {\n    if (!Number.isFinite(input)) {\n        throw new TypeError(`Invalid ${label} input`);\n    }\n    return input;\n}\nexport class ProduceJWT {\n    _payload;\n    constructor(payload = {}) {\n        if (!isObject(payload)) {\n            throw new TypeError('JWT Claims Set MUST be an object');\n        }\n        this._payload = payload;\n    }\n    setIssuer(issuer) {\n        this._payload = { ...this._payload, iss: issuer };\n        return this;\n    }\n    setSubject(subject) {\n        this._payload = { ...this._payload, sub: subject };\n        return this;\n    }\n    setAudience(audience) {\n        this._payload = { ...this._payload, aud: audience };\n        return this;\n    }\n    setJti(jwtId) {\n        this._payload = { ...this._payload, jti: jwtId };\n        return this;\n    }\n    setNotBefore(input) {\n        if (typeof input === 'number') {\n            this._payload = { ...this._payload, nbf: validateInput('setNotBefore', input) };\n        }\n        else if (input instanceof Date) {\n            this._payload = { ...this._payload, nbf: validateInput('setNotBefore', epoch(input)) };\n        }\n        else {\n            this._payload = { ...this._payload, nbf: epoch(new Date()) + secs(input) };\n        }\n        return this;\n    }\n    setExpirationTime(input) {\n        if (typeof input === 'number') {\n            this._payload = { ...this._payload, exp: validateInput('setExpirationTime', input) };\n        }\n        else if (input instanceof Date) {\n            this._payload = { ...this._payload, exp: validateInput('setExpirationTime', epoch(input)) };\n        }\n        else {\n            this._payload = { ...this._payload, exp: epoch(new Date()) + secs(input) };\n        }\n        return this;\n    }\n    setIssuedAt(input) {\n        if (typeof input === 'undefined') {\n            this._payload = { ...this._payload, iat: epoch(new Date()) };\n        }\n        else if (input instanceof Date) {\n            this._payload = { ...this._payload, iat: validateInput('setIssuedAt', epoch(input)) };\n        }\n        else if (typeof input === 'string') {\n            this._payload = {\n                ...this._payload,\n                iat: validateInput('setIssuedAt', epoch(new Date()) + secs(input)),\n            };\n        }\n        else {\n            this._payload = { ...this._payload, iat: validateInput('setIssuedAt', input) };\n        }\n        return this;\n    }\n}\n", "import { CompactSign } from '../jws/compact/sign.js';\nimport { JWTInvalid } from '../util/errors.js';\nimport { encoder } from '../lib/buffer_utils.js';\nimport { ProduceJWT } from './produce.js';\nexport class SignJWT extends ProduceJWT {\n    _protectedHeader;\n    setProtectedHeader(protectedHeader) {\n        this._protectedHeader = protectedHeader;\n        return this;\n    }\n    async sign(key, options) {\n        const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload)));\n        sig.setProtectedHeader(this._protectedHeader);\n        if (Array.isArray(this._protectedHeader?.crit) &&\n            this._protectedHeader.crit.includes('b64') &&\n            this._protectedHeader.b64 === false) {\n            throw new JWTInvalid('JWTs MUST NOT use unencoded payload');\n        }\n        return sig.sign(key, options);\n    }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient } from '@medplum/core';\nimport { ContentType, getDisplayString, MEDPLUM_CLI_CLIENT_ID, normalizeErrorString } from '@medplum/core';\nimport { exec } from 'node:child_process';\nimport { createServer } from 'node:http';\nimport { platform } from 'node:os';\nimport { createMedplumClient } from './util/client';\nimport type { Profile } from './utils';\nimport { jwtAssertionLogin, jwtBearerLogin, MedplumCommand, saveProfile } from './utils';\n\nconst clientId = MEDPLUM_CLI_CLIENT_ID;\nconst redirectUri = 'http://localhost:9615';\n\nexport const login = new MedplumCommand('login');\nexport const whoami = new MedplumCommand('whoami');\nexport const token = new MedplumCommand('token');\n\nlogin.action(async (options) => {\n  const profileName = options.profile ?? 'default';\n\n  // Always save the profile to update settings\n  const profile = saveProfile(profileName, options);\n\n  const medplum = await createMedplumClient(options, false);\n  await startLogin(medplum, profile);\n});\n\nwhoami.action(async (options) => {\n  const medplum = await createMedplumClient(options);\n  printMe(medplum);\n});\n\ntoken.action(async (options) => {\n  const medplum = await createMedplumClient(options);\n  await medplum.getProfileAsync();\n  const token = medplum.getAccessToken();\n  if (!token) {\n    throw new Error('Not logged in');\n  }\n  console.log(token);\n});\n\nasync function startLogin(medplum: MedplumClient, profile: Profile): Promise<void> {\n  const authType = profile?.authType ?? 'authorization-code';\n  switch (authType) {\n    case 'authorization-code':\n      await medplumAuthorizationCodeLogin(medplum);\n      break;\n    case 'basic':\n      medplum.setBasicAuth(profile.clientId as string, profile.clientSecret as string);\n      break;\n    case 'client-credentials':\n      medplum.setBasicAuth(profile.clientId as string, profile.clientSecret as string);\n      await medplum.startClientLogin(profile.clientId as string, profile.clientSecret as string);\n      break;\n    case 'jwt-bearer':\n      await jwtBearerLogin(medplum, profile);\n      break;\n    case 'jwt-assertion':\n      await jwtAssertionLogin(medplum, profile);\n      break;\n  }\n}\n\nasync function startWebServer(medplum: MedplumClient): Promise<void> {\n  const server = createServer(async (req, res) => {\n    const url = new URL(req.url as string, 'http://localhost:9615');\n    const code = url.searchParams.get('code');\n    if (req.method === 'OPTIONS') {\n      res.writeHead(200, {\n        Allow: 'GET, POST',\n        'Content-Type': ContentType.TEXT,\n      });\n      res.end('OK');\n      return;\n    }\n    if (url.pathname === '/' && code) {\n      try {\n        const profile = await medplum.processCode(code, { clientId, redirectUri });\n        res.writeHead(200, { 'Content-Type': ContentType.TEXT });\n        res.end(`Signed in as ${getDisplayString(profile)}. You may close this window.`);\n      } catch (err) {\n        res.writeHead(400, { 'Content-Type': ContentType.TEXT });\n        res.end(`Error: ${normalizeErrorString(err)}`);\n      } finally {\n        server.close();\n        process.exit(0);\n      }\n    } else {\n      res.writeHead(404, { 'Content-Type': ContentType.TEXT });\n      res.end('Not found');\n    }\n  }).listen(9615);\n}\n\n/**\n * Opens a web browser to the specified URL.\n * See: https://hasinthaindrajee.medium.com/browser-sso-for-cli-applications-b0be743fa656\n * @param url - The URL to open.\n */\nasync function openBrowser(url: string): Promise<void> {\n  const os = platform();\n  let cmd = undefined;\n  switch (os) {\n    case 'openbsd':\n    case 'linux':\n      cmd = `xdg-open '${url}'`;\n      break;\n    case 'darwin':\n      cmd = `open '${url}'`;\n      break;\n    case 'win32':\n      cmd = `cmd /c start \"\" \"${url}\"`;\n      break;\n    default:\n      throw new Error('Unsupported platform: ' + os);\n  }\n  return new Promise((resolve, reject) => {\n    exec(cmd, (error, _, stderr) => {\n      if (error) {\n        reject(error);\n        return;\n      }\n      if (stderr) {\n        reject(new Error('Could not open browser: ' + stderr));\n        return;\n      }\n      resolve();\n    });\n  });\n}\n\n/**\n * Prints the current user and project.\n * @param medplum - The Medplum client.\n */\nfunction printMe(medplum: MedplumClient): void {\n  const loginState = medplum.getActiveLogin();\n  if (loginState) {\n    console.log(`Server:  ${medplum.getBaseUrl()}`);\n    console.log(`Profile: ${loginState.profile.display} (${loginState.profile.reference})`);\n    console.log(`Project: ${loginState.project.display} (${loginState.project.reference})`);\n  } else {\n    console.log('Not logged in');\n  }\n}\n\nasync function medplumAuthorizationCodeLogin(medplum: MedplumClient): Promise<void> {\n  await startWebServer(medplum);\n  const loginUrl = new URL(medplum.getAuthorizeUrl());\n  loginUrl.searchParams.set('client_id', clientId);\n  loginUrl.searchParams.set('redirect_uri', redirectUri);\n  loginUrl.searchParams.set('scope', 'openid');\n  loginUrl.searchParams.set('response_type', 'code');\n  loginUrl.searchParams.set('prompt', 'login');\n  await openBrowser(loginUrl.toString());\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n\n// CLI color highlighting\nconst RESET = '\\x1b[0m';\nconst BOLD = '\\x1b[1m';\nconst RED = '\\x1b[31m';\nconst GREEN = '\\x1b[32m';\nconst YELLOW = '\\x1b[33m';\nconst BLUE = '\\x1b[34m';\n\nexport const color = {\n  red: (text: string) => `${RED}${text}${RESET}`,\n  green: (text: string) => `${GREEN}${text}${RESET}`,\n  yellow: (text: string) => `${YELLOW}${text}${RESET}`,\n  blue: (text: string) => `${BLUE}${text}${RESET}`,\n  bold: (text: string) => `${BOLD}${text}${RESET}`,\n};\n\n// Bold text wrapped in ** **\nexport const processDescription = (desc: string): string => {\n  return desc.replaceAll(/\\*\\*(.*?)\\*\\*/g, (_, text) => color.bold(text));\n};\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Stack, StackResource, StackSummary } from '@aws-sdk/client-cloudformation';\nimport {\n  CloudFormationClient,\n  DescribeStackResourcesCommand,\n  DescribeStacksCommand,\n  paginateListStacks,\n} from '@aws-sdk/client-cloudformation';\nimport { CloudFrontClient, CreateInvalidationCommand } from '@aws-sdk/client-cloudfront';\nimport { ECSClient } from '@aws-sdk/client-ecs';\nimport { S3Client } from '@aws-sdk/client-s3';\nimport { GetParameterCommand, PutParameterCommand, SSMClient } from '@aws-sdk/client-ssm';\nimport { GetCallerIdentityCommand, STSClient } from '@aws-sdk/client-sts';\nimport { EMPTY, normalizeErrorString } from '@medplum/core';\nimport { readdirSync } from 'node:fs';\nimport * as semver from 'semver';\nimport { getConfigFileName } from '../utils';\nimport { checkOk, print } from './terminal';\n\nexport interface MedplumStackDetails {\n  stack: Stack;\n  tag: string;\n  ecsCluster?: StackResource;\n  ecsService?: StackResource;\n  appBucket?: StackResource;\n  appDistribution?: StackResource;\n  appOriginAccessIdentity?: StackResource;\n  storageBucket?: StackResource;\n  storageDistribution?: StackResource;\n  storageOriginAccessIdentity?: StackResource;\n}\n\nexport const cloudFormationClient = new CloudFormationClient({});\nexport const cloudFrontClient = new CloudFrontClient({ region: 'us-east-1' });\nexport const ecsClient = new ECSClient({});\nexport const s3Client = new S3Client({});\nexport const tagKey = 'medplum:environment';\n\n/**\n * Returns a list of all AWS CloudFormation stacks (both Medplum and non-Medplum).\n * @returns List of AWS CloudFormation stacks.\n */\nexport async function getAllStacks(): Promise<(StackSummary & { StackName: string })[]> {\n  const listResult = [] as StackSummary[];\n  const paginator = paginateListStacks(\n    { client: cloudFormationClient },\n    {\n      StackStatusFilter: [\n        'CREATE_COMPLETE',\n        'CREATE_FAILED',\n        'CREATE_IN_PROGRESS',\n        'DELETE_FAILED',\n        'DELETE_IN_PROGRESS',\n        'IMPORT_COMPLETE',\n        'IMPORT_IN_PROGRESS',\n        'IMPORT_ROLLBACK_COMPLETE',\n        'IMPORT_ROLLBACK_FAILED',\n        'IMPORT_ROLLBACK_IN_PROGRESS',\n        'REVIEW_IN_PROGRESS',\n        'ROLLBACK_COMPLETE',\n        'ROLLBACK_FAILED',\n        'ROLLBACK_IN_PROGRESS',\n        'UPDATE_COMPLETE',\n        'UPDATE_COMPLETE_CLEANUP_IN_PROGRESS',\n        'UPDATE_FAILED',\n        'UPDATE_IN_PROGRESS',\n        'UPDATE_ROLLBACK_COMPLETE',\n        'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS',\n        'UPDATE_ROLLBACK_FAILED',\n        'UPDATE_ROLLBACK_IN_PROGRESS',\n      ],\n    }\n  );\n\n  for await (const page of paginator) {\n    for (const stack of page.StackSummaries ?? EMPTY) {\n      listResult.push(stack);\n    }\n  }\n\n  return listResult as (StackSummary & { StackName: string })[];\n}\n\n/**\n * Returns Medplum stack details for the given tag.\n * @param tag - The Medplum stack tag.\n * @returns The Medplum stack details.\n */\nexport async function getStackByTag(tag: string): Promise<MedplumStackDetails | undefined> {\n  const stackSummaries = await getAllStacks();\n  for (const stackSummary of stackSummaries) {\n    const stackName = stackSummary.StackName;\n    const details = await getStackDetails(stackName);\n    if (details?.tag === tag) {\n      return details;\n    }\n  }\n  return undefined;\n}\n\n/**\n * Returns Medplum stack details for the given stack name.\n * @param stackName - The CloudFormation stack name.\n * @returns The Medplum stack details.\n */\nexport async function getStackDetails(stackName: string): Promise<MedplumStackDetails | undefined> {\n  const result = {} as Partial<MedplumStackDetails>;\n  await buildStackDetails(cloudFormationClient, stackName, result);\n  if ((await cloudFormationClient.config.region()) !== 'us-east-1') {\n    try {\n      await buildStackDetails(new CloudFormationClient({ region: 'us-east-1' }), stackName + '-us-east-1', result);\n    } catch {\n      // Fail gracefully\n    }\n  }\n  return result as MedplumStackDetails;\n}\n\n/**\n * Builds the Medplum stack details for the given stack name and region.\n * @param client - The CloudFormation client.\n * @param stackName - The CloudFormation stack name.\n * @param result - The Medplum stack details builder.\n */\nasync function buildStackDetails(\n  client: CloudFormationClient,\n  stackName: string,\n  result: Partial<MedplumStackDetails>\n): Promise<void> {\n  const describeStacksCommand = new DescribeStacksCommand({ StackName: stackName });\n  const stackDetails = await client.send(describeStacksCommand);\n  const stack = stackDetails?.Stacks?.[0];\n  const medplumTag = stack?.Tags?.find((tag) => tag.Key === tagKey);\n  if (!medplumTag) {\n    return;\n  }\n\n  const stackResources = await client.send(new DescribeStackResourcesCommand({ StackName: stackName }));\n  if (!stackResources.StackResources) {\n    return;\n  }\n\n  if (client === cloudFormationClient) {\n    result.stack = stack;\n    result.tag = medplumTag.Value;\n  }\n\n  for (const resource of stackResources.StackResources) {\n    assignStackDetails(resource, result);\n  }\n}\n\nfunction assignStackDetails(resource: StackResource, result: Partial<MedplumStackDetails>): void {\n  if (resource.ResourceType === 'AWS::ECS::Cluster') {\n    result.ecsCluster = resource;\n  } else if (resource.ResourceType === 'AWS::ECS::Service') {\n    result.ecsService = resource;\n  } else if (\n    resource.ResourceType === 'AWS::S3::Bucket' &&\n    resource.LogicalResourceId?.startsWith('FrontEndAppBucket')\n  ) {\n    result.appBucket = resource;\n  } else if (\n    resource.ResourceType === 'AWS::CloudFront::Distribution' &&\n    resource.LogicalResourceId?.startsWith('FrontEndAppDistribution')\n  ) {\n    result.appDistribution = resource;\n  } else if (\n    resource.ResourceType === 'AWS::CloudFront::CloudFrontOriginAccessIdentity' &&\n    resource.LogicalResourceId?.startsWith('FrontEndOriginAccessIdentity')\n  ) {\n    result.appOriginAccessIdentity = resource;\n  } else if (\n    resource.ResourceType === 'AWS::S3::Bucket' &&\n    resource.LogicalResourceId?.startsWith('StorageStorageBucket')\n  ) {\n    result.storageBucket = resource;\n  } else if (\n    resource.ResourceType === 'AWS::CloudFront::Distribution' &&\n    resource.LogicalResourceId?.startsWith('StorageStorageDistribution')\n  ) {\n    result.storageDistribution = resource;\n  } else if (\n    resource.ResourceType === 'AWS::CloudFront::CloudFrontOriginAccessIdentity' &&\n    resource.LogicalResourceId?.startsWith('StorageOriginAccessIdentity')\n  ) {\n    result.storageOriginAccessIdentity = resource;\n  }\n}\n\n/**\n * Prints the given Medplum stack details to stdout.\n * @param details - The Medplum stack details.\n */\nexport function printStackDetails(details: MedplumStackDetails): void {\n  console.log(`Medplum Tag:           ${details.tag}`);\n  console.log(`Stack Name:            ${details.stack?.StackName}`);\n  console.log(`Stack ID:              ${details.stack?.StackId}`);\n  console.log(`Status:                ${details.stack?.StackStatus}`);\n  console.log(`ECS Cluster:           ${details.ecsCluster?.PhysicalResourceId}`);\n  console.log(`ECS Service:           ${getEcsServiceName(details.ecsService)}`);\n  console.log(`App Bucket:            ${details.appBucket?.PhysicalResourceId}`);\n  console.log(`App Distribution:      ${details.appDistribution?.PhysicalResourceId}`);\n  console.log(`App OAI:               ${details.appOriginAccessIdentity?.PhysicalResourceId}`);\n  console.log(`Storage Bucket:        ${details.storageBucket?.PhysicalResourceId}`);\n  console.log(`Storage Distribution:  ${details.storageDistribution?.PhysicalResourceId}`);\n  console.log(`Storage OAI:           ${details.storageOriginAccessIdentity?.PhysicalResourceId}`);\n}\n\n/**\n * Parses the ECS service name from the given AWS ECS service resource.\n * @param resource - The AWS ECS service resource.\n * @returns The ECS service name.\n */\nexport function getEcsServiceName(resource: StackResource | undefined): string | undefined {\n  return resource?.PhysicalResourceId?.split('/')?.pop() || '';\n}\n\n/**\n * Creates a CloudFront invalidation to clear the cache for all files.\n * This is not strictly necessary, but it helps to ensure that the latest version of the app is served.\n * In a perfect world, every deploy is clean, and hashed resources should be cached forever.\n * However, we do not recalculate hashes after variable replacements.\n * So if variables change, we need to invalidate the cache.\n * @param distributionId - The CloudFront distribution ID.\n */\nexport async function createInvalidation(distributionId: string): Promise<void> {\n  const response = await cloudFrontClient.send(\n    new CreateInvalidationCommand({\n      DistributionId: distributionId,\n      InvalidationBatch: {\n        CallerReference: `invalidate-all-${Date.now()}`,\n        Paths: {\n          Quantity: 1,\n          Items: ['/*'],\n        },\n      },\n    })\n  );\n  console.log(`Created invalidation with ID: ${response.Invalidation?.Id}`);\n}\n\nexport async function getServerVersions(from?: string): Promise<string[]> {\n  const response = await fetch('https://api.github.com/repos/medplum/medplum/releases?per_page=100', {\n    headers: {\n      Accept: 'application/vnd.github+json',\n      'X-GitHub-Api-Version': '2022-11-28',\n    },\n  });\n\n  const json = (await response.json()) as { tag_name: string }[];\n  const versions = json.map((release) =>\n    release.tag_name.startsWith('v') ? release.tag_name.slice(1) : release.tag_name\n  );\n\n  // Sort in descending order\n  versions.sort((a, b) => semver.compare(b, a));\n\n  return from ? versions.slice(0, versions.indexOf(from)) : versions;\n}\n\n/**\n * Writes a collection of parameters to AWS Parameter Store.\n * @param region - The AWS region.\n * @param prefix - The AWS Parameter Store prefix.\n * @param params - The parameters to write.\n */\nexport async function writeParameters(\n  region: string,\n  prefix: string,\n  params: Record<string, string | number | boolean | object>\n): Promise<void> {\n  const client = new SSMClient({ region });\n  for (const [key, value] of Object.entries(params)) {\n    const name = prefix + key;\n    const valueStr = typeof value === 'object' ? JSON.stringify(value) : value.toString();\n    const existingValue = await readParameter(client, name);\n\n    if (existingValue !== undefined && existingValue !== valueStr) {\n      print(`Parameter \"${name}\" exists with different value.`);\n      await checkOk(`Do you want to overwrite \"${name}\"?`);\n    }\n\n    await writeParameter(client, name, valueStr);\n  }\n}\n\n/**\n * Reads a parameter from AWS Parameter Store.\n * @param client - The AWS SSM client.\n * @param name - The parameter name.\n * @returns The parameter value, or undefined if not found.\n */\nasync function readParameter(client: SSMClient, name: string): Promise<string | undefined> {\n  const command = new GetParameterCommand({\n    Name: name,\n    WithDecryption: true,\n  });\n  try {\n    const result = await client.send(command);\n    return result.Parameter?.Value;\n  } catch (err: any) {\n    if (err.name === 'ParameterNotFound') {\n      return undefined;\n    }\n    throw err;\n  }\n}\n\n/**\n * Writes a parameter to AWS Parameter Store.\n * @param client - The AWS SSM client.\n * @param name - The parameter name.\n * @param value - The parameter value.\n */\nasync function writeParameter(client: SSMClient, name: string, value: string): Promise<void> {\n  const command = new PutParameterCommand({\n    Name: name,\n    Value: value,\n    Type: 'SecureString',\n    Overwrite: true,\n  });\n  await client.send(command);\n}\n\n/**\n * Prints a \"config not found\" message to stdout.\n * Includes helpful debugging information such as available configs.\n * @param tagName - Medplum stack tag name.\n * @param options - Additional command line options.\n */\nexport function printConfigNotFound(tagName: string, options?: Record<string, any>): void {\n  console.log(`Config not found: ${tagName} (${getConfigFileName(tagName, options)})`);\n\n  if (options) {\n    const entries = Object.entries(options);\n    if (entries.length > 0) {\n      console.log('Additional options:');\n      for (const [key, value] of entries) {\n        console.log(`  ${key}: ${value}`);\n      }\n    }\n  }\n\n  console.log();\n\n  let files: any[] = readdirSync('.', { withFileTypes: true });\n  files = files\n    .filter((f) => f.isFile() && f.name.startsWith('medplum.') && f.name.endsWith('.json'))\n    .map((f) => f.name);\n\n  if (files.length === 0) {\n    console.log('No configs found');\n  } else {\n    console.log('Available configs:');\n    for (const file of files) {\n      console.log(\n        `  ${file\n          .replaceAll('medplum.', '')\n          .replaceAll('.config', '')\n          .replaceAll('.server', '')\n          .replaceAll('.json', '')\n          .padEnd(40, ' ')} (${file})`\n      );\n    }\n  }\n}\n\n/**\n * Prints a \"stack not found\" message to stdout.\n * Includes helpful debugging information such as AWS account ID and region.\n * @param tagName - Medplum stack tag name.\n */\nexport async function printStackNotFound(tagName: string): Promise<void> {\n  console.log(`Stack not found: ${tagName}`);\n  console.log();\n\n  try {\n    const client = new STSClient();\n    const command = new GetCallerIdentityCommand({});\n    const response = await client.send(command);\n    const region = await client.config.region();\n    console.log('AWS Region:        ', region);\n    console.log('AWS Account ID:    ', response.Account);\n    console.log('AWS Account ARN:   ', response.Arn);\n    console.log('AWS User ID:       ', response.UserId);\n  } catch (err) {\n    console.log('Warning: Unable to get AWS account ID', normalizeErrorString(err));\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport readline from 'node:readline';\n\nlet terminal: readline.Interface;\n\nexport function initTerminal(): void {\n  terminal = readline.createInterface({ input: process.stdin, output: process.stdout });\n}\n\nexport function closeTerminal(): void {\n  terminal.close();\n}\n\n/**\n * Prints to stdout.\n * @param text - The text to print.\n */\nexport function print(text: string): void {\n  terminal.write(text + '\\n');\n}\n\n/**\n * Prints a header with extra line spacing.\n * @param text - The text to print.\n */\nexport function header(text: string): void {\n  print('\\n' + text + '\\n');\n}\n\n/**\n * Prints a question and waits for user input.\n * @param text - The question text to print.\n * @param defaultValue - Optional default value.\n * @returns The selected value, or default value on empty selection.\n */\nexport function ask(text: string, defaultValue: string | number = ''): Promise<string> {\n  return new Promise((resolve) => {\n    terminal.question(text + (defaultValue ? ' (' + defaultValue + ')' : '') + ' ', (answer: string) => {\n      resolve(answer || defaultValue.toString());\n    });\n  });\n}\n\n/**\n * Prints a question and waits for user to choose one of the provided options.\n * @param text - The prompt text to print.\n * @param options - The list of options that the user can select.\n * @param defaultValue - Optional default value.\n * @returns The selected value, or default value on empty selection.\n */\nexport async function choose(text: string, options: (string | number)[], defaultValue = ''): Promise<string> {\n  const str = text + ' [' + options.map((o) => (o === defaultValue ? '(' + o + ')' : o)).join('|') + ']';\n\n  while (true) {\n    const answer = (await ask(str)) || defaultValue;\n    if (options.includes(answer)) {\n      return answer;\n    }\n    print('Please choose one of the following options: ' + options.join(', '));\n  }\n}\n\n/**\n * Prints a question and waits for the user to choose a valid integer option.\n * @param text - The prompt text to print.\n * @param options - The list of options that the user can select.\n * @param defaultValue - Default value.\n * @returns The selected value, or default value on empty selection.\n */\nexport async function chooseInt(text: string, options: number[], defaultValue: number): Promise<number> {\n  return Number.parseInt(\n    await choose(\n      text,\n      options.map((o) => o.toString()),\n      defaultValue.toString()\n    ),\n    10\n  );\n}\n\n/**\n * Prints a question and waits for the user to choose yes or no.\n * @param text - The question to print.\n * @returns true on accept or false on reject.\n */\nexport async function yesOrNo(text: string): Promise<boolean> {\n  return (await choose(text, ['y', 'n'])).toLowerCase() === 'y';\n}\n\n/**\n * Prints a question and waits for the user to confirm yes. Throws error on no, and exits the program.\n * @param text - The prompt text to print.\n */\nexport async function checkOk(text: string): Promise<void> {\n  if (!(await yesOrNo(text))) {\n    print('Exiting...');\n    throw new Error('User cancelled');\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { getStackByTag, printStackDetails, printStackNotFound } from './utils';\n\n/**\n * The AWS \"describe\" command prints details about a Medplum CloudFormation stack.\n * @param tag - The Medplum stack tag.\n */\nexport async function describeStacksCommand(tag: string): Promise<void> {\n  const details = await getStackByTag(tag);\n  if (!details) {\n    await printStackNotFound(tag);\n    throw new Error(`Stack not found: ${tag}`);\n  }\n  printStackDetails(details);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { CertificateSummary, ValidationMethod } from '@aws-sdk/client-acm';\nimport { ACMClient, ListCertificatesCommand, RequestCertificateCommand } from '@aws-sdk/client-acm';\nimport { CloudFrontClient, CreatePublicKeyCommand } from '@aws-sdk/client-cloudfront';\nimport { GetCallerIdentityCommand, STSClient } from '@aws-sdk/client-sts';\nimport type { MedplumInfraConfig } from '@medplum/core';\nimport { normalizeErrorString } from '@medplum/core';\nimport { generateKeyPairSync, randomUUID } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { getConfigFileName, writeConfig } from '../utils';\nimport { ask, checkOk, choose, chooseInt, closeTerminal, header, initTerminal, print, yesOrNo } from './terminal';\nimport { getServerVersions, writeParameters } from './utils';\n\ntype MedplumDomainType = 'api' | 'app' | 'storage';\ntype MedplumDomainSetting = `${MedplumDomainType}DomainName`;\ntype MedplumDomainCertSetting = `${MedplumDomainType}SslCertArn`;\n\nconst getDomainSetting = (domain: MedplumDomainType): MedplumDomainSetting => `${domain}DomainName`;\nconst getDomainCertSetting = (domain: MedplumDomainType): MedplumDomainCertSetting => `${domain}SslCertArn`;\n\nexport async function initStackCommand(): Promise<void> {\n  const config = { apiPort: 8103, region: 'us-east-1' } as MedplumInfraConfig;\n  initTerminal();\n  header('MEDPLUM');\n  print('This tool prepares the necessary prerequisites for deploying Medplum in your AWS account.');\n  print('');\n  print('Most Medplum infrastructure is deployed using the AWS CDK.');\n  print('However, some AWS resources must be created manually, such as email addresses and SSL certificates.');\n  print('This tool will help you create those resources.');\n  print('');\n  print('Upon completion, this tool will:');\n  print('  1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)');\n  print('  2. Optionally generate an AWS CloudFront signing key');\n  print('  3. Optionally request SSL certificates from AWS Certificate Manager');\n  print('  4. Optionally write server config settings to AWS Parameter Store');\n  print('');\n  print('The Medplum infra config file is an input to the Medplum CDK.');\n  print('The Medplum CDK will create and manage the necessary AWS resources.');\n  print('');\n  print('We will ask a series of questions to generate your infra config file.');\n  print('Some questions have predefined options in [square brackets].');\n  print('Some questions have default values in (parentheses), which you can accept by pressing Enter.');\n  print('Press Ctrl+C at any time to exit.');\n\n  const currentAccountId = await getAccountId(config.region);\n  if (!currentAccountId) {\n    print('It appears that you do not have AWS credentials configured.');\n    print('AWS credentials are not strictly required, but will enable some additional features.');\n    print('If you intend to use AWS credentials, please configure them now.');\n    await checkOk('Do you want to continue without AWS credentials?');\n  }\n\n  header('ENVIRONMENT NAME');\n  print('Medplum deployments have a short environment name such as \"prod\", \"staging\", \"alice\", or \"demo\".');\n  print('The environment name is used in multiple places:');\n  print('  1. As part of config file names (i.e., medplum.demo.config.json)');\n  print('  2. As the base of CloudFormation stack names (i.e., MedplumDemo)');\n  print('  3. AWS Parameter Store keys (i.e., /medplum/demo/...)');\n  config.name = await ask('What is your environment name?', 'demo');\n  print('Using environment name \"' + config.name + '\"...');\n\n  header('CONFIG FILE');\n  print('Medplum Infrastructure will create a config file in the current directory.');\n  const configFileName = await ask('What is the config file name?', `medplum.${config.name}.config.json`);\n  if (existsSync(configFileName)) {\n    print('Config file already exists.');\n    await checkOk('Do you want to overwrite the config file?');\n  }\n  print('Using config file \"' + configFileName + '\"...');\n  writeConfig(configFileName, config);\n\n  header('AWS REGION');\n  print('Most Medplum resources will be created in a single AWS region.');\n  config.region = await ask('Enter your AWS region:', 'us-east-1');\n  writeConfig(configFileName, config);\n\n  header('AWS ACCOUNT NUMBER');\n  print('Medplum Infrastructure will use your AWS account number to create AWS resources.');\n  if (currentAccountId) {\n    print('Using the AWS CLI, your current account ID is: ' + currentAccountId);\n  }\n  config.accountNumber = await ask('What is your AWS account number?', currentAccountId);\n  writeConfig(configFileName, config);\n\n  header('STACK NAME');\n  print('Medplum will create a CloudFormation stack to manage AWS resources.');\n  print('AWS CloudFormation stack names ');\n  const defaultStackName = 'Medplum' + config.name.charAt(0).toUpperCase() + config.name.slice(1);\n  config.stackName = await ask('Enter your CloudFormation stack name?', defaultStackName);\n  writeConfig(configFileName, config);\n\n  header('BASE DOMAIN NAME');\n  print('Please enter the base domain name for your Medplum deployment.');\n  print('');\n  print('Medplum deploys multiple subdomains for various services.');\n  print('');\n  print('For example, \"api.\" for the REST API and \"app.\" for the web application.');\n  print('The base domain name is the common suffix for all subdomains.');\n  print('');\n  print('For example, if your base domain name is \"example.com\",');\n  print('then the REST API will be \"api.example.com\".');\n  print('');\n  print('The base domain should include the TLD (i.e., \".com\", \".org\", \".net\").');\n  print('');\n  print('Note that you must own the base domain, and it must use Route53 DNS.');\n  while (!config.domainName) {\n    config.domainName = await ask('Enter your base domain name:');\n  }\n  writeConfig(configFileName, config);\n\n  header('SUPPORT EMAIL');\n  print('Medplum sends transactional emails to users.');\n  print('For example, emails to new users or for password reset.');\n  print('Medplum will use the support email address to send these emails.');\n  print('Note that you must verify the support email address in SES.');\n  const supportEmail = await ask('Enter your support email address:');\n\n  header('API DOMAIN NAME');\n  print('Medplum deploys a REST API for the backend services.');\n  config.apiDomainName = await ask('Enter your REST API domain name:', 'api.' + config.domainName);\n  config.baseUrl = `https://${config.apiDomainName}/`;\n  writeConfig(configFileName, config);\n\n  header('APP DOMAIN NAME');\n  print('Medplum deploys a web application for the user interface.');\n  config.appDomainName = await ask('Enter your web application domain name:', 'app.' + config.domainName);\n  writeConfig(configFileName, config);\n\n  header('STORAGE DOMAIN NAME');\n  print('Medplum deploys a storage service for file uploads.');\n  config.storageDomainName = await ask('Enter your storage domain name:', 'storage.' + config.domainName);\n  writeConfig(configFileName, config);\n\n  header('STORAGE BUCKET');\n  print('Medplum uses an S3 bucket to store binary content such as file uploads.');\n  print('Medplum will create a the S3 bucket as part of the CloudFormation stack.');\n  config.storageBucketName = await ask('Enter your storage bucket name:', config.storageDomainName);\n  writeConfig(configFileName, config);\n\n  header('MAX AVAILABILITY ZONES');\n  print('Medplum API servers can be deployed in multiple availability zones.');\n  print('This provides redundancy and high availability.');\n  print('However, it also increases the cost of the deployment.');\n  print('If you want to use all availability zones, choose a large number such as 99.');\n  print('If you want to restrict the number, for example to manage EIP limits,');\n  print('then choose a small number such as 2 or 3.');\n  config.maxAzs = await chooseInt('Enter the maximum number of availability zones:', [2, 3, 99], 2);\n\n  header('DATABASE INSTANCES');\n  print('Medplum uses a relational database to store data.');\n  print('Medplum can create a new RDS database as part of the CloudFormation stack,');\n  print('or can set up your own database and enter the database name, username, and password.');\n  if (await yesOrNo('Do you want to create a new RDS database as part of the CloudFormation stack?')) {\n    print('Medplum will create a new RDS database as part of the CloudFormation stack.');\n    print('');\n    print('If you need high availability, you can choose multiple instances.');\n    print('Use 1 for a single instance, or 2 for a primary and a standby.');\n    config.rdsInstances = await chooseInt('Enter the number of database instances:', [1, 2], 1);\n  } else {\n    print('Medplum will not create a new RDS database.');\n    print('Please create a new RDS database and enter the database name, username, and password.');\n    print('Set the AWS Secrets Manager secret ARN in the config file in the \"rdsSecretsArn\" setting.');\n    config.rdsSecretsArn = 'TODO';\n  }\n  writeConfig(configFileName, config);\n\n  header('SERVER INSTANCES');\n  print('Medplum uses AWS Fargate to run the API servers.');\n  print('Medplum will create a new Fargate cluster as part of the CloudFormation stack.');\n  print('Fargate will automatically scale the number of servers up and down.');\n  print('If you need high availability, you can choose multiple instances.');\n  config.desiredServerCount = await chooseInt('Enter the number of server instances:', [1, 2, 3, 4, 6, 8], 1);\n  writeConfig(configFileName, config);\n\n  header('SERVER MEMORY');\n  print('You can choose the amount of memory for each server instance.');\n  print('The default is 512 MB, which is sufficient for getting started.');\n  print('Note that only certain CPU units are compatible with memory units.');\n  print('Consult AWS Fargate \"Task Definition Parameters\" for more information.');\n  config.serverMemory = await chooseInt('Enter the server memory (MB):', [512, 1024, 2048, 4096, 8192, 16384], 512);\n  writeConfig(configFileName, config);\n\n  header('SERVER CPU');\n  print('You can choose the amount of CPU for each server instance.');\n  print('CPU is expressed as an integer using AWS CPU units');\n  print('The default is 256, which is sufficient for getting started.');\n  print('Note that only certain CPU units are compatible with memory units.');\n  print('Consult AWS Fargate \"Task Definition Parameters\" for more information.');\n  config.serverCpu = await chooseInt('Enter the server CPU:', [256, 512, 1024, 2048, 4096, 8192, 16384], 256);\n  writeConfig(configFileName, config);\n\n  header('SERVER IMAGE');\n  print('Medplum uses Docker images for the API servers.');\n  print('You can choose the image to use for the servers.');\n  print('Docker images can be loaded from either Docker Hub or AWS ECR.');\n  print('The default is the latest Medplum release.');\n  const latestVersion = (await getServerVersions())[0] ?? 'latest';\n  config.serverImage = await ask('Enter the server image:', `medplum/medplum-server:${latestVersion}`);\n  writeConfig(configFileName, config);\n\n  header('SIGNING KEY');\n  print('Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.');\n  const signingKey = await generateSigningKey(config.region, config.stackName + 'SigningKey');\n  if (signingKey) {\n    config.signingKeyId = signingKey.keyId;\n    config.storagePublicKey = signingKey.publicKey;\n    writeConfig(configFileName, config);\n  } else {\n    print('Unable to generate signing key.');\n    print('Please manually create a signing key and enter the key ID and public key in the config file.');\n    print('You must set the \"signingKeyId\", \"signingKey\", and \"signingKeyPassphrase\" settings.');\n  }\n\n  header('SSL CERTIFICATES');\n  print(`Medplum will now check for existing SSL certificates for the subdomains.`);\n  const allCerts = await listAllCertificates(config.region);\n  print('Found ' + allCerts.length + ' certificate(s).');\n\n  // Process certificates for each subdomain\n  // Note: The \"api\" certificate must be created in the same region as the API\n  // Note: The \"app\" and \"storage\" certificates must be created in us-east-1\n  for (const { region, certName } of [\n    { region: config.region, certName: 'api' },\n    { region: 'us-east-1', certName: 'app' },\n    { region: 'us-east-1', certName: 'storage' },\n  ] as const) {\n    print('');\n    const arn = await processCert(config, allCerts, region, certName);\n    config[getDomainCertSetting(certName)] = arn;\n    writeConfig(configFileName, config);\n  }\n\n  header('AWS PARAMETER STORE');\n  print('Medplum uses AWS Parameter Store to store sensitive configuration values.');\n  print('These values will be encrypted at rest.');\n  print(`The values will be stored in the \"/medplum/${config.name}\" path.`);\n\n  const serverParams: Record<string, string | number> = {\n    port: config.apiPort,\n    baseUrl: config.baseUrl,\n    appBaseUrl: `https://${config.appDomainName}/`,\n    storageBaseUrl: `https://${config.storageDomainName}/binary/`,\n    binaryStorage: `s3:${config.storageBucketName}`,\n    supportEmail: supportEmail,\n  };\n\n  if (signingKey) {\n    serverParams.signingKeyId = signingKey.keyId;\n    serverParams.signingKey = signingKey.privateKey;\n    serverParams.signingKeyPassphrase = signingKey.passphrase;\n  }\n\n  print(\n    JSON.stringify(\n      {\n        ...serverParams,\n        signingKey: '****',\n        signingKeyPassphrase: '****',\n      },\n      null,\n      2\n    )\n  );\n\n  if (await yesOrNo('Do you want to store these values in AWS Parameter Store?')) {\n    await writeParameters(config.region, `/medplum/${config.name}/`, serverParams);\n  } else {\n    const serverConfigFileName = getConfigFileName(config.name, { server: true });\n    writeConfig(serverConfigFileName, serverParams);\n    print('Skipping AWS Parameter Store.');\n    print(`Writing values to local config file: ${serverConfigFileName}`);\n    print('Please add these values to AWS Parameter Store manually.');\n  }\n\n  header('DONE!');\n  print('Medplum configuration complete.');\n  print('You can now proceed to deploying the Medplum infrastructure with CDK.');\n  print('Run:');\n  print('');\n  print(`    npx cdk bootstrap -c config=${configFileName}`);\n  print(`    npx cdk synth -c config=${configFileName}`);\n  if (config.region === 'us-east-1') {\n    print(`    npx cdk deploy -c config=${configFileName}`);\n  } else {\n    print(`    npx cdk deploy -c config=${configFileName} --all`);\n  }\n  print('');\n  print('See Medplum documentation for more information:');\n  print('');\n  print('    https://www.medplum.com/docs/self-hosting/install-on-aws');\n  print('');\n  closeTerminal();\n}\n\n/**\n * Returns the current AWS account ID.\n * This is used as the default value for the \"accountNumber\" config setting.\n * @param region - The AWS region.\n * @returns The AWS account ID.\n */\nasync function getAccountId(region: string): Promise<string | undefined> {\n  try {\n    const client = new STSClient({ region });\n    const command = new GetCallerIdentityCommand({});\n    const response = await client.send(command);\n    return response.Account;\n  } catch (err) {\n    console.log('Warning: Unable to get AWS account ID', (err as Error).message);\n    return undefined;\n  }\n}\n\n/**\n * Returns a list of all AWS certificates.\n * This is used to find existing certificates for the subdomains.\n * If the primary region is not us-east-1, then certificates in us-east-1 will also be returned.\n * @param region - The AWS region.\n * @returns The list of AWS Certificates.\n */\nasync function listAllCertificates(region: string): Promise<CertificateSummary[]> {\n  const result = await listCertificates(region);\n  if (region !== 'us-east-1') {\n    const usEast1Result = await listCertificates('us-east-1');\n    result.push(...usEast1Result);\n  }\n  return result;\n}\n\n/**\n * Returns a list of AWS Certificates.\n * This is used to find existing certificates for the subdomains.\n * @param region - The AWS region.\n * @returns The list of AWS Certificates.\n */\nasync function listCertificates(region: string): Promise<CertificateSummary[]> {\n  try {\n    const client = new ACMClient({ region });\n    const command = new ListCertificatesCommand({ MaxItems: 1000 });\n    const response = await client.send(command);\n    return response.CertificateSummaryList as CertificateSummary[];\n  } catch (err) {\n    console.log('Warning: Unable to list certificates', (err as Error).message);\n    return [];\n  }\n}\n\n/**\n * Processes a required certificate.\n *\n * 1. If the certificate already exists, return the ARN.\n * 2. If the certificate does not exist, and the user wants to create a new certificate, create it and return the ARN.\n * 3. If the certificate does not exist, and the user does not want to create a new certificate, return a placeholder.\n * @param config - In-progress config settings.\n * @param allCerts - List of all existing certificates.\n * @param region - The AWS region where the certificate is needed.\n * @param certName - The name of the certificate (api, app, or storage).\n * @returns The ARN of the certificate or placeholder if a new certificate is needed.\n */\nasync function processCert(\n  config: MedplumInfraConfig,\n  allCerts: CertificateSummary[],\n  region: string,\n  certName: 'api' | 'app' | 'storage'\n): Promise<string> {\n  const domainName = config[getDomainSetting(certName)];\n  const existingCert = allCerts.find((cert) => cert.CertificateArn?.includes(region) && cert.DomainName === domainName);\n  if (existingCert) {\n    print(`Found existing certificate for \"${domainName}\" in \"${region}.`);\n    return existingCert.CertificateArn as string;\n  }\n\n  print(`No existing certificate found for \"${domainName}\" in \"${region}.`);\n  if (!(await yesOrNo('Do you want to request a new certificate?'))) {\n    print(`Please add your certificate ARN to the config file in the \"${getDomainCertSetting(certName)}\" setting.`);\n    return 'TODO';\n  }\n\n  const arn = await requestCert(region, domainName);\n  print('Certificate ARN: ' + arn);\n  return arn;\n}\n\n/**\n * Requests an AWS Certificate.\n * @param region - The AWS region.\n * @param domain - The domain name.\n * @returns The AWS Certificate ARN on success, or undefined on failure.\n */\nasync function requestCert(region: string, domain: string): Promise<string> {\n  try {\n    const validationMethod = await choose(\n      'Validate certificate using DNS or email validation?',\n      ['dns', 'email'],\n      'dns'\n    );\n    const client = new ACMClient({ region });\n    const command = new RequestCertificateCommand({\n      DomainName: domain,\n      ValidationMethod: validationMethod.toUpperCase() as ValidationMethod,\n    });\n    const response = await client.send(command);\n    return response.CertificateArn as string;\n  } catch (err) {\n    console.log('Error: Unable to request certificate', (err as Error).message);\n    return 'TODO';\n  }\n}\n\n/**\n * Generates an AWS CloudFront signing key.\n *\n * Requirements:\n *\n *   1. It must be an SSH-2 RSA key pair.\n *   2. It must be in base64-encoded PEM format.\n *   3. It must be a 2048-bit key pair.\n *\n * See: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-trusted-signers.html#private-content-creating-cloudfront-key-pairs\n *\n * @param region - The AWS region.\n * @param keyName - The key name.\n * @returns A new signing key.\n */\nasync function generateSigningKey(\n  region: string,\n  keyName: string\n): Promise<\n  | {\n      keyId: string;\n      publicKey: string;\n      privateKey: string;\n      passphrase: string;\n    }\n  | undefined\n> {\n  const passphrase = randomUUID();\n  const signingKey = generateKeyPairSync('rsa', {\n    modulusLength: 2048,\n    publicKeyEncoding: {\n      type: 'spki',\n      format: 'pem',\n    },\n    privateKeyEncoding: {\n      type: 'pkcs1',\n      format: 'pem',\n      cipher: 'aes-256-cbc',\n      passphrase,\n    },\n  });\n\n  try {\n    const response = await new CloudFrontClient({ region }).send(\n      new CreatePublicKeyCommand({\n        PublicKeyConfig: {\n          Name: keyName,\n          CallerReference: randomUUID(),\n          EncodedKey: signingKey.publicKey,\n        },\n      })\n    );\n\n    return {\n      keyId: response.PublicKey?.Id as string,\n      publicKey: signingKey.publicKey,\n      privateKey: signingKey.privateKey,\n      passphrase,\n    };\n  } catch (err) {\n    console.log('Error: Unable to create signing key: ', normalizeErrorString(err));\n    return undefined;\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { getAllStacks, getStackDetails, printStackDetails } from './utils';\n\n/**\n * The AWS \"list\" command prints summary details about all Medplum CloudFormation stacks.\n */\nexport async function listStacksCommand(): Promise<void> {\n  const stackSummaries = await getAllStacks();\n  for (const stackSummary of stackSummaries) {\n    const stackName = stackSummary.StackName;\n    const details = await getStackDetails(stackName);\n    if (!details) {\n      continue;\n    }\n    printStackDetails(details);\n    console.log('');\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { PutObjectCommand } from '@aws-sdk/client-s3';\nimport { ContentType } from '@medplum/core';\nimport fastGlob from 'fast-glob';\nimport { createReadStream, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join, sep } from 'node:path';\nimport { Readable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport { readConfig, safeTarExtractor } from '../utils';\nimport { createInvalidation, getStackByTag, printConfigNotFound, printStackNotFound, s3Client } from './utils';\n\nexport interface UpdateAppOptions {\n  file?: string;\n  toVersion?: string;\n  dryrun?: boolean;\n  tarPath?: string;\n}\n\n/**\n * The AWS \"update-app\" command updates the Medplum app in a Medplum CloudFormation stack to the latest version.\n * @param tag - The Medplum stack tag.\n * @param options - The update options.\n */\nexport async function updateAppCommand(tag: string, options: UpdateAppOptions): Promise<void> {\n  const config = readConfig(tag, options);\n  if (!config) {\n    printConfigNotFound(tag, options);\n    throw new Error(`Config not found: ${tag}`);\n  }\n  const details = await getStackByTag(tag);\n  if (!details) {\n    await printStackNotFound(tag);\n    throw new Error(`Stack not found: ${tag}`);\n  }\n  const appBucket = details.appBucket;\n  if (!appBucket) {\n    throw new Error(`App bucket not found for stack ${tag}`);\n  }\n\n  let tmpDir: string;\n\n  if (options.tarPath) {\n    tmpDir = options.tarPath;\n  } else {\n    const version = options?.toVersion ?? 'latest';\n    tmpDir = await downloadNpmPackage('@medplum/app', version);\n  }\n\n  // Replace variables in the app\n  replaceVariables(tmpDir, {\n    MEDPLUM_BASE_URL: config.baseUrl as string,\n    MEDPLUM_CLIENT_ID: config.clientId ?? '',\n    GOOGLE_CLIENT_ID: config.googleClientId ?? '',\n    RECAPTCHA_SITE_KEY: config.recaptchaSiteKey ?? '',\n    MEDPLUM_REGISTER_ENABLED: config.registerEnabled ? 'true' : 'false',\n  });\n\n  // Upload the app to S3 with correct content-type and cache-control\n  await uploadAppToS3(tmpDir, appBucket.PhysicalResourceId as string, options);\n\n  // Create a CloudFront invalidation to clear any cached resources\n  if (details.appDistribution?.PhysicalResourceId && !options.dryrun) {\n    await createInvalidation(details.appDistribution.PhysicalResourceId);\n  }\n\n  console.log('Done');\n}\n\n/**\n * Returns NPM package metadata for a given package name.\n * See: https://github.com/npm/registry/blob/master/docs/REGISTRY-API.md#getpackageversion\n * @param packageName - The npm package name.\n * @param version - The npm package version string.\n * @returns The package.json metadata content.\n */\nasync function getNpmPackageMetadata(packageName: string, version: string): Promise<any> {\n  const url = `https://registry.npmjs.org/${packageName}/${version}`;\n  const response = await fetch(url);\n  return response.json();\n}\n\n/**\n * Downloads and extracts an NPM package.\n * @param packageName - The NPM package name.\n * @param version - The NPM package version or \"latest\".\n * @returns Path to temporary directory where the package was downloaded and extracted.\n */\nasync function downloadNpmPackage(packageName: string, version: string): Promise<string> {\n  const packageMetadata = await getNpmPackageMetadata(packageName, version);\n  const tarballUrl = packageMetadata.dist.tarball as string;\n  const tmpDir = mkdtempSync(join(tmpdir(), 'tarball-'));\n  try {\n    const response = await fetch(tarballUrl);\n    if (!response.body) {\n      throw new Error('Received empty response body');\n    }\n    const extractor = safeTarExtractor(tmpDir);\n    await pipeline(Readable.fromWeb(response.body as Parameters<typeof Readable.fromWeb>[0]), extractor);\n    return join(tmpDir, 'package', 'dist');\n  } catch (error) {\n    rmSync(tmpDir, { recursive: true, force: true });\n    throw error;\n  }\n}\n\n/**\n * Replaces variables in all JS files in the given folder.\n * @param folderName - The folder name of the files.\n * @param replacements - The collection of variable placeholders and replacements.\n */\nfunction replaceVariables(folderName: string, replacements: Record<string, string>): void {\n  for (const item of readdirSync(folderName, { withFileTypes: true })) {\n    const itemPath = join(folderName, item.name);\n    if (item.isDirectory()) {\n      replaceVariables(itemPath, replacements);\n    } else if (item.isFile() && itemPath.endsWith('.js')) {\n      replaceVariablesInFile(itemPath, replacements);\n    }\n  }\n}\n\n/**\n * Replaces variables in the JS file.\n * @param fileName - The file name.\n * @param replacements - The collection of variable placeholders and replacements.\n */\nfunction replaceVariablesInFile(fileName: string, replacements: Record<string, string>): void {\n  let contents = readFileSync(fileName, 'utf-8');\n  for (const [placeholder, replacement] of Object.entries(replacements)) {\n    contents = contents.replaceAll(`__${placeholder}__`, replacement);\n  }\n  writeFileSync(fileName, contents);\n}\n\n/**\n * Uploads the app to S3.\n * Ensures correct content-type and cache-control for each file.\n * @param tmpDir - The temporary directory where the app is located.\n * @param bucketName - The destination S3 bucket name.\n * @param options - The update options.\n */\nasync function uploadAppToS3(tmpDir: string, bucketName: string, options: UpdateAppOptions): Promise<void> {\n  // Manually iterate and upload files\n  // Automatic content-type detection is not reliable on Microsoft Windows\n  // So we explicitly set content-type\n  const uploadPatterns: [string, string, boolean][] = [\n    // Cached\n    // These files generally have a hash, so they can be cached forever\n    // It is important to upload them first to avoid broken references from index.html\n    ['assets/**/*.css', ContentType.CSS, true],\n    ['assets/**/*.css.map', ContentType.JSON, true],\n    ['assets/**/*.js', ContentType.JAVASCRIPT, true],\n    ['assets/**/*.js.map', ContentType.JSON, true],\n    ['assets/**/*.txt', ContentType.TEXT, true],\n    ['assets/**/*.ico', ContentType.FAVICON, true],\n    ['img/**/*.png', ContentType.PNG, true],\n    ['img/**/*.svg', ContentType.SVG, true],\n    ['robots.txt', ContentType.TEXT, true],\n\n    // Not cached\n    ['index.html', ContentType.HTML, false],\n  ];\n  for (const uploadPattern of uploadPatterns) {\n    await uploadFolderToS3({\n      rootDir: tmpDir,\n      bucketName,\n      fileNamePattern: uploadPattern[0],\n      contentType: uploadPattern[1],\n      cached: uploadPattern[2],\n      dryrun: options.dryrun,\n    });\n  }\n}\n\n/**\n * Uploads a directory of files to S3.\n * @param options - The upload options such as bucket name, content type, and cache control.\n * @param options.rootDir - The root directory of the upload.\n * @param options.bucketName - The destination bucket name.\n * @param options.fileNamePattern - The glob file pattern to upload.\n * @param options.contentType - The content type MIME type.\n * @param options.cached - True to mark as public and cached forever.\n * @param options.dryrun - True to skip the upload.\n */\nasync function uploadFolderToS3(options: {\n  rootDir: string;\n  bucketName: string;\n  fileNamePattern: string;\n  contentType: string;\n  cached: boolean;\n  dryrun?: boolean;\n}): Promise<void> {\n  const items = fastGlob.sync(options.fileNamePattern, { cwd: options.rootDir });\n  for (const item of items) {\n    await uploadFileToS3(join(options.rootDir, item), options);\n  }\n}\n\n/**\n * Uploads a file to S3.\n * @param filePath - The file path.\n * @param options - The upload options such as bucket name, content type, and cache control.\n * @param options.rootDir - The root directory of the upload.\n * @param options.bucketName - The destination bucket name.\n * @param options.contentType - The content type MIME type.\n * @param options.cached - True to mark as public and cached forever.\n * @param options.dryrun - True to skip the upload.\n */\nasync function uploadFileToS3(\n  filePath: string,\n  options: {\n    rootDir: string;\n    bucketName: string;\n    contentType: string;\n    cached: boolean;\n    dryrun?: boolean;\n  }\n): Promise<void> {\n  const fileStream = createReadStream(filePath);\n  const s3Key = filePath\n    .substring(options.rootDir.length + 1)\n    .split(sep)\n    .join('/');\n\n  const putObjectParams = {\n    Bucket: options.bucketName,\n    Key: s3Key,\n    Body: fileStream,\n    ContentType: options.contentType,\n    CacheControl: options.cached ? 'public, max-age=31536000' : 'no-cache, no-store, must-revalidate',\n  };\n\n  console.log(`Uploading ${s3Key} to ${options.bucketName}...`);\n  if (!options.dryrun) {\n    await s3Client.send(new PutObjectCommand(putObjectParams));\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { StackResource } from '@aws-sdk/client-cloudformation';\nimport { GetBucketPolicyCommand, PutBucketPolicyCommand } from '@aws-sdk/client-s3';\nimport { readConfig } from '../utils';\nimport { createInvalidation, getStackByTag, printConfigNotFound, printStackNotFound, s3Client } from './utils';\n\nexport interface UpdateBucketPoliciesOptions {\n  file?: string;\n  dryrun?: boolean;\n  guarddutyMalwareProtection?: boolean;\n}\n\ninterface Policy {\n  Version?: string;\n  Statement?: PolicyStatement[];\n}\n\ninterface PolicyStatement {\n  Sid?: string;\n  Effect?: string;\n  Principal?: { AWS?: string; CanonicalUser?: string };\n  Action?: string | string[];\n  Resource?: string | string[];\n  Condition?: Record<string, Record<string, string | string[]>>;\n}\n\n/**\n * The AWS \"update-bucket-policies\" command adds necessary policy statements to S3 bucket policy documents.\n *\n * This is necessary for Medplum deployments outside of the us-east-1 region.\n *\n * @param tag - The Medplum stack tag.\n * @param options - The update options.\n */\nexport async function updateBucketPoliciesCommand(tag: string, options: UpdateBucketPoliciesOptions): Promise<void> {\n  const config = readConfig(tag, options);\n  if (!config) {\n    printConfigNotFound(tag, options);\n    throw new Error(`Config not found: ${tag}`);\n  }\n\n  const details = await getStackByTag(tag);\n  if (!details) {\n    await printStackNotFound(tag);\n    throw new Error(`Stack not found: ${tag}`);\n  }\n\n  try {\n    await updateBucketPolicy(\n      'App',\n      details.appBucket,\n      details.appDistribution,\n      details.appOriginAccessIdentity,\n      options\n    );\n  } catch (err) {\n    console.error(`Error updating App bucket policy: ${(err as Error).message}`);\n  }\n\n  try {\n    await updateBucketPolicy(\n      'Storage',\n      details.storageBucket,\n      details.storageDistribution,\n      details.storageOriginAccessIdentity,\n      options\n    );\n  } catch (err) {\n    console.error(`Error updating Storage bucket policy: ${(err as Error).message}`);\n  }\n\n  console.log('Done');\n}\n\nexport async function updateBucketPolicy(\n  friendlyName: string,\n  bucketResource: StackResource | undefined,\n  distributionResource: StackResource | undefined,\n  oaiResource: StackResource | undefined,\n  options: UpdateBucketPoliciesOptions\n): Promise<void> {\n  if (!bucketResource?.PhysicalResourceId) {\n    throw new Error(`${friendlyName} bucket not found`);\n  }\n\n  if (!distributionResource?.PhysicalResourceId) {\n    throw new Error(`${friendlyName} distribution not found`);\n  }\n\n  if (!oaiResource?.PhysicalResourceId) {\n    throw new Error(`${friendlyName} OAI not found`);\n  }\n\n  const bucketName = bucketResource.PhysicalResourceId;\n  const oaiId = oaiResource.PhysicalResourceId;\n  const bucketPolicy = await getPolicy(bucketName);\n  if (policyHasAllowStatement(bucketPolicy, bucketName, oaiId)) {\n    throw new Error(`${friendlyName} bucket already has policy statement`);\n  }\n\n  addAllowPolicyStatement(bucketPolicy, bucketName, oaiId);\n  if (friendlyName === 'Storage' && options.guarddutyMalwareProtection) {\n    addGuardDutyReadPolicyStatement(bucketPolicy, bucketName, oaiId);\n  }\n  console.log(`${friendlyName} bucket policy:`);\n  console.log(JSON.stringify(bucketPolicy, undefined, 2));\n\n  if (options.dryrun) {\n    console.log('Dry run - skipping updates');\n  } else {\n    // Apply the updated policy\n    console.log('Updating bucket policy...');\n    await setPolicy(bucketName, bucketPolicy);\n    console.log('Bucket policy updated');\n\n    // Create a CloudFront invalidation to clear any cached responses\n    console.log('Creating CloudFront invalidation...');\n    await createInvalidation(distributionResource.PhysicalResourceId);\n    console.log('CloudFront invalidation created');\n\n    console.log(`${friendlyName} bucket policy updated`);\n  }\n}\n\nasync function getPolicy(bucketName: string): Promise<Policy> {\n  const policyResponse = await s3Client.send(\n    new GetBucketPolicyCommand({\n      Bucket: bucketName,\n    })\n  );\n  return JSON.parse(policyResponse.Policy ?? '{}') as Policy;\n}\n\nasync function setPolicy(bucketName: string, policy: Policy): Promise<void> {\n  await s3Client.send(\n    new PutBucketPolicyCommand({\n      Bucket: bucketName,\n      Policy: JSON.stringify(policy),\n    })\n  );\n}\n\nfunction policyHasAllowStatement(policy: Policy, bucketName: string, oaiId: string): boolean {\n  return !!policy?.Statement?.some((s: PolicyStatement) => {\n    return (\n      s?.Effect === 'Allow' &&\n      s?.Principal?.AWS === `arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${oaiId}` &&\n      Array.isArray(s?.Action) &&\n      s?.Action?.includes('s3:GetObject*') &&\n      s?.Action?.includes('s3:GetBucket*') &&\n      s?.Action?.includes('s3:List*') &&\n      Array.isArray(s?.Resource) &&\n      s?.Resource?.includes(`arn:aws:s3:::${bucketName}`) &&\n      s?.Resource?.includes(`arn:aws:s3:::${bucketName}/*`)\n    );\n  });\n}\n\nfunction addAllowPolicyStatement(policy: Policy, bucketName: string, oaiId: string): void {\n  if (!policy.Version) {\n    policy.Version = '2012-10-17';\n  }\n\n  if (!policy.Statement) {\n    policy.Statement = [];\n  }\n\n  policy.Statement.push({\n    Effect: 'Allow',\n    Principal: {\n      AWS: `arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${oaiId}`,\n    },\n    Action: ['s3:GetObject*', 's3:GetBucket*', 's3:List*'],\n    Resource: [`arn:aws:s3:::${bucketName}`, `arn:aws:s3:::${bucketName}/*`],\n  });\n}\n\nfunction addGuardDutyReadPolicyStatement(policy: Policy, bucketName: string, oaiId: string): void {\n  if (\n    policy.Statement?.some(\n      (s) =>\n        s?.Effect === 'Deny' &&\n        s?.Principal?.AWS === `arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${oaiId}` &&\n        statementHasAction(s, 's3:GetObject') &&\n        statementHasAction(s, 's3:GetObjectVersion') &&\n        s?.Condition?.StringNotEquals?.['s3:ExistingObjectTag/GuardDutyMalwareScanStatus'] === 'NO_THREATS_FOUND'\n    )\n  ) {\n    return;\n  }\n\n  policy.Statement?.push({\n    Sid: 'GuardDutyMalwareProtectionReadGate',\n    Effect: 'Deny',\n    Principal: {\n      AWS: `arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${oaiId}`,\n    },\n    Action: ['s3:GetObject', 's3:GetObjectVersion'],\n    Resource: `arn:aws:s3:::${bucketName}/*`,\n    Condition: {\n      StringNotEquals: {\n        's3:ExistingObjectTag/GuardDutyMalwareScanStatus': 'NO_THREATS_FOUND',\n      },\n    },\n  });\n}\n\nfunction statementHasAction(statement: PolicyStatement, action: string): boolean {\n  if (statement.Action === action) {\n    return true;\n  }\n  return Array.isArray(statement.Action) && statement.Action.includes(action);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumInfraConfig } from '@medplum/core';\nimport { color } from '../util/color';\nimport { getConfigFileName, readConfig, readServerConfig } from '../utils';\nimport { closeTerminal, initTerminal, print, yesOrNo } from './terminal';\nimport { printConfigNotFound, writeParameters } from './utils';\n\nexport interface UpdateConfigOptions {\n  file?: string;\n  dryrun?: boolean;\n  yes?: boolean;\n}\n\n/**\n * The AWS \"update-config\" command updates AWS Parameter Store values with values from the local config file.\n * @param tag - The Medplum stack tag.\n * @param options - Additional command line options.\n */\nexport async function updateConfigCommand(tag: string, options: UpdateConfigOptions): Promise<void> {\n  try {\n    initTerminal();\n\n    const infraConfig = readConfig(tag, options) as MedplumInfraConfig;\n    if (!infraConfig) {\n      printConfigNotFound(tag, options);\n      throw new Error(`Config not found: ${tag}`);\n    }\n\n    const serverConfig = readServerConfig(tag) ?? {};\n\n    // If the server config is empty, prompt the user to proceed\n    if (!options.yes && Object.keys(serverConfig).length === 0) {\n      const serverConfigFileName = getConfigFileName(tag, { server: true });\n      console.log(color.yellow(`Config file ${serverConfigFileName} not found!`));\n      if (!(await yesOrNo('Do you want to proceed?'))) {\n        console.log(color.red(`Run Aborted, please ensure ${serverConfigFileName} is present and try again.`));\n        return;\n      }\n    }\n\n    checkConfigConflicts(infraConfig, serverConfig);\n    mergeConfigs(infraConfig, serverConfig);\n\n    print('Medplum uses AWS Parameter Store to store sensitive configuration values.');\n    print('These values will be encrypted at rest.');\n    print(`The values will be stored in the \"/medplum/${infraConfig.name}\" path.`);\n\n    print(\n      JSON.stringify(\n        {\n          ...serverConfig,\n          signingKey: '****',\n          signingKeyPassphrase: '****',\n        },\n        null,\n        2\n      )\n    );\n\n    if (options.dryrun) {\n      console.log(color.yellow('Dry run - skipping updates!'));\n    } else if (options.yes || (await yesOrNo('Do you want to store these values in AWS Parameter Store?'))) {\n      await writeParameters(infraConfig.region, `/medplum/${infraConfig.name}/`, serverConfig);\n    }\n  } finally {\n    closeTerminal();\n  }\n}\n\nexport function checkConfigConflicts(\n  infraConfig: MedplumInfraConfig,\n  serverConfig: Record<string, string | number>\n): void {\n  checkConflict(\n    infraConfig.apiPort,\n    serverConfig.port,\n    `Infra \"apiPort\" (${infraConfig.apiPort}) does not match server \"port\" (${serverConfig.port})`\n  );\n\n  checkConflict(\n    infraConfig.baseUrl,\n    serverConfig.baseUrl,\n    `Infra \"baseUrl\" (${infraConfig.baseUrl}) does not match server \"baseUrl\" (${serverConfig.baseUrl})`\n  );\n\n  checkConflict(\n    infraConfig.appDomainName && `https://${infraConfig.appDomainName}/`,\n    serverConfig.appBaseUrl,\n    `Infra \"appDomainName\" (${infraConfig.appDomainName}) does not match server \"appBaseUrl\" (${serverConfig.appBaseUrl})`\n  );\n\n  checkConflict(\n    infraConfig.storageDomainName && `https://${infraConfig.storageDomainName}/binary/`,\n    serverConfig.storageBaseUrl,\n    `Infra \"storageDomainName\" (${infraConfig.storageDomainName}) does not match server \"storageBaseUrl\" (${serverConfig.storageBaseUrl})`\n  );\n}\n\nfunction checkConflict<T>(a: T, b: T, message: string): void {\n  if (isConflict(a, b)) {\n    throw new Error(message);\n  }\n}\n\nfunction isConflict<T>(a: T, b: T): boolean {\n  return a !== undefined && b !== undefined && a !== b;\n}\n\nexport function mergeConfigs(infraConfig: MedplumInfraConfig, serverConfig: Record<string, string | number>): void {\n  if (infraConfig.apiPort) {\n    serverConfig.port = infraConfig.apiPort;\n  }\n  if (infraConfig.baseUrl) {\n    serverConfig.baseUrl = infraConfig.baseUrl;\n  }\n  if (infraConfig.appDomainName) {\n    serverConfig.appBaseUrl = `https://${infraConfig.appDomainName}/`;\n  }\n  if (infraConfig.storageDomainName) {\n    serverConfig.storageBaseUrl = `https://${infraConfig.storageDomainName}/binary/`;\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient, MedplumClientOptions, MedplumInfraConfig } from '@medplum/core';\nimport { spawnSync } from 'node:child_process';\nimport * as semver from 'semver';\nimport { createMedplumClient } from '../util/client';\nimport { getConfigFileName, readConfig, writeConfig } from '../utils';\nimport { getServerVersions, printConfigNotFound } from './utils';\n\nexport interface UpdateServerOptions extends MedplumClientOptions {\n  file?: string;\n  toVersion?: string;\n}\n\n/**\n * The AWS \"update-server\" command updates the Medplum server in a Medplum CloudFormation stack.\n * @param tag - The Medplum stack tag.\n * @param options - Client options\n */\nexport async function updateServerCommand(tag: string, options: UpdateServerOptions): Promise<void> {\n  const client = await createMedplumClient(options);\n  const config = readConfig(tag, options) as MedplumInfraConfig;\n  if (!config) {\n    console.log(`Configuration file ${getConfigFileName(tag)} not found`);\n    printConfigNotFound(tag, options);\n    throw new Error(`Config not found: ${tag}`);\n  }\n\n  const separatorIndex = config.serverImage.lastIndexOf(':');\n  const serverImagePrefix = config.serverImage.slice(0, separatorIndex);\n\n  const initialVersion = await getCurrentVersion(client, config);\n\n  let updateVersion = await nextUpdateVersion(initialVersion);\n  while (updateVersion) {\n    if (options.toVersion && semver.gt(updateVersion, options.toVersion)) {\n      console.log(`Skipping update to v${updateVersion}`);\n      break;\n    }\n\n    console.log(`Performing update to v${updateVersion}`);\n    config.serverImage = `${serverImagePrefix}:${updateVersion}`;\n    deployServerUpdate(tag, config);\n\n    // Run data migrations\n    await client.startAsyncRequest('/admin/super/migrate');\n\n    updateVersion = await nextUpdateVersion(updateVersion);\n  }\n}\n\nasync function getCurrentVersion(medplum: MedplumClient, config: MedplumInfraConfig): Promise<string> {\n  const separatorIndex = config.serverImage.lastIndexOf(':');\n  let initialVersion = config.serverImage.slice(separatorIndex + 1);\n  if (initialVersion === 'latest') {\n    const serverInfo = await medplum.get('/healthcheck');\n    initialVersion = serverInfo.version as string;\n    const sep = initialVersion.indexOf('-');\n    if (sep > -1) {\n      initialVersion = initialVersion.slice(0, sep);\n    }\n  }\n  return initialVersion;\n}\n\nasync function nextUpdateVersion(currentVersion: string, targetVersion?: string): Promise<string | undefined> {\n  // The list of server versions is sorted in descending order\n  // The first entry is the latest version\n  // The last entry is the oldest version\n  // We want to find the \"next\" version after our current version\n  // Filter the list to only include versions that are greater than or equal to the current minor version\n  // Then pop the last entry from the list\n  const allVersions = await getServerVersions(currentVersion);\n  const latestVersion = allVersions[0];\n  return allVersions\n    .filter(\n      (v) => v === latestVersion || v === targetVersion || semver.gte(v, semver.inc(currentVersion, 'minor') as string)\n    )\n    .pop();\n}\n\nfunction deployServerUpdate(tag: string, config: MedplumInfraConfig): void {\n  const configFile = getConfigFileName(tag);\n  writeConfig(configFile, config);\n\n  const cmd = `npx cdk deploy -c config=${configFile}${config.region !== 'us-east-1' ? ' --all' : ''}`;\n  console.log('> ' + cmd);\n  const deploy = spawnSync(cmd, { stdio: 'inherit' });\n\n  if (deploy.status !== 0) {\n    throw new Error(`Deploy of ${config.serverImage} failed (exit code ${deploy.status}): ${deploy.stderr}`);\n  }\n  console.log(deploy.stdout);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { color, processDescription } from '../util/color';\nimport { addSubcommand, MedplumCommand } from '../utils';\nimport { describeStacksCommand } from './describe';\nimport { initStackCommand } from './init';\nimport { listStacksCommand } from './list';\nimport { updateAppCommand } from './update-app';\nimport { updateBucketPoliciesCommand } from './update-bucket-policies';\nimport { updateConfigCommand } from './update-config';\nimport { updateServerCommand } from './update-server';\n\nexport function buildAwsCommand(): MedplumCommand {\n  const aws = new MedplumCommand('aws').description('Commands to manage AWS resources');\n\n  aws.command('init').description('Initialize a new Medplum AWS CloudFormation stacks').action(initStackCommand);\n\n  aws.command('list').description('List Medplum AWS CloudFormation stacks').action(listStacksCommand);\n\n  aws\n    .command('describe')\n    .description('Describe a Medplum AWS CloudFormation stack by tag')\n    .argument('<tag>', 'The Medplum stack tag')\n    .action(describeStacksCommand);\n\n  aws\n    .command('update-config')\n    .alias('deploy-config')\n    .summary('Update the AWS Parameter Store config values.')\n    .description(\n      processDescription(\n        'Update the AWS Parameter Store config values.\\n\\nConfiguration values come from a file named **medplum.<tag>.config.server.json** where **<tag>** is the Medplum stack tag.\\n\\n' +\n          color.yellow('**Services must be restarted to apply changes.**')\n      )\n    )\n    .argument('<tag>', 'The Medplum stack tag')\n    .option(\n      '--file [file]',\n      processDescription(\n        'File to provide overrides for **apiPort**, **baseUrl**, **appDomainName** and **storageDomainName** values that appear in the config file.'\n      )\n    )\n    .option(\n      '--dryrun',\n      'Displays the operations that would be performed using the specified command without actually running them.'\n    )\n    .option('--yes', 'Automatically confirm the update')\n    .action(updateConfigCommand);\n\n  addSubcommand(\n    aws,\n    new MedplumCommand('update-server')\n      .alias('deploy-server')\n      .description('Update the server image')\n      .argument('<tag>', 'The Medplum stack tag')\n      .option('--file [file]', 'Specifies the config file to use. If not specified, the file is based on the tag.')\n      .option(\n        '--to-version [version]',\n        'Specifies the version of the configuration to update. If not specified, the latest version is updated.'\n      )\n      .action(updateServerCommand)\n  );\n\n  aws\n    .command('update-app')\n    .alias('deploy-app')\n    .description('Update the app site')\n    .argument('<tag>', 'The Medplum stack tag')\n    .option('--file [file]', 'Specifies the config file to use. If not specified, the file is based on the tag.')\n    .option(\n      '--to-version [version]',\n      'Specifies the version of the configuration to update. If not specified, the latest version is updated.'\n    )\n    .option(\n      '--dryrun',\n      'Displays the operations that would be performed using the specified command without actually running them.'\n    )\n    .option('--tar-path [tarPath]', 'Specifies the path to the extracted tarball of the @medplum/app package.')\n    .action(updateAppCommand);\n\n  aws\n    .command('update-bucket-policies')\n    .description('Update S3 bucket policies')\n    .argument('<tag>', 'The Medplum stack tag')\n    .option('--file [file]', 'Specifies the config file to use. If not specified, the file is based on the tag.')\n    .option(\n      '--guardduty-malware-protection',\n      'Adds the GuardDuty Malware Protection for S3 read-gating deny to the storage bucket policy.'\n    )\n    .option(\n      '--dryrun',\n      'Displays the operations that would be performed using the specified command without actually running them.'\n    )\n    .action(updateBucketPoliciesCommand);\n\n  return aws;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient } from '@medplum/core';\nimport { createMedplumClient } from './util/client';\nimport { MedplumCommand, addSubcommand, createBot, deployBot, readBotConfigs, saveBot } from './utils';\n\nconst botSaveCommand = new MedplumCommand('save');\nconst botDeployCommand = new MedplumCommand('deploy');\nconst botCreateCommand = new MedplumCommand('create');\n\nexport const bot = new MedplumCommand('bot');\naddSubcommand(bot, botSaveCommand);\naddSubcommand(bot, botDeployCommand);\naddSubcommand(bot, botCreateCommand);\n\n// Commands to deprecate\nexport const saveBotDeprecate = new MedplumCommand('save-bot');\nexport const deployBotDeprecate = new MedplumCommand('deploy-bot');\nexport const createBotDeprecate = new MedplumCommand('create-bot');\n\nbotSaveCommand\n  .description('Saving the bot')\n  .argument('<botName>')\n  .action(async (botName, options) => {\n    const medplum = await createMedplumClient(options);\n\n    await botWrapper(medplum, botName);\n  });\n\nbotDeployCommand\n  .description('Deploy the app to AWS')\n  .argument('<botName>')\n  .action(async (botName, options) => {\n    const medplum = await createMedplumClient(options);\n\n    await botWrapper(medplum, botName, true);\n  });\n\nbotCreateCommand\n  .arguments('<botName> <projectId> <sourceFile> <distFile>')\n  .description('Creating a bot')\n  .option('--runtime-version <runtimeVersion>', 'Runtime version (awslambda, vmcontext)')\n  .option('--no-write-config', 'Do not write bot to config')\n  .action(async (botName, projectId, sourceFile, distFile, options) => {\n    const medplum = await createMedplumClient(options);\n\n    await createBot(medplum, botName, projectId, sourceFile, distFile, options.runtimeVersion, !!options.writeConfig);\n  });\n\nexport async function botWrapper(medplum: MedplumClient, botName: string, deploy = false): Promise<void> {\n  const botConfigs = readBotConfigs(botName);\n  const errors = [] as Error[];\n  const errored = [] as string[];\n  let saved = 0;\n  let deployed = 0;\n\n  for (const botConfig of botConfigs) {\n    try {\n      const bot = await medplum.readResource('Bot', botConfig.id);\n      await saveBot(medplum, botConfig, bot);\n      saved++;\n      if (deploy) {\n        await deployBot(medplum, botConfig, bot);\n        deployed++;\n      }\n    } catch (err: unknown) {\n      errors.push(err as Error);\n      errored.push(`${botConfig.name} [${botConfig.id}]`);\n    }\n  }\n\n  console.log(`Number of bots saved: ${saved}`);\n  console.log(`Number of bots deployed: ${deployed}`);\n  console.log(`Number of errors: ${errors.length}`);\n\n  if (errors.length) {\n    throw new Error(`${errors.length} bot(s) had failures. Bots with failures:\\n\\n    ${errored.join('\\n    ')}`, {\n      cause: errors,\n    });\n  }\n}\n\n// Deprecate bot commands\nsaveBotDeprecate\n  .description('Saves the bot')\n  .argument('<botName>')\n  .action(async (botName, options) => {\n    const medplum = await createMedplumClient(options);\n\n    await botWrapper(medplum, botName);\n  });\n\ndeployBotDeprecate\n  .description('Deploy the bot to AWS')\n  .argument('<botName>')\n  .action(async (botName, options) => {\n    const medplum = await createMedplumClient(options);\n\n    await botWrapper(medplum, botName, true);\n  });\n\ncreateBotDeprecate\n  .arguments('<botName> <projectId> <sourceFile> <distFile>')\n  .description('Creates and saves the bot')\n  .action(async (botName, projectId, sourceFile, distFile, options) => {\n    const medplum = await createMedplumClient(options);\n\n    await createBot(medplum, botName, projectId, sourceFile, distFile);\n  });\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient } from '@medplum/core';\nimport { EMPTY } from '@medplum/core';\nimport type { BundleEntry, ExplanationOfBenefit, ExplanationOfBenefitItem, Resource } from '@medplum/fhirtypes';\nimport { createReadStream, createWriteStream } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { createInterface } from 'node:readline';\nimport { Readable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport type { ReadableStream } from 'node:stream/web';\nimport { createMedplumClient } from './util/client';\nimport { MedplumCommand, addSubcommand, getUnsupportedExtension, prettyPrint } from './utils';\n\nconst bulkExportCommand = new MedplumCommand('export');\nconst bulkImportCommand = new MedplumCommand('import');\n\nexport const bulk = new MedplumCommand('bulk');\naddSubcommand(bulk, bulkExportCommand);\naddSubcommand(bulk, bulkImportCommand);\n\nbulkExportCommand\n  .option(\n    '-e, --export-level <exportLevel>',\n    'Optional export level. Defaults to system level export. \"Group/:id\" - Group of Patients, \"Patient\" - All Patients.'\n  )\n  .option('-t, --types <types>', 'optional resource types to export')\n  .option(\n    '-s, --since <since>',\n    'optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).'\n  )\n  .option(\n    '-d, --target-directory <targetDirectory>',\n    'optional target directory to save files from the bulk export operations.'\n  )\n  .action(async (options) => {\n    const { exportLevel, types, since, targetDirectory } = options;\n    const medplum = await createMedplumClient(options);\n    const response = await medplum.bulkExport(exportLevel, types, since, { pollStatusOnAccepted: true });\n\n    for (const { type, url } of response.output ?? EMPTY) {\n      const fileUrl = new URL(url);\n      const fileName = `${type}_${fileUrl.pathname}`.replaceAll(/[^a-zA-Z0-9]+/g, '_') + '.ndjson';\n      const path = resolve(targetDirectory ?? '', fileName);\n\n      const res = await medplum.downloadResponse(url);\n      if (!res.ok) {\n        throw new Error(`Download failed: ${res.status} ${res.statusText}`);\n      }\n      if (!res.body) {\n        throw new Error('Download response missing body');\n      }\n\n      const nodeStream = Readable.fromWeb(res.body as ReadableStream<Uint8Array>);\n      await pipeline(nodeStream, createWriteStream(path));\n      console.log(`${path} is created`);\n    }\n  });\n\nbulkImportCommand\n  .argument('<filename>', 'File Name')\n  .option(\n    '--num-resources-per-request <numResourcesPerRequest>',\n    'optional number of resources to import per batch request. Defaults to 25.',\n    '25'\n  )\n  .option(\n    '--add-extensions-for-missing-values',\n    'optional flag to add extensions for missing values in a resource',\n    false\n  )\n  .option('-d, --target-directory <targetDirectory>', 'optional target directory of file to be imported')\n  .action(async (fileName, options) => {\n    const { numResourcesPerRequest, addExtensionsForMissingValues, targetDirectory } = options;\n    const path = resolve(targetDirectory ?? process.cwd(), fileName);\n    const medplum = await createMedplumClient(options);\n\n    await importFile(path, Number.parseInt(numResourcesPerRequest, 10), medplum, addExtensionsForMissingValues);\n  });\n\nasync function importFile(\n  path: string,\n  numResourcesPerRequest: number,\n  medplum: MedplumClient,\n  addExtensionsForMissingValues: boolean\n): Promise<void> {\n  let entries: BundleEntry[] = [];\n  const fileStream = createReadStream(path);\n  const rl = createInterface({\n    input: fileStream,\n  });\n\n  for await (const line of rl) {\n    const resource = parseResource(line, addExtensionsForMissingValues);\n    entries.push({\n      resource: resource,\n      request: {\n        method: 'POST',\n        url: resource.resourceType,\n      },\n    });\n    if (entries.length % numResourcesPerRequest === 0) {\n      await sendBatchEntries(entries, medplum);\n      entries = [];\n    }\n  }\n  if (entries.length > 0) {\n    await sendBatchEntries(entries, medplum);\n  }\n}\n\nasync function sendBatchEntries(entries: BundleEntry[], medplum: MedplumClient): Promise<void> {\n  const result = await medplum.executeBatch({\n    resourceType: 'Bundle',\n    type: 'transaction',\n    entry: entries,\n  });\n\n  for (const resultEntry of result.entry ?? EMPTY) {\n    prettyPrint(resultEntry.response);\n  }\n}\n\nfunction parseResource(jsonString: string, addExtensionsForMissingValues: boolean): Resource {\n  const resource = JSON.parse(jsonString);\n\n  if (addExtensionsForMissingValues) {\n    return addExtensionsForMissingValuesResource(resource);\n  }\n\n  return resource;\n}\n\nfunction addExtensionsForMissingValuesResource(resource: Resource): Resource {\n  if (resource.resourceType === 'ExplanationOfBenefit') {\n    return addExtensionsForMissingValuesExplanationOfBenefits(resource);\n  }\n  return resource;\n}\n\nfunction addExtensionsForMissingValuesExplanationOfBenefits(resource: ExplanationOfBenefit): ExplanationOfBenefit {\n  if (!resource.provider) {\n    resource.provider = getUnsupportedExtension();\n  }\n\n  resource.item?.forEach((item: ExplanationOfBenefitItem) => {\n    if (!item?.productOrService) {\n      item.productOrService = getUnsupportedExtension();\n    }\n  });\n\n  return resource;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { formatHl7DateTime, Hl7Message } from '@medplum/core';\nimport { Hl7Client, Hl7Server } from '@medplum/hl7';\nimport { readFileSync } from 'node:fs';\nimport { addSubcommand, MedplumCommand } from './utils';\n\nconst send = new MedplumCommand('send')\n  .description('Send an HL7 v2 message via MLLP')\n  .argument('<host>', 'The destination host name or IP address')\n  .argument('<port>', 'The destination port number')\n  .argument('[body]', 'Optional HL7 message body')\n  .option('--generate-example', 'Generate a sample HL7 message')\n  .option('--file <file>', 'Read the HL7 message from a file')\n  .option('--encoding <encoding>', 'The encoding to use')\n  .action(async (host, port, body, options) => {\n    if (options.generateExample) {\n      body = generateSampleHl7Message();\n    } else if (options.file) {\n      body = readFileSync(options.file, 'utf8');\n    }\n\n    if (!body) {\n      throw new Error('Missing HL7 message body');\n    }\n\n    const client = new Hl7Client({\n      host,\n      port: Number.parseInt(port, 10),\n      encoding: options.encoding,\n    });\n\n    try {\n      const response = await client.sendAndWait(Hl7Message.parse(body));\n      console.log(response.toString().replaceAll('\\r', '\\n'));\n    } finally {\n      await client.close();\n    }\n  });\n\nconst listen = new MedplumCommand('listen')\n  .description('Starts an HL7 v2 MLLP server')\n  .argument('<port>')\n  .option('--encoding <encoding>', 'The encoding to use')\n  .action(async (port, options) => {\n    const server = new Hl7Server((connection) => {\n      connection.addEventListener('message', ({ message }) => {\n        console.log(message.toString().replaceAll('\\r', '\\n'));\n        connection.send(message.buildAck());\n      });\n    });\n\n    await server.start(Number.parseInt(port, 10), options.encoding);\n    console.log('Listening on port ' + port);\n  });\n\nexport const hl7 = new MedplumCommand('hl7');\naddSubcommand(hl7, send);\naddSubcommand(hl7, listen);\n\nexport function generateSampleHl7Message(): string {\n  const now = formatHl7DateTime(new Date());\n  const controlId = Date.now().toString();\n  return `MSH|^~\\\\&|ADTSYS|HOSPITAL|RECEIVER|DEST|${now}||ADT^A01|${controlId}|P|2.5|\nEVN|A01|${now}||\nPID|1|12345|12345^^^HOSP^MR|123456|DOE^JOHN^MIDDLE^SUFFIX|19800101|M|||123 STREET^APT 4B^CITY^ST^12345-6789||555-555-5555||S|\nPV1|1|I|2000^2012^01||||12345^DOCTOR^DOC||||||||||1234567^DOCTOR^DOC||AMB|||||||||||||||||||||||||202309280900|`;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Hl7CloseEvent, Hl7EnhancedAckSentEvent, Hl7ErrorEvent, Hl7MessageEvent, Hl7WarningEvent } from './events';\n\nexport interface Hl7EventMap {\n  message: Hl7MessageEvent;\n  error: Hl7ErrorEvent;\n  warning: Hl7WarningEvent;\n  close: Hl7CloseEvent;\n  enhancedAckSent: Hl7EnhancedAckSentEvent;\n}\n\nexport abstract class Hl7Base extends EventTarget {\n  addEventListener<K extends keyof Hl7EventMap>(\n    type: K,\n    listener: ((event: Hl7EventMap[K]) => void) | EventListenerObject | null,\n    options?: boolean | AddEventListenerOptions\n  ): void;\n\n  addEventListener(\n    type: string,\n    listener: EventListenerOrEventListenerObject | null,\n    options?: boolean | AddEventListenerOptions\n  ): void {\n    super.addEventListener(type, listener, options);\n  }\n  removeEventListener<K extends keyof Hl7EventMap>(\n    type: K,\n    listener: ((event: Hl7EventMap[K]) => void) | EventListenerObject | null,\n    options?: boolean | AddEventListenerOptions\n  ): void;\n\n  removeEventListener(\n    type: string,\n    listener: EventListenerOrEventListenerObject | null,\n    options?: boolean | AddEventListenerOptions\n  ): void {\n    super.removeEventListener(type, listener, options);\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Hl7Message } from '@medplum/core';\nimport assert from 'node:assert';\nimport type { Socket } from 'node:net';\nimport net from 'node:net';\nimport { Hl7Base } from './base';\nimport type { EnhancedMode, Hl7ConnectionOptions, SendAndWaitOptions } from './connection';\nimport { Hl7Connection } from './connection';\nimport { Hl7CloseEvent, Hl7ErrorEvent, Hl7WarningEvent } from './events';\n\nexport interface Hl7ClientOptions {\n  host: string;\n  port: number;\n  encoding?: string;\n  keepAlive?: boolean;\n  connectTimeout?: number; // Add timeout option\n}\n\nexport interface DeferredConnectionPromise {\n  promise: Promise<Hl7Connection>;\n  resolve: (connection: Hl7Connection) => void;\n  reject: (err: Error) => void;\n}\n\nexport class Hl7Client extends Hl7Base {\n  options: Hl7ClientOptions;\n  host: string;\n  port: number;\n  encoding?: string;\n  connection?: Hl7Connection;\n  keepAlive: boolean;\n  private socket?: Socket;\n  private connectTimeout: number;\n  private deferredConnectionPromise?: DeferredConnectionPromise;\n\n  constructor(options: Hl7ClientOptions) {\n    super();\n    this.options = options;\n    this.host = this.options.host;\n    this.port = this.options.port;\n    this.encoding = this.options.encoding;\n    this.keepAlive = this.options.keepAlive ?? false;\n    this.connectTimeout = this.options.connectTimeout ?? 30000; // Default 30 seconds\n  }\n\n  connect(): Promise<Hl7Connection> {\n    // If we are already waiting for a pending connection attempt, just return the deferred promise to that\n    // In the case that the promise is already resolve, we will also return a resolved connection\n    if (this.deferredConnectionPromise) {\n      return this.deferredConnectionPromise.promise;\n    }\n\n    const deferredPromise = (this.deferredConnectionPromise = this.createDeferredConnectionPromise());\n\n    // Create the socket\n    this.socket = net.connect({\n      host: this.host,\n      port: this.port,\n      keepAlive: this.keepAlive,\n    });\n\n    if (this.connectTimeout > 0) {\n      this.socket.setTimeout(this.connectTimeout);\n      this.registerSocketTimeoutListener(deferredPromise);\n    }\n\n    this.registerSocketConnectListener(deferredPromise);\n    this.registerSocketErrorListener(deferredPromise);\n    this.registerSocketCloseListener(deferredPromise);\n\n    return deferredPromise.promise;\n  }\n\n  private registerSocketTimeoutListener(deferredPromise: DeferredConnectionPromise): void {\n    assert(this.socket);\n    const socket = this.socket;\n\n    // Handle timeout event\n    const timeoutListener = (): void => {\n      this.cleanupSocket(socket);\n      const error = new Error(`Connection timeout after ${this.connectTimeout}ms`);\n      this.rejectDeferredPromise(deferredPromise, error);\n    };\n\n    socket.on('timeout', timeoutListener);\n  }\n\n  private registerSocketConnectListener(deferredPromise: DeferredConnectionPromise): void {\n    assert(this.socket);\n    const socket = this.socket;\n\n    // Handle successful connection\n    const connectListener = (): void => {\n      if (socket !== this.socket) {\n        this.cleanupSocket(socket);\n        return;\n      }\n\n      // Create the HL7 connection via the factory method (allows subclasses to customize)\n      let connection: Hl7Connection;\n      this.connection = connection = this.createConnection(socket, this.encoding);\n\n      // Remove the timeout listener as we're now connected\n      socket.setTimeout(0);\n\n      this.registerHl7ConnectionListeners(connection);\n\n      deferredPromise.resolve(connection);\n    };\n\n    socket.on('connect', connectListener);\n  }\n\n  private registerSocketErrorListener(deferredPromise: DeferredConnectionPromise): void {\n    assert(this.socket);\n    const socket = this.socket;\n\n    // Handle connection errors\n    const errorListener = (err: Error | AggregateError): void => {\n      this.cleanupSocket(socket);\n\n      if (err.constructor.name === 'AggregateError') {\n        this.rejectDeferredPromise(deferredPromise, (err as AggregateError).errors[0]);\n      } else {\n        this.rejectDeferredPromise(deferredPromise, err);\n      }\n    };\n\n    socket.on('error', errorListener);\n  }\n\n  private registerSocketCloseListener(deferredPromise: DeferredConnectionPromise): void {\n    assert(this.socket);\n    const socket = this.socket;\n\n    // Handle connection errors\n    const closeListener = (): void => {\n      this.cleanupSocket(socket);\n      this.rejectDeferredPromise(deferredPromise, new Error('Socket closed before connection finished'));\n    };\n    socket.on('close', closeListener);\n  }\n\n  private registerHl7ConnectionListeners(connection: Hl7Connection): void {\n    // Set up event handlers\n    connection.addEventListener('close', () => {\n      this.socket = undefined;\n      this.connection = undefined;\n      this.deferredConnectionPromise = undefined;\n      this.dispatchEvent(new Hl7CloseEvent());\n    });\n\n    connection.addEventListener('error', (event) => {\n      this.dispatchEvent(new Hl7ErrorEvent(event.error));\n    });\n\n    connection.addEventListener('warning', (event) => {\n      this.dispatchEvent(new Hl7WarningEvent(event.error));\n    });\n  }\n\n  private createDeferredConnectionPromise(): DeferredConnectionPromise {\n    // Setup our deferred connection promise\n    let resolve!: (connection: Hl7Connection) => void;\n    let reject!: (err: Error) => void;\n\n    const promise = new Promise<Hl7Connection>((_resolve, _reject) => {\n      resolve = _resolve;\n      reject = _reject;\n    });\n\n    return {\n      promise,\n      resolve,\n      reject,\n    };\n  }\n\n  private rejectDeferredPromise(deferredPromise: DeferredConnectionPromise, err: Error): void {\n    // Reject this deferred promise with the given error\n    deferredPromise.reject(err);\n\n    // If the currently tracked deferred promise is this deferred promise, remove it from the client\n    if (this.deferredConnectionPromise === deferredPromise) {\n      this.deferredConnectionPromise = undefined;\n    }\n  }\n\n  private cleanupSocket(socket: Socket): void {\n    if (!socket.destroyed) {\n      socket.destroy();\n    }\n    if (socket === this.socket) {\n      this.socket = undefined;\n    }\n  }\n\n  /**\n   * Creates an `Hl7Connection` for the given socket.\n   *\n   * Subclasses may override this to return a customized connection\n   * (e.g. one that delegates pending message tracking to a shared tracker).\n   * @param socket - The connected socket.\n   * @param encoding - The character encoding to use.\n   * @param enhancedMode - Optional enhanced mode for the connection.\n   * @param options - Optional connection options.\n   * @returns A new `Hl7Connection`.\n   */\n  protected createConnection(\n    socket: Socket,\n    encoding?: string,\n    enhancedMode?: EnhancedMode,\n    options?: Hl7ConnectionOptions\n  ): Hl7Connection {\n    return new Hl7Connection(socket, encoding, enhancedMode, options);\n  }\n\n  async send(msg: Hl7Message): Promise<void> {\n    return (await this.connect()).send(msg);\n  }\n\n  async sendAndWait(msg: Hl7Message, options?: SendAndWaitOptions): Promise<Hl7Message> {\n    return (await this.connect()).sendAndWait(msg, options);\n  }\n\n  async close(): Promise<void> {\n    if (this.deferredConnectionPromise) {\n      this.rejectDeferredPromise(this.deferredConnectionPromise, new Error('Client closed while connecting'));\n    }\n\n    // Close established connection if it exists\n    if (this.connection) {\n      const connection = this.connection;\n      delete this.connection;\n      await connection.close();\n    } else {\n      // Emit close event because the connection will not be able to emit it for us\n      // Since it has not connected at this point\n      this.dispatchEvent(new Hl7CloseEvent());\n    }\n    // Close the socket if it exists\n    if (this.socket) {\n      this.socket.removeAllListeners();\n      this.socket.destroy();\n      this.socket = undefined;\n    }\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Hl7Message, OperationOutcomeError, ReturnAckCategory, sleep, validationError } from '@medplum/core';\nimport iconv from 'iconv-lite';\nimport type net from 'node:net';\nimport { Hl7Base } from './base';\nimport { CR, FS, VT } from './constants';\nimport { Hl7CloseEvent, Hl7EnhancedAckSentEvent, Hl7ErrorEvent, Hl7MessageEvent, Hl7WarningEvent } from './events';\n\n// Export `ReturnAckCategory` for backwards-compat\nexport { ReturnAckCategory } from '@medplum/core';\n\n// iconv-lite docs have great examples and explanations for how to use Buffers with iconv-lite:\n// See: https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding\n\nexport type Hl7MessageQueueItem = {\n  message: Hl7Message;\n  resolve: (reply: Hl7Message) => void;\n  reject: (err: Error) => void;\n  returnAck: ReturnAckCategory;\n  timer?: NodeJS.Timeout;\n};\n\nexport interface SendAndWaitOptions {\n  /** The ACK-level that the Promise should resolve on. The default is `ReturnAckCategory.APPLICATION` (returns on the first application-level ACK). */\n  returnAck?: ReturnAckCategory;\n  /** The amount of milliseconds to wait before timing out when waiting for the response to a message. */\n  timeoutMs?: number;\n}\n\nexport interface Hl7ConnectionOptions {\n  messagesPerMin?: number;\n  gracefulCloseTimeoutMs?: number;\n}\n\n/**\n * Enhanced mode for HL7 connections.\n * - `'standard'`: Standard enhanced mode behavior\n * - `'aaMode'`: AA mode - special enhanced mode that only accepts AA acknowledgements\n * - `undefined`: Enhanced mode is not enabled (standard behavior)\n */\nexport type EnhancedMode = 'standard' | 'aaMode' | undefined;\n\nexport const DEFAULT_ENCODING = 'utf-8';\nexport const GRACEFUL_CLOSE_TIMEOUT_MS = 5000;\nconst ONE_MINUTE = 60 * 1000;\n\nexport class Hl7Connection extends Hl7Base {\n  readonly socket: net.Socket;\n  encoding: string;\n  enhancedMode: EnhancedMode = undefined;\n  private messagesPerMin: number | undefined = undefined;\n  private gracefulCloseTimeoutMs: number;\n  private chunks: Buffer[] = [];\n  private readonly pendingMessages: Map<string, Hl7MessageQueueItem> = new Map<string, Hl7MessageQueueItem>();\n  private readonly responseQueue: Hl7MessageEvent[] = [];\n  private lastMessageDispatchedTime = 0;\n  private responseQueueProcessing = false;\n  private closing = false;\n\n  constructor(\n    socket: net.Socket,\n    encoding: string = DEFAULT_ENCODING,\n    enhancedMode?: EnhancedMode,\n    options: Hl7ConnectionOptions = {}\n  ) {\n    super();\n\n    this.socket = socket;\n    this.encoding = encoding;\n    this.enhancedMode = enhancedMode;\n    this.messagesPerMin = options.messagesPerMin;\n    this.gracefulCloseTimeoutMs = options.gracefulCloseTimeoutMs ?? GRACEFUL_CLOSE_TIMEOUT_MS;\n\n    socket.on('data', (data: Buffer) => {\n      if (this.closing) {\n        this.dispatchEvent(\n          new Hl7WarningEvent(\n            new OperationOutcomeError({\n              resourceType: 'OperationOutcome',\n              issue: [\n                {\n                  severity: 'warning',\n                  code: 'transient',\n                  details: {\n                    text: 'Data received after close was initiated',\n                  },\n                },\n              ],\n            })\n          )\n        );\n        return;\n      }\n      try {\n        this.appendData(data);\n        const messages = this.parseMessages();\n        for (const message of messages) {\n          this.responseQueue.push(new Hl7MessageEvent(this, message));\n        }\n        this.processResponseQueue().catch((err) => {\n          this.dispatchEvent(new Hl7ErrorEvent(err));\n        });\n      } catch (err) {\n        this.dispatchEvent(new Hl7ErrorEvent(err as Error));\n      }\n    });\n\n    socket.on('error', (err) => {\n      this.resetBuffer();\n      this.dispatchEvent(new Hl7ErrorEvent(err));\n    });\n\n    // The difference between \"end\" and \"close\", is that \"end\" is only emitted on half-close from the other side\n    // If the connection from the other side does not close gracefully, but instead we destroy the socket, then the Hl7Connection will not emit close\n    // if we listen only for \"end\"; \"close\" is always emitted, whether the close is graceful or forceful\n    socket.on('close', () => {\n      // Reject any messages that were still pending when the connection was closed externally (e.g. closed by peer)\n      this.drainPendingMessages();\n      this.dispatchEvent(new Hl7CloseEvent());\n    });\n\n    this.addEventListener('message', (event) => {\n      // In standard enhanced mode, send commit ACK (CA) immediately, then later forward app-level ACKs\n      // In aaMode, send application ACK (AA) immediately, then ignore any later app-level ACKs\n      let response: Hl7Message | undefined;\n      if (this.enhancedMode === 'standard') {\n        response = event.message.buildAck({ ackCode: 'CA' });\n      } else if (this.enhancedMode === 'aaMode') {\n        response = event.message.buildAck({ ackCode: 'AA' });\n      }\n      if (response) {\n        this.send(response);\n        this.dispatchEvent(new Hl7EnhancedAckSentEvent(this, response));\n      }\n      const origMsgCtrlId = event.message.getSegment('MSA')?.getField(2)?.toString();\n      // If there is no message control ID, just return\n      if (!origMsgCtrlId) {\n        return;\n      }\n      const queueItem = this.getPendingMessage(origMsgCtrlId);\n      if (!queueItem) {\n        this.dispatchEvent(\n          new Hl7WarningEvent(\n            new OperationOutcomeError({\n              resourceType: 'OperationOutcome',\n              issue: [\n                {\n                  severity: 'warning',\n                  code: 'not-found',\n                  details: {\n                    text: 'Response received for unknown message control ID',\n                  },\n                  diagnostics: `Received ACK for message control ID '${origMsgCtrlId}' but there was no pending message with this control ID`,\n                },\n              ],\n            })\n          )\n        );\n        return;\n      }\n      // Check the ACK type we should return on\n      const ackCode = event.message.getSegment('MSA')?.getField(1)?.toString()?.toUpperCase();\n      if (!ackCode) {\n        return;\n      }\n\n      // Two modes:\n      // Application-level or first ACK\n\n      // First should always return on any ACK message, this is the default\n      // The exception is APPLICATION, which should not resolve when the ACK is a CA, but should resolve on all other ACK types\n      // On CA, we return early\n      if (queueItem.returnAck === ReturnAckCategory.APPLICATION && ackCode === 'CA') {\n        return;\n      }\n\n      // Resolve the promise if there is one pending for this message and we didn't exit already because the ACK type matches\n      if (queueItem.timer) {\n        clearTimeout(queueItem.timer);\n      }\n      queueItem.resolve(event.message);\n      this.deletePendingMessage(origMsgCtrlId);\n    });\n  }\n\n  /** @returns A boolean representing whether the socket attached to this Hl7Connection has emitted the close event already or not. */\n  isClosed(): boolean {\n    return this.socket.closed;\n  }\n\n  private sendImpl(reply: Hl7Message): void {\n    const replyString = reply.toString();\n    const replyBuffer = iconv.encode(replyString, this.encoding);\n    const outputBuffer = Buffer.alloc(replyBuffer.length + 3);\n    outputBuffer.writeInt8(VT, 0);\n    replyBuffer.copy(outputBuffer, 1);\n    outputBuffer.writeInt8(FS, replyBuffer.length + 1);\n    outputBuffer.writeInt8(CR, replyBuffer.length + 2);\n    this.socket.write(outputBuffer);\n  }\n\n  private async processResponseQueue(): Promise<void> {\n    if (this.responseQueueProcessing) {\n      return;\n    }\n\n    this.responseQueueProcessing = true;\n    while (this.responseQueue.length) {\n      if (this.messagesPerMin) {\n        const millisBetweenMsgs = ONE_MINUTE / this.messagesPerMin;\n        const elapsedMillis = Date.now() - this.lastMessageDispatchedTime;\n        if (millisBetweenMsgs > elapsedMillis) {\n          await sleep(millisBetweenMsgs - elapsedMillis);\n        }\n      }\n      const messageEvent = this.responseQueue.shift() as Hl7MessageEvent;\n      if (messageEvent) {\n        this.dispatchEvent(messageEvent);\n      }\n      this.lastMessageDispatchedTime = Date.now();\n    }\n    this.responseQueueProcessing = false;\n  }\n\n  /**\n   * Parses complete HL7 messages from the accumulated buffer.\n   * Continues parsing while the buffer starts with VT and contains FS+CR.\n   * Keeps any incomplete message data in the buffer for the next chunk.\n   * @returns An array of parsed HL7 messages.\n   */\n  private parseMessages(): Hl7Message[] {\n    const messages: Hl7Message[] = [];\n    const buffer = Buffer.concat(this.chunks);\n    this.resetBuffer();\n\n    // Check if buffer starts with VT (Vertical Tab)\n    if (buffer.length === 0) {\n      return messages;\n    }\n\n    let bufferIdx = 0;\n\n    // Keep parsing while we have complete messages\n    while (bufferIdx < buffer.length) {\n      // Ignore bytes between message frames\n      while (buffer[bufferIdx] !== VT && bufferIdx < buffer.length) {\n        bufferIdx++;\n      }\n\n      // Look for FS+CR sequence to mark end of message\n      let messageEndIndex = -1;\n\n      for (let i = bufferIdx + 1; i < buffer.length - 1; i++) {\n        if (buffer[i] === FS && buffer[i + 1] === CR) {\n          messageEndIndex = i + 1; // Index of CR (end of message)\n          break;\n        }\n      }\n\n      // If we don't have a complete message yet, wait for more data\n      if (messageEndIndex === -1) {\n        break;\n      }\n\n      // Extract the complete message (including VT, FS, and CR)\n      const messageBuffer = buffer.subarray(bufferIdx, messageEndIndex + 1);\n      // Extract the content (without VT at start and FS+CR at end)\n      const contentBuffer = messageBuffer.subarray(1, -2);\n      const contentString = iconv.decode(contentBuffer, this.encoding);\n      const message = Hl7Message.parse(contentString);\n\n      messages.push(message);\n\n      // Move past this message\n      bufferIdx = messageEndIndex + 1;\n    }\n\n    // Keep any remaining unfinished chunk in this.chunks\n    this.chunks = bufferIdx < buffer.length ? [buffer.subarray(bufferIdx)] : [];\n\n    return messages;\n  }\n\n  send(reply: Hl7Message): void {\n    this.sendImpl(reply);\n  }\n\n  async sendAndWait(msg: Hl7Message, options?: SendAndWaitOptions): Promise<Hl7Message> {\n    return new Promise<Hl7Message>((resolve, reject) => {\n      const msgCtrlId = msg.getSegment('MSH')?.getField(10)?.toString();\n      if (!msgCtrlId) {\n        reject(new OperationOutcomeError(validationError('Required field missing: MSH.10')));\n        return;\n      }\n\n      let timer: NodeJS.Timeout | undefined;\n\n      if (options?.timeoutMs) {\n        timer = setTimeout(() => {\n          this.deletePendingMessage(msgCtrlId);\n          reject(\n            new OperationOutcomeError({\n              resourceType: 'OperationOutcome',\n              issue: [\n                {\n                  severity: 'error',\n                  code: 'timeout',\n                  details: {\n                    text: 'Client timeout',\n                  },\n                  diagnostics: `Request timed out after waiting ${options.timeoutMs} milliseconds for response`,\n                },\n              ],\n            })\n          );\n        }, options.timeoutMs);\n      }\n\n      this.setPendingMessage(msgCtrlId, {\n        message: msg,\n        resolve,\n        reject,\n        returnAck: options?.returnAck ?? ReturnAckCategory.APPLICATION,\n        timer,\n      });\n      this.sendImpl(msg);\n    });\n  }\n\n  async close(): Promise<void> {\n    // If we have already received the close event, then we can just return immediately\n    if (this.isClosed()) {\n      return;\n    }\n    this.closing = true;\n    this.socket.end();\n    // drainPendingMessages is also called by the socket 'close' handler, but we call it here first so\n    // that rejections are delivered before the close event is dispatched when close() is called explicitly.\n    // The socket 'close' handler's call will be a no-op since the map will already be empty.\n    this.drainPendingMessages();\n    await new Promise<void>((resolve) => {\n      const timer = setTimeout(() => {\n        this.socket.destroy();\n      }, this.gracefulCloseTimeoutMs);\n\n      this.socket.once('close', () => {\n        clearTimeout(timer);\n        resolve();\n      });\n    });\n  }\n\n  /**\n   * Rejects all pending sendAndWait promises and clears the pending messages map.\n   * Safe to call multiple times \u2014 subsequent calls are no-ops once the map is empty.\n   *\n   * Subclasses may override this to change the behavior when a connection closes\n   * (e.g. to keep promises alive in an external tracker).\n   */\n  protected drainPendingMessages(): void {\n    if (!this.pendingMessages.size) {\n      return;\n    }\n    const pendingCount = this.pendingMessages.size;\n    for (const queueItem of this.pendingMessages.values()) {\n      if (queueItem.timer) {\n        clearTimeout(queueItem.timer);\n      }\n      queueItem.reject(\n        new OperationOutcomeError({\n          resourceType: 'OperationOutcome',\n          issue: [\n            {\n              severity: 'warning',\n              code: 'incomplete',\n              details: {\n                text: 'Message was still pending when connection closed',\n              },\n            },\n          ],\n        })\n      );\n    }\n    this.dispatchEvent(\n      new Hl7ErrorEvent(\n        new OperationOutcomeError({\n          resourceType: 'OperationOutcome',\n          issue: [\n            {\n              severity: 'warning',\n              code: 'incomplete',\n              details: {\n                text: 'Messages were still pending when connection closed',\n              },\n              diagnostics: `Hl7Connection closed while ${pendingCount} messages were pending`,\n            },\n          ],\n        })\n      )\n    );\n    this.pendingMessages.clear();\n  }\n\n  private appendData(data: Buffer): void {\n    this.chunks.push(data);\n  }\n\n  private resetBuffer(): void {\n    this.chunks = [];\n  }\n\n  setEncoding(encoding: string | undefined): void {\n    this.encoding = encoding ?? DEFAULT_ENCODING;\n  }\n\n  getEncoding(): string {\n    return this.encoding;\n  }\n\n  setEnhancedMode(enhancedMode: EnhancedMode): void {\n    this.enhancedMode = enhancedMode;\n  }\n\n  getEnhancedMode(): EnhancedMode {\n    return this.enhancedMode;\n  }\n\n  setMessagesPerMin(messagesPerMin: number | undefined): void {\n    this.messagesPerMin = messagesPerMin;\n  }\n\n  getMessagesPerMin(): number | undefined {\n    return this.messagesPerMin;\n  }\n\n  getPendingMessageCount(): number {\n    return this.pendingMessages.size;\n  }\n\n  /**\n   * Looks up a pending message by its message control ID.\n   * Subclasses may override this to use an external message store (e.g. a shared tracker).\n   * @param msgCtrlId - The message control ID (MSH.10) to look up.\n   * @returns The pending queue item, or undefined if not found.\n   */\n  protected getPendingMessage(msgCtrlId: string): Hl7MessageQueueItem | undefined {\n    return this.pendingMessages.get(msgCtrlId);\n  }\n\n  /**\n   * Stores a pending message by its message control ID.\n   * Subclasses may override this to use an external message store (e.g. a shared tracker).\n   * @param msgCtrlId - The message control ID (MSH.10).\n   * @param item - The queue item containing the message and its resolve/reject callbacks.\n   */\n  protected setPendingMessage(msgCtrlId: string, item: Hl7MessageQueueItem): void {\n    this.pendingMessages.set(msgCtrlId, item);\n  }\n\n  /**\n   * Removes a pending message by its message control ID.\n   * Subclasses may override this to use an external message store (e.g. a shared tracker).\n   * @param msgCtrlId - The message control ID (MSH.10) to remove.\n   */\n  protected deletePendingMessage(msgCtrlId: string): void {\n    this.pendingMessages.delete(msgCtrlId);\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * VT (Vertical Tab) character.\n *\n * In HL7 messages, this character is used to indicate the start of a message.\n */\nexport const VT = 0x0b;\n\n/**\n * CR (Carriage Return) character.\n *\n * In HL7 messages, this character is used to indicate the end of a message.\n */\nexport const CR = 0x0d;\n\n/**\n * FS (File Separator) character.\n *\n * In HL7 messages, this character is used to separate fields.\n */\nexport const FS = 0x1c;\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Hl7Message } from '@medplum/core';\nimport type { Hl7Connection } from './connection';\n\nexport class Hl7MessageEvent extends Event {\n  readonly connection: Hl7Connection;\n  readonly message: Hl7Message;\n\n  constructor(connection: Hl7Connection, message: Hl7Message) {\n    super('message');\n    this.connection = connection;\n    this.message = message;\n  }\n}\n\nexport class Hl7EnhancedAckSentEvent extends Event {\n  readonly connection: Hl7Connection;\n  readonly message: Hl7Message;\n\n  constructor(connection: Hl7Connection, message: Hl7Message) {\n    super('enhancedAckSent');\n    this.connection = connection;\n    this.message = message;\n  }\n}\n\nexport class Hl7ErrorEvent extends Event {\n  readonly error: Error;\n\n  constructor(error: Error) {\n    super('error');\n    this.error = error;\n  }\n}\n\nexport class Hl7WarningEvent extends Event {\n  readonly error: Error;\n\n  constructor(error: Error) {\n    super('warning');\n    this.error = error;\n  }\n}\n\nexport class Hl7CloseEvent extends Event {\n  constructor() {\n    super('close');\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { sleep } from '@medplum/core';\nimport net from 'node:net';\nimport type { EnhancedMode, Hl7ConnectionOptions } from './connection';\nimport { Hl7Connection } from './connection';\n\n/**\n * Options for configuring the `Hl7Server#stop` method.\n */\nexport interface Hl7ServerStopOptions {\n  /**\n   * Time in milliseconds to allow client connections to gracefully close after the stop method has been called, before forcefully closing them.\n   *\n   * Can be set to `-1` to disable forceful draining of connections during stop.\n   *\n   * Defaults to `10_000`.\n   */\n  forceDrainTimeoutMs?: number;\n}\n\nexport const DEFAULT_FORCE_DRAIN_TIMEOUT_MS = 10_000;\n\nexport class Hl7Server {\n  readonly handler: (connection: Hl7Connection) => void;\n  server?: net.Server;\n  private encoding: string | undefined = undefined;\n  private enhancedMode: EnhancedMode = undefined;\n  private messagesPerMin: number | undefined = undefined;\n  private readonly connections = new Set<Hl7Connection>();\n\n  constructor(handler: (connection: Hl7Connection) => void) {\n    this.handler = handler;\n  }\n\n  async start(\n    port: number,\n    encoding?: string,\n    enhancedMode?: EnhancedMode,\n    connectionOptions?: Hl7ConnectionOptions\n  ): Promise<number> {\n    if (encoding) {\n      this.setEncoding(encoding);\n    }\n    if (enhancedMode !== undefined) {\n      this.setEnhancedMode(enhancedMode);\n    }\n    if (connectionOptions?.messagesPerMin !== undefined) {\n      this.setMessagesPerMin(connectionOptions.messagesPerMin);\n    }\n\n    const server = net.createServer((socket) => {\n      const connection = new Hl7Connection(socket, this.encoding, this.enhancedMode, {\n        messagesPerMin: this.messagesPerMin,\n      });\n      this.handler(connection);\n      this.connections.add(connection);\n      connection.addEventListener('close', () => {\n        this.connections.delete(connection);\n      });\n    });\n\n    return new Promise<number>((resolve, reject) => {\n      const listenOnPort = (port: number): void => {\n        server.listen(port, () => {\n          const boundPort = (server.address() as { port: number }).port;\n          resolve(boundPort);\n        });\n      };\n\n      const errorListener = (e: Error & { code?: string }): void => {\n        if (e?.code === 'EADDRINUSE') {\n          server.close(() => sleep(50).then(() => listenOnPort(port)));\n        } else {\n          reject(e);\n        }\n      };\n\n      server.on('error', errorListener);\n\n      server.once('listening', () => {\n        server.off('error', errorListener);\n      });\n\n      listenOnPort(port);\n\n      this.server = server;\n    });\n  }\n\n  /**\n   * Stops the HL7 server.\n   *\n   * By default, the server will stop accepting new connections after this method is called, and wait for current connections to close naturally.\n   *\n   * If all connections don't close within 10 seconds, the server will forcefully close them before shutting down.\n   *\n   * The default time to wait before forcefully closing connections can be changed by passing an integer value for the optional `options.forceDrainTimeoutMs`.\n   *\n   * Forced drain can also be disabled by passing `-1` for `options.forceDrainTimeoutMs`.\n   * @param options - Optional options to configure the stopping of the server.\n   * @returns Promise that resolves when the server has stopped, or rejects if an error prevents server from stopping.\n   */\n  async stop(options?: Hl7ServerStopOptions): Promise<void> {\n    return new Promise<void>((resolve, reject) => {\n      if (!this.server) {\n        reject(new Error('Stop was called but there is no server running'));\n        return;\n      }\n      let forceDrainTimeout: NodeJS.Timeout | undefined;\n      if (options?.forceDrainTimeoutMs !== -1) {\n        forceDrainTimeout = setTimeout(() => {\n          for (const connection of this.connections) {\n            // Theoretically close should almost never throw as most errors are caught internal to the method and emitted as error events\n            // We put a .catch here to prevent floating promises and log any errors that somehow make it through\n            connection.close().catch(console.error);\n          }\n        }, options?.forceDrainTimeoutMs ?? DEFAULT_FORCE_DRAIN_TIMEOUT_MS);\n      }\n      this.server.close((err) => {\n        if (err) {\n          reject(err);\n          return;\n        }\n        if (forceDrainTimeout) {\n          clearTimeout(forceDrainTimeout);\n        }\n        this.connections.clear();\n        this.server = undefined;\n        resolve();\n      });\n    });\n  }\n\n  setEnhancedMode(enhancedMode: EnhancedMode): void {\n    this.enhancedMode = enhancedMode;\n  }\n\n  getEnhancedMode(): EnhancedMode {\n    return this.enhancedMode;\n  }\n\n  setEncoding(encoding: string | undefined): void {\n    this.encoding = encoding;\n  }\n\n  getEncoding(): string | undefined {\n    return this.encoding;\n  }\n\n  setMessagesPerMin(messagesPerMin: number | undefined): void {\n    this.messagesPerMin = messagesPerMin;\n  }\n\n  getMessagesPerMin(): number | undefined {\n    return this.messagesPerMin;\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { readdirSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { resolve } from 'node:path';\nimport { FileSystemStorage } from './storage';\nimport { MedplumCommand, addSubcommand, loadProfile, saveProfile } from './utils';\n\nconst setProfile = new MedplumCommand('set');\nconst removeProfile = new MedplumCommand('remove');\nconst listProfiles = new MedplumCommand('list');\nconst describeProfile = new MedplumCommand('describe');\n\nexport const profile = new MedplumCommand('profile');\naddSubcommand(profile, setProfile);\naddSubcommand(profile, removeProfile);\naddSubcommand(profile, listProfiles);\naddSubcommand(profile, describeProfile);\n\nsetProfile\n  .argument('<profileName>', 'Name of the profile')\n  .description('Create a new profile or replace it with the given name and its associated properties')\n  .action(async (profileName, options) => {\n    saveProfile(profileName, options);\n  });\n\nremoveProfile\n  .argument('<profileName>', 'Name of the profile')\n  .description('Remove a profile by name')\n  .action(async (profileName) => {\n    const storage = new FileSystemStorage(profileName);\n    storage.setObject('options', undefined);\n    console.log(`${profileName} profile removed`);\n  });\n\nlistProfiles.description('List all profiles saved').action(async () => {\n  const dir = resolve(homedir(), '.medplum');\n  const files = readdirSync(dir);\n  const allProfiles: any[] = [];\n  files.forEach((file) => {\n    const fileName = file.split('.')[0];\n    const storage = new FileSystemStorage(fileName);\n    const profile = storage.getObject('options');\n    if (profile) {\n      allProfiles.push({ profileName: fileName, profile });\n    }\n  });\n  console.log(allProfiles);\n});\n\ndescribeProfile\n  .argument('<profileName>', 'Name of the profile')\n  .description('Describes a profile')\n  .action(async (profileName) => {\n    const profile = loadProfile(profileName);\n    console.log(profile);\n  });\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { InviteRequest, LoginState, MedplumClient } from '@medplum/core';\nimport { Option } from 'commander';\nimport { createMedplumClient } from './util/client';\nimport { addSubcommand, MedplumCommand } from './utils';\n\nconst projectListCommand = new MedplumCommand('list');\nconst projectCurrentCommand = new MedplumCommand('current');\nconst projectSwitchCommand = new MedplumCommand('switch');\nconst projectInviteCommand = new MedplumCommand('invite');\n\nexport const project = new MedplumCommand('project');\naddSubcommand(project, projectListCommand);\naddSubcommand(project, projectCurrentCommand);\naddSubcommand(project, projectSwitchCommand);\naddSubcommand(project, projectInviteCommand);\n\nprojectListCommand.description('List of current projects').action(async (options) => {\n  const medplum = await createMedplumClient(options);\n  projectList(medplum);\n});\n\nfunction projectList(medplum: MedplumClient): void {\n  const logins = medplum.getLogins();\n\n  const projects = logins\n    .map((login: LoginState) => `${login.project.display} (${login.project.reference})`)\n    .join('\\n\\n');\n\n  console.log(projects);\n}\n\nprojectCurrentCommand.description('Project you are currently on').action(async (options) => {\n  const medplum = await createMedplumClient(options);\n  const login = medplum.getActiveLogin();\n  if (!login) {\n    throw new Error('Unauthenticated: run `npx medplum login` to login');\n  }\n  console.log(`${login.project.display} (${login.project.reference})`);\n});\n\nprojectSwitchCommand\n  .description('Switching to another project from the current one')\n  .argument('<projectId>')\n  .action(async (projectId, options) => {\n    const medplum = await createMedplumClient(options);\n    await switchProject(medplum, projectId);\n  });\n\nprojectInviteCommand\n  .description('Invite a member to your current project (run npx medplum project current to confirm)')\n  .arguments('<firstName> <lastName> <email>')\n  .option('--send-email', 'If you want to send the email when inviting the user')\n  .option('--admin', 'If the user you are inviting is an admin')\n  .addOption(\n    new Option('-r, --role <role>', 'Role of user')\n      .choices(['Practitioner', 'Patient', 'RelatedPerson'])\n      .default('Practitioner')\n  )\n  .action(async (firstName, lastName, email, options) => {\n    const medplum = await createMedplumClient(options);\n    const login = medplum.getActiveLogin();\n    if (!login) {\n      throw new Error('Unauthenticated: run `npx medplum login` to login');\n    }\n    if (!login?.project?.reference) {\n      throw new Error('No current project to invite user to');\n    }\n\n    const projectId = login.project.reference.split('/')[1];\n    const inviteBody: InviteRequest = {\n      resourceType: options.role,\n      firstName,\n      lastName,\n      email,\n      sendEmail: !!options.sendEmail,\n      admin: !!options.admin,\n    };\n    await inviteUser(projectId, inviteBody, medplum);\n  });\n\nasync function switchProject(medplum: MedplumClient, projectId: string): Promise<void> {\n  const logins = medplum.getLogins();\n  const login = logins.find((login: LoginState) => login.project.reference?.includes(projectId));\n  if (!login) {\n    throw new Error(`Project ${projectId} not found. Make sure you are added as a user to this project`);\n  }\n  await medplum.setActiveLogin(login);\n  console.log(`Switched to project ${projectId}\\n`);\n}\n\nasync function inviteUser(projectId: string, inviteBody: InviteRequest, medplum: MedplumClient): Promise<void> {\n  await medplum.invite(projectId, inviteBody);\n  if (inviteBody.sendEmail) {\n    console.log('Email sent');\n  }\n  console.log('See your users at https://app.medplum.com/admin/users');\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient } from '@medplum/core';\nimport { convertToTransactionBundle } from '@medplum/core';\nimport { createMedplumClient } from './util/client';\nimport { MedplumCommand, prettyPrint } from './utils';\n\nexport const deleteObject = new MedplumCommand('delete');\nexport const get = new MedplumCommand('get');\nexport const patch = new MedplumCommand('patch');\nexport const post = new MedplumCommand('post');\nexport const put = new MedplumCommand('put');\n\ndeleteObject.argument('<url>', 'Resource/$id').action(async (url, options) => {\n  const medplum = await createMedplumClient(options);\n  prettyPrint(await medplum.delete(cleanUrl(medplum, url)));\n});\n\nget\n  .argument('<url>', 'Resource/$id')\n  .option('--as-transaction', 'Print out the bundle as a transaction type')\n  .action(async (url, options) => {\n    const medplum = await createMedplumClient(options);\n    const response = await medplum.get(cleanUrl(medplum, url));\n    if (options.asTransaction) {\n      prettyPrint(convertToTransactionBundle(response));\n    } else {\n      prettyPrint(response);\n    }\n  });\n\npatch.arguments('<url> <body>').action(async (url, body, options) => {\n  const medplum = await createMedplumClient(options);\n\n  prettyPrint(await medplum.patch(cleanUrl(medplum, url), parseBody(body)));\n});\n\npost\n  .arguments('<url> <body>')\n  .option('--prefer-async', 'Sets the Prefer header to \"respond-async\"')\n  .action(async (url, body, options) => {\n    const medplum = await createMedplumClient(options);\n\n    const headers = options.preferAsync ? { Prefer: 'respond-async' } : undefined;\n    prettyPrint(await medplum.post(cleanUrl(medplum, url), parseBody(body), undefined, { headers }));\n  });\n\nput.arguments('<url> <body>').action(async (url, body, options) => {\n  const medplum = await createMedplumClient(options);\n\n  prettyPrint(await medplum.put(cleanUrl(medplum, url), parseBody(body)));\n});\n\nfunction parseBody(input: string | undefined): any {\n  if (!input) {\n    return undefined;\n  }\n  try {\n    return JSON.parse(input);\n  } catch (_err) {\n    return input;\n  }\n}\n\nexport function cleanUrl(medplum: MedplumClient, input: string): string {\n  const knownPrefixes = ['admin/', 'auth/', 'fhir/R4'];\n  if (knownPrefixes.some((p) => input.startsWith(p))) {\n    // If the URL starts with a known prefix, return it as-is\n    return input;\n  }\n\n  // Otherwise, default to FHIR\n  return medplum.fhirUrl(input).toString();\n}\n"],
  "mappings": ";ue8CEA,IAAAA,GAAsD,yBACtDC,GAAuC,qBACvCC,GAAmB,uBCOnBF,GAAuE,yBAEvEC,GAAuB,qBCVvBD,GAA8B,yBCD9BA,GAA8B,yBAC9BG,GAAmE,mBACnEC,GAAwB,mBACxBC,GAAwB,qBCFxBL,GAAiE,yBAEjEC,GAAwB,qBCLxBK,GAAuB,uBGAvBC,GAAsB,0BCAtBC,GAAwB,4BACxBC,GAAsB,0BMDtBC,GAA0B,uBEA1BA,GAA0B,uBIA1BA,GAAqC,uBCArCC,GAAwB,4BACxBC,GAA0B,qBED1BF,GAA2C,uBpBO3CA,GAA0D,uBAC1DP,GAAwD,mBACxDE,GAA2C,qBAC3CQ,GAA0B,2BAC1BC,GAAwB,e2BRxBd,EAA2F,yBAC3Fe,GAAqB,8BACrBC,GAA6B,qBAC7BZ,GAAyB,mBEHzBa,GAKO,0CACPC,GAA4D,sCAC5DC,GAA0B,+BAC1BC,GAAyB,8BACzBC,GAAoE,+BACpEC,GAAoD,+BACpDtB,GAA4C,yBAC5CG,GAA4B,mBCb5BoB,GAAqB,8BECrBC,GAA8E,+BAC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pnB,EAAK,CAAC,CAAC,QAAQ,IAAI,OAAO,EAC7C,IAAMqnB,EAAQrnB,EAAI,MAClB,GAAI,QAAQ,IAAI,QACd,GAAI,MAAM,QAAQqnB,CAAK,EACrB,QAAWrnB,KAAOqnB,EAChBD,GAAmBpnB,EAAK,EAAI,OAErBqnB,aAAiB,OAC1BD,GAAmBC,EAAO,EAAI,CAGpC,CACA,QAAQ,KAAKJ,CAAQ,CACvB,CAEA,SAASG,GAAmBpnB,EAAcsnB,EAAU,GAAa,CAC/D,GAAIA,EAAS,CACX,QAAQ,MAAMtnB,CAAG,EACjB,MACF,CACIA,aAAemnB,GAAAA,eACjB,QAAQ,OAAO,MAAM,MAAGnZ,GAAAA,sBAAqBhO,CAAG,CAAC;CAAI,EAErD,QAAQ,OAAO,MAAM,aAAUgO,GAAAA,sBAAqBhO,CAAG,CAAC;CAAI,CAEhE,CAEA,eAAsBunB,IAAqB,CACzCC,GAAAA,QAAO,OAAO,CAAE,MAAO,EAAK,CAAC,EAC7B,MAAMX,GAAK,QAAQ,IAAI,CACzB,CAGEU,GAAI,EAAE,MAAOvnB,GAAQ,CACnB,QAAQ,MAAM,sBAAoBgO,GAAAA,sBAAqBhO,CAAG,CAAC,EAC3D,QAAQ,KAAK,CAAC,CAChB,CAAC",
  "names": ["import_core", "import_commander", "import_dotenv", "import_node_fs", "import_node_os", "import_node_path", "import_node_buffer", "vr", "Cr", "Tr", "import_node_crypto", "Ne", "import_node_util", "import_types", "import_tar", "import_node_child_process", "import_node_http", "import_client_cloudformation", "import_client_cloudfront", "import_client_ecs", "import_client_s3", "import_client_ssm", "import_client_sts", "import_node_readline", "import_client_acm", "import_fast_glob", "import_node_stream", "import_promises", "import_node_assert", "import_node_net", "import_iconv_lite", "require_constants", "__commonJSMin", "exports", "module", "SEMVER_SPEC_VERSION", "MAX_SAFE_INTEGER", "MAX_SAFE_COMPONENT_LENGTH", "MAX_SAFE_BUILD_LENGTH", "RELEASE_TYPES", "require_debug", "debug", "args", "require_re", "MAX_LENGTH", "oe", "Se", "re", "safeRe", "src", "safeSrc", "t", "R", "LETTERDASHNUMBER", "safeRegexReplacements", "makeSafeRegex", "value", "token", "max", "createToken", "name", "isGlobal", "safe", "index", "require_parse_options", "looseOption", "emptyOpts", "parseOptions", "options", "require_identifiers", "numeric", "compareIdentifiers", "a", "b", "anum", "bnum", "rcompareIdentifiers", "require_semver", "ie", "We", "Ft", "isPrereleaseIdentifier", "prerelease", "identifier", "identifiers", "i", "SemVer", "_SemVer", "version", "m", "id", "num", "other", "release", "identifierBase", "match", "base", "prereleaseBase", "require_parse", "O", "parse", "throwErrors", "er", "require_valid", "X", "valid", "v", "require_clean", "clean", "s", "require_inc", "inc", "require_diff", "diff", "version1", "version2", "v1", "v2", "comparison", "v1Higher", "highVersion", "lowVersion", "highHasPre", "prefix", "require_major", "major", "loose", "require_minor", "minor", "require_patch", "patch", "require_prerelease", "parsed", "require_compare", "compare", "require_rcompare", "L", "rcompare", "require_compare_loose", "compareLoose", "require_compare_build", "compareBuild", "versionA", "versionB", "require_sort", "Ve", "sort", "list", "require_rsort", "rsort", "require_gt", "gt", "require_lt", "lt", "require_eq", "eq", "require_neq", "neq", "require_gte", "gte", "require_lte", "lte", "require_cmp", "Kt", "qt", "Re", "Xe", "Je", "ze", "cmp", "op", "require_coerce", "coerce", "coerceRtlRegex", "next", "build", "require_truncate", "constants", "truncate", "truncation", "clonedVersion", "cloneInputVersion", "doTruncation", "versionStringToParse", "isPrerelease", "type", "require_lrucache", "LRUCache", "key", "firstKey", "require_range", "SPACE_CHARACTERS", "Range", "_Range", "range", "Comparator", "r", "c", "first", "isNullSet", "isAny", "comps", "k", "BUILDSTRIPRE", "memoKey", "FLAG_INCLUDE_PRERELEASE", "FLAG_LOOSE", "cached", "cache", "hr", "hyphenReplace", "comparatorTrimReplace", "tildeTrimReplace", "caretTrimReplace", "rangeList", "comp", "parseComparator", "replaceGTE0", "rangeMap", "comparators", "result", "thisComparators", "isSatisfiable", "rangeComparators", "thisComparator", "rangeComparator", "testSet", "LRU", "ys", "Ae", "remainingComparators", "testComparator", "otherComparator", "replaceCarets", "replaceTildes", "replaceXRanges", "replaceStars", "isX", "invalidXRangeOrder", "M", "p", "replaceTilde", "z", "_", "pr", "ret", "replaceCaret", "replaceXRange", "gtlt", "xM", "xm", "xp", "anyX", "incPr", "$0", "from", "fM", "fm", "fp", "fpr", "fb", "to", "tM", "tm", "tp", "tpr", "set", "allowed", "require_comparator", "ANY", "_Comparator", "Ht", "require_satisfies", "satisfies", "require_to_comparators", "toComparators", "require_max_satisfying", "maxSatisfying", "versions", "maxSV", "rangeObj", "require_min_satisfying", "minSatisfying", "min", "minSV", "require_min_version", "minVersion", "minver", "setMin", "comparator", "compver", "validRange", "require_outside", "Pe", "outside", "hilo", "gtfn", "ltefn", "ltfn", "ecomp", "high", "low", "require_gtr", "Ze", "gtr", "require_ltr", "ltr", "require_intersects", "intersects", "r1", "r2", "require_simplify", "prev", "ranges", "simplified", "original", "require_subset", "subset", "sub", "dom", "sawNonNull", "OUTER", "simpleSub", "simpleDom", "isSub", "simpleSubset", "minimumVersionWithPreRelease", "minimumVersion", "eqSet", "higherGT", "lowerLT", "gtltComp", "higher", "lower", "hasDomLT", "hasDomGT", "needDomLTPre", "needDomGTPre", "internalRe", "xn", "Nn", "Mn", "Un", "Fn", "Wn", "qn", "Gn", "zn", "Qn", "rs", "ss", "ms", "hs", "xs", "Ns", "Ls", "_s", "js", "Hs", "Vs", "zs", "simplifyRange", "Qs", "so", "FileSystemStorage", "ClientStorage", "profile", "__publicField", "resolve", "homedir", "data", "str", "existsSync", "readFileSync", "mkdirSync", "writeFileSync", "createMedplumClient", "setupCredentials", "profileName", "storage", "baseUrl", "fhirUrlPath", "accessToken", "tokenUrl", "authorizeUrl", "clientId", "clientSecret", "getClientValues", "fetchApi", "validateBaseUrl", "medplumClient", "MedplumClient", "onUnauthenticated", "storageOptions", "url", "response", "err", "message", "encoder", "decoder", "MAX_INT32", "concat", "buffers", "size", "acc", "length", "buf", "buffer", "encode", "input", "Buffer", "JOSEError", "JOSENotSupported", "JWSInvalid", "JWTInvalid", "_a", "_b", "JWKSMultipleMatchingKeys", "is_key_object_default", "obj", "webcrypto", "webcrypto_default", "isCryptoKey", "unusable", "prop", "isAlgorithm", "algorithm", "getHashLength", "hash", "getNamedCurve", "alg", "checkUsage", "usages", "expected", "msg", "last", "checkSigCryptoKey", "actual", "types", "invalid_key_input_default", "withAlg", "is_key_like_default", "isDisjoint", "headers", "sources", "header", "parameters", "parameter", "is_disjoint_default", "isObjectLike", "isObject", "proto", "isJWK", "isPrivateJWK", "isPublicJWK", "isSecretJWK", "namedCurveToJOSE", "namedCurve", "kee", "raw", "KeyObject", "get_named_curve_default", "check_key_length_default", "modulusLength", "tag", "jwkMatchesOp", "usage", "symmetricTypeCheck", "allowJwk", "asymmetricTypeCheck", "checkKeyType", "check_key_type_default", "checkKeyTypeWithJwk", "validateCrit", "Err", "recognizedDefault", "recognizedOption", "protectedHeader", "joseHeader", "recognized", "validate_crit_default", "dsaDigest", "ecCurveAlgMap", "keyForCrypto", "asymmetricKeyType", "asymmetricKeyDetails", "hashAlgorithm", "mgf1HashAlgorithm", "saltLength", "hmacDigest", "getSignVerifyKey", "createSecretKey", "oneShotSign", "promisify", "sign", "hmac", "sign_default", "epoch_default", "date", "REGEX", "secs_default", "matched", "unit", "numericDate", "FlattenedSign", "payload", "unprotectedHeader", "extensions", "b64", "signature", "jws", "CompactSign", "validateInput", "label", "ProduceJWT", "issuer", "subject", "audience", "jwtId", "SignJWT", "sig", "prettyPrint", "saveBot", "medplum", "botConfig", "bot", "codePath", "code", "readFileContents", "sourceCode", "basename", "getCodeContentType", "updateResult", "deployBot", "deployResult", "createBot", "botName", "projectId", "sourceFile", "distFile", "runtimeVersion", "writeConfig", "body", "newBot", "addBotToConfig", "readBotConfigs", "regExBotName", "escapeRegex", "readConfig", "getConfigFileName", "tagName", "parts", "configFileName", "config", "fileName", "content", "readServerConfig", "path", "safeTarExtractor", "destinationDir", "fileCount", "totalSize", "extract", "_path", "entry", "getUnsupportedExtension", "filename", "ext", "extname", "ContentType", "saveProfile", "optionsObject", "loadProfile", "jwtBearerLogin", "OAuthSigningAlgorithm", "currentTimestamp", "encodedHeader", "encodeBase64", "encodedData", "createHmac", "signedToken", "jwtAssertionLogin", "privateKey", "createPrivateKey", "jwt", "randomBytes", "addSubcommand", "command", "subcommand", "MedplumCommand", "Command", "fn", "wrappedFn", "withMergedOptions", "option", "expectedArgsCount", "actionArgs", "isPromise", "agentStatusCommand", "agentPingCommand", "agentPushCommand", "agentReloadConfigCommand", "agentUpgradeCommand", "agentStatsCommand", "agent", "Option", "agentIds", "callAgentBulkOperation", "statusEntry", "parseParameterValues", "ipOrDomain", "agentId", "agentRef", "resolveAgentReference", "count", "pingResult", "deviceId", "pushResult", "params", "stats", "normalizeErrorString", "rows", "renderAgentStats", "SUMMARY_STAT_KEYS", "formatStatValue", "buildChannelStatsRows", "entries", "row", "heading", "summary", "knownKeys", "channelRows", "clientRows", "operation", "parseSuccessfulResponse", "renderSuccessfulRows", "normalized", "parseEitherIdsOrCriteria", "usedCriteria", "searchParams", "paramName", "paramVal", "successfulResponses", "failedResponses", "responses", "parseAgentBulkOpBundle", "isOk", "successfulRows", "failedRows", "issue", "usedId", "assertValidAgentCriteria", "bundle", "EMPTY", "parseAgentBulkOpParameters", "paramNames", "map", "requiredParams", "optionalParams", "paramsParam", "valueProp", "extractValueFromParametersParameter", "isUUID", "criteria", "invalidCriteriaMsg", "resourceType", "queryStr", "MEDPLUM_CLI_CLIENT_ID", "redirectUri", "login", "whoami", "startLogin", "printMe", "medplumAuthorizationCodeLogin", "startWebServer", "server", "createServer", "req", "res", "getDisplayString", "openBrowser", "os", "platform", "cmd", "reject", "exec", "error", "stderr", "loginState", "loginUrl", "RESET", "BOLD", "RED", "GREEN", "YELLOW", "BLUE", "color", "text", "processDescription", "desc", "semver", "Sr", "sr", "terminal", "initTerminal", "readline", "closeTerminal", "print", "ask", "defaultValue", "answer", "choose", "o", "chooseInt", "yesOrNo", "checkOk", "cloudFormationClient", "CloudFormationClient", "cloudFrontClient", "CloudFrontClient", "ecsClient", "ECSClient", "s3Client", "S3Client", "tagKey", "getAllStacks", "listResult", "paginator", "paginateListStacks", "page", "stack", "getStackByTag", "stackSummaries", "stackSummary", "stackName", "details", "getStackDetails", "buildStackDetails", "client", "describeStacksCommand", "DescribeStacksCommand", "medplumTag", "stackResources", "DescribeStackResourcesCommand", "resource", "assignStackDetails", "printStackDetails", "getEcsServiceName", "createInvalidation", "distributionId", "CreateInvalidationCommand", "getServerVersions", "uo", "writeParameters", "region", "SSMClient", "valueStr", "existingValue", "readParameter", "writeParameter", "GetParameterCommand", "PutParameterCommand", "printConfigNotFound", "files", "readdirSync", "f", "file", "printStackNotFound", "STSClient", "GetCallerIdentityCommand", "getDomainSetting", "domain", "getDomainCertSetting", "initStackCommand", "currentAccountId", "getAccountId", "defaultStackName", "supportEmail", "latestVersion", "signingKey", "generateSigningKey", "allCerts", "listAllCertificates", "certName", "arn", "processCert", "serverParams", "serverConfigFileName", "listCertificates", "usEast1Result", "ACMClient", "ListCertificatesCommand", "domainName", "existingCert", "cert", "requestCert", "validationMethod", "RequestCertificateCommand", "keyName", "passphrase", "randomUUID", "generateKeyPairSync", "CreatePublicKeyCommand", "listStacksCommand", "updateAppCommand", "appBucket", "tmpDir", "downloadNpmPackage", "replaceVariables", "uploadAppToS3", "getNpmPackageMetadata", "packageName", "tarballUrl", "mkdtempSync", "join", "tmpdir", "extractor", "pipeline", "Readable", "rmSync", "folderName", "replacements", "item", "itemPath", "replaceVariablesInFile", "contents", "placeholder", "replacement", "bucketName", "uploadPatterns", "uploadPattern", "uploadFolderToS3", "items", "fastGlob", "uploadFileToS3", "filePath", "fileStream", "createReadStream", "s3Key", "sep", "putObjectParams", "PutObjectCommand", "updateBucketPoliciesCommand", "updateBucketPolicy", "friendlyName", "bucketResource", "distributionResource", "oaiResource", "oaiId", "bucketPolicy", "getPolicy", "policyHasAllowStatement", "addAllowPolicyStatement", "addGuardDutyReadPolicyStatement", "setPolicy", "policyResponse", "GetBucketPolicyCommand", "policy", "PutBucketPolicyCommand", "statementHasAction", "statement", "action", "updateConfigCommand", "infraConfig", "serverConfig", "checkConfigConflicts", "mergeConfigs", "checkConflict", "isConflict", "updateServerCommand", "separatorIndex", "serverImagePrefix", "initialVersion", "getCurrentVersion", "updateVersion", "nextUpdateVersion", "ue", "deployServerUpdate", "currentVersion", "targetVersion", "allVersions", "configFile", "deploy", "spawnSync", "buildAwsCommand", "aws", "botSaveCommand", "botDeployCommand", "botCreateCommand", "saveBotDeprecate", "deployBotDeprecate", "createBotDeprecate", "botWrapper", "botConfigs", "errors", "errored", "saved", "deployed", "bulkExportCommand", "bulkImportCommand", "bulk", "exportLevel", "since", "targetDirectory", "fileUrl", "nodeStream", "createWriteStream", "numResourcesPerRequest", "addExtensionsForMissingValues", "importFile", "rl", "createInterface", "line", "parseResource", "sendBatchEntries", "resultEntry", "jsonString", "addExtensionsForMissingValuesResource", "addExtensionsForMissingValuesExplanationOfBenefits", "Jp", "Xp", "Hl7Base", "listener", "Hl7MessageEvent", "connection", "Hl7EnhancedAckSentEvent", "Hl7ErrorEvent", "Hl7WarningEvent", "Hl7CloseEvent", "DEFAULT_ENCODING", "GRACEFUL_CLOSE_TIMEOUT_MS", "ONE_MINUTE", "Hl7Connection", "socket", "encoding", "enhancedMode", "OperationOutcomeError", "messages", "event", "origMsgCtrlId", "queueItem", "ackCode", "ReturnAckCategory", "reply", "replyString", "replyBuffer", "iconv", "outputBuffer", "millisBetweenMsgs", "elapsedMillis", "sleep", "messageEvent", "bufferIdx", "messageEndIndex", "contentBuffer", "contentString", "Hl7Message", "msgCtrlId", "validationError", "timer", "pendingCount", "messagesPerMin", "Hl7Client", "deferredPromise", "net", "assert", "timeoutListener", "connectListener", "errorListener", "closeListener", "_resolve", "_reject", "DEFAULT_FORCE_DRAIN_TIMEOUT_MS", "Hl7Server", "handler", "port", "connectionOptions", "listenOnPort", "boundPort", "e", "forceDrainTimeout", "send", "host", "generateSampleHl7Message", "A", "listen", "x", "hl7", "now", "formatHl7DateTime", "controlId", "setProfile", "removeProfile", "listProfiles", "describeProfile", "dir", "allProfiles", "projectListCommand", "projectCurrentCommand", "projectSwitchCommand", "projectInviteCommand", "project", "projectList", "projects", "switchProject", "firstName", "lastName", "email", "inviteBody", "inviteUser", "deleteObject", "get", "post", "put", "cleanUrl", "convertToTransactionBundle", "parseBody", "main", "argv", "MEDPLUM_VERSION", "handleError", "exitCode", "shouldPrint", "CommanderError", "writeErrorToStderr", "cause", "verbose", "run", "dotenv"]
}
