@atomic-ehr/codegen 0.0.1-canary.20251006070905.fb6ed98 → 0.0.1-canary.20251006094042.7f0be72

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/cli/index.js +45 -124
  2. package/dist/index.d.ts +2130 -62
  3. package/dist/index.js +5865 -84
  4. package/dist/index.js.map +1 -0
  5. package/package.json +3 -7
  6. package/dist/api/builder.d.ts +0 -154
  7. package/dist/api/builder.js +0 -341
  8. package/dist/api/generators/base/BaseGenerator.d.ts +0 -186
  9. package/dist/api/generators/base/BaseGenerator.js +0 -565
  10. package/dist/api/generators/base/FileManager.d.ts +0 -88
  11. package/dist/api/generators/base/FileManager.js +0 -202
  12. package/dist/api/generators/base/PythonTypeMapper.d.ts +0 -16
  13. package/dist/api/generators/base/PythonTypeMapper.js +0 -71
  14. package/dist/api/generators/base/TemplateEngine.d.ts +0 -126
  15. package/dist/api/generators/base/TemplateEngine.js +0 -133
  16. package/dist/api/generators/base/TypeMapper.d.ts +0 -129
  17. package/dist/api/generators/base/TypeMapper.js +0 -153
  18. package/dist/api/generators/base/TypeScriptTypeMapper.d.ts +0 -51
  19. package/dist/api/generators/base/TypeScriptTypeMapper.js +0 -232
  20. package/dist/api/generators/base/builders/DirectoryBuilder.d.ts +0 -99
  21. package/dist/api/generators/base/builders/DirectoryBuilder.js +0 -215
  22. package/dist/api/generators/base/builders/FileBuilder.d.ts +0 -160
  23. package/dist/api/generators/base/builders/FileBuilder.js +0 -406
  24. package/dist/api/generators/base/builders/IndexBuilder.d.ts +0 -126
  25. package/dist/api/generators/base/builders/IndexBuilder.js +0 -290
  26. package/dist/api/generators/base/enhanced-errors.d.ts +0 -84
  27. package/dist/api/generators/base/enhanced-errors.js +0 -259
  28. package/dist/api/generators/base/error-handler.d.ts +0 -89
  29. package/dist/api/generators/base/error-handler.js +0 -243
  30. package/dist/api/generators/base/errors.d.ts +0 -251
  31. package/dist/api/generators/base/errors.js +0 -692
  32. package/dist/api/generators/base/index.d.ts +0 -99
  33. package/dist/api/generators/base/index.js +0 -160
  34. package/dist/api/generators/base/types.d.ts +0 -433
  35. package/dist/api/generators/base/types.js +0 -12
  36. package/dist/api/generators/types.d.ts +0 -53
  37. package/dist/api/generators/types.js +0 -4
  38. package/dist/api/generators/typescript.d.ts +0 -190
  39. package/dist/api/generators/typescript.js +0 -819
  40. package/dist/api/index.d.ts +0 -51
  41. package/dist/api/index.js +0 -50
  42. package/dist/cli/commands/generate/typescript.d.ts +0 -10
  43. package/dist/cli/commands/generate/typescript.js +0 -52
  44. package/dist/cli/commands/generate.d.ts +0 -15
  45. package/dist/cli/commands/generate.js +0 -159
  46. package/dist/cli/commands/index.d.ts +0 -29
  47. package/dist/cli/commands/index.js +0 -100
  48. package/dist/cli/commands/typeschema/generate.d.ts +0 -19
  49. package/dist/cli/commands/typeschema/generate.js +0 -124
  50. package/dist/cli/commands/typeschema.d.ts +0 -10
  51. package/dist/cli/commands/typeschema.js +0 -47
  52. package/dist/cli/index.d.ts +0 -9
  53. package/dist/cli/utils/log.d.ts +0 -10
  54. package/dist/cli/utils/log.js +0 -23
  55. package/dist/cli/utils/prompts.d.ts +0 -56
  56. package/dist/cli/utils/prompts.js +0 -202
  57. package/dist/cli/utils/spinner.d.ts +0 -110
  58. package/dist/cli/utils/spinner.js +0 -266
  59. package/dist/config.d.ts +0 -217
  60. package/dist/config.js +0 -591
  61. package/dist/logger.d.ts +0 -157
  62. package/dist/logger.js +0 -281
  63. package/dist/typeschema/cache.d.ts +0 -80
  64. package/dist/typeschema/cache.js +0 -239
  65. package/dist/typeschema/core/binding.d.ts +0 -11
  66. package/dist/typeschema/core/binding.js +0 -143
  67. package/dist/typeschema/core/field-builder.d.ts +0 -12
  68. package/dist/typeschema/core/field-builder.js +0 -123
  69. package/dist/typeschema/core/identifier.d.ts +0 -13
  70. package/dist/typeschema/core/identifier.js +0 -94
  71. package/dist/typeschema/core/nested-types.d.ts +0 -9
  72. package/dist/typeschema/core/nested-types.js +0 -94
  73. package/dist/typeschema/core/transformer.d.ts +0 -11
  74. package/dist/typeschema/core/transformer.js +0 -235
  75. package/dist/typeschema/generator.d.ts +0 -43
  76. package/dist/typeschema/generator.js +0 -264
  77. package/dist/typeschema/index.d.ts +0 -15
  78. package/dist/typeschema/index.js +0 -15
  79. package/dist/typeschema/parser.d.ts +0 -79
  80. package/dist/typeschema/parser.js +0 -274
  81. package/dist/typeschema/profile/processor.d.ts +0 -14
  82. package/dist/typeschema/profile/processor.js +0 -262
  83. package/dist/typeschema/register.d.ts +0 -21
  84. package/dist/typeschema/register.js +0 -117
  85. package/dist/typeschema/types.d.ts +0 -240
  86. package/dist/typeschema/types.js +0 -19
  87. package/dist/utils/codegen-logger.d.ts +0 -102
  88. package/dist/utils/codegen-logger.js +0 -196
  89. package/dist/utils.d.ts +0 -22
  90. package/dist/utils.js +0 -42
package/dist/cli/index.js CHANGED
@@ -1,131 +1,52 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as w6}from"node:module";var L6=Object.create;var{getPrototypeOf:N6,defineProperty:q0,getOwnPropertyNames:C1,getOwnPropertyDescriptor:T6}=Object,E1=Object.prototype.hasOwnProperty;var b0=(D,F,u)=>{u=D!=null?L6(N6(D)):{};let C=F||!D||!D.__esModule?q0(u,"default",{value:D,enumerable:!0}):u;for(let E of C1(D))if(!E1.call(C,E))q0(C,E,{get:()=>D[E],enumerable:!0});return C},u1=new WeakMap,KF=(D)=>{var F=u1.get(D),u;if(F)return F;if(F=q0({},"__esModule",{value:!0}),D&&typeof D==="object"||typeof D==="function")C1(D).map((C)=>!E1.call(F,C)&&q0(F,C,{get:()=>D[C],enumerable:!(u=T6(D,C))||u.enumerable}));return u1.set(D,F),F},RF=(D,F)=>()=>(F||D((F={exports:{}}).exports,F),F.exports);var UF=(D,F)=>{for(var u in F)q0(D,u,{get:F[u],enumerable:!0,configurable:!0,set:(C)=>F[u]=()=>C})};var B1=(D,F)=>()=>(D&&(F=D(D=0)),F);var jF=w6(import.meta.url);var W1=RF((zC,J1)=>{J1.exports=()=>{return/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g}});var d1=RF((aC,h1)=>{h1.exports=function(F){if(F===void 0)F=2;if(F>=Error.stackTraceLimit)throw TypeError("getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `"+F+"` and Error.stackTraceLimit was: `"+Error.stackTraceLimit+"`");var u=Error.prepareStackTrace;Error.prepareStackTrace=function(E,B){return B};var C=Error().stack;if(Error.prepareStackTrace=u,C!==null&&typeof C==="object")return C[F]?C[F].getFileName():void 0}});var u2=RF((_B,F2)=>{var i0=process||{},T3=i0.argv||[],n0=i0.env||{},hu=!(!!n0.NO_COLOR||T3.includes("--no-color"))&&(!!n0.FORCE_COLOR||T3.includes("--color")||i0.platform==="win32"||(i0.stdout||{}).isTTY&&n0.TERM!=="dumb"||!!n0.CI),du=(D,F,u=D)=>(C)=>{let E=""+C,B=E.indexOf(F,D.length);return~B?D+pu(E,F,u,B)+F:D+E+F},pu=(D,F,u,C)=>{let E="",B=0;do E+=D.substring(B,C)+u,B=C+F.length,C=D.indexOf(F,B);while(~C);return E+D.substring(B)},w3=(D=hu)=>{let F=D?du:()=>String;return{isColorSupported:D,reset:F("\x1B[0m","\x1B[0m"),bold:F("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:F("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:F("\x1B[3m","\x1B[23m"),underline:F("\x1B[4m","\x1B[24m"),inverse:F("\x1B[7m","\x1B[27m"),hidden:F("\x1B[8m","\x1B[28m"),strikethrough:F("\x1B[9m","\x1B[29m"),black:F("\x1B[30m","\x1B[39m"),red:F("\x1B[31m","\x1B[39m"),green:F("\x1B[32m","\x1B[39m"),yellow:F("\x1B[33m","\x1B[39m"),blue:F("\x1B[34m","\x1B[39m"),magenta:F("\x1B[35m","\x1B[39m"),cyan:F("\x1B[36m","\x1B[39m"),white:F("\x1B[37m","\x1B[39m"),gray:F("\x1B[90m","\x1B[39m"),bgBlack:F("\x1B[40m","\x1B[49m"),bgRed:F("\x1B[41m","\x1B[49m"),bgGreen:F("\x1B[42m","\x1B[49m"),bgYellow:F("\x1B[43m","\x1B[49m"),bgBlue:F("\x1B[44m","\x1B[49m"),bgMagenta:F("\x1B[45m","\x1B[49m"),bgCyan:F("\x1B[46m","\x1B[49m"),bgWhite:F("\x1B[47m","\x1B[49m"),blackBright:F("\x1B[90m","\x1B[39m"),redBright:F("\x1B[91m","\x1B[39m"),greenBright:F("\x1B[92m","\x1B[39m"),yellowBright:F("\x1B[93m","\x1B[39m"),blueBright:F("\x1B[94m","\x1B[39m"),magentaBright:F("\x1B[95m","\x1B[39m"),cyanBright:F("\x1B[96m","\x1B[39m"),whiteBright:F("\x1B[97m","\x1B[39m"),bgBlackBright:F("\x1B[100m","\x1B[49m"),bgRedBright:F("\x1B[101m","\x1B[49m"),bgGreenBright:F("\x1B[102m","\x1B[49m"),bgYellowBright:F("\x1B[103m","\x1B[49m"),bgBlueBright:F("\x1B[104m","\x1B[49m"),bgMagentaBright:F("\x1B[105m","\x1B[49m"),bgCyanBright:F("\x1B[106m","\x1B[49m"),bgWhiteBright:F("\x1B[107m","\x1B[49m")}};F2.exports=w3();F2.exports.createColors=w3});var ID,p2,GF,Z0,g2,m2;var w0=B1(()=>{ID=class ID extends Error{phase;context;timestamp;errorId;constructor(D,F,u){super(D);this.phase=F;this.context=u;if(this.name=this.constructor.name,this.timestamp=new Date,this.errorId=this.generateErrorId(),Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}generateErrorId(){return`${this.constructor.name}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}getDetailedMessage(){let D=[`❌ ${this.constructor.name}: ${this.message}`,` Error ID: ${this.errorId}`,` Phase: ${this.phase}`,` Time: ${this.timestamp.toISOString()}`];if(this.context&&Object.keys(this.context).length>0)D.push(""),D.push("\uD83D\uDCCD Context:"),Object.entries(this.context).forEach(([F,u])=>{D.push(` ${F}: ${this.formatContextValue(u)}`)});return D.join(`
3
- `)}formatContextValue(D){if(D===null||D===void 0)return String(D);if(typeof D==="string")return`"${D}"`;if(typeof D==="object")try{return JSON.stringify(D,null,2)}catch{return"[Object]"}return String(D)}getSeverity(){return"error"}isRecoverable(){return!1}getDocumentationLinks(){return["https://github.com/atomic-ehr/codegen/docs/troubleshooting.md",`https://github.com/atomic-ehr/codegen/docs/errors/${this.constructor.name}.md`]}};p2=class p2 extends ID{schema;validationErrors;userContext;constructor(D,F,u,C){super(D,"validation",{schemaName:F.identifier?.name||"unknown",schemaKind:F.identifier?.kind||"unknown",schemaPackage:F.identifier?.package||"unknown",validationErrors:u,userContext:C});this.schema=F;this.validationErrors=u;this.userContext=C}getSuggestions(){let D=[];D.push("Verify the schema follows the TypeSchema specification"),D.push("Check that all required fields are present and properly typed");for(let F of this.validationErrors){if(F.includes("identifier.name"))D.push(" Add a valid identifier.name field to your schema"),D.push('\uD83D\uDCA1 Example: identifier: { name: "Patient", kind: "resource" }');if(F.includes("identifier.kind"))D.push('\uD83C\uDFAF Set identifier.kind to: "resource", "complex-type", "profile", or "primitive-type"'),D.push("\uD83D\uDCDA Check FHIR specification for the correct kind value");if(F.includes("circular"))D.push("\uD83D\uDD04 Remove circular references between schemas"),D.push("\uD83D\uDCA1 Use forward declarations for recursive types"),D.push("\uD83D\uDD0D Look for schemas that reference each other in a loop");if(F.includes("fields"))D.push("\uD83D\uDCDD Check that all fields have proper type definitions"),D.push("\uD83D\uDD27 Ensure field types reference valid TypeSchema identifiers")}if(this.userContext?.isBeginnerMode){if(D.push(""),D.push("\uD83C\uDF93 Beginner Tips:"),D.push("\uD83D\uDCD6 Start with the Quick Start guide: docs/getting-started/quick-start.md"),D.push("\uD83D\uDD0D Use --verbose flag for detailed error information"),D.push("\uD83E\uDDEA Test with a simple schema first to verify your setup"),this.userContext.previousSuccessfulSchemas?.length)D.push(`✅ Compare with your working schema: ${this.userContext.previousSuccessfulSchemas[0]}`)}if(!this.userContext?.isBeginnerMode)D.push(""),D.push("\uD83D\uDD27 Advanced Debugging:"),D.push("\uD83D\uDD75️ Enable schema validation debugging"),D.push("\uD83D\uDCCA Check schema statistics and complexity metrics"),D.push(" Consider schema preprocessing if dealing with complex inheritance");return D}isRecoverable(){return this.validationErrors.every((D)=>!D.includes("circular")&&!D.includes("corruption"))}};GF=class GF extends ID{templateName;templateContext;debugInfo;constructor(D,F,u,C){super(D,"generation",{templateName:F,contextKeys:Object.keys(u),availableTemplates:C?.availableTemplates?.length||0,debugInfo:C});this.templateName=F;this.templateContext=u;this.debugInfo=C}getSuggestions(){let D=[];if(this.debugInfo?.availableTemplates?.length){if(!this.debugInfo.availableTemplates.includes(this.templateName)){D.push(`❌ Template '${this.templateName}' not found`),D.push("\uD83D\uDCC2 Available templates:"),this.debugInfo.availableTemplates.forEach((u)=>{D.push(` ${u}`)});let F=this.findSimilarTemplates(this.templateName,this.debugInfo.availableTemplates);if(F.length>0)D.push("\uD83E\uDD14 Did you mean:"),F.forEach((u)=>{D.push(` ${u}`)})}}if(this.debugInfo?.missingVariables?.length){D.push("\uD83D\uDCDD Missing template variables:"),this.debugInfo.missingVariables.forEach((u)=>{D.push(` ${u}`)}),D.push("\uD83D\uDCA1 Add these variables to your template context");let F=Object.keys(this.templateContext);this.debugInfo.missingVariables.forEach((u)=>{let C=F.filter((E)=>this.levenshteinDistance(u.toLowerCase(),E.toLowerCase())<=2);if(C.length>0)D.push(` Similar to: ${C.join(", ")}`)})}if(this.debugInfo?.lineNumber){if(D.push(`\uD83D\uDC1B Check template syntax around line ${this.debugInfo.lineNumber}`),this.debugInfo.columnNumber)D.push(` Column: ${this.debugInfo.columnNumber}`);if(this.debugInfo.templateSource){let u=this.debugInfo.templateSource.split(`
4
- `)[this.debugInfo.lineNumber-1];if(u)D.push(` Code: ${u.trim()}`)}}return D.push("\uD83D\uDD27 Template debugging steps:"),D.push(" Enable template debugging: { debug: true }"),D.push(" Verify template file exists and has correct syntax"),D.push(" Check template variable names match context keys"),D.push(" Ensure template engine is properly configured"),D}findSimilarTemplates(D,F){return F.filter((u)=>{let C=this.levenshteinDistance(D.toLowerCase(),u.toLowerCase());return C<=2&&C>0}).slice(0,3).sort((u,C)=>this.levenshteinDistance(D.toLowerCase(),u.toLowerCase())-this.levenshteinDistance(D.toLowerCase(),C.toLowerCase()))}levenshteinDistance(D,F){let u=Array(F.length+1).fill(null).map(()=>Array(D.length+1).fill(0));for(let C=0;C<=D.length;C++)u[0][C]=C;for(let C=0;C<=F.length;C++)u[C][0]=C;for(let C=1;C<=F.length;C++)for(let E=1;E<=D.length;E++){let B=D[E-1]===F[C-1]?0:1;u[C][E]=Math.min(u[C]?.[E-1]+1,u[C-1]?.[E]+1,u[C-1]?.[E-1]+B)}return u[F.length]?.[D.length]}isRecoverable(){return!0}};Z0=class Z0 extends ID{operation;filePath;originalError;recoveryOptions;constructor(D,F,u,C,E){super(D,"writing",{operation:F,filePath:u,originalErrorMessage:C?.message,originalErrorCode:C?.code,recoveryOptions:E});this.operation=F;this.filePath=u;this.originalError=C;this.recoveryOptions=E}getSuggestions(){let D=[],F=this.originalError?.code;switch(this.operation){case"create":case"write":if(D.push("\uD83D\uDCC1 File writing troubleshooting:"),D.push(" Check if the output directory exists"),D.push(" Verify write permissions for the target directory"),D.push(" Ensure no other process has the file locked"),this.filePath.includes(" "))D.push(" File path contains spaces - check path escaping");if(this.recoveryOptions?.alternativePaths?.length)D.push("\uD83D\uDD04 Alternative output directories:"),this.recoveryOptions.alternativePaths.forEach((u)=>{D.push(` ${u}`)});break;case"read":D.push("\uD83D\uDCD6 File reading troubleshooting:"),D.push(" Verify the file exists at the specified path"),D.push(" Check file read permissions"),D.push(" Ensure file is not corrupted");break;case"delete":D.push("\uD83D\uDDD1️ File deletion troubleshooting:"),D.push(" Check if file is locked by another process"),D.push(" Verify delete permissions for the directory"),D.push(" Ensure file exists before attempting deletion");break}switch(F){case"EACCES":if(D.push("\uD83D\uDD10 Permission Error:"),D.push(" Current user lacks necessary file permissions"),this.recoveryOptions?.permissionFix)D.push(` Fix command: ${this.recoveryOptions.permissionFix}`);else D.push(` Try: chmod 755 "${this.filePath}"`);D.push(" Consider running with elevated permissions"),D.push(" Check directory ownership and permissions");break;case"ENOSPC":if(D.push("\uD83D\uDCBE Disk Space Error:"),D.push(" Insufficient disk space available"),D.push(" Free up disk space and retry"),D.push(" Consider using a different output directory"),this.recoveryOptions?.diskSpaceRequired){let u=Math.ceil(this.recoveryOptions.diskSpaceRequired/1024/1024);D.push(` Required space: ~${u}MB`)}break;case"ENOENT":D.push("\uD83D\uDCC2 File Not Found:"),D.push(" File or directory does not exist"),D.push(" Check the file path for typos"),D.push(" Ensure parent directories exist"),D.push(` Create directory: mkdir -p "$(dirname "${this.filePath}")"`);break;case"EMFILE":case"ENFILE":D.push("\uD83D\uDCCA Too Many Open Files:"),D.push(" System has reached file handle limit"),D.push(" Close unused files and retry"),D.push(" Consider processing files in smaller batches");break}if(this.recoveryOptions?.canRetry)D.push(""),D.push("\uD83D\uDD04 Recovery Options:"),D.push(" This operation can be retried safely"),D.push(" Fix the underlying issue and run again");return D.push(""),D.push("\uD83D\uDD0D General Debugging:"),D.push(" Check system logs for more details"),D.push(" Verify disk health if errors persist"),D.push(" Test with a simpler file path"),D}isRecoverable(){return this.recoveryOptions?.canRetry||!1}getRecoveryActions(){let D=[];switch(this.originalError?.code){case"EACCES":D.push({action:"Fix file permissions",command:`chmod 755 "${this.filePath}"`,automatic:!1,riskLevel:"medium"});break;case"ENOENT":D.push({action:"Create missing directory",command:`mkdir -p "$(dirname "${this.filePath}")"`,automatic:!0,riskLevel:"low"});break;case"ENOSPC":D.push({action:"Free up disk space",automatic:!1,riskLevel:"low"});break}return D}};g2=class g2 extends ID{configKey;providedValue;expectedValue;validOptions;constructor(D,F,u,C,E){super(D,"initialization",{configKey:F,providedValue:u,providedType:typeof u,expectedValue:C,validOptions:E});this.configKey=F;this.providedValue=u;this.expectedValue=C;this.validOptions=E}getSuggestions(){let D=[];if(D.push(`⚙️ Configuration error for '${this.configKey}'`),D.push(` Provided: ${JSON.stringify(this.providedValue)} (${typeof this.providedValue})`),this.expectedValue)D.push(` Expected: ${this.expectedValue}`);if(this.validOptions?.length)D.push(" Valid options:"),this.validOptions.forEach((F)=>{D.push(` ${JSON.stringify(F)}`)});switch(D.push(""),D.push("\uD83D\uDD27 Configuration fixes:"),D.push(` Check the '${this.configKey}' value in your configuration`),D.push(" Refer to the configuration documentation"),D.push(" Use TypeScript for better config validation"),D.push(" Check for typos in configuration keys"),this.configKey){case"outputDir":D.push(" Ensure the output directory path exists"),D.push(" Use absolute paths for better reliability");break;case"logger":D.push(" Provide a valid logger instance"),D.push(" Use createLogger() from utils/codegen-logger");break;case"validation":D.push(' Set to true, false, or "strict"');break}return D}isRecoverable(){return!0}};m2=class m2 extends ID{errors;constructor(D,F){super(D,"generation",{errorCount:F.length,errorTypes:[...new Set(F.map((u)=>u.constructor.name))],phases:[...new Set(F.map((u)=>u.phase))]});this.errors=F}getSuggestions(){let D=this.errors.flatMap((B)=>B.getSuggestions()),F=[...new Set(D)],u=[];u.push(`\uD83D\uDCCA Batch operation failed with ${this.errors.length} errors:`);let C=new Map;this.errors.forEach((B)=>{let $=B.constructor.name;if(!C.has($))C.set($,[]);C.get($)?.push(B)}),u.push(""),u.push("\uD83D\uDD0D Error breakdown:");for(let[B,$]of C)u.push(` ${B}: ${$.length} occurrences`);u.push("\uD83D\uDCA1 Most relevant suggestions:");let E=F.slice(0,8).map((B)=>` ${B}`);return u.push(...E),u}getErrorBreakdown(){let D=[];return this.errors.forEach((F,u)=>{if(D.push(`${u+1}. ${F.constructor.name}: ${F.message}`),F.context?.schemaName)D.push(` Schema: ${F.context.schemaName}`);if(F.context?.filename)D.push(` File: ${F.context.filename}`);D.push("")}),D.join(`
5
- `)}isRecoverable(){return this.errors.some((D)=>D.isRecoverable())}getRecoverableErrors(){return this.errors.filter((D)=>D.isRecoverable())}getNonRecoverableErrors(){return this.errors.filter((D)=>!D.isRecoverable())}}});var J6={};UF(J6,{FileBuilder:()=>O6});class O6{config;content="";imports=new Map;exports=new Set;metadata=new Map;beforeSaveHooks=[];afterSaveHooks=[];errorHooks=[];options={template:void 0,importStrategy:"auto",validation:"strict",prettify:!0,formatting:{indentSize:2,useTabs:!1,maxLineLength:100},encoding:"utf-8"};constructor(D){this.config=D}withContent(D){return this.content=typeof D==="string"?D:D(),this}withTemplate(D,F){if(!this.config.templateEngine)throw new GF(`Template engine is required for template rendering. Template: '${D}'`,D,F);this.options.template=D;try{this.content=this.config.templateEngine.render(D,{...F,imports:this.imports,exports:this.exports,filename:this.config.filename})}catch(u){throw new GF(`Failed to render template '${D}'`,D,F,{availableTemplates:this.config.templateEngine.getAvailableTemplates?.()||[]})}return this}appendContent(D){return this.content+=D,this}prependContent(D){return this.content=D+this.content,this}withImports(D){this.imports.clear();for(let[F,u]of D)this.imports.set(F,u);return this}addImport(D,F){return this.imports.set(D,F),this}addImports(D,F){for(let u of D)this.imports.set(u,F);return this}withExports(D){this.exports.clear();for(let F of D)this.exports.add(F);return this}addExport(D){return this.exports.add(D),this}addExports(D){for(let F of D)this.exports.add(F);return this}withMetadata(D,F){return this.metadata.set(D,F),this}withOptions(D){return this.options={...this.options,...D},this}onBeforeSave(D){return this.beforeSaveHooks.push(D),this}onAfterSave(D){return this.afterSaveHooks.push(D),this}onError(D){return this.errorHooks.push(D),this}build(){let D=this.buildFinalContent();return{filename:this.config.filename,content:D,imports:new Map(this.imports),exports:new Set(this.exports),metadata:Object.fromEntries(this.metadata),templateName:this.options.template}}async save(){let D=this.build();try{for(let C of this.beforeSaveHooks)await C(D);if(this.options.validation!=="none")await this.validateContent(D.content);let F=await this.config.fileManager.writeFile(this.config.filename,D.content,{encoding:this.options.encoding}),u={size:F.size,generationTime:0,writeTime:F.writeTime};for(let C of this.afterSaveHooks)await C(F.path,u);return this.config.logger.debug(`Saved ${this.config.filename} successfully`),F.path}catch(F){for(let u of this.errorHooks)try{await u(F instanceof Error?F:Error(String(F)),D)}catch(C){this.config.logger.warn(`Error hook failed: ${C instanceof Error?C.message:String(C)}`)}throw F}}buildFinalContent(){let D=[];if(this.imports.size>0&&this.options.importStrategy!=="none")D.push(this.generateImportStatements()),D.push("");if(this.content)D.push(this.content);if(this.exports.size>0&&!this.content.includes("export"))D.push(""),D.push(this.generateExportStatements());let F=D.join(`
6
- `);if(this.options.prettify)F=this.prettifyContent(F);return F}generateImportStatements(){let D=[],F=new Map;for(let[u,C]of this.imports){let E=this.options.importStrategy==="auto"?this.config.fileManager.getRelativeImportPath(this.config.filename,C):C;if(!F.has(E))F.set(E,[]);F.get(E)?.push(u)}for(let[u,C]of F)if(C.length===1)D.push(`import type { ${C[0]} } from '${u}';`);else{let E=C.sort();if(E.length<=3)D.push(`import type { ${E.join(", ")} } from '${u}';`);else{D.push("import type {");let B="\t";E.forEach(($,Z)=>{let Q=Z===E.length-1;D.push(`${B}${$}${Q?"":","}`)}),D.push(`} from '${u}';`)}}return D.join(`
7
- `)}generateExportStatements(){return Array.from(this.exports).sort().map((F)=>`export { ${F} };`).join(`
8
- `)}prettifyContent(D){return D.replace(/\n{3,}/g,`
2
+ import Jt from'yargs';import {hideBin}from'yargs/helpers';import'perf_hooks';import'ora';import m from'picocolors';import {existsSync,mkdirSync}from'fs';import {dirname,resolve,join,relative}from'path';import {mkdir,writeFile,readFile,readdir,stat,unlink,access,rm}from'fs/promises';import {CanonicalManager}from'@atomic-ehr/fhir-canonical-manager';import*as De from'@atomic-ehr/fhirschema';var te=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var st=Object.getOwnPropertyNames;var ot=Object.prototype.hasOwnProperty;var at=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var N=(s,e)=>()=>(s&&(e=s(s=0)),e);var re=(s,e)=>{for(var t in e)te(s,t,{get:e[t],enumerable:true});},ct=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of st(e))!ot.call(s,i)&&i!==t&&te(s,i,{get:()=>e[i],enumerable:!(r=nt(e,i))||r.enumerable});return s};var ie=s=>ct(te({},"__esModule",{value:true}),s);var y,_,I,w,z,q,E=N(()=>{y=class extends Error{constructor(t,r,i){super(t);this.phase=r;this.context=i;this.name=this.constructor.name,this.timestamp=new Date,this.errorId=this.generateErrorId(),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor);}timestamp;errorId;generateErrorId(){return `${this.constructor.name}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}getDetailedMessage(){let t=[`\u274C ${this.constructor.name}: ${this.message}`,` Error ID: ${this.errorId}`,` Phase: ${this.phase}`,` Time: ${this.timestamp.toISOString()}`];return this.context&&Object.keys(this.context).length>0&&(t.push(""),t.push("\u{1F4CD} Context:"),Object.entries(this.context).forEach(([r,i])=>{t.push(` ${r}: ${this.formatContextValue(i)}`);})),t.join(`
3
+ `)}formatContextValue(t){if(t==null)return String(t);if(typeof t=="string")return `"${t}"`;if(typeof t=="object")try{return JSON.stringify(t,null,2)}catch{return "[Object]"}return String(t)}getSeverity(){return "error"}isRecoverable(){return false}getDocumentationLinks(){return ["https://github.com/atomic-ehr/codegen/docs/troubleshooting.md",`https://github.com/atomic-ehr/codegen/docs/errors/${this.constructor.name}.md`]}},_=class extends y{constructor(t,r,i,n){super(t,"validation",{schemaName:r.identifier?.name||"unknown",schemaKind:r.identifier?.kind||"unknown",schemaPackage:r.identifier?.package||"unknown",validationErrors:i,userContext:n});this.schema=r;this.validationErrors=i;this.userContext=n;}getSuggestions(){let t=[];t.push("Verify the schema follows the TypeSchema specification"),t.push("Check that all required fields are present and properly typed");for(let r of this.validationErrors)r.includes("identifier.name")&&(t.push("\u2728 Add a valid identifier.name field to your schema"),t.push('\u{1F4A1} Example: identifier: { name: "Patient", kind: "resource" }')),r.includes("identifier.kind")&&(t.push('\u{1F3AF} Set identifier.kind to: "resource", "complex-type", "profile", or "primitive-type"'),t.push("\u{1F4DA} Check FHIR specification for the correct kind value")),r.includes("circular")&&(t.push("\u{1F504} Remove circular references between schemas"),t.push("\u{1F4A1} Use forward declarations for recursive types"),t.push("\u{1F50D} Look for schemas that reference each other in a loop")),r.includes("fields")&&(t.push("\u{1F4DD} Check that all fields have proper type definitions"),t.push("\u{1F527} Ensure field types reference valid TypeSchema identifiers"));return this.userContext?.isBeginnerMode&&(t.push(""),t.push("\u{1F393} Beginner Tips:"),t.push("\u{1F4D6} Start with the Quick Start guide: docs/getting-started/quick-start.md"),t.push("\u{1F50D} Use --verbose flag for detailed error information"),t.push("\u{1F9EA} Test with a simple schema first to verify your setup"),this.userContext.previousSuccessfulSchemas?.length&&t.push(`\u2705 Compare with your working schema: ${this.userContext.previousSuccessfulSchemas[0]}`)),this.userContext?.isBeginnerMode||(t.push(""),t.push("\u{1F527} Advanced Debugging:"),t.push("\u{1F575}\uFE0F Enable schema validation debugging"),t.push("\u{1F4CA} Check schema statistics and complexity metrics"),t.push("\u26A1 Consider schema preprocessing if dealing with complex inheritance")),t}isRecoverable(){return this.validationErrors.every(t=>!t.includes("circular")&&!t.includes("corruption"))}},I=class extends y{constructor(t,r,i,n){super(t,"generation",{templateName:r,contextKeys:Object.keys(i),availableTemplates:n?.availableTemplates?.length||0,debugInfo:n});this.templateName=r;this.templateContext=i;this.debugInfo=n;}getSuggestions(){let t=[];if(this.debugInfo?.availableTemplates?.length&&!this.debugInfo.availableTemplates.includes(this.templateName)){t.push(`\u274C Template '${this.templateName}' not found`),t.push("\u{1F4C2} Available templates:"),this.debugInfo.availableTemplates.forEach(i=>{t.push(` \u2022 ${i}`);});let r=this.findSimilarTemplates(this.templateName,this.debugInfo.availableTemplates);r.length>0&&(t.push("\u{1F914} Did you mean:"),r.forEach(i=>{t.push(` \u2022 ${i}`);}));}if(this.debugInfo?.missingVariables?.length){t.push("\u{1F4DD} Missing template variables:"),this.debugInfo.missingVariables.forEach(i=>{t.push(` \u2022 ${i}`);}),t.push("\u{1F4A1} Add these variables to your template context");let r=Object.keys(this.templateContext);this.debugInfo.missingVariables.forEach(i=>{let n=r.filter(o=>this.levenshteinDistance(i.toLowerCase(),o.toLowerCase())<=2);n.length>0&&t.push(` Similar to: ${n.join(", ")}`);});}if(this.debugInfo?.lineNumber&&(t.push(`\u{1F41B} Check template syntax around line ${this.debugInfo.lineNumber}`),this.debugInfo.columnNumber&&t.push(` Column: ${this.debugInfo.columnNumber}`),this.debugInfo.templateSource)){let i=this.debugInfo.templateSource.split(`
4
+ `)[this.debugInfo.lineNumber-1];i&&t.push(` Code: ${i.trim()}`);}return t.push("\u{1F527} Template debugging steps:"),t.push(" \u2022 Enable template debugging: { debug: true }"),t.push(" \u2022 Verify template file exists and has correct syntax"),t.push(" \u2022 Check template variable names match context keys"),t.push(" \u2022 Ensure template engine is properly configured"),t}findSimilarTemplates(t,r){return r.filter(i=>{let n=this.levenshteinDistance(t.toLowerCase(),i.toLowerCase());return n<=2&&n>0}).slice(0,3).sort((i,n)=>this.levenshteinDistance(t.toLowerCase(),i.toLowerCase())-this.levenshteinDistance(t.toLowerCase(),n.toLowerCase()))}levenshteinDistance(t,r){let i=Array(r.length+1).fill(null).map(()=>Array(t.length+1).fill(0));for(let n=0;n<=t.length;n++)i[0][n]=n;for(let n=0;n<=r.length;n++)i[n][0]=n;for(let n=1;n<=r.length;n++)for(let o=1;o<=t.length;o++){let a=t[o-1]===r[n-1]?0:1;i[n][o]=Math.min(i[n]?.[o-1]+1,i[n-1]?.[o]+1,i[n-1]?.[o-1]+a);}return i[r.length]?.[t.length]}isRecoverable(){return true}},w=class extends y{constructor(t,r,i,n,o){super(t,"writing",{operation:r,filePath:i,originalErrorMessage:n?.message,originalErrorCode:n?.code,recoveryOptions:o});this.operation=r;this.filePath=i;this.originalError=n;this.recoveryOptions=o;}getSuggestions(){let t=[],r=this.originalError?.code;switch(this.operation){case "create":case "write":t.push("\u{1F4C1} File writing troubleshooting:"),t.push(" \u2022 Check if the output directory exists"),t.push(" \u2022 Verify write permissions for the target directory"),t.push(" \u2022 Ensure no other process has the file locked"),this.filePath.includes(" ")&&t.push(" \u2022 File path contains spaces - check path escaping"),this.recoveryOptions?.alternativePaths?.length&&(t.push("\u{1F504} Alternative output directories:"),this.recoveryOptions.alternativePaths.forEach(i=>{t.push(` \u2022 ${i}`);}));break;case "read":t.push("\u{1F4D6} File reading troubleshooting:"),t.push(" \u2022 Verify the file exists at the specified path"),t.push(" \u2022 Check file read permissions"),t.push(" \u2022 Ensure file is not corrupted");break;case "delete":t.push("\u{1F5D1}\uFE0F File deletion troubleshooting:"),t.push(" \u2022 Check if file is locked by another process"),t.push(" \u2022 Verify delete permissions for the directory"),t.push(" \u2022 Ensure file exists before attempting deletion");break}switch(r){case "EACCES":t.push("\u{1F510} Permission Error:"),t.push(" \u2022 Current user lacks necessary file permissions"),this.recoveryOptions?.permissionFix?t.push(` \u2022 Fix command: ${this.recoveryOptions.permissionFix}`):t.push(` \u2022 Try: chmod 755 "${this.filePath}"`),t.push(" \u2022 Consider running with elevated permissions"),t.push(" \u2022 Check directory ownership and permissions");break;case "ENOSPC":if(t.push("\u{1F4BE} Disk Space Error:"),t.push(" \u2022 Insufficient disk space available"),t.push(" \u2022 Free up disk space and retry"),t.push(" \u2022 Consider using a different output directory"),this.recoveryOptions?.diskSpaceRequired){let i=Math.ceil(this.recoveryOptions.diskSpaceRequired/1024/1024);t.push(` \u2022 Required space: ~${i}MB`);}break;case "ENOENT":t.push("\u{1F4C2} File Not Found:"),t.push(" \u2022 File or directory does not exist"),t.push(" \u2022 Check the file path for typos"),t.push(" \u2022 Ensure parent directories exist"),t.push(` \u2022 Create directory: mkdir -p "$(dirname "${this.filePath}")"`);break;case "EMFILE":case "ENFILE":t.push("\u{1F4CA} Too Many Open Files:"),t.push(" \u2022 System has reached file handle limit"),t.push(" \u2022 Close unused files and retry"),t.push(" \u2022 Consider processing files in smaller batches");break}return this.recoveryOptions?.canRetry&&(t.push(""),t.push("\u{1F504} Recovery Options:"),t.push(" \u2022 This operation can be retried safely"),t.push(" \u2022 Fix the underlying issue and run again")),t.push(""),t.push("\u{1F50D} General Debugging:"),t.push(" \u2022 Check system logs for more details"),t.push(" \u2022 Verify disk health if errors persist"),t.push(" \u2022 Test with a simpler file path"),t}isRecoverable(){return this.recoveryOptions?.canRetry||false}getRecoveryActions(){let t=[];switch(this.originalError?.code){case "EACCES":t.push({action:"Fix file permissions",command:`chmod 755 "${this.filePath}"`,automatic:false,riskLevel:"medium"});break;case "ENOENT":t.push({action:"Create missing directory",command:`mkdir -p "$(dirname "${this.filePath}")"`,automatic:true,riskLevel:"low"});break;case "ENOSPC":t.push({action:"Free up disk space",automatic:false,riskLevel:"low"});break}return t}},z=class extends y{constructor(t,r,i,n,o){super(t,"initialization",{configKey:r,providedValue:i,providedType:typeof i,expectedValue:n,validOptions:o});this.configKey=r;this.providedValue=i;this.expectedValue=n;this.validOptions=o;}getSuggestions(){let t=[];switch(t.push(`\u2699\uFE0F Configuration error for '${this.configKey}'`),t.push(` Provided: ${JSON.stringify(this.providedValue)} (${typeof this.providedValue})`),this.expectedValue&&t.push(` Expected: ${this.expectedValue}`),this.validOptions?.length&&(t.push(" Valid options:"),this.validOptions.forEach(r=>{t.push(` \u2022 ${JSON.stringify(r)}`);})),t.push(""),t.push("\u{1F527} Configuration fixes:"),t.push(` \u2022 Check the '${this.configKey}' value in your configuration`),t.push(" \u2022 Refer to the configuration documentation"),t.push(" \u2022 Use TypeScript for better config validation"),t.push(" \u2022 Check for typos in configuration keys"),this.configKey){case "outputDir":t.push(" \u2022 Ensure the output directory path exists"),t.push(" \u2022 Use absolute paths for better reliability");break;case "logger":t.push(" \u2022 Provide a valid logger instance"),t.push(" \u2022 Use createLogger() from utils/codegen-logger");break;case "validation":t.push(' \u2022 Set to true, false, or "strict"');break}return t}isRecoverable(){return true}},q=class extends y{constructor(t,r){super(t,"generation",{errorCount:r.length,errorTypes:[...new Set(r.map(i=>i.constructor.name))],phases:[...new Set(r.map(i=>i.phase))]});this.errors=r;}getSuggestions(){let t=this.errors.flatMap(a=>a.getSuggestions()),r=[...new Set(t)],i=[];i.push(`\u{1F4CA} Batch operation failed with ${this.errors.length} errors:`);let n=new Map;this.errors.forEach(a=>{let c=a.constructor.name;n.has(c)||n.set(c,[]),n.get(c)?.push(a);}),i.push(""),i.push("\u{1F50D} Error breakdown:");for(let[a,c]of n)i.push(` \u2022 ${a}: ${c.length} occurrences`);i.push("\u{1F4A1} Most relevant suggestions:");let o=r.slice(0,8).map(a=>` ${a}`);return i.push(...o),i}getErrorBreakdown(){let t=[];return this.errors.forEach((r,i)=>{t.push(`${i+1}. ${r.constructor.name}: ${r.message}`),r.context?.schemaName&&t.push(` Schema: ${r.context.schemaName}`),r.context?.filename&&t.push(` File: ${r.context.filename}`),t.push("");}),t.join(`
5
+ `)}isRecoverable(){return this.errors.some(t=>t.isRecoverable())}getRecoverableErrors(){return this.errors.filter(t=>t.isRecoverable())}getNonRecoverableErrors(){return this.errors.filter(t=>!t.isRecoverable())}};});var qe={};re(qe,{FileBuilder:()=>Ce});var Ce,Je=N(()=>{E();Ce=class{config;content="";imports=new Map;exports=new Set;metadata=new Map;beforeSaveHooks=[];afterSaveHooks=[];errorHooks=[];options={template:void 0,importStrategy:"auto",validation:"strict",prettify:true,formatting:{indentSize:2,useTabs:false,maxLineLength:100},encoding:"utf-8"};constructor(e){this.config=e;}withContent(e){return this.content=typeof e=="string"?e:e(),this}withTemplate(e,t){if(!this.config.templateEngine)throw new I(`Template engine is required for template rendering. Template: '${e}'`,e,t);this.options.template=e;try{this.content=this.config.templateEngine.render(e,{...t,imports:this.imports,exports:this.exports,filename:this.config.filename});}catch{throw new I(`Failed to render template '${e}'`,e,t,{availableTemplates:this.config.templateEngine.getAvailableTemplates?.()||[]})}return this}appendContent(e){return this.content+=e,this}prependContent(e){return this.content=e+this.content,this}withImports(e){this.imports.clear();for(let[t,r]of e)this.imports.set(t,r);return this}addImport(e,t){return this.imports.set(e,t),this}addImports(e,t){for(let r of e)this.imports.set(r,t);return this}withExports(e){this.exports.clear();for(let t of e)this.exports.add(t);return this}addExport(e){return this.exports.add(e),this}addExports(e){for(let t of e)this.exports.add(t);return this}withMetadata(e,t){return this.metadata.set(e,t),this}withOptions(e){return this.options={...this.options,...e},this}onBeforeSave(e){return this.beforeSaveHooks.push(e),this}onAfterSave(e){return this.afterSaveHooks.push(e),this}onError(e){return this.errorHooks.push(e),this}build(){let e=this.buildFinalContent();return {filename:this.config.filename,content:e,imports:new Map(this.imports),exports:new Set(this.exports),metadata:Object.fromEntries(this.metadata),templateName:this.options.template}}async save(){let e=this.build();try{for(let i of this.beforeSaveHooks)await i(e);this.options.validation!=="none"&&await this.validateContent(e.content);let t=await this.config.fileManager.writeFile(this.config.filename,e.content,{encoding:this.options.encoding}),r={size:t.size,generationTime:0,writeTime:t.writeTime};for(let i of this.afterSaveHooks)await i(t.path,r);return this.config.logger.debug(`Saved ${this.config.filename} successfully`),t.path}catch(t){for(let r of this.errorHooks)try{await r(t instanceof Error?t:new Error(String(t)),e);}catch(i){this.config.logger.warn(`Error hook failed: ${i instanceof Error?i.message:String(i)}`);}throw t}}buildFinalContent(){let e=[];this.imports.size>0&&this.options.importStrategy!=="none"&&(e.push(this.generateImportStatements()),e.push("")),this.content&&e.push(this.content),this.exports.size>0&&!this.content.includes("export")&&(e.push(""),e.push(this.generateExportStatements()));let t=e.join(`
6
+ `);return this.options.prettify&&(t=this.prettifyContent(t)),t}generateImportStatements(){let e=[],t=new Map;for(let[r,i]of this.imports){let n=this.options.importStrategy==="auto"?this.config.fileManager.getRelativeImportPath(this.config.filename,i):i;t.has(n)||t.set(n,[]),t.get(n)?.push(r);}for(let[r,i]of t)if(i.length===1)e.push(`import type { ${i[0]} } from '${r}';`);else {let n=i.sort();if(n.length<=3)e.push(`import type { ${n.join(", ")} } from '${r}';`);else {e.push("import type {");let o=" ";n.forEach((a,c)=>{let l=c===n.length-1;e.push(`${o}${a}${l?"":","}`);}),e.push(`} from '${r}';`);}}return e.join(`
7
+ `)}generateExportStatements(){return Array.from(this.exports).sort().map(t=>`export { ${t} };`).join(`
8
+ `)}prettifyContent(e){return e.replace(/\n{3,}/g,`
9
9
 
10
- `).replace(/\t/g,this.options.formatting?.useTabs?"\t":" ".repeat(this.options.formatting?.indentSize||2)).trim()}async validateContent(D){if(this.options.validation==="none")return;let F=[],u=(D.match(/\{/g)||[]).length,C=(D.match(/\}/g)||[]).length;if(u!==C)F.push(`Unmatched braces: ${u} open, ${C} close`);let E=(D.match(/\(/g)||[]).length,B=(D.match(/\)/g)||[]).length;if(E!==B)F.push(`Unmatched parentheses: ${E} open, ${B} close`);if(this.config.filename.endsWith(".ts")||this.config.filename.endsWith(".tsx")){if(D.includes("interface")&&!D.match(/interface\s+\w+\s*\{/))F.push("Invalid interface syntax detected")}if(F.length>0&&this.options.validation==="strict")throw new Z0(`Content validation failed for ${this.config.filename}: ${F.join(", ")}`,"write",this.config.filename);else if(F.length>0)this.config.logger.warn(`Validation issues in ${this.config.filename}: ${F.join(", ")}`)}getContent(){return this.content}getImports(){return new Map(this.imports)}getExports(){return new Set(this.exports)}}var W6=B1(()=>{w0()});var A6={};UF(A6,{DirectoryBuilder:()=>s2});class s2{config;files=new Map;subdirectories=new Map;indexBuilder;shouldClean=!1;constructor(D){this.config=D}withSubdirectory(D){let F=`${this.config.path}/${D}`,u=new s2({path:F,fileManager:this.config.fileManager,logger:this.config.logger.child(`Dir:${D}`)});return this.subdirectories.set(D,u),u}withFiles(D){for(let[F,u]of Object.entries(D))this.files.set(F,u);return this}withFile(D,F){return this.files.set(D,F),this}withIndex(D){return this.indexBuilder=D,this}clean(){return this.shouldClean=!0,this}async ensure(){return await this.config.fileManager.ensureDirectory(this.config.path),this}async save(){let D=[];if(this.shouldClean)await this.config.fileManager.cleanDirectory(this.config.path);await this.ensure();let F=Array.from(this.files.entries()).map(async([u,C])=>{try{let E=await C.save();return D.push(E),E}catch(E){throw this.config.logger.error(`Failed to save file ${u}:`,E instanceof Error?E:void 0),E}});await Promise.all(F);for(let[u,C]of this.subdirectories)try{let E=await C.save();D.push(...E)}catch(E){throw this.config.logger.error(`Failed to save subdirectory ${u}:`,E instanceof Error?E:void 0),E}if(this.indexBuilder)try{let u=await this.indexBuilder.save();D.push(u)}catch(u){throw this.config.logger.error("Failed to save index file:",u instanceof Error?u:void 0),u}return this.config.logger.info(`Saved directory ${this.config.path} with ${D.length} files`),D}getFileList(){let D=[];for(let F of this.files.keys())D.push(`${this.config.path}/${F}`);for(let[F,u]of this.subdirectories){let C=u.getFileList();D.push(...C)}if(this.indexBuilder)D.push(`${this.config.path}/index.ts`);return D.sort()}getStats(){let D=this.files.size;for(let F of this.subdirectories.values())D+=F.getStats().totalFiles;if(this.indexBuilder)D+=1;return{fileCount:this.files.size,subdirectoryCount:this.subdirectories.size,hasIndex:!!this.indexBuilder,totalFiles:D}}async wouldOverwrite(){let D=[];for(let F of this.files.keys()){let u=`${this.config.path}/${F}`;if(await this.config.fileManager.wouldOverwrite(u))D.push(u)}for(let F of this.subdirectories.values()){let u=await F.wouldOverwrite();D.push(...u)}if(this.indexBuilder){let F=`${this.config.path}/index.ts`;if(await this.config.fileManager.wouldOverwrite(F))D.push(F)}return D}getPath(){return this.config.path}getFiles(){return new Map(this.files)}getSubdirectories(){return new Map(this.subdirectories)}getIndexBuilder(){return this.indexBuilder}}var H6={};UF(H6,{IndexBuilder:()=>G6});class G6{config;exports=new Map;namespaces=new Map;reExports=new Map;header="";footer="";groupingFunction;sortFunction;constructor(D){this.config=D}withExports(D,F){for(let u of D)this.exports.set(u,F);return this}withExport(D,F){return this.exports.set(D,F),this}withNamespaces(D){for(let[F,u]of Object.entries(D))this.namespaces.set(F,u);return this}withNamespace(D,F){return this.namespaces.set(D,F),this}withReExports(D){for(let F of D)this.reExports.set(F,F);return this}withReExport(D){return this.reExports.set(D,D),this}withHeader(D){return this.header=D,this}withFooter(D){return this.footer=D,this}groupBy(D){return this.groupingFunction=D,this}sortBy(D){return this.sortFunction=D,this}async autoDiscover(D){return this.config.logger.debug(`Auto-discovering exports in ${this.config.directory}`),this.config.logger.warn("Auto-discovery not yet implemented - manually add exports"),this}async save(){let D=this.generateContent(),F=`${this.config.directory}/index.ts`,u=await this.config.fileManager.writeFile(F,D);return this.config.logger.debug(`Generated index file: ${F}`),u.path}build(){return this.generateContent()}generateContent(){let D=[];if(this.header)D.push(this.header),D.push("");if(this.reExports.size>0){D.push("// Re-exports");for(let u of this.reExports.values())D.push(`export * from './${u}';`);D.push("")}if(this.exports.size>0){if(this.groupingFunction)this.generateGroupedExports(D);else this.generateSimpleExports(D);D.push("")}if(this.namespaces.size>0){D.push("// Namespace exports");let u=Array.from(this.namespaces.entries()).sort();for(let[C,E]of u)D.push(`export * as ${C} from './${E}';`);D.push("")}if(this.footer)D.push(this.footer);return`${D.join(`
10
+ `).replace(/\t/g,this.options.formatting?.useTabs?" ":" ".repeat(this.options.formatting?.indentSize||2)).trim()}async validateContent(e){if(this.options.validation==="none")return;let t=[],r=(e.match(/\{/g)||[]).length,i=(e.match(/\}/g)||[]).length;r!==i&&t.push(`Unmatched braces: ${r} open, ${i} close`);let n=(e.match(/\(/g)||[]).length,o=(e.match(/\)/g)||[]).length;if(n!==o&&t.push(`Unmatched parentheses: ${n} open, ${o} close`),(this.config.filename.endsWith(".ts")||this.config.filename.endsWith(".tsx"))&&e.includes("interface")&&!e.match(/interface\s+\w+\s*\{/)&&t.push("Invalid interface syntax detected"),t.length>0&&this.options.validation==="strict")throw new w(`Content validation failed for ${this.config.filename}: ${t.join(", ")}`,"write",this.config.filename);t.length>0&&this.config.logger.warn(`Validation issues in ${this.config.filename}: ${t.join(", ")}`);}getContent(){return this.content}getImports(){return new Map(this.imports)}getExports(){return new Set(this.exports)}};});var Ke={};re(Ke,{DirectoryBuilder:()=>ke});var ke,We=N(()=>{ke=class s{config;files=new Map;subdirectories=new Map;indexBuilder;shouldClean=false;constructor(e){this.config=e;}withSubdirectory(e){let t=`${this.config.path}/${e}`,r=new s({path:t,fileManager:this.config.fileManager,logger:this.config.logger.child(`Dir:${e}`)});return this.subdirectories.set(e,r),r}withFiles(e){for(let[t,r]of Object.entries(e))this.files.set(t,r);return this}withFile(e,t){return this.files.set(e,t),this}withIndex(e){return this.indexBuilder=e,this}clean(){return this.shouldClean=true,this}async ensure(){return await this.config.fileManager.ensureDirectory(this.config.path),this}async save(){let e=[];this.shouldClean&&await this.config.fileManager.cleanDirectory(this.config.path),await this.ensure();let t=Array.from(this.files.entries()).map(async([r,i])=>{try{let n=await i.save();return e.push(n),n}catch(n){throw this.config.logger.error(`Failed to save file ${r}:`,n instanceof Error?n:void 0),n}});await Promise.all(t);for(let[r,i]of this.subdirectories)try{let n=await i.save();e.push(...n);}catch(n){throw this.config.logger.error(`Failed to save subdirectory ${r}:`,n instanceof Error?n:void 0),n}if(this.indexBuilder)try{let r=await this.indexBuilder.save();e.push(r);}catch(r){throw this.config.logger.error("Failed to save index file:",r instanceof Error?r:void 0),r}return this.config.logger.info(`Saved directory ${this.config.path} with ${e.length} files`),e}getFileList(){let e=[];for(let t of this.files.keys())e.push(`${this.config.path}/${t}`);for(let[t,r]of this.subdirectories){let i=r.getFileList();e.push(...i);}return this.indexBuilder&&e.push(`${this.config.path}/index.ts`),e.sort()}getStats(){let e=this.files.size;for(let t of this.subdirectories.values())e+=t.getStats().totalFiles;return this.indexBuilder&&(e+=1),{fileCount:this.files.size,subdirectoryCount:this.subdirectories.size,hasIndex:!!this.indexBuilder,totalFiles:e}}async wouldOverwrite(){let e=[];for(let t of this.files.keys()){let r=`${this.config.path}/${t}`;await this.config.fileManager.wouldOverwrite(r)&&e.push(r);}for(let t of this.subdirectories.values()){let r=await t.wouldOverwrite();e.push(...r);}if(this.indexBuilder){let t=`${this.config.path}/index.ts`;await this.config.fileManager.wouldOverwrite(t)&&e.push(t);}return e}getPath(){return this.config.path}getFiles(){return new Map(this.files)}getSubdirectories(){return new Map(this.subdirectories)}getIndexBuilder(){return this.indexBuilder}};});var Ze={};re(Ze,{IndexBuilder:()=>Fe});var Fe,Ye=N(()=>{Fe=class{config;exports=new Map;namespaces=new Map;reExports=new Map;header="";footer="";groupingFunction;sortFunction;constructor(e){this.config=e;}withExports(e,t){for(let r of e)this.exports.set(r,t);return this}withExport(e,t){return this.exports.set(e,t),this}withNamespaces(e){for(let[t,r]of Object.entries(e))this.namespaces.set(t,r);return this}withNamespace(e,t){return this.namespaces.set(e,t),this}withReExports(e){for(let t of e)this.reExports.set(t,t);return this}withReExport(e){return this.reExports.set(e,e),this}withHeader(e){return this.header=e,this}withFooter(e){return this.footer=e,this}groupBy(e){return this.groupingFunction=e,this}sortBy(e){return this.sortFunction=e,this}async autoDiscover(e){return this.config.logger.debug(`Auto-discovering exports in ${this.config.directory}`),this.config.logger.warn("Auto-discovery not yet implemented - manually add exports"),this}async save(){let e=this.generateContent(),t=`${this.config.directory}/index.ts`,r=await this.config.fileManager.writeFile(t,e);return this.config.logger.debug(`Generated index file: ${t}`),r.path}build(){return this.generateContent()}generateContent(){let e=[];if(this.header&&(e.push(this.header),e.push("")),this.reExports.size>0){e.push("// Re-exports");for(let r of this.reExports.values())e.push(`export * from './${r}';`);e.push("");}if(this.exports.size>0&&(this.groupingFunction?this.generateGroupedExports(e):this.generateSimpleExports(e),e.push("")),this.namespaces.size>0){e.push("// Namespace exports");let r=Array.from(this.namespaces.entries()).sort();for(let[i,n]of r)e.push(`export * as ${i} from './${n}';`);e.push("");}return this.footer&&e.push(this.footer),`${e.join(`
11
11
  `).replace(/\n{3,}/g,`
12
12
 
13
13
  `).trim()}
14
- `}generateSimpleExports(D){D.push("// Exports");let F=Array.from(this.exports.entries());if(this.sortFunction)F=F.sort(this.sortFunction);else F=F.sort(([C],[E])=>C.localeCompare(E));let u=new Map;for(let[C,E]of F){if(!u.has(E))u.set(E,[]);u.get(E)?.push(C)}for(let[C,E]of u){let B=E.sort();if(B.length===1)D.push(`export type { ${B[0]} } from './${C}';`);else if(B.length<=3)D.push(`export type { ${B.join(", ")} } from './${C}';`);else D.push("export type {"),B.forEach(($,Z)=>{let Q=Z===B.length-1;D.push(` ${$}${Q?"":","}`)}),D.push(`} from './${C}';`)}}generateGroupedExports(D){if(!this.groupingFunction)return;let F=new Map;for(let[C,E]of this.exports){let B=this.groupingFunction(C);if(!F.has(B))F.set(B,new Map);let $=F.get(B);if(!$.has(E))$.set(E,[]);$.get(E)?.push(C)}let u=Array.from(F.entries()).sort();for(let[C,E]of u){D.push(`// ${C}`);for(let[B,$]of E){let Z=$.sort();if(Z.length===1)D.push(`export type { ${Z[0]} } from './${B}';`);else D.push(`export type { ${Z.join(", ")} } from './${B}';`)}D.push("")}}getExports(){return new Map(this.exports)}getNamespaces(){return new Map(this.namespaces)}getReExports(){return new Map(this.reExports)}}import{notStrictEqual as Ou,strictEqual as Ju}from"assert";var b6={right:S6,center:v6};class Z1{constructor(D){var F;this.width=D.width,this.wrap=(F=D.wrap)!==null&&F!==void 0?F:!0,this.rows=[]}span(...D){let F=this.div(...D);F.span=!0}resetOutput(){this.rows=[]}div(...D){if(D.length===0)this.div("");if(this.wrap&&this.shouldApplyLayoutDSL(...D)&&typeof D[0]==="string")return this.applyLayoutDSL(D[0]);let F=D.map((u)=>{if(typeof u==="string")return this.colFromString(u);return u});return this.rows.push(F),F}shouldApplyLayoutDSL(...D){return D.length===1&&typeof D[0]==="string"&&/[\t\n]/.test(D[0])}applyLayoutDSL(D){let F=D.split(`
15
- `).map((C)=>C.split("\t")),u=0;return F.forEach((C)=>{if(C.length>1&&WD.stringWidth(C[0])>u)u=Math.min(Math.floor(this.width*0.5),WD.stringWidth(C[0]))}),F.forEach((C)=>{this.div(...C.map((E,B)=>{return{text:E.trim(),padding:this.measurePadding(E),width:B===0&&C.length>1?u:void 0}}))}),this.rows[this.rows.length-1]}colFromString(D){return{text:D,padding:this.measurePadding(D)}}measurePadding(D){let F=WD.stripAnsi(D);return[0,F.match(/\s*$/)[0].length,0,F.match(/^\s*/)[0].length]}toString(){let D=[];return this.rows.forEach((F)=>{this.rowToString(F,D)}),D.filter((F)=>!F.hidden).map((F)=>F.text).join(`
16
- `)}rowToString(D,F){return this.rasterize(D).forEach((u,C)=>{let E="";u.forEach((B,$)=>{let{width:Z}=D[$],Q=this.negatePadding(D[$]),z=B;if(Q>WD.stringWidth(B))z+=" ".repeat(Q-WD.stringWidth(B));if(D[$].align&&D[$].align!=="left"&&this.wrap){let A=b6[D[$].align];if(z=A(z,Q),WD.stringWidth(z)<Q)z+=" ".repeat((Z||0)-WD.stringWidth(z)-1)}let O=D[$].padding||[0,0,0,0];if(O[3])E+=" ".repeat(O[3]);if(E+=$1(D[$],z,"| "),E+=z,E+=$1(D[$],z," |"),O[1])E+=" ".repeat(O[1]);if(C===0&&F.length>0)E=this.renderInline(E,F[F.length-1])}),F.push({text:E.replace(/ +$/,""),span:D.span})}),F}renderInline(D,F){let u=D.match(/^ */),C=u?u[0].length:0,E=F.text,B=WD.stringWidth(E.trimRight());if(!F.span)return D;if(!this.wrap)return F.hidden=!0,E+D;if(C<B)return D;return F.hidden=!0,E.trimRight()+" ".repeat(C-B)+D.trimLeft()}rasterize(D){let F=[],u=this.columnWidths(D),C;return D.forEach((E,B)=>{if(E.width=u[B],this.wrap)C=WD.wrap(E.text,this.negatePadding(E),{hard:!0}).split(`
17
- `);else C=E.text.split(`
18
- `);if(E.border)C.unshift("."+"-".repeat(this.negatePadding(E)+2)+"."),C.push("'"+"-".repeat(this.negatePadding(E)+2)+"'");if(E.padding)C.unshift(...Array(E.padding[0]||0).fill("")),C.push(...Array(E.padding[2]||0).fill(""));C.forEach(($,Z)=>{if(!F[Z])F.push([]);let Q=F[Z];for(let z=0;z<B;z++)if(Q[z]===void 0)Q.push("");Q.push($)})}),F}negatePadding(D){let F=D.width||0;if(D.padding)F-=(D.padding[3]||0)+(D.padding[1]||0);if(D.border)F-=4;return F}columnWidths(D){if(!this.wrap)return D.map((B)=>{return B.width||WD.stringWidth(B.text)});let F=D.length,u=this.width,C=D.map((B)=>{if(B.width)return F--,u-=B.width,B.width;return}),E=F?Math.floor(u/F):0;return C.map((B,$)=>{if(B===void 0)return Math.max(E,x6(D[$]));return B})}}function $1(D,F,u){if(D.border){if(/[.']-+[.']/.test(F))return"";if(F.trim().length!==0)return u;return" "}return""}function x6(D){let F=D.padding||[],u=1+(F[3]||0)+(F[1]||0);if(D.border)return u+4;return u}function P6(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function S6(D,F){D=D.trim();let u=WD.stringWidth(D);if(u<F)return" ".repeat(F-u)+D;return D}function v6(D,F){D=D.trim();let u=WD.stringWidth(D);if(u>=F)return D;return" ".repeat(F-u>>1)+D}var WD;function X1(D,F){return WD=F,new Z1({width:(D===null||D===void 0?void 0:D.width)||P6(),wrap:D===null||D===void 0?void 0:D.wrap})}function IF({onlyFirst:D=!1}={}){let u=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(u,D?void 0:"g")}var f6=IF();function mD(D){if(typeof D!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof D}\``);return D.replace(f6,"")}function Q1(D){return D===161||D===164||D===167||D===168||D===170||D===173||D===174||D>=176&&D<=180||D>=182&&D<=186||D>=188&&D<=191||D===198||D===208||D===215||D===216||D>=222&&D<=225||D===230||D>=232&&D<=234||D===236||D===237||D===240||D===242||D===243||D>=247&&D<=250||D===252||D===254||D===257||D===273||D===275||D===283||D===294||D===295||D===299||D>=305&&D<=307||D===312||D>=319&&D<=322||D===324||D>=328&&D<=331||D===333||D===338||D===339||D===358||D===359||D===363||D===462||D===464||D===466||D===468||D===470||D===472||D===474||D===476||D===593||D===609||D===708||D===711||D>=713&&D<=715||D===717||D===720||D>=728&&D<=731||D===733||D===735||D>=768&&D<=879||D>=913&&D<=929||D>=931&&D<=937||D>=945&&D<=961||D>=963&&D<=969||D===1025||D>=1040&&D<=1103||D===1105||D===8208||D>=8211&&D<=8214||D===8216||D===8217||D===8220||D===8221||D>=8224&&D<=8226||D>=8228&&D<=8231||D===8240||D===8242||D===8243||D===8245||D===8251||D===8254||D===8308||D===8319||D>=8321&&D<=8324||D===8364||D===8451||D===8453||D===8457||D===8467||D===8470||D===8481||D===8482||D===8486||D===8491||D===8531||D===8532||D>=8539&&D<=8542||D>=8544&&D<=8555||D>=8560&&D<=8569||D===8585||D>=8592&&D<=8601||D===8632||D===8633||D===8658||D===8660||D===8679||D===8704||D===8706||D===8707||D===8711||D===8712||D===8715||D===8719||D===8721||D===8725||D===8730||D>=8733&&D<=8736||D===8739||D===8741||D>=8743&&D<=8748||D===8750||D>=8756&&D<=8759||D===8764||D===8765||D===8776||D===8780||D===8786||D===8800||D===8801||D>=8804&&D<=8807||D===8810||D===8811||D===8814||D===8815||D===8834||D===8835||D===8838||D===8839||D===8853||D===8857||D===8869||D===8895||D===8978||D>=9312&&D<=9449||D>=9451&&D<=9547||D>=9552&&D<=9587||D>=9600&&D<=9615||D>=9618&&D<=9621||D===9632||D===9633||D>=9635&&D<=9641||D===9650||D===9651||D===9654||D===9655||D===9660||D===9661||D===9664||D===9665||D>=9670&&D<=9672||D===9675||D>=9678&&D<=9681||D>=9698&&D<=9701||D===9711||D===9733||D===9734||D===9737||D===9742||D===9743||D===9756||D===9758||D===9792||D===9794||D===9824||D===9825||D>=9827&&D<=9829||D>=9831&&D<=9834||D===9836||D===9837||D===9839||D===9886||D===9887||D===9919||D>=9926&&D<=9933||D>=9935&&D<=9939||D>=9941&&D<=9953||D===9955||D===9960||D===9961||D>=9963&&D<=9969||D===9972||D>=9974&&D<=9977||D===9979||D===9980||D===9982||D===9983||D===10045||D>=10102&&D<=10111||D>=11094&&D<=11097||D>=12872&&D<=12879||D>=57344&&D<=63743||D>=65024&&D<=65039||D===65533||D>=127232&&D<=127242||D>=127248&&D<=127277||D>=127280&&D<=127337||D>=127344&&D<=127373||D===127375||D===127376||D>=127387&&D<=127404||D>=917760&&D<=917999||D>=983040&&D<=1048573||D>=1048576&&D<=1114109}function z1(D){return D===12288||D>=65281&&D<=65376||D>=65504&&D<=65510}function Y1(D){return D>=4352&&D<=4447||D===8986||D===8987||D===9001||D===9002||D>=9193&&D<=9196||D===9200||D===9203||D===9725||D===9726||D===9748||D===9749||D>=9776&&D<=9783||D>=9800&&D<=9811||D===9855||D>=9866&&D<=9871||D===9875||D===9889||D===9898||D===9899||D===9917||D===9918||D===9924||D===9925||D===9934||D===9940||D===9962||D===9970||D===9971||D===9973||D===9978||D===9981||D===9989||D===9994||D===9995||D===10024||D===10060||D===10062||D>=10067&&D<=10069||D===10071||D>=10133&&D<=10135||D===10160||D===10175||D===11035||D===11036||D===11088||D===11093||D>=11904&&D<=11929||D>=11931&&D<=12019||D>=12032&&D<=12245||D>=12272&&D<=12287||D>=12289&&D<=12350||D>=12353&&D<=12438||D>=12441&&D<=12543||D>=12549&&D<=12591||D>=12593&&D<=12686||D>=12688&&D<=12773||D>=12783&&D<=12830||D>=12832&&D<=12871||D>=12880&&D<=42124||D>=42128&&D<=42182||D>=43360&&D<=43388||D>=44032&&D<=55203||D>=63744&&D<=64255||D>=65040&&D<=65049||D>=65072&&D<=65106||D>=65108&&D<=65126||D>=65128&&D<=65131||D>=94176&&D<=94180||D===94192||D===94193||D>=94208&&D<=100343||D>=100352&&D<=101589||D>=101631&&D<=101640||D>=110576&&D<=110579||D>=110581&&D<=110587||D===110589||D===110590||D>=110592&&D<=110882||D===110898||D>=110928&&D<=110930||D===110933||D>=110948&&D<=110951||D>=110960&&D<=111355||D>=119552&&D<=119638||D>=119648&&D<=119670||D===126980||D===127183||D===127374||D>=127377&&D<=127386||D>=127488&&D<=127490||D>=127504&&D<=127547||D>=127552&&D<=127560||D===127568||D===127569||D>=127584&&D<=127589||D>=127744&&D<=127776||D>=127789&&D<=127797||D>=127799&&D<=127868||D>=127870&&D<=127891||D>=127904&&D<=127946||D>=127951&&D<=127955||D>=127968&&D<=127984||D===127988||D>=127992&&D<=128062||D===128064||D>=128066&&D<=128252||D>=128255&&D<=128317||D>=128331&&D<=128334||D>=128336&&D<=128359||D===128378||D===128405||D===128406||D===128420||D>=128507&&D<=128591||D>=128640&&D<=128709||D===128716||D>=128720&&D<=128722||D>=128725&&D<=128727||D>=128732&&D<=128735||D===128747||D===128748||D>=128756&&D<=128764||D>=128992&&D<=129003||D===129008||D>=129292&&D<=129338||D>=129340&&D<=129349||D>=129351&&D<=129535||D>=129648&&D<=129660||D>=129664&&D<=129673||D>=129679&&D<=129734||D>=129742&&D<=129756||D>=129759&&D<=129769||D>=129776&&D<=129784||D>=131072&&D<=196605||D>=196608&&D<=262141}function k6(D){if(!Number.isSafeInteger(D))throw TypeError(`Expected a code point, got \`${typeof D}\`.`)}function O1(D,{ambiguousAsWide:F=!1}={}){if(k6(D),z1(D)||Y1(D)||F&&Q1(D))return 2;return 1}var A1=b0(W1(),1),y6=new Intl.Segmenter,h6=/^\p{Default_Ignorable_Code_Point}$/u;function RD(D,F={}){if(typeof D!=="string"||D.length===0)return 0;let{ambiguousIsNarrow:u=!0,countAnsiEscapeCodes:C=!1}=F;if(!C)D=mD(D);if(D.length===0)return 0;let E=0,B={ambiguousAsWide:!u};for(let{segment:$}of y6.segment(D)){let Z=$.codePointAt(0);if(Z<=31||Z>=127&&Z<=159)continue;if(Z>=8203&&Z<=8207||Z===65279)continue;if(Z>=768&&Z<=879||Z>=6832&&Z<=6911||Z>=7616&&Z<=7679||Z>=8400&&Z<=8447||Z>=65056&&Z<=65071)continue;if(Z>=55296&&Z<=57343)continue;if(Z>=65024&&Z<=65039)continue;if(h6.test($))continue;if(A1.default().test($)){E+=2;continue}E+=O1(Z,B)}return E}var G1=(D=0)=>(F)=>`\x1B[${F+D}m`,H1=(D=0)=>(F)=>`\x1B[${38+D};5;${F}m`,q1=(D=0)=>(F,u,C)=>`\x1B[${38+D};2;${F};${u};${C}m`,r={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},WC=Object.keys(r.modifier),d6=Object.keys(r.color),p6=Object.keys(r.bgColor),AC=[...d6,...p6];function g6(){let D=new Map;for(let[F,u]of Object.entries(r)){for(let[C,E]of Object.entries(u))r[C]={open:`\x1B[${E[0]}m`,close:`\x1B[${E[1]}m`},u[C]=r[C],D.set(E[0],E[1]);Object.defineProperty(r,F,{value:u,enumerable:!1})}return Object.defineProperty(r,"codes",{value:D,enumerable:!1}),r.color.close="\x1B[39m",r.bgColor.close="\x1B[49m",r.color.ansi=G1(),r.color.ansi256=H1(),r.color.ansi16m=q1(),r.bgColor.ansi=G1(10),r.bgColor.ansi256=H1(10),r.bgColor.ansi16m=q1(10),Object.defineProperties(r,{rgbToAnsi256:{value:(F,u,C)=>{if(F===u&&u===C){if(F<8)return 16;if(F>248)return 231;return Math.round((F-8)/247*24)+232}return 16+36*Math.round(F/255*5)+6*Math.round(u/255*5)+Math.round(C/255*5)},enumerable:!1},hexToRgb:{value:(F)=>{let u=/[a-f\d]{6}|[a-f\d]{3}/i.exec(F.toString(16));if(!u)return[0,0,0];let[C]=u;if(C.length===3)C=[...C].map((B)=>B+B).join("");let E=Number.parseInt(C,16);return[E>>16&255,E>>8&255,E&255]},enumerable:!1},hexToAnsi256:{value:(F)=>r.rgbToAnsi256(...r.hexToRgb(F)),enumerable:!1},ansi256ToAnsi:{value:(F)=>{if(F<8)return 30+F;if(F<16)return 90+(F-8);let u,C,E;if(F>=232)u=((F-232)*10+8)/255,C=u,E=u;else{F-=16;let Z=F%36;u=Math.floor(F/36)/5,C=Math.floor(Z/6)/5,E=Z%6/5}let B=Math.max(u,C,E)*2;if(B===0)return 30;let $=30+(Math.round(E)<<2|Math.round(C)<<1|Math.round(u));if(B===2)$+=60;return $},enumerable:!1},rgbToAnsi:{value:(F,u,C)=>r.ansi256ToAnsi(r.rgbToAnsi256(F,u,C)),enumerable:!1},hexToAnsi:{value:(F)=>r.ansi256ToAnsi(r.hexToAnsi256(F)),enumerable:!1}}),r}var m6=g6(),_1=m6;var P0=new Set(["\x1B","›"]),c6=39,NF="\x07",K1="[",l6="]",R1="m",x0=`${l6}8;;`,M1=(D)=>`${P0.values().next().value}${K1}${D}${R1}`,V1=(D)=>`${P0.values().next().value}${x0}${D}${NF}`,o6=(D)=>D.split(" ").map((F)=>RD(F)),LF=(D,F,u)=>{let C=[...F],E=!1,B=!1,$=RD(mD(D.at(-1)));for(let[Z,Q]of C.entries()){let z=RD(Q);if($+z<=u)D[D.length-1]+=Q;else D.push(Q),$=0;if(P0.has(Q))E=!0,B=C.slice(Z+1,Z+1+x0.length).join("")===x0;if(E){if(B){if(Q===NF)E=!1,B=!1}else if(Q===R1)E=!1;continue}if($+=z,$===u&&Z<C.length-1)D.push(""),$=0}if(!$&&D.at(-1).length>0&&D.length>1)D[D.length-2]+=D.pop()},n6=(D)=>{let F=D.split(" "),u=F.length;while(u>0){if(RD(F[u-1])>0)break;u--}if(u===F.length)return D;return F.slice(0,u).join(" ")+F.slice(u).join("")},i6=(D,F,u={})=>{if(u.trim!==!1&&D.trim()==="")return"";let C="",E,B,$=o6(D),Z=[""];for(let[A,J]of D.split(" ").entries()){if(u.trim!==!1)Z[Z.length-1]=Z.at(-1).trimStart();let W=RD(Z.at(-1));if(A!==0){if(W>=F&&(u.wordWrap===!1||u.trim===!1))Z.push(""),W=0;if(W>0||u.trim===!1)Z[Z.length-1]+=" ",W++}if(u.hard&&$[A]>F){let _=F-W,q=1+Math.floor(($[A]-_-1)/F);if(Math.floor(($[A]-1)/F)<q)Z.push("");LF(Z,J,F);continue}if(W+$[A]>F&&W>0&&$[A]>0){if(u.wordWrap===!1&&W<F){LF(Z,J,F);continue}Z.push("")}if(W+$[A]>F&&u.wordWrap===!1){LF(Z,J,F);continue}Z[Z.length-1]+=J}if(u.trim!==!1)Z=Z.map((A)=>n6(A));let Q=Z.join(`
19
- `),z=[...Q],O=0;for(let[A,J]of z.entries()){if(C+=J,P0.has(J)){let{groups:_}=new RegExp(`(?:\\${K1}(?<code>\\d+)m|\\${x0}(?<uri>.*)${NF})`).exec(Q.slice(O))||{groups:{}};if(_.code!==void 0){let q=Number.parseFloat(_.code);E=q===c6?void 0:q}else if(_.uri!==void 0)B=_.uri.length===0?void 0:_.uri}let W=_1.codes.get(Number(E));if(z[A+1]===`
20
- `){if(B)C+=V1("");if(E&&W)C+=M1(W)}else if(J===`
21
- `){if(E&&W)C+=M1(E);if(B)C+=V1(B)}O+=J.length}return C};function TF(D,F,u){return String(D).normalize().replaceAll(`\r
22
- `,`
23
- `).split(`
24
- `).map((C)=>i6(C,F,u)).join(`
25
- `)}function wF(D){return X1(D,{stringWidth:RD,stripAnsi:mD,wrap:TF})}import{dirname as U1,resolve as j1}from"path";import{readdirSync as t6,statSync as s6}from"fs";function bF(D,F){let u=j1(".",D),C;if(!s6(u).isDirectory())u=U1(u);while(!0){if(C=F(u,t6(u)),C)return j1(u,C);if(u=U1(C=u),C===u)break}}import{inspect as Wu}from"util";import{fileURLToPath as g1}from"url";import{format as e6}from"util";import{normalize as Du,resolve as Fu}from"path";function cD(D){if(!(D!==D.toLowerCase()&&D!==D.toUpperCase()))D=D.toLowerCase();if(D.indexOf("-")===-1&&D.indexOf("_")===-1)return D;else{let u="",C=!1,E=D.match(/^-+/);for(let B=E?E[0].length:0;B<D.length;B++){let $=D.charAt(B);if(C)C=!1,$=$.toUpperCase();if(B!==0&&($==="-"||$==="_"))C=!0;else if($!=="-"&&$!=="_")u+=$}return u}}function S0(D,F){let u=D.toLowerCase();F=F||"-";let C="";for(let E=0;E<D.length;E++){let B=u.charAt(E),$=D.charAt(E);if(B!==$&&E>0)C+=`${F}${u.charAt(E)}`;else C+=$}return C}function v0(D){if(D===null||D===void 0)return!1;if(typeof D==="number")return!0;if(/^0x[0-9a-f]+$/i.test(D))return!0;if(/^0[^.]/.test(D))return!1;return/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(D)}function I1(D){if(Array.isArray(D))return D.map(($)=>typeof $!=="string"?$+"":$);D=D.trim();let F=0,u=null,C=null,E=null,B=[];for(let $=0;$<D.length;$++){if(u=C,C=D.charAt($),C===" "&&!E){if(u!==" ")F++;continue}if(C===E)E=null;else if((C==="'"||C==='"')&&!E)E=C;if(!B[F])B[F]="";B[F]+=C}return B}var qD;(function(D){D.BOOLEAN="boolean",D.STRING="string",D.NUMBER="number",D.ARRAY="array"})(qD||(qD={}));var bD;class PF{constructor(D){bD=D}parse(D,F){let u=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},F),C=I1(D),E=typeof D==="string",B=r6(Object.assign(Object.create(null),u.alias)),$=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":"no-","parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},u.configuration),Z=Object.assign(Object.create(null),u.default),Q=u.configObjects||[],z=u.envPrefix,O=$["populate--"],A=O?"--":"_",J=Object.create(null),W=Object.create(null),_=u.__||bD.format,q={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},P=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,c=new RegExp("^--"+$["negation-prefix"]+"(.+)");if([].concat(u.array||[]).filter(Boolean).forEach(function(Y){let H=typeof Y==="object"?Y.key:Y,V=Object.keys(Y).map(function(M){return{boolean:"bools",string:"strings",number:"numbers"}[M]}).filter(Boolean).pop();if(V)q[V][H]=!0;q.arrays[H]=!0,q.keys.push(H)}),[].concat(u.boolean||[]).filter(Boolean).forEach(function(Y){q.bools[Y]=!0,q.keys.push(Y)}),[].concat(u.string||[]).filter(Boolean).forEach(function(Y){q.strings[Y]=!0,q.keys.push(Y)}),[].concat(u.number||[]).filter(Boolean).forEach(function(Y){q.numbers[Y]=!0,q.keys.push(Y)}),[].concat(u.count||[]).filter(Boolean).forEach(function(Y){q.counts[Y]=!0,q.keys.push(Y)}),[].concat(u.normalize||[]).filter(Boolean).forEach(function(Y){q.normalize[Y]=!0,q.keys.push(Y)}),typeof u.narg==="object")Object.entries(u.narg).forEach(([Y,H])=>{if(typeof H==="number")q.nargs[Y]=H,q.keys.push(Y)});if(typeof u.coerce==="object")Object.entries(u.coerce).forEach(([Y,H])=>{if(typeof H==="function")q.coercions[Y]=H,q.keys.push(Y)});if(typeof u.config<"u"){if(Array.isArray(u.config)||typeof u.config==="string")[].concat(u.config).filter(Boolean).forEach(function(Y){q.configs[Y]=!0});else if(typeof u.config==="object")Object.entries(u.config).forEach(([Y,H])=>{if(typeof H==="boolean"||typeof H==="function")q.configs[Y]=H})}H0(u.key,B,u.default,q.arrays),Object.keys(Z).forEach(function(Y){(q.aliases[Y]||[]).forEach(function(H){Z[H]=Z[Y]})});let p=null;VF();let QD=[],d=Object.assign(Object.create(null),{_:[]}),U={};for(let Y=0;Y<C.length;Y++){let H=C[Y],V=H.replace(/^-{3,}/,"---"),M,G,T,R,x,ZD;if(H!=="--"&&/^-/.test(H)&&i(H))j(H);else if(V.match(/^---+(=|$)/)){j(H);continue}else if(H.match(/^--.+=/)||!$["short-option-groups"]&&H.match(/^-.+=/)){if(R=H.match(/^--?([^=]+)=([\s\S]*)$/),R!==null&&Array.isArray(R)&&R.length>=3)if(v(R[1],q.arrays))Y=l(Y,R[1],C,R[2]);else if(v(R[1],q.nargs)!==!1)Y=S(Y,R[1],C,R[2]);else g(R[1],R[2],!0)}else if(H.match(c)&&$["boolean-negation"]){if(R=H.match(c),R!==null&&Array.isArray(R)&&R.length>=2)G=R[1],g(G,v(G,q.arrays)?[!1]:!1)}else if(H.match(/^--.+/)||!$["short-option-groups"]&&H.match(/^-[^-]+/)){if(R=H.match(/^--?(.+)/),R!==null&&Array.isArray(R)&&R.length>=2)if(G=R[1],v(G,q.arrays))Y=l(Y,G,C);else if(v(G,q.nargs)!==!1)Y=S(Y,G,C);else if(x=C[Y+1],x!==void 0&&(!x.match(/^-/)||x.match(P))&&!v(G,q.bools)&&!v(G,q.counts))g(G,x),Y++;else if(/^(true|false)$/.test(x))g(G,x),Y++;else g(G,m(G))}else if(H.match(/^-.\..+=/)){if(R=H.match(/^-([^=]+)=([\s\S]*)$/),R!==null&&Array.isArray(R)&&R.length>=3)g(R[1],R[2])}else if(H.match(/^-.\..+/)&&!H.match(P)){if(x=C[Y+1],R=H.match(/^-(.\..+)/),R!==null&&Array.isArray(R)&&R.length>=2)if(G=R[1],x!==void 0&&!x.match(/^-/)&&!v(G,q.bools)&&!v(G,q.counts))g(G,x),Y++;else g(G,m(G))}else if(H.match(/^-[^-]+/)&&!H.match(P)){T=H.slice(1,-1).split(""),M=!1;for(let YD=0;YD<T.length;YD++){if(x=H.slice(YD+2),T[YD+1]&&T[YD+1]==="="){if(ZD=H.slice(YD+3),G=T[YD],v(G,q.arrays))Y=l(Y,G,C,ZD);else if(v(G,q.nargs)!==!1)Y=S(Y,G,C,ZD);else g(G,ZD);M=!0;break}if(x==="-"){g(T[YD],x);continue}if(/[A-Za-z]/.test(T[YD])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(x)&&v(x,q.bools)===!1){g(T[YD],x),M=!0;break}if(T[YD+1]&&T[YD+1].match(/\W/)){g(T[YD],x),M=!0;break}else g(T[YD],m(T[YD]))}if(G=H.slice(-1)[0],!M&&G!=="-")if(v(G,q.arrays))Y=l(Y,G,C);else if(v(G,q.nargs)!==!1)Y=S(Y,G,C);else if(x=C[Y+1],x!==void 0&&(!/^(-|--)[^-]/.test(x)||x.match(P))&&!v(G,q.bools)&&!v(G,q.counts))g(G,x),Y++;else if(/^(true|false)$/.test(x))g(G,x),Y++;else g(G,m(G))}else if(H.match(/^-[0-9]$/)&&H.match(P)&&v(H.slice(1),q.bools))G=H.slice(1),g(G,m(G));else if(H==="--"){QD=C.slice(Y+1);break}else if($["halt-at-non-option"]){QD=C.slice(Y);break}else j(H)}if(uD(d,!0),uD(d,!1),w(d),n(),PD(d,q.aliases,Z,!0),o(d),$["set-placeholder-key"])CD(d);if(Object.keys(q.counts).forEach(function(Y){if(!t(d,Y.split(".")))g(Y,0)}),O&&QD.length)d[A]=[];if(QD.forEach(function(Y){d[A].push(Y)}),$["camel-case-expansion"]&&$["strip-dashed"])Object.keys(d).filter((Y)=>Y!=="--"&&Y.includes("-")).forEach((Y)=>{delete d[Y]});if($["strip-aliased"])[].concat(...Object.keys(B).map((Y)=>B[Y])).forEach((Y)=>{if($["camel-case-expansion"]&&Y.includes("-"))delete d[Y.split(".").map((H)=>cD(H)).join(".")];delete d[Y]});function j(Y){let H=K("_",Y);if(typeof H==="string"||typeof H==="number")d._.push(H)}function S(Y,H,V,M){let G,T=v(H,q.nargs);if(T=typeof T!=="number"||isNaN(T)?1:T,T===0){if(!BD(M))p=Error(_("Argument unexpected for: %s",H));return g(H,m(H)),Y}let R=BD(M)?0:1;if($["nargs-eats-options"]){if(V.length-(Y+1)+R<T)p=Error(_("Not enough arguments following: %s",H));R=T}else{for(G=Y+1;G<V.length;G++)if(!V[G].match(/^-[^0-9]/)||V[G].match(P)||i(V[G]))R++;else break;if(R<T)p=Error(_("Not enough arguments following: %s",H))}let x=Math.min(R,T);if(!BD(M)&&x>0)g(H,M),x--;for(G=Y+1;G<x+Y+1;G++)g(H,V[G]);return Y+x}function l(Y,H,V,M){let G=[],T=M||V[Y+1],R=v(H,q.nargs);if(v(H,q.bools)&&!/^(true|false)$/.test(T))G.push(!0);else if(BD(T)||BD(M)&&/^-/.test(T)&&!P.test(T)&&!i(T)){if(Z[H]!==void 0){let x=Z[H];G=Array.isArray(x)?x:[x]}}else{if(!BD(M))G.push(I(H,M,!0));for(let x=Y+1;x<V.length;x++){if(!$["greedy-arrays"]&&G.length>0||R&&typeof R==="number"&&G.length>=R)break;if(T=V[x],/^-/.test(T)&&!P.test(T)&&!i(T))break;Y=x,G.push(I(H,T,E))}}if(typeof R==="number"&&(R&&G.length<R||isNaN(R)&&G.length===0))p=Error(_("Not enough arguments following: %s",H));return g(H,G),Y}function g(Y,H,V=E){if(/-/.test(Y)&&$["camel-case-expansion"]){let T=Y.split(".").map(function(R){return cD(R)}).join(".");LD(Y,T)}let M=I(Y,H,V),G=Y.split(".");if(wD(d,G,M),q.aliases[Y])q.aliases[Y].forEach(function(T){let R=T.split(".");wD(d,R,M)});if(G.length>1&&$["dot-notation"])(q.aliases[G[0]]||[]).forEach(function(T){let R=T.split("."),x=[].concat(G);if(x.shift(),R=R.concat(x),!(q.aliases[Y]||[]).includes(R.join(".")))wD(d,R,M)});if(v(Y,q.normalize)&&!v(Y,q.arrays))[Y].concat(q.aliases[Y]||[]).forEach(function(R){Object.defineProperty(U,R,{enumerable:!0,get(){return H},set(x){H=typeof x==="string"?bD.normalize(x):x}})})}function LD(Y,H){if(!(q.aliases[Y]&&q.aliases[Y].length))q.aliases[Y]=[H],J[H]=!0;if(!(q.aliases[H]&&q.aliases[H].length))LD(H,Y)}function I(Y,H,V){if(V)H=a6(H);if(v(Y,q.bools)||v(Y,q.counts)){if(typeof H==="string")H=H==="true"}let M=Array.isArray(H)?H.map(function(G){return K(Y,G)}):K(Y,H);if(v(Y,q.counts)&&(BD(M)||typeof M==="boolean"))M=xF();if(v(Y,q.normalize)&&v(Y,q.arrays))if(Array.isArray(H))M=H.map((G)=>{return bD.normalize(G)});else M=bD.normalize(H);return M}function K(Y,H){if(!$["parse-positional-numbers"]&&Y==="_")return H;if(!v(Y,q.strings)&&!v(Y,q.bools)&&!Array.isArray(H)){if(v0(H)&&$["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${H}`)))||!BD(H)&&v(Y,q.numbers))H=Number(H)}return H}function w(Y){let H=Object.create(null);PD(H,q.aliases,Z),Object.keys(q.configs).forEach(function(V){let M=Y[V]||H[V];if(M)try{let G=null,T=bD.resolve(bD.cwd(),M),R=q.configs[V];if(typeof R==="function"){try{G=R(T)}catch(x){G=x}if(G instanceof Error){p=G;return}}else G=bD.require(T);y(G)}catch(G){if(G.name==="PermissionDenied")p=G;else if(Y[V])p=Error(_("Invalid JSON config file: %s",M))}})}function y(Y,H){Object.keys(Y).forEach(function(V){let M=Y[V],G=H?H+"."+V:V;if(typeof M==="object"&&M!==null&&!Array.isArray(M)&&$["dot-notation"])y(M,G);else if(!t(d,G.split("."))||v(G,q.arrays)&&$["combine-arrays"])g(G,M)})}function n(){if(typeof Q<"u")Q.forEach(function(Y){y(Y)})}function uD(Y,H){if(typeof z>"u")return;let V=typeof z==="string"?z:"",M=bD.env();Object.keys(M).forEach(function(G){if(V===""||G.lastIndexOf(V,0)===0){let T=G.split("__").map(function(R,x){if(x===0)R=R.substring(V.length);return cD(R)});if((H&&q.configs[T.join(".")]||!H)&&!t(Y,T))g(T.join("."),M[G])}})}function o(Y){let H,V=new Set;Object.keys(Y).forEach(function(M){if(!V.has(M)){if(H=v(M,q.coercions),typeof H==="function")try{let G=K(M,H(Y[M]));[].concat(q.aliases[M]||[],M).forEach((T)=>{V.add(T),Y[T]=G})}catch(G){p=G}}})}function CD(Y){return q.keys.forEach((H)=>{if(~H.indexOf("."))return;if(typeof Y[H]>"u")Y[H]=void 0}),Y}function PD(Y,H,V,M=!1){Object.keys(V).forEach(function(G){if(!t(Y,G.split("."))){if(wD(Y,G.split("."),V[G]),M)W[G]=!0;(H[G]||[]).forEach(function(T){if(t(Y,T.split(".")))return;wD(Y,T.split("."),V[G])})}})}function t(Y,H){let V=Y;if(!$["dot-notation"])H=[H.join(".")];H.slice(0,-1).forEach(function(G){V=V[G]||{}});let M=H[H.length-1];if(typeof V!=="object")return!1;else return M in V}function wD(Y,H,V){let M=Y;if(!$["dot-notation"])H=[H.join(".")];H.slice(0,-1).forEach(function(ZD){if(ZD=L1(ZD),typeof M==="object"&&M[ZD]===void 0)M[ZD]={};if(typeof M[ZD]!=="object"||Array.isArray(M[ZD])){if(Array.isArray(M[ZD]))M[ZD].push({});else M[ZD]=[M[ZD],{}];M=M[ZD][M[ZD].length-1]}else M=M[ZD]});let G=L1(H[H.length-1]),T=v(H.join("."),q.arrays),R=Array.isArray(V),x=$["duplicate-arguments-array"];if(!x&&v(G,q.nargs)){if(x=!0,!BD(M[G])&&q.nargs[G]===1||Array.isArray(M[G])&&M[G].length===q.nargs[G])M[G]=void 0}if(V===xF())M[G]=xF(M[G]);else if(Array.isArray(M[G]))if(x&&T&&R)M[G]=$["flatten-duplicate-arrays"]?M[G].concat(V):(Array.isArray(M[G][0])?M[G]:[M[G]]).concat([V]);else if(!x&&Boolean(T)===Boolean(R))M[G]=V;else M[G]=M[G].concat([V]);else if(M[G]===void 0&&T)M[G]=R?V:[V];else if(x&&!(M[G]===void 0||v(G,q.counts)||v(G,q.bools)))M[G]=[M[G],V];else M[G]=V}function H0(...Y){Y.forEach(function(H){Object.keys(H||{}).forEach(function(V){if(q.aliases[V])return;q.aliases[V]=[].concat(B[V]||[]),q.aliases[V].concat(V).forEach(function(M){if(/-/.test(M)&&$["camel-case-expansion"]){let G=cD(M);if(G!==V&&q.aliases[V].indexOf(G)===-1)q.aliases[V].push(G),J[G]=!0}}),q.aliases[V].concat(V).forEach(function(M){if(M.length>1&&/[A-Z]/.test(M)&&$["camel-case-expansion"]){let G=S0(M,"-");if(G!==V&&q.aliases[V].indexOf(G)===-1)q.aliases[V].push(G),J[G]=!0}}),q.aliases[V].forEach(function(M){q.aliases[M]=[V].concat(q.aliases[V].filter(function(G){return M!==G}))})})})}function v(Y,H){let V=[].concat(q.aliases[Y]||[],Y),M=Object.keys(H),G=V.find((T)=>M.includes(T));return G?H[G]:!1}function Q0(Y){let H=Object.keys(q);return[].concat(H.map((M)=>q[M])).some(function(M){return Array.isArray(M)?M.includes(Y):M[Y]})}function F1(Y,...H){return[].concat(...H).some(function(M){let G=Y.match(M);return G&&Q0(G[1])})}function f(Y){if(Y.match(P)||!Y.match(/^-[^-]+/))return!1;let H=!0,V,M=Y.slice(1).split("");for(let G=0;G<M.length;G++){if(V=Y.slice(G+2),!Q0(M[G])){H=!1;break}if(M[G+1]&&M[G+1]==="="||V==="-"||/[A-Za-z]/.test(M[G])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(V)||M[G+1]&&M[G+1].match(/\W/))break}return H}function i(Y){return $["unknown-options-as-args"]&&ED(Y)}function ED(Y){if(Y=Y.replace(/^-{3,}/,"--"),Y.match(P))return!1;if(f(Y))return!1;return!F1(Y,/^-+([^=]+?)=[\s\S]*$/,c,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function m(Y){if(!v(Y,q.bools)&&!v(Y,q.counts)&&`${Y}`in Z)return Z[Y];else return zD(e(Y))}function zD(Y){return{[qD.BOOLEAN]:!0,[qD.STRING]:"",[qD.NUMBER]:void 0,[qD.ARRAY]:[]}[Y]}function e(Y){let H=qD.BOOLEAN;if(v(Y,q.strings))H=qD.STRING;else if(v(Y,q.numbers))H=qD.NUMBER;else if(v(Y,q.bools))H=qD.BOOLEAN;else if(v(Y,q.arrays))H=qD.ARRAY;return H}function BD(Y){return Y===void 0}function VF(){Object.keys(q.counts).find((Y)=>{if(v(Y,q.arrays))return p=Error(_("Invalid configuration: %s, opts.count excludes opts.array.",Y)),!0;else if(v(Y,q.nargs))return p=Error(_("Invalid configuration: %s, opts.count excludes opts.narg.",Y)),!0;return!1})}return{aliases:Object.assign({},q.aliases),argv:Object.assign(U,d),configuration:$,defaulted:Object.assign({},W),error:p,newAliases:Object.assign({},J)}}}function r6(D){let F=[],u=Object.create(null),C=!0;Object.keys(D).forEach(function(E){F.push([].concat(D[E],E))});while(C){C=!1;for(let E=0;E<F.length;E++)for(let B=E+1;B<F.length;B++)if(F[E].filter(function(Z){return F[B].indexOf(Z)!==-1}).length){F[E]=F[E].concat(F[B]),F.splice(B,1),C=!0;break}}return F.forEach(function(E){E=E.filter(function($,Z,Q){return Q.indexOf($)===Z});let B=E.pop();if(B!==void 0&&typeof B==="string")u[B]=E}),u}function xF(D){return D!==void 0?D+1:1}function L1(D){if(D==="__proto__")return"___proto___";return D}function a6(D){return typeof D==="string"&&(D[0]==="'"||D[0]==='"')&&D[D.length-1]===D[0]?D.substring(1,D.length-1):D}import{readFileSync as uu}from"fs";import{createRequire as N1}from"node:module";var SF,vF,fF,T1=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,w1=(vF=(SF=process===null||process===void 0?void 0:process.versions)===null||SF===void 0?void 0:SF.node)!==null&&vF!==void 0?vF:(fF=process===null||process===void 0?void 0:process.version)===null||fF===void 0?void 0:fF.slice(1);if(w1){if(Number(w1.match(/^([^.]+)/)[1])<T1)throw Error(`yargs parser supports a minimum Node.js version of ${T1}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var Cu=process?process.env:{},b1=N1?N1(import.meta.url):void 0,x1=new PF({cwd:process.cwd,env:()=>{return Cu},format:e6,normalize:Du,resolve:Fu,require:(D)=>{if(typeof b1<"u")return b1(D);else if(D.match(/\.json$/))return JSON.parse(uu(D,"utf8"));else throw Error("only .json config files are supported in ESM")}}),_0=function(F,u){return x1.parse(F.slice(),u).argv};_0.detailed=function(D,F){return x1.parse(D.slice(),F)};_0.camelCase=cD;_0.decamelize=S0;_0.looksLikeNumber=v0;var kF=_0;import{basename as Au,dirname as Gu,extname as Hu,relative as qu,resolve as p1,join as _u}from"path";function P1(){if(Eu())return 0;return 1}function Eu(){return Bu()&&!process.defaultApp}function Bu(){return!!process.versions.electron}function yF(D){return D.slice(P1()+1)}function S1(){return process.argv[P1()]}import{readFileSync as $u,statSync as Zu,writeFile as Xu}from"fs";import{format as Qu}from"util";import{resolve as zu}from"path";var v1={fs:{readFileSync:$u,writeFile:Xu},format:Qu,resolve:zu,exists:(D)=>{try{return Zu(D).isFile()}catch(F){return!1}}};var UD;class f1{constructor(D){D=D||{},this.directory=D.directory||"./locales",this.updateFiles=typeof D.updateFiles==="boolean"?D.updateFiles:!0,this.locale=D.locale||"en",this.fallbackToLanguage=typeof D.fallbackToLanguage==="boolean"?D.fallbackToLanguage:!0,this.cache=Object.create(null),this.writeQueue=[]}__(...D){if(typeof arguments[0]!=="string")return this._taggedLiteral(arguments[0],...arguments);let F=D.shift(),u=function(){};if(typeof D[D.length-1]==="function")u=D.pop();if(u=u||function(){},!this.cache[this.locale])this._readLocaleFile();if(!this.cache[this.locale][F]&&this.updateFiles)this.cache[this.locale][F]=F,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:u});else u();return UD.format.apply(UD.format,[this.cache[this.locale][F]||F].concat(D))}__n(){let D=Array.prototype.slice.call(arguments),F=D.shift(),u=D.shift(),C=D.shift(),E=function(){};if(typeof D[D.length-1]==="function")E=D.pop();if(!this.cache[this.locale])this._readLocaleFile();let B=C===1?F:u;if(this.cache[this.locale][F])B=this.cache[this.locale][F][C===1?"one":"other"];if(!this.cache[this.locale][F]&&this.updateFiles)this.cache[this.locale][F]={one:F,other:u},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:E});else E();let $=[B];if(~B.indexOf("%d"))$.push(C);return UD.format.apply(UD.format,$.concat(D))}setLocale(D){this.locale=D}getLocale(){return this.locale}updateLocale(D){if(!this.cache[this.locale])this._readLocaleFile();for(let F in D)if(Object.prototype.hasOwnProperty.call(D,F))this.cache[this.locale][F]=D[F]}_taggedLiteral(D,...F){let u="";return D.forEach(function(C,E){let B=F[E+1];if(u+=C,typeof B<"u")u+="%s"}),this.__.apply(this,[u].concat([].slice.call(F,1)))}_enqueueWrite(D){if(this.writeQueue.push(D),this.writeQueue.length===1)this._processWriteQueue()}_processWriteQueue(){let D=this,F=this.writeQueue[0],u=F.directory,C=F.locale,E=F.cb,B=this._resolveLocaleFile(u,C),$=JSON.stringify(this.cache[C],null,2);UD.fs.writeFile(B,$,"utf-8",function(Z){if(D.writeQueue.shift(),D.writeQueue.length>0)D._processWriteQueue();E(Z)})}_readLocaleFile(){let D={},F=this._resolveLocaleFile(this.directory,this.locale);try{if(UD.fs.readFileSync)D=JSON.parse(UD.fs.readFileSync(F,"utf-8"))}catch(u){if(u instanceof SyntaxError)u.message="syntax error in "+F;if(u.code==="ENOENT")D={};else throw u}this.cache[this.locale]=D}_resolveLocaleFile(D,F){let u=UD.resolve(D,"./",F+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(u)&&~F.lastIndexOf("_")){let C=UD.resolve(D,"./",F.split("_")[0]+".json");if(this._fileExistsSync(C))u=C}return u}_fileExistsSync(D){return UD.exists(D)}}function k1(D,F){UD=F;let u=new f1(D);return{__:u.__.bind(u),__n:u.__n.bind(u),setLocale:u.setLocale.bind(u),getLocale:u.getLocale.bind(u),updateLocale:u.updateLocale.bind(u),locale:u.locale}}var Yu=(D)=>{return k1(D,v1)},y1=Yu;var m1=b0(d1(),1);import{createRequire as Mu}from"node:module";import{readFileSync as Vu,readdirSync as Ku}from"node:fs";var hF=g1(import.meta.url),Ru=hF.substring(0,hF.lastIndexOf("node_modules")),Uu=Mu(import.meta.url),dF={assert:{notStrictEqual:Ou,strictEqual:Ju},cliui:wF,findUp:bF,getEnv:(D)=>{return process.env[D]},inspect:Wu,getProcessArgvBin:S1,mainFilename:Ru||process.cwd(),Parser:kF,path:{basename:Au,dirname:Gu,extname:Hu,relative:qu,resolve:p1,join:_u},process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(D,F)=>process.emitWarning(D,F),execPath:()=>process.execPath,exit:(D)=>{process.exit(D)},nextTick:process.nextTick,stdColumns:typeof process.stdout.columns<"u"?process.stdout.columns:null},readFileSync:Vu,readdirSync:Ku,require:Uu,getCallerFile:()=>{let D=m1.default(3);return D.match(/^file:\/\//)?g1(D):D},stringWidth:RD,y18n:y1({directory:p1(hF,"../../../locales"),updateFiles:!1})};function OD(D,F,u,C){u.assert.notStrictEqual(D,F,C)}function pF(D,F){F.assert.strictEqual(typeof D,"string")}function z0(D){return Object.keys(D)}function s(D){return!!D&&!!D.then&&typeof D.then==="function"}class DD extends Error{constructor(D){super(D||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,DD)}}function SD(D){let u=D.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),C=/\.*[\][<>]/g,E=u.shift();if(!E)throw Error(`No command found in: ${D}`);let B={cmd:E.replace(C,""),demanded:[],optional:[]};return u.forEach(($,Z)=>{let Q=!1;if($=$.replace(/\s/g,""),/\.+[\]>]/.test($)&&Z===u.length-1)Q=!0;if(/^\[/.test($))B.optional.push({cmd:$.replace(C,"").split("|"),variadic:Q});else B.demanded.push({cmd:$.replace(C,"").split("|"),variadic:Q})}),B}var ju=["first","second","third","fourth","fifth","sixth"];function L(D,F,u){function C(){return typeof D==="object"?[{demanded:[],optional:[]},D,F]:[SD(`cmd ${D}`),F,u]}try{let E=0,[B,$,Z]=C(),Q=[].slice.call($);while(Q.length&&Q[Q.length-1]===void 0)Q.pop();let z=Z||Q.length;if(z<B.demanded.length)throw new DD(`Not enough arguments provided. Expected ${B.demanded.length} but received ${Q.length}.`);let O=B.demanded.length+B.optional.length;if(z>O)throw new DD(`Too many arguments provided. Expected max ${O} but received ${z}.`);B.demanded.forEach((A)=>{let J=Q.shift(),W=c1(J);if(A.cmd.filter((q)=>q===W||q==="*").length===0)l1(W,A.cmd,E);E+=1}),B.optional.forEach((A)=>{if(Q.length===0)return;let J=Q.shift(),W=c1(J);if(A.cmd.filter((q)=>q===W||q==="*").length===0)l1(W,A.cmd,E);E+=1})}catch(E){console.warn(E.stack)}}function c1(D){if(Array.isArray(D))return"array";else if(D===null)return"null";return typeof D}function l1(D,F,u){throw new DD(`Invalid ${ju[u]||"manyith"} argument. Expected ${F.join(" or ")} but received ${D}.`)}class gF{constructor(D){this.globalMiddleware=[],this.frozens=[],this.yargs=D}addMiddleware(D,F,u=!0,C=!1){if(L("<array|function> [boolean] [boolean] [boolean]",[D,F,u],arguments.length),Array.isArray(D)){for(let E=0;E<D.length;E++){if(typeof D[E]!=="function")throw Error("middleware must be a function");let B=D[E];B.applyBeforeValidation=F,B.global=u}Array.prototype.push.apply(this.globalMiddleware,D)}else if(typeof D==="function"){let E=D;E.applyBeforeValidation=F,E.global=u,E.mutates=C,this.globalMiddleware.push(D)}return this.yargs}addCoerceMiddleware(D,F){let u=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((C)=>{let E=[...u[F]||[],F];if(!C.option)return!0;else return!E.includes(C.option)}),D.option=F,this.addMiddleware(D,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let D=this.frozens.pop();if(D!==void 0)this.globalMiddleware=D}reset(){this.globalMiddleware=this.globalMiddleware.filter((D)=>D.global)}}function o1(D){if(!D)return[];return D.map((F)=>{return F.applyBeforeValidation=!1,F})}function lD(D,F,u,C){return u.reduce((E,B)=>{if(B.applyBeforeValidation!==C)return E;if(B.mutates){if(B.applied)return E;B.applied=!0}if(s(E))return E.then(($)=>Promise.all([$,B($,F)])).then(([$,Z])=>Object.assign($,Z));else{let $=B(E,F);return s($)?$.then((Z)=>Object.assign(E,Z)):Object.assign(E,$)}},D)}function oD(D,F,u=(C)=>{throw C}){try{let C=Iu(D)?D():D;return s(C)?C.then((E)=>F(E)):F(C)}catch(C){return u(C)}}function Iu(D){return typeof D==="function"}var Y0=/(^\*)|(^\$0)/;class i1{constructor(D,F,u,C){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=C,this.usage=D,this.globalMiddleware=u,this.validation=F}addDirectory(D,F,u,C){C=C||{},this.requireCache.add(u);let E=this.shim.path.resolve(this.shim.path.dirname(u),D),B=this.shim.readdirSync(E,{recursive:C.recurse?!0:!1});if(!Array.isArray(C.extensions))C.extensions=["js"];let $=typeof C.visit==="function"?C.visit:(Z)=>Z;for(let Z of B){let Q=Z.toString();if(C.exclude){let O=!1;if(typeof C.exclude==="function")O=C.exclude(Q);else O=C.exclude.test(Q);if(O)continue}if(C.include){let O=!1;if(typeof C.include==="function")O=C.include(Q);else O=C.include.test(Q);if(!O)continue}let z=!1;for(let O of C.extensions)if(Q.endsWith(O))z=!0;if(z){let O=this.shim.path.join(E,Q),A=F(O),J=Object.create(null,Object.getOwnPropertyDescriptors({...A}));if($(J,O,Q)){if(this.requireCache.has(O))continue;else this.requireCache.add(O);if(!J.command)J.command=this.shim.path.basename(O,this.shim.path.extname(O));this.addHandler(J)}}}}addHandler(D,F,u,C,E,B){let $=[],Z=o1(E);if(C=C||(()=>{}),Array.isArray(D))if(Lu(D))[D,...$]=D;else for(let Q of D)this.addHandler(Q);else if(Tu(D)){let Q=Array.isArray(D.command)||typeof D.command==="string"?D.command:null;if(Q===null)throw Error(`No command name given for module: ${this.shim.inspect(D)}`);if(D.aliases)Q=[].concat(Q).concat(D.aliases);this.addHandler(Q,this.extractDesc(D),D.builder,D.handler,D.middlewares,D.deprecated);return}else if(n1(u)){this.addHandler([D].concat($),F,u.builder,u.handler,u.middlewares,u.deprecated);return}if(typeof D==="string"){let Q=SD(D);$=$.map((A)=>SD(A).cmd);let z=!1,O=[Q.cmd].concat($).filter((A)=>{if(Y0.test(A))return z=!0,!1;return!0});if(O.length===0&&z)O.push("$0");if(z)Q.cmd=O[0],$=O.slice(1),D=D.replace(Y0,Q.cmd);if($.forEach((A)=>{this.aliasMap[A]=Q.cmd}),F!==!1)this.usage.command(D,F,z,$,B);if(this.handlers[Q.cmd]={original:D,description:F,handler:C,builder:u||{},middlewares:Z,deprecated:B,demanded:Q.demanded,optional:Q.optional},z)this.defaultCommand=this.handlers[Q.cmd]}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(D,F,u,C,E,B){let $=this.handlers[D]||this.handlers[this.aliasMap[D]]||this.defaultCommand,Z=F.getInternalMethods().getContext(),Q=Z.commands.slice(),z=!D;if(D)Z.commands.push(D),Z.fullCommands.push($.original);let O=this.applyBuilderUpdateUsageAndParse(z,$,F,u.aliases,Q,C,E,B);return s(O)?O.then((A)=>this.applyMiddlewareAndGetResult(z,$,A.innerArgv,Z,E,A.aliases,F)):this.applyMiddlewareAndGetResult(z,$,O.innerArgv,Z,E,O.aliases,F)}applyBuilderUpdateUsageAndParse(D,F,u,C,E,B,$,Z){let Q=F.builder,z=u;if(f0(Q)){u.getInternalMethods().getUsageInstance().freeze();let O=Q(u.getInternalMethods().reset(C),Z);if(s(O))return O.then((A)=>{return z=s1(A)?A:u,this.parseAndUpdateUsage(D,F,z,E,B,$)})}else if(Nu(Q))u.getInternalMethods().getUsageInstance().freeze(),z=u.getInternalMethods().reset(C),Object.keys(F.builder).forEach((O)=>{z.option(O,Q[O])});return this.parseAndUpdateUsage(D,F,z,E,B,$)}parseAndUpdateUsage(D,F,u,C,E,B){if(D)u.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(u))u.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(C,F),F.description);let $=u.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,E,B);return s($)?$.then((Z)=>({aliases:u.parsed.aliases,innerArgv:Z})):{aliases:u.parsed.aliases,innerArgv:$}}shouldUpdateUsage(D){return!D.getInternalMethods().getUsageInstance().getUsageDisabled()&&D.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(D,F){let u=Y0.test(F.original)?F.original.replace(Y0,"").trim():F.original,C=D.filter((E)=>{return!Y0.test(E)});return C.push(u),`$0 ${C.join(" ")}`}handleValidationAndGetResult(D,F,u,C,E,B,$,Z){if(!B.getInternalMethods().getHasOutput()){let Q=B.getInternalMethods().runValidation(E,Z,B.parsed.error,D);u=oD(u,(z)=>{return Q(z),z})}if(F.handler&&!B.getInternalMethods().getHasOutput()){B.getInternalMethods().setHasOutput();let Q=!!B.getOptions().configuration["populate--"];if(B.getInternalMethods().postProcess(u,Q,!1,!1),u=lD(u,B,$,!1),u=oD(u,(z)=>{let O=F.handler(z);return s(O)?O.then(()=>z):z}),!D)B.getInternalMethods().getUsageInstance().cacheHelpMessage();if(s(u)&&!B.getInternalMethods().hasParseCallback())u.catch((z)=>{try{B.getInternalMethods().getUsageInstance().fail(null,z)}catch(O){}})}if(!D)C.commands.pop(),C.fullCommands.pop();return u}applyMiddlewareAndGetResult(D,F,u,C,E,B,$){let Z={};if(E)return u;if(!$.getInternalMethods().getHasOutput())Z=this.populatePositionals(F,u,C,$);let Q=this.globalMiddleware.getMiddleware().slice(0).concat(F.middlewares),z=lD(u,$,Q,!0);return s(z)?z.then((O)=>this.handleValidationAndGetResult(D,F,O,C,B,$,Q,Z)):this.handleValidationAndGetResult(D,F,z,C,B,$,Q,Z)}populatePositionals(D,F,u,C){F._=F._.slice(u.commands.length);let E=D.demanded.slice(0),B=D.optional.slice(0),$={};this.validation.positionalCount(E.length,F._.length);while(E.length){let Z=E.shift();this.populatePositional(Z,F,$)}while(B.length){let Z=B.shift();this.populatePositional(Z,F,$)}return F._=u.commands.concat(F._.map((Z)=>""+Z)),this.postProcessPositionals(F,$,this.cmdToParseOptions(D.original),C),$}populatePositional(D,F,u){let C=D.cmd[0];if(D.variadic)u[C]=F._.splice(0).map(String);else if(F._.length)u[C]=[String(F._.shift())]}cmdToParseOptions(D){let F={array:[],default:{},alias:{},demand:{}},u=SD(D);return u.demanded.forEach((C)=>{let[E,...B]=C.cmd;if(C.variadic)F.array.push(E),F.default[E]=[];F.alias[E]=B,F.demand[E]=!0}),u.optional.forEach((C)=>{let[E,...B]=C.cmd;if(C.variadic)F.array.push(E),F.default[E]=[];F.alias[E]=B}),F}postProcessPositionals(D,F,u,C){let E=Object.assign({},C.getOptions());E.default=Object.assign(u.default,E.default);for(let Q of Object.keys(u.alias))E.alias[Q]=(E.alias[Q]||[]).concat(u.alias[Q]);E.array=E.array.concat(u.array),E.config={};let B=[];if(Object.keys(F).forEach((Q)=>{F[Q].map((z)=>{if(E.configuration["unknown-options-as-args"])E.key[Q]=!0;B.push(`--${Q}`),B.push(z)})}),!B.length)return;let $=Object.assign({},E.configuration,{"populate--":!1}),Z=this.shim.Parser.detailed(B,Object.assign({},E,{configuration:$}));if(Z.error)C.getInternalMethods().getUsageInstance().fail(Z.error.message,Z.error);else{let Q=Object.keys(F);Object.keys(F).forEach((z)=>{Q.push(...Z.aliases[z])}),Object.keys(Z.argv).forEach((z)=>{if(Q.includes(z)){if(!F[z])F[z]=Z.argv[z];if(!this.isInConfigs(C,z)&&!this.isDefaulted(C,z)&&Object.prototype.hasOwnProperty.call(D,z)&&Object.prototype.hasOwnProperty.call(Z.argv,z)&&(Array.isArray(D[z])||Array.isArray(Z.argv[z])))D[z]=[].concat(D[z],Z.argv[z]);else D[z]=Z.argv[z]}})}}isDefaulted(D,F){let{default:u}=D.getOptions();return Object.prototype.hasOwnProperty.call(u,F)||Object.prototype.hasOwnProperty.call(u,this.shim.Parser.camelCase(F))}isInConfigs(D,F){let{configObjects:u}=D.getOptions();return u.some((C)=>Object.prototype.hasOwnProperty.call(C,F))||u.some((C)=>Object.prototype.hasOwnProperty.call(C,this.shim.Parser.camelCase(F)))}runDefaultBuilderOn(D){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(D)){let u=Y0.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,"$0 ");D.getInternalMethods().getUsageInstance().usage(u,this.defaultCommand.description)}let F=this.defaultCommand.builder;if(f0(F))return F(D,!0);else if(!n1(F))Object.keys(F).forEach((u)=>{D.option(u,F[u])});return}extractDesc({describe:D,description:F,desc:u}){for(let C of[D,F,u]){if(typeof C==="string"||C===!1)return C;OD(C,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let D=this.frozens.pop();OD(D,void 0,this.shim),{handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand}=D}reset(){return this.handlers={},this.aliasMap={},this.defaultCommand=void 0,this.requireCache=new Set,this}}function t1(D,F,u,C){return new i1(D,F,u,C)}function n1(D){return typeof D==="object"&&!!D.builder&&typeof D.handler==="function"}function Lu(D){return D.every((F)=>typeof F==="string")}function f0(D){return typeof D==="function"}function Nu(D){return typeof D==="object"}function Tu(D){return typeof D==="object"&&!Array.isArray(D)}function vD(D={},F=()=>!0){let u={};return z0(D).forEach((C)=>{if(F(C,D[C]))u[C]=D[C]}),u}function fD(D){if(typeof process>"u")return;[process.stdout,process.stderr].forEach((F)=>{let u=F;if(u._handle&&u.isTTY&&typeof u._handle.setBlocking==="function")u._handle.setBlocking(D)})}function wu(D){return typeof D==="boolean"}function a1(D,F){let u=F.y18n.__,C={},E=[];C.failFn=function(K){E.push(K)};let B=null,$=null,Z=!0;C.showHelpOnFail=function(K=!0,w){let[y,n]=typeof K==="string"?[!0,K]:[K,w];if(D.getInternalMethods().isGlobalContext())$=n;return B=n,Z=y,C};let Q=!1;C.fail=function(K,w){let y=D.getInternalMethods().getLoggerInstance();if(E.length)for(let n=E.length-1;n>=0;--n){let uD=E[n];if(wu(uD)){if(w)throw w;else if(K)throw Error(K)}else uD(K,w,C)}else{if(D.getExitProcess())fD(!0);if(!Q){if(Q=!0,Z)D.showHelp("error"),y.error();if(K||w)y.error(K||w);let n=B||$;if(n){if(K||w)y.error("");y.error(n)}}if(w=w||new DD(K),D.getExitProcess())return D.exit(1);else if(D.getInternalMethods().hasParseCallback())return D.exit(1,w);else throw w}};let z=[],O=!1;C.usage=(I,K)=>{if(I===null)return O=!0,z=[],C;return O=!1,z.push([I,K||""]),C},C.getUsage=()=>{return z},C.getUsageDisabled=()=>{return O},C.getPositionalGroupName=()=>{return u("Positionals:")};let A=[];C.example=(I,K)=>{A.push([I,K||""])};let J=[];C.command=function(K,w,y,n,uD=!1){if(y)J=J.map((o)=>{return o[2]=!1,o});J.push([K,w||"",y,n,uD])},C.getCommands=()=>J;let W={};C.describe=function(K,w){if(Array.isArray(K))K.forEach((y)=>{C.describe(y,w)});else if(typeof K==="object")Object.keys(K).forEach((y)=>{C.describe(y,K[y])});else W[K]=w},C.getDescriptions=()=>W;let _=[];C.epilog=(I)=>{_.push(I)};let q=!1,P;C.wrap=(I)=>{q=!0,P=I},C.getWrap=()=>{if(F.getEnv("YARGS_DISABLE_WRAP"))return null;if(!q)P=l(),q=!0;return P};let c="__yargsString__:";C.deferY18nLookup=(I)=>c+I,C.help=function(){if(d)return d;QD();let K=D.customScriptName?D.$0:F.path.basename(D.$0),w=D.getDemandedOptions(),y=D.getDemandedCommands(),n=D.getDeprecatedOptions(),uD=D.getGroups(),o=D.getOptions(),CD=[];CD=CD.concat(Object.keys(W)),CD=CD.concat(Object.keys(w)),CD=CD.concat(Object.keys(y)),CD=CD.concat(Object.keys(o.default)),CD=CD.filter(j),CD=Object.keys(CD.reduce((f,i)=>{if(i!=="_")f[i]=!0;return f},{}));let PD=C.getWrap(),t=F.cliui({width:PD,wrap:!!PD});if(!O){if(z.length)z.forEach((f)=>{if(t.div({text:`${f[0].replace(/\$0/g,K)}`}),f[1])t.div({text:`${f[1]}`,padding:[1,0,0,0]})}),t.div();else if(J.length){let f=null;if(y._)f=`${K} <${u("command")}>
26
- `;else f=`${K} [${u("command")}]
27
- `;t.div(`${f}`)}}if(J.length>1||J.length===1&&!J[0][2]){t.div(u("Commands:"));let f=D.getInternalMethods().getContext(),i=f.commands.length?`${f.commands.join(" ")} `:"";if(D.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)J=J.sort((m,zD)=>m[0].localeCompare(zD[0]));let ED=K?`${K} `:"";J.forEach((m)=>{let zD=`${ED}${i}${m[0].replace(/^\$0 ?/,"")}`;t.span({text:zD,padding:[0,2,0,2],width:p(J,PD,`${K}${i}`)+4},{text:m[1]});let e=[];if(m[2])e.push(`[${u("default")}]`);if(m[3]&&m[3].length)e.push(`[${u("aliases:")} ${m[3].join(", ")}]`);if(m[4])if(typeof m[4]==="string")e.push(`[${u("deprecated: %s",m[4])}]`);else e.push(`[${u("deprecated")}]`);if(e.length)t.div({text:e.join(" "),padding:[0,0,0,2],align:"right"});else t.div()}),t.div()}let wD=(Object.keys(o.alias)||[]).concat(Object.keys(D.parsed.newAliases)||[]);CD=CD.filter((f)=>!D.parsed.newAliases[f]&&wD.every((i)=>(o.alias[i]||[]).indexOf(f)===-1));let H0=u("Options:");if(!uD[H0])uD[H0]=[];U(CD,o.alias,uD,H0);let v=(f)=>/^--/.test(k0(f)),Q0=Object.keys(uD).filter((f)=>uD[f].length>0).map((f)=>{let i=uD[f].filter(j).map((ED)=>{if(wD.includes(ED))return ED;for(let m=0,zD;(zD=wD[m])!==void 0;m++)if((o.alias[zD]||[]).includes(ED))return zD;return ED});return{groupName:f,normalizedKeys:i}}).filter(({normalizedKeys:f})=>f.length>0).map(({groupName:f,normalizedKeys:i})=>{let ED=i.reduce((m,zD)=>{return m[zD]=[zD].concat(o.alias[zD]||[]).map((e)=>{if(f===C.getPositionalGroupName())return e;else return(/^[0-9]$/.test(e)?o.boolean.includes(zD)?"-":"--":e.length>1?"--":"-")+e}).sort((e,BD)=>v(e)===v(BD)?0:v(e)?1:-1).join(", "),m},{});return{groupName:f,normalizedKeys:i,switches:ED}});if(Q0.filter(({groupName:f})=>f!==C.getPositionalGroupName()).some(({normalizedKeys:f,switches:i})=>!f.every((ED)=>v(i[ED]))))Q0.filter(({groupName:f})=>f!==C.getPositionalGroupName()).forEach(({normalizedKeys:f,switches:i})=>{f.forEach((ED)=>{if(v(i[ED]))i[ED]=bu(i[ED],4)})});if(Q0.forEach(({groupName:f,normalizedKeys:i,switches:ED})=>{t.div(f),i.forEach((m)=>{let zD=ED[m],e=W[m]||"",BD=null;if(e.includes(c))e=u(e.substring(c.length));if(o.boolean.includes(m))BD=`[${u("boolean")}]`;if(o.count.includes(m))BD=`[${u("count")}]`;if(o.string.includes(m))BD=`[${u("string")}]`;if(o.normalize.includes(m))BD=`[${u("string")}]`;if(o.array.includes(m))BD=`[${u("array")}]`;if(o.number.includes(m))BD=`[${u("number")}]`;let VF=(V)=>typeof V==="string"?`[${u("deprecated: %s",V)}]`:`[${u("deprecated")}]`,Y=[m in n?VF(n[m]):null,BD,m in w?`[${u("required")}]`:null,o.choices&&o.choices[m]?`[${u("choices:")} ${C.stringifiedValues(o.choices[m])}]`:null,S(o.default[m],o.defaultDescription[m])].filter(Boolean).join(" ");t.span({text:k0(zD),padding:[0,2,0,2+r1(zD)],width:p(ED,PD)+4},e);let H=D.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(Y&&!H)t.div({text:Y,padding:[0,0,0,2],align:"right"});else t.div()}),t.div()}),A.length)t.div(u("Examples:")),A.forEach((f)=>{f[0]=f[0].replace(/\$0/g,K)}),A.forEach((f)=>{if(f[1]==="")t.div({text:f[0],padding:[0,2,0,2]});else t.div({text:f[0],padding:[0,2,0,2],width:p(A,PD)+4},{text:f[1]})}),t.div();if(_.length>0){let f=_.map((i)=>i.replace(/\$0/g,K)).join(`
28
- `);t.div(`${f}
29
- `)}return t.toString().replace(/\s*$/,"")};function p(I,K,w){let y=0;if(!Array.isArray(I))I=Object.values(I).map((n)=>[n]);if(I.forEach((n)=>{y=Math.max(F.stringWidth(w?`${w} ${k0(n[0])}`:k0(n[0]))+r1(n[0]),y)}),K)y=Math.min(y,parseInt((K*0.5).toString(),10));return y}function QD(){let I=D.getDemandedOptions(),K=D.getOptions();(Object.keys(K.alias)||[]).forEach((w)=>{K.alias[w].forEach((y)=>{if(W[y])C.describe(w,W[y]);if(y in I)D.demandOption(w,I[y]);if(K.boolean.includes(y))D.boolean(w);if(K.count.includes(y))D.count(w);if(K.string.includes(y))D.string(w);if(K.normalize.includes(y))D.normalize(w);if(K.array.includes(y))D.array(w);if(K.number.includes(y))D.number(w)})})}let d;C.cacheHelpMessage=function(){d=this.help()},C.clearCachedHelpMessage=function(){d=void 0},C.hasCachedHelpMessage=function(){return!!d};function U(I,K,w,y){let n=[],uD=null;return Object.keys(w).forEach((o)=>{n=n.concat(w[o])}),I.forEach((o)=>{if(uD=[o].concat(K[o]),!uD.some((CD)=>n.indexOf(CD)!==-1))w[y].push(o)}),n}function j(I){return D.getOptions().hiddenOptions.indexOf(I)<0||D.parsed.argv[D.getOptions().showHiddenOpt]}C.showHelp=(I)=>{let K=D.getInternalMethods().getLoggerInstance();if(!I)I="error";(typeof I==="function"?I:K[I])(C.help())},C.functionDescription=(I)=>{return["(",I.name?F.Parser.decamelize(I.name,"-"):u("generated-value"),")"].join("")},C.stringifiedValues=function(K,w){let y="",n=w||", ",uD=[].concat(K);if(!K||!uD.length)return y;return uD.forEach((o)=>{if(y.length)y+=n;y+=JSON.stringify(o)}),y};function S(I,K){let w=`[${u("default:")} `;if(I===void 0&&!K)return null;if(K)w+=K;else switch(typeof I){case"string":w+=`"${I}"`;break;case"object":w+=JSON.stringify(I);break;default:w+=I}return`${w}]`}function l(){if(F.process.stdColumns)return Math.min(80,F.process.stdColumns);else return 80}let g=null;C.version=(I)=>{g=I},C.showVersion=(I)=>{let K=D.getInternalMethods().getLoggerInstance();if(!I)I="error";(typeof I==="function"?I:K[I])(g)},C.reset=function(K){return B=null,Q=!1,z=[],O=!1,_=[],A=[],J=[],W=vD(W,(w)=>!K[w]),C};let LD=[];return C.freeze=function(){LD.push({failMessage:B,failureOutput:Q,usages:z,usageDisabled:O,epilogs:_,examples:A,commands:J,descriptions:W})},C.unfreeze=function(K=!1){let w=LD.pop();if(!w)return;if(K)W={...w.descriptions,...W},J=[...w.commands,...J],z=[...w.usages,...z],A=[...w.examples,...A],_=[...w.epilogs,..._];else({failMessage:B,failureOutput:Q,usages:z,usageDisabled:O,epilogs:_,examples:A,commands:J,descriptions:W}=w)},C}function mF(D){return typeof D==="object"}function bu(D,F){return mF(D)?{text:D.text,indentation:D.indentation+F}:{text:D,indentation:F}}function r1(D){return mF(D)?D.indentation:0}function k0(D){return mF(D)?D.text:D}var e1=`###-begin-{{app_name}}-completions-###
30
- #
31
- # yargs command completion script
32
- #
33
- # Installation: {{app_path}} {{completion_command}} >> ~/.bashrc
34
- # or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.
35
- #
36
- _{{app_name}}_yargs_completions()
37
- {
38
- local cur_word args type_list
14
+ `}generateSimpleExports(e){e.push("// Exports");let t=Array.from(this.exports.entries());this.sortFunction?t=t.sort(this.sortFunction):t=t.sort(([i],[n])=>i.localeCompare(n));let r=new Map;for(let[i,n]of t)r.has(n)||r.set(n,[]),r.get(n)?.push(i);for(let[i,n]of r){let o=n.sort();o.length===1?e.push(`export type { ${o[0]} } from './${i}';`):o.length<=3?e.push(`export type { ${o.join(", ")} } from './${i}';`):(e.push("export type {"),o.forEach((a,c)=>{let l=c===o.length-1;e.push(` ${a}${l?"":","}`);}),e.push(`} from './${i}';`));}}generateGroupedExports(e){if(!this.groupingFunction)return;let t=new Map;for(let[i,n]of this.exports){let o=this.groupingFunction(i);t.has(o)||t.set(o,new Map);let a=t.get(o);a.has(n)||a.set(n,[]),a.get(n)?.push(i);}let r=Array.from(t.entries()).sort();for(let[i,n]of r){e.push(`// ${i}`);for(let[o,a]of n){let c=a.sort();c.length===1?e.push(`export type { ${c[0]} } from './${o}';`):e.push(`export type { ${c.join(", ")} } from './${o}';`);}e.push("");}}getExports(){return new Map(this.exports)}getNamespaces(){return new Map(this.namespaces)}getReExports(){return new Map(this.reExports)}};});var D=class s{options;constructor(e={}){this.options={timestamp:false,verbose:false,...e};}formatMessage(e,t,r){let i=this.options.timestamp?`${m.gray(new Date().toLocaleTimeString())} `:"",n=this.options.prefix?`${m.cyan(`[${this.options.prefix}]`)} `:"";return `${i}${r(e)} ${n}${t}`}success(e){console.log(this.formatMessage("\u2705",e,m.green));}error(e,t){console.error(this.formatMessage("\u274C",e,m.red)),t&&this.options.verbose&&(console.error(m.red(` ${t.message}`)),t.stack&&console.error(m.gray(t.stack)));}warn(e){console.warn(this.formatMessage("\u26A0\uFE0F",e,m.yellow));}info(e){console.log(this.formatMessage("\u2139\uFE0F",e,m.blue));}debug(e){this.options.verbose&&console.log(this.formatMessage("\u{1F41B}",e,m.magenta));}step(e){console.log(this.formatMessage("\u{1F680}",e,m.cyan));}progress(e){console.log(this.formatMessage("\u23F3",e,m.blue));}plain(e,t=r=>r){let r=this.options.timestamp?`${m.gray(new Date().toLocaleTimeString())} `:"",i=this.options.prefix?`${m.cyan(`[${this.options.prefix}]`)} `:"";console.log(`${r}${i}${t(e)}`);}dim(e){this.plain(e,m.gray);}child(e){return new s({...this.options,prefix:this.options.prefix?`${this.options.prefix}:${e}`:e})}configure(e){this.options={...this.options,...e};}},T=new D;function B(s){T.success(s);}function h(s,e){T.error(s,e);}function ne(s){T.warn(s);}function V(s){T.info(s);}function se(s){T.step(s);}function Pe(s){T.dim(s);}function oe(s){T.configure(s);}function b(s={}){return new D(s)}function ae(s){console.log(),console.log(m.cyan(m.bold(`\u2501\u2501\u2501 ${s} \u2501\u2501\u2501`)));}function ce(s,e,t){let r=s;e&&(r+=` ${m.gray(`(${e}ms)`)}`),B(r),t&&Object.entries(t).forEach(([i,n])=>{Pe(` ${i}: ${n}`);});}function C(s,e="\u2022"){s.forEach(t=>{console.log(m.gray(` ${e} ${t}`));});}var x=class{cache=new Map;config;cacheDir;constructor(e){this.config={enablePersistence:true,cacheDir:".typeschema-cache",maxAge:1440*60*1e3,validateCached:true,...e},this.config.enablePersistence&&this.config.cacheDir&&(this.cacheDir=this.config.cacheDir);}async set(e){let t=this.generateKey(e.identifier);this.cache.set(t,e),this.config.enablePersistence&&this.cacheDir&&await this.persistSchema(e);}get(e){let t=this.generateKey(e);return this.cache.get(t)||null}getByUrl(e){for(let t of this.cache.values())if(t.identifier.url===e)return t;return null}has(e){let t=this.generateKey(e);return this.cache.has(t)}hasByUrl(e){for(let t of this.cache.values())if(t.identifier.url===e)return true;return false}delete(e){let t=this.generateKey(e);return this.cache.delete(t)}deleteByUrl(e){for(let[t,r]of this.cache.entries())if(r.identifier.url===e)return this.cache.delete(t);return false}getByPackage(e){let t=[];for(let r of this.cache.values())r.identifier.package===e&&t.push(r);return t}getByKind(e){let t=[];for(let r of this.cache.values())r.identifier.kind===e&&t.push(r);return t}setMany(e){for(let t of e)this.set(t);}clear(){this.cache.clear();}generateKey(e){return `${e.package}:${e.version}:${e.kind}:${e.name}`}async initialize(){this.config.enablePersistence&&this.cacheDir&&(existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:true}),await this.loadFromDisk());}async loadFromDisk(){if(!(!this.cacheDir||!existsSync(this.cacheDir)))try{let t=(await readdir(this.cacheDir)).filter(r=>r.endsWith(".typeschema.json"));for(let r of t){let i=join(this.cacheDir,r),n=await stat(i);if(this.config.maxAge&&Date.now()-n.mtimeMs>this.config.maxAge){await unlink(i);continue}try{let o=await readFile(i,"utf-8"),a=JSON.parse(o);if(this.config.validateCached&&!a.schema?.identifier)continue;let c=this.generateKey(a.schema.identifier);this.cache.set(c,a.schema);}catch(o){console.warn(`Failed to load cached schema from ${r}:`,o);}}}catch(e){console.warn("Failed to load cached schemas from disk:",e);}}async persistSchema(e){if(!this.cacheDir)return;existsSync(this.cacheDir)||mkdirSync(this.cacheDir,{recursive:true});let t={schema:e,timestamp:Date.now(),version:e.identifier.version},r=`${e.identifier.package}-${e.identifier.version}-${e.identifier.kind}-${e.identifier.name}.typeschema.json`.replace(/[^a-zA-Z0-9.-]/g,"_"),i=join(this.cacheDir,r);try{await writeFile(i,JSON.stringify(t,null,2),"utf-8");}catch(n){console.warn(`Failed to persist schema to ${i}:`,n);}}async clearDisk(){if(!(!this.cacheDir||!existsSync(this.cacheDir)))try{let t=(await readdir(this.cacheDir)).filter(r=>r.endsWith(".typeschema.json"));for(let r of t)await unlink(join(this.cacheDir,r));}catch(e){console.warn("Failed to clear cache directory:",e);}}};var pe=(s,e)=>(e||(e={name:"undefined",version:"undefined"}),{...s,package_meta:s.package_meta||e,name:s.name,url:s.url,base:s.base});function ue(s){return s.identifier.kind==="binding"}var de=async(s,e,t)=>{let r=await s.search({}),i={};for(let u of r){let g=u.url;g&&(i[g]=u);}let n={};for(let u of r)if(u.resourceType==="StructureDefinition"){let g=u.url;n[g]=u;}let o={},a={},[c]=[0,0];for(let u of Object.values(n)){try{let g=pe(De.translate(u),t);o[g.url]=g,a[g.name]=g.url,c++;}catch(g){}}let p={};for(let u of r)u.resourceType==="ValueSet"&&(u.package_meta||(u.package_meta=t),p[u.url]=u);let d={};for(let u of Object.values(o))u.kind==="complex-type"&&(d[u.url]=u);return {...s,appendFs(u){let g=pe(u);o[g.url]=g,a[g.name]=g.url;},resolveFs:u=>o[u],resolveFsGenealogy:u=>{let g=o[u];if(g===void 0)throw new Error(`Failed to resolve FHIR Schema genealogy for '${u}'`);let O=[g];for(;g?.base;)if(g=o[g.base]||o[a[g.base]],O.push(g),g===void 0)throw new Error(`Failed to resolve FHIR Schema genealogy for '${u}'`);return O},ensureCanonicalUrl:u=>a[u]||u,allSd:()=>Object.values(n),resolveSd:u=>n[u],allFs:()=>Object.values(o),allVs:()=>Object.values(p),resolveVs:u=>p[u],complexTypeDict:()=>d,resolveAny:u=>i[u]}};var ge=(s,e)=>{let[t,...r]=e;return t===void 0?[]:s.map(i=>{if(!i.elements)return;let n=i.elements?.[t];for(let o of r)n=n?.elements?.[o];return n}).filter(i=>i!==void 0)};function fe(s){let e=s.reverse().reduce((t,r)=>({...t,...r}),{});return e.elements=void 0,e}function me(s){let e=s.split("|")[0];return e||s}function dt(s){return s.split("|")[1]}function gt(s){return s.derivation==="constraint"?"profile":s.kind==="primitive-type"?"primitive-type":s.kind==="complex-type"?"complex-type":(s.kind==="resource","resource")}function v(s){return {kind:gt(s),package:s.package_meta.name,version:s.package_meta.version,name:s.name,url:s.url}}function $(s,e){let t=e.join(".");return {kind:"nested",package:s.package_meta.name,version:s.package_meta.version,name:t,url:`${s.url}#${t}`}}var ft=s=>{let e=s.split("/"),t=e[e.length-1];return t&&t.length>0?t.split(/[-_]/).map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(""):s};function A(s,e){let t=me(e),r=ft(t),i={package_meta:{name:"missing_valuesets",version:dt(t)||"0.0.0"},id:e},n=s.resolveVs(t)||i,o=n?.id&&!/^[a-zA-Z0-9_-]{20,}$/.test(n.id)?n.id:r;return {kind:"value-set",package:n?.package_meta.name,version:n?.package_meta.version,name:o,url:t}}function L(s,e,t){let r=e.join("."),[i,n,o]=t?[{name:"shared",version:"1.0.0"},t,`urn:fhir:binding:${t}`]:[s.package_meta,`${s.name}.${r}_binding`,`${s.url}#${r}_binding`];return {kind:"binding",package:i.name,version:i.version,name:n,url:o}}async function Be(s,e){let t=v(e);if(t.kind!=="profile")throw new Error(`Expected profile, got ${t.kind} for ${e.name}`);let r;if(e.base){let l=e.base.includes("/")?e.base:`http://hl7.org/fhir/StructureDefinition/${e.base}`,p=e.base.split("/").pop()||e.base,d=await mt(l,s),f=l.startsWith("http://hl7.org/fhir/");r={kind:d,package:f?"hl7.fhir.r4.core":e.package_meta.name||"undefined",version:f?"4.0.1":e.package_meta.version||"undefined",name:p,url:l};}let i={identifier:t,base:r,dependencies:r?[r]:[]};e.description&&(i.description=e.description);let n=ht(e);if(Object.keys(n).length>0&&(i.metadata=n),e.elements){let l=await G(s,e,[],e.elements);l&&Object.keys(l).length>0&&(i.fields=l);}let o=await yt(e);Object.keys(o).length>0&&(i.constraints=o);let a=await bt(e);a.length>0&&(i.extensions=a);let c=vt(e);return c.length>0&&(i.validation=c),i}async function mt(s,e){try{let t=e.resolveFs(s);if(!t)return "resource";if(t){if(t.derivation==="constraint")return "profile";if(t.kind==="resource")return "resource";if(t.kind==="complex-type")return "complex-type"}}catch(t){console.warn(`Could not resolve base schema ${s}:`,t);}return s.includes("StructureDefinition/")&&!s.startsWith("http://hl7.org/fhir/StructureDefinition/")?"profile":"resource"}function ht(s){let e={},t=s.package_meta;return s.publisher&&(e.publisher=s.publisher),s.contact&&(e.contact=s.contact),s.copyright&&(e.copyright=s.copyright),s.purpose&&(e.purpose=s.purpose),s.experimental!==void 0&&(e.experimental=s.experimental),s.date&&(e.date=s.date),s.jurisdiction&&(e.jurisdiction=s.jurisdiction),t?.name?e.package=t.name:s.package_meta.name&&(e.package=s.package_meta.name),e}async function yt(s,e){let t={};if(!s.elements)return t;for(let[r,i]of Object.entries(s.elements)){let n={};i.min!==void 0&&(n.min=i.min),i.max!==void 0&&(n.max=String(i.max)),i.mustSupport&&(n.mustSupport=true),i.fixedValue!==void 0&&(n.fixedValue=i.fixedValue),i.patternValue!==void 0&&(n.patternValue=i.patternValue),i.binding&&(n.binding={strength:i.binding.strength,valueSet:i.binding.valueSet??""}),i.type&&Array.isArray(i.type)&&i.type.length>0&&(n.types=i.type.map(o=>{let a={code:o.code};return o.profile&&(a.profile=o.profile),o.targetProfile&&(a.targetProfile=o.targetProfile),a})),i.slicing&&(n.slicing={discriminator:i.slicing.discriminator??[],rules:String(i.slicing),ordered:i.slicing.ordered}),Object.keys(n).length>0&&(t[r]=n);}return t}async function bt(s,e){let t=[];if(!s.elements)return t;for(let[r,i]of Object.entries(s.elements))if(r.includes("extension")&&i.type&&Array.isArray(i.type))for(let n of i.type)n.code==="Extension"&&n.profile&&t.push({path:r,profile:n.profile,min:i.min,max:String(i.max),mustSupport:i.mustSupport});return t}function vt(s){let e=[];if(!s.elements)return e;for(let[t,r]of Object.entries(s.elements))if(r.constraint&&Array.isArray(r.constraint))for(let i of r.constraint)e.push({path:t,key:i.key,severity:i.severity,human:i.human,expression:i.expression});return e}function Ve(s,e,t){let r=t[t.length-1],i=t.slice(0,-1),n=s.resolveFsGenealogy(e.url).flatMap(o=>{if(i.length===0)return o.required||[];if(!o.elements)return [];let a=o;for(let c of i)a=a?.elements?.[c];return a?.required||[]});return new Set(n).has(r)}function je(s,e,t){let r=t[t.length-1];if(!r)throw new Error(`Internal error: fieldName is missing for path ${t.join("/")}`);let i=t.slice(0,-1),n=s.resolveFsGenealogy(e.url).flatMap(o=>{if(i.length===0)return o.excluded||[];if(!o.elements)return [];let a=o;for(let c of i)a=a?.elements?.[c];return a?.excluded||[]});return new Set(n).has(r)}var St=(s,e,t)=>{if(s.refers)return s.refers.map(r=>{let i=e.ensureCanonicalUrl(r),n=e.resolveFs(i);return v(n)})};function he(s,e,t){if(t.elementReference){let r=t.elementReference.filter((i,n)=>n%2===1).map(i=>i).filter(i=>i!=="elements");if(r.length>0)return $(e,r)}if(t.type){let r=t.type.match(/^[a-z]/)?"primitive-type":"complex-type",i=s.ensureCanonicalUrl(t.type),n=s.resolveFs(i);if(!n)throw new Error(`Could not resolve field '${t.type}'`);return {kind:r,package:n.package_meta.name,version:n.package_meta.version,name:t.type,url:i}}}var H=(s,e,t,r)=>{let i,n;return r.binding&&(i=L(e,t,r.binding.bindingName),r.binding.strength==="required"&&r.type==="code"&&(n=ye(s,r))),{type:he(s,e,r),required:Ve(s,e,t),excluded:je(s,e,t),reference:St(r,s,e.package_meta),array:r.array||false,min:r.min,max:r.max,choices:r.choices,choiceOf:r.choiceOf,binding:i,enum:n}};function R(s){let e=s.type==="BackboneElement",t=s.type==="Element"&&s.elements!==void 0&&Object.keys(s.elements).length>0,r=s.type===void 0&&s.choiceOf===void 0&&s.elements!==void 0&&Object.keys(s.elements).length>0;return e||t||r}function U(s,e,t,r){return {type:$(e,t),array:r.array||false,required:Ve(s,e,t),excluded:je(s,e,t)}}function be(s,e){let t=me(e)||e,r=s.resolveVs(t);if(r)return xt(s,r)}function xt(s,e){if(e.expansion?.contains)return e.expansion.contains;let t=[];if(e.compose?.include){for(let r of e.compose.include)if(r.concept)for(let i of r.concept)t.push({system:r.system,code:i.code,display:i.display});else if(r.system&&!r.filter)try{let i=s.resolveAny(r.system);if(i?.concept){let n=(o,a)=>{for(let c of o)t.push({system:a,code:c.code,display:c.display}),c.concept&&n(c.concept,a);};n(i.concept,r.system);}}catch{}}return t.length>0?t:void 0}var Ae=100;function ye(s,e){if(!e.binding)return;let t=e.binding.strength,r=e.binding.valueSet;if(!r||!(t==="required"||t==="extensible"&&(e.type==="code"||e.type==="Coding")||t==="preferred"&&(e.type==="code"||e.type==="Coding")))return;let n=be(s,r);if(!n||n.length===0)return;let o=n.map(a=>a.code).filter(a=>a&&typeof a=="string"&&a.trim().length>0);if(o.length>Ae){console.warn(`Value set ${r} has more than ${Ae} codes, which may cause issues with code generation.`);return}return o.length>0?o:void 0}function wt(s,e,t,r){if(!r.binding?.valueSet)return;let i=L(e,t,r.binding.bindingName),n=he(s,e,r),o=A(s,r.binding.valueSet),a=[];n&&a.push(n),a.push(o);let c=ye(s,r);return {identifier:i,type:n,valueset:o,strength:r.binding.strength,enum:c,dependencies:a}}function ve(s,e){let t=new Set;if(!e.elements)return [];let r=[];function i(a,c){for(let[l,p]of Object.entries(a)){let d=[...c,l],f=d.join(".");if(!t.has(f)){if(t.add(f),p.binding){let u=wt(s,e,d,p);u&&r.push(u);}p.elements&&i(p.elements,d);}}}i(e.elements,[]),r.sort((a,c)=>a.identifier.name.localeCompare(c.identifier.name));let n=[],o=new Set;for(let a of r)o.has(a.identifier.url)||(o.add(a.identifier.url),n.push(a));return n}function Le(s,e,t){let r=[];for(let[i,n]of Object.entries(t)){let o=[...e,i];R(n)&&r.push([o,n]),n.elements&&r.push(...Le(s,o,n.elements));}return r}function Tt(s,e,t,r){let i={};for(let[n,o]of Object.entries(t)){let a=[...e,n];R(o)?i[n]=U(r,s,a,o):i[n]=H(r,s,a,o);}return i}function Se(s,e){if(!e.elements)return;let r=Le(e,[],e.elements).filter(([n,o])=>o.elements&&Object.keys(o.elements).length>0),i=[];for(let[n,o]of r){let a=$(e,n),c;o.type==="BackboneElement"||!o.type?c={kind:"complex-type",package:e.package_meta.name,version:e.package_meta.version,name:"BackboneElement",url:"http://hl7.org/fhir/StructureDefinition/BackboneElement"}:c={kind:"complex-type",package:e.package_meta.name,version:e.package_meta.version,name:o.type,url:`http://hl7.org/fhir/StructureDefinition/${o.type}`};let l=Tt(e,n,o.elements,s),p={identifier:a,base:c,fields:l};i.push(p);}return i.sort((n,o)=>n.identifier.url.localeCompare(o.identifier.url)),i.length===0?void 0:i}function xe(s){let e=[];for(let t of s){t.base&&e.push(t.base);for(let r of Object.values(t.fields||{}))"type"in r&&r.type&&e.push(r.type),"binding"in r&&r.binding&&e.push(r.binding);}return e}function G(s,e,t,r){if(!r)return;let i=s.resolveFsGenealogy(e.url),n={};for(let[a,c]of Object.entries(r)){let l=[...t,a],p=ge(i,l),d=fe(p);n[a]={elem:c,elemSnapshot:d,path:l};}for(let[a,{elem:c,elemSnapshot:l,path:p}]of Object.entries(n))for(let d of c?.choices||[])if(!n[d]){let f=[...t,d],u=ge(i,f),g=fe(u);n[d]={elem:void 0,elemSnapshot:g,path:f};}let o={};for(let[a,{elem:c,elemSnapshot:l,path:p}]of Object.entries(n))R(l)?o[a]=U(s,e,p,l):o[a]=H(s,e,p,l);return o}function Ge(s){let e=[];for(let t of Object.values(s))"type"in t&&t.type&&e.push(t.type),"binding"in t&&t.binding&&e.push(t.binding);return e}function Ct(s){let e=new Set,t=[];for(let r of s){let i=r.url;e.has(i)||(e.add(i),t.push(r));}return t.sort((r,i)=>r.name.localeCompare(i.name)),t}function kt(s,e){return !!(s.base==="Extension"||s.base==="http://hl7.org/fhir/StructureDefinition/Extension"||s.url?.includes("/extension/")||s.url?.includes("-extension")||s.name?.toLowerCase().includes("extension")||s.type==="Extension")}async function He(s,e){if(!e.url)throw new Error("ValueSet URL is required");let t=A(s,e.url),r=be(s,e.url);return {identifier:t,description:e.description,concept:r,compose:r?void 0:e.compose}}async function Ft(s,e,t){try{let r=v(s),i;if(s.base&&s.base!=="Extension"){let a=s.base.includes("/")?s.base:`http://hl7.org/fhir/StructureDefinition/${s.base}`;i={kind:"complex-type",package:"hl7.fhir.r4.core",version:"4.0.1",name:s.base.split("/").pop()||s.base,url:a};}else i={kind:"complex-type",package:"hl7.fhir.r4.core",version:"4.0.1",name:"Extension",url:"http://hl7.org/fhir/StructureDefinition/Extension"};let n={identifier:r,base:i,description:s.description,dependencies:[],metadata:{isExtension:!0}};if(i&&n.dependencies.push(i),s.elements){let a=G(e,s,[],s.elements);a&&Object.keys(a).length>0&&(n.fields=a,n.dependencies.push(...Ge(a)));}let o=Se(e,s);return o&&o.length>0&&(n.nested=o,n.dependencies.push(...xe(o))),n.dependencies=Ct(n.dependencies),n.dependencies=n.dependencies.filter(a=>a.url!==r.url),n}catch(r){return console.warn(`Failed to transform extension ${s.name}: ${r}`),null}}function $t(s,e,t,r){let i=[];e&&i.push(e),t&&i.push(...Ge(t)),r&&i.push(...xe(r));let n={};for(let c of i)c.url!==s.url&&(n[c.url]=c);let o=new Set(r?.map(c=>c.identifier.url)),a=Object.values(n).filter(c=>!(c.kind==="nested"&&o.has(c.url))).sort((c,l)=>c.url.localeCompare(l.url));return a.length>0?a:void 0}function Rt(s,e){let t=v(e),r;if(e.base&&e.type!=="Element"){let l=s.resolveFs(s.ensureCanonicalUrl(e.base));if(!l)throw new Error(`Base resource not found '${e.base}' for '${e.url}'`);r=v(l);}let i=G(s,e,[],e.elements),n=Se(s,e),o=$t(t,r,i,n),a={identifier:t,base:r,fields:i,nested:n,description:e.description,dependencies:o},c=ve(s,e);return [a,...c]}async function Ue(s,e){let t=[],r=v(e);if(r.kind==="profile"){let i=await Be(s,e);t.push(i);let n=ve(s,e);return t.push(...n),t}if(kt(e)){let i=await Ft(e,s,e.package_meta);return i&&t.push(i),t}return Rt(s,e)}var S=class{manager;options;cacheConfig;cache;logger;constructor(e={},t){this.options={verbose:false,...e},this.manager=e.manager||CanonicalManager({packages:[],workingDir:"tmp/fhir"}),this.cacheConfig=t,this.logger=e.logger||b({verbose:this.options.verbose,prefix:"TypeSchema"});}async initializeCache(){this.cacheConfig&&!this.cache&&(this.cache=new x(this.cacheConfig),await this.cache.initialize());}async registerFromPackageMetas(e){let t=e.map(r=>`${r.name}${r.version}`);return this.logger.step(`Loading FHIR packages: ${t.join(", ")}`),await this.manager.init(),de(this.manager)}generateFhirSchemas(e){this.logger.progress(`Converting ${e.length} StructureDefinitions to FHIRSchemas`);let t=this.applyStructureDefinitionTreeshaking(e),r=[],i=0,n=0;for(let o of t)try{let a=De.translate(o);r.push(a),i++,this.logger.debug(`Converted StructureDefinition: ${o.name||o.id} (${o.resourceType})`);}catch(a){n++,this.logger.warn(`Failed to convert StructureDefinition ${o.name||o.id}: ${a instanceof Error?a.message:String(a)}`);}return this.logger.success(`FHIR Schema conversion completed: ${i}/${t.length} successful, ${n} failed`),r}async generateValueSetSchemas(e,t){e.length>0&&this.logger.debug(`${e.length} ValueSets available for enum extraction`);let r=[];if(e.length>0){this.logger.progress(`Converting ${e.length} ValueSets to TypeSchema`);let i=0,n=0;for(let o of e)try{let a=await He(await de(this.manager),o);a&&(r.push(a),i++,this.logger.debug(`Converted ValueSet: ${o.name||o.id}`));}catch(a){n++,this.logger.warn(`Failed to convert ValueSet ${o.name||o.id}: ${a instanceof Error?a.message:String(a)}`);}this.logger.success(`ValueSet conversion completed: ${i}/${e.length} successful, ${n} failed`);}return r}async generateFromPackage(e,t){if(await this.initializeCache(),this.cache&&!(this.cacheConfig?.forceRegenerate??false)){let o=this.cache.getByPackage(e);if(o.length>0)return this.logger.info(`Using cached TypeSchemas for package: ${e} (${o.length} schemas)`),o}let r={name:e,version:t||"latest"},i=await this.registerFromPackageMetas([r]),n=[...(await Promise.all(i.allFs().map(async o=>await Ue(i,o)))).flat(),...await this.generateValueSetSchemas(i.allVs(),r)];if(this.cache)for(let o of n)await this.cache.set(o);return n}applyStructureDefinitionTreeshaking(e){let t=this.options.treeshake;if(!t||t.length===0)return e;this.logger.info(`Applying treeshaking filter for ResourceTypes: ${t.join(", ")}`);let r=new Map,i=new Map,n=new Map;for(let p of e){let d=p.name||p.id;d&&(r.set(d,p),i.set(d,new Set),n.set(d,new Set));}for(let p of e){let d=p.name||p.id;if(!d)continue;let{realDeps:f,refTargets:u}=this.extractStructureDefinitionDependenciesWithReferences(p);i.set(d,new Set(f)),n.set(d,new Set(u));}let o=new Set;for(let p of t)r.has(p)?o.add(p):this.logger.warn(`ResourceType '${p}' not found in structure definitions`);let a=(p,d=new Set)=>{if(d.has(p)||!i.has(p))return;d.add(p);let f=i.get(p)||new Set;for(let u of Array.from(f))r.has(u)&&(o.add(u),a(u,d));};for(let p of Array.from(o))a(p);let c=e.filter(p=>{let d=p.name||p.id;return d&&o.has(d)}),l=new Set;for(let p of e){let d=p.name||p.id;d&&!o.has(d)&&Array.from(n.values()).some(u=>u.has(d))&&l.add(d);}return l.size>0&&this.logger.info(`Excluded reference-only targets: ${Array.from(l).join(", ")}`),this.logger.success(`Treeshaking completed: kept ${c.length}/${e.length} structure definitions`),c}extractStructureDefinitionDependenciesWithReferences(e){let t=new Set,r=new Set;if(e.baseDefinition){let i=this.extractResourceNameFromUrl(e.baseDefinition);i&&t.add(i);}if(e.snapshot?.element||e.differential?.element){let i=e.snapshot?.element||e.differential?.element;for(let n of i)if(n.type)for(let o of n.type){if(o.code&&(t.add(o.code),o.code==="Reference"&&o.targetProfile))for(let a of o.targetProfile){let c=this.extractResourceNameFromUrl(a);c&&r.add(c);}if(o.profile)for(let a of o.profile){let c=this.extractResourceNameFromUrl(a);c&&t.add(c);}}}return {realDeps:Array.from(t),refTargets:Array.from(r)}}extractResourceNameFromUrl(e){let t=e.match(/\/([^/]+)$/);return t?t[1]??null:null}};var F=class{options;constructor(e={}){this.options={format:"auto",validate:true,strict:false,...e};}async parseFromFile(e){let t=await readFile(e,"utf-8"),r=this.options.format==="auto"?this.detectFormat(t,e):this.options.format;return this.parseFromString(t,r)}async parseFromString(e,t){let r=t||this.detectFormat(e),i;return r==="ndjson"?i=this.parseNDJSON(e):i=this.parseJSON(e),this.options.validate&&this.validateSchemas(i),i}async parseFromFiles(e){let t=[];for(let r of e){let i=await this.parseFromFile(r);t.push(...i);}return t}parseSchema(e){if(!e.identifier)throw new Error("TypeSchema must have an identifier");if(!this.isValidIdentifier(e.identifier))throw new Error("TypeSchema identifier is invalid");return e}findByIdentifier(e,t){return e.filter(r=>this.matchesIdentifier(r.identifier,t))}findByUrl(e,t){return e.find(r=>r.identifier.url===t)}findByKind(e,t){return e.filter(r=>r.identifier.kind===t)}findByPackage(e,t){return e.filter(r=>r.identifier.package===t)}detectFormat(e,t){if(t){if(t.endsWith(".ndjson"))return "ndjson";if(t.endsWith(".json"))return "json"}let r=e.trim();if(r.includes(`
15
+ `)){let i=r.split(`
16
+ `).filter(n=>n.trim());if(i.length>1)try{return i[0]&&JSON.parse(i[0]),"ndjson"}catch{}}return "json"}parseNDJSON(e){let t=[],r=e.split(`
17
+ `).filter(i=>i.trim());for(let i of r)try{let n=JSON.parse(i);t.push(this.parseSchema(n));}catch(n){if(this.options.strict)throw new Error(`Failed to parse NDJSON line: ${n}`)}return t}parseJSON(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.map(r=>this.parseSchema(r)):[this.parseSchema(t)]}catch(t){throw new Error(`Failed to parse JSON: ${t}`)}}validateSchemas(e){for(let t of e){if(!t.identifier)throw new Error("Schema missing identifier");if(!this.isValidIdentifier(t.identifier))throw new Error(`Invalid identifier in schema: ${JSON.stringify(t.identifier)}`)}}isValidIdentifier(e){return typeof e=="object"&&e!==null&&typeof e.kind=="string"&&typeof e.package=="string"&&typeof e.version=="string"&&typeof e.name=="string"&&typeof e.url=="string"}matchesIdentifier(e,t){return (!t.kind||e.kind===t.kind)&&(!t.package||e.package===t.package)&&(!t.version||e.version===t.version)&&(!t.name||e.name===t.name)&&(!t.url||e.url===t.url)}};E();var J=class{constructor(e){this.options=e;}handleError(e,t){e instanceof y?this.handleGeneratorError(e,t):this.handleUnknownError(e,t);}handleBatchErrors(e){let t=e.filter(i=>i instanceof y),r=e.filter(i=>!(i instanceof y));t.length>0&&this.reportBatchErrors(t),r.forEach(i=>{this.handleUnknownError(i);});}handleGeneratorError(e,t){switch(this.options.outputFormat){case "json":this.reportErrorAsJson(e);break;case "structured":this.reportErrorStructured(e);break;default:this.reportErrorToConsole(e);}}handleUnknownError(e,t){this.options.logger.error("Unexpected error occurred:",e),this.options.verbose&&(console.error(`
18
+ \u{1F6A8} Unexpected Error Details:`),console.error(` Type: ${e.constructor.name}`),console.error(` Message: ${e.message}`),e.stack&&console.error(` Stack: ${e.stack}`),t?.schema&&console.error(` Schema: ${t.schema.identifier.name}`),t?.filename&&console.error(` File: ${t.filename}`)),console.error(`
19
+ \u{1F4A1} General troubleshooting suggestions:`),console.error(" \u2022 Run with --verbose flag for more details"),console.error(" \u2022 Check your input files for corruption"),console.error(" \u2022 Update to the latest version of atomic-codegen"),console.error(" \u2022 Report this issue at: https://github.com/atomic-ehr/codegen/issues");}reportErrorToConsole(e){if("getFormattedMessage"in e)console.error(e.getFormattedMessage());else {console.error(`
20
+ \u274C ${e.constructor.name}: ${e.message}`);let t=e.getSuggestions();t.length>0&&(console.error(`
21
+ \u{1F4A1} Suggestions:`),t.forEach(r=>{console.error(` \u2022 ${r}`);}));}this.options.verbose&&e.context&&(console.error(`
22
+ \u{1F50D} Debug Information:`),console.error(JSON.stringify(e.context,null,2)));}reportErrorAsJson(e){let t={type:e.constructor.name,message:e.message,phase:e.phase,context:e.context,suggestions:e.getSuggestions(),timestamp:new Date().toISOString()};console.error(JSON.stringify(t,null,2));}reportErrorStructured(e){let t={error:{type:e.constructor.name,message:e.message,phase:e.phase},context:e.context,suggestions:e.getSuggestions(),actions:this.getRecoveryActions(e)};console.error("---"),console.error("Error Report:"),console.error(JSON.stringify(t,null,2)),console.error("---");}reportBatchErrors(e){console.error(`
23
+ \u274C ${e.length} errors occurred during generation:`);let t=new Map;e.forEach(r=>{let i=r.constructor.name;t.has(i)||t.set(i,[]),t.get(i)?.push(r);});for(let[r,i]of t){console.error(`
24
+ \u{1F4CB} ${r} (${i.length} occurrences):`),i.forEach((o,a)=>{console.error(` ${a+1}. ${o.message}`),o.context?.schemaName&&console.error(` Schema: ${o.context.schemaName}`);});let n=this.getCommonSuggestions(i);n.length>0&&(console.error(`
25
+ \u{1F4A1} Common suggestions:`),n.forEach(o=>{console.error(` \u2022 ${o}`);}));}}getCommonSuggestions(e){let t=e.flatMap(n=>n.getSuggestions()),r=new Map;t.forEach(n=>{r.set(n,(r.get(n)||0)+1);});let i=Math.ceil(e.length/2);return Array.from(r.entries()).filter(([n,o])=>o>=i).map(([n,o])=>n).slice(0,5)}getRecoveryActions(e){return "getRecoveryActions"in e?e.getRecoveryActions():[{action:"Review error message and suggestions above"},{action:"Check input files and configuration"},{action:"Try with --verbose flag for more information"}]}},K=class{constructor(e){this.errorHandler=e;}async withErrorBoundary(e,t){try{return await e()}catch(r){throw this.errorHandler.handleError(r instanceof Error?r:new Error(String(r)),t),r}}async withBatchErrorBoundary(e,t){let r=[],i=[];for(let n of e)try{let o=await n();r.push(o);}catch(o){i.push(o instanceof Error?o:new Error(String(o)));}if(i.length>0)throw this.errorHandler.handleBatchErrors(i),new q(`${i.length} operations failed`,i.filter(n=>n instanceof y));return r}};E();E();var W=class{options;logger;constructor(e){this.options={overwrite:true,batchSize:10,...e},this.logger=e.logger;}async writeFile(e,t,r={}){let i=performance.now(),n=join(this.options.outputDir,e),o=r.encoding||"utf-8",a=r.overwrite??this.options.overwrite;try{if(!a)try{await access(n),this.logger.debug(`Skipping existing file: ${e}`);let p=await stat(n);return {path:n,size:p.size,writeTime:0}}catch{}await this.ensureDirectory(dirname(n)),await writeFile(n,t,o);let c=performance.now()-i,l=Buffer.byteLength(t,o);return this.logger.debug(`Written ${e} (${l} bytes, ${c.toFixed(2)}ms)`),{path:n,size:l,writeTime:c}}catch(c){throw new w(`Failed to write file '${e}': ${c}`,"write",n,c instanceof Error?c:void 0,{canRetry:true,alternativePaths:[join(process.cwd(),"backup-output",e)]})}}async writeBatch(e){this.logger.debug(`Writing batch of ${e.size} files`);let t=Array.from(e.entries()),r=[];for(let i=0;i<t.length;i+=this.options.batchSize){let o=t.slice(i,i+this.options.batchSize).map(([c,l])=>this.writeFile(c,l)),a=await Promise.all(o);r.push(...a),i+this.options.batchSize<t.length&&await new Promise(c=>setTimeout(c,10));}return r}async ensureDirectory(e){try{await mkdir(e,{recursive:!0});}catch(t){throw new w(`Failed to create directory '${e}': ${t}`,"create",e,t instanceof Error?t:void 0,{canRetry:true,permissionFix:`chmod 755 "${dirname(e)}"`})}}async cleanDirectory(e="."){let t=join(this.options.outputDir,e);try{await access(t),this.logger.debug(`Cleaning directory: ${e}`),await rm(t,{recursive:!0,force:!0});}catch(r){if(r?.code!=="ENOENT")throw new w(`Failed to clean directory '${e}': ${r}`,"delete",t,r instanceof Error?r:void 0,{canRetry:true})}}getRelativeImportPath(e,t){let r=dirname(join(this.options.outputDir,e)),i=join(this.options.outputDir,t),n=relative(r,i);return n.startsWith(".")||(n=`./${n}`),n.replace(/\.(d\.ts|ts|tsx|js|jsx)$/,"")}async wouldOverwrite(e){let t=join(this.options.outputDir,e);try{return await access(t),!0}catch{return false}}async getFileStats(e){let t=join(this.options.outputDir,e);try{return {size:(await stat(t)).size,generationTime:0,writeTime:0}}catch{return null}}getOutputDirectory(){return this.options.outputDir}setBatchSize(e){this.options.batchSize=Math.max(1,Math.min(50,e));}getBatchSize(){return this.options.batchSize}};var Z=class{options;logger;fileManager;templateEngine;typeMapper;errorHandler;errorBoundary;progressCallback;generatedFiles=[];generationStartTime=0;cache=new Map;constructor(e){let t=this.validateConfiguration(e);if(!t.isValid)throw new z(`Invalid generator configuration: ${t.errors.join(", ")}`,"configuration",e);this.options=this.mergeWithDefaults(e),this.logger=e.logger||b({prefix:this.getLanguageName(),verbose:this.options.verbose||false}),this.fileManager=this.createFileManager(),this.templateEngine=this.createTemplateEngine(),this.typeMapper=this.createTypeMapper(),this.errorHandler=new J({logger:this.logger,verbose:this.options.verbose||false,beginnerMode:this.options.beginnerMode||false,outputFormat:this.options.errorFormat||"console"}),this.errorBoundary=new K(this.errorHandler),this.logger.debug(`${this.getLanguageName()} generator initialized`),t.warnings.length>0&&t.warnings.forEach(r=>{this.logger.warn(`Configuration warning: ${r}`);});}getCapabilities(){return {language:this.getLanguageName(),fileExtensions:[this.getFileExtension()],supportsTemplates:true,supportsCustomTypeMapping:true,supportsIncrementalGeneration:false,supportsValidation:true,supportedSchemaKinds:["resource","complex-type","profile","logical"],version:"1.0.0"}}createFileManager(){return new W({outputDir:this.options.outputDir,logger:this.logger.child("FileManager"),overwrite:this.options.overwrite})}createTemplateEngine(){}async generate(e){return this.errorBoundary.withErrorBoundary(async()=>{this.generationStartTime=performance.now(),this.generatedFiles=[],this.logger.info(`Starting ${this.getLanguageName()} generation for ${e.length} schemas`),this.reportProgress("validation",0,e.length,"Validating schemas..."),await this.validateSchemas(e),this.reportProgress("generation",0,e.length,"Processing schemas...");let t=this.filterAndSortSchemas(e);this.logger.debug(`Filtered to ${t.length} schemas for generation`),await this.generateFiles(t),await this.runPostGenerationHooks(),this.reportProgress("complete",e.length,e.length,"Generation complete");let r=performance.now()-this.generationStartTime;return this.logger.info(`Generated ${this.generatedFiles.length} files in ${r.toFixed(2)}ms (avg ${(r/this.generatedFiles.length).toFixed(2)}ms per file)`),this.generatedFiles},{operationName:"generate"})}async build(e){let t=this.fileManager.writeFile,r=new Map;this.fileManager.writeFile=async(i,n)=>{let o={path:`${this.options.outputDir}/${i}`,size:Buffer.byteLength(n,"utf-8"),writeTime:0};return r.set(i,o),o};try{let i=await this.generate(e);return i.forEach(n=>{let o=r.get(n.filename);o&&(n.path=o.path,n.size=o.size);}),i}finally{this.fileManager.writeFile=t;}}file(e){if(!this.templateEngine)throw new Error("Template engine is required for fluent file generation. Override createTemplateEngine() in your generator.");let{FileBuilder:t}=(Je(),ie(qe));return new t({filename:this.ensureFileExtension(e),fileManager:this.fileManager,templateEngine:this.templateEngine,typeMapper:this.typeMapper,logger:this.logger.child("FileBuilder")})}directory(e){let{DirectoryBuilder:t}=(We(),ie(Ke));return new t({path:e,fileManager:this.fileManager,logger:this.logger.child("DirectoryBuilder")})}index(e="."){if(!this.templateEngine)throw new Error("Template engine is required for index file generation. Override createTemplateEngine() in your generator.");let{IndexBuilder:t}=(Ye(),ie(Ze));return new t({directory:e,fileManager:this.fileManager,templateEngine:this.templateEngine,logger:this.logger.child("IndexBuilder")})}onProgress(e){return this.progressCallback=e,this}validateConfiguration(e){let t=[],r=[],i=[];return e.outputDir||(t.push("outputDir is required"),i.push("Provide a valid output directory path")),e.outputDir&&typeof e.outputDir!="string"&&t.push("outputDir must be a string"),e.overwrite!==void 0&&typeof e.overwrite!="boolean"&&t.push("overwrite must be a boolean"),e.validate!==void 0&&typeof e.validate!="boolean"&&t.push("validate must be a boolean"),e.outputDir&&!at("path").isAbsolute(e.outputDir)&&(r.push("Using relative path for outputDir - consider using absolute path"),i.push("Use path.resolve() to convert to absolute path")),e.validate===false&&(r.push("Validation is disabled - this may lead to invalid generated code"),i.push("Consider enabling validation for better code quality")),{isValid:t.length===0,errors:t,warnings:r,suggestions:i}}mergeWithDefaults(e){return {overwrite:true,validate:true,verbose:false,beginnerMode:false,errorFormat:"console",...e}}async validateSchemas(e){if(!this.options.validate){this.logger.debug("Schema validation disabled");return}this.logger.info(`\u{1F50D} Starting schema validation for ${e.length} schemas`),this.logger.debug("Schema validation enabled - performing comprehensive validation");let t=e.map(r=>()=>this.errorBoundary.withErrorBoundary(async()=>{await this.validateSchema(r),this.reportProgress("validation",e.indexOf(r)+1,e.length,`Validated ${r.identifier?.name||"schema"}`);},{schema:r,operationName:"validateSchema"}));await this.errorBoundary.withBatchErrorBoundary(t,{operationName:"validateSchemas"}),this.logger.debug(`Successfully validated ${e.length} schemas`);}async validateSchema(e){let t=[],r=e.identifier?.name||"unknown";if(this.logger.debug(`\u{1F50D} Validating schema: ${r} (kind: ${e.identifier?.kind})`),!e.identifier)t.push("Schema missing identifier"),this.logger.warn(`\u274C Schema missing identifier: ${JSON.stringify(e,null,2).substring(0,200)}...`);else if(e.identifier.name||t.push("Schema identifier missing name"),!e.identifier.kind)t.push("Schema identifier missing kind");else {let i=["resource","complex-type","profile","primitive-type","logical","value-set","binding","extension"];i.includes(e.identifier.kind)||t.push(`Schema identifier.kind must be one of: ${i.join(", ")}`);}if("fields"in e&&e.fields)for(let[i,n]of Object.entries(e.fields))i.trim()||t.push("Field name cannot be empty"),n||t.push(`Field '${i}' is null or undefined`);if(await this.detectCircularReferences(e)&&this.logger.warn(`\u26A0\uFE0F Circular reference detected in schema '${r}' - this may be expected for FHIR primitive types`),t.length>0)throw this.logger.error(`\u274C Schema validation failed for '${r}': ${t.join(", ")}`),this.logger.debug(`Schema details: ${JSON.stringify(e,null,2)}`),new _(`Schema validation failed for '${e.identifier?.name||"unknown"}'`,e,t);this.logger.debug(`\u2705 Schema validation passed for '${r}'`);}async detectCircularReferences(e){let t=new Set,r=new Set;return (n=>{let o=n.identifier?.name;if(!o)return false;if(r.has(o))return true;if(t.has(o))return false;if(r.add(o),"fields"in n&&n.fields){for(let a of Object.values(n.fields))if(a?.type?.name===o)return true}return r.delete(o),t.add(o),false})(e)}async generateFiles(e){let t=e.map((r,i)=>()=>this.errorBoundary.withErrorBoundary(async()=>{let n=await this.generateFileForSchema(r,i,e.length);return this.generatedFiles.push(n),n},{schema:r,operationName:"generateFile"}));await this.errorBoundary.withBatchErrorBoundary(t,{operationName:"generateFiles"}),this.logger.debug(`Generated ${this.generatedFiles.length} files`);}async generateFileForSchema(e,t,r){let i=performance.now(),n={schema:e,typeMapper:this.typeMapper,filename:this.typeMapper.formatFileName(e.identifier?.name||"unknown"),language:this.getLanguageName(),timestamp:new Date().toISOString(),imports:new Map,exports:new Set},o=await this.generateSchemaContent(e,n);this.options.validate&&await this.validateContent(o,n);let a=n.filename+this.getFileExtension(),c=await this.fileManager.writeFile(a,o),l=performance.now()-i;return this.reportProgress("writing",t+1,r,`Generated ${a} (${c.size} bytes)`),{path:c.path,filename:a,content:o,exports:this.extractExports(o),size:c.size,timestamp:new Date,metadata:{generationTime:l,schemaCount:1,templateName:n.templateName?.toString(),warnings:[]}}}ensureFileExtension(e){let t=this.getFileExtension();return e.endsWith(t)?e:`${e}${t}`}extractExports(e){let t=[],r=/export\s*\{\s*([^}]+)\s*\}/g,i;for(;(i=r.exec(e))!==null;)if(i[1]){let o=i[1].split(",").map(a=>a.trim()).filter(Boolean);t.push(...o);}let n=/export\s+(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/g;for(;(i=n.exec(e))!==null;)i[1]&&t.push(i[1]);return [...new Set(t)]}reportProgress(e,t,r,i,n){this.progressCallback&&this.progressCallback(e,t,r,i,n),i&&this.options.verbose&&this.logger.debug(`[${e}] ${i} (${t}/${r})`);}async runPostGenerationHooks(){}getCachedOrCompute(e,t){if(this.cache.has(e))return this.cache.get(e);let r=t();return r instanceof Promise?r.then(i=>(this.cache.set(e,i),i)):(this.cache.set(e,r),r)}clearCache(){this.cache.clear();}getGenerationStats(){let e=this.generatedFiles.reduce((r,i)=>r+i.size,0),t=performance.now()-this.generationStartTime;return {filesGenerated:this.generatedFiles.length,totalSize:e,averageFileSize:this.generatedFiles.length>0?e/this.generatedFiles.length:0,generationTime:t,averageTimePerFile:this.generatedFiles.length>0?t/this.generatedFiles.length:0,cacheHitRate:0}}};var Y=class{options;constructor(e={}){this.options={generateNullable:true,strictTypes:true,customMappings:{},preferArraySyntax:true,namingConvention:"PascalCase",...e};}mapType(e){if(typeof e=="string")return this.mapPrimitive(e);if(e&&typeof e=="object")switch(e.kind||e.type){case "primitive-type":return this.mapPrimitive(e.name);case "reference":return this.mapReference(e.targets||[]);case "array":{let r=this.mapType(e.element);return this.mapArray(r)}case "enum":case "coded":return this.mapEnum(e.values||[],e.name);case "complex-type":case "resource":return this.mapComplexType(e);default:return this.mapUnknownType(e)}return this.mapUnknownType(e)}mapComplexType(e){return {name:this.formatTypeName(e.name||"Unknown"),isPrimitive:false,importPath:this.calculateImportPath(e),nullable:!e.required&&this.options.generateNullable,metadata:{kind:e.kind,package:e.package}}}mapUnknownType(e){return {name:"unknown",isPrimitive:true,nullable:true,metadata:{originalType:e,warning:"unmapped_type"}}}calculateImportPath(e){return e.name?`./${this.formatFileName(e.name)}`:void 0}applyNamingConvention(e){switch(this.options.namingConvention){case "camelCase":return Qe(e);case "PascalCase":return Dt(e);case "snake_case":return Xe(e);case "kebab-case":return Bt(e);default:return e}}getCustomMapping(e){return this.options.customMappings[e]}shouldBeNullable(e){return !e&&this.options.generateNullable}};function Qe(s){return s.replace(/[-_\s]+(.)?/g,(e,t)=>t?.toUpperCase()||"")}function Dt(s){let e=Qe(s);return e.charAt(0).toUpperCase()+e.slice(1)}function Xe(s){return s.replace(/([A-Z])/g,"_$1").replace(/[-\s]+/g,"_").toLowerCase().replace(/^_/,"")}function Bt(s){return Xe(s).replace(/_/g,"-")}var Q=class extends Y{tsOptions;constructor(e={}){super(e),this.tsOptions={...this.options,preferUnknown:true,useBrandedTypes:false,preferUndefined:true,moduleFormat:"esm",...e};}getLanguageName(){return "TypeScript"}mapPrimitive(e){let t=this.getCustomMapping(e);if(t)return {name:t,isPrimitive:true,nullable:false};let i={string:"string",integer:"number",decimal:"number",boolean:"boolean",dateTime:"string",date:"string",time:"string",instant:"string",uri:"string",url:"string",canonical:"string",oid:"string",uuid:"string",base64Binary:"string",code:"string",id:"string",markdown:"string",unsignedInt:"number",positiveInt:"number",xhtml:"string",json:"unknown"}[e];return i?this.tsOptions.useBrandedTypes&&e!==i?{name:`${i} & { readonly __brand: '${e}' }`,isPrimitive:false,importPath:"./brands",nullable:false,metadata:{isBranded:true,originalFhirType:e}}:{name:i,isPrimitive:true,nullable:false}:(console.warn(`Unknown FHIR primitive type: ${e}`),{name:this.tsOptions.preferUnknown?"unknown":"any",isPrimitive:true,nullable:false,metadata:{warning:"unmapped_primitive",originalType:e}})}mapReference(e){if(!e||e.length===0)return {name:"Reference",isPrimitive:false,importPath:"./Reference",generics:["unknown"],nullable:false};if(e.length===1){let r=e[0]?.name||"unknown";return {name:"Reference",isPrimitive:false,importPath:"./Reference",generics:[r==="unknown"?"unknown":`'${r}'`],nullable:false,metadata:{referencedType:r,referencedSchema:e[0]}}}return {name:"Reference",isPrimitive:false,importPath:"./Reference",generics:[e.map(r=>{let i=r.name||"unknown";return i==="unknown"?"unknown":`'${i}'`}).join(" | ")],nullable:false,metadata:{referencedTypes:e.map(r=>r.name||"unknown"),referencedSchemas:e}}}mapArray(e){return this.options.preferArraySyntax?{name:`${e.name}[]`,isPrimitive:e.isPrimitive,importPath:e.importPath,isArray:true,nullable:false,metadata:{elementType:e,arrayStyle:"suffix"}}:{name:"Array",isPrimitive:false,generics:[e.name],isArray:true,nullable:false,metadata:{elementType:e,arrayStyle:"generic"}}}mapOptional(e,t){if(t||!this.shouldBeNullable(t))return e;let r=this.tsOptions.preferUndefined?"undefined":"null";return {...e,name:`${e.name} | ${r}`,nullable:true,metadata:{...e.metadata,nullabilityType:r,wasOptional:true}}}mapEnum(e,t){let r=t?this.formatTypeName(t):"CodedValue";return {name:e.map(n=>`'${n}'`).join(" | "),isPrimitive:false,nullable:false,metadata:{enumName:r,values:e,isUnionType:true}}}formatTypeName(e){return this.applyNamingConvention(e)}formatFieldName(e){return Vt(e)}formatFileName(e){return this.applyNamingConvention(e)}generateInterfaceField(e,t,r){return `${this.formatFieldName(e)}${r?"":"?"}: ${t.name};`}generateImportStatement(e){if(!(!e.importPath||e.isPrimitive))return this.tsOptions.moduleFormat==="esm"?`import type { ${e.name} } from '${e.importPath}';`:`const { ${e.name} } = require('${e.importPath}');`}getRequiredImports(e){let t=new Set;for(let r of e){let i=this.generateImportStatement(r);i&&t.add(i);}return Array.from(t).sort()}};function Vt(s){return s.replace(/[-_\s]+(.)?/g,(e,t)=>t?.toUpperCase()||"")}var P=class extends Z{resourceTypes=new Set;collectedValueSets=new Map;get tsOptions(){return this.options}getLanguageName(){return "TypeScript"}getFileExtension(){return ".ts"}createTypeMapper(){let e=this.options;return new Q({namingConvention:(e.namingConvention??"PascalCase")==="PascalCase"?"PascalCase":"camelCase",moduleFormat:e.moduleFormat==="cjs"?"commonjs":"esm",preferUndefined:true,...e.typeMapperOptions})}async generateSchemaContent(e,t){if(this.shouldSkipSchema(e))return "";if(e.identifier.kind==="resource"&&this.resourceTypes.add(this.typeMapper.formatTypeName(e.identifier.name)),e.identifier.name==="Reference")return this.generateReferenceInterface(e);let r=this.generateTypeScriptInterface(e),i="";return "nested"in e&&e.nested&&Array.isArray(e.nested)&&(i=e.nested.map(o=>this.generateNestedTypeInterface(e.identifier.name,o)).join(`
39
26
 
40
- cur_word="\${COMP_WORDS[COMP_CWORD]}"
41
- args=("\${COMP_WORDS[@]}")
27
+ `)),i?`${r}
42
28
 
43
- # ask yargs to generate completions.
44
- # see https://stackoverflow.com/a/40944195/7080036 for the spaces-handling awk
45
- mapfile -t type_list < <({{app_path}} --get-yargs-completions "\${args[@]}")
46
- mapfile -t COMPREPLY < <(compgen -W "$( printf '%q ' "\${type_list[@]}" )" -- "\${cur_word}" |
47
- awk '/ / { print "\\""$0"\\"" } /^[^ ]+$/ { print $0 }')
48
-
49
- # if no match was found, fall back to filename completion
50
- if [ \${#COMPREPLY[@]} -eq 0 ]; then
51
- COMPREPLY=()
52
- fi
53
-
54
- return 0
55
- }
56
- complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}
57
- ###-end-{{app_name}}-completions-###
58
- `,D3=`#compdef {{app_name}}
59
- ###-begin-{{app_name}}-completions-###
60
- #
61
- # yargs command completion script
62
- #
63
- # Installation: {{app_path}} {{completion_command}} >> ~/.zshrc
64
- # or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX.
65
- #
66
- _{{app_name}}_yargs_completions()
67
- {
68
- local reply
69
- local si=$IFS
70
- IFS=$'
71
- ' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}"))
72
- IFS=$si
73
- if [[ \${#reply} -gt 0 ]]; then
74
- _describe 'values' reply
75
- else
76
- _default
77
- fi
78
- }
79
- if [[ "'\${zsh_eval_context[-1]}" == "loadautofunc" ]]; then
80
- _{{app_name}}_yargs_completions "$@"
81
- else
82
- compdef _{{app_name}}_yargs_completions {{app_name}}
83
- fi
84
- ###-end-{{app_name}}-completions-###
85
- `;class F3{constructor(D,F,u,C){var E,B,$;this.yargs=D,this.usage=F,this.command=u,this.shim=C,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=($=((E=this.shim.getEnv("SHELL"))===null||E===void 0?void 0:E.includes("zsh"))||((B=this.shim.getEnv("ZSH_NAME"))===null||B===void 0?void 0:B.includes("zsh")))!==null&&$!==void 0?$:!1}defaultCompletion(D,F,u,C){let E=this.command.getCommandHandlers();for(let $=0,Z=D.length;$<Z;++$)if(E[D[$]]&&E[D[$]].builder){let Q=E[D[$]].builder;if(f0(Q)){this.indexAfterLastReset=$+1;let z=this.yargs.getInternalMethods().reset();return Q(z,!0),z.argv}}let B=[];this.commandCompletions(B,D,u),this.optionCompletions(B,D,F,u),this.choicesFromOptionsCompletions(B,D,F,u),this.choicesFromPositionalsCompletions(B,D,F,u),C(null,B)}commandCompletions(D,F,u){let C=this.yargs.getInternalMethods().getContext().commands;if(!u.match(/^-/)&&C[C.length-1]!==u&&!this.previousArgHasChoices(F))this.usage.getCommands().forEach((E)=>{let B=SD(E[0]).cmd;if(F.indexOf(B)===-1)if(!this.zshShell)D.push(B);else{let $=E[1]||"";D.push(B.replace(/:/g,"\\:")+":"+$)}})}optionCompletions(D,F,u,C){if((C.match(/^-/)||C===""&&D.length===0)&&!this.previousArgHasChoices(F)){let E=this.yargs.getOptions(),B=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(E.key).forEach(($)=>{let Z=!!E.configuration["boolean-negation"]&&E.boolean.includes($);if(!B.includes($)&&!E.hiddenOptions.includes($)&&!this.argsContainKey(F,$,Z))this.completeOptionKey($,D,C,Z&&!!E.default[$])})}}choicesFromOptionsCompletions(D,F,u,C){if(this.previousArgHasChoices(F)){let E=this.getPreviousArgChoices(F);if(E&&E.length>0)D.push(...E.map((B)=>B.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(D,F,u,C){if(C===""&&D.length>0&&this.previousArgHasChoices(F))return;let E=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],B=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),$=E[u._.length-B-1];if(!$)return;let Z=this.yargs.getOptions().choices[$]||[];for(let Q of Z)if(Q.startsWith(C))D.push(Q.replace(/:/g,"\\:"))}getPreviousArgChoices(D){if(D.length<1)return;let F=D[D.length-1],u="";if(!F.startsWith("-")&&D.length>1)u=F,F=D[D.length-2];if(!F.startsWith("-"))return;let C=F.replace(/^-+/,""),E=this.yargs.getOptions(),B=[C,...this.yargs.getAliases()[C]||[]],$;for(let Z of B)if(Object.prototype.hasOwnProperty.call(E.key,Z)&&Array.isArray(E.choices[Z])){$=E.choices[Z];break}if($)return $.filter((Z)=>!u||Z.startsWith(u))}previousArgHasChoices(D){let F=this.getPreviousArgChoices(D);return F!==void 0&&F.length>0}argsContainKey(D,F,u){let C=(E)=>D.indexOf((/^[^0-9]$/.test(E)?"-":"--")+E)!==-1;if(C(F))return!0;if(u&&C(`no-${F}`))return!0;if(this.aliases){for(let E of this.aliases[F])if(C(E))return!0}return!1}completeOptionKey(D,F,u,C){var E,B,$,Z;let Q=D;if(this.zshShell){let J=this.usage.getDescriptions(),W=(B=(E=this===null||this===void 0?void 0:this.aliases)===null||E===void 0?void 0:E[D])===null||B===void 0?void 0:B.find((P)=>{let c=J[P];return typeof c==="string"&&c.length>0}),_=W?J[W]:void 0,q=(Z=($=J[D])!==null&&$!==void 0?$:_)!==null&&Z!==void 0?Z:"";Q=`${D.replace(/:/g,"\\:")}:${q.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let z=(J)=>/^--/.test(J),O=(J)=>/^[^0-9]$/.test(J),A=!z(u)&&O(D)?"-":"--";if(F.push(A+Q),C)F.push(A+"no-"+Q)}customCompletion(D,F,u,C){if(OD(this.customCompletionFunction,null,this.shim),Pu(this.customCompletionFunction)){let E=this.customCompletionFunction(u,F);if(s(E))return E.then((B)=>{this.shim.process.nextTick(()=>{C(null,B)})}).catch((B)=>{this.shim.process.nextTick(()=>{C(B,void 0)})});return C(null,E)}else if(Su(this.customCompletionFunction))return this.customCompletionFunction(u,F,(E=C)=>this.defaultCompletion(D,F,u,E),(E)=>{C(null,E)});else return this.customCompletionFunction(u,F,(E)=>{C(null,E)})}getCompletion(D,F){let u=D.length?D[D.length-1]:"",C=this.yargs.parse(D,!0),E=this.customCompletionFunction?(B)=>this.customCompletion(D,B,u,F):(B)=>this.defaultCompletion(D,B,u,F);return s(C)?C.then(E):E(C)}generateCompletionScript(D,F){let u=this.zshShell?D3:e1,C=this.shim.path.basename(D);if(D.match(/\.js$/))D=`./${D}`;return u=u.replace(/{{app_name}}/g,C),u=u.replace(/{{completion_command}}/g,F),u.replace(/{{app_path}}/g,D)}registerFunction(D){this.customCompletionFunction=D}setParsed(D){this.aliases=D.aliases}}function u3(D,F,u,C){return new F3(D,F,u,C)}function Pu(D){return D.length<3}function Su(D){return D.length>3}function C3(D,F){if(D.length===0)return F.length;if(F.length===0)return D.length;let u=[],C;for(C=0;C<=F.length;C++)u[C]=[C];let E;for(E=0;E<=D.length;E++)u[0][E]=E;for(C=1;C<=F.length;C++)for(E=1;E<=D.length;E++)if(F.charAt(C-1)===D.charAt(E-1))u[C][E]=u[C-1][E-1];else if(C>1&&E>1&&F.charAt(C-2)===D.charAt(E-1)&&F.charAt(C-1)===D.charAt(E-2))u[C][E]=u[C-2][E-2]+1;else u[C][E]=Math.min(u[C-1][E-1]+1,Math.min(u[C][E-1]+1,u[C-1][E]+1));return u[F.length][D.length]}var E3=["$0","--","_"];function B3(D,F,u){let C=u.y18n.__,E=u.y18n.__n,B={};B.nonOptionCount=function(A){let J=D.getDemandedCommands(),_=A._.length+(A["--"]?A["--"].length:0)-D.getInternalMethods().getContext().commands.length;if(J._&&(_<J._.min||_>J._.max)){if(_<J._.min)if(J._.minMsg!==void 0)F.fail(J._.minMsg?J._.minMsg.replace(/\$0/g,_.toString()).replace(/\$1/,J._.min.toString()):null);else F.fail(E("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",_,_.toString(),J._.min.toString()));else if(_>J._.max)if(J._.maxMsg!==void 0)F.fail(J._.maxMsg?J._.maxMsg.replace(/\$0/g,_.toString()).replace(/\$1/,J._.max.toString()):null);else F.fail(E("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",_,_.toString(),J._.max.toString()))}},B.positionalCount=function(A,J){if(J<A)F.fail(E("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",J,J+"",A+""))},B.requiredArguments=function(A,J){let W=null;for(let _ of Object.keys(J))if(!Object.prototype.hasOwnProperty.call(A,_)||typeof A[_]>"u")W=W||{},W[_]=J[_];if(W){let _=[];for(let P of Object.keys(W)){let c=W[P];if(c&&_.indexOf(c)<0)_.push(c)}let q=_.length?`
86
- ${_.join(`
87
- `)}`:"";F.fail(E("Missing required argument: %s","Missing required arguments: %s",Object.keys(W).length,Object.keys(W).join(", ")+q))}},B.unknownArguments=function(A,J,W,_,q=!0){var P;let c=D.getInternalMethods().getCommandInstance().getCommands(),p=[],QD=D.getInternalMethods().getContext();if(Object.keys(A).forEach((d)=>{if(!E3.includes(d)&&!Object.prototype.hasOwnProperty.call(W,d)&&!Object.prototype.hasOwnProperty.call(D.getInternalMethods().getParseContext(),d)&&!B.isValidAndSomeAliasIsNotNew(d,J))p.push(d)}),q&&(QD.commands.length>0||c.length>0||_))A._.slice(QD.commands.length).forEach((d)=>{if(!c.includes(""+d))p.push(""+d)});if(q){let U=((P=D.getDemandedCommands()._)===null||P===void 0?void 0:P.max)||0,j=QD.commands.length+U;if(j<A._.length)A._.slice(j).forEach((S)=>{if(S=String(S),!QD.commands.includes(S)&&!p.includes(S))p.push(S)})}if(p.length)F.fail(E("Unknown argument: %s","Unknown arguments: %s",p.length,p.map((d)=>d.trim()?d:`"${d}"`).join(", ")))},B.unknownCommands=function(A){let J=D.getInternalMethods().getCommandInstance().getCommands(),W=[],_=D.getInternalMethods().getContext();if(_.commands.length>0||J.length>0)A._.slice(_.commands.length).forEach((q)=>{if(!J.includes(""+q))W.push(""+q)});if(W.length>0)return F.fail(E("Unknown command: %s","Unknown commands: %s",W.length,W.join(", "))),!0;else return!1},B.isValidAndSomeAliasIsNotNew=function(A,J){if(!Object.prototype.hasOwnProperty.call(J,A))return!1;let W=D.parsed.newAliases;return[A,...J[A]].some((_)=>!Object.prototype.hasOwnProperty.call(W,_)||!W[A])},B.limitedChoices=function(A){let J=D.getOptions(),W={};if(!Object.keys(J.choices).length)return;Object.keys(A).forEach((P)=>{if(E3.indexOf(P)===-1&&Object.prototype.hasOwnProperty.call(J.choices,P))[].concat(A[P]).forEach((c)=>{if(J.choices[P].indexOf(c)===-1&&c!==void 0)W[P]=(W[P]||[]).concat(c)})});let _=Object.keys(W);if(!_.length)return;let q=C("Invalid values:");_.forEach((P)=>{q+=`
88
- ${C("Argument: %s, Given: %s, Choices: %s",P,F.stringifiedValues(W[P]),F.stringifiedValues(J.choices[P]))}`}),F.fail(q)};let $={};B.implies=function(A,J){if(L("<string|object> [array|number|string]",[A,J],arguments.length),typeof A==="object")Object.keys(A).forEach((W)=>{B.implies(W,A[W])});else{if(D.global(A),!$[A])$[A]=[];if(Array.isArray(J))J.forEach((W)=>B.implies(A,W));else OD(J,void 0,u),$[A].push(J)}},B.getImplied=function(){return $};function Z(O,A){let J=Number(A);if(A=isNaN(J)?A:J,typeof A==="number")A=O._.length>=A;else if(A.match(/^--no-.+/))A=A.match(/^--no-(.+)/)[1],A=!Object.prototype.hasOwnProperty.call(O,A);else A=Object.prototype.hasOwnProperty.call(O,A);return A}B.implications=function(A){let J=[];if(Object.keys($).forEach((W)=>{let _=W;($[W]||[]).forEach((q)=>{let P=_,c=q;if(P=Z(A,P),q=Z(A,q),P&&!q)J.push(` ${_} -> ${c}`)})}),J.length){let W=`${C("Implications failed:")}
89
- `;J.forEach((_)=>{W+=_}),F.fail(W)}};let Q={};B.conflicts=function(A,J){if(L("<string|object> [array|string]",[A,J],arguments.length),typeof A==="object")Object.keys(A).forEach((W)=>{B.conflicts(W,A[W])});else{if(D.global(A),!Q[A])Q[A]=[];if(Array.isArray(J))J.forEach((W)=>B.conflicts(A,W));else Q[A].push(J)}},B.getConflicting=()=>Q,B.conflicting=function(A){if(Object.keys(A).forEach((J)=>{if(Q[J])Q[J].forEach((W)=>{if(W&&A[J]!==void 0&&A[W]!==void 0)F.fail(C("Arguments %s and %s are mutually exclusive",J,W))})}),D.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(Q).forEach((J)=>{Q[J].forEach((W)=>{if(W&&A[u.Parser.camelCase(J)]!==void 0&&A[u.Parser.camelCase(W)]!==void 0)F.fail(C("Arguments %s and %s are mutually exclusive",J,W))})})},B.recommendCommands=function(A,J){J=J.sort((P,c)=>c.length-P.length);let _=null,q=1/0;for(let P=0,c;(c=J[P])!==void 0;P++){let p=C3(A,c);if(p<=3&&p<q)q=p,_=c}if(_)F.fail(C("Did you mean %s?",_))},B.reset=function(A){return $=vD($,(J)=>!A[J]),Q=vD(Q,(J)=>!A[J]),B};let z=[];return B.freeze=function(){z.push({implied:$,conflicting:Q})},B.unfreeze=function(){let A=z.pop();OD(A,void 0,u),{implied:$,conflicting:Q}=A},B}var cF=[],M0;function V0(D,F,u,C){M0=C;let E={};if(Object.prototype.hasOwnProperty.call(D,"extends")){if(typeof D.extends!=="string")return E;let B=/\.json|\..*rc$/.test(D.extends),$=null;if(!B)try{$=import.meta.resolve(D.extends)}catch(Z){return D}else $=fu(F,D.extends);vu($),cF.push($),E=B?JSON.parse(M0.readFileSync($,"utf8")):C.require(D.extends),delete D.extends,E=V0(E,M0.path.dirname($),u,M0)}return cF=[],u?$3(E,D):Object.assign({},E,D)}function vu(D){if(cF.indexOf(D)>-1)throw new DD(`Circular extended configurations: '${D}'.`)}function fu(D,F){return M0.path.resolve(D,F)}function $3(D,F){let u={};function C(E){return E&&typeof E==="object"&&!Array.isArray(E)}Object.assign(u,D);for(let E of Object.keys(F))if(C(F[E])&&C(u[E]))u[E]=$3(D[E],F[E]);else u[E]=F[E];return u}var N=function(D,F,u,C,E){if(C==="m")throw TypeError("Private method is not writable");if(C==="a"&&!E)throw TypeError("Private accessor was defined without a setter");if(typeof F==="function"?D!==F||!E:!F.has(D))throw TypeError("Cannot write private member to an object whose class did not declare it");return C==="a"?E.call(D,u):E?E.value=u:F.set(D,u),u},X=function(D,F,u,C){if(u==="a"&&!C)throw TypeError("Private accessor was defined without a getter");if(typeof F==="function"?D!==F||!C:!F.has(D))throw TypeError("Cannot read private member from an object whose class did not declare it");return u==="m"?C:u==="a"?C.call(D):C?C.value:F.get(D)},FD,nD,K0,JD,AD,y0,kD,iD,h0,_D,d0,MD,ND,GD,VD,p0,tD,XD,b,g0,m0,HD,sD,O0,rD,yD,c0,k,aD,eD,D0,h,l0,TD,a;function I3(D){return(F=[],u=D.process.cwd(),C)=>{let E=new L3(F,u,C,D);return Object.defineProperty(E,"argv",{get:()=>{return E.parse()},enumerable:!0}),E.help(),E.version(),E}}var Z3=Symbol("copyDoubleDash"),X3=Symbol("copyDoubleDash"),lF=Symbol("deleteFromParserHintObject"),Q3=Symbol("emitWarning"),z3=Symbol("freeze"),Y3=Symbol("getDollarZero"),F0=Symbol("getParserConfiguration"),O3=Symbol("getUsageConfiguration"),oF=Symbol("guessLocale"),J3=Symbol("guessVersion"),W3=Symbol("parsePositionalNumbers"),nF=Symbol("pkgUp"),hD=Symbol("populateParserHintArray"),J0=Symbol("populateParserHintSingleValueDictionary"),iF=Symbol("populateParserHintArrayDictionary"),tF=Symbol("populateParserHintDictionary"),sF=Symbol("sanitizeKey"),rF=Symbol("setKey"),aF=Symbol("unfreeze"),A3=Symbol("validateAsync"),G3=Symbol("getCommandInstance"),H3=Symbol("getContext"),q3=Symbol("getHasOutput"),_3=Symbol("getLoggerInstance"),M3=Symbol("getParseContext"),V3=Symbol("getUsageInstance"),K3=Symbol("getValidationInstance"),o0=Symbol("hasParseCallback"),R3=Symbol("isGlobalContext"),u0=Symbol("postProcess"),U3=Symbol("rebase"),eF=Symbol("reset"),R0=Symbol("runYargsParserAndExecuteCommands"),D2=Symbol("runValidation"),j3=Symbol("setHasOutput"),C0=Symbol("kTrackManuallySetKeys"),ku="en_US";class L3{constructor(D=[],F,u,C){this.customScriptName=!1,this.parsed=!1,FD.set(this,void 0),nD.set(this,void 0),K0.set(this,{commands:[],fullCommands:[]}),JD.set(this,null),AD.set(this,null),y0.set(this,"show-hidden"),kD.set(this,null),iD.set(this,!0),h0.set(this,{}),_D.set(this,!0),d0.set(this,[]),MD.set(this,void 0),ND.set(this,{}),GD.set(this,!1),VD.set(this,null),p0.set(this,!0),tD.set(this,void 0),XD.set(this,""),b.set(this,void 0),g0.set(this,void 0),m0.set(this,{}),HD.set(this,null),sD.set(this,null),O0.set(this,{}),rD.set(this,{}),yD.set(this,void 0),c0.set(this,!1),k.set(this,void 0),aD.set(this,!1),eD.set(this,!1),D0.set(this,!1),h.set(this,void 0),l0.set(this,{}),TD.set(this,null),a.set(this,void 0),N(this,k,C,"f"),N(this,yD,D,"f"),N(this,nD,F,"f"),N(this,g0,u,"f"),N(this,MD,new gF(this),"f"),this.$0=this[Y3](),this[eF](),N(this,FD,X(this,FD,"f"),"f"),N(this,h,X(this,h,"f"),"f"),N(this,a,X(this,a,"f"),"f"),N(this,b,X(this,b,"f"),"f"),X(this,b,"f").showHiddenOpt=X(this,y0,"f"),N(this,tD,this[X3](),"f"),X(this,k,"f").y18n.setLocale(ku)}addHelpOpt(D,F){if(L("[string|boolean] [string]",[D,F],arguments.length),X(this,VD,"f"))this[lF](X(this,VD,"f")),N(this,VD,null,"f");if(D===!1&&F===void 0)return this;return N(this,VD,typeof D==="string"?D:"help","f"),this.boolean(X(this,VD,"f")),this.describe(X(this,VD,"f"),F||X(this,h,"f").deferY18nLookup("Show help")),this}help(D,F){return this.addHelpOpt(D,F)}addShowHiddenOpt(D,F){if(L("[string|boolean] [string]",[D,F],arguments.length),D===!1&&F===void 0)return this;let u=typeof D==="string"?D:X(this,y0,"f");return this.boolean(u),this.describe(u,F||X(this,h,"f").deferY18nLookup("Show hidden options")),X(this,b,"f").showHiddenOpt=u,this}showHidden(D,F){return this.addShowHiddenOpt(D,F)}alias(D,F){return L("<object|string|array> [string|array]",[D,F],arguments.length),this[iF](this.alias.bind(this),"alias",D,F),this}array(D){return L("<array|string>",[D],arguments.length),this[hD]("array",D),this[C0](D),this}boolean(D){return L("<array|string>",[D],arguments.length),this[hD]("boolean",D),this[C0](D),this}check(D,F){return L("<function> [boolean]",[D,F],arguments.length),this.middleware((u,C)=>{return oD(()=>{return D(u,C.getOptions())},(E)=>{if(!E)X(this,h,"f").fail(X(this,k,"f").y18n.__("Argument check failed: %s",D.toString()));else if(typeof E==="string"||E instanceof Error)X(this,h,"f").fail(E.toString(),E);return u},(E)=>{return X(this,h,"f").fail(E.message?E.message:E.toString(),E),u})},!1,F),this}choices(D,F){return L("<object|string|array> [string|array]",[D,F],arguments.length),this[iF](this.choices.bind(this),"choices",D,F),this}coerce(D,F){if(L("<object|string|array> [function]",[D,F],arguments.length),Array.isArray(D)){if(!F)throw new DD("coerce callback must be provided");for(let C of D)this.coerce(C,F);return this}else if(typeof D==="object"){for(let C of Object.keys(D))this.coerce(C,D[C]);return this}if(!F)throw new DD("coerce callback must be provided");let u=D;return X(this,b,"f").key[u]=!0,X(this,MD,"f").addCoerceMiddleware((C,E)=>{var B;let $=(B=E.getAliases()[u])!==null&&B!==void 0?B:[],Z=[u,...$].filter((Q)=>Object.prototype.hasOwnProperty.call(C,Q));if(Z.length===0)return C;return oD(()=>{return F(C[Z[0]])},(Q)=>{return Z.forEach((z)=>{C[z]=Q}),C},(Q)=>{throw new DD(Q.message)})},u),this}conflicts(D,F){return L("<string|object> [string|array]",[D,F],arguments.length),X(this,a,"f").conflicts(D,F),this}config(D="config",F,u){if(L("[object|string] [string|function] [function]",[D,F,u],arguments.length),typeof D==="object"&&!Array.isArray(D))return D=V0(D,X(this,nD,"f"),this[F0]()["deep-merge-config"]||!1,X(this,k,"f")),X(this,b,"f").configObjects=(X(this,b,"f").configObjects||[]).concat(D),this;if(typeof F==="function")u=F,F=void 0;return this.describe(D,F||X(this,h,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(D)?D:[D]).forEach((C)=>{X(this,b,"f").config[C]=u||!0}),this}completion(D,F,u){if(L("[string] [string|boolean|function] [function]",[D,F,u],arguments.length),typeof F==="function")u=F,F=void 0;if(N(this,AD,D||X(this,AD,"f")||"completion","f"),!F&&F!==!1)F="generate completion script";if(this.command(X(this,AD,"f"),F),u)X(this,JD,"f").registerFunction(u);return this}command(D,F,u,C,E,B){return L("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[D,F,u,C,E,B],arguments.length),X(this,FD,"f").addHandler(D,F,u,C,E,B),this}commands(D,F,u,C,E,B){return this.command(D,F,u,C,E,B)}commandDir(D,F){L("<string> [object]",[D,F],arguments.length);let u=X(this,g0,"f")||X(this,k,"f").require;return X(this,FD,"f").addDirectory(D,u,X(this,k,"f").getCallerFile(),F),this}count(D){return L("<array|string>",[D],arguments.length),this[hD]("count",D),this[C0](D),this}default(D,F,u){if(L("<object|string|array> [*] [string]",[D,F,u],arguments.length),u)pF(D,X(this,k,"f")),X(this,b,"f").defaultDescription[D]=u;if(typeof F==="function"){if(pF(D,X(this,k,"f")),!X(this,b,"f").defaultDescription[D])X(this,b,"f").defaultDescription[D]=X(this,h,"f").functionDescription(F);F=F.call()}return this[J0](this.default.bind(this),"default",D,F),this}defaults(D,F,u){return this.default(D,F,u)}demandCommand(D=1,F,u,C){if(L("[number] [number|string] [string|null|undefined] [string|null|undefined]",[D,F,u,C],arguments.length),typeof F!=="number")u=F,F=1/0;return this.global("_",!1),X(this,b,"f").demandedCommands._={min:D,max:F,minMsg:u,maxMsg:C},this}demand(D,F,u){if(Array.isArray(F))F.forEach((C)=>{OD(u,!0,X(this,k,"f")),this.demandOption(C,u)}),F=1/0;else if(typeof F!=="number")u=F,F=1/0;if(typeof D==="number")OD(u,!0,X(this,k,"f")),this.demandCommand(D,F,u,u);else if(Array.isArray(D))D.forEach((C)=>{OD(u,!0,X(this,k,"f")),this.demandOption(C,u)});else if(typeof u==="string")this.demandOption(D,u);else if(u===!0||typeof u>"u")this.demandOption(D);return this}demandOption(D,F){return L("<object|string|array> [string]",[D,F],arguments.length),this[J0](this.demandOption.bind(this),"demandedOptions",D,F),this}deprecateOption(D,F){return L("<string> [string|boolean]",[D,F],arguments.length),X(this,b,"f").deprecatedOptions[D]=F,this}describe(D,F){return L("<object|string|array> [string]",[D,F],arguments.length),this[rF](D,!0),X(this,h,"f").describe(D,F),this}detectLocale(D){return L("<boolean>",[D],arguments.length),N(this,iD,D,"f"),this}env(D){if(L("[string|boolean]",[D],arguments.length),D===!1)delete X(this,b,"f").envPrefix;else X(this,b,"f").envPrefix=D||"";return this}epilogue(D){return L("<string>",[D],arguments.length),X(this,h,"f").epilog(D),this}epilog(D){return this.epilogue(D)}example(D,F){if(L("<string|array> [string]",[D,F],arguments.length),Array.isArray(D))D.forEach((u)=>this.example(...u));else X(this,h,"f").example(D,F);return this}exit(D,F){if(N(this,GD,!0,"f"),N(this,kD,F,"f"),X(this,_D,"f"))X(this,k,"f").process.exit(D)}exitProcess(D=!0){return L("[boolean]",[D],arguments.length),N(this,_D,D,"f"),this}fail(D){if(L("<function|boolean>",[D],arguments.length),typeof D==="boolean"&&D!==!1)throw new DD("Invalid first argument. Expected function or boolean 'false'");return X(this,h,"f").failFn(D),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(D,F){if(L("<array> [function]",[D,F],arguments.length),!F)return new Promise((u,C)=>{X(this,JD,"f").getCompletion(D,(E,B)=>{if(E)C(E);else u(B)})});else return X(this,JD,"f").getCompletion(D,F)}getDemandedOptions(){return L([],0),X(this,b,"f").demandedOptions}getDemandedCommands(){return L([],0),X(this,b,"f").demandedCommands}getDeprecatedOptions(){return L([],0),X(this,b,"f").deprecatedOptions}getDetectLocale(){return X(this,iD,"f")}getExitProcess(){return X(this,_D,"f")}getGroups(){return Object.assign({},X(this,ND,"f"),X(this,rD,"f"))}getHelp(){if(N(this,GD,!0,"f"),!X(this,h,"f").hasCachedHelpMessage()){if(!this.parsed){let F=this[R0](X(this,yD,"f"),void 0,void 0,0,!0);if(s(F))return F.then(()=>{return X(this,h,"f").help()})}let D=X(this,FD,"f").runDefaultBuilderOn(this);if(s(D))return D.then(()=>{return X(this,h,"f").help()})}return Promise.resolve(X(this,h,"f").help())}getOptions(){return X(this,b,"f")}getStrict(){return X(this,aD,"f")}getStrictCommands(){return X(this,eD,"f")}getStrictOptions(){return X(this,D0,"f")}global(D,F){if(L("<string|array> [boolean]",[D,F],arguments.length),D=[].concat(D),F!==!1)X(this,b,"f").local=X(this,b,"f").local.filter((u)=>D.indexOf(u)===-1);else D.forEach((u)=>{if(!X(this,b,"f").local.includes(u))X(this,b,"f").local.push(u)});return this}group(D,F){L("<string|array> <string>",[D,F],arguments.length);let u=X(this,rD,"f")[F]||X(this,ND,"f")[F];if(X(this,rD,"f")[F])delete X(this,rD,"f")[F];let C={};return X(this,ND,"f")[F]=(u||[]).concat(D).filter((E)=>{if(C[E])return!1;return C[E]=!0}),this}hide(D){return L("<string>",[D],arguments.length),X(this,b,"f").hiddenOptions.push(D),this}implies(D,F){return L("<string|object> [number|string|array]",[D,F],arguments.length),X(this,a,"f").implies(D,F),this}locale(D){if(L("[string]",[D],arguments.length),D===void 0)return this[oF](),X(this,k,"f").y18n.getLocale();return N(this,iD,!1,"f"),X(this,k,"f").y18n.setLocale(D),this}middleware(D,F,u){return X(this,MD,"f").addMiddleware(D,!!F,u)}nargs(D,F){return L("<string|object|array> [number]",[D,F],arguments.length),this[J0](this.nargs.bind(this),"narg",D,F),this}normalize(D){return L("<array|string>",[D],arguments.length),this[hD]("normalize",D),this}number(D){return L("<array|string>",[D],arguments.length),this[hD]("number",D),this[C0](D),this}option(D,F){if(L("<string|object> [object]",[D,F],arguments.length),typeof D==="object")Object.keys(D).forEach((u)=>{this.options(u,D[u])});else{if(typeof F!=="object")F={};if(this[C0](D),X(this,TD,"f")&&(D==="version"||(F===null||F===void 0?void 0:F.alias)==="version"))this[Q3](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join(`
90
- `),void 0,"versionWarning");if(X(this,b,"f").key[D]=!0,F.alias)this.alias(D,F.alias);let u=F.deprecate||F.deprecated;if(u)this.deprecateOption(D,u);let C=F.demand||F.required||F.require;if(C)this.demand(D,C);if(F.demandOption)this.demandOption(D,typeof F.demandOption==="string"?F.demandOption:void 0);if(F.conflicts)this.conflicts(D,F.conflicts);if("default"in F)this.default(D,F.default);if(F.implies!==void 0)this.implies(D,F.implies);if(F.nargs!==void 0)this.nargs(D,F.nargs);if(F.config)this.config(D,F.configParser);if(F.normalize)this.normalize(D);if(F.choices)this.choices(D,F.choices);if(F.coerce)this.coerce(D,F.coerce);if(F.group)this.group(D,F.group);if(F.boolean||F.type==="boolean"){if(this.boolean(D),F.alias)this.boolean(F.alias)}if(F.array||F.type==="array"){if(this.array(D),F.alias)this.array(F.alias)}if(F.number||F.type==="number"){if(this.number(D),F.alias)this.number(F.alias)}if(F.string||F.type==="string"){if(this.string(D),F.alias)this.string(F.alias)}if(F.count||F.type==="count")this.count(D);if(typeof F.global==="boolean")this.global(D,F.global);if(F.defaultDescription)X(this,b,"f").defaultDescription[D]=F.defaultDescription;if(F.skipValidation)this.skipValidation(D);let E=F.describe||F.description||F.desc,B=X(this,h,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(B,D)||typeof E==="string")this.describe(D,E);if(F.hidden)this.hide(D);if(F.requiresArg)this.requiresArg(D)}return this}options(D,F){return this.option(D,F)}parse(D,F,u){if(L("[string|array] [function|boolean|object] [function]",[D,F,u],arguments.length),this[z3](),typeof D>"u")D=X(this,yD,"f");if(typeof F==="object")N(this,sD,F,"f"),F=u;if(typeof F==="function")N(this,HD,F,"f"),F=!1;if(!F)N(this,yD,D,"f");if(X(this,HD,"f"))N(this,_D,!1,"f");let C=this[R0](D,!!F),E=this.parsed;if(X(this,JD,"f").setParsed(this.parsed),s(C))return C.then((B)=>{if(X(this,HD,"f"))X(this,HD,"f").call(this,X(this,kD,"f"),B,X(this,XD,"f"));return B}).catch((B)=>{if(X(this,HD,"f"))X(this,HD,"f")(B,this.parsed.argv,X(this,XD,"f"));throw B}).finally(()=>{this[aF](),this.parsed=E});else{if(X(this,HD,"f"))X(this,HD,"f").call(this,X(this,kD,"f"),C,X(this,XD,"f"));this[aF](),this.parsed=E}return C}parseAsync(D,F,u){let C=this.parse(D,F,u);return!s(C)?Promise.resolve(C):C}parseSync(D,F,u){let C=this.parse(D,F,u);if(s(C))throw new DD(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return C}parserConfiguration(D){return L("<object>",[D],arguments.length),N(this,m0,D,"f"),this}pkgConf(D,F){L("<string> [string]",[D,F],arguments.length);let u=null,C=this[nF](F||X(this,nD,"f"));if(C[D]&&typeof C[D]==="object")u=V0(C[D],F||X(this,nD,"f"),this[F0]()["deep-merge-config"]||!1,X(this,k,"f")),X(this,b,"f").configObjects=(X(this,b,"f").configObjects||[]).concat(u);return this}positional(D,F){L("<string> <object>",[D,F],arguments.length);let u=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];F=vD(F,(B,$)=>{if(B==="type"&&!["string","number","boolean"].includes($))return!1;return u.includes(B)});let C=X(this,K0,"f").fullCommands[X(this,K0,"f").fullCommands.length-1],E=C?X(this,FD,"f").cmdToParseOptions(C):{array:[],alias:{},default:{},demand:{}};return z0(E).forEach((B)=>{let $=E[B];if(Array.isArray($)){if($.indexOf(D)!==-1)F[B]=!0}else if($[D]&&!(B in F))F[B]=$[D]}),this.group(D,X(this,h,"f").getPositionalGroupName()),this.option(D,F)}recommendCommands(D=!0){return L("[boolean]",[D],arguments.length),N(this,c0,D,"f"),this}required(D,F,u){return this.demand(D,F,u)}require(D,F,u){return this.demand(D,F,u)}requiresArg(D){if(L("<array|string|object> [number]",[D],arguments.length),typeof D==="string"&&X(this,b,"f").narg[D])return this;else this[J0](this.requiresArg.bind(this),"narg",D,NaN);return this}showCompletionScript(D,F){return L("[string] [string]",[D,F],arguments.length),D=D||this.$0,X(this,tD,"f").log(X(this,JD,"f").generateCompletionScript(D,F||X(this,AD,"f")||"completion")),this}showHelp(D){if(L("[string|function]",[D],arguments.length),N(this,GD,!0,"f"),!X(this,h,"f").hasCachedHelpMessage()){if(!this.parsed){let u=this[R0](X(this,yD,"f"),void 0,void 0,0,!0);if(s(u))return u.then(()=>{X(this,h,"f").showHelp(D)}),this}let F=X(this,FD,"f").runDefaultBuilderOn(this);if(s(F))return F.then(()=>{X(this,h,"f").showHelp(D)}),this}return X(this,h,"f").showHelp(D),this}scriptName(D){return this.customScriptName=!0,this.$0=D,this}showHelpOnFail(D,F){return L("[boolean|string] [string]",[D,F],arguments.length),X(this,h,"f").showHelpOnFail(D,F),this}showVersion(D){return L("[string|function]",[D],arguments.length),X(this,h,"f").showVersion(D),this}skipValidation(D){return L("<array|string>",[D],arguments.length),this[hD]("skipValidation",D),this}strict(D){return L("[boolean]",[D],arguments.length),N(this,aD,D!==!1,"f"),this}strictCommands(D){return L("[boolean]",[D],arguments.length),N(this,eD,D!==!1,"f"),this}strictOptions(D){return L("[boolean]",[D],arguments.length),N(this,D0,D!==!1,"f"),this}string(D){return L("<array|string>",[D],arguments.length),this[hD]("string",D),this[C0](D),this}terminalWidth(){return L([],0),X(this,k,"f").process.stdColumns}updateLocale(D){return this.updateStrings(D)}updateStrings(D){return L("<object>",[D],arguments.length),N(this,iD,!1,"f"),X(this,k,"f").y18n.updateLocale(D),this}usage(D,F,u,C){if(L("<string|null|undefined> [string|boolean] [function|object] [function]",[D,F,u,C],arguments.length),F!==void 0)if(OD(D,null,X(this,k,"f")),(D||"").match(/^\$0( |$)/))return this.command(D,F,u,C);else throw new DD(".usage() description must start with $0 if being used as alias for .command()");else return X(this,h,"f").usage(D),this}usageConfiguration(D){return L("<object>",[D],arguments.length),N(this,l0,D,"f"),this}version(D,F,u){if(L("[boolean|string] [string] [string]",[D,F,u],arguments.length),X(this,TD,"f"))this[lF](X(this,TD,"f")),X(this,h,"f").version(void 0),N(this,TD,null,"f");if(arguments.length===0)u=this[J3](),D="version";else if(arguments.length===1){if(D===!1)return this;u=D,D="version"}else if(arguments.length===2)u=F,F=void 0;return N(this,TD,typeof D==="string"?D:"version","f"),F=F||X(this,h,"f").deferY18nLookup("Show version number"),X(this,h,"f").version(u||void 0),this.boolean(X(this,TD,"f")),this.describe(X(this,TD,"f"),F),this}wrap(D){return L("<number|null|undefined>",[D],arguments.length),X(this,h,"f").wrap(D),this}[(FD=new WeakMap,nD=new WeakMap,K0=new WeakMap,JD=new WeakMap,AD=new WeakMap,y0=new WeakMap,kD=new WeakMap,iD=new WeakMap,h0=new WeakMap,_D=new WeakMap,d0=new WeakMap,MD=new WeakMap,ND=new WeakMap,GD=new WeakMap,VD=new WeakMap,p0=new WeakMap,tD=new WeakMap,XD=new WeakMap,b=new WeakMap,g0=new WeakMap,m0=new WeakMap,HD=new WeakMap,sD=new WeakMap,O0=new WeakMap,rD=new WeakMap,yD=new WeakMap,c0=new WeakMap,k=new WeakMap,aD=new WeakMap,eD=new WeakMap,D0=new WeakMap,h=new WeakMap,l0=new WeakMap,TD=new WeakMap,a=new WeakMap,Z3)](D){if(!D._||!D["--"])return D;D._.push.apply(D._,D["--"]);try{delete D["--"]}catch(F){}return D}[X3](){return{log:(...D)=>{if(!this[o0]())console.log(...D);if(N(this,GD,!0,"f"),X(this,XD,"f").length)N(this,XD,X(this,XD,"f")+`
91
- `,"f");N(this,XD,X(this,XD,"f")+D.join(" "),"f")},error:(...D)=>{if(!this[o0]())console.error(...D);if(N(this,GD,!0,"f"),X(this,XD,"f").length)N(this,XD,X(this,XD,"f")+`
92
- `,"f");N(this,XD,X(this,XD,"f")+D.join(" "),"f")}}}[lF](D){z0(X(this,b,"f")).forEach((F)=>{if(((C)=>C==="configObjects")(F))return;let u=X(this,b,"f")[F];if(Array.isArray(u)){if(u.includes(D))u.splice(u.indexOf(D),1)}else if(typeof u==="object")delete u[D]}),delete X(this,h,"f").getDescriptions()[D]}[Q3](D,F,u){if(!X(this,h0,"f")[u])X(this,k,"f").process.emitWarning(D,F),X(this,h0,"f")[u]=!0}[z3](){X(this,d0,"f").push({options:X(this,b,"f"),configObjects:X(this,b,"f").configObjects.slice(0),exitProcess:X(this,_D,"f"),groups:X(this,ND,"f"),strict:X(this,aD,"f"),strictCommands:X(this,eD,"f"),strictOptions:X(this,D0,"f"),completionCommand:X(this,AD,"f"),output:X(this,XD,"f"),exitError:X(this,kD,"f"),hasOutput:X(this,GD,"f"),parsed:this.parsed,parseFn:X(this,HD,"f"),parseContext:X(this,sD,"f")}),X(this,h,"f").freeze(),X(this,a,"f").freeze(),X(this,FD,"f").freeze(),X(this,MD,"f").freeze()}[Y3](){let D="",F;if(/\b(node|iojs|electron)(\.exe)?$/.test(X(this,k,"f").process.argv()[0]))F=X(this,k,"f").process.argv().slice(1,2);else F=X(this,k,"f").process.argv().slice(0,1);if(D=F.map((u)=>{let C=this[U3](X(this,nD,"f"),u);return u.match(/^(\/|([a-zA-Z]:)?\\)/)&&C.length<u.length?C:u}).join(" ").trim(),X(this,k,"f").getEnv("_")&&X(this,k,"f").getProcessArgvBin()===X(this,k,"f").getEnv("_"))D=X(this,k,"f").getEnv("_").replace(`${X(this,k,"f").path.dirname(X(this,k,"f").process.execPath())}/`,"");return D}[F0](){return X(this,m0,"f")}[O3](){return X(this,l0,"f")}[oF](){if(!X(this,iD,"f"))return;let D=X(this,k,"f").getEnv("LC_ALL")||X(this,k,"f").getEnv("LC_MESSAGES")||X(this,k,"f").getEnv("LANG")||X(this,k,"f").getEnv("LANGUAGE")||"en_US";this.locale(D.replace(/[.:].*/,""))}[J3](){return this[nF]().version||"unknown"}[W3](D){let F=D["--"]?D["--"]:D._;for(let u=0,C;(C=F[u])!==void 0;u++)if(X(this,k,"f").Parser.looksLikeNumber(C)&&Number.isSafeInteger(Math.floor(parseFloat(`${C}`))))F[u]=Number(C);return D}[nF](D){let F=D||"*";if(X(this,O0,"f")[F])return X(this,O0,"f")[F];let u={};try{let C=D||X(this,k,"f").mainFilename;if(X(this,k,"f").path.extname(C))C=X(this,k,"f").path.dirname(C);let E=X(this,k,"f").findUp(C,(B,$)=>{if($.includes("package.json"))return"package.json";else return});OD(E,void 0,X(this,k,"f")),u=JSON.parse(X(this,k,"f").readFileSync(E,"utf8"))}catch(C){}return X(this,O0,"f")[F]=u||{},X(this,O0,"f")[F]}[hD](D,F){F=[].concat(F),F.forEach((u)=>{u=this[sF](u),X(this,b,"f")[D].push(u)})}[J0](D,F,u,C){this[tF](D,F,u,C,(E,B,$)=>{X(this,b,"f")[E][B]=$})}[iF](D,F,u,C){this[tF](D,F,u,C,(E,B,$)=>{X(this,b,"f")[E][B]=(X(this,b,"f")[E][B]||[]).concat($)})}[tF](D,F,u,C,E){if(Array.isArray(u))u.forEach((B)=>{D(B,C)});else if(((B)=>typeof B==="object")(u))for(let B of z0(u))D(B,u[B]);else E(F,this[sF](u),C)}[sF](D){if(D==="__proto__")return"___proto___";return D}[rF](D,F){return this[J0](this[rF].bind(this),"key",D,F),this}[aF](){var D,F,u,C,E,B,$,Z,Q,z,O,A;let J=X(this,d0,"f").pop();OD(J,void 0,X(this,k,"f"));let W;D=this,F=this,u=this,C=this,E=this,B=this,$=this,Z=this,Q=this,z=this,O=this,A=this,{options:{set value(_){N(D,b,_,"f")}}.value,configObjects:W,exitProcess:{set value(_){N(F,_D,_,"f")}}.value,groups:{set value(_){N(u,ND,_,"f")}}.value,output:{set value(_){N(C,XD,_,"f")}}.value,exitError:{set value(_){N(E,kD,_,"f")}}.value,hasOutput:{set value(_){N(B,GD,_,"f")}}.value,parsed:this.parsed,strict:{set value(_){N($,aD,_,"f")}}.value,strictCommands:{set value(_){N(Z,eD,_,"f")}}.value,strictOptions:{set value(_){N(Q,D0,_,"f")}}.value,completionCommand:{set value(_){N(z,AD,_,"f")}}.value,parseFn:{set value(_){N(O,HD,_,"f")}}.value,parseContext:{set value(_){N(A,sD,_,"f")}}.value}=J,X(this,b,"f").configObjects=W,X(this,h,"f").unfreeze(),X(this,a,"f").unfreeze(),X(this,FD,"f").unfreeze(),X(this,MD,"f").unfreeze()}[A3](D,F){return oD(F,(u)=>{return D(u),u})}getInternalMethods(){return{getCommandInstance:this[G3].bind(this),getContext:this[H3].bind(this),getHasOutput:this[q3].bind(this),getLoggerInstance:this[_3].bind(this),getParseContext:this[M3].bind(this),getParserConfiguration:this[F0].bind(this),getUsageConfiguration:this[O3].bind(this),getUsageInstance:this[V3].bind(this),getValidationInstance:this[K3].bind(this),hasParseCallback:this[o0].bind(this),isGlobalContext:this[R3].bind(this),postProcess:this[u0].bind(this),reset:this[eF].bind(this),runValidation:this[D2].bind(this),runYargsParserAndExecuteCommands:this[R0].bind(this),setHasOutput:this[j3].bind(this)}}[G3](){return X(this,FD,"f")}[H3](){return X(this,K0,"f")}[q3](){return X(this,GD,"f")}[_3](){return X(this,tD,"f")}[M3](){return X(this,sD,"f")||{}}[V3](){return X(this,h,"f")}[K3](){return X(this,a,"f")}[o0](){return!!X(this,HD,"f")}[R3](){return X(this,p0,"f")}[u0](D,F,u,C){if(u)return D;if(s(D))return D;if(!F)D=this[Z3](D);if(this[F0]()["parse-positional-numbers"]||this[F0]()["parse-positional-numbers"]===void 0)D=this[W3](D);if(C)D=lD(D,this,X(this,MD,"f").getMiddleware(),!1);return D}[eF](D={}){N(this,b,X(this,b,"f")||{},"f");let F={};F.local=X(this,b,"f").local||[],F.configObjects=X(this,b,"f").configObjects||[];let u={};F.local.forEach((B)=>{u[B]=!0,(D[B]||[]).forEach(($)=>{u[$]=!0})}),Object.assign(X(this,rD,"f"),Object.keys(X(this,ND,"f")).reduce((B,$)=>{let Z=X(this,ND,"f")[$].filter((Q)=>!(Q in u));if(Z.length>0)B[$]=Z;return B},{})),N(this,ND,{},"f");let C=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],E=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(C.forEach((B)=>{F[B]=(X(this,b,"f")[B]||[]).filter(($)=>!u[$])}),E.forEach((B)=>{F[B]=vD(X(this,b,"f")[B],($)=>!u[$])}),F.envPrefix=X(this,b,"f").envPrefix,N(this,b,F,"f"),N(this,h,X(this,h,"f")?X(this,h,"f").reset(u):a1(this,X(this,k,"f")),"f"),N(this,a,X(this,a,"f")?X(this,a,"f").reset(u):B3(this,X(this,h,"f"),X(this,k,"f")),"f"),N(this,FD,X(this,FD,"f")?X(this,FD,"f").reset():t1(X(this,h,"f"),X(this,a,"f"),X(this,MD,"f"),X(this,k,"f")),"f"),!X(this,JD,"f"))N(this,JD,u3(this,X(this,h,"f"),X(this,FD,"f"),X(this,k,"f")),"f");return X(this,MD,"f").reset(),N(this,AD,null,"f"),N(this,XD,"","f"),N(this,kD,null,"f"),N(this,GD,!1,"f"),this.parsed=!1,this}[U3](D,F){return X(this,k,"f").path.relative(D,F)}[R0](D,F,u,C=0,E=!1){var B,$,Z,Q;let z=!!u||E;D=D||X(this,yD,"f"),X(this,b,"f").__=X(this,k,"f").y18n.__,X(this,b,"f").configuration=this[F0]();let O=!!X(this,b,"f").configuration["populate--"],A=Object.assign({},X(this,b,"f").configuration,{"populate--":!0}),J=X(this,k,"f").Parser.detailed(D,Object.assign({},X(this,b,"f"),{configuration:{"parse-positional-numbers":!1,...A}})),W=Object.assign(J.argv,X(this,sD,"f")),_=void 0,q=J.aliases,P=!1,c=!1;if(Object.keys(W).forEach((p)=>{if(p===X(this,VD,"f")&&W[p])P=!0;else if(p===X(this,TD,"f")&&W[p])c=!0}),W.$0=this.$0,this.parsed=J,C===0)X(this,h,"f").clearCachedHelpMessage();try{if(this[oF](),F)return this[u0](W,O,!!u,!1);if(X(this,VD,"f")){if([X(this,VD,"f")].concat(q[X(this,VD,"f")]||[]).filter((j)=>j.length>1).includes(""+W._[W._.length-1]))W._.pop(),P=!0}N(this,p0,!1,"f");let p=X(this,FD,"f").getCommands(),QD=((B=X(this,JD,"f"))===null||B===void 0?void 0:B.completionKey)?[($=X(this,JD,"f"))===null||$===void 0?void 0:$.completionKey,...(Q=this.getAliases()[(Z=X(this,JD,"f"))===null||Z===void 0?void 0:Z.completionKey])!==null&&Q!==void 0?Q:[]].some((U)=>Object.prototype.hasOwnProperty.call(W,U)):!1,d=P||QD||E;if(W._.length){if(p.length){let U;for(let j=C||0,S;W._[j]!==void 0;j++)if(S=String(W._[j]),p.includes(S)&&S!==X(this,AD,"f")){let l=X(this,FD,"f").runCommand(S,this,J,j+1,E,P||c||E);return this[u0](l,O,!!u,!1)}else if(!U&&S!==X(this,AD,"f")){U=S;break}if(!X(this,FD,"f").hasDefaultCommand()&&X(this,c0,"f")&&U&&!d)X(this,a,"f").recommendCommands(U,p)}if(X(this,AD,"f")&&W._.includes(X(this,AD,"f"))&&!QD){if(X(this,_D,"f"))fD(!0);this.showCompletionScript(),this.exit(0)}}if(X(this,FD,"f").hasDefaultCommand()&&!d){let U=X(this,FD,"f").runCommand(null,this,J,0,E,P||c||E);return this[u0](U,O,!!u,!1)}if(QD){if(X(this,_D,"f"))fD(!0);D=[].concat(D);let U=D.slice(D.indexOf(`--${X(this,JD,"f").completionKey}`)+1);return X(this,JD,"f").getCompletion(U,(j,S)=>{if(j)throw new DD(j.message);(S||[]).forEach((l)=>{X(this,tD,"f").log(l)}),this.exit(0)}),this[u0](W,!O,!!u,!1)}if(!X(this,GD,"f")){if(P){if(X(this,_D,"f"))fD(!0);z=!0,this.showHelp((U)=>{X(this,tD,"f").log(U),this.exit(0)})}else if(c){if(X(this,_D,"f"))fD(!0);z=!0,X(this,h,"f").showVersion("log"),this.exit(0)}}if(!z&&X(this,b,"f").skipValidation.length>0)z=Object.keys(W).some((U)=>X(this,b,"f").skipValidation.indexOf(U)>=0&&W[U]===!0);if(!z){if(J.error)throw new DD(J.error.message);if(!QD){let U=this[D2](q,{},J.error);if(!u)_=lD(W,this,X(this,MD,"f").getMiddleware(),!0);if(_=this[A3](U,_!==null&&_!==void 0?_:W),s(_)&&!u)_=_.then(()=>{return lD(W,this,X(this,MD,"f").getMiddleware(),!1)})}}}catch(p){if(p instanceof DD)X(this,h,"f").fail(p.message,p);else throw p}return this[u0](_!==null&&_!==void 0?_:W,O,!!u,!0)}[D2](D,F,u,C){let E={...this.getDemandedOptions()};return(B)=>{if(u)throw new DD(u.message);X(this,a,"f").nonOptionCount(B),X(this,a,"f").requiredArguments(B,E);let $=!1;if(X(this,eD,"f"))$=X(this,a,"f").unknownCommands(B);if(X(this,aD,"f")&&!$)X(this,a,"f").unknownArguments(B,D,F,!!C);else if(X(this,D0,"f"))X(this,a,"f").unknownArguments(B,D,{},!1,!1);X(this,a,"f").limitedChoices(B),X(this,a,"f").implications(B),X(this,a,"f").conflicting(B)}}[j3](){N(this,GD,!0,"f")}[C0](D){if(typeof D==="string")X(this,b,"f").key[D]=!0;else for(let F of D)X(this,b,"f").key[F]=!0}}function s1(D){return!!D&&typeof D.getInternalMethods==="function"}var yu=I3(dF),N3=yu;import{performance as b3}from"node:perf_hooks";var dD=b0(u2(),1);class gu{total;message;current=0;barLength=30;startTime=b3.now();constructor(D,F){this.total=D;this.message=F}update(D,F){this.current=Math.min(D,this.total),this.render(F)}increment(D){this.update(this.current+1,D)}complete(D){this.current=this.total,this.render();let F=Math.round(b3.now()-this.startTime);console.log(dD.default.green(`✅ ${D||this.message} ${dD.default.gray(`(${F}ms)`)}`))}render(D){let F=Math.round(this.current/this.total*100),u=Math.round(this.current/this.total*this.barLength),C=this.barLength-u,E=dD.default.green("█".repeat(u))+dD.default.gray("░".repeat(C)),B=`${this.current}/${this.total}`,$=D?dD.default.gray(` ${D}`):"";if(process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(`${this.message} ${E} ${dD.default.cyan(B)} ${dD.default.yellow(`${F}%`)}${$}`),this.current===this.total)process.stdout.write(`
93
- `)}}var $D=b0(u2(),1);class t0{options;constructor(D={}){this.options={timestamp:!1,verbose:!1,...D}}formatMessage(D,F,u){let C=this.options.timestamp?`${$D.default.gray(new Date().toLocaleTimeString())} `:"",E=this.options.prefix?`${$D.default.cyan(`[${this.options.prefix}]`)} `:"";return`${C}${u(D)} ${E}${F}`}success(D){console.log(this.formatMessage("✅",D,$D.default.green))}error(D,F){if(console.error(this.formatMessage("❌",D,$D.default.red)),F&&this.options.verbose){if(console.error($D.default.red(` ${F.message}`)),F.stack)console.error($D.default.gray(F.stack))}}warn(D){console.warn(this.formatMessage("⚠️",D,$D.default.yellow))}info(D){console.log(this.formatMessage("ℹ️",D,$D.default.blue))}debug(D){if(this.options.verbose)console.log(this.formatMessage("\uD83D\uDC1B",D,$D.default.magenta))}step(D){console.log(this.formatMessage("\uD83D\uDE80",D,$D.default.cyan))}progress(D){console.log(this.formatMessage("⏳",D,$D.default.blue))}plain(D,F=(u)=>u){let u=this.options.timestamp?`${$D.default.gray(new Date().toLocaleTimeString())} `:"",C=this.options.prefix?`${$D.default.cyan(`[${this.options.prefix}]`)} `:"";console.log(`${u}${C}${F(D)}`)}dim(D){this.plain(D,$D.default.gray)}child(D){return new t0({...this.options,prefix:this.options.prefix?`${this.options.prefix}:${D}`:D})}configure(D){this.options={...this.options,...D}}}var E0=new t0;function s0(D){E0.success(D)}function KD(D,F){E0.error(D,F)}function C2(D){E0.warn(D)}function r0(D){E0.info(D)}function E2(D){E0.step(D)}function x3(D){E0.dim(D)}function B2(D){E0.configure(D)}function jD(D={}){return new t0(D)}function $2(D){console.log(),console.log($D.default.cyan($D.default.bold(`━━━ ${D} ━━━`)))}function Z2(D,F,u){let C=D;if(F)C+=` ${$D.default.gray(`(${F}ms)`)}`;if(s0(C),u)Object.entries(u).forEach(([E,B])=>{x3(` ${E}: ${B}`)})}function B0(D,F="•"){D.forEach((u)=>{console.log($D.default.gray(` ${F} ${u}`))})}import{existsSync as o8}from"node:fs";import{resolve as n8}from"node:path";import{existsSync as a0,mkdirSync as P3}from"node:fs";import{readdir as S3,readFile as mu,stat as cu,unlink as v3,writeFile as lu}from"node:fs/promises";import{join as X2}from"node:path";class $0{cache=new Map;config;cacheDir;constructor(D){if(this.config={enablePersistence:!0,cacheDir:".typeschema-cache",maxAge:86400000,validateCached:!0,...D},this.config.enablePersistence&&this.config.cacheDir)this.cacheDir=this.config.cacheDir}async set(D){let F=this.generateKey(D.identifier);if(this.cache.set(F,D),this.config.enablePersistence&&this.cacheDir)await this.persistSchema(D)}get(D){let F=this.generateKey(D);return this.cache.get(F)||null}getByUrl(D){for(let F of this.cache.values())if(F.identifier.url===D)return F;return null}has(D){let F=this.generateKey(D);return this.cache.has(F)}hasByUrl(D){for(let F of this.cache.values())if(F.identifier.url===D)return!0;return!1}delete(D){let F=this.generateKey(D);return this.cache.delete(F)}deleteByUrl(D){for(let[F,u]of this.cache.entries())if(u.identifier.url===D)return this.cache.delete(F);return!1}getByPackage(D){let F=[];for(let u of this.cache.values())if(u.identifier.package===D)F.push(u);return F}getByKind(D){let F=[];for(let u of this.cache.values())if(u.identifier.kind===D)F.push(u);return F}setMany(D){for(let F of D)this.set(F)}clear(){this.cache.clear()}generateKey(D){return`${D.package}:${D.version}:${D.kind}:${D.name}`}async initialize(){if(this.config.enablePersistence&&this.cacheDir){if(!a0(this.cacheDir))P3(this.cacheDir,{recursive:!0});await this.loadFromDisk()}}async loadFromDisk(){if(!this.cacheDir||!a0(this.cacheDir))return;try{let F=(await S3(this.cacheDir)).filter((u)=>u.endsWith(".typeschema.json"));for(let u of F){let C=X2(this.cacheDir,u),E=await cu(C);if(this.config.maxAge){if(Date.now()-E.mtimeMs>this.config.maxAge){await v3(C);continue}}try{let B=await mu(C,"utf-8"),$=JSON.parse(B);if(this.config.validateCached){if(!$.schema?.identifier)continue}let Z=this.generateKey($.schema.identifier);this.cache.set(Z,$.schema)}catch(B){console.warn(`Failed to load cached schema from ${u}:`,B)}}}catch(D){console.warn("Failed to load cached schemas from disk:",D)}}async persistSchema(D){if(!this.cacheDir)return;if(!a0(this.cacheDir))P3(this.cacheDir,{recursive:!0});let F={schema:D,timestamp:Date.now(),version:D.identifier.version},u=`${D.identifier.package}-${D.identifier.version}-${D.identifier.kind}-${D.identifier.name}.typeschema.json`.replace(/[^a-zA-Z0-9.-]/g,"_"),C=X2(this.cacheDir,u);try{await lu(C,JSON.stringify(F,null,2),"utf-8")}catch(E){console.warn(`Failed to persist schema to ${C}:`,E)}}async clearDisk(){if(!this.cacheDir||!a0(this.cacheDir))return;try{let F=(await S3(this.cacheDir)).filter((u)=>u.endsWith(".typeschema.json"));for(let u of F)await v3(X2(this.cacheDir,u))}catch(D){console.warn("Failed to clear cache directory:",D)}}}import{createHash as ou}from"crypto";var Q2=(D)=>{let F=`${D.packageName}@${D.packageVersion}:${D.filePath}`;return ou("sha256").update(F).digest("base64url")};var W0=()=>{let D={},F={};return{generateId:Q2,get:(E)=>D[E],set:(E,B)=>{if(D[E]=B,B.url){if(!F[B.url])F[B.url]=[];let $=F[B.url];if($&&!$.includes(E))$.push(E)}},has:(E)=>(E in D),clear:()=>{Object.keys(D).forEach((E)=>delete D[E]),Object.keys(F).forEach((E)=>delete F[E])},size:()=>Object.keys(D).length,getIdsByUrl:(E)=>F[E]||[],createReference:(E,B)=>({id:E,resourceType:B.resourceType}),getAllReferences:()=>D}};import*as K2 from"path";import*as n3 from"fs/promises";var f3="https://fs.get-ig.org/pkgs/";import*as e0 from"fs/promises";import*as k3 from"path";var A0=async(D)=>{try{return await e0.access(D),!0}catch{return!1}},G0=async(D)=>{try{await e0.mkdir(D,{recursive:!0})}catch{}},DF=async(D)=>{let F=k3.join(D,".index.json");return A0(F)};import{exec as nu}from"child_process";import{promisify as iu}from"util";var y3=iu(nu);async function z2(){try{return await y3("bun --version"),"bun"}catch{try{return await y3("npm --version"),"npm"}catch{return null}}}import*as d3 from"fs/promises";import*as p3 from"path";import{exec as tu}from"child_process";import{promisify as su}from"util";var h3=su(tu),FF=async(D,F,u)=>{await G0(F);let C=p3.join(F,"package.json");if(!await A0(C))await d3.writeFile(C,JSON.stringify({name:"fhir-canonical-manager-workspace",version:"1.0.0",private:!0,dependencies:{}},null,2));let E=await z2();if(!E)throw Error("No package manager found. Please install npm or bun.");for(let B of D)try{if(E==="bun"){let $={...process.env,HOME:F,NPM_CONFIG_USERCONFIG:"/dev/null"},Z=u?`cd ${F} && bun add ${B} --registry ${u}`:`cd ${F} && bun add ${B}`;await h3(Z,{env:$,maxBuffer:10485760})}else{let $=u?`cd ${F} && npm add ${B} --registry ${u}`:`cd ${F} && npm add ${B}`;await h3($,{maxBuffer:10485760})}}catch($){throw console.error(`Failed to install package ${B}:`,$),$}};var uF=()=>{let D=W0();return{entries:{},packages:{},references:{},referenceManager:D}};import*as CF from"fs/promises";import*as J2 from"path";import*as Y2 from"fs/promises";import*as O2 from"path";import{createHash as g3}from"crypto";var U0=async(D)=>{try{let F=O2.join(D,"package-lock.json");try{let u=await Y2.readFile(F,"utf-8");return g3("sha256").update(u).digest("hex")}catch{let u=O2.join(D,"bun.lock"),C=await Y2.readFile(u,"utf-8");return g3("sha256").update(C).digest("hex")}}catch{return null}};var EF=async(D,F,u)=>{let C=await U0(u),E={entries:D.entries,packages:D.packages,references:D.referenceManager.getAllReferences(),packageLockHash:C||void 0},B=J2.join(F,"index.json");await CF.writeFile(B,JSON.stringify(E,null,2))},W2=async(D)=>{try{let F=J2.join(D,"index.json"),u=await CF.readFile(F,"utf-8");return JSON.parse(u)}catch{return null}};var m3=(D)=>{if(!D||typeof D!=="object")return!1;if(!D.filename||typeof D.filename!=="string")return!1;if(!D.resourceType||typeof D.resourceType!=="string")return!1;if(!D.id||typeof D.id!=="string")return!1;let F=["url","version","kind","type"];for(let u of F)if(D[u]!==void 0&&typeof D[u]!=="string")return!1;return!0},c3=(D)=>{if(!D||typeof D!=="object")return!1;if(!D["index-version"]||typeof D["index-version"]!=="number")return!1;if(!Array.isArray(D.files))return!1;return D.files.every((F)=>m3(F))},A2=(D,F)=>{try{let u=JSON.parse(D);if(!c3(u))return null;return u}catch{return null}};import*as l3 from"fs/promises";import*as G2 from"path";var BF=async(D,F,u)=>{let C=G2.join(D,".index.json");try{let E=await l3.readFile(C,"utf-8"),B=A2(E,C);if(!B)return;for(let $ of B.files){if(!$.url)continue;let Z=G2.join(D,$.filename),Q=u.referenceManager.generateId({packageName:F.name,packageVersion:F.version,filePath:Z});u.referenceManager.set(Q,{packageName:F.name,packageVersion:F.version,filePath:Z,resourceType:$.resourceType,url:$.url,version:$.version});let z={id:Q,resourceType:$.resourceType,indexVersion:B["index-version"],url:$.url,version:$.version,kind:$.kind,type:$.type,package:{name:F.name,version:F.version}};if(!u.entries[$.url])u.entries[$.url]=[];let O=u.entries[$.url];if(O)O.push(z)}}catch{}};import*as o3 from"fs/promises";import*as $F from"path";var ZF=async(D,F)=>{try{let u=$F.join(D,"package.json"),C=await o3.readFile(u,"utf-8"),E=JSON.parse(C),B={id:{name:E.name,version:E.version},path:D,canonical:E.canonical,fhirVersions:E.fhirVersions};F.packages[E.name]=B,await BF(D,E,F);let $=$F.join(D,"examples");if(await A0($F.join($,".index.json")))await BF($,E,F)}catch{}};import*as H2 from"fs/promises";import*as q2 from"path";var XF=async(D,F)=>{try{let u=await H2.readdir(D,{withFileTypes:!0});for(let C of u){if(!C.isDirectory())continue;let E=q2.join(D,C.name);if(C.name.startsWith("@")){let B=await H2.readdir(E,{withFileTypes:!0});for(let $ of B){if(!$.isDirectory())continue;let Z=q2.join(E,$.name);if(await DF(Z))await ZF(Z,F)}}else if(await DF(E))await ZF(E,F)}}catch{}};var _2=async(D,F,u,C)=>{if(F.package)try{return await C(D,{package:F.package.name,version:F.package.version})}catch{}return null};var M2={str:["structure"],struct:["structure"],def:["definition"],pati:["patient"],obs:["observation"],org:["organization"],pract:["practitioner"],med:["medication","medicinal"],req:["request"],resp:["response"],ref:["reference"],val:["value"],code:["codesystem","code"],cs:["codesystem"],vs:["valueset"],sd:["structuredefinition"]};var V2=(D,F)=>{if(F.length===0)return D;let u=F.map((C)=>C.toLowerCase());return D.filter((C)=>{if(!C.url)return!1;let B=[C.url.toLowerCase(),C.type?.toLowerCase()||"",C.resourceType?.toLowerCase()||""].join(" ");return u.every(($)=>{let Z=B.split(/[\/\-_\.\s]+/);if(Z.some((O)=>O.startsWith($)))return!0;let z=M2[$]||[];for(let O of z)if(Z.some((A)=>A.startsWith(O)))return!0;return B.includes($)})})};var pD=(D)=>{let{packages:F=[],workingDir:u}=D,C=D.registry?D.registry.endsWith("/")?D.registry:`${D.registry}/`:f3,E=K2.join(u,"node_modules"),B=K2.join(u,".fcm","cache"),$=uF(),Z=!1,Q=new Map,z=()=>{if(!Z)throw Error("CanonicalManager not initialized. Call init() first.")},O=async()=>{if(Z)return;await G0(u),await G0(B);let U=await U0(u),j=await W2(B);if(j&&j.packageLockHash===U&&U!==null)$.entries=j.entries,$.packages=j.packages,Object.entries(j.references).forEach(([l,g])=>{$.referenceManager.set(l,g)});else{if(j&&j.packageLockHash!==U)console.log("Package dependencies have changed, rebuilding index...");await FF(F,u,C),$=uF(),await XF(E,$),await EF($,B,u)}Z=!0},A=async()=>{$.entries={},$.packages={},$.referenceManager.clear(),Q.clear(),Z=!1},J=async()=>{return z(),Object.values($.packages).map((U)=>U.id)},W=async(...U)=>{if(U.length===0)return;let j=U.filter((S)=>!F.includes(S));if(j.length!==0)F.push(...j);if(!Z){await O();return}if(j.length===0)return;await FF(F,u,C),await XF(E,$),await EF($,B,u)},_=async(U,j)=>{if(z(),j?.sourceContext){let g=await _2(U,j.sourceContext,$,_);if(g)return g}let S=$.entries[U]||[];if(S.length===0)throw Error(`Cannot resolve canonical URL: ${U}`);let l=[...S];if(j?.package)l=l.filter((g)=>g.package?.name===j.package);if(j?.version)l=l.filter((g)=>g.version===j.version);if(l.length===0)throw Error(`No matching resource found for ${U} with given options`);return l[0]},q=async(U,j)=>{let S=await _(U,j);return P(S)},P=async(U)=>{z();let j=$.referenceManager.get(U.id);if(!j)throw Error(`Invalid reference ID: ${U.id}`);try{let S=await n3.readFile(j.filePath,"utf-8");return{...JSON.parse(S),id:U.id,resourceType:U.resourceType}}catch(S){throw Error(`Failed to read resource: ${S}`)}},c=async(U)=>{z();let j=[];if(U.url)j=$.entries[U.url]||[];else for(let S of Object.values($.entries))j.push(...S);if(U.kind!==void 0)j=j.filter((S)=>S.kind===U.kind);if(U.type!==void 0)j=j.filter((S)=>S.type===U.type);if(U.version!==void 0)j=j.filter((S)=>S.version===U.version);if(U.package){let S=U.package;j=j.filter((l)=>l.package?.name===S.name&&l.package?.version===S.version)}return j};return{init:O,destroy:A,packages:J,addPackages:W,resolveEntry:_,resolve:q,read:P,searchEntries:c,search:async(U)=>{let j=await c(U);return await Promise.all(j.map((l)=>P(l)))},smartSearch:async(U,j)=>{z();let S=await c({kind:j?.kind,package:j?.package});if(j?.resourceType)S=S.filter((l)=>l.resourceType===j.resourceType);if(j?.type)S=S.filter((l)=>l.type===j.type);return V2(S,U)},getSearchParametersForResource:async(U)=>{if(z(),Q.has(U))return Q.get(U);let S=(await c({})).filter((g)=>g.resourceType==="SearchParameter"),l=[];for(let g of S){let LD=await P(g),I=LD.base||[];if(Array.isArray(I)&&I.includes(U))l.push(LD)}return l.sort((g,LD)=>{let I=g.code||"",K=LD.code||"";return I.localeCompare(K)}),Q.set(U,l),l}}};function R2(D){let C=D.path.split(".").slice(1).map(($)=>({el:$}));if(C.length===0)return[];let E=C.length-1,B={};if(D.slicing){if(B.slicing={...D.slicing},D.min!==void 0)B.slicing.min=D.min;if(D.max&&D.max!=="*")B.slicing.max=parseInt(D.max)}if(D.sliceName){if(B.slice={},D.min!==void 0)B.slice.min=D.min;if(D.max&&D.max!=="*")B.slice.max=parseInt(D.max);B.sliceName=D.sliceName}return C[E]={...C[E],...B},C}function U2(D,F){let u=[],C=Math.min(D.length,F.length);for(let E=0;E<C;E++)if(D[E].el===F[E].el)u.push({el:D[E].el});else break;return u}function j2(D,F){let u=[];for(let C=0;C<F.length;C++)if(C<D.length&&D[C].el===F[C].el)u.push({...D[C],...F[C],...D[C].slicing&&!F[C].slicing&&{slicing:D[C].slicing}});else u.push(F[C]);return u}function ru(D,F){return!!(D.sliceName&&F.sliceName&&D.sliceName!==F.sliceName)}function i3(D){return{type:"exit-slice",sliceName:D.sliceName,...D.slicing&&{slicing:D.slicing},...D.slice&&{slice:D.slice}}}function au(D,F,u,C){let E=[];for(let B=D-1;B>=F;B--){let $=u[B];if($.sliceName)E.push(i3($));E.push({type:"exit",el:$.el})}if(F>0){let B=u[F-1],$=C[F-1];if(ru(B,$))E.push(i3(B))}return E}function eu(D,F,u,C){let E=[];if(D>0&&D<=F){let B=u[D-1]||{},$=C[D-1];if($.sliceName&&(!B.sliceName||B.sliceName!==$.sliceName))E.push({type:"enter-slice",sliceName:$.sliceName});if(D===F)return E}for(let B=D;B<F;B++){let $=C[B];if(E.push({type:"enter",el:$.el}),$.sliceName)E.push({type:"enter-slice",sliceName:$.sliceName})}return E}function QF(D,F){let u=D.length,C=F.length,B=U2(D,F).length,$=au(u,B,D,F),Z=eu(B,C,D,F);return[...$,...Z]}function s3(D,F){if(!D)return;return D.find((u)=>u.url===F)}function t3(D){return{Instant:"instant",Time:"time",Date:"date",DateTime:"dateTime",Decimal:"decimal",Boolean:"boolean",Integer:"integer",String:"string",Uri:"uri",Base64Binary:"base64Binary",Code:"code",Id:"id",Oid:"oid",UnsignedInt:"unsignedInt",PositiveInt:"positiveInt",Markdown:"markdown",Url:"url",Canonical:"canonical",Uuid:"uuid"}[D]||D}function D8(D){let F={};for(let[u,C]of Object.entries(D))if(typeof u==="string"&&u.startsWith("pattern")){let E=t3(u.replace(/^pattern/,""));F.pattern={type:E,value:C}}else if(typeof u==="string"&&u.startsWith("fixed")){let E=t3(u.replace(/^fixed/,""));F.pattern={type:E,value:C}}else F[u]=C;if(F.pattern?.type&&!F.type)F.type=F.pattern.type;return F}function F8(D){let F=[];for(let u of D)if(u.targetProfile){let C=Array.isArray(u.targetProfile)?u.targetProfile:[u.targetProfile];F.push(...C)}return F.length>0?[...new Set(F)].sort():void 0}function u8(D){if(!D.type||D.type.length===0)return D;if(D.type[0].code==="Reference"){let u=F8(D.type);return{...D,type:[{code:"Reference"}],...u&&{refers:u}}}return D}function C8(D,F){let u=(B)=>{let $={strength:B.strength,...B.valueSet&&{valueSet:B.valueSet}},Z=s3(B.extension,"http://hl7.org/fhir/StructureDefinition/elementdefinition-bindingName");if(Z?.valueString)$.bindingName=Z.valueString;return $};if(D.choices){let{binding:B,...$}=D;return $}if(D.choiceOf&&F.snapshot){let B=`${F.id}.${D.choiceOf}[x]`,$=F.snapshot.element.find((Z)=>Z.path===B);if($?.binding)return{...D,binding:u($.binding)}}if(D.binding?.valueSet)return{...D,binding:u(D.binding)};let{binding:C,...E}=D;return E}function E8(D){if(!D.constraint||D.constraint.length===0)return D;let F={};for(let u of D.constraint)F[u.key]={expression:u.expression,human:u.human,severity:u.severity};return{...D,constraint:F}}function B8(D,F){if(!D.type||D.type.length===0)return D;let u=D.type[0]?.extension?.[0];if(u?.url==="http://hl7.org/fhir/StructureDefinition/structuredefinition-fhir-type"&&u.valueUrl)return{...D,type:u.valueUrl};let C=D.type[0].code,E={...D,type:C};if(F.kind==="logical"){let B=s3(D.extension,"http://hl7.org/fhir/StructureDefinition/elementdefinition-defaulttype");if(B?.valueCanonical)E.defaultType=B.valueCanonical}return E}function $8(D){if(D.type?.[0]?.code!=="Extension")return D;let u=D.type[0]?.profile?.[0];if(!u)return D;return{...D,url:u,...D.min&&{min:D.min},...D.max&&D.max!=="*"&&{max:parseInt(D.max)}}}function Z8(D){if(D.url)return D;let F=D.max==="*"||D.min&&D.min>=2||D.max&&parseInt(D.max)>=2,u=D.min===1,C={...D};if(delete C.min,delete C.max,F){if(C.array=!0,D.min&&D.min>0)C.min=D.min;if(D.max&&D.max!=="*")C.max=parseInt(D.max)}if(u)C._required=!0;return C}function X8(D,F){let u=D.substring(1).split("."),C=[F.url];for(let E of u.slice(1))C.push("elements",E);return C}function Q8(D,F){if(!D.contentReference)return D;let{contentReference:u,...C}=D;return{...C,elementReference:X8(u,F)}}function z8(D){let{path:F,slicing:u,sliceName:C,id:E,mapping:B,example:$,alias:Z,condition:Q,comment:z,definition:O,requirements:A,extension:J,...W}=D;return W}function I2(D,F){let u=u8(D);return u=z8(u),u=C8(u,F),u=E8(u),u=Q8(u,F),u=$8(u),u=Z8(u),u=B8(u,F),u=D8(u),u}function L2(D){if(D.path.endsWith("[x]"))return!0;if(D.type&&D.type.length>1)return new Set(D.type.map((u)=>u.code)).size>1;return!1}function r3(D){if(!D)return D;return D.charAt(0).toUpperCase()+D.slice(1)}function a3(D){let F=D.split("/");return F[F.length-1]}function N2(D){let F=D.path.replace(/\[x\]$/,""),u=F.split(".").pop()||"";if(!D.type)return[];let C=[],E=D.type.map((z)=>u+r3(a3(z.code))),{type:B,binding:$,...Z}=D,Q={...Z,path:F,choices:E};C.push(Q);for(let z of D.type){let O=r3(a3(z.code)),A={...D,path:F+O,type:[z],choiceOf:u};if(D.binding)delete A.binding;C.push(A)}return C}function e3(D,F){let u=D[D.length-1],C=D.slice(0,-1),E=C[C.length-1],B=F(E,u);return[...C.slice(0,-1),B]}function Y8(D,F){if(!D.discriminator)return{};let u={};for(let C of D.discriminator){if(!C.type||!["pattern","value",void 0].includes(C.type))continue;let E=C.path.trim();if(E==="$this"){if(F.pattern?.value)Object.assign(u,F.pattern.value)}else{let B=E.split(".").filter((z)=>z),$=Object.keys(F).filter((z)=>z.startsWith("pattern"));for(let z of $){let O=z.replace("pattern","").toLowerCase();if(B.length===1&&B[0]===O)u[O]=F[z]}let Z=["elements"];for(let z of B)if(Z.push(z),B.indexOf(z)<B.length-1)Z.push("elements");Z.push("pattern");let Q=F;for(let z of Z)Q=Q?.[z];if(Q?.value!==void 0){let z=u;for(let O=0;O<B.length-1;O++){if(!z[B[O]])z[B[O]]={};z=z[B[O]]}z[B[B.length-1]]=Q.value}}}return u}function O8(D,F,u){let C={match:F,schema:D};if(u?.min!==void 0&&u.min!==0)C.min=u.min;if(u?.max!==void 0)C.max=u.max;return C}function J8(D,F,u){let C=F.slicing||D.slicing||{},E=Y8(C,u),B=O8(u,E,D.slice);if(!F.slicing)F.slicing={};if(D.slicing)F.slicing={...F.slicing,...D.slicing};if(!F.slicing.slices)F.slicing.slices={};return F.slicing.slices[D.sliceName]=B,F}function W8(D){if(!D.slicing?.slices)return{};let F={};for(let[u,C]of Object.entries(D.slicing.slices)){let{match:E,schema:B,...$}=C,{slicing:Z,elements:Q,type:z,min:O,...A}=B||{},J={};if(E?.url)J.url=E.url;if($.min!==void 0&&$.min!==0)J.min=$.min;if($.max!==void 0)J.max=$.max;if(Object.assign(J,A),O!==void 0&&O!==0&&J.min===void 0)J.min=O;F[u]=J}return F}function A8(D,F,u){let C={...F};if(D==="extension")C.extensions=W8(u);if(!C.elements)C.elements={};let E=u.choiceOf||D,{_required:B,...$}=u;if(C.elements[D]=$,B){if(!C.required)C.required=[];if(!C.required.includes(E))C.required.push(E)}return C}function zF(D,F,u){let C=[...D];for(let E=0;E<F.length;E++){let B=F[E],Z=F[E+1]?.type==="enter"?{}:u;switch(B.type){case"enter":C.push(Z);break;case"enter-slice":C.push(Z);break;case"exit":C=e3(C,(Q,z)=>A8(B.el,Q,z));break;case"exit-slice":C=e3(C,(Q,z)=>J8(B,Q,z));break}}return C}function D6(D,F){let u={};if(u.name=D.name,u.type=D.type,D.url)u.url=D.url;if(D.version)u.version=D.version;if(D.description)u.description=D.description;if(D.package_name)u.package_name=D.package_name;if(D.package_version)u.package_version=D.package_version;if(D.package_id)u.package_id=D.package_id;if(u.kind=D.kind,D.derivation)u.derivation=D.derivation;if(D.baseDefinition&&D.type!=="Element")u.base=D.baseDefinition;if(D.abstract)u.abstract=D.abstract;if(u.class=G8(D),F?.package_meta)u.package_meta=F.package_meta;return u}function G8(D){if(D.kind==="resource"&&D.derivation==="constraint")return"profile";if(D.type==="Extension")return"extension";return D.kind||"unknown"}function H8(D){return(D.differential?.element||[]).filter((u)=>u.path.includes("."))}function F6(D){let u=Object.entries(D).sort((E,B)=>{let $=E[1].index??1/0,Z=B[1].index??1/0;return $-Z}),C={};for(let[E,B]of u)if(B.elements)C[E]={...B,elements:F6(B.elements)};else C[E]=B;return C}function j0(D,F=new WeakSet){if(Array.isArray(D))return D.map((u)=>j0(u,F));if(D&&typeof D==="object"){if(F.has(D))return"[Circular Reference]";F.add(D);let u={},C=Object.keys(D);for(let E of C)if(E==="elements"&&D[E])u[E]=F6(j0(D[E],F));else if(E==="required"&&Array.isArray(D[E]))u[E]=[...D[E]].sort();else u[E]=j0(D[E],F);return u}return D}function I0(D,F){if(D.kind==="primitive-type")return j0(D6(D,F));let u=D6(D,F),C=H8(D),E=[u],B=[],$=[...C],Z=0;while($.length>0){let z=$.shift();if(L2(z)){let q=N2(z);$.unshift(...q),Z++;continue}let O=R2(z),A=j2(B,O),J=QF(B,A),_={...I2(z,D),index:Z++};E=zF(E,J,_),B=A}let Q=QF(B,[]);if(E=zF(E,Q,{index:Z}),E.length!==1)throw Error(`Invalid stack state: expected 1 element, got ${E.length}`);return j0(E[0])}var T2=(D,F)=>{if(!F)F={name:"undefined",version:"undefined"};return{...D,package_meta:D.package_meta||F,name:D.name,url:D.url,base:D.base}};function w2(D){return D.identifier.kind==="binding"}var b2=async(D,F,u)=>{let C=await D.search({}),E={};for(let W of C){let _=W.url;if(!_)continue;E[_]=W}let B={};for(let W of C)if(W.resourceType==="StructureDefinition"){let _=W.url;B[_]=W}let $={},Z={},[Q,z]=[0,0];for(let W of Object.values(B)){try{let _=T2(I0(W),u);$[_.url]=_,Z[_.name]=_.url,Q++}catch(_){F?.warn(`Failed to convert StructureDefinition ${W.name||W.id}: ${_ instanceof Error?_.message:String(_)}`),z++}F?.success(`FHIR Schema conversion completed: ${Q}/${Object.values(B).length} successful, ${z} failed`)}let O={};for(let W of C)if(W.resourceType==="ValueSet"){if(!W.package_meta)W.package_meta=u;O[W.url]=W}let A={};for(let W of Object.values($))if(W.kind==="complex-type")A[W.url]=W;return{...D,appendFs(W){let _=T2(W);$[_.url]=_,Z[_.name]=_.url},resolveFs:(W)=>$[W],resolveFsGenealogy:(W)=>{let _=$[W];if(_===void 0)throw Error(`Failed to resolve FHIR Schema genealogy for '${W}'`);let q=[_];while(_?.base)if(_=$[_.base]||$[Z[_.base]],q.push(_),_===void 0)throw Error(`Failed to resolve FHIR Schema genealogy for '${W}'`);return q},ensureCanonicalUrl:(W)=>Z[W]||W,allSd:()=>Object.values(B),resolveSd:(W)=>B[W],allFs:()=>Object.values($),allVs:()=>Object.values(O),resolveVs:(W)=>O[W],complexTypeDict:()=>A,resolveAny:(W)=>E[W]}};var x2=(D,F)=>{let[u,...C]=F;if(u===void 0)return[];return D.map((E)=>{if(!E.elements)return;let B=E.elements?.[u];for(let $ of C)B=B?.elements?.[$];return B}).filter((E)=>E!==void 0)};function P2(D){let F=D.reverse().reduce((u,C)=>({...u,...C}),{});return F.elements=void 0,F}function S2(D){let F=D.split("|")[0];return F?F:D}function q8(D){return D.split("|")[1]}function _8(D){if(D.derivation==="constraint")return"profile";if(D.kind==="primitive-type")return"primitive-type";if(D.kind==="complex-type")return"complex-type";if(D.kind==="resource")return"resource";return"resource"}function xD(D){return{kind:_8(D),package:D.package_meta.name,version:D.package_meta.version,name:D.name,url:D.url}}function L0(D,F){let u=F.join(".");return{kind:"nested",package:D.package_meta.name,version:D.package_meta.version,name:u,url:`${D.url}#${u}`}}var M8=(D)=>{let F=D.split("/"),u=F[F.length-1];if(u&&u.length>0)return u.split(/[-_]/).map((C)=>C.charAt(0).toUpperCase()+C.slice(1).toLowerCase()).join("");return D};function YF(D,F){let u=S2(F),C=M8(u),E={resourceType:"ValueSet",package_meta:{name:"missing_valuesets",version:q8(u)||"0.0.0"},name:C,id:F,url:u},B=D.resolveVs(u)||E,$=B?.id&&!/^[a-zA-Z0-9_-]{20,}$/.test(B.id)?B.id:C;return{kind:"value-set",package:B?.package_meta.name,version:B?.package_meta.version,name:$,url:u}}function OF(D,F,u){let C=F.join("."),[E,B,$]=u?[{name:"shared",version:"1.0.0"},u,`urn:fhir:binding:${u}`]:[D.package_meta,`${D.name}.${C}_binding`,`${D.url}#${C}_binding`];return{kind:"binding",package:E.name,version:E.version,name:B,url:$}}async function C6(D,F){let u=xD(F),C=F.package_meta;if(u.kind!=="profile")throw Error(`Expected profile, got ${u.kind} for ${F.name}`);let E;if(F.base){let O=F.base.includes("/")?F.base:`http://hl7.org/fhir/StructureDefinition/${F.base}`,A=F.base.split("/").pop()||F.base,J=await V8(O,D),W=O.startsWith("http://hl7.org/fhir/");E={kind:J,package:W?"hl7.fhir.r4.core":F.package_meta.name||"undefined",version:W?"4.0.1":F.package_meta.version||"undefined",name:A,url:O}}let B={identifier:u,base:E,dependencies:E?[E]:[]};if(F.description)B.description=F.description;let $=K8(F);if(Object.keys($).length>0)B.metadata=$;if(F.elements){let O=await JF(D,F,[],F.elements);if(O&&Object.keys(O).length>0)B.fields=O}let Z=await R8(F,D);if(Object.keys(Z).length>0)B.constraints=Z;let Q=await U8(F,D);if(Q.length>0)B.extensions=Q;let z=j8(F);if(z.length>0)B.validation=z;return B}async function V8(D,F){try{let u=F.resolveFs(D);if(!u)return"resource";if(u){if(u.derivation==="constraint")return"profile";if(u.kind==="resource")return"resource";if(u.kind==="complex-type")return"complex-type"}}catch(u){console.warn(`Could not resolve base schema ${D}:`,u)}if(D.includes("StructureDefinition/")&&!D.startsWith("http://hl7.org/fhir/StructureDefinition/"))return"profile";return"resource"}function K8(D){let F={},u=D.package_meta;if(D.publisher)F.publisher=D.publisher;if(D.contact)F.contact=D.contact;if(D.copyright)F.copyright=D.copyright;if(D.purpose)F.purpose=D.purpose;if(D.experimental!==void 0)F.experimental=D.experimental;if(D.date)F.date=D.date;if(D.jurisdiction)F.jurisdiction=D.jurisdiction;if(u?.name)F.package=u.name;else if(D.package_meta.name)F.package=D.package_meta.name;return F}async function R8(D,F){let u={};if(!D.elements)return u;for(let[C,E]of Object.entries(D.elements)){let B={};if(E.min!==void 0)B.min=E.min;if(E.max!==void 0)B.max=String(E.max);if(E.mustSupport)B.mustSupport=!0;if(E.fixedValue!==void 0)B.fixedValue=E.fixedValue;if(E.patternValue!==void 0)B.patternValue=E.patternValue;if(E.binding)B.binding={strength:E.binding.strength,valueSet:E.binding.valueSet??""};if(E.type&&Array.isArray(E.type)&&E.type.length>0)B.types=E.type.map(($)=>{let Z={code:$.code};if($.profile)Z.profile=$.profile;if($.targetProfile)Z.targetProfile=$.targetProfile;return Z});if(E.slicing)B.slicing={discriminator:E.slicing.discriminator??[],rules:String(E.slicing),ordered:E.slicing.ordered};if(Object.keys(B).length>0)u[C]=B}return u}async function U8(D,F){let u=[];if(!D.elements)return u;for(let[C,E]of Object.entries(D.elements))if(C.includes("extension")&&E.type&&Array.isArray(E.type)){for(let B of E.type)if(B.code==="Extension"&&B.profile)u.push({path:C,profile:B.profile,min:E.min,max:String(E.max),mustSupport:E.mustSupport})}return u}function j8(D){let F=[];if(!D.elements)return F;for(let[u,C]of Object.entries(D.elements))if(C.constraint&&Array.isArray(C.constraint))for(let E of C.constraint)F.push({path:u,key:E.key,severity:E.severity,human:E.human,expression:E.expression});return F}function E6(D,F,u){let C=u[u.length-1],E=u.slice(0,-1),B=D.resolveFsGenealogy(F.url).flatMap(($)=>{if(E.length===0)return $.required||[];if(!$.elements)return[];let Z=$;for(let Q of E)Z=Z?.elements?.[Q];return Z?.required||[]});return new Set(B).has(C)}function B6(D,F,u){let C=u[u.length-1];if(!C)throw Error(`Internal error: fieldName is missing for path ${u.join("/")}`);let E=u.slice(0,-1),B=D.resolveFsGenealogy(F.url).flatMap(($)=>{if(E.length===0)return $.excluded||[];if(!$.elements)return[];let Z=$;for(let Q of E)Z=Z?.elements?.[Q];return Z?.excluded||[]});return new Set(B).has(C)}var I8=(D,F,u)=>{if(!D.refers)return;return D.refers.map((C)=>{let E=F.ensureCanonicalUrl(C),B=F.resolveFs(E);return xD(B)})};function v2(D,F,u){if(u.elementReference){let C=u.elementReference.filter((E,B)=>B%2===1).map((E)=>E).filter((E)=>E!=="elements");if(C.length>0)return L0(F,C)}if(u.type){let C=u.type.match(/^[a-z]/)?"primitive-type":"complex-type",E=D.ensureCanonicalUrl(u.type),B=D.resolveFs(E);if(!B)throw Error(`Could not resolve field '${u.type}'`);return{kind:C,package:B.package_meta.name,version:B.package_meta.version,name:u.type,url:E}}return}var WF=(D,F,u,C)=>{let E,B;if(C.binding){if(E=OF(F,u,C.binding.bindingName),C.binding.strength==="required"&&C.type==="code")B=f2(D,C)}return{type:v2(D,F,C),required:E6(D,F,u),excluded:B6(D,F,u),reference:I8(C,D,F.package_meta),array:C.array||!1,min:C.min,max:C.max,choices:C.choices,choiceOf:C.choiceOf,binding:E,enum:B}};function N0(D){let F=D.type==="BackboneElement",u=D.type==="Element"&&D.elements!==void 0&&Object.keys(D.elements).length>0,C=D.type===void 0&&D.choiceOf===void 0&&D.elements!==void 0&&Object.keys(D.elements).length>0;return F||u||C}function AF(D,F,u,C){return{type:L0(F,u),array:C.array||!1,required:E6(D,F,u),excluded:B6(D,F,u)}}function k2(D,F){let u=S2(F)||F,C=D.resolveVs(u);if(!C)return;return L8(D,C)}function L8(D,F){if(F.expansion?.contains)return F.expansion.contains;let u=[];if(F.compose?.include){for(let C of F.compose.include)if(C.concept)for(let E of C.concept)u.push({system:C.system,code:E.code,display:E.display});else if(C.system&&!C.filter)try{let E=D.resolveAny(C.system);if(E?.concept){let B=($,Z)=>{for(let Q of $)if(u.push({system:Z,code:Q.code,display:Q.display}),Q.concept)B(Q.concept,Z)};B(E.concept,C.system)}}catch{}}return u.length>0?u:void 0}var $6=100;function f2(D,F){if(!F.binding)return;let u=F.binding.strength,C=F.binding.valueSet;if(!C)return;if(!(u==="required"||u==="extensible"&&(F.type==="code"||F.type==="Coding")||u==="preferred"&&(F.type==="code"||F.type==="Coding")))return;let B=k2(D,C);if(!B||B.length===0)return;let $=B.map((Z)=>Z.code).filter((Z)=>Z&&typeof Z==="string"&&Z.trim().length>0);if($.length>$6){console.warn(`Value set ${C} has more than ${$6} codes, which may cause issues with code generation.`);return}return $.length>0?$:void 0}async function N8(D,F,u,C){if(!C.binding?.valueSet)return;let E=OF(F,u,C.binding.bindingName),B=v2(D,F,C),$=YF(D,C.binding.valueSet),Z=[];if(B)Z.push(B);Z.push($);let Q=f2(D,C);return{identifier:E,type:B,valueset:$,strength:C.binding.strength,enum:Q,dependencies:Z}}async function y2(D,F){let u=new Set;if(!F.elements)return[];let C=[];async function E(Z,Q){for(let[z,O]of Object.entries(Z)){let A=[...Q,z],J=A.join(".");if(u.has(J))continue;if(u.add(J),O.binding){let W=await N8(D,F,A,O);if(W)C.push(W)}if(O.elements)await E(O.elements,A)}}await E(F.elements,[]),C.sort((Z,Q)=>Z.identifier.name.localeCompare(Q.identifier.name));let B=[],$=new Set;for(let Z of C)if(!$.has(Z.identifier.url))$.add(Z.identifier.url),B.push(Z);return B}function Z6(D,F,u){let C=[];for(let[E,B]of Object.entries(u)){let $=[...F,E];if(N0(B))C.push([$,B]);if(B.elements)C.push(...Z6(D,$,B.elements))}return C}async function T8(D,F,u,C,E){let B={};for(let[$,Z]of Object.entries(u)){let Q=[...F,$];if(N0(Z))B[$]=AF(C,D,Q,Z);else B[$]=WF(C,D,Q,Z)}return B}async function h2(D,F){if(!F.elements)return;let C=Z6(F,[],F.elements).filter(([B,$])=>$.elements&&Object.keys($.elements).length>0),E=[];for(let[B,$]of C){let Z=L0(F,B),Q;if($.type==="BackboneElement"||!$.type)Q={kind:"complex-type",package:F.package_meta.name,version:F.package_meta.version,name:"BackboneElement",url:"http://hl7.org/fhir/StructureDefinition/BackboneElement"};else Q={kind:"complex-type",package:F.package_meta.name,version:F.package_meta.version,name:$.type,url:`http://hl7.org/fhir/StructureDefinition/${$.type}`};let z=await T8(F,B,$.elements,D,F.package_meta),O={identifier:Z,base:Q,fields:z};E.push(O)}return E.sort((B,$)=>B.identifier.url.localeCompare($.identifier.url)),E.length===0?void 0:E}function d2(D){let F=[];for(let u of D){if(u.base)F.push(u.base);for(let C of Object.values(u.fields||{})){if("type"in C&&C.type)F.push(C.type);if("binding"in C&&C.binding)F.push(C.binding)}}return F}async function JF(D,F,u,C){if(!C)return;let E=D.resolveFsGenealogy(F.url),B={};for(let[Z,Q]of Object.entries(C)){let z=[...u,Z],O=x2(E,z),A=P2(O);B[Z]={elem:Q,elemSnapshot:A,path:z}}for(let[Z,{elem:Q,elemSnapshot:z,path:O}]of Object.entries(B))for(let A of Q?.choices||[])if(!B[A]){let J=[...u,A],W=x2(E,J),_=P2(W);B[A]={elem:void 0,elemSnapshot:_,path:J}}let $={};for(let[Z,{elem:Q,elemSnapshot:z,path:O}]of Object.entries(B))if(N0(z))$[Z]=AF(D,F,O,z);else $[Z]=WF(D,F,O,z);return $}function X6(D){let F=[];for(let u of Object.values(D)){if("type"in u&&u.type)F.push(u.type);if("binding"in u&&u.binding)F.push(u.binding)}return F}function w8(D){let F=new Set,u=[];for(let C of D){let E=C.url;if(!F.has(E))F.add(E),u.push(C)}return u.sort((C,E)=>C.name.localeCompare(E.name)),u}function b8(D,F){if(D.base==="Extension"||D.base==="http://hl7.org/fhir/StructureDefinition/Extension")return!0;if(D.url?.includes("/extension/")||D.url?.includes("-extension"))return!0;if(D.name?.toLowerCase().includes("extension"))return!0;if(D.type==="Extension")return!0;return!1}async function Q6(D,F){if(!F.url)throw Error("ValueSet URL is required");let u=YF(D,F.url),C=k2(D,F.url);return{identifier:u,description:F.description,concept:C,compose:!C?F.compose:void 0}}async function x8(D,F,u){try{let C=xD(D),E;if(D.base&&D.base!=="Extension"){let Z=D.base.includes("/")?D.base:`http://hl7.org/fhir/StructureDefinition/${D.base}`;E={kind:"complex-type",package:"hl7.fhir.r4.core",version:"4.0.1",name:D.base.split("/").pop()||D.base,url:Z}}else E={kind:"complex-type",package:"hl7.fhir.r4.core",version:"4.0.1",name:"Extension",url:"http://hl7.org/fhir/StructureDefinition/Extension"};let B={identifier:C,base:E,description:D.description,dependencies:[],metadata:{isExtension:!0}};if(E)B.dependencies.push(E);if(D.elements){let Z=await JF(F,D,[],D.elements);if(Z&&Object.keys(Z).length>0)B.fields=Z,B.dependencies.push(...X6(Z))}let $=await h2(F,D);if($&&$.length>0)B.nested=$,B.dependencies.push(...d2($));return B.dependencies=w8(B.dependencies),B.dependencies=B.dependencies.filter((Z)=>Z.url!==C.url),B}catch(C){return console.warn(`Failed to transform extension ${D.name}: ${C}`),null}}function P8(D,F,u,C){let E=[];if(F)E.push(F);if(u)E.push(...X6(u));if(C)E.push(...d2(C));let B={};for(let Q of E){if(Q.url===D.url)continue;B[Q.url]=Q}let $=new Set(C?.map((Q)=>Q.identifier.url)),Z=Object.values(B).filter((Q)=>!(Q.kind==="nested"&&$.has(Q.url))).sort((Q,z)=>Q.url.localeCompare(z.url));return Z.length>0?Z:void 0}async function S8(D,F){let u=xD(F),C;if(F.base&&F.type!=="Element"){let z=D.resolveFs(D.ensureCanonicalUrl(F.base));if(!z)throw Error(`Base resource not found '${F.base}' for '${F.url}'`);C=xD(z)}let E=await JF(D,F,[],F.elements),B=await h2(D,F),$=P8(u,C,E,B),Z={identifier:u,base:C,fields:E,nested:B,description:F.description,dependencies:$},Q=await y2(D,F);return[Z,...Q]}async function z6(D,F){let u=[],C=xD(F);if(C.kind==="profile"){let E=await C6(D,F);u.push(E);let B=await y2(D,F);return u.push(...B),u}if(b8(F,C)){let E=await x8(F,D,F.package_meta);if(E)u.push(E);return u}return await S8(D,F)}class gD{manager;options;cacheConfig;cache;logger;constructor(D={},F){this.options={verbose:!1,...D},this.manager=D.manager||pD({packages:[],workingDir:"tmp/fhir"}),this.cacheConfig=F,this.logger=D.logger||jD({verbose:this.options.verbose,prefix:"TypeSchema"})}async initializeCache(){if(this.cacheConfig&&!this.cache)this.cache=new $0(this.cacheConfig),await this.cache.initialize()}async registerFromPackageMetas(D){let F=D.map((u)=>`${u.name}${u.version}`);return this.logger.step(`Loading FHIR packages: ${F.join(", ")}`),await this.manager.init(),b2(this.manager)}generateFhirSchemas(D){this.logger.progress(`Converting ${D.length} StructureDefinitions to FHIRSchemas`);let F=this.applyStructureDefinitionTreeshaking(D),u=[],C=0,E=0;for(let B of F)try{let $=I0(B);u.push($),C++,this.logger.debug(`Converted StructureDefinition: ${B.name||B.id} (${B.resourceType})`)}catch($){E++,this.logger.warn(`Failed to convert StructureDefinition ${B.name||B.id}: ${$ instanceof Error?$.message:String($)}`)}return this.logger.success(`FHIR Schema conversion completed: ${C}/${F.length} successful, ${E} failed`),u}async generateValueSetSchemas(D,F){if(D.length>0)this.logger.debug(`${D.length} ValueSets available for enum extraction`);let u=[];if(D.length>0){this.logger.progress(`Converting ${D.length} ValueSets to TypeSchema`);let C=0,E=0;for(let B of D)try{let $=await Q6(await b2(this.manager),B);if($)u.push($),C++,this.logger.debug(`Converted ValueSet: ${B.name||B.id}`)}catch($){E++,this.logger.warn(`Failed to convert ValueSet ${B.name||B.id}: ${$ instanceof Error?$.message:String($)}`)}this.logger.success(`ValueSet conversion completed: ${C}/${D.length} successful, ${E} failed`)}return u}async generateFromPackage(D,F){if(await this.initializeCache(),this.cache&&!(this.cacheConfig?.forceRegenerate??!1)){let B=this.cache.getByPackage(D);if(B.length>0)return this.logger.info(`Using cached TypeSchemas for package: ${D} (${B.length} schemas)`),B}let u={name:D,version:F||"latest"},C=await this.registerFromPackageMetas([u]),E=[...(await Promise.all(C.allFs().map(async(B)=>await z6(C,B)))).flat(),...await this.generateValueSetSchemas(C.allVs(),u)];if(this.cache)for(let B of E)await this.cache.set(B);return E}applyStructureDefinitionTreeshaking(D){let F=this.options.treeshake;if(!F||F.length===0)return D;this.logger.info(`Applying treeshaking filter for ResourceTypes: ${F.join(", ")}`);let u=new Map,C=new Map,E=new Map;for(let z of D){let O=z.name||z.id;if(O)u.set(O,z),C.set(O,new Set),E.set(O,new Set)}for(let z of D){let O=z.name||z.id;if(!O)continue;let{realDeps:A,refTargets:J}=this.extractStructureDefinitionDependenciesWithReferences(z);C.set(O,new Set(A)),E.set(O,new Set(J))}let B=new Set;for(let z of F)if(u.has(z))B.add(z);else this.logger.warn(`ResourceType '${z}' not found in structure definitions`);let $=(z,O=new Set)=>{if(O.has(z)||!C.has(z))return;O.add(z);let A=C.get(z)||new Set;for(let J of Array.from(A))if(u.has(J))B.add(J),$(J,O)};for(let z of Array.from(B))$(z);let Z=D.filter((z)=>{let O=z.name||z.id;return O&&B.has(O)}),Q=new Set;for(let z of D){let O=z.name||z.id;if(O&&!B.has(O)){if(Array.from(E.values()).some((J)=>J.has(O)))Q.add(O)}}if(Q.size>0)this.logger.info(`Excluded reference-only targets: ${Array.from(Q).join(", ")}`);return this.logger.success(`Treeshaking completed: kept ${Z.length}/${D.length} structure definitions`),Z}extractStructureDefinitionDependenciesWithReferences(D){let F=new Set,u=new Set;if(D.baseDefinition){let C=this.extractResourceNameFromUrl(D.baseDefinition);if(C)F.add(C)}if(D.snapshot?.element||D.differential?.element){let C=D.snapshot?.element||D.differential?.element;for(let E of C)if(E.type)for(let B of E.type){if(B.code){if(F.add(B.code),B.code==="Reference"&&B.targetProfile)for(let $ of B.targetProfile){let Z=this.extractResourceNameFromUrl($);if(Z)u.add(Z)}}if(B.profile)for(let $ of B.profile){let Z=this.extractResourceNameFromUrl($);if(Z)F.add(Z)}}}return{realDeps:Array.from(F),refTargets:Array.from(u)}}extractResourceNameFromUrl(D){let F=D.match(/\/([^/]+)$/);return F?F[1]??null:null}}import{readFile as v8}from"node:fs/promises";class T0{options;constructor(D={}){this.options={format:"auto",validate:!0,strict:!1,...D}}async parseFromFile(D){let F=await v8(D,"utf-8"),u=this.options.format==="auto"?this.detectFormat(F,D):this.options.format;return this.parseFromString(F,u)}async parseFromString(D,F){let u=F||this.detectFormat(D),C;if(u==="ndjson")C=this.parseNDJSON(D);else C=this.parseJSON(D);if(this.options.validate)this.validateSchemas(C);return C}async parseFromFiles(D){let F=[];for(let u of D){let C=await this.parseFromFile(u);F.push(...C)}return F}parseSchema(D){if(!D.identifier)throw Error("TypeSchema must have an identifier");if(!this.isValidIdentifier(D.identifier))throw Error("TypeSchema identifier is invalid");return D}findByIdentifier(D,F){return D.filter((u)=>this.matchesIdentifier(u.identifier,F))}findByUrl(D,F){return D.find((u)=>u.identifier.url===F)}findByKind(D,F){return D.filter((u)=>u.identifier.kind===F)}findByPackage(D,F){return D.filter((u)=>u.identifier.package===F)}detectFormat(D,F){if(F){if(F.endsWith(".ndjson"))return"ndjson";if(F.endsWith(".json"))return"json"}let u=D.trim();if(u.includes(`
94
- `)){let C=u.split(`
95
- `).filter((E)=>E.trim());if(C.length>1)try{if(C[0])JSON.parse(C[0]);return"ndjson"}catch{}}return"json"}parseNDJSON(D){let F=[],u=D.split(`
96
- `).filter((C)=>C.trim());for(let C of u)try{let E=JSON.parse(C);F.push(this.parseSchema(E))}catch(E){if(this.options.strict)throw Error(`Failed to parse NDJSON line: ${E}`)}return F}parseJSON(D){try{let F=JSON.parse(D);if(Array.isArray(F))return F.map((u)=>this.parseSchema(u));else return[this.parseSchema(F)]}catch(F){throw Error(`Failed to parse JSON: ${F}`)}}validateSchemas(D){for(let F of D){if(!F.identifier)throw Error("Schema missing identifier");if(!this.isValidIdentifier(F.identifier))throw Error(`Invalid identifier in schema: ${JSON.stringify(F.identifier)}`)}}isValidIdentifier(D){return typeof D==="object"&&D!==null&&typeof D.kind==="string"&&typeof D.package==="string"&&typeof D.version==="string"&&typeof D.name==="string"&&typeof D.url==="string"}matchesIdentifier(D,F){return(!F.kind||D.kind===F.kind)&&(!F.package||D.package===F.package)&&(!F.version||D.version===F.version)&&(!F.name||D.name===F.name)&&(!F.url||D.url===F.url)}}w0();class c2{options;constructor(D){this.options=D}handleError(D,F){if(D instanceof ID)this.handleGeneratorError(D,F);else this.handleUnknownError(D,F)}handleBatchErrors(D){let F=D.filter((C)=>C instanceof ID),u=D.filter((C)=>!(C instanceof ID));if(F.length>0)this.reportBatchErrors(F);u.forEach((C)=>{this.handleUnknownError(C)})}handleGeneratorError(D,F){switch(this.options.outputFormat){case"json":this.reportErrorAsJson(D);break;case"structured":this.reportErrorStructured(D);break;default:this.reportErrorToConsole(D)}}handleUnknownError(D,F){if(this.options.logger.error("Unexpected error occurred:",D),this.options.verbose){if(console.error(`
97
- \uD83D\uDEA8 Unexpected Error Details:`),console.error(` Type: ${D.constructor.name}`),console.error(` Message: ${D.message}`),D.stack)console.error(` Stack: ${D.stack}`);if(F?.schema)console.error(` Schema: ${F.schema.identifier.name}`);if(F?.filename)console.error(` File: ${F.filename}`)}console.error(`
98
- \uD83D\uDCA1 General troubleshooting suggestions:`),console.error(" • Run with --verbose flag for more details"),console.error(" • Check your input files for corruption"),console.error(" • Update to the latest version of atomic-codegen"),console.error(" • Report this issue at: https://github.com/atomic-ehr/codegen/issues")}reportErrorToConsole(D){if("getFormattedMessage"in D)console.error(D.getFormattedMessage());else{console.error(`
99
- ❌ ${D.constructor.name}: ${D.message}`);let F=D.getSuggestions();if(F.length>0)console.error(`
100
- \uD83D\uDCA1 Suggestions:`),F.forEach((u)=>{console.error(` • ${u}`)})}if(this.options.verbose&&D.context)console.error(`
101
- \uD83D\uDD0D Debug Information:`),console.error(JSON.stringify(D.context,null,2))}reportErrorAsJson(D){let F={type:D.constructor.name,message:D.message,phase:D.phase,context:D.context,suggestions:D.getSuggestions(),timestamp:new Date().toISOString()};console.error(JSON.stringify(F,null,2))}reportErrorStructured(D){let F={error:{type:D.constructor.name,message:D.message,phase:D.phase},context:D.context,suggestions:D.getSuggestions(),actions:this.getRecoveryActions(D)};console.error("---"),console.error("Error Report:"),console.error(JSON.stringify(F,null,2)),console.error("---")}reportBatchErrors(D){console.error(`
102
- ❌ ${D.length} errors occurred during generation:`);let F=new Map;D.forEach((u)=>{let C=u.constructor.name;if(!F.has(C))F.set(C,[]);F.get(C)?.push(u)});for(let[u,C]of F){console.error(`
103
- \uD83D\uDCCB ${u} (${C.length} occurrences):`),C.forEach((B,$)=>{if(console.error(` ${$+1}. ${B.message}`),B.context?.schemaName)console.error(` Schema: ${B.context.schemaName}`)});let E=this.getCommonSuggestions(C);if(E.length>0)console.error(`
104
- \uD83D\uDCA1 Common suggestions:`),E.forEach((B)=>{console.error(` • ${B}`)})}}getCommonSuggestions(D){let F=D.flatMap((E)=>E.getSuggestions()),u=new Map;F.forEach((E)=>{u.set(E,(u.get(E)||0)+1)});let C=Math.ceil(D.length/2);return Array.from(u.entries()).filter(([E,B])=>B>=C).map(([E,B])=>E).slice(0,5)}getRecoveryActions(D){if("getRecoveryActions"in D)return D.getRecoveryActions();return[{action:"Review error message and suggestions above"},{action:"Check input files and configuration"},{action:"Try with --verbose flag for more information"}]}}class l2{errorHandler;constructor(D){this.errorHandler=D}async withErrorBoundary(D,F){try{return await D()}catch(u){throw this.errorHandler.handleError(u instanceof Error?u:Error(String(u)),F),u}}async withBatchErrorBoundary(D,F){let u=[],C=[];for(let E of D)try{let B=await E();u.push(B)}catch(B){C.push(B instanceof Error?B:Error(String(B)))}if(C.length>0)throw this.errorHandler.handleBatchErrors(C),new m2(`${C.length} operations failed`,C.filter((E)=>E instanceof ID));return u}}w0();w0();import{access as o2,mkdir as f8,rm as k8,stat as Y6,writeFile as y8}from"node:fs/promises";import{dirname as n2,join as X0,relative as h8}from"node:path";class i2{options;logger;constructor(D){this.options={overwrite:!0,batchSize:10,...D},this.logger=D.logger}async writeFile(D,F,u={}){let C=performance.now(),E=X0(this.options.outputDir,D),B=u.encoding||"utf-8",$=u.overwrite??this.options.overwrite;try{if(!$)try{await o2(E),this.logger.debug(`Skipping existing file: ${D}`);let z=await Y6(E);return{path:E,size:z.size,writeTime:0}}catch{}await this.ensureDirectory(n2(E)),await y8(E,F,B);let Z=performance.now()-C,Q=Buffer.byteLength(F,B);return this.logger.debug(`Written ${D} (${Q} bytes, ${Z.toFixed(2)}ms)`),{path:E,size:Q,writeTime:Z}}catch(Z){throw new Z0(`Failed to write file '${D}': ${Z}`,"write",E,Z instanceof Error?Z:void 0,{canRetry:!0,alternativePaths:[X0(process.cwd(),"backup-output",D)]})}}async writeBatch(D){this.logger.debug(`Writing batch of ${D.size} files`);let F=Array.from(D.entries()),u=[];for(let C=0;C<F.length;C+=this.options.batchSize){let B=F.slice(C,C+this.options.batchSize).map(([Z,Q])=>this.writeFile(Z,Q)),$=await Promise.all(B);if(u.push(...$),C+this.options.batchSize<F.length)await new Promise((Z)=>setTimeout(Z,10))}return u}async ensureDirectory(D){try{await f8(D,{recursive:!0})}catch(F){throw new Z0(`Failed to create directory '${D}': ${F}`,"create",D,F instanceof Error?F:void 0,{canRetry:!0,permissionFix:`chmod 755 "${n2(D)}"`})}}async cleanDirectory(D="."){let F=X0(this.options.outputDir,D);try{await o2(F),this.logger.debug(`Cleaning directory: ${D}`),await k8(F,{recursive:!0,force:!0})}catch(u){if(u?.code!=="ENOENT")throw new Z0(`Failed to clean directory '${D}': ${u}`,"delete",F,u instanceof Error?u:void 0,{canRetry:!0})}}getRelativeImportPath(D,F){let u=n2(X0(this.options.outputDir,D)),C=X0(this.options.outputDir,F),E=h8(u,C);if(!E.startsWith("."))E=`./${E}`;return E.replace(/\.(d\.ts|ts|tsx|js|jsx)$/,"")}async wouldOverwrite(D){let F=X0(this.options.outputDir,D);try{return await o2(F),!0}catch{return!1}}async getFileStats(D){let F=X0(this.options.outputDir,D);try{return{size:(await Y6(F)).size,generationTime:0,writeTime:0}}catch{return null}}getOutputDirectory(){return this.options.outputDir}setBatchSize(D){this.options.batchSize=Math.max(1,Math.min(50,D))}getBatchSize(){return this.options.batchSize}}class r2{options;logger;fileManager;templateEngine;typeMapper;errorHandler;errorBoundary;progressCallback;generatedFiles=[];generationStartTime=0;cache=new Map;constructor(D){let F=this.validateConfiguration(D);if(!F.isValid)throw new g2(`Invalid generator configuration: ${F.errors.join(", ")}`,"configuration",D);if(this.options=this.mergeWithDefaults(D),this.logger=D.logger||jD({prefix:this.getLanguageName(),verbose:this.options.verbose||!1}),this.fileManager=this.createFileManager(),this.templateEngine=this.createTemplateEngine(),this.typeMapper=this.createTypeMapper(),this.errorHandler=new c2({logger:this.logger,verbose:this.options.verbose||!1,beginnerMode:this.options.beginnerMode||!1,outputFormat:this.options.errorFormat||"console"}),this.errorBoundary=new l2(this.errorHandler),this.logger.debug(`${this.getLanguageName()} generator initialized`),F.warnings.length>0)F.warnings.forEach((u)=>{this.logger.warn(`Configuration warning: ${u}`)})}getCapabilities(){return{language:this.getLanguageName(),fileExtensions:[this.getFileExtension()],supportsTemplates:!0,supportsCustomTypeMapping:!0,supportsIncrementalGeneration:!1,supportsValidation:!0,supportedSchemaKinds:["resource","complex-type","profile","logical"],version:"1.0.0"}}createFileManager(){return new i2({outputDir:this.options.outputDir,logger:this.logger.child("FileManager"),overwrite:this.options.overwrite})}createTemplateEngine(){return}async generate(D){return this.errorBoundary.withErrorBoundary(async()=>{this.generationStartTime=performance.now(),this.generatedFiles=[],this.logger.info(`Starting ${this.getLanguageName()} generation for ${D.length} schemas`),this.reportProgress("validation",0,D.length,"Validating schemas..."),await this.validateSchemas(D),this.reportProgress("generation",0,D.length,"Processing schemas...");let F=this.filterAndSortSchemas(D);this.logger.debug(`Filtered to ${F.length} schemas for generation`),await this.generateFiles(F),await this.runPostGenerationHooks(),this.reportProgress("complete",D.length,D.length,"Generation complete");let u=performance.now()-this.generationStartTime;return this.logger.info(`Generated ${this.generatedFiles.length} files in ${u.toFixed(2)}ms (avg ${(u/this.generatedFiles.length).toFixed(2)}ms per file)`),this.generatedFiles},{operationName:"generate"})}async build(D){let F=this.fileManager.writeFile,u=new Map;this.fileManager.writeFile=async(C,E)=>{let B={path:`${this.options.outputDir}/${C}`,size:Buffer.byteLength(E,"utf-8"),writeTime:0};return u.set(C,B),B};try{let C=await this.generate(D);return C.forEach((E)=>{let B=u.get(E.filename);if(B)E.path=B.path,E.size=B.size}),C}finally{this.fileManager.writeFile=F}}file(D){if(!this.templateEngine)throw Error("Template engine is required for fluent file generation. Override createTemplateEngine() in your generator.");let{FileBuilder:F}=(W6(),KF(J6));return new F({filename:this.ensureFileExtension(D),fileManager:this.fileManager,templateEngine:this.templateEngine,typeMapper:this.typeMapper,logger:this.logger.child("FileBuilder")})}directory(D){let{DirectoryBuilder:F}=KF(A6);return new F({path:D,fileManager:this.fileManager,logger:this.logger.child("DirectoryBuilder")})}index(D="."){if(!this.templateEngine)throw Error("Template engine is required for index file generation. Override createTemplateEngine() in your generator.");let{IndexBuilder:F}=KF(H6);return new F({directory:D,fileManager:this.fileManager,templateEngine:this.templateEngine,logger:this.logger.child("IndexBuilder")})}onProgress(D){return this.progressCallback=D,this}validateConfiguration(D){let F=[],u=[],C=[];if(!D.outputDir)F.push("outputDir is required"),C.push("Provide a valid output directory path");if(D.outputDir&&typeof D.outputDir!=="string")F.push("outputDir must be a string");if(D.overwrite!==void 0&&typeof D.overwrite!=="boolean")F.push("overwrite must be a boolean");if(D.validate!==void 0&&typeof D.validate!=="boolean")F.push("validate must be a boolean");if(D.outputDir&&!jF("node:path").isAbsolute(D.outputDir))u.push("Using relative path for outputDir - consider using absolute path"),C.push("Use path.resolve() to convert to absolute path");if(D.validate===!1)u.push("Validation is disabled - this may lead to invalid generated code"),C.push("Consider enabling validation for better code quality");return{isValid:F.length===0,errors:F,warnings:u,suggestions:C}}mergeWithDefaults(D){return{overwrite:!0,validate:!0,verbose:!1,beginnerMode:!1,errorFormat:"console",...D}}async validateSchemas(D){if(!this.options.validate){this.logger.debug("Schema validation disabled");return}this.logger.info(`\uD83D\uDD0D Starting schema validation for ${D.length} schemas`),this.logger.debug("Schema validation enabled - performing comprehensive validation");let F=D.map((u)=>()=>this.errorBoundary.withErrorBoundary(async()=>{await this.validateSchema(u),this.reportProgress("validation",D.indexOf(u)+1,D.length,`Validated ${u.identifier?.name||"schema"}`)},{schema:u,operationName:"validateSchema"}));await this.errorBoundary.withBatchErrorBoundary(F,{operationName:"validateSchemas"}),this.logger.debug(`Successfully validated ${D.length} schemas`)}async validateSchema(D){let F=[],u=D.identifier?.name||"unknown";if(this.logger.debug(`\uD83D\uDD0D Validating schema: ${u} (kind: ${D.identifier?.kind})`),!D.identifier)F.push("Schema missing identifier"),this.logger.warn(`❌ Schema missing identifier: ${JSON.stringify(D,null,2).substring(0,200)}...`);else{if(!D.identifier.name)F.push("Schema identifier missing name");if(!D.identifier.kind)F.push("Schema identifier missing kind");else{let C=["resource","complex-type","profile","primitive-type","logical","value-set","binding","extension"];if(!C.includes(D.identifier.kind))F.push(`Schema identifier.kind must be one of: ${C.join(", ")}`)}}if("fields"in D&&D.fields)for(let[C,E]of Object.entries(D.fields)){if(!C.trim())F.push("Field name cannot be empty");if(!E)F.push(`Field '${C}' is null or undefined`)}if(await this.detectCircularReferences(D))this.logger.warn(`⚠️ Circular reference detected in schema '${u}' - this may be expected for FHIR primitive types`);if(F.length>0)throw this.logger.error(`❌ Schema validation failed for '${u}': ${F.join(", ")}`),this.logger.debug(`Schema details: ${JSON.stringify(D,null,2)}`),new p2(`Schema validation failed for '${D.identifier?.name||"unknown"}'`,D,F);this.logger.debug(`✅ Schema validation passed for '${u}'`)}async detectCircularReferences(D){let F=new Set,u=new Set;return((E)=>{let B=E.identifier?.name;if(!B)return!1;if(u.has(B))return!0;if(F.has(B))return!1;if(u.add(B),"fields"in E&&E.fields){for(let $ of Object.values(E.fields))if($?.type?.name===B)return!0}return u.delete(B),F.add(B),!1})(D)}async generateFiles(D){let F=D.map((u,C)=>()=>this.errorBoundary.withErrorBoundary(async()=>{let E=await this.generateFileForSchema(u,C,D.length);return this.generatedFiles.push(E),E},{schema:u,operationName:"generateFile"}));await this.errorBoundary.withBatchErrorBoundary(F,{operationName:"generateFiles"}),this.logger.debug(`Generated ${this.generatedFiles.length} files`)}async generateFileForSchema(D,F,u){let C=performance.now(),E={schema:D,typeMapper:this.typeMapper,filename:this.typeMapper.formatFileName(D.identifier?.name||"unknown"),language:this.getLanguageName(),timestamp:new Date().toISOString(),imports:new Map,exports:new Set},B=await this.generateSchemaContent(D,E);if(this.options.validate)await this.validateContent(B,E);let $=E.filename+this.getFileExtension(),Z=await this.fileManager.writeFile($,B),Q=performance.now()-C;return this.reportProgress("writing",F+1,u,`Generated ${$} (${Z.size} bytes)`),{path:Z.path,filename:$,content:B,exports:this.extractExports(B),size:Z.size,timestamp:new Date,metadata:{generationTime:Q,schemaCount:1,templateName:E.templateName?.toString(),warnings:[]}}}ensureFileExtension(D){let F=this.getFileExtension();return D.endsWith(F)?D:`${D}${F}`}extractExports(D){let F=[],u=/export\s*\{\s*([^}]+)\s*\}/g,C;while((C=u.exec(D))!==null)if(C[1]){let B=C[1].split(",").map(($)=>$.trim()).filter(Boolean);F.push(...B)}let E=/export\s+(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/g;while((C=E.exec(D))!==null)if(C[1])F.push(C[1]);return[...new Set(F)]}reportProgress(D,F,u,C,E){if(this.progressCallback)this.progressCallback(D,F,u,C,E);if(C&&this.options.verbose)this.logger.debug(`[${D}] ${C} (${F}/${u})`)}async runPostGenerationHooks(){}getCachedOrCompute(D,F){if(this.cache.has(D))return this.cache.get(D);let u=F();if(u instanceof Promise)return u.then((C)=>{return this.cache.set(D,C),C});else return this.cache.set(D,u),u}clearCache(){this.cache.clear()}getGenerationStats(){let D=this.generatedFiles.reduce((u,C)=>u+C.size,0),F=performance.now()-this.generationStartTime;return{filesGenerated:this.generatedFiles.length,totalSize:D,averageFileSize:this.generatedFiles.length>0?D/this.generatedFiles.length:0,generationTime:F,averageTimePerFile:this.generatedFiles.length>0?F/this.generatedFiles.length:0,cacheHitRate:0}}}class a2{options;constructor(D={}){this.options={generateNullable:!0,strictTypes:!0,customMappings:{},preferArraySyntax:!0,namingConvention:"PascalCase",...D}}mapType(D){if(typeof D==="string")return this.mapPrimitive(D);if(D&&typeof D==="object")switch(D.kind||D.type){case"primitive-type":return this.mapPrimitive(D.name);case"reference":return this.mapReference(D.targets||[]);case"array":{let u=this.mapType(D.element);return this.mapArray(u)}case"enum":case"coded":return this.mapEnum(D.values||[],D.name);case"complex-type":case"resource":return this.mapComplexType(D);default:return this.mapUnknownType(D)}return this.mapUnknownType(D)}mapComplexType(D){return{name:this.formatTypeName(D.name||"Unknown"),isPrimitive:!1,importPath:this.calculateImportPath(D),nullable:!D.required&&this.options.generateNullable,metadata:{kind:D.kind,package:D.package}}}mapUnknownType(D){return{name:"unknown",isPrimitive:!0,nullable:!0,metadata:{originalType:D,warning:"unmapped_type"}}}calculateImportPath(D){if(!D.name)return;return`./${this.formatFileName(D.name)}`}applyNamingConvention(D){switch(this.options.namingConvention){case"camelCase":return q6(D);case"PascalCase":return d8(D);case"snake_case":return _6(D);case"kebab-case":return p8(D);default:return D}}getCustomMapping(D){return this.options.customMappings[D]}shouldBeNullable(D){return!D&&this.options.generateNullable}}function q6(D){return D.replace(/[-_\s]+(.)?/g,(F,u)=>u?.toUpperCase()||"")}function d8(D){let F=q6(D);return F.charAt(0).toUpperCase()+F.slice(1)}function _6(D){return D.replace(/([A-Z])/g,"_$1").replace(/[-\s]+/g,"_").toLowerCase().replace(/^_/,"")}function p8(D){return _6(D).replace(/_/g,"-")}class e2 extends a2{tsOptions;constructor(D={}){super(D);this.tsOptions={...this.options,preferUnknown:!0,useBrandedTypes:!1,preferUndefined:!0,moduleFormat:"esm",...D}}getLanguageName(){return"TypeScript"}mapPrimitive(D){let F=this.getCustomMapping(D);if(F)return{name:F,isPrimitive:!0,nullable:!1};let C={string:"string",integer:"number",decimal:"number",boolean:"boolean",dateTime:"string",date:"string",time:"string",instant:"string",uri:"string",url:"string",canonical:"string",oid:"string",uuid:"string",base64Binary:"string",code:"string",id:"string",markdown:"string",unsignedInt:"number",positiveInt:"number",xhtml:"string",json:"unknown"}[D];if(!C)return console.warn(`Unknown FHIR primitive type: ${D}`),{name:this.tsOptions.preferUnknown?"unknown":"any",isPrimitive:!0,nullable:!1,metadata:{warning:"unmapped_primitive",originalType:D}};if(this.tsOptions.useBrandedTypes&&D!==C)return{name:`${C} & { readonly __brand: '${D}' }`,isPrimitive:!1,importPath:"./brands",nullable:!1,metadata:{isBranded:!0,originalFhirType:D}};return{name:C,isPrimitive:!0,nullable:!1}}mapReference(D){if(!D||D.length===0)return{name:"Reference",isPrimitive:!1,importPath:"./Reference",generics:["unknown"],nullable:!1};if(D.length===1){let u=D[0]?.name||"unknown";return{name:"Reference",isPrimitive:!1,importPath:"./Reference",generics:[u==="unknown"?"unknown":`'${u}'`],nullable:!1,metadata:{referencedType:u,referencedSchema:D[0]}}}return{name:"Reference",isPrimitive:!1,importPath:"./Reference",generics:[D.map((u)=>{let C=u.name||"unknown";return C==="unknown"?"unknown":`'${C}'`}).join(" | ")],nullable:!1,metadata:{referencedTypes:D.map((u)=>u.name||"unknown"),referencedSchemas:D}}}mapArray(D){if(this.options.preferArraySyntax)return{name:`${D.name}[]`,isPrimitive:D.isPrimitive,importPath:D.importPath,isArray:!0,nullable:!1,metadata:{elementType:D,arrayStyle:"suffix"}};else return{name:"Array",isPrimitive:!1,generics:[D.name],isArray:!0,nullable:!1,metadata:{elementType:D,arrayStyle:"generic"}}}mapOptional(D,F){if(F||!this.shouldBeNullable(F))return D;let u=this.tsOptions.preferUndefined?"undefined":"null";return{...D,name:`${D.name} | ${u}`,nullable:!0,metadata:{...D.metadata,nullabilityType:u,wasOptional:!0}}}mapEnum(D,F){let u=F?this.formatTypeName(F):"CodedValue";return{name:D.map((E)=>`'${E}'`).join(" | "),isPrimitive:!1,nullable:!1,metadata:{enumName:u,values:D,isUnionType:!0}}}formatTypeName(D){return this.applyNamingConvention(D)}formatFieldName(D){return g8(D)}formatFileName(D){return this.applyNamingConvention(D)}generateInterfaceField(D,F,u){return`${this.formatFieldName(D)}${u?"":"?"}: ${F.name};`}generateImportStatement(D){if(!D.importPath||D.isPrimitive)return;if(this.tsOptions.moduleFormat==="esm")return`import type { ${D.name} } from '${D.importPath}';`;else return`const { ${D.name} } = require('${D.importPath}');`}getRequiredImports(D){let F=new Set;for(let u of D){let C=this.generateImportStatement(u);if(C)F.add(C)}return Array.from(F).sort()}}function g8(D){return D.replace(/[-_\s]+(.)?/g,(F,u)=>u?.toUpperCase()||"")}class HF extends r2{resourceTypes=new Set;collectedValueSets=new Map;get tsOptions(){return this.options}getLanguageName(){return"TypeScript"}getFileExtension(){return".ts"}createTypeMapper(){let D=this.options;return new e2({namingConvention:(D.namingConvention??"PascalCase")==="PascalCase"?"PascalCase":"camelCase",moduleFormat:D.moduleFormat==="cjs"?"commonjs":"esm",preferUndefined:!0,...D.typeMapperOptions})}async generateSchemaContent(D,F){if(this.shouldSkipSchema(D))return"";if(D.identifier.kind==="resource")this.resourceTypes.add(this.typeMapper.formatTypeName(D.identifier.name));if(D.identifier.name==="Reference")return this.generateReferenceInterface(D);let u=this.generateTypeScriptInterface(D),C="";if("nested"in D&&D.nested&&Array.isArray(D.nested))C=D.nested.map((B)=>this.generateNestedTypeInterface(D.identifier.name,B)).join(`
105
-
106
- `);if(C)return`${u}
107
-
108
- ${C}`;return u}filterAndSortSchemas(D){return this.collectedValueSets=this.collectValueSets(D),D.filter((F)=>!this.shouldSkipSchema(F))}async validateContent(D,F){let u=/export\s+(interface|class|type|enum)\s+\w+/.test(D),C=D.includes("{")&&D.includes("}");if(!u)throw Error(`Generated content for ${F.schema.identifier.name} does not contain valid export statements`);if(!C)throw Error(`Generated content for ${F.schema.identifier.name} has invalid syntax (missing braces)`)}async transformSchemas(D){let F=[];for(let u of D){let C=await this.transformSchema(u);if(C)F.push(C)}return F}async transformSchema(D){if(this.shouldSkipSchema(D))return;let F={schema:D,typeMapper:this.typeMapper,filename:this.getFilenameForSchema(D),language:"TypeScript",timestamp:new Date().toISOString()},u=await this.generateSchemaContent(D,F);if(!u.trim())return;let C=this.extractImportsFromContent(u,D),E=this.extractExportsFromContent(u,D),B=this.getFilenameForSchema(D);return{content:u,imports:C,exports:Array.from(E),filename:B}}shouldGenerateValueSet(D){if(!w2(D)||!D.enum||!Array.isArray(D.enum)||D.enum.length===0)return!1;switch(this.options.valueSetMode||"required-only"){case"all":return!0;case"required-only":return D.strength==="required";case"custom":return(this.options.valueSetStrengths||["required"]).includes(D.strength);default:return D.strength==="required"}}collectValueSets(D){let F=new Map;for(let u of D)if(this.shouldGenerateValueSet(u)&&w2(u)){let C=this.typeMapper.formatTypeName(u.identifier.name);F.set(C,u)}return F}shouldUseValueSetType(D){if(!D)return!1;if(!this.tsOptions.generateValueSets)return!1;let F=this.typeMapper.formatTypeName(D.name);return this.collectedValueSets.has(F)}getValueSetTypeName(D){return this.typeMapper.formatTypeName(D.name)}shouldUseInlineEnum(D){if(!D)return!1;if(this.tsOptions.generateValueSets)return!1;return D.enum&&Array.isArray(D.enum)&&D.enum.length>0}generateInlineEnumType(D){if(!D.enum||!Array.isArray(D.enum))return"string";return D.enum.map((u)=>`'${u}'`).join(" | ")}shouldSkipSchema(D){if(D.identifier.kind==="value-set"||D.identifier.kind==="binding"||D.identifier.kind==="primitive-type")return!0;if(!this.tsOptions.includeExtensions){let F=D.identifier.url;if(F?.includes("StructureDefinition/")){let u=F.split("StructureDefinition/")[1];if(u){let C=u.includes("-"),E=D.identifier.kind==="profile";if(C&&E)return!0}}}return!1}getFilenameForSchema(D){return`${this.typeMapper.formatFileName(D.identifier.name)}${this.getFileExtension()}`}extractImportsFromContent(D,F){let u=new Map,C=/import\s+(?:type\s+)?{\s*([^}]+)\s*}\s+from\s+['"]([^'"]+)['"];?/g,E;while((E=C.exec(D))!==null){let B=E[1],$=E[2];if(!B||!$)continue;let Z=B.split(",").map((Q)=>Q.trim());for(let Q of Z)u.set(Q,$)}return u}extractExportsFromContent(D,F){let u=new Set,C=/export\s+(?:interface|class|enum|type)\s+([A-Za-z_$][A-Za-z0-9_$]*)/g,E;while((E=C.exec(D))!==null)if(E[1])u.add(E[1]);return u.add(this.typeMapper.formatTypeName(F.identifier.name)),u}generateReferenceInterface(D){let F=[],u=new Set;if("fields"in D&&D.fields)for(let[,C]of Object.entries(D.fields))this.collectFieldImports(C).forEach((B)=>u.add(B));if(F.push("import type { ResourceType } from './utilities.js';"),u.size>0){let C=Array.from(u).sort();for(let E of C)F.push(`import type { ${E} } from './${E}.js';`)}if(F.push(""),this.tsOptions.includeDocuments&&D.description){if(F.push("/**"),F.push(` * ${D.description}`),D.identifier.url)F.push(` * @see ${D.identifier.url}`);if(D.identifier.package)F.push(` * @package ${D.identifier.package}`);F.push(" * @template T - The resource type being referenced"),F.push(" */")}if(F.push("export interface Reference<T extends ResourceType = ResourceType> {"),"fields"in D&&D.fields)for(let[C,E]of Object.entries(D.fields))if(C==="type")F.push(" type?: T;");else{let B=this.generateFieldLines(C,E);for(let $ of B)if($)F.push(` ${$}`)}return F.push("}"),F.join(`
109
- `)}generateTypeScriptInterface(D){let F=[],u=this.typeMapper.formatTypeName(D.identifier.name),C=new Set,E=new Set;if("fields"in D&&D.fields)for(let[,B]of Object.entries(D.fields)){let $=this.collectFieldImports(B);for(let Z of $)if(this.collectedValueSets.has(Z))E.add(Z);else C.add(Z)}if("nested"in D&&D.nested&&Array.isArray(D.nested)){for(let B of D.nested)if(B.fields)for(let[,$]of Object.entries(B.fields)){let Z=this.collectFieldImports($);for(let Q of Z)if(this.collectedValueSets.has(Q))E.add(Q);else C.add(Q)}}if(C.size>0){let B=Array.from(C).sort();for(let $ of B)F.push(`import type { ${$} } from './${$}.js';`)}if(E.size>0){let $=Array.from(E).sort().join(", ");F.push(`import type { ${$} } from './valuesets/index.js';`)}if(C.size>0||E.size>0)F.push("");if(this.tsOptions.includeDocuments&&D.description){if(F.push("/**"),F.push(` * ${D.description}`),D.identifier.url)F.push(` * @see ${D.identifier.url}`);if(D.identifier.package)F.push(` * @package ${D.identifier.package}`);F.push(" */")}if(F.push(`export interface ${u} {`),D.identifier.kind==="resource")F.push(` resourceType: '${u}';`);if("fields"in D&&D.fields)for(let[B,$]of Object.entries(D.fields)){let Z=this.generateFieldLines(B,$);for(let Q of Z)if(Q)F.push(` ${Q}`)}return F.push("}"),F.join(`
110
- `)}collectFieldImports(D){let F=[];if("choices"in D&&D.choices&&Array.isArray(D.choices))return F;if(D.binding&&this.shouldUseValueSetType(D.binding)){let u=this.getValueSetTypeName(D.binding);return F.push(u),F}if("type"in D&&D.type){if(D.type.kind==="nested")return F;let u=this.typeMapper.mapType(D.type);if(!u.isPrimitive&&u.name!=="any"){if(!["string","number","boolean","Date","object","unknown","any"].includes(u.name))F.push(u.name)}}return[...new Set(F)]}extractReferenceTypes(D){let F=[];if(!Array.isArray(D))return F;for(let u of D){if(!u||typeof u!=="object")continue;if(u.kind==="resource"&&u.name){let C=this.typeMapper.formatTypeName(u.name);F.push(C)}}return[...new Set(F)]}generateNestedTypeInterface(D,F){let u=[],C=this.typeMapper.formatTypeName(`${D}${this.capitalizeFirst(F.identifier.name)}`);if(this.tsOptions.includeDocuments&&F.description){if(u.push("/**"),u.push(` * ${F.description}`),F.identifier.url)u.push(` * @see ${F.identifier.url}`);u.push(" */")}if(u.push(`export interface ${C} {`),F.fields)for(let[E,B]of Object.entries(F.fields)){let $=this.generateFieldLines(E,B);for(let Z of $)if(Z)u.push(` ${Z}`)}return u.push("}"),u.join(`
111
- `)}capitalizeFirst(D){return D.charAt(0).toUpperCase()+D.slice(1)}generateFieldLines(D,F){if("choices"in F&&F.choices&&Array.isArray(F.choices))return[];let u=this.generateFieldLine(D,F);return u?[u]:[]}generateFieldLine(D,F){let u="any",C=!1,E=!1;if("type"in F&&F.type){if(F.binding&&this.shouldUseValueSetType(F.binding))u=this.getValueSetTypeName(F.binding);else if(F.binding&&this.shouldUseInlineEnum(F))u=this.generateInlineEnumType(F);else if(u=this.typeMapper.mapType(F.type).name,F.type.kind==="nested"){let Q=F.type.url?.split("#")||[];if(Q.length===2){let z=Q[0].split("/").pop()||"",O=F.type.name;u=this.typeMapper.formatTypeName(`${z}${this.capitalizeFirst(O)}`)}else u=this.typeMapper.formatTypeName(F.type.name)}else if(u==="Reference"&&F.reference&&Array.isArray(F.reference)){let Q=this.extractReferenceTypes(F.reference);if(Q.length>0)Q.forEach((O)=>this.resourceTypes.add(O)),u=`Reference<${Q.map((O)=>`'${O}'`).join(" | ")}>`}}if("required"in F)C=F.required;if("array"in F)E=F.array;return`${D}${C?"":"?"}: ${u}${E?"[]":""};`}extractExports(D){let F=[],u=/export\s*\{\s*([^}]+)\s*\}/g,C;while((C=u.exec(D))!==null)if(C[1]){let B=C[1].split(",").map(($)=>$.trim()).filter(Boolean);F.push(...B)}let E=[/export\s+interface\s+(\w+)/g,/export\s+type\s+(\w+)/g,/export\s+class\s+(\w+)/g,/export\s+enum\s+(\w+)/g,/export\s+const\s+(\w+)/g,/export\s+function\s+(\w+)/g];for(let B of E){let $;while(($=B.exec(D))!==null)if($[1])F.push($[1])}return[...new Set(F)]}setOutputDir(D){this.options.outputDir=D}setOptions(D){this.options={...this.options,...D}}getOptions(){return{...this.options}}async generate(D){return await this.fileManager.cleanDirectory(),this.logger.debug("Cleaned output directory before generation"),super.generate(D)}async runPostGenerationHooks(){await super.runPostGenerationHooks(),await this.generateValueSetFiles(),await this.generateUtilitiesFile(),await this.generateMainIndexFile()}async generateUtilitiesFile(){if(this.resourceTypes.size===0){this.logger.warn("No resource types found, skipping utilities.ts generation");return}let D=[];D.push("/**"),D.push(" * FHIR Resource Type Utilities"),D.push(" * This file contains utility types for FHIR resources."),D.push(" * "),D.push(" * @generated This file is auto-generated. Do not edit manually."),D.push(" */"),D.push("");let F=Array.from(this.resourceTypes).sort();D.push("/**"),D.push(" * Union of all FHIR resource types in this package"),D.push(" */"),D.push("export type ResourceType =");for(let C=0;C<F.length;C++){let B=C===F.length-1?";":"";D.push(` | '${F[C]}'${B}`)}D.push(""),D.push("/**"),D.push(" * Helper type for creating typed References"),D.push(" * @example Reference<'Patient' | 'Practitioner'> - Reference that can point to Patient or Practitioner"),D.push(" */"),D.push("export type TypedReference<T extends ResourceType> = {"),D.push(" reference?: string;"),D.push(" type?: T;"),D.push(" identifier?: any; // Simplified for utility"),D.push(" display?: string;"),D.push("};");let u=D.join(`
112
- `);await this.fileManager.writeFile("utilities.ts",u),this.logger.info(`Generated utilities.ts with ${this.resourceTypes.size} resource types`)}generateValueSetFile(D){let F=this.typeMapper.formatTypeName(D.identifier.name),u=D.enum?.map((E)=>` '${E}'`).join(`,
113
- `)||"",C=[];if(this.options.includeDocuments){if(C.push("/**"),C.push(` * ${D.identifier.name} value set`),D.description)C.push(` * ${D.description}`);if(D.valueset?.url)C.push(` * @see ${D.valueset.url}`);if(D.identifier.package)C.push(` * @package ${D.identifier.package}`);C.push(" * @generated This file is auto-generated. Do not edit manually."),C.push(" */"),C.push("")}if(C.push(`export const ${F}Values = [`),u)C.push(u);if(C.push("] as const;"),C.push(""),C.push(`export type ${F} = typeof ${F}Values[number];`),this.tsOptions.includeValueSetHelpers)C.push(""),C.push(`export const isValid${F} = (value: string): value is ${F} =>`),C.push(` ${F}Values.includes(value as ${F});`);return C.join(`
114
- `)}async generateValueSetFiles(){if(!this.tsOptions.generateValueSets||this.collectedValueSets.size===0)return;for(let[D,F]of this.collectedValueSets){let u=this.generateValueSetFile(F),C=`valuesets/${D}.ts`;await this.fileManager.writeFile(C,u),this.logger.info(`Generated value set: ${C}`)}await this.generateValueSetIndexFile()}async generateValueSetIndexFile(){let D=[];if(this.tsOptions.includeDocuments)D.push("/**"),D.push(" * FHIR Value Sets"),D.push(" * This file re-exports all generated value sets."),D.push(" * "),D.push(" * @generated This file is auto-generated. Do not edit manually."),D.push(" */"),D.push("");let F=Array.from(this.collectedValueSets.keys()).sort();for(let C of F)D.push(`export * from './${C}.js';`);let u=D.join(`
115
- `);await this.fileManager.writeFile("valuesets/index.ts",u),this.logger.info(`Generated valuesets/index.ts with ${this.collectedValueSets.size} value sets`)}async generateMainIndexFile(){if(!this.options.generateIndex)return;let D=[];if(this.tsOptions.includeDocuments)D.push("/**"),D.push(" * FHIR R4 TypeScript Types"),D.push(" * Generated from FHIR StructureDefinitions"),D.push(" * "),D.push(" * @generated This file is auto-generated. Do not edit manually."),D.push(" */"),D.push("");if(D.push('export * from "./utilities";'),this.tsOptions.generateValueSets&&this.collectedValueSets.size>0)D.push(""),D.push("// Value Sets"),D.push('export * from "./valuesets/index";');let F=D.join(`
116
- `);await this.fileManager.writeFile("index.ts",F),this.logger.info(`Generated index.ts with type exports${this.tsOptions.generateValueSets&&this.collectedValueSets.size>0?" and value sets":""}`)}}class qF{schemas=[];options;generators=new Map;progressCallback;cache;pendingOperations=[];typeSchemaGenerator;logger;typeSchemaConfig;constructor(D={}){if(this.options={outputDir:D.outputDir||"./generated",verbose:D.verbose??!1,overwrite:D.overwrite??!0,validate:D.validate??!0,cache:D.cache??!0,typeSchemaConfig:D.typeSchemaConfig,manager:D.manager||null},this.typeSchemaConfig=D.typeSchemaConfig,this.logger=D.logger||jD({verbose:this.options.verbose,prefix:"API"}),this.options.cache)this.cache=new $0(this.typeSchemaConfig)}fromPackage(D,F){this.logger.debug(`Loading from FHIR package: ${D}@${F||"latest"}`);let u=this.loadFromPackage(D,F);return this.pendingOperations.push(u),this}fromFiles(...D){this.logger.debug(`Loading from ${D.length} TypeSchema files`);let F=this.loadFromFiles(D);return this.pendingOperations.push(F),this}fromSchemas(D){return this.logger.debug(`Adding ${D.length} TypeSchemas to generation`),this.schemas=[...this.schemas,...D],this}typescript(D={}){let F=`${this.options.outputDir}/types`,u=new HF({outputDir:F,moduleFormat:D.moduleFormat||"esm",generateIndex:D.generateIndex??!0,includeDocuments:D.includeDocuments??!0,namingConvention:D.namingConvention||"PascalCase",includeExtensions:D.includeExtensions??!1,includeProfiles:D.includeProfiles??!1,generateValueSets:D.generateValueSets??!1,includeValueSetHelpers:D.includeValueSetHelpers??!1,valueSetStrengths:D.valueSetStrengths??["required"],logger:this.logger.child("TS"),valueSetMode:D.valueSetMode??"required-only",valueSetDirectory:D.valueSetDirectory??"valuesets",verbose:this.options.verbose,validate:!0,overwrite:this.options.overwrite});return this.generators.set("typescript",u),this.logger.debug(`Configured TypeScript generator (${D.moduleFormat||"esm"})`),this}onProgress(D){return this.progressCallback=D,this}outputTo(D){this.logger.debug(`Setting output directory: ${D}`),this.options.outputDir=D;for(let F of this.generators.values())if(F.setOutputDir)F.setOutputDir(D);return this}verbose(D=!0){return this.options.verbose=D,this}validate(D=!0){return this.options.validate=D,this}async generate(){let D=performance.now(),F={success:!1,outputDir:this.options.outputDir,filesGenerated:[],errors:[],warnings:[],duration:0};this.logger.debug(`Starting generation with ${this.generators.size} generators`);try{if(this.reportProgress("Loading",0,4,"Loading TypeSchema data..."),await this.resolveSchemas(),this.logger.debug(`Resolved ${this.schemas.length} schemas`),this.reportProgress("Validating",1,4,"Validating TypeSchema documents..."),this.options.validate)this.logger.debug("Starting schema validation"),await this.validateSchemas(F),this.logger.debug("Schema validation completed");this.reportProgress("Generating",2,4,"Generating code..."),this.logger.debug(`Executing ${this.generators.size} generators`),await this.executeGenerators(F),this.reportProgress("Complete",4,4,"Generation completed successfully"),F.success=F.errors.length===0,this.logger.debug(`Generation completed: ${F.filesGenerated.length} files`)}catch(u){this.logger.error("Code generation failed",u instanceof Error?u:Error(String(u))),F.errors.push(u instanceof Error?u.message:String(u)),F.success=!1}finally{F.duration=performance.now()-D}return F}async build(){await this.resolveSchemas();let D={};for(let[F,u]of this.generators.entries())if(u.build)D[F]=await u.build(this.schemas);return D}reset(){return this.schemas=[],this.generators.clear(),this.progressCallback=void 0,this}getSchemas(){return[...this.schemas]}getGenerators(){return Array.from(this.generators.keys())}async loadFromPackage(D,F){let u=new gD({verbose:this.options.verbose,logger:this.logger.child("Schema"),treeshake:this.typeSchemaConfig?.treeshake,manager:this.options.manager},this.typeSchemaConfig);this.typeSchemaGenerator=u;let C=await u.generateFromPackage(D,F);if(this.schemas=[...this.schemas,...C],this.cache)this.cache.setMany(C)}async loadFromFiles(D){if(!this.typeSchemaGenerator)this.typeSchemaGenerator=new gD({verbose:this.options.verbose,logger:this.logger.child("Schema"),treeshake:this.typeSchemaConfig?.treeshake},this.typeSchemaConfig);let u=await new T0({format:"auto",validate:this.options.validate}).parseFromFiles(D);if(this.schemas=[...this.schemas,...u],this.cache)this.cache.setMany(u)}async resolveSchemas(){if(this.pendingOperations.length>0)await Promise.all(this.pendingOperations),this.pendingOperations=[]}async validateSchemas(D){return}async executeGenerators(D){let F=this.generators.size,u=0;for(let[C,E]of this.generators.entries()){this.reportProgress("Generating",2+u/F,4,`Generating ${C}...`);try{let B=await E.generate(this.schemas);D.filesGenerated.push(...B.map(($)=>$.path||$.filename))}catch(B){D.errors.push(`${C} generator failed: ${B instanceof Error?B.message:String(B)}`)}u++}}reportProgress(D,F,u,C){if(this.progressCallback)this.progressCallback(D,F,u,C);if(this.options.verbose&&C)this.logger.debug(`[${D}] ${C}`)}}import{existsSync as m8}from"node:fs";import{readFile as c8}from"node:fs/promises";import{resolve as M6}from"node:path";var D1={outputDir:"./generated",verbose:!1,overwrite:!0,validate:!0,cache:!0,typescript:{moduleFormat:"esm",generateIndex:!0,includeDocuments:!1,namingConvention:"PascalCase",strictMode:!0,includeProfiles:!0,includeExtensions:!1,includeCodeSystems:!1,includeOperations:!1,generateValueSets:!1,valueSetDirectory:"valuesets",valueSetMode:"required-only",valueSetStrengths:["required"],includeValueSetHelpers:!1,fhirVersion:"R4",resourceTypes:[],maxDepth:10,profileOptions:{generateKind:"interface",includeConstraints:!0,includeDocumentation:!0,strictMode:!1,subfolder:"profiles"},generateBuilders:!1,builderOptions:{includeValidation:!0,includeFactoryMethods:!0,includeInterfaces:!0,generateNestedBuilders:!0,includeHelperMethods:!0,supportPartialBuild:!0,includeJSDoc:!0,generateFactories:!0,includeTypeGuards:!0,handleChoiceTypes:!0,generateArrayHelpers:!0},validatorOptions:{includeCardinality:!0,includeTypes:!0,includeConstraints:!0,includeInvariants:!1,validateRequired:!0,allowAdditional:!1,strictValidation:!1,collectMetrics:!1,generateAssertions:!0,generatePartialValidators:!0,optimizePerformance:!0,includeJSDoc:!0,generateCompositeValidators:!0},guardOptions:{includeRuntimeValidation:!0,includeErrorMessages:!0,treeShakeable:!0,targetTSVersion:"5.0",strictGuards:!1,includeNullChecks:!0,verbose:!1}},typeSchema:{enablePersistence:!0,cacheDir:".typeschema-cache",maxAge:86400000,validateCached:!0,forceRegenerate:!1,shareCache:!0,cacheKeyPrefix:"",treeshake:[],singleFile:!1,profiles:{autoDetect:!0}},packages:[],files:[],$schema:""},_F=["atomic-codegen.config.ts","atomic-codegen.config","atomic-codegen.config.json",".atomic-codegenrc","atomic-codegen.json",".atomic-codegen.json","codegen.config.json","codegen.json"];class V6{validate(D){let F={valid:!0,errors:[],warnings:[]};if(!D||typeof D!=="object")return F.valid=!1,F.errors.push({path:"root",message:"Configuration must be an object",value:D}),F;let u=D;if(u.outputDir!==void 0&&typeof u.outputDir!=="string")F.errors.push({path:"outputDir",message:"outputDir must be a string",value:u.outputDir});let C=["verbose","overwrite","validate","cache"];for(let E of C)if(u[E]!==void 0&&typeof u[E]!=="boolean")F.errors.push({path:E,message:`${E} must be a boolean`,value:u[E]});if(u.typescript!==void 0){let E=this.validateTypeScriptConfig(u.typescript);F.errors.push(...E)}if(u.typeSchema!==void 0){let E=this.validateTypeSchemaConfig(u.typeSchema);F.errors.push(...E)}if(u.packages!==void 0)if(!Array.isArray(u.packages))F.errors.push({path:"packages",message:"packages must be an array",value:u.packages});else u.packages.forEach((E,B)=>{if(typeof E!=="string")F.errors.push({path:`packages[${B}]`,message:"package name must be a string",value:E})});if(u.files!==void 0)if(!Array.isArray(u.files))F.errors.push({path:"files",message:"files must be an array",value:u.files});else u.files.forEach((E,B)=>{if(typeof E!=="string")F.errors.push({path:`files[${B}]`,message:"file path must be a string",value:E})});if(F.valid=F.errors.length===0,F.valid)F.config=u;return F}validateTypeScriptConfig(D){let F=[];if(typeof D!=="object"||D===null)return F.push({path:"typescript",message:"typescript config must be an object",value:D}),F;let u=D;if(u.moduleFormat!==void 0){if(!["esm","cjs"].includes(u.moduleFormat))F.push({path:"typescript.moduleFormat",message:'moduleFormat must be "esm" or "cjs"',value:u.moduleFormat})}if(u.namingConvention!==void 0){if(!["PascalCase","camelCase"].includes(u.namingConvention))F.push({path:"typescript.namingConvention",message:'namingConvention must be "PascalCase" or "camelCase"',value:u.namingConvention})}let C=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let E of C)if(u[E]!==void 0&&typeof u[E]!=="boolean")F.push({path:`typescript.${E}`,message:`${E} must be a boolean`,value:u[E]});if(u.validatorOptions!==void 0){let E=this.validateValidatorOptions(u.validatorOptions);F.push(...E)}if(u.guardOptions!==void 0){let E=this.validateGuardOptions(u.guardOptions);F.push(...E)}if(u.profileOptions!==void 0){let E=this.validateProfileOptions(u.profileOptions);F.push(...E)}return F}validateValidatorOptions(D){let F=[];if(typeof D!=="object"||D===null)return F.push({path:"typescript.validatorOptions",message:"validatorOptions must be an object",value:D}),F;let u=D,C=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let E of C)if(u[E]!==void 0&&typeof u[E]!=="boolean")F.push({path:`typescript.validatorOptions.${E}`,message:`${E} must be a boolean`,value:u[E]});return F}validateGuardOptions(D){let F=[];if(typeof D!=="object"||D===null)return F.push({path:"typescript.guardOptions",message:"guardOptions must be an object",value:D}),F;let u=D;if(u.targetTSVersion!==void 0){if(!["3.8","4.0","4.5","5.0"].includes(u.targetTSVersion))F.push({path:"typescript.guardOptions.targetTSVersion",message:'targetTSVersion must be one of: "3.8", "4.0", "4.5", "5.0"',value:u.targetTSVersion})}let C=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let E of C)if(u[E]!==void 0&&typeof u[E]!=="boolean")F.push({path:`typescript.guardOptions.${E}`,message:`${E} must be a boolean`,value:u[E]});return F}validateProfileOptions(D){let F=[];if(typeof D!=="object"||D===null)return F.push({path:"typescript.profileOptions",message:"profileOptions must be an object",value:D}),F;let u=D;if(u.generateKind!==void 0){if(!["interface","type","both"].includes(u.generateKind))F.push({path:"typescript.profileOptions.generateKind",message:'generateKind must be "interface", "type", or "both"',value:u.generateKind})}if(u.subfolder!==void 0&&typeof u.subfolder!=="string")F.push({path:"typescript.profileOptions.subfolder",message:"subfolder must be a string",value:u.subfolder});let C=["includeConstraints","includeDocumentation","strictMode"];for(let E of C)if(u[E]!==void 0&&typeof u[E]!=="boolean")F.push({path:`typescript.profileOptions.${E}`,message:`${E} must be a boolean`,value:u[E]});return F}validateTypeSchemaConfig(D){let F=[];if(typeof D!=="object"||D===null)return F.push({path:"typeSchema",message:"typeSchema config must be an object",value:D}),F;let u=D,C=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let B of C)if(u[B]!==void 0&&typeof u[B]!=="boolean")F.push({path:`typeSchema.${B}`,message:`${B} must be a boolean`,value:u[B]});let E=["cacheDir","cacheKeyPrefix"];for(let B of E)if(u[B]!==void 0&&typeof u[B]!=="string")F.push({path:`typeSchema.${B}`,message:`${B} must be a string`,value:u[B]});if(u.maxAge!==void 0){if(typeof u.maxAge!=="number"||u.maxAge<=0)F.push({path:"typeSchema.maxAge",message:"maxAge must be a positive number",value:u.maxAge})}if(u.profiles!==void 0)if(typeof u.profiles!=="object"||u.profiles===null)F.push({path:"typeSchema.profiles",message:"profiles must be an object",value:u.profiles});else{let B=u.profiles;if(B.autoDetect!==void 0&&typeof B.autoDetect!=="boolean")F.push({path:"typeSchema.profiles.autoDetect",message:"autoDetect must be a boolean",value:B.autoDetect})}return F}}class K6{validator=new V6;async autoload(D=process.cwd()){let F=await this.findConfigFile(D);if(F)return this.loadFromFile(F);return{...D1}}async loadFromFile(D){try{let F;if(D.endsWith(".ts")||D.endsWith("")){let E=await import(M6(D));F=E.default||E}else{let C=await c8(D,"utf-8");F=JSON.parse(C)}let u=this.validator.validate(F);if(!u.valid){let C=u.errors.map((E)=>`${E.path}: ${E.message}`).join(`
117
- `);throw Error(`Configuration validation failed:
118
- ${C}`)}return this.mergeWithDefaults(u.config)}catch(F){if(F instanceof Error)throw Error(`Failed to load config from ${D}: ${F.message}`);throw F}}async findConfigFile(D){for(let F of _F){let u=M6(D,F);if(m8(u))return u}return null}mergeWithDefaults(D){return{...D1,...D,typescript:{...D1.typescript,...D.typescript}}}}var l8=new K6;async function MF(D){return l8.autoload(D)}var R6={command:"generate",describe:"Generate code based on configuration file settings",builder:(D)=>D.option("verbose",{alias:"v",type:"boolean",default:!1,description:"Enable verbose output"}).example("$0 generate","Generate code using settings from config file").example("$0 generate --verbose","Generate with verbose output"),handler:async(D)=>{if(D._.length>1){let $=D._.slice(1).join(" ");KD(`Invalid syntax: 'atomic-codegen generate ${$}'
29
+ ${i}`:r}filterAndSortSchemas(e){return this.collectedValueSets=this.collectValueSets(e),e.filter(t=>!this.shouldSkipSchema(t))}async validateContent(e,t){let r=/export\s+(interface|class|type|enum)\s+\w+/.test(e),i=e.includes("{")&&e.includes("}");if(!r)throw new Error(`Generated content for ${t.schema.identifier.name} does not contain valid export statements`);if(!i)throw new Error(`Generated content for ${t.schema.identifier.name} has invalid syntax (missing braces)`)}async transformSchemas(e){let t=[];for(let r of e){let i=await this.transformSchema(r);i&&t.push(i);}return t}async transformSchema(e){if(this.shouldSkipSchema(e))return;let t={schema:e,typeMapper:this.typeMapper,filename:this.getFilenameForSchema(e),language:"TypeScript",timestamp:new Date().toISOString()},r=await this.generateSchemaContent(e,t);if(!r.trim())return;let i=this.extractImportsFromContent(r,e),n=this.extractExportsFromContent(r,e),o=this.getFilenameForSchema(e);return {content:r,imports:i,exports:Array.from(n),filename:o}}shouldGenerateValueSet(e){if(!ue(e)||!e.enum||!Array.isArray(e.enum)||e.enum.length===0)return false;switch(this.options.valueSetMode||"required-only"){case "all":return true;case "required-only":return e.strength==="required";case "custom":return (this.options.valueSetStrengths||["required"]).includes(e.strength);default:return e.strength==="required"}}collectValueSets(e){let t=new Map;for(let r of e)if(this.shouldGenerateValueSet(r)&&ue(r)){let i=this.typeMapper.formatTypeName(r.identifier.name);t.set(i,r);}return t}shouldUseValueSetType(e){if(!e||!this.tsOptions.generateValueSets)return false;let t=this.typeMapper.formatTypeName(e.name);return this.collectedValueSets.has(t)}getValueSetTypeName(e){return this.typeMapper.formatTypeName(e.name)}shouldUseInlineEnum(e){return !e||this.tsOptions.generateValueSets?false:e.enum&&Array.isArray(e.enum)&&e.enum.length>0}generateInlineEnumType(e){return !e.enum||!Array.isArray(e.enum)?"string":e.enum.map(r=>`'${r}'`).join(" | ")}shouldSkipSchema(e){if(e.identifier.kind==="value-set"||e.identifier.kind==="binding"||e.identifier.kind==="primitive-type")return true;if(!this.tsOptions.includeExtensions){let t=e.identifier.url;if(t?.includes("StructureDefinition/")){let r=t.split("StructureDefinition/")[1];if(r){let i=r.includes("-"),n=e.identifier.kind==="profile";if(i&&n)return true}}}return false}getFilenameForSchema(e){return `${this.typeMapper.formatFileName(e.identifier.name)}${this.getFileExtension()}`}extractImportsFromContent(e,t){let r=new Map,i=/import\s+(?:type\s+)?{\s*([^}]+)\s*}\s+from\s+['"]([^'"]+)['"];?/g,n;for(;(n=i.exec(e))!==null;){let o=n[1],a=n[2];if(!o||!a)continue;let c=o.split(",").map(l=>l.trim());for(let l of c)r.set(l,a);}return r}extractExportsFromContent(e,t){let r=new Set,i=/export\s+(?:interface|class|enum|type)\s+([A-Za-z_$][A-Za-z0-9_$]*)/g,n;for(;(n=i.exec(e))!==null;)n[1]&&r.add(n[1]);return r.add(this.typeMapper.formatTypeName(t.identifier.name)),r}generateReferenceInterface(e){let t=[],r=new Set;if("fields"in e&&e.fields)for(let[,i]of Object.entries(e.fields))this.collectFieldImports(i).forEach(o=>r.add(o));if(t.push("import type { ResourceType } from './utilities.js';"),r.size>0){let i=Array.from(r).sort();for(let n of i)t.push(`import type { ${n} } from './${n}.js';`);}if(t.push(""),this.tsOptions.includeDocuments&&e.description&&(t.push("/**"),t.push(` * ${e.description}`),e.identifier.url&&t.push(` * @see ${e.identifier.url}`),e.identifier.package&&t.push(` * @package ${e.identifier.package}`),t.push(" * @template T - The resource type being referenced"),t.push(" */")),t.push("export interface Reference<T extends ResourceType = ResourceType> {"),"fields"in e&&e.fields)for(let[i,n]of Object.entries(e.fields))if(i==="type")t.push(" type?: T;");else {let o=this.generateFieldLines(i,n);for(let a of o)a&&t.push(` ${a}`);}return t.push("}"),t.join(`
30
+ `)}generateTypeScriptInterface(e){let t=[],r=this.typeMapper.formatTypeName(e.identifier.name),i=new Set,n=new Set;if("fields"in e&&e.fields)for(let[,o]of Object.entries(e.fields)){let a=this.collectFieldImports(o);for(let c of a)this.collectedValueSets.has(c)?n.add(c):i.add(c);}if("nested"in e&&e.nested&&Array.isArray(e.nested)){for(let o of e.nested)if(o.fields)for(let[,a]of Object.entries(o.fields)){let c=this.collectFieldImports(a);for(let l of c)this.collectedValueSets.has(l)?n.add(l):i.add(l);}}if(i.size>0){let o=Array.from(i).sort();for(let a of o)t.push(`import type { ${a} } from './${a}.js';`);}if(n.size>0){let a=Array.from(n).sort().join(", ");t.push(`import type { ${a} } from './valuesets/index.js';`);}if((i.size>0||n.size>0)&&t.push(""),this.tsOptions.includeDocuments&&e.description&&(t.push("/**"),t.push(` * ${e.description}`),e.identifier.url&&t.push(` * @see ${e.identifier.url}`),e.identifier.package&&t.push(` * @package ${e.identifier.package}`),t.push(" */")),t.push(`export interface ${r} {`),e.identifier.kind==="resource"&&t.push(` resourceType: '${r}';`),"fields"in e&&e.fields)for(let[o,a]of Object.entries(e.fields)){let c=this.generateFieldLines(o,a);for(let l of c)l&&t.push(` ${l}`);}return t.push("}"),t.join(`
31
+ `)}collectFieldImports(e){let t=[];if("choices"in e&&e.choices&&Array.isArray(e.choices))return t;if(e.binding&&this.shouldUseValueSetType(e.binding)){let r=this.getValueSetTypeName(e.binding);return t.push(r),t}if("type"in e&&e.type){if(e.type.kind==="nested")return t;let r=this.typeMapper.mapType(e.type);!r.isPrimitive&&r.name!=="any"&&(["string","number","boolean","Date","object","unknown","any"].includes(r.name)||t.push(r.name));}return [...new Set(t)]}extractReferenceTypes(e){let t=[];if(!Array.isArray(e))return t;for(let r of e)if(!(!r||typeof r!="object")&&r.kind==="resource"&&r.name){let i=this.typeMapper.formatTypeName(r.name);t.push(i);}return [...new Set(t)]}generateNestedTypeInterface(e,t){let r=[],i=this.typeMapper.formatTypeName(`${e}${this.capitalizeFirst(t.identifier.name)}`);if(this.tsOptions.includeDocuments&&t.description&&(r.push("/**"),r.push(` * ${t.description}`),t.identifier.url&&r.push(` * @see ${t.identifier.url}`),r.push(" */")),r.push(`export interface ${i} {`),t.fields)for(let[n,o]of Object.entries(t.fields)){let a=this.generateFieldLines(n,o);for(let c of a)c&&r.push(` ${c}`);}return r.push("}"),r.join(`
32
+ `)}capitalizeFirst(e){return e.charAt(0).toUpperCase()+e.slice(1)}generateFieldLines(e,t){if("choices"in t&&t.choices&&Array.isArray(t.choices))return [];let r=this.generateFieldLine(e,t);return r?[r]:[]}generateFieldLine(e,t){let r="any",i=false,n=false;if("type"in t&&t.type){if(t.binding&&this.shouldUseValueSetType(t.binding))r=this.getValueSetTypeName(t.binding);else if(t.binding&&this.shouldUseInlineEnum(t))r=this.generateInlineEnumType(t);else if(r=this.typeMapper.mapType(t.type).name,t.type.kind==="nested"){let l=t.type.url?.split("#")||[];if(l.length===2){let p=l[0].split("/").pop()||"",d=t.type.name;r=this.typeMapper.formatTypeName(`${p}${this.capitalizeFirst(d)}`);}else r=this.typeMapper.formatTypeName(t.type.name);}else if(r==="Reference"&&t.reference&&Array.isArray(t.reference)){let l=this.extractReferenceTypes(t.reference);l.length>0&&(l.forEach(d=>this.resourceTypes.add(d)),r=`Reference<${l.map(d=>`'${d}'`).join(" | ")}>`);}}return "required"in t&&(i=t.required),"array"in t&&(n=t.array),`${e}${i?"":"?"}: ${r}${n?"[]":""};`}extractExports(e){let t=[],r=/export\s*\{\s*([^}]+)\s*\}/g,i;for(;(i=r.exec(e))!==null;)if(i[1]){let o=i[1].split(",").map(a=>a.trim()).filter(Boolean);t.push(...o);}let n=[/export\s+interface\s+(\w+)/g,/export\s+type\s+(\w+)/g,/export\s+class\s+(\w+)/g,/export\s+enum\s+(\w+)/g,/export\s+const\s+(\w+)/g,/export\s+function\s+(\w+)/g];for(let o of n){let a;for(;(a=o.exec(e))!==null;)a[1]&&t.push(a[1]);}return [...new Set(t)]}setOutputDir(e){this.options.outputDir=e;}setOptions(e){this.options={...this.options,...e};}getOptions(){return {...this.options}}async generate(e){return await this.fileManager.cleanDirectory(),this.logger.debug("Cleaned output directory before generation"),super.generate(e)}async runPostGenerationHooks(){await super.runPostGenerationHooks(),await this.generateValueSetFiles(),await this.generateUtilitiesFile(),await this.generateMainIndexFile();}async generateUtilitiesFile(){if(this.resourceTypes.size===0){this.logger.warn("No resource types found, skipping utilities.ts generation");return}let e=[];e.push("/**"),e.push(" * FHIR Resource Type Utilities"),e.push(" * This file contains utility types for FHIR resources."),e.push(" * "),e.push(" * @generated This file is auto-generated. Do not edit manually."),e.push(" */"),e.push("");let t=Array.from(this.resourceTypes).sort();e.push("/**"),e.push(" * Union of all FHIR resource types in this package"),e.push(" */"),e.push("export type ResourceType =");for(let i=0;i<t.length;i++){let o=i===t.length-1?";":"";e.push(` | '${t[i]}'${o}`);}e.push(""),e.push("/**"),e.push(" * Helper type for creating typed References"),e.push(" * @example Reference<'Patient' | 'Practitioner'> - Reference that can point to Patient or Practitioner"),e.push(" */"),e.push("export type TypedReference<T extends ResourceType> = {"),e.push(" reference?: string;"),e.push(" type?: T;"),e.push(" identifier?: any; // Simplified for utility"),e.push(" display?: string;"),e.push("};");let r=e.join(`
33
+ `);await this.fileManager.writeFile("utilities.ts",r),this.logger.info(`Generated utilities.ts with ${this.resourceTypes.size} resource types`);}generateValueSetFile(e){let t=this.typeMapper.formatTypeName(e.identifier.name),r=e.enum?.map(n=>` '${n}'`).join(`,
34
+ `)||"",i=[];return this.options.includeDocuments&&(i.push("/**"),i.push(` * ${e.identifier.name} value set`),e.description&&i.push(` * ${e.description}`),e.valueset?.url&&i.push(` * @see ${e.valueset.url}`),e.identifier.package&&i.push(` * @package ${e.identifier.package}`),i.push(" * @generated This file is auto-generated. Do not edit manually."),i.push(" */"),i.push("")),i.push(`export const ${t}Values = [`),r&&i.push(r),i.push("] as const;"),i.push(""),i.push(`export type ${t} = typeof ${t}Values[number];`),this.tsOptions.includeValueSetHelpers&&(i.push(""),i.push(`export const isValid${t} = (value: string): value is ${t} =>`),i.push(` ${t}Values.includes(value as ${t});`)),i.join(`
35
+ `)}async generateValueSetFiles(){if(!(!this.tsOptions.generateValueSets||this.collectedValueSets.size===0)){for(let[e,t]of this.collectedValueSets){let r=this.generateValueSetFile(t),i=`valuesets/${e}.ts`;await this.fileManager.writeFile(i,r),this.logger.info(`Generated value set: ${i}`);}await this.generateValueSetIndexFile();}}async generateValueSetIndexFile(){let e=[];this.tsOptions.includeDocuments&&(e.push("/**"),e.push(" * FHIR Value Sets"),e.push(" * This file re-exports all generated value sets."),e.push(" * "),e.push(" * @generated This file is auto-generated. Do not edit manually."),e.push(" */"),e.push(""));let t=Array.from(this.collectedValueSets.keys()).sort();for(let i of t)e.push(`export * from './${i}.js';`);let r=e.join(`
36
+ `);await this.fileManager.writeFile("valuesets/index.ts",r),this.logger.info(`Generated valuesets/index.ts with ${this.collectedValueSets.size} value sets`);}async generateMainIndexFile(){if(!this.options.generateIndex)return;let e=[];this.tsOptions.includeDocuments&&(e.push("/**"),e.push(" * FHIR R4 TypeScript Types"),e.push(" * Generated from FHIR StructureDefinitions"),e.push(" * "),e.push(" * @generated This file is auto-generated. Do not edit manually."),e.push(" */"),e.push("")),e.push('export * from "./utilities";'),this.tsOptions.generateValueSets&&this.collectedValueSets.size>0&&(e.push(""),e.push("// Value Sets"),e.push('export * from "./valuesets/index";'));let t=e.join(`
37
+ `);await this.fileManager.writeFile("index.ts",t),this.logger.info(`Generated index.ts with type exports${this.tsOptions.generateValueSets&&this.collectedValueSets.size>0?" and value sets":""}`);}};var M=class{schemas=[];options;generators=new Map;progressCallback;cache;pendingOperations=[];typeSchemaGenerator;logger;typeSchemaConfig;constructor(e={}){this.options={outputDir:e.outputDir||"./generated",verbose:e.verbose??false,overwrite:e.overwrite??true,validate:e.validate??true,cache:e.cache??true,typeSchemaConfig:e.typeSchemaConfig,manager:e.manager||null},this.typeSchemaConfig=e.typeSchemaConfig,this.logger=e.logger||b({verbose:this.options.verbose,prefix:"API"}),this.options.cache&&(this.cache=new x(this.typeSchemaConfig));}fromPackage(e,t){this.logger.debug(`Loading from FHIR package: ${e}@${t||"latest"}`);let r=this.loadFromPackage(e,t);return this.pendingOperations.push(r),this}fromFiles(...e){this.logger.debug(`Loading from ${e.length} TypeSchema files`);let t=this.loadFromFiles(e);return this.pendingOperations.push(t),this}fromSchemas(e){return this.logger.debug(`Adding ${e.length} TypeSchemas to generation`),this.schemas=[...this.schemas,...e],this}typescript(e={}){let t=`${this.options.outputDir}/types`,r=new P({outputDir:t,moduleFormat:e.moduleFormat||"esm",generateIndex:e.generateIndex??true,includeDocuments:e.includeDocuments??true,namingConvention:e.namingConvention||"PascalCase",includeExtensions:e.includeExtensions??false,includeProfiles:e.includeProfiles??false,generateValueSets:e.generateValueSets??false,includeValueSetHelpers:e.includeValueSetHelpers??false,valueSetStrengths:e.valueSetStrengths??["required"],logger:this.logger.child("TS"),valueSetMode:e.valueSetMode??"required-only",valueSetDirectory:e.valueSetDirectory??"valuesets",verbose:this.options.verbose,validate:true,overwrite:this.options.overwrite});return this.generators.set("typescript",r),this.logger.debug(`Configured TypeScript generator (${e.moduleFormat||"esm"})`),this}onProgress(e){return this.progressCallback=e,this}outputTo(e){this.logger.debug(`Setting output directory: ${e}`),this.options.outputDir=e;for(let t of this.generators.values())t.setOutputDir&&t.setOutputDir(e);return this}verbose(e=true){return this.options.verbose=e,this}validate(e=true){return this.options.validate=e,this}async generate(){let e=performance.now(),t={success:false,outputDir:this.options.outputDir,filesGenerated:[],errors:[],warnings:[],duration:0};this.logger.debug(`Starting generation with ${this.generators.size} generators`);try{this.reportProgress("Loading",0,4,"Loading TypeSchema data..."),await this.resolveSchemas(),this.logger.debug(`Resolved ${this.schemas.length} schemas`),this.reportProgress("Validating",1,4,"Validating TypeSchema documents..."),this.options.validate&&(this.logger.debug("Starting schema validation"),await this.validateSchemas(t),this.logger.debug("Schema validation completed")),this.reportProgress("Generating",2,4,"Generating code..."),this.logger.debug(`Executing ${this.generators.size} generators`),await this.executeGenerators(t),this.reportProgress("Complete",4,4,"Generation completed successfully"),t.success=t.errors.length===0,this.logger.debug(`Generation completed: ${t.filesGenerated.length} files`);}catch(r){this.logger.error("Code generation failed",r instanceof Error?r:new Error(String(r))),t.errors.push(r instanceof Error?r.message:String(r)),t.success=false;}finally{t.duration=performance.now()-e;}return t}async build(){await this.resolveSchemas();let e={};for(let[t,r]of this.generators.entries())r.build&&(e[t]=await r.build(this.schemas));return e}reset(){return this.schemas=[],this.generators.clear(),this.progressCallback=void 0,this}getSchemas(){return [...this.schemas]}getGenerators(){return Array.from(this.generators.keys())}async loadFromPackage(e,t){let r=new S({verbose:this.options.verbose,logger:this.logger.child("Schema"),treeshake:this.typeSchemaConfig?.treeshake,manager:this.options.manager},this.typeSchemaConfig);this.typeSchemaGenerator=r;let i=await r.generateFromPackage(e,t);this.schemas=[...this.schemas,...i],this.cache&&this.cache.setMany(i);}async loadFromFiles(e){this.typeSchemaGenerator||(this.typeSchemaGenerator=new S({verbose:this.options.verbose,logger:this.logger.child("Schema"),treeshake:this.typeSchemaConfig?.treeshake},this.typeSchemaConfig));let r=await new F({format:"auto",validate:this.options.validate}).parseFromFiles(e);this.schemas=[...this.schemas,...r],this.cache&&this.cache.setMany(r);}async resolveSchemas(){this.pendingOperations.length>0&&(await Promise.all(this.pendingOperations),this.pendingOperations=[]);}async validateSchemas(e){}async executeGenerators(e){let t=this.generators.size,r=0;for(let[i,n]of this.generators.entries()){this.reportProgress("Generating",2+r/t,4,`Generating ${i}...`);try{let o=await n.generate(this.schemas);e.filesGenerated.push(...o.map(a=>a.path||a.filename));}catch(o){e.errors.push(`${i} generator failed: ${o instanceof Error?o.message:String(o)}`);}r++;}}reportProgress(e,t,r,i){this.progressCallback&&this.progressCallback(e,t,r,i),this.options.verbose&&i&&this.logger.debug(`[${e}] ${i}`);}};var $e={outputDir:"./generated",verbose:false,overwrite:true,validate:true,cache:true,typescript:{moduleFormat:"esm",generateIndex:true,includeDocuments:false,namingConvention:"PascalCase",strictMode:true,includeProfiles:true,includeExtensions:false,includeCodeSystems:false,includeOperations:false,generateValueSets:false,valueSetDirectory:"valuesets",valueSetMode:"required-only",valueSetStrengths:["required"],includeValueSetHelpers:false,fhirVersion:"R4",resourceTypes:[],maxDepth:10,profileOptions:{generateKind:"interface",includeConstraints:true,includeDocumentation:true,strictMode:false,subfolder:"profiles"},generateBuilders:false,builderOptions:{includeValidation:true,includeFactoryMethods:true,includeInterfaces:true,generateNestedBuilders:true,includeHelperMethods:true,supportPartialBuild:true,includeJSDoc:true,generateFactories:true,includeTypeGuards:true,handleChoiceTypes:true,generateArrayHelpers:true},validatorOptions:{includeCardinality:true,includeTypes:true,includeConstraints:true,includeInvariants:false,validateRequired:true,allowAdditional:false,strictValidation:false,collectMetrics:false,generateAssertions:true,generatePartialValidators:true,optimizePerformance:true,includeJSDoc:true,generateCompositeValidators:true},guardOptions:{includeRuntimeValidation:true,includeErrorMessages:true,treeShakeable:true,targetTSVersion:"5.0",strictGuards:false,includeNullChecks:true,verbose:false}},typeSchema:{enablePersistence:true,cacheDir:".typeschema-cache",maxAge:1440*60*1e3,validateCached:true,forceRegenerate:false,shareCache:true,cacheKeyPrefix:"",treeshake:[],singleFile:false,profiles:{autoDetect:true}},packages:[],files:[],$schema:""},X=["atomic-codegen.config.ts","atomic-codegen.config","atomic-codegen.config.json",".atomic-codegenrc","atomic-codegen.json",".atomic-codegen.json","codegen.config.json","codegen.json"],Re=class{validate(e){let t={valid:true,errors:[],warnings:[]};if(!e||typeof e!="object")return t.valid=false,t.errors.push({path:"root",message:"Configuration must be an object",value:e}),t;let r=e;r.outputDir!==void 0&&typeof r.outputDir!="string"&&t.errors.push({path:"outputDir",message:"outputDir must be a string",value:r.outputDir});let i=["verbose","overwrite","validate","cache"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.errors.push({path:n,message:`${n} must be a boolean`,value:r[n]});if(r.typescript!==void 0){let n=this.validateTypeScriptConfig(r.typescript);t.errors.push(...n);}if(r.typeSchema!==void 0){let n=this.validateTypeSchemaConfig(r.typeSchema);t.errors.push(...n);}return r.packages!==void 0&&(Array.isArray(r.packages)?r.packages.forEach((n,o)=>{typeof n!="string"&&t.errors.push({path:`packages[${o}]`,message:"package name must be a string",value:n});}):t.errors.push({path:"packages",message:"packages must be an array",value:r.packages})),r.files!==void 0&&(Array.isArray(r.files)?r.files.forEach((n,o)=>{typeof n!="string"&&t.errors.push({path:`files[${o}]`,message:"file path must be a string",value:n});}):t.errors.push({path:"files",message:"files must be an array",value:r.files})),t.valid=t.errors.length===0,t.valid&&(t.config=r),t}validateTypeScriptConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript",message:"typescript config must be an object",value:e}),t;let r=e;r.moduleFormat!==void 0&&(["esm","cjs"].includes(r.moduleFormat)||t.push({path:"typescript.moduleFormat",message:'moduleFormat must be "esm" or "cjs"',value:r.moduleFormat})),r.namingConvention!==void 0&&(["PascalCase","camelCase"].includes(r.namingConvention)||t.push({path:"typescript.namingConvention",message:'namingConvention must be "PascalCase" or "camelCase"',value:r.namingConvention}));let i=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.${n}`,message:`${n} must be a boolean`,value:r[n]});if(r.validatorOptions!==void 0){let n=this.validateValidatorOptions(r.validatorOptions);t.push(...n);}if(r.guardOptions!==void 0){let n=this.validateGuardOptions(r.guardOptions);t.push(...n);}if(r.profileOptions!==void 0){let n=this.validateProfileOptions(r.profileOptions);t.push(...n);}return t}validateValidatorOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.validatorOptions",message:"validatorOptions must be an object",value:e}),t;let r=e,i=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.validatorOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateGuardOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.guardOptions",message:"guardOptions must be an object",value:e}),t;let r=e;r.targetTSVersion!==void 0&&(["3.8","4.0","4.5","5.0"].includes(r.targetTSVersion)||t.push({path:"typescript.guardOptions.targetTSVersion",message:'targetTSVersion must be one of: "3.8", "4.0", "4.5", "5.0"',value:r.targetTSVersion}));let i=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.guardOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateProfileOptions(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typescript.profileOptions",message:"profileOptions must be an object",value:e}),t;let r=e;r.generateKind!==void 0&&(["interface","type","both"].includes(r.generateKind)||t.push({path:"typescript.profileOptions.generateKind",message:'generateKind must be "interface", "type", or "both"',value:r.generateKind})),r.subfolder!==void 0&&typeof r.subfolder!="string"&&t.push({path:"typescript.profileOptions.subfolder",message:"subfolder must be a string",value:r.subfolder});let i=["includeConstraints","includeDocumentation","strictMode"];for(let n of i)r[n]!==void 0&&typeof r[n]!="boolean"&&t.push({path:`typescript.profileOptions.${n}`,message:`${n} must be a boolean`,value:r[n]});return t}validateTypeSchemaConfig(e){let t=[];if(typeof e!="object"||e===null)return t.push({path:"typeSchema",message:"typeSchema config must be an object",value:e}),t;let r=e,i=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let o of i)r[o]!==void 0&&typeof r[o]!="boolean"&&t.push({path:`typeSchema.${o}`,message:`${o} must be a boolean`,value:r[o]});let n=["cacheDir","cacheKeyPrefix"];for(let o of n)r[o]!==void 0&&typeof r[o]!="string"&&t.push({path:`typeSchema.${o}`,message:`${o} must be a string`,value:r[o]});if(r.maxAge!==void 0&&(typeof r.maxAge!="number"||r.maxAge<=0)&&t.push({path:"typeSchema.maxAge",message:"maxAge must be a positive number",value:r.maxAge}),r.profiles!==void 0)if(typeof r.profiles!="object"||r.profiles===null)t.push({path:"typeSchema.profiles",message:"profiles must be an object",value:r.profiles});else {let o=r.profiles;o.autoDetect!==void 0&&typeof o.autoDetect!="boolean"&&t.push({path:"typeSchema.profiles.autoDetect",message:"autoDetect must be a boolean",value:o.autoDetect});}return t}},Ie=class{validator=new Re;async autoload(e=process.cwd()){let t=await this.findConfigFile(e);return t?this.loadFromFile(t):{...$e}}async loadFromFile(e){try{let t;if(e.endsWith(".ts")||e.endsWith("")){let n=await import(resolve(e));t=n.default||n;}else {let i=await readFile(e,"utf-8");t=JSON.parse(i);}let r=this.validator.validate(t);if(!r.valid){let i=r.errors.map(n=>`${n.path}: ${n.message}`).join(`
38
+ `);throw new Error(`Configuration validation failed:
39
+ ${i}`)}return this.mergeWithDefaults(r.config)}catch(t){throw t instanceof Error?new Error(`Failed to load config from ${e}: ${t.message}`):t}}async findConfigFile(e){for(let t of X){let r=resolve(e,t);if(existsSync(r))return r}return null}mergeWithDefaults(e){return {...$e,...e,typescript:{...$e.typescript,...e.typescript}}}},Lt=new Ie;async function ee(s){return Lt.autoload(s)}var tt={command:"generate",describe:"Generate code based on configuration file settings",builder:s=>s.option("verbose",{alias:"v",type:"boolean",default:false,description:"Enable verbose output"}).example("$0 generate","Generate code using settings from config file").example("$0 generate --verbose","Generate with verbose output"),handler:async s=>{if(s._.length>1){let o=s._.slice(1).join(" ");h(`Invalid syntax: 'atomic-codegen generate ${o}'
119
40
 
120
41
  The CLI has been simplified and no longer uses subcommands.
121
42
 
122
- `+`✅ Use: atomic-codegen generate
123
- `+`❌ Old: atomic-codegen generate typescript
43
+ \u2705 Use: atomic-codegen generate
44
+ \u274C Old: atomic-codegen generate typescript
124
45
 
125
- `+`All generation settings are now configured in your config file.
126
- Create an atomic-codegen.config.ts file to get started.`),process.exit(1)}let F=process.cwd(),u=await i8(F);if(!u){let $=_F.map((Z)=>` - ${Z}`).join(`
127
- `);KD(`No configuration file found. Please create one of the following files in your project root:
128
- ${$}
46
+ All generation settings are now configured in your config file.
47
+ Create an atomic-codegen.config.ts file to get started.`),process.exit(1);}let e=process.cwd(),t=await Ut(e);if(!t){let o=X.map(a=>` - ${a}`).join(`
48
+ `);h(`No configuration file found. Please create one of the following files in your project root:
49
+ ${o}
129
50
 
130
51
  Example atomic-codegen.config.ts:
131
52
 
@@ -136,13 +57,13 @@ export default defineConfig({
136
57
  typescript: {
137
58
  generateIndex: true
138
59
  }
139
- });`),process.exit(1)}let C=await MF(F),E=D.verbose??C.verbose??!1,B=jD({verbose:E,prefix:"Generate"});try{if(E2("Starting generation from config"),E)B.info(`Config file: ${u}`),B.info(`Output directory: ${C.outputDir||"./generated"}`),B.info(`Packages: ${C.packages?.length||0}`),B.info(`Files: ${C.files?.length||0}`),B.info(`TypeScript generation: ${C.typescript?"enabled":"disabled"}`);let $=new qF({outputDir:C.outputDir||"./generated",verbose:E,overwrite:C.overwrite??!0,validate:C.validate??!0,cache:C.cache??!0,typeSchemaConfig:C.typeSchema,logger:B});if(C.packages&&C.packages.length>0){B.info(`Loading packages from config: ${C.packages.join(", ")}`);for(let Q of C.packages){let[z,O]=Q.includes("@")?Q.split("@"):[Q,void 0];$.fromPackage(z,O)}}else if(C.files&&C.files.length>0){B.info(`Loading files from config: ${C.files.join(", ")}`);for(let Q of C.files)$.fromFiles(Q)}else throw Error("No data source specified in config. Please configure 'packages' or 'files' in your config file.");if(C.typescript){if(E)B.info("Configuring TypeScript generation from config"),B.debug(`Module format: ${C.typescript.moduleFormat||"esm"}`),B.debug(`Generate index: ${C.typescript.generateIndex??!0}`),B.debug(`Include docs: ${C.typescript.includeDocuments??!1}`),B.debug(`Naming convention: ${C.typescript.namingConvention||"PascalCase"}`);$.typescript(C.typescript)}if(!C.typescript)throw Error("No generators configured. Please enable 'typescript' in your config file.");if(E)$.onProgress((Q,z,O,A)=>{let J=Math.round(z/O*100);B.progress(`[${Q}] ${J}% - ${A||"Processing..."}`)});B.step("Executing generation...");let Z=await $.generate();if(Z.success){if(s0(`Generated ${Z.filesGenerated.length} files in ${Z.duration.toFixed(2)}ms`),B.dim(`Output directory: ${Z.outputDir}`),Z.warnings.length>0)for(let Q of Z.warnings)C2(Q)}else{KD(`Generation failed with ${Z.errors.length} errors`);for(let Q of Z.errors)B.dim(` ${Q}`);process.exit(1)}}catch($){KD("Generation failed with unexpected error",$ instanceof Error?$:Error(String($))),process.exit(1)}}};async function i8(D){for(let F of _F){let u=n8(D,F);if(o8(u))return u}return null}import{mkdir as t8,writeFile as s8}from"node:fs/promises";import{dirname as r8}from"node:path";var U6={command:"generate <packages..>",describe:"Generate TypeSchema files from FHIR packages",builder:{packages:{type:"string",array:!0,demandOption:!0,describe:"FHIR packages to process (e.g., hl7.fhir.r4.core@4.0.1)"},output:{alias:"o",type:"string",describe:"Output file or directory",default:"./schemas.ndjson"},format:{alias:"f",type:"string",choices:["ndjson","json"],default:"ndjson",describe:"Output format for TypeSchema files"},treeshake:{alias:"t",type:"string",array:!0,describe:"Only generate TypeSchemas for specific ResourceTypes (treeshaking)"},singleFile:{alias:"s",type:"boolean",default:!1,describe:"Generate single TypeSchema file instead of multiple files (NDJSON format)"},verbose:{alias:"v",type:"boolean",default:!1,describe:"Enable verbose output"}},handler:async(D)=>{let F=jD({verbose:D.verbose,prefix:"TypeSchema"});try{let u=await MF(process.cwd());F.step("Generating TypeSchema from FHIR packages"),F.info(`Packages: ${D.packages.join(", ")}`),F.info(`Output: ${D.output}`);let C=D.singleFile!==void 0?D.singleFile:u.typeSchema?.singleFile??!1,E=C?"ndjson":D.format;F.debug(`Format: ${E}${C&&D.format==="json"?" (forced from json due to singleFile)":""}`);let B=D.treeshake&&D.treeshake.length>0?D.treeshake:u.typeSchema?.treeshake;if(B&&B.length>0)F.info(`Treeshaking enabled for ResourceTypes: ${B.join(", ")}`);if(C)F.info("Single file output enabled (NDJSON format)");let $=Date.now(),Z=new gD({verbose:D.verbose,treeshake:B}),Q=[];for(let J of D.packages){let[W,_]=J.includes("@")?J.split("@"):[J,void 0];F.progress(`Processing package: ${W}${_?`@${_}`:""}`);let q=await Z.generateFromPackage(W,_);Q.push(...q)}if(Q.length===0)throw Error("No schemas were generated from the specified packages");let z=D.output;await t8(r8(z),{recursive:!0});let O;if(E==="json")O=JSON.stringify(Q,null,2);else O=Q.map((J)=>JSON.stringify(J)).join(`
140
- `);await s8(z,O,"utf-8");let A=Date.now()-$;if(Z2(`Generated ${Q.length} TypeSchema definitions`,A,{schemas:Q.length}),F.dim(`Output: ${z}`),D.verbose){F.debug("Generated schemas:");let J=Q.map((W)=>`${W.identifier?.name||"Unknown"} (${W.identifier?.kind||"unknown"})`);B0(J)}}catch(u){F.error("Failed to generate TypeSchema",u instanceof Error?u:Error(String(u))),process.exit(1)}}};var j6={command:"typeschema [subcommand]",describe:"TypeSchema operations - generate, validate and merge schemas",builder:(D)=>{return D.command(U6).help().example("$0 typeschema generate hl7.fhir.r4.core@4.0.1","Generate TypeSchema from FHIR R4 core package")},handler:(D)=>{if(!D.subcommand&&D._.length===1){r0("Available typeschema subcommands:"),B0(["generate Generate TypeSchema files from FHIR packages"]),console.log(`
60
+ });`),process.exit(1);}let r=await ee(e),i=s.verbose??r.verbose??false,n=b({verbose:i,prefix:"Generate"});try{se("Starting generation from config"),i&&(n.info(`Config file: ${t}`),n.info(`Output directory: ${r.outputDir||"./generated"}`),n.info(`Packages: ${r.packages?.length||0}`),n.info(`Files: ${r.files?.length||0}`),n.info(`TypeScript generation: ${r.typescript?"enabled":"disabled"}`));let o=new M({outputDir:r.outputDir||"./generated",verbose:i,overwrite:r.overwrite??!0,validate:r.validate??!0,cache:r.cache??!0,typeSchemaConfig:r.typeSchema,logger:n});if(r.packages&&r.packages.length>0){n.info(`Loading packages from config: ${r.packages.join(", ")}`);for(let c of r.packages){let[l,p]=c.includes("@")?c.split("@"):[c,void 0];o.fromPackage(l,p);}}else if(r.files&&r.files.length>0){n.info(`Loading files from config: ${r.files.join(", ")}`);for(let c of r.files)o.fromFiles(c);}else throw new Error("No data source specified in config. Please configure 'packages' or 'files' in your config file.");if(r.typescript&&(i&&(n.info("Configuring TypeScript generation from config"),n.debug(`Module format: ${r.typescript.moduleFormat||"esm"}`),n.debug(`Generate index: ${r.typescript.generateIndex??!0}`),n.debug(`Include docs: ${r.typescript.includeDocuments??!1}`),n.debug(`Naming convention: ${r.typescript.namingConvention||"PascalCase"}`)),o.typescript(r.typescript)),!r.typescript)throw new Error("No generators configured. Please enable 'typescript' in your config file.");i&&o.onProgress((c,l,p,d)=>{let f=Math.round(l/p*100);n.progress(`[${c}] ${f}% - ${d||"Processing..."}`);}),n.step("Executing generation...");let a=await o.generate();if(a.success){if(B(`Generated ${a.filesGenerated.length} files in ${a.duration.toFixed(2)}ms`),n.dim(`Output directory: ${a.outputDir}`),a.warnings.length>0)for(let c of a.warnings)ne(c);}else {h(`Generation failed with ${a.errors.length} errors`);for(let c of a.errors)n.dim(` ${c}`);process.exit(1);}}catch(o){h("Generation failed with unexpected error",o instanceof Error?o:new Error(String(o))),process.exit(1);}}};async function Ut(s){for(let e of X){let t=resolve(s,e);if(existsSync(t))return t}return null}var rt={command:"generate <packages..>",describe:"Generate TypeSchema files from FHIR packages",builder:{packages:{type:"string",array:true,demandOption:true,describe:"FHIR packages to process (e.g., hl7.fhir.r4.core@4.0.1)"},output:{alias:"o",type:"string",describe:"Output file or directory",default:"./schemas.ndjson"},format:{alias:"f",type:"string",choices:["ndjson","json"],default:"ndjson",describe:"Output format for TypeSchema files"},treeshake:{alias:"t",type:"string",array:true,describe:"Only generate TypeSchemas for specific ResourceTypes (treeshaking)"},singleFile:{alias:"s",type:"boolean",default:false,describe:"Generate single TypeSchema file instead of multiple files (NDJSON format)"},verbose:{alias:"v",type:"boolean",default:false,describe:"Enable verbose output"}},handler:async s=>{let e=b({verbose:s.verbose,prefix:"TypeSchema"});try{let t=await ee(process.cwd());e.step("Generating TypeSchema from FHIR packages"),e.info(`Packages: ${s.packages.join(", ")}`),e.info(`Output: ${s.output}`);let r=s.singleFile!==void 0?s.singleFile:t.typeSchema?.singleFile??!1,i=r?"ndjson":s.format;e.debug(`Format: ${i}${r&&s.format==="json"?" (forced from json due to singleFile)":""}`);let n=s.treeshake&&s.treeshake.length>0?s.treeshake:t.typeSchema?.treeshake;n&&n.length>0&&e.info(`Treeshaking enabled for ResourceTypes: ${n.join(", ")}`),r&&e.info("Single file output enabled (NDJSON format)");let o=Date.now(),a=new S({verbose:s.verbose,treeshake:n}),c=[];for(let f of s.packages){let[u,g]=f.includes("@")?f.split("@"):[f,void 0];e.progress(`Processing package: ${u}${g?`@${g}`:""}`);let O=await a.generateFromPackage(u,g);c.push(...O);}if(c.length===0)throw new Error("No schemas were generated from the specified packages");let l=s.output;await mkdir(dirname(l),{recursive:!0});let p;i==="json"?p=JSON.stringify(c,null,2):p=c.map(f=>JSON.stringify(f)).join(`
61
+ `),await writeFile(l,p,"utf-8");let d=Date.now()-o;if(ce(`Generated ${c.length} TypeSchema definitions`,d,{schemas:c.length}),e.dim(`Output: ${l}`),s.verbose){e.debug("Generated schemas:");let f=c.map(u=>`${u.identifier?.name||"Unknown"} (${u.identifier?.kind||"unknown"})`);C(f);}}catch(t){e.error("Failed to generate TypeSchema",t instanceof Error?t:new Error(String(t))),process.exit(1);}}};var it={command:"typeschema [subcommand]",describe:"TypeSchema operations - generate, validate and merge schemas",builder:s=>s.command(rt).help().example("$0 typeschema generate hl7.fhir.r4.core@4.0.1","Generate TypeSchema from FHIR R4 core package"),handler:s=>{if(!s.subcommand&&s._.length===1){V("Available typeschema subcommands:"),C(["generate Generate TypeSchema files from FHIR packages"]),console.log(`
141
62
  Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),console.log(`
142
- Examples:`),B0(["atomic-codegen typeschema generate hl7.fhir.r4.core@4.0.1 -o schemas.ndjson","atomic-codegen typeschema validate schemas.ndjson","atomic-codegen typeschema merge schema1.ndjson schema2.ndjson -o merged.ndjson"]);return}if(D.subcommand&&!["generate","validate","merge"].includes(D.subcommand))KD(`Unknown typeschema subcommand: ${D.subcommand}
143
- `),r0("Available typeschema subcommands:"),B0(["generate Generate TypeSchema files from FHIR packages","validate Validate TypeSchema files for correctness and consistency","merge Merge multiple TypeSchema files into a single file"]),console.log(`
144
- Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),process.exit(1)}};async function a8(D){B2({verbose:D.verbose||D.debug,timestamp:D.debug})}function e8(){return N3(yF(process.argv)).scriptName("atomic-codegen").usage("$0 <command> [options]").middleware(a8).command(j6).command(R6).option("verbose",{alias:"v",type:"boolean",description:"Enable verbose output",default:!1,global:!0}).option("debug",{alias:"d",type:"boolean",description:"Enable debug output with detailed logging",default:!1,global:!0}).option("config",{alias:"c",type:"string",description:"Path to configuration file (.atomic-codegen.json by default)",global:!0}).demandCommand(0).middleware((D)=>{if(D._.length===0)$2("Welcome to Atomic Codegen!"),console.log("Available commands:"),console.log(" typeschema Generate, validate and merge TypeSchema files"),console.log(" generate Generate code based on configuration file"),console.log(`
63
+ Examples:`),C(["atomic-codegen typeschema generate hl7.fhir.r4.core@4.0.1 -o schemas.ndjson","atomic-codegen typeschema validate schemas.ndjson","atomic-codegen typeschema merge schema1.ndjson schema2.ndjson -o merged.ndjson"]);return}s.subcommand&&!["generate","validate","merge"].includes(s.subcommand)&&(h(`Unknown typeschema subcommand: ${s.subcommand}
64
+ `),V("Available typeschema subcommands:"),C(["generate Generate TypeSchema files from FHIR packages","validate Validate TypeSchema files for correctness and consistency","merge Merge multiple TypeSchema files into a single file"]),console.log(`
65
+ Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),process.exit(1));}};async function Wt(s){oe({verbose:s.verbose||s.debug,timestamp:s.debug});}function Zt(){return Jt(hideBin(process.argv)).scriptName("atomic-codegen").usage("$0 <command> [options]").middleware(Wt).command(it).command(tt).option("verbose",{alias:"v",type:"boolean",description:"Enable verbose output",default:false,global:true}).option("debug",{alias:"d",type:"boolean",description:"Enable debug output with detailed logging",default:false,global:true}).option("config",{alias:"c",type:"string",description:"Path to configuration file (.atomic-codegen.json by default)",global:true}).demandCommand(0).middleware(s=>{s._.length===0&&(ae("Welcome to Atomic Codegen!"),console.log("Available commands:"),console.log(" typeschema Generate, validate and merge TypeSchema files"),console.log(" generate Generate code based on configuration file"),console.log(`
145
66
  Use 'atomic-codegen <command> --help' for more information about a command.`),console.log(`
146
67
  Quick examples:`),console.log(" atomic-codegen typeschema generate hl7.fhir.r4.core@4.0.1 -o schemas.ndjson"),console.log(" atomic-codegen generate # Uses atomic-codegen.config.ts"),console.log(`
147
- Use 'atomic-codegen --help' to see all options.`),process.exit(0)}).help().version("0.1.0").example("$0 generate","Generate code using atomic-codegen.config.ts").example("$0 generate --verbose","Generate with detailed progress output").example("$0 --config custom-config.ts generate","Use custom configuration file").example("$0 typeschema generate hl7.fhir.r4.core@4.0.1 -o schemas.ndjson","Generate TypeSchemas from FHIR package").fail((D,F,u)=>{if(F)KD(F.message,F);else KD(D);KD(`
148
- Use --help for usage information`),process.exit(1)}).wrap(Math.min(120,process.stdout.columns||80))}async function I6(){await e8().parseAsync()}if(jF.main==jF.module)I6().catch((D)=>{console.error("CLI Error:",D instanceof Error?D.message:D),process.exit(1)});
68
+ Use 'atomic-codegen --help' to see all options.`),process.exit(0));}).help().version("0.1.0").example("$0 generate","Generate code using atomic-codegen.config.ts").example("$0 generate --verbose","Generate with detailed progress output").example("$0 --config custom-config.ts generate","Use custom configuration file").example("$0 typeschema generate hl7.fhir.r4.core@4.0.1 -o schemas.ndjson","Generate TypeSchemas from FHIR package").fail((s,e,t)=>{e?h(e.message,e):h(s),h(`
69
+ Use --help for usage information`),process.exit(1);}).wrap(Math.min(120,process.stdout.columns||80))}async function Ee(){await Zt().parseAsync();}import.meta.main&&Ee().catch(s=>{s("Unexpected error:",s),process.exit(1);});Ee().catch(s=>{console.error("CLI Error:",s instanceof Error?s.message:s),process.exit(1);});