@atomic-ehr/codegen 0.0.1-canary.20250925150012.6169b6d → 0.0.1-canary.20250929141928.699688c
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as Tu}from"node:module";var Iu=Object.create;var{getPrototypeOf:Lu,defineProperty:q0,getOwnPropertyNames:a2,getOwnPropertyDescriptor:Nu}=Object,e2=Object.prototype.hasOwnProperty;var b0=(D,F,u)=>{u=D!=null?Iu(Lu(D)):{};let B=F||!D||!D.__esModule?q0(u,"default",{value:D,enumerable:!0}):u;for(let E of a2(D))if(!e2.call(B,E))q0(B,E,{get:()=>D[E],enumerable:!0});return B},r2=new WeakMap,qF=(D)=>{var F=r2.get(D),u;if(F)return F;if(F=q0({},"__esModule",{value:!0}),D&&typeof D==="object"||typeof D==="function")a2(D).map((B)=>!e2.call(F,B)&&q0(F,B,{get:()=>D[B],enumerable:!(u=Nu(D,B))||u.enumerable}));return r2.set(D,F),F},MF=(D,F)=>()=>(F||D((F={exports:{}}).exports,F),F.exports);var _F=(D,F)=>{for(var u in F)q0(D,u,{get:F[u],enumerable:!0,configurable:!0,set:(B)=>F[u]=()=>B})};var D1=(D,F)=>()=>(D&&(F=D(D=0)),F);var VF=Tu(import.meta.url);var Q1=MF((ZB,Z1)=>{Z1.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 v1=MF((sB,S1)=>{S1.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,C){return C};var B=Error().stack;if(Error.prepareStackTrace=u,B!==null&&typeof B==="object")return B[F]?B[F].getFileName():void 0}});var aF=MF((HC,rF)=>{var i0=process||{},U3=i0.argv||[],n0=i0.env||{},y6=!(!!n0.NO_COLOR||U3.includes("--no-color"))&&(!!n0.FORCE_COLOR||U3.includes("--color")||i0.platform==="win32"||(i0.stdout||{}).isTTY&&n0.TERM!=="dumb"||!!n0.CI),d6=(D,F,u=D)=>(B)=>{let E=""+B,C=E.indexOf(F,D.length);return~C?D+h6(E,F,u,C)+F:D+E+F},h6=(D,F,u,B)=>{let E="",C=0;do E+=D.substring(C,B)+u,C=B+F.length,B=D.indexOf(F,C);while(~B);return E+D.substring(C)},j3=(D=y6)=>{let F=D?d6:()=>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")}};rF.exports=j3();rF.exports.createColors=j3});var ID,f2,YF,X0,k2,y2;var w0=D1(()=>{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`]}};f2=class f2 extends ID{schema;validationErrors;userContext;constructor(D,F,u,B){super(D,"validation",{schemaName:F.identifier?.name||"unknown",schemaKind:F.identifier?.kind||"unknown",schemaPackage:F.identifier?.package||"unknown",validationErrors:u,userContext:B});this.schema=F;this.validationErrors=u;this.userContext=B}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"))}};
|
|
2
|
+
import{createRequire as Tu}from"node:module";var Iu=Object.create;var{getPrototypeOf:Lu,defineProperty:M0,getOwnPropertyNames:a2,getOwnPropertyDescriptor:Nu}=Object,e2=Object.prototype.hasOwnProperty;var b0=(D,F,u)=>{u=D!=null?Iu(Lu(D)):{};let B=F||!D||!D.__esModule?M0(u,"default",{value:D,enumerable:!0}):u;for(let E of a2(D))if(!e2.call(B,E))M0(B,E,{get:()=>D[E],enumerable:!0});return B},r2=new WeakMap,VF=(D)=>{var F=r2.get(D),u;if(F)return F;if(F=M0({},"__esModule",{value:!0}),D&&typeof D==="object"||typeof D==="function")a2(D).map((B)=>!e2.call(F,B)&&M0(F,B,{get:()=>D[B],enumerable:!(u=Nu(D,B))||u.enumerable}));return r2.set(D,F),F},KF=(D,F)=>()=>(F||D((F={exports:{}}).exports,F),F.exports);var RF=(D,F)=>{for(var u in F)M0(D,u,{get:F[u],enumerable:!0,configurable:!0,set:(B)=>F[u]=()=>B})};var D1=(D,F)=>()=>(D&&(F=D(D=0)),F);var UF=Tu(import.meta.url);var Q1=KF((ZB,Z1)=>{Z1.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 v1=KF((sB,S1)=>{S1.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,C){return C};var B=Error().stack;if(Error.prepareStackTrace=u,B!==null&&typeof B==="object")return B[F]?B[F].getFileName():void 0}});var F2=KF((HC,D2)=>{var i0=process||{},U3=i0.argv||[],n0=i0.env||{},y6=!(!!n0.NO_COLOR||U3.includes("--no-color"))&&(!!n0.FORCE_COLOR||U3.includes("--color")||i0.platform==="win32"||(i0.stdout||{}).isTTY&&n0.TERM!=="dumb"||!!n0.CI),d6=(D,F,u=D)=>(B)=>{let E=""+B,C=E.indexOf(F,D.length);return~C?D+h6(E,F,u,C)+F:D+E+F},h6=(D,F,u,B)=>{let E="",C=0;do E+=D.substring(C,B)+u,C=B+F.length,B=D.indexOf(F,C);while(~B);return E+D.substring(C)},j3=(D=y6)=>{let F=D?d6:()=>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")}};D2.exports=j3();D2.exports.createColors=j3});var ID,f2,GF,X0,k2,y2;var w0=D1(()=>{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`]}};f2=class f2 extends ID{schema;validationErrors;userContext;constructor(D,F,u,B){super(D,"validation",{schemaName:F.identifier?.name||"unknown",schemaKind:F.identifier?.kind||"unknown",schemaPackage:F.identifier?.package||"unknown",validationErrors:u,userContext:B});this.schema=F;this.validationErrors=u;this.userContext=B}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,B){super(D,"generation",{templateName:F,contextKeys:Object.keys(u),availableTemplates:B?.availableTemplates?.length||0,debugInfo:B});this.templateName=F;this.templateContext=u;this.debugInfo=B}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 B=F.filter((E)=>this.levenshteinDistance(u.toLowerCase(),E.toLowerCase())<=2);if(B.length>0)D.push(` Similar to: ${B.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
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 B=this.levenshteinDistance(D.toLowerCase(),u.toLowerCase());return B<=2&&B>0}).slice(0,3).sort((u,B)=>this.levenshteinDistance(D.toLowerCase(),u.toLowerCase())-this.levenshteinDistance(D.toLowerCase(),B.toLowerCase()))}levenshteinDistance(D,F){let u=Array(F.length+1).fill(null).map(()=>Array(D.length+1).fill(0));for(let B=0;B<=D.length;B++)u[0][B]=B;for(let B=0;B<=F.length;B++)u[B][0]=B;for(let B=1;B<=F.length;B++)for(let E=1;E<=D.length;E++){let C=D[E-1]===F[B-1]?0:1;u[B][E]=Math.min(u[B]?.[E-1]+1,u[B-1]?.[E]+1,u[B-1]?.[E-1]+C)}return u[F.length]?.[D.length]}isRecoverable(){return!0}};X0=class X0 extends ID{operation;filePath;originalError;recoveryOptions;constructor(D,F,u,B,E){super(D,"writing",{operation:F,filePath:u,originalErrorMessage:B?.message,originalErrorCode:B?.code,recoveryOptions:E});this.operation=F;this.filePath=u;this.originalError=B;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}};k2=class k2 extends ID{configKey;providedValue;expectedValue;validOptions;constructor(D,F,u,B,E){super(D,"initialization",{configKey:F,providedValue:u,providedType:typeof u,expectedValue:B,validOptions:E});this.configKey=F;this.providedValue=u;this.expectedValue=B;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}};y2=class y2 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((C)=>C.getSuggestions()),F=[...new Set(D)],u=[];u.push(`\uD83D\uDCCA Batch operation failed with ${this.errors.length} errors:`);let B=new Map;this.errors.forEach((C)=>{let $=C.constructor.name;if(!B.has($))B.set($,[]);B.get($)?.push(C)}),u.push(""),u.push("\uD83D\uDD0D Error breakdown:");for(let[C,$]of B)u.push(` • ${C}: ${$.length} occurrences`);u.push("\uD83D\uDCA1 Most relevant suggestions:");let E=F.slice(0,8).map((C)=>` ${C}`);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 Yu={};
|
|
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 Yu={};RF(Yu,{FileBuilder:()=>Ou});class Ou{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 B of this.beforeSaveHooks)await B(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 B of this.afterSaveHooks)await B(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(B){this.config.logger.warn(`Error hook failed: ${B instanceof Error?B.message:String(B)}`)}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
6
|
`);if(this.options.prettify)F=this.prettifyContent(F);return F}generateImportStatements(){let D=[],F=new Map;for(let[u,B]of this.imports){let E=this.options.importStrategy==="auto"?this.config.fileManager.getRelativeImportPath(this.config.filename,B):B;if(!F.has(E))F.set(E,[]);F.get(E)?.push(u)}for(let[u,B]of F)if(B.length===1)D.push(`import type { ${B[0]} } from '${u}';`);else{let E=B.sort();if(E.length<=3)D.push(`import type { ${E.join(", ")} } from '${u}';`);else{D.push("import type {");let C="\t";E.forEach(($,X)=>{let Q=X===E.length-1;D.push(`${C}${$}${Q?"":","}`)}),D.push(`} from '${u}';`)}}return D.join(`
|
|
7
7
|
`)}generateExportStatements(){return Array.from(this.exports).sort().map((F)=>`export { ${F} };`).join(`
|
|
8
8
|
`)}prettifyContent(D){return D.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,B=(D.match(/\}/g)||[]).length;if(u!==B)F.push(`Unmatched braces: ${u} open, ${B} close`);let E=(D.match(/\(/g)||[]).length,C=(D.match(/\)/g)||[]).length;if(E!==C)F.push(`Unmatched parentheses: ${E} open, ${C} 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 X0(`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 Ju=D1(()=>{w0()});var Wu={};
|
|
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,B=(D.match(/\}/g)||[]).length;if(u!==B)F.push(`Unmatched braces: ${u} open, ${B} close`);let E=(D.match(/\(/g)||[]).length,C=(D.match(/\)/g)||[]).length;if(E!==C)F.push(`Unmatched parentheses: ${E} open, ${C} 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 X0(`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 Ju=D1(()=>{w0()});var Wu={};RF(Wu,{DirectoryBuilder:()=>l2});class l2{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 l2({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,B])=>{try{let E=await B.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,B]of this.subdirectories)try{let E=await B.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 B=u.getFileList();D.push(...B)}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 Au={};RF(Au,{IndexBuilder:()=>Gu});class Gu{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[B,E]of u)D.push(`export * as ${B} from './${E}';`);D.push("")}if(this.footer)D.push(this.footer);return`${D.join(`
|
|
11
11
|
`).replace(/\n{3,}/g,`
|
|
12
12
|
|
|
13
13
|
`).trim()}
|
|
@@ -15,18 +15,18 @@ import{createRequire as Tu}from"node:module";var Iu=Object.create;var{getPrototy
|
|
|
15
15
|
`).map((B)=>B.split("\t")),u=0;return F.forEach((B)=>{if(B.length>1&&WD.stringWidth(B[0])>u)u=Math.min(Math.floor(this.width*0.5),WD.stringWidth(B[0]))}),F.forEach((B)=>{this.div(...B.map((E,C)=>{return{text:E.trim(),padding:this.measurePadding(E),width:C===0&&B.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
16
|
`)}rowToString(D,F){return this.rasterize(D).forEach((u,B)=>{let E="";u.forEach((C,$)=>{let{width:X}=D[$],Q=this.negatePadding(D[$]),z=C;if(Q>WD.stringWidth(C))z+=" ".repeat(Q-WD.stringWidth(C));if(D[$].align&&D[$].align!=="left"&&this.wrap){let W=wu[D[$].align];if(z=W(z,Q),WD.stringWidth(z)<Q)z+=" ".repeat((X||0)-WD.stringWidth(z)-1)}let Y=D[$].padding||[0,0,0,0];if(Y[3])E+=" ".repeat(Y[3]);if(E+=F1(D[$],z,"| "),E+=z,E+=F1(D[$],z," |"),Y[1])E+=" ".repeat(Y[1]);if(B===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(/^ */),B=u?u[0].length:0,E=F.text,C=WD.stringWidth(E.trimRight());if(!F.span)return D;if(!this.wrap)return F.hidden=!0,E+D;if(B<C)return D;return F.hidden=!0,E.trimRight()+" ".repeat(B-C)+D.trimLeft()}rasterize(D){let F=[],u=this.columnWidths(D),B;return D.forEach((E,C)=>{if(E.width=u[C],this.wrap)B=WD.wrap(E.text,this.negatePadding(E),{hard:!0}).split(`
|
|
17
17
|
`);else B=E.text.split(`
|
|
18
|
-
`);if(E.border)B.unshift("."+"-".repeat(this.negatePadding(E)+2)+"."),B.push("'"+"-".repeat(this.negatePadding(E)+2)+"'");if(E.padding)B.unshift(...Array(E.padding[0]||0).fill("")),B.push(...Array(E.padding[2]||0).fill(""));B.forEach(($,X)=>{if(!F[X])F.push([]);let Q=F[X];for(let z=0;z<C;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((C)=>{return C.width||WD.stringWidth(C.text)});let F=D.length,u=this.width,B=D.map((C)=>{if(C.width)return F--,u-=C.width,C.width;return}),E=F?Math.floor(u/F):0;return B.map((C,$)=>{if(C===void 0)return Math.max(E,bu(D[$]));return C})}}function F1(D,F,u){if(D.border){if(/[.']-+[.']/.test(F))return"";if(F.trim().length!==0)return u;return" "}return""}function bu(D){let F=D.padding||[],u=1+(F[3]||0)+(F[1]||0);if(D.border)return u+4;return u}function xu(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function Pu(D,F){D=D.trim();let u=WD.stringWidth(D);if(u<F)return" ".repeat(F-u)+D;return D}function Su(D,F){D=D.trim();let u=WD.stringWidth(D);if(u>=F)return D;return" ".repeat(F-u>>1)+D}var WD;function B1(D,F){return WD=F,new u1({width:(D===null||D===void 0?void 0:D.width)||xu(),wrap:D===null||D===void 0?void 0:D.wrap})}function KF({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 vu=KF();function mD(D){if(typeof D!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof D}\``);return D.replace(vu,"")}function E1(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 C1(D){return D===12288||D>=65281&&D<=65376||D>=65504&&D<=65510}function $1(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 fu(D){if(!Number.isSafeInteger(D))throw TypeError(`Expected a code point, got \`${typeof D}\`.`)}function X1(D,{ambiguousAsWide:F=!1}={}){if(fu(D),C1(D)||$1(D)||F&&E1(D))return 2;return 1}var z1=b0(Q1(),1),ku=new Intl.Segmenter,yu=/^\p{Default_Ignorable_Code_Point}$/u;function RD(D,F={}){if(typeof D!=="string"||D.length===0)return 0;let{ambiguousIsNarrow:u=!0,countAnsiEscapeCodes:B=!1}=F;if(!B)D=mD(D);if(D.length===0)return 0;let E=0,C={ambiguousAsWide:!u};for(let{segment:$}of ku.segment(D)){let X=$.codePointAt(0);if(X<=31||X>=127&&X<=159)continue;if(X>=8203&&X<=8207||X===65279)continue;if(X>=768&&X<=879||X>=6832&&X<=6911||X>=7616&&X<=7679||X>=8400&&X<=8447||X>=65056&&X<=65071)continue;if(X>=55296&&X<=57343)continue;if(X>=65024&&X<=65039)continue;if(yu.test($))continue;if(z1.default().test($)){E+=2;continue}E+=X1(X,C)}return E}var O1=(D=0)=>(F)=>`\x1B[${F+D}m`,Y1=(D=0)=>(F)=>`\x1B[${38+D};5;${F}m`,J1=(D=0)=>(F,u,B)=>`\x1B[${38+D};2;${F};${u};${B}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]}},YB=Object.keys(r.modifier),du=Object.keys(r.color),hu=Object.keys(r.bgColor),JB=[...du,...hu];function pu(){let D=new Map;for(let[F,u]of Object.entries(r)){for(let[B,E]of Object.entries(u))r[B]={open:`\x1B[${E[0]}m`,close:`\x1B[${E[1]}m`},u[B]=r[B],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=O1(),r.color.ansi256=Y1(),r.color.ansi16m=J1(),r.bgColor.ansi=O1(10),r.bgColor.ansi256=Y1(10),r.bgColor.ansi16m=J1(10),Object.defineProperties(r,{rgbToAnsi256:{value:(F,u,B)=>{if(F===u&&u===B){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(B/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[B]=u;if(B.length===3)B=[...B].map((C)=>C+C).join("");let E=Number.parseInt(B,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,B,E;if(F>=232)u=((F-232)*10+8)/255,B=u,E=u;else{F-=16;let X=F%36;u=Math.floor(F/36)/5,B=Math.floor(X/6)/5,E=X%6/5}let C=Math.max(u,B,E)*2;if(C===0)return 30;let $=30+(Math.round(E)<<2|Math.round(B)<<1|Math.round(u));if(C===2)$+=60;return $},enumerable:!1},rgbToAnsi:{value:(F,u,B)=>r.ansi256ToAnsi(r.rgbToAnsi256(F,u,B)),enumerable:!1},hexToAnsi:{value:(F)=>r.ansi256ToAnsi(r.hexToAnsi256(F)),enumerable:!1}}),r}var gu=pu(),W1=gu;var P0=new Set(["\x1B",""]),mu=39,UF="\x07",H1="[",cu="]",q1="m",x0=`${cu}8;;`,A1=(D)=>`${P0.values().next().value}${H1}${D}${q1}`,G1=(D)=>`${P0.values().next().value}${x0}${D}${UF}`,lu=(D)=>D.split(" ").map((F)=>RD(F)),RF=(D,F,u)=>{let B=[...F],E=!1,C=!1,$=RD(mD(D.at(-1)));for(let[X,Q]of B.entries()){let z=RD(Q);if($+z<=u)D[D.length-1]+=Q;else D.push(Q),$=0;if(P0.has(Q))E=!0,C=B.slice(X+1,X+1+x0.length).join("")===x0;if(E){if(C){if(Q===UF)E=!1,C=!1}else if(Q===q1)E=!1;continue}if($+=z,$===u&&X<B.length-1)D.push(""),$=0}if(!$&&D.at(-1).length>0&&D.length>1)D[D.length-2]+=D.pop()},ou=(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("")},nu=(D,F,u={})=>{if(u.trim!==!1&&D.trim()==="")return"";let B="",E,C,$=lu(D),X=[""];for(let[W,J]of D.split(" ").entries()){if(u.trim!==!1)X[X.length-1]=X.at(-1).trimStart();let q=RD(X.at(-1));if(W!==0){if(q>=F&&(u.wordWrap===!1||u.trim===!1))X.push(""),q=0;if(q>0||u.trim===!1)X[X.length-1]+=" ",q++}if(u.hard&&$[W]>F){let _=F-q,H=1+Math.floor(($[W]-_-1)/F);if(Math.floor(($[W]-1)/F)<H)X.push("");RF(X,J,F);continue}if(q+$[W]>F&&q>0&&$[W]>0){if(u.wordWrap===!1&&q<F){RF(X,J,F);continue}X.push("")}if(q+$[W]>F&&u.wordWrap===!1){RF(X,J,F);continue}X[X.length-1]+=J}if(u.trim!==!1)X=X.map((W)=>ou(W));let Q=X.join(`
|
|
19
|
-
`),z=[...Q],Y=0;for(let[W,J]of z.entries()){if(B+=J,P0.has(J)){let{groups:
|
|
20
|
-
`){if(C)B+=
|
|
21
|
-
`){if(E&&
|
|
18
|
+
`);if(E.border)B.unshift("."+"-".repeat(this.negatePadding(E)+2)+"."),B.push("'"+"-".repeat(this.negatePadding(E)+2)+"'");if(E.padding)B.unshift(...Array(E.padding[0]||0).fill("")),B.push(...Array(E.padding[2]||0).fill(""));B.forEach(($,X)=>{if(!F[X])F.push([]);let Q=F[X];for(let z=0;z<C;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((C)=>{return C.width||WD.stringWidth(C.text)});let F=D.length,u=this.width,B=D.map((C)=>{if(C.width)return F--,u-=C.width,C.width;return}),E=F?Math.floor(u/F):0;return B.map((C,$)=>{if(C===void 0)return Math.max(E,bu(D[$]));return C})}}function F1(D,F,u){if(D.border){if(/[.']-+[.']/.test(F))return"";if(F.trim().length!==0)return u;return" "}return""}function bu(D){let F=D.padding||[],u=1+(F[3]||0)+(F[1]||0);if(D.border)return u+4;return u}function xu(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function Pu(D,F){D=D.trim();let u=WD.stringWidth(D);if(u<F)return" ".repeat(F-u)+D;return D}function Su(D,F){D=D.trim();let u=WD.stringWidth(D);if(u>=F)return D;return" ".repeat(F-u>>1)+D}var WD;function B1(D,F){return WD=F,new u1({width:(D===null||D===void 0?void 0:D.width)||xu(),wrap:D===null||D===void 0?void 0:D.wrap})}function jF({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 vu=jF();function gD(D){if(typeof D!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof D}\``);return D.replace(vu,"")}function E1(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 C1(D){return D===12288||D>=65281&&D<=65376||D>=65504&&D<=65510}function $1(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 fu(D){if(!Number.isSafeInteger(D))throw TypeError(`Expected a code point, got \`${typeof D}\`.`)}function X1(D,{ambiguousAsWide:F=!1}={}){if(fu(D),C1(D)||$1(D)||F&&E1(D))return 2;return 1}var z1=b0(Q1(),1),ku=new Intl.Segmenter,yu=/^\p{Default_Ignorable_Code_Point}$/u;function RD(D,F={}){if(typeof D!=="string"||D.length===0)return 0;let{ambiguousIsNarrow:u=!0,countAnsiEscapeCodes:B=!1}=F;if(!B)D=gD(D);if(D.length===0)return 0;let E=0,C={ambiguousAsWide:!u};for(let{segment:$}of ku.segment(D)){let X=$.codePointAt(0);if(X<=31||X>=127&&X<=159)continue;if(X>=8203&&X<=8207||X===65279)continue;if(X>=768&&X<=879||X>=6832&&X<=6911||X>=7616&&X<=7679||X>=8400&&X<=8447||X>=65056&&X<=65071)continue;if(X>=55296&&X<=57343)continue;if(X>=65024&&X<=65039)continue;if(yu.test($))continue;if(z1.default().test($)){E+=2;continue}E+=X1(X,C)}return E}var O1=(D=0)=>(F)=>`\x1B[${F+D}m`,Y1=(D=0)=>(F)=>`\x1B[${38+D};5;${F}m`,J1=(D=0)=>(F,u,B)=>`\x1B[${38+D};2;${F};${u};${B}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]}},YB=Object.keys(r.modifier),du=Object.keys(r.color),hu=Object.keys(r.bgColor),JB=[...du,...hu];function pu(){let D=new Map;for(let[F,u]of Object.entries(r)){for(let[B,E]of Object.entries(u))r[B]={open:`\x1B[${E[0]}m`,close:`\x1B[${E[1]}m`},u[B]=r[B],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=O1(),r.color.ansi256=Y1(),r.color.ansi16m=J1(),r.bgColor.ansi=O1(10),r.bgColor.ansi256=Y1(10),r.bgColor.ansi16m=J1(10),Object.defineProperties(r,{rgbToAnsi256:{value:(F,u,B)=>{if(F===u&&u===B){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(B/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[B]=u;if(B.length===3)B=[...B].map((C)=>C+C).join("");let E=Number.parseInt(B,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,B,E;if(F>=232)u=((F-232)*10+8)/255,B=u,E=u;else{F-=16;let X=F%36;u=Math.floor(F/36)/5,B=Math.floor(X/6)/5,E=X%6/5}let C=Math.max(u,B,E)*2;if(C===0)return 30;let $=30+(Math.round(E)<<2|Math.round(B)<<1|Math.round(u));if(C===2)$+=60;return $},enumerable:!1},rgbToAnsi:{value:(F,u,B)=>r.ansi256ToAnsi(r.rgbToAnsi256(F,u,B)),enumerable:!1},hexToAnsi:{value:(F)=>r.ansi256ToAnsi(r.hexToAnsi256(F)),enumerable:!1}}),r}var gu=pu(),W1=gu;var P0=new Set(["\x1B",""]),mu=39,LF="\x07",H1="[",cu="]",M1="m",x0=`${cu}8;;`,G1=(D)=>`${P0.values().next().value}${H1}${D}${M1}`,A1=(D)=>`${P0.values().next().value}${x0}${D}${LF}`,lu=(D)=>D.split(" ").map((F)=>RD(F)),IF=(D,F,u)=>{let B=[...F],E=!1,C=!1,$=RD(gD(D.at(-1)));for(let[X,Q]of B.entries()){let z=RD(Q);if($+z<=u)D[D.length-1]+=Q;else D.push(Q),$=0;if(P0.has(Q))E=!0,C=B.slice(X+1,X+1+x0.length).join("")===x0;if(E){if(C){if(Q===LF)E=!1,C=!1}else if(Q===M1)E=!1;continue}if($+=z,$===u&&X<B.length-1)D.push(""),$=0}if(!$&&D.at(-1).length>0&&D.length>1)D[D.length-2]+=D.pop()},ou=(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("")},nu=(D,F,u={})=>{if(u.trim!==!1&&D.trim()==="")return"";let B="",E,C,$=lu(D),X=[""];for(let[W,J]of D.split(" ").entries()){if(u.trim!==!1)X[X.length-1]=X.at(-1).trimStart();let M=RD(X.at(-1));if(W!==0){if(M>=F&&(u.wordWrap===!1||u.trim===!1))X.push(""),M=0;if(M>0||u.trim===!1)X[X.length-1]+=" ",M++}if(u.hard&&$[W]>F){let q=F-M,H=1+Math.floor(($[W]-q-1)/F);if(Math.floor(($[W]-1)/F)<H)X.push("");IF(X,J,F);continue}if(M+$[W]>F&&M>0&&$[W]>0){if(u.wordWrap===!1&&M<F){IF(X,J,F);continue}X.push("")}if(M+$[W]>F&&u.wordWrap===!1){IF(X,J,F);continue}X[X.length-1]+=J}if(u.trim!==!1)X=X.map((W)=>ou(W));let Q=X.join(`
|
|
19
|
+
`),z=[...Q],Y=0;for(let[W,J]of z.entries()){if(B+=J,P0.has(J)){let{groups:q}=new RegExp(`(?:\\${H1}(?<code>\\d+)m|\\${x0}(?<uri>.*)${LF})`).exec(Q.slice(Y))||{groups:{}};if(q.code!==void 0){let H=Number.parseFloat(q.code);E=H===mu?void 0:H}else if(q.uri!==void 0)C=q.uri.length===0?void 0:q.uri}let M=W1.codes.get(Number(E));if(z[W+1]===`
|
|
20
|
+
`){if(C)B+=A1("");if(E&&M)B+=G1(M)}else if(J===`
|
|
21
|
+
`){if(E&&M)B+=G1(E);if(C)B+=A1(C)}Y+=J.length}return B};function NF(D,F,u){return String(D).normalize().replaceAll(`\r
|
|
22
22
|
`,`
|
|
23
23
|
`).split(`
|
|
24
24
|
`).map((B)=>nu(B,F,u)).join(`
|
|
25
|
-
`)}function IF(D){return B1(D,{stringWidth:RD,stripAnsi:mD,wrap:jF})}import{dirname as M1,resolve as _1}from"path";import{readdirSync as iu,statSync as tu}from"fs";function LF(D,F){let u=_1(".",D),B;if(!tu(u).isDirectory())u=M1(u);while(!0){if(B=F(u,iu(u)),B)return _1(u,B);if(u=M1(B=u),B===u)break}}import{inspect as J6}from"util";import{fileURLToPath as k1}from"url";import{format as au}from"util";import{normalize as eu,resolve as D6}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="",B=!1,E=D.match(/^-+/);for(let C=E?E[0].length:0;C<D.length;C++){let $=D.charAt(C);if(B)B=!1,$=$.toUpperCase();if(C!==0&&($==="-"||$==="_"))B=!0;else if($!=="-"&&$!=="_")u+=$}return u}}function S0(D,F){let u=D.toLowerCase();F=F||"-";let B="";for(let E=0;E<D.length;E++){let C=u.charAt(E),$=D.charAt(E);if(C!==$&&E>0)B+=`${F}${u.charAt(E)}`;else B+=$}return B}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 V1(D){if(Array.isArray(D))return D.map(($)=>typeof $!=="string"?$+"":$);D=D.trim();let F=0,u=null,B=null,E=null,C=[];for(let $=0;$<D.length;$++){if(u=B,B=D.charAt($),B===" "&&!E){if(u!==" ")F++;continue}if(B===E)E=null;else if((B==="'"||B==='"')&&!E)E=B;if(!C[F])C[F]="";C[F]+=B}return C}var qD;(function(D){D.BOOLEAN="boolean",D.STRING="string",D.NUMBER="number",D.ARRAY="array"})(qD||(qD={}));var bD;class TF{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),B=V1(D),E=typeof D==="string",C=su(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),X=Object.assign(Object.create(null),u.default),Q=u.configObjects||[],z=u.envPrefix,Y=$["populate--"],W=Y?"--":"_",J=Object.create(null),q=Object.create(null),_=u.__||bD.format,H={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]+)$/,m=new RegExp("^--"+$["negation-prefix"]+"(.+)");if([].concat(u.array||[]).filter(Boolean).forEach(function(O){let G=typeof O==="object"?O.key:O,V=Object.keys(O).map(function(M){return{boolean:"bools",string:"strings",number:"numbers"}[M]}).filter(Boolean).pop();if(V)H[V][G]=!0;H.arrays[G]=!0,H.keys.push(G)}),[].concat(u.boolean||[]).filter(Boolean).forEach(function(O){H.bools[O]=!0,H.keys.push(O)}),[].concat(u.string||[]).filter(Boolean).forEach(function(O){H.strings[O]=!0,H.keys.push(O)}),[].concat(u.number||[]).filter(Boolean).forEach(function(O){H.numbers[O]=!0,H.keys.push(O)}),[].concat(u.count||[]).filter(Boolean).forEach(function(O){H.counts[O]=!0,H.keys.push(O)}),[].concat(u.normalize||[]).filter(Boolean).forEach(function(O){H.normalize[O]=!0,H.keys.push(O)}),typeof u.narg==="object")Object.entries(u.narg).forEach(([O,G])=>{if(typeof G==="number")H.nargs[O]=G,H.keys.push(O)});if(typeof u.coerce==="object")Object.entries(u.coerce).forEach(([O,G])=>{if(typeof G==="function")H.coercions[O]=G,H.keys.push(O)});if(typeof u.config<"u"){if(Array.isArray(u.config)||typeof u.config==="string")[].concat(u.config).filter(Boolean).forEach(function(O){H.configs[O]=!0});else if(typeof u.config==="object")Object.entries(u.config).forEach(([O,G])=>{if(typeof G==="boolean"||typeof G==="function")H.configs[O]=G})}H0(u.key,C,u.default,H.arrays),Object.keys(X).forEach(function(O){(H.aliases[O]||[]).forEach(function(G){X[G]=X[O]})});let p=null;HF();let QD=[],K=Object.assign(Object.create(null),{_:[]}),j={};for(let O=0;O<B.length;O++){let G=B[O],V=G.replace(/^-{3,}/,"---"),M,A,T,U,x,XD;if(G!=="--"&&/^-/.test(G)&&n(G))f(G);else if(V.match(/^---+(=|$)/)){f(G);continue}else if(G.match(/^--.+=/)||!$["short-option-groups"]&&G.match(/^-.+=/)){if(U=G.match(/^--?([^=]+)=([\s\S]*)$/),U!==null&&Array.isArray(U)&&U.length>=3)if(S(U[1],H.arrays))O=t(O,U[1],B,U[2]);else if(S(U[1],H.nargs)!==!1)O=d(O,U[1],B,U[2]);else c(U[1],U[2],!0)}else if(G.match(m)&&$["boolean-negation"]){if(U=G.match(m),U!==null&&Array.isArray(U)&&U.length>=2)A=U[1],c(A,S(A,H.arrays)?[!1]:!1)}else if(G.match(/^--.+/)||!$["short-option-groups"]&&G.match(/^-[^-]+/)){if(U=G.match(/^--?(.+)/),U!==null&&Array.isArray(U)&&U.length>=2)if(A=U[1],S(A,H.arrays))O=t(O,A,B);else if(S(A,H.nargs)!==!1)O=d(O,A,B);else if(x=B[O+1],x!==void 0&&(!x.match(/^-/)||x.match(P))&&!S(A,H.bools)&&!S(A,H.counts))c(A,x),O++;else if(/^(true|false)$/.test(x))c(A,x),O++;else c(A,g(A))}else if(G.match(/^-.\..+=/)){if(U=G.match(/^-([^=]+)=([\s\S]*)$/),U!==null&&Array.isArray(U)&&U.length>=3)c(U[1],U[2])}else if(G.match(/^-.\..+/)&&!G.match(P)){if(x=B[O+1],U=G.match(/^-(.\..+)/),U!==null&&Array.isArray(U)&&U.length>=2)if(A=U[1],x!==void 0&&!x.match(/^-/)&&!S(A,H.bools)&&!S(A,H.counts))c(A,x),O++;else c(A,g(A))}else if(G.match(/^-[^-]+/)&&!G.match(P)){T=G.slice(1,-1).split(""),M=!1;for(let OD=0;OD<T.length;OD++){if(x=G.slice(OD+2),T[OD+1]&&T[OD+1]==="="){if(XD=G.slice(OD+3),A=T[OD],S(A,H.arrays))O=t(O,A,B,XD);else if(S(A,H.nargs)!==!1)O=d(O,A,B,XD);else c(A,XD);M=!0;break}if(x==="-"){c(T[OD],x);continue}if(/[A-Za-z]/.test(T[OD])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(x)&&S(x,H.bools)===!1){c(T[OD],x),M=!0;break}if(T[OD+1]&&T[OD+1].match(/\W/)){c(T[OD],x),M=!0;break}else c(T[OD],g(T[OD]))}if(A=G.slice(-1)[0],!M&&A!=="-")if(S(A,H.arrays))O=t(O,A,B);else if(S(A,H.nargs)!==!1)O=d(O,A,B);else if(x=B[O+1],x!==void 0&&(!/^(-|--)[^-]/.test(x)||x.match(P))&&!S(A,H.bools)&&!S(A,H.counts))c(A,x),O++;else if(/^(true|false)$/.test(x))c(A,x),O++;else c(A,g(A))}else if(G.match(/^-[0-9]$/)&&G.match(P)&&S(G.slice(1),H.bools))A=G.slice(1),c(A,g(A));else if(G==="--"){QD=B.slice(O+1);break}else if($["halt-at-non-option"]){QD=B.slice(O);break}else f(G)}if(uD(K,!0),uD(K,!1),w(K),o(),xD(K,H.aliases,X,!0),l(K),$["set-placeholder-key"])BD(K);if(Object.keys(H.counts).forEach(function(O){if(!i(K,O.split(".")))c(O,0)}),Y&&QD.length)K[W]=[];if(QD.forEach(function(O){K[W].push(O)}),$["camel-case-expansion"]&&$["strip-dashed"])Object.keys(K).filter((O)=>O!=="--"&&O.includes("-")).forEach((O)=>{delete K[O]});if($["strip-aliased"])[].concat(...Object.keys(C).map((O)=>C[O])).forEach((O)=>{if($["camel-case-expansion"]&&O.includes("-"))delete K[O.split(".").map((G)=>cD(G)).join(".")];delete K[O]});function f(O){let G=R("_",O);if(typeof G==="string"||typeof G==="number")K._.push(G)}function d(O,G,V,M){let A,T=S(G,H.nargs);if(T=typeof T!=="number"||isNaN(T)?1:T,T===0){if(!CD(M))p=Error(_("Argument unexpected for: %s",G));return c(G,g(G)),O}let U=CD(M)?0:1;if($["nargs-eats-options"]){if(V.length-(O+1)+U<T)p=Error(_("Not enough arguments following: %s",G));U=T}else{for(A=O+1;A<V.length;A++)if(!V[A].match(/^-[^0-9]/)||V[A].match(P)||n(V[A]))U++;else break;if(U<T)p=Error(_("Not enough arguments following: %s",G))}let x=Math.min(U,T);if(!CD(M)&&x>0)c(G,M),x--;for(A=O+1;A<x+O+1;A++)c(G,V[A]);return O+x}function t(O,G,V,M){let A=[],T=M||V[O+1],U=S(G,H.nargs);if(S(G,H.bools)&&!/^(true|false)$/.test(T))A.push(!0);else if(CD(T)||CD(M)&&/^-/.test(T)&&!P.test(T)&&!n(T)){if(X[G]!==void 0){let x=X[G];A=Array.isArray(x)?x:[x]}}else{if(!CD(M))A.push(N(G,M,!0));for(let x=O+1;x<V.length;x++){if(!$["greedy-arrays"]&&A.length>0||U&&typeof U==="number"&&A.length>=U)break;if(T=V[x],/^-/.test(T)&&!P.test(T)&&!n(T))break;O=x,A.push(N(G,T,E))}}if(typeof U==="number"&&(U&&A.length<U||isNaN(U)&&A.length===0))p=Error(_("Not enough arguments following: %s",G));return c(G,A),O}function c(O,G,V=E){if(/-/.test(O)&&$["camel-case-expansion"]){let T=O.split(".").map(function(U){return cD(U)}).join(".");LD(O,T)}let M=N(O,G,V),A=O.split(".");if(wD(K,A,M),H.aliases[O])H.aliases[O].forEach(function(T){let U=T.split(".");wD(K,U,M)});if(A.length>1&&$["dot-notation"])(H.aliases[A[0]]||[]).forEach(function(T){let U=T.split("."),x=[].concat(A);if(x.shift(),U=U.concat(x),!(H.aliases[O]||[]).includes(U.join(".")))wD(K,U,M)});if(S(O,H.normalize)&&!S(O,H.arrays))[O].concat(H.aliases[O]||[]).forEach(function(U){Object.defineProperty(j,U,{enumerable:!0,get(){return G},set(x){G=typeof x==="string"?bD.normalize(x):x}})})}function LD(O,G){if(!(H.aliases[O]&&H.aliases[O].length))H.aliases[O]=[G],J[G]=!0;if(!(H.aliases[G]&&H.aliases[G].length))LD(G,O)}function N(O,G,V){if(V)G=ru(G);if(S(O,H.bools)||S(O,H.counts)){if(typeof G==="string")G=G==="true"}let M=Array.isArray(G)?G.map(function(A){return R(O,A)}):R(O,G);if(S(O,H.counts)&&(CD(M)||typeof M==="boolean"))M=NF();if(S(O,H.normalize)&&S(O,H.arrays))if(Array.isArray(G))M=G.map((A)=>{return bD.normalize(A)});else M=bD.normalize(G);return M}function R(O,G){if(!$["parse-positional-numbers"]&&O==="_")return G;if(!S(O,H.strings)&&!S(O,H.bools)&&!Array.isArray(G)){if(v0(G)&&$["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${G}`)))||!CD(G)&&S(O,H.numbers))G=Number(G)}return G}function w(O){let G=Object.create(null);xD(G,H.aliases,X),Object.keys(H.configs).forEach(function(V){let M=O[V]||G[V];if(M)try{let A=null,T=bD.resolve(bD.cwd(),M),U=H.configs[V];if(typeof U==="function"){try{A=U(T)}catch(x){A=x}if(A instanceof Error){p=A;return}}else A=bD.require(T);y(A)}catch(A){if(A.name==="PermissionDenied")p=A;else if(O[V])p=Error(_("Invalid JSON config file: %s",M))}})}function y(O,G){Object.keys(O).forEach(function(V){let M=O[V],A=G?G+"."+V:V;if(typeof M==="object"&&M!==null&&!Array.isArray(M)&&$["dot-notation"])y(M,A);else if(!i(K,A.split("."))||S(A,H.arrays)&&$["combine-arrays"])c(A,M)})}function o(){if(typeof Q<"u")Q.forEach(function(O){y(O)})}function uD(O,G){if(typeof z>"u")return;let V=typeof z==="string"?z:"",M=bD.env();Object.keys(M).forEach(function(A){if(V===""||A.lastIndexOf(V,0)===0){let T=A.split("__").map(function(U,x){if(x===0)U=U.substring(V.length);return cD(U)});if((G&&H.configs[T.join(".")]||!G)&&!i(O,T))c(T.join("."),M[A])}})}function l(O){let G,V=new Set;Object.keys(O).forEach(function(M){if(!V.has(M)){if(G=S(M,H.coercions),typeof G==="function")try{let A=R(M,G(O[M]));[].concat(H.aliases[M]||[],M).forEach((T)=>{V.add(T),O[T]=A})}catch(A){p=A}}})}function BD(O){return H.keys.forEach((G)=>{if(~G.indexOf("."))return;if(typeof O[G]>"u")O[G]=void 0}),O}function xD(O,G,V,M=!1){Object.keys(V).forEach(function(A){if(!i(O,A.split("."))){if(wD(O,A.split("."),V[A]),M)q[A]=!0;(G[A]||[]).forEach(function(T){if(i(O,T.split(".")))return;wD(O,T.split("."),V[A])})}})}function i(O,G){let V=O;if(!$["dot-notation"])G=[G.join(".")];G.slice(0,-1).forEach(function(A){V=V[A]||{}});let M=G[G.length-1];if(typeof V!=="object")return!1;else return M in V}function wD(O,G,V){let M=O;if(!$["dot-notation"])G=[G.join(".")];G.slice(0,-1).forEach(function(XD){if(XD=K1(XD),typeof M==="object"&&M[XD]===void 0)M[XD]={};if(typeof M[XD]!=="object"||Array.isArray(M[XD])){if(Array.isArray(M[XD]))M[XD].push({});else M[XD]=[M[XD],{}];M=M[XD][M[XD].length-1]}else M=M[XD]});let A=K1(G[G.length-1]),T=S(G.join("."),H.arrays),U=Array.isArray(V),x=$["duplicate-arguments-array"];if(!x&&S(A,H.nargs)){if(x=!0,!CD(M[A])&&H.nargs[A]===1||Array.isArray(M[A])&&M[A].length===H.nargs[A])M[A]=void 0}if(V===NF())M[A]=NF(M[A]);else if(Array.isArray(M[A]))if(x&&T&&U)M[A]=$["flatten-duplicate-arrays"]?M[A].concat(V):(Array.isArray(M[A][0])?M[A]:[M[A]]).concat([V]);else if(!x&&Boolean(T)===Boolean(U))M[A]=V;else M[A]=M[A].concat([V]);else if(M[A]===void 0&&T)M[A]=U?V:[V];else if(x&&!(M[A]===void 0||S(A,H.counts)||S(A,H.bools)))M[A]=[M[A],V];else M[A]=V}function H0(...O){O.forEach(function(G){Object.keys(G||{}).forEach(function(V){if(H.aliases[V])return;H.aliases[V]=[].concat(C[V]||[]),H.aliases[V].concat(V).forEach(function(M){if(/-/.test(M)&&$["camel-case-expansion"]){let A=cD(M);if(A!==V&&H.aliases[V].indexOf(A)===-1)H.aliases[V].push(A),J[A]=!0}}),H.aliases[V].concat(V).forEach(function(M){if(M.length>1&&/[A-Z]/.test(M)&&$["camel-case-expansion"]){let A=S0(M,"-");if(A!==V&&H.aliases[V].indexOf(A)===-1)H.aliases[V].push(A),J[A]=!0}}),H.aliases[V].forEach(function(M){H.aliases[M]=[V].concat(H.aliases[V].filter(function(A){return M!==A}))})})})}function S(O,G){let V=[].concat(H.aliases[O]||[],O),M=Object.keys(G),A=V.find((T)=>M.includes(T));return A?G[A]:!1}function Q0(O){let G=Object.keys(H);return[].concat(G.map((M)=>H[M])).some(function(M){return Array.isArray(M)?M.includes(O):M[O]})}function s2(O,...G){return[].concat(...G).some(function(M){let A=O.match(M);return A&&Q0(A[1])})}function v(O){if(O.match(P)||!O.match(/^-[^-]+/))return!1;let G=!0,V,M=O.slice(1).split("");for(let A=0;A<M.length;A++){if(V=O.slice(A+2),!Q0(M[A])){G=!1;break}if(M[A+1]&&M[A+1]==="="||V==="-"||/[A-Za-z]/.test(M[A])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(V)||M[A+1]&&M[A+1].match(/\W/))break}return G}function n(O){return $["unknown-options-as-args"]&&ED(O)}function ED(O){if(O=O.replace(/^-{3,}/,"--"),O.match(P))return!1;if(v(O))return!1;return!s2(O,/^-+([^=]+?)=[\s\S]*$/,m,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function g(O){if(!S(O,H.bools)&&!S(O,H.counts)&&`${O}`in X)return X[O];else return zD(e(O))}function zD(O){return{[qD.BOOLEAN]:!0,[qD.STRING]:"",[qD.NUMBER]:void 0,[qD.ARRAY]:[]}[O]}function e(O){let G=qD.BOOLEAN;if(S(O,H.strings))G=qD.STRING;else if(S(O,H.numbers))G=qD.NUMBER;else if(S(O,H.bools))G=qD.BOOLEAN;else if(S(O,H.arrays))G=qD.ARRAY;return G}function CD(O){return O===void 0}function HF(){Object.keys(H.counts).find((O)=>{if(S(O,H.arrays))return p=Error(_("Invalid configuration: %s, opts.count excludes opts.array.",O)),!0;else if(S(O,H.nargs))return p=Error(_("Invalid configuration: %s, opts.count excludes opts.narg.",O)),!0;return!1})}return{aliases:Object.assign({},H.aliases),argv:Object.assign(j,K),configuration:$,defaulted:Object.assign({},q),error:p,newAliases:Object.assign({},J)}}}function su(D){let F=[],u=Object.create(null),B=!0;Object.keys(D).forEach(function(E){F.push([].concat(D[E],E))});while(B){B=!1;for(let E=0;E<F.length;E++)for(let C=E+1;C<F.length;C++)if(F[E].filter(function(X){return F[C].indexOf(X)!==-1}).length){F[E]=F[E].concat(F[C]),F.splice(C,1),B=!0;break}}return F.forEach(function(E){E=E.filter(function($,X,Q){return Q.indexOf($)===X});let C=E.pop();if(C!==void 0&&typeof C==="string")u[C]=E}),u}function NF(D){return D!==void 0?D+1:1}function K1(D){if(D==="__proto__")return"___proto___";return D}function ru(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 F6}from"fs";import{createRequire as R1}from"node:module";var wF,bF,xF,U1=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,j1=(bF=(wF=process===null||process===void 0?void 0:process.versions)===null||wF===void 0?void 0:wF.node)!==null&&bF!==void 0?bF:(xF=process===null||process===void 0?void 0:process.version)===null||xF===void 0?void 0:xF.slice(1);if(j1){if(Number(j1.match(/^([^.]+)/)[1])<U1)throw Error(`yargs parser supports a minimum Node.js version of ${U1}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var u6=process?process.env:{},I1=R1?R1(import.meta.url):void 0,L1=new TF({cwd:process.cwd,env:()=>{return u6},format:au,normalize:eu,resolve:D6,require:(D)=>{if(typeof I1<"u")return I1(D);else if(D.match(/\.json$/))return JSON.parse(F6(D,"utf8"));else throw Error("only .json config files are supported in ESM")}}),M0=function(F,u){return L1.parse(F.slice(),u).argv};M0.detailed=function(D,F){return L1.parse(D.slice(),F)};M0.camelCase=cD;M0.decamelize=S0;M0.looksLikeNumber=v0;var PF=M0;import{basename as W6,dirname as A6,extname as G6,relative as H6,resolve as f1,join as q6}from"path";function N1(){if(B6())return 0;return 1}function B6(){return E6()&&!process.defaultApp}function E6(){return!!process.versions.electron}function SF(D){return D.slice(N1()+1)}function T1(){return process.argv[N1()]}import{readFileSync as C6,statSync as $6,writeFile as X6}from"fs";import{format as Z6}from"util";import{resolve as Q6}from"path";var w1={fs:{readFileSync:C6,writeFile:X6},format:Z6,resolve:Q6,exists:(D)=>{try{return $6(D).isFile()}catch(F){return!1}}};var UD;class b1{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(),B=D.shift(),E=function(){};if(typeof D[D.length-1]==="function")E=D.pop();if(!this.cache[this.locale])this._readLocaleFile();let C=B===1?F:u;if(this.cache[this.locale][F])C=this.cache[this.locale][F][B===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 $=[C];if(~C.indexOf("%d"))$.push(B);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(B,E){let C=F[E+1];if(u+=B,typeof C<"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,B=F.locale,E=F.cb,C=this._resolveLocaleFile(u,B),$=JSON.stringify(this.cache[B],null,2);UD.fs.writeFile(C,$,"utf-8",function(X){if(D.writeQueue.shift(),D.writeQueue.length>0)D._processWriteQueue();E(X)})}_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 B=UD.resolve(D,"./",F.split("_")[0]+".json");if(this._fileExistsSync(B))u=B}return u}_fileExistsSync(D){return UD.exists(D)}}function x1(D,F){UD=F;let u=new b1(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 z6=(D)=>{return x1(D,w1)},P1=z6;var y1=b0(v1(),1);import{createRequire as M6}from"node:module";import{readFileSync as _6,readdirSync as V6}from"node:fs";var vF=k1(import.meta.url),K6=vF.substring(0,vF.lastIndexOf("node_modules")),R6=M6(import.meta.url),fF={assert:{notStrictEqual:O6,strictEqual:Y6},cliui:IF,findUp:LF,getEnv:(D)=>{return process.env[D]},inspect:J6,getProcessArgvBin:T1,mainFilename:K6||process.cwd(),Parser:PF,path:{basename:W6,dirname:A6,extname:G6,relative:H6,resolve:f1,join:q6},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:_6,readdirSync:V6,require:R6,getCallerFile:()=>{let D=y1.default(3);return D.match(/^file:\/\//)?k1(D):D},stringWidth:RD,y18n:P1({directory:f1(vF,"../../../locales"),updateFiles:!1})};function YD(D,F,u,B){u.assert.notStrictEqual(D,F,B)}function kF(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 PD(D){let u=D.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),B=/\.*[\][<>]/g,E=u.shift();if(!E)throw Error(`No command found in: ${D}`);let C={cmd:E.replace(B,""),demanded:[],optional:[]};return u.forEach(($,X)=>{let Q=!1;if($=$.replace(/\s/g,""),/\.+[\]>]/.test($)&&X===u.length-1)Q=!0;if(/^\[/.test($))C.optional.push({cmd:$.replace(B,"").split("|"),variadic:Q});else C.demanded.push({cmd:$.replace(B,"").split("|"),variadic:Q})}),C}var U6=["first","second","third","fourth","fifth","sixth"];function I(D,F,u){function B(){return typeof D==="object"?[{demanded:[],optional:[]},D,F]:[PD(`cmd ${D}`),F,u]}try{let E=0,[C,$,X]=B(),Q=[].slice.call($);while(Q.length&&Q[Q.length-1]===void 0)Q.pop();let z=X||Q.length;if(z<C.demanded.length)throw new DD(`Not enough arguments provided. Expected ${C.demanded.length} but received ${Q.length}.`);let Y=C.demanded.length+C.optional.length;if(z>Y)throw new DD(`Too many arguments provided. Expected max ${Y} but received ${z}.`);C.demanded.forEach((W)=>{let J=Q.shift(),q=d1(J);if(W.cmd.filter((H)=>H===q||H==="*").length===0)h1(q,W.cmd,E);E+=1}),C.optional.forEach((W)=>{if(Q.length===0)return;let J=Q.shift(),q=d1(J);if(W.cmd.filter((H)=>H===q||H==="*").length===0)h1(q,W.cmd,E);E+=1})}catch(E){console.warn(E.stack)}}function d1(D){if(Array.isArray(D))return"array";else if(D===null)return"null";return typeof D}function h1(D,F,u){throw new DD(`Invalid ${U6[u]||"manyith"} argument. Expected ${F.join(" or ")} but received ${D}.`)}class yF{constructor(D){this.globalMiddleware=[],this.frozens=[],this.yargs=D}addMiddleware(D,F,u=!0,B=!1){if(I("<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 C=D[E];C.applyBeforeValidation=F,C.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=B,this.globalMiddleware.push(D)}return this.yargs}addCoerceMiddleware(D,F){let u=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((B)=>{let E=[...u[F]||[],F];if(!B.option)return!0;else return!E.includes(B.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 p1(D){if(!D)return[];return D.map((F)=>{return F.applyBeforeValidation=!1,F})}function lD(D,F,u,B){return u.reduce((E,C)=>{if(C.applyBeforeValidation!==B)return E;if(C.mutates){if(C.applied)return E;C.applied=!0}if(s(E))return E.then(($)=>Promise.all([$,C($,F)])).then(([$,X])=>Object.assign($,X));else{let $=C(E,F);return s($)?$.then((X)=>Object.assign(E,X)):Object.assign(E,$)}},D)}function oD(D,F,u=(B)=>{throw B}){try{let B=j6(D)?D():D;return s(B)?B.then((E)=>F(E)):F(B)}catch(B){return u(B)}}function j6(D){return typeof D==="function"}var O0=/(^\*)|(^\$0)/;class m1{constructor(D,F,u,B){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=B,this.usage=D,this.globalMiddleware=u,this.validation=F}addDirectory(D,F,u,B){B=B||{},this.requireCache.add(u);let E=this.shim.path.resolve(this.shim.path.dirname(u),D),C=this.shim.readdirSync(E,{recursive:B.recurse?!0:!1});if(!Array.isArray(B.extensions))B.extensions=["js"];let $=typeof B.visit==="function"?B.visit:(X)=>X;for(let X of C){let Q=X.toString();if(B.exclude){let Y=!1;if(typeof B.exclude==="function")Y=B.exclude(Q);else Y=B.exclude.test(Q);if(Y)continue}if(B.include){let Y=!1;if(typeof B.include==="function")Y=B.include(Q);else Y=B.include.test(Q);if(!Y)continue}let z=!1;for(let Y of B.extensions)if(Q.endsWith(Y))z=!0;if(z){let Y=this.shim.path.join(E,Q),W=F(Y),J=Object.create(null,Object.getOwnPropertyDescriptors({...W}));if($(J,Y,Q)){if(this.requireCache.has(Y))continue;else this.requireCache.add(Y);if(!J.command)J.command=this.shim.path.basename(Y,this.shim.path.extname(Y));this.addHandler(J)}}}}addHandler(D,F,u,B,E,C){let $=[],X=p1(E);if(B=B||(()=>{}),Array.isArray(D))if(I6(D))[D,...$]=D;else for(let Q of D)this.addHandler(Q);else if(N6(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(g1(u)){this.addHandler([D].concat($),F,u.builder,u.handler,u.middlewares,u.deprecated);return}if(typeof D==="string"){let Q=PD(D);$=$.map((W)=>PD(W).cmd);let z=!1,Y=[Q.cmd].concat($).filter((W)=>{if(O0.test(W))return z=!0,!1;return!0});if(Y.length===0&&z)Y.push("$0");if(z)Q.cmd=Y[0],$=Y.slice(1),D=D.replace(O0,Q.cmd);if($.forEach((W)=>{this.aliasMap[W]=Q.cmd}),F!==!1)this.usage.command(D,F,z,$,C);if(this.handlers[Q.cmd]={original:D,description:F,handler:B,builder:u||{},middlewares:X,deprecated:C,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,B,E,C){let $=this.handlers[D]||this.handlers[this.aliasMap[D]]||this.defaultCommand,X=F.getInternalMethods().getContext(),Q=X.commands.slice(),z=!D;if(D)X.commands.push(D),X.fullCommands.push($.original);let Y=this.applyBuilderUpdateUsageAndParse(z,$,F,u.aliases,Q,B,E,C);return s(Y)?Y.then((W)=>this.applyMiddlewareAndGetResult(z,$,W.innerArgv,X,E,W.aliases,F)):this.applyMiddlewareAndGetResult(z,$,Y.innerArgv,X,E,Y.aliases,F)}applyBuilderUpdateUsageAndParse(D,F,u,B,E,C,$,X){let Q=F.builder,z=u;if(f0(Q)){u.getInternalMethods().getUsageInstance().freeze();let Y=Q(u.getInternalMethods().reset(B),X);if(s(Y))return Y.then((W)=>{return z=l1(W)?W:u,this.parseAndUpdateUsage(D,F,z,E,C,$)})}else if(L6(Q))u.getInternalMethods().getUsageInstance().freeze(),z=u.getInternalMethods().reset(B),Object.keys(F.builder).forEach((Y)=>{z.option(Y,Q[Y])});return this.parseAndUpdateUsage(D,F,z,E,C,$)}parseAndUpdateUsage(D,F,u,B,E,C){if(D)u.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(u))u.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(B,F),F.description);let $=u.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,E,C);return s($)?$.then((X)=>({aliases:u.parsed.aliases,innerArgv:X})):{aliases:u.parsed.aliases,innerArgv:$}}shouldUpdateUsage(D){return!D.getInternalMethods().getUsageInstance().getUsageDisabled()&&D.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(D,F){let u=O0.test(F.original)?F.original.replace(O0,"").trim():F.original,B=D.filter((E)=>{return!O0.test(E)});return B.push(u),`$0 ${B.join(" ")}`}handleValidationAndGetResult(D,F,u,B,E,C,$,X){if(!C.getInternalMethods().getHasOutput()){let Q=C.getInternalMethods().runValidation(E,X,C.parsed.error,D);u=oD(u,(z)=>{return Q(z),z})}if(F.handler&&!C.getInternalMethods().getHasOutput()){C.getInternalMethods().setHasOutput();let Q=!!C.getOptions().configuration["populate--"];if(C.getInternalMethods().postProcess(u,Q,!1,!1),u=lD(u,C,$,!1),u=oD(u,(z)=>{let Y=F.handler(z);return s(Y)?Y.then(()=>z):z}),!D)C.getInternalMethods().getUsageInstance().cacheHelpMessage();if(s(u)&&!C.getInternalMethods().hasParseCallback())u.catch((z)=>{try{C.getInternalMethods().getUsageInstance().fail(null,z)}catch(Y){}})}if(!D)B.commands.pop(),B.fullCommands.pop();return u}applyMiddlewareAndGetResult(D,F,u,B,E,C,$){let X={};if(E)return u;if(!$.getInternalMethods().getHasOutput())X=this.populatePositionals(F,u,B,$);let Q=this.globalMiddleware.getMiddleware().slice(0).concat(F.middlewares),z=lD(u,$,Q,!0);return s(z)?z.then((Y)=>this.handleValidationAndGetResult(D,F,Y,B,C,$,Q,X)):this.handleValidationAndGetResult(D,F,z,B,C,$,Q,X)}populatePositionals(D,F,u,B){F._=F._.slice(u.commands.length);let E=D.demanded.slice(0),C=D.optional.slice(0),$={};this.validation.positionalCount(E.length,F._.length);while(E.length){let X=E.shift();this.populatePositional(X,F,$)}while(C.length){let X=C.shift();this.populatePositional(X,F,$)}return F._=u.commands.concat(F._.map((X)=>""+X)),this.postProcessPositionals(F,$,this.cmdToParseOptions(D.original),B),$}populatePositional(D,F,u){let B=D.cmd[0];if(D.variadic)u[B]=F._.splice(0).map(String);else if(F._.length)u[B]=[String(F._.shift())]}cmdToParseOptions(D){let F={array:[],default:{},alias:{},demand:{}},u=PD(D);return u.demanded.forEach((B)=>{let[E,...C]=B.cmd;if(B.variadic)F.array.push(E),F.default[E]=[];F.alias[E]=C,F.demand[E]=!0}),u.optional.forEach((B)=>{let[E,...C]=B.cmd;if(B.variadic)F.array.push(E),F.default[E]=[];F.alias[E]=C}),F}postProcessPositionals(D,F,u,B){let E=Object.assign({},B.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 C=[];if(Object.keys(F).forEach((Q)=>{F[Q].map((z)=>{if(E.configuration["unknown-options-as-args"])E.key[Q]=!0;C.push(`--${Q}`),C.push(z)})}),!C.length)return;let $=Object.assign({},E.configuration,{"populate--":!1}),X=this.shim.Parser.detailed(C,Object.assign({},E,{configuration:$}));if(X.error)B.getInternalMethods().getUsageInstance().fail(X.error.message,X.error);else{let Q=Object.keys(F);Object.keys(F).forEach((z)=>{Q.push(...X.aliases[z])}),Object.keys(X.argv).forEach((z)=>{if(Q.includes(z)){if(!F[z])F[z]=X.argv[z];if(!this.isInConfigs(B,z)&&!this.isDefaulted(B,z)&&Object.prototype.hasOwnProperty.call(D,z)&&Object.prototype.hasOwnProperty.call(X.argv,z)&&(Array.isArray(D[z])||Array.isArray(X.argv[z])))D[z]=[].concat(D[z],X.argv[z]);else D[z]=X.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((B)=>Object.prototype.hasOwnProperty.call(B,F))||u.some((B)=>Object.prototype.hasOwnProperty.call(B,this.shim.Parser.camelCase(F)))}runDefaultBuilderOn(D){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(D)){let u=O0.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(!g1(F))Object.keys(F).forEach((u)=>{D.option(u,F[u])});return}extractDesc({describe:D,description:F,desc:u}){for(let B of[D,F,u]){if(typeof B==="string"||B===!1)return B;YD(B,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let D=this.frozens.pop();YD(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 c1(D,F,u,B){return new m1(D,F,u,B)}function g1(D){return typeof D==="object"&&!!D.builder&&typeof D.handler==="function"}function I6(D){return D.every((F)=>typeof F==="string")}function f0(D){return typeof D==="function"}function L6(D){return typeof D==="object"}function N6(D){return typeof D==="object"&&!Array.isArray(D)}function SD(D={},F=()=>!0){let u={};return z0(D).forEach((B)=>{if(F(B,D[B]))u[B]=D[B]}),u}function vD(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 T6(D){return typeof D==="boolean"}function n1(D,F){let u=F.y18n.__,B={},E=[];B.failFn=function(R){E.push(R)};let C=null,$=null,X=!0;B.showHelpOnFail=function(R=!0,w){let[y,o]=typeof R==="string"?[!0,R]:[R,w];if(D.getInternalMethods().isGlobalContext())$=o;return C=o,X=y,B};let Q=!1;B.fail=function(R,w){let y=D.getInternalMethods().getLoggerInstance();if(E.length)for(let o=E.length-1;o>=0;--o){let uD=E[o];if(T6(uD)){if(w)throw w;else if(R)throw Error(R)}else uD(R,w,B)}else{if(D.getExitProcess())vD(!0);if(!Q){if(Q=!0,X)D.showHelp("error"),y.error();if(R||w)y.error(R||w);let o=C||$;if(o){if(R||w)y.error("");y.error(o)}}if(w=w||new DD(R),D.getExitProcess())return D.exit(1);else if(D.getInternalMethods().hasParseCallback())return D.exit(1,w);else throw w}};let z=[],Y=!1;B.usage=(N,R)=>{if(N===null)return Y=!0,z=[],B;return Y=!1,z.push([N,R||""]),B},B.getUsage=()=>{return z},B.getUsageDisabled=()=>{return Y},B.getPositionalGroupName=()=>{return u("Positionals:")};let W=[];B.example=(N,R)=>{W.push([N,R||""])};let J=[];B.command=function(R,w,y,o,uD=!1){if(y)J=J.map((l)=>{return l[2]=!1,l});J.push([R,w||"",y,o,uD])},B.getCommands=()=>J;let q={};B.describe=function(R,w){if(Array.isArray(R))R.forEach((y)=>{B.describe(y,w)});else if(typeof R==="object")Object.keys(R).forEach((y)=>{B.describe(y,R[y])});else q[R]=w},B.getDescriptions=()=>q;let _=[];B.epilog=(N)=>{_.push(N)};let H=!1,P;B.wrap=(N)=>{H=!0,P=N},B.getWrap=()=>{if(F.getEnv("YARGS_DISABLE_WRAP"))return null;if(!H)P=t(),H=!0;return P};let m="__yargsString__:";B.deferY18nLookup=(N)=>m+N,B.help=function(){if(K)return K;QD();let R=D.customScriptName?D.$0:F.path.basename(D.$0),w=D.getDemandedOptions(),y=D.getDemandedCommands(),o=D.getDeprecatedOptions(),uD=D.getGroups(),l=D.getOptions(),BD=[];BD=BD.concat(Object.keys(q)),BD=BD.concat(Object.keys(w)),BD=BD.concat(Object.keys(y)),BD=BD.concat(Object.keys(l.default)),BD=BD.filter(f),BD=Object.keys(BD.reduce((v,n)=>{if(n!=="_")v[n]=!0;return v},{}));let xD=B.getWrap(),i=F.cliui({width:xD,wrap:!!xD});if(!Y){if(z.length)z.forEach((v)=>{if(i.div({text:`${v[0].replace(/\$0/g,R)}`}),v[1])i.div({text:`${v[1]}`,padding:[1,0,0,0]})}),i.div();else if(J.length){let v=null;if(y._)v=`${R} <${u("command")}>
|
|
26
|
-
`;else
|
|
27
|
-
`;
|
|
28
|
-
`);
|
|
29
|
-
`)}return
|
|
25
|
+
`)}function TF(D){return B1(D,{stringWidth:RD,stripAnsi:gD,wrap:NF})}import{dirname as q1,resolve as _1}from"path";import{readdirSync as iu,statSync as tu}from"fs";function wF(D,F){let u=_1(".",D),B;if(!tu(u).isDirectory())u=q1(u);while(!0){if(B=F(u,iu(u)),B)return _1(u,B);if(u=q1(B=u),B===u)break}}import{inspect as J6}from"util";import{fileURLToPath as k1}from"url";import{format as au}from"util";import{normalize as eu,resolve as D6}from"path";function mD(D){if(!(D!==D.toLowerCase()&&D!==D.toUpperCase()))D=D.toLowerCase();if(D.indexOf("-")===-1&&D.indexOf("_")===-1)return D;else{let u="",B=!1,E=D.match(/^-+/);for(let C=E?E[0].length:0;C<D.length;C++){let $=D.charAt(C);if(B)B=!1,$=$.toUpperCase();if(C!==0&&($==="-"||$==="_"))B=!0;else if($!=="-"&&$!=="_")u+=$}return u}}function S0(D,F){let u=D.toLowerCase();F=F||"-";let B="";for(let E=0;E<D.length;E++){let C=u.charAt(E),$=D.charAt(E);if(C!==$&&E>0)B+=`${F}${u.charAt(E)}`;else B+=$}return B}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 V1(D){if(Array.isArray(D))return D.map(($)=>typeof $!=="string"?$+"":$);D=D.trim();let F=0,u=null,B=null,E=null,C=[];for(let $=0;$<D.length;$++){if(u=B,B=D.charAt($),B===" "&&!E){if(u!==" ")F++;continue}if(B===E)E=null;else if((B==="'"||B==='"')&&!E)E=B;if(!C[F])C[F]="";C[F]+=B}return C}var MD;(function(D){D.BOOLEAN="boolean",D.STRING="string",D.NUMBER="number",D.ARRAY="array"})(MD||(MD={}));var bD;class xF{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),B=V1(D),E=typeof D==="string",C=su(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),X=Object.assign(Object.create(null),u.default),Q=u.configObjects||[],z=u.envPrefix,Y=$["populate--"],W=Y?"--":"_",J=Object.create(null),M=Object.create(null),q=u.__||bD.format,H={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(O){let A=typeof O==="object"?O.key:O,V=Object.keys(O).map(function(_){return{boolean:"bools",string:"strings",number:"numbers"}[_]}).filter(Boolean).pop();if(V)H[V][A]=!0;H.arrays[A]=!0,H.keys.push(A)}),[].concat(u.boolean||[]).filter(Boolean).forEach(function(O){H.bools[O]=!0,H.keys.push(O)}),[].concat(u.string||[]).filter(Boolean).forEach(function(O){H.strings[O]=!0,H.keys.push(O)}),[].concat(u.number||[]).filter(Boolean).forEach(function(O){H.numbers[O]=!0,H.keys.push(O)}),[].concat(u.count||[]).filter(Boolean).forEach(function(O){H.counts[O]=!0,H.keys.push(O)}),[].concat(u.normalize||[]).filter(Boolean).forEach(function(O){H.normalize[O]=!0,H.keys.push(O)}),typeof u.narg==="object")Object.entries(u.narg).forEach(([O,A])=>{if(typeof A==="number")H.nargs[O]=A,H.keys.push(O)});if(typeof u.coerce==="object")Object.entries(u.coerce).forEach(([O,A])=>{if(typeof A==="function")H.coercions[O]=A,H.keys.push(O)});if(typeof u.config<"u"){if(Array.isArray(u.config)||typeof u.config==="string")[].concat(u.config).filter(Boolean).forEach(function(O){H.configs[O]=!0});else if(typeof u.config==="object")Object.entries(u.config).forEach(([O,A])=>{if(typeof A==="boolean"||typeof A==="function")H.configs[O]=A})}H0(u.key,C,u.default,H.arrays),Object.keys(X).forEach(function(O){(H.aliases[O]||[]).forEach(function(A){X[A]=X[O]})});let p=null;_F();let QD=[],h=Object.assign(Object.create(null),{_:[]}),U={};for(let O=0;O<B.length;O++){let A=B[O],V=A.replace(/^-{3,}/,"---"),_,G,T,R,x,XD;if(A!=="--"&&/^-/.test(A)&&i(A))j(A);else if(V.match(/^---+(=|$)/)){j(A);continue}else if(A.match(/^--.+=/)||!$["short-option-groups"]&&A.match(/^-.+=/)){if(R=A.match(/^--?([^=]+)=([\s\S]*)$/),R!==null&&Array.isArray(R)&&R.length>=3)if(v(R[1],H.arrays))O=l(O,R[1],B,R[2]);else if(v(R[1],H.nargs)!==!1)O=S(O,R[1],B,R[2]);else g(R[1],R[2],!0)}else if(A.match(c)&&$["boolean-negation"]){if(R=A.match(c),R!==null&&Array.isArray(R)&&R.length>=2)G=R[1],g(G,v(G,H.arrays)?[!1]:!1)}else if(A.match(/^--.+/)||!$["short-option-groups"]&&A.match(/^-[^-]+/)){if(R=A.match(/^--?(.+)/),R!==null&&Array.isArray(R)&&R.length>=2)if(G=R[1],v(G,H.arrays))O=l(O,G,B);else if(v(G,H.nargs)!==!1)O=S(O,G,B);else if(x=B[O+1],x!==void 0&&(!x.match(/^-/)||x.match(P))&&!v(G,H.bools)&&!v(G,H.counts))g(G,x),O++;else if(/^(true|false)$/.test(x))g(G,x),O++;else g(G,m(G))}else if(A.match(/^-.\..+=/)){if(R=A.match(/^-([^=]+)=([\s\S]*)$/),R!==null&&Array.isArray(R)&&R.length>=3)g(R[1],R[2])}else if(A.match(/^-.\..+/)&&!A.match(P)){if(x=B[O+1],R=A.match(/^-(.\..+)/),R!==null&&Array.isArray(R)&&R.length>=2)if(G=R[1],x!==void 0&&!x.match(/^-/)&&!v(G,H.bools)&&!v(G,H.counts))g(G,x),O++;else g(G,m(G))}else if(A.match(/^-[^-]+/)&&!A.match(P)){T=A.slice(1,-1).split(""),_=!1;for(let OD=0;OD<T.length;OD++){if(x=A.slice(OD+2),T[OD+1]&&T[OD+1]==="="){if(XD=A.slice(OD+3),G=T[OD],v(G,H.arrays))O=l(O,G,B,XD);else if(v(G,H.nargs)!==!1)O=S(O,G,B,XD);else g(G,XD);_=!0;break}if(x==="-"){g(T[OD],x);continue}if(/[A-Za-z]/.test(T[OD])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(x)&&v(x,H.bools)===!1){g(T[OD],x),_=!0;break}if(T[OD+1]&&T[OD+1].match(/\W/)){g(T[OD],x),_=!0;break}else g(T[OD],m(T[OD]))}if(G=A.slice(-1)[0],!_&&G!=="-")if(v(G,H.arrays))O=l(O,G,B);else if(v(G,H.nargs)!==!1)O=S(O,G,B);else if(x=B[O+1],x!==void 0&&(!/^(-|--)[^-]/.test(x)||x.match(P))&&!v(G,H.bools)&&!v(G,H.counts))g(G,x),O++;else if(/^(true|false)$/.test(x))g(G,x),O++;else g(G,m(G))}else if(A.match(/^-[0-9]$/)&&A.match(P)&&v(A.slice(1),H.bools))G=A.slice(1),g(G,m(G));else if(A==="--"){QD=B.slice(O+1);break}else if($["halt-at-non-option"]){QD=B.slice(O);break}else j(A)}if(uD(h,!0),uD(h,!1),w(h),n(),xD(h,H.aliases,X,!0),o(h),$["set-placeholder-key"])BD(h);if(Object.keys(H.counts).forEach(function(O){if(!t(h,O.split(".")))g(O,0)}),Y&&QD.length)h[W]=[];if(QD.forEach(function(O){h[W].push(O)}),$["camel-case-expansion"]&&$["strip-dashed"])Object.keys(h).filter((O)=>O!=="--"&&O.includes("-")).forEach((O)=>{delete h[O]});if($["strip-aliased"])[].concat(...Object.keys(C).map((O)=>C[O])).forEach((O)=>{if($["camel-case-expansion"]&&O.includes("-"))delete h[O.split(".").map((A)=>mD(A)).join(".")];delete h[O]});function j(O){let A=K("_",O);if(typeof A==="string"||typeof A==="number")h._.push(A)}function S(O,A,V,_){let G,T=v(A,H.nargs);if(T=typeof T!=="number"||isNaN(T)?1:T,T===0){if(!CD(_))p=Error(q("Argument unexpected for: %s",A));return g(A,m(A)),O}let R=CD(_)?0:1;if($["nargs-eats-options"]){if(V.length-(O+1)+R<T)p=Error(q("Not enough arguments following: %s",A));R=T}else{for(G=O+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(q("Not enough arguments following: %s",A))}let x=Math.min(R,T);if(!CD(_)&&x>0)g(A,_),x--;for(G=O+1;G<x+O+1;G++)g(A,V[G]);return O+x}function l(O,A,V,_){let G=[],T=_||V[O+1],R=v(A,H.nargs);if(v(A,H.bools)&&!/^(true|false)$/.test(T))G.push(!0);else if(CD(T)||CD(_)&&/^-/.test(T)&&!P.test(T)&&!i(T)){if(X[A]!==void 0){let x=X[A];G=Array.isArray(x)?x:[x]}}else{if(!CD(_))G.push(I(A,_,!0));for(let x=O+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;O=x,G.push(I(A,T,E))}}if(typeof R==="number"&&(R&&G.length<R||isNaN(R)&&G.length===0))p=Error(q("Not enough arguments following: %s",A));return g(A,G),O}function g(O,A,V=E){if(/-/.test(O)&&$["camel-case-expansion"]){let T=O.split(".").map(function(R){return mD(R)}).join(".");LD(O,T)}let _=I(O,A,V),G=O.split(".");if(wD(h,G,_),H.aliases[O])H.aliases[O].forEach(function(T){let R=T.split(".");wD(h,R,_)});if(G.length>1&&$["dot-notation"])(H.aliases[G[0]]||[]).forEach(function(T){let R=T.split("."),x=[].concat(G);if(x.shift(),R=R.concat(x),!(H.aliases[O]||[]).includes(R.join(".")))wD(h,R,_)});if(v(O,H.normalize)&&!v(O,H.arrays))[O].concat(H.aliases[O]||[]).forEach(function(R){Object.defineProperty(U,R,{enumerable:!0,get(){return A},set(x){A=typeof x==="string"?bD.normalize(x):x}})})}function LD(O,A){if(!(H.aliases[O]&&H.aliases[O].length))H.aliases[O]=[A],J[A]=!0;if(!(H.aliases[A]&&H.aliases[A].length))LD(A,O)}function I(O,A,V){if(V)A=ru(A);if(v(O,H.bools)||v(O,H.counts)){if(typeof A==="string")A=A==="true"}let _=Array.isArray(A)?A.map(function(G){return K(O,G)}):K(O,A);if(v(O,H.counts)&&(CD(_)||typeof _==="boolean"))_=bF();if(v(O,H.normalize)&&v(O,H.arrays))if(Array.isArray(A))_=A.map((G)=>{return bD.normalize(G)});else _=bD.normalize(A);return _}function K(O,A){if(!$["parse-positional-numbers"]&&O==="_")return A;if(!v(O,H.strings)&&!v(O,H.bools)&&!Array.isArray(A)){if(v0(A)&&$["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${A}`)))||!CD(A)&&v(O,H.numbers))A=Number(A)}return A}function w(O){let A=Object.create(null);xD(A,H.aliases,X),Object.keys(H.configs).forEach(function(V){let _=O[V]||A[V];if(_)try{let G=null,T=bD.resolve(bD.cwd(),_),R=H.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(O[V])p=Error(q("Invalid JSON config file: %s",_))}})}function y(O,A){Object.keys(O).forEach(function(V){let _=O[V],G=A?A+"."+V:V;if(typeof _==="object"&&_!==null&&!Array.isArray(_)&&$["dot-notation"])y(_,G);else if(!t(h,G.split("."))||v(G,H.arrays)&&$["combine-arrays"])g(G,_)})}function n(){if(typeof Q<"u")Q.forEach(function(O){y(O)})}function uD(O,A){if(typeof z>"u")return;let V=typeof z==="string"?z:"",_=bD.env();Object.keys(_).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 mD(R)});if((A&&H.configs[T.join(".")]||!A)&&!t(O,T))g(T.join("."),_[G])}})}function o(O){let A,V=new Set;Object.keys(O).forEach(function(_){if(!V.has(_)){if(A=v(_,H.coercions),typeof A==="function")try{let G=K(_,A(O[_]));[].concat(H.aliases[_]||[],_).forEach((T)=>{V.add(T),O[T]=G})}catch(G){p=G}}})}function BD(O){return H.keys.forEach((A)=>{if(~A.indexOf("."))return;if(typeof O[A]>"u")O[A]=void 0}),O}function xD(O,A,V,_=!1){Object.keys(V).forEach(function(G){if(!t(O,G.split("."))){if(wD(O,G.split("."),V[G]),_)M[G]=!0;(A[G]||[]).forEach(function(T){if(t(O,T.split(".")))return;wD(O,T.split("."),V[G])})}})}function t(O,A){let V=O;if(!$["dot-notation"])A=[A.join(".")];A.slice(0,-1).forEach(function(G){V=V[G]||{}});let _=A[A.length-1];if(typeof V!=="object")return!1;else return _ in V}function wD(O,A,V){let _=O;if(!$["dot-notation"])A=[A.join(".")];A.slice(0,-1).forEach(function(XD){if(XD=K1(XD),typeof _==="object"&&_[XD]===void 0)_[XD]={};if(typeof _[XD]!=="object"||Array.isArray(_[XD])){if(Array.isArray(_[XD]))_[XD].push({});else _[XD]=[_[XD],{}];_=_[XD][_[XD].length-1]}else _=_[XD]});let G=K1(A[A.length-1]),T=v(A.join("."),H.arrays),R=Array.isArray(V),x=$["duplicate-arguments-array"];if(!x&&v(G,H.nargs)){if(x=!0,!CD(_[G])&&H.nargs[G]===1||Array.isArray(_[G])&&_[G].length===H.nargs[G])_[G]=void 0}if(V===bF())_[G]=bF(_[G]);else if(Array.isArray(_[G]))if(x&&T&&R)_[G]=$["flatten-duplicate-arrays"]?_[G].concat(V):(Array.isArray(_[G][0])?_[G]:[_[G]]).concat([V]);else if(!x&&Boolean(T)===Boolean(R))_[G]=V;else _[G]=_[G].concat([V]);else if(_[G]===void 0&&T)_[G]=R?V:[V];else if(x&&!(_[G]===void 0||v(G,H.counts)||v(G,H.bools)))_[G]=[_[G],V];else _[G]=V}function H0(...O){O.forEach(function(A){Object.keys(A||{}).forEach(function(V){if(H.aliases[V])return;H.aliases[V]=[].concat(C[V]||[]),H.aliases[V].concat(V).forEach(function(_){if(/-/.test(_)&&$["camel-case-expansion"]){let G=mD(_);if(G!==V&&H.aliases[V].indexOf(G)===-1)H.aliases[V].push(G),J[G]=!0}}),H.aliases[V].concat(V).forEach(function(_){if(_.length>1&&/[A-Z]/.test(_)&&$["camel-case-expansion"]){let G=S0(_,"-");if(G!==V&&H.aliases[V].indexOf(G)===-1)H.aliases[V].push(G),J[G]=!0}}),H.aliases[V].forEach(function(_){H.aliases[_]=[V].concat(H.aliases[V].filter(function(G){return _!==G}))})})})}function v(O,A){let V=[].concat(H.aliases[O]||[],O),_=Object.keys(A),G=V.find((T)=>_.includes(T));return G?A[G]:!1}function Q0(O){let A=Object.keys(H);return[].concat(A.map((_)=>H[_])).some(function(_){return Array.isArray(_)?_.includes(O):_[O]})}function s2(O,...A){return[].concat(...A).some(function(_){let G=O.match(_);return G&&Q0(G[1])})}function f(O){if(O.match(P)||!O.match(/^-[^-]+/))return!1;let A=!0,V,_=O.slice(1).split("");for(let G=0;G<_.length;G++){if(V=O.slice(G+2),!Q0(_[G])){A=!1;break}if(_[G+1]&&_[G+1]==="="||V==="-"||/[A-Za-z]/.test(_[G])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(V)||_[G+1]&&_[G+1].match(/\W/))break}return A}function i(O){return $["unknown-options-as-args"]&&ED(O)}function ED(O){if(O=O.replace(/^-{3,}/,"--"),O.match(P))return!1;if(f(O))return!1;return!s2(O,/^-+([^=]+?)=[\s\S]*$/,c,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function m(O){if(!v(O,H.bools)&&!v(O,H.counts)&&`${O}`in X)return X[O];else return zD(e(O))}function zD(O){return{[MD.BOOLEAN]:!0,[MD.STRING]:"",[MD.NUMBER]:void 0,[MD.ARRAY]:[]}[O]}function e(O){let A=MD.BOOLEAN;if(v(O,H.strings))A=MD.STRING;else if(v(O,H.numbers))A=MD.NUMBER;else if(v(O,H.bools))A=MD.BOOLEAN;else if(v(O,H.arrays))A=MD.ARRAY;return A}function CD(O){return O===void 0}function _F(){Object.keys(H.counts).find((O)=>{if(v(O,H.arrays))return p=Error(q("Invalid configuration: %s, opts.count excludes opts.array.",O)),!0;else if(v(O,H.nargs))return p=Error(q("Invalid configuration: %s, opts.count excludes opts.narg.",O)),!0;return!1})}return{aliases:Object.assign({},H.aliases),argv:Object.assign(U,h),configuration:$,defaulted:Object.assign({},M),error:p,newAliases:Object.assign({},J)}}}function su(D){let F=[],u=Object.create(null),B=!0;Object.keys(D).forEach(function(E){F.push([].concat(D[E],E))});while(B){B=!1;for(let E=0;E<F.length;E++)for(let C=E+1;C<F.length;C++)if(F[E].filter(function(X){return F[C].indexOf(X)!==-1}).length){F[E]=F[E].concat(F[C]),F.splice(C,1),B=!0;break}}return F.forEach(function(E){E=E.filter(function($,X,Q){return Q.indexOf($)===X});let C=E.pop();if(C!==void 0&&typeof C==="string")u[C]=E}),u}function bF(D){return D!==void 0?D+1:1}function K1(D){if(D==="__proto__")return"___proto___";return D}function ru(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 F6}from"fs";import{createRequire as R1}from"node:module";var PF,SF,vF,U1=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,j1=(SF=(PF=process===null||process===void 0?void 0:process.versions)===null||PF===void 0?void 0:PF.node)!==null&&SF!==void 0?SF:(vF=process===null||process===void 0?void 0:process.version)===null||vF===void 0?void 0:vF.slice(1);if(j1){if(Number(j1.match(/^([^.]+)/)[1])<U1)throw Error(`yargs parser supports a minimum Node.js version of ${U1}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var u6=process?process.env:{},I1=R1?R1(import.meta.url):void 0,L1=new xF({cwd:process.cwd,env:()=>{return u6},format:au,normalize:eu,resolve:D6,require:(D)=>{if(typeof I1<"u")return I1(D);else if(D.match(/\.json$/))return JSON.parse(F6(D,"utf8"));else throw Error("only .json config files are supported in ESM")}}),q0=function(F,u){return L1.parse(F.slice(),u).argv};q0.detailed=function(D,F){return L1.parse(D.slice(),F)};q0.camelCase=mD;q0.decamelize=S0;q0.looksLikeNumber=v0;var fF=q0;import{basename as W6,dirname as G6,extname as A6,relative as H6,resolve as f1,join as M6}from"path";function N1(){if(B6())return 0;return 1}function B6(){return E6()&&!process.defaultApp}function E6(){return!!process.versions.electron}function kF(D){return D.slice(N1()+1)}function T1(){return process.argv[N1()]}import{readFileSync as C6,statSync as $6,writeFile as X6}from"fs";import{format as Z6}from"util";import{resolve as Q6}from"path";var w1={fs:{readFileSync:C6,writeFile:X6},format:Z6,resolve:Q6,exists:(D)=>{try{return $6(D).isFile()}catch(F){return!1}}};var UD;class b1{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(),B=D.shift(),E=function(){};if(typeof D[D.length-1]==="function")E=D.pop();if(!this.cache[this.locale])this._readLocaleFile();let C=B===1?F:u;if(this.cache[this.locale][F])C=this.cache[this.locale][F][B===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 $=[C];if(~C.indexOf("%d"))$.push(B);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(B,E){let C=F[E+1];if(u+=B,typeof C<"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,B=F.locale,E=F.cb,C=this._resolveLocaleFile(u,B),$=JSON.stringify(this.cache[B],null,2);UD.fs.writeFile(C,$,"utf-8",function(X){if(D.writeQueue.shift(),D.writeQueue.length>0)D._processWriteQueue();E(X)})}_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 B=UD.resolve(D,"./",F.split("_")[0]+".json");if(this._fileExistsSync(B))u=B}return u}_fileExistsSync(D){return UD.exists(D)}}function x1(D,F){UD=F;let u=new b1(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 z6=(D)=>{return x1(D,w1)},P1=z6;var y1=b0(v1(),1);import{createRequire as q6}from"node:module";import{readFileSync as _6,readdirSync as V6}from"node:fs";var yF=k1(import.meta.url),K6=yF.substring(0,yF.lastIndexOf("node_modules")),R6=q6(import.meta.url),dF={assert:{notStrictEqual:O6,strictEqual:Y6},cliui:TF,findUp:wF,getEnv:(D)=>{return process.env[D]},inspect:J6,getProcessArgvBin:T1,mainFilename:K6||process.cwd(),Parser:fF,path:{basename:W6,dirname:G6,extname:A6,relative:H6,resolve:f1,join:M6},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:_6,readdirSync:V6,require:R6,getCallerFile:()=>{let D=y1.default(3);return D.match(/^file:\/\//)?k1(D):D},stringWidth:RD,y18n:P1({directory:f1(yF,"../../../locales"),updateFiles:!1})};function YD(D,F,u,B){u.assert.notStrictEqual(D,F,B)}function hF(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 PD(D){let u=D.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),B=/\.*[\][<>]/g,E=u.shift();if(!E)throw Error(`No command found in: ${D}`);let C={cmd:E.replace(B,""),demanded:[],optional:[]};return u.forEach(($,X)=>{let Q=!1;if($=$.replace(/\s/g,""),/\.+[\]>]/.test($)&&X===u.length-1)Q=!0;if(/^\[/.test($))C.optional.push({cmd:$.replace(B,"").split("|"),variadic:Q});else C.demanded.push({cmd:$.replace(B,"").split("|"),variadic:Q})}),C}var U6=["first","second","third","fourth","fifth","sixth"];function L(D,F,u){function B(){return typeof D==="object"?[{demanded:[],optional:[]},D,F]:[PD(`cmd ${D}`),F,u]}try{let E=0,[C,$,X]=B(),Q=[].slice.call($);while(Q.length&&Q[Q.length-1]===void 0)Q.pop();let z=X||Q.length;if(z<C.demanded.length)throw new DD(`Not enough arguments provided. Expected ${C.demanded.length} but received ${Q.length}.`);let Y=C.demanded.length+C.optional.length;if(z>Y)throw new DD(`Too many arguments provided. Expected max ${Y} but received ${z}.`);C.demanded.forEach((W)=>{let J=Q.shift(),M=d1(J);if(W.cmd.filter((H)=>H===M||H==="*").length===0)h1(M,W.cmd,E);E+=1}),C.optional.forEach((W)=>{if(Q.length===0)return;let J=Q.shift(),M=d1(J);if(W.cmd.filter((H)=>H===M||H==="*").length===0)h1(M,W.cmd,E);E+=1})}catch(E){console.warn(E.stack)}}function d1(D){if(Array.isArray(D))return"array";else if(D===null)return"null";return typeof D}function h1(D,F,u){throw new DD(`Invalid ${U6[u]||"manyith"} argument. Expected ${F.join(" or ")} but received ${D}.`)}class pF{constructor(D){this.globalMiddleware=[],this.frozens=[],this.yargs=D}addMiddleware(D,F,u=!0,B=!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 C=D[E];C.applyBeforeValidation=F,C.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=B,this.globalMiddleware.push(D)}return this.yargs}addCoerceMiddleware(D,F){let u=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((B)=>{let E=[...u[F]||[],F];if(!B.option)return!0;else return!E.includes(B.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 p1(D){if(!D)return[];return D.map((F)=>{return F.applyBeforeValidation=!1,F})}function cD(D,F,u,B){return u.reduce((E,C)=>{if(C.applyBeforeValidation!==B)return E;if(C.mutates){if(C.applied)return E;C.applied=!0}if(s(E))return E.then(($)=>Promise.all([$,C($,F)])).then(([$,X])=>Object.assign($,X));else{let $=C(E,F);return s($)?$.then((X)=>Object.assign(E,X)):Object.assign(E,$)}},D)}function lD(D,F,u=(B)=>{throw B}){try{let B=j6(D)?D():D;return s(B)?B.then((E)=>F(E)):F(B)}catch(B){return u(B)}}function j6(D){return typeof D==="function"}var O0=/(^\*)|(^\$0)/;class m1{constructor(D,F,u,B){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=B,this.usage=D,this.globalMiddleware=u,this.validation=F}addDirectory(D,F,u,B){B=B||{},this.requireCache.add(u);let E=this.shim.path.resolve(this.shim.path.dirname(u),D),C=this.shim.readdirSync(E,{recursive:B.recurse?!0:!1});if(!Array.isArray(B.extensions))B.extensions=["js"];let $=typeof B.visit==="function"?B.visit:(X)=>X;for(let X of C){let Q=X.toString();if(B.exclude){let Y=!1;if(typeof B.exclude==="function")Y=B.exclude(Q);else Y=B.exclude.test(Q);if(Y)continue}if(B.include){let Y=!1;if(typeof B.include==="function")Y=B.include(Q);else Y=B.include.test(Q);if(!Y)continue}let z=!1;for(let Y of B.extensions)if(Q.endsWith(Y))z=!0;if(z){let Y=this.shim.path.join(E,Q),W=F(Y),J=Object.create(null,Object.getOwnPropertyDescriptors({...W}));if($(J,Y,Q)){if(this.requireCache.has(Y))continue;else this.requireCache.add(Y);if(!J.command)J.command=this.shim.path.basename(Y,this.shim.path.extname(Y));this.addHandler(J)}}}}addHandler(D,F,u,B,E,C){let $=[],X=p1(E);if(B=B||(()=>{}),Array.isArray(D))if(I6(D))[D,...$]=D;else for(let Q of D)this.addHandler(Q);else if(N6(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(g1(u)){this.addHandler([D].concat($),F,u.builder,u.handler,u.middlewares,u.deprecated);return}if(typeof D==="string"){let Q=PD(D);$=$.map((W)=>PD(W).cmd);let z=!1,Y=[Q.cmd].concat($).filter((W)=>{if(O0.test(W))return z=!0,!1;return!0});if(Y.length===0&&z)Y.push("$0");if(z)Q.cmd=Y[0],$=Y.slice(1),D=D.replace(O0,Q.cmd);if($.forEach((W)=>{this.aliasMap[W]=Q.cmd}),F!==!1)this.usage.command(D,F,z,$,C);if(this.handlers[Q.cmd]={original:D,description:F,handler:B,builder:u||{},middlewares:X,deprecated:C,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,B,E,C){let $=this.handlers[D]||this.handlers[this.aliasMap[D]]||this.defaultCommand,X=F.getInternalMethods().getContext(),Q=X.commands.slice(),z=!D;if(D)X.commands.push(D),X.fullCommands.push($.original);let Y=this.applyBuilderUpdateUsageAndParse(z,$,F,u.aliases,Q,B,E,C);return s(Y)?Y.then((W)=>this.applyMiddlewareAndGetResult(z,$,W.innerArgv,X,E,W.aliases,F)):this.applyMiddlewareAndGetResult(z,$,Y.innerArgv,X,E,Y.aliases,F)}applyBuilderUpdateUsageAndParse(D,F,u,B,E,C,$,X){let Q=F.builder,z=u;if(f0(Q)){u.getInternalMethods().getUsageInstance().freeze();let Y=Q(u.getInternalMethods().reset(B),X);if(s(Y))return Y.then((W)=>{return z=l1(W)?W:u,this.parseAndUpdateUsage(D,F,z,E,C,$)})}else if(L6(Q))u.getInternalMethods().getUsageInstance().freeze(),z=u.getInternalMethods().reset(B),Object.keys(F.builder).forEach((Y)=>{z.option(Y,Q[Y])});return this.parseAndUpdateUsage(D,F,z,E,C,$)}parseAndUpdateUsage(D,F,u,B,E,C){if(D)u.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(u))u.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(B,F),F.description);let $=u.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,E,C);return s($)?$.then((X)=>({aliases:u.parsed.aliases,innerArgv:X})):{aliases:u.parsed.aliases,innerArgv:$}}shouldUpdateUsage(D){return!D.getInternalMethods().getUsageInstance().getUsageDisabled()&&D.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(D,F){let u=O0.test(F.original)?F.original.replace(O0,"").trim():F.original,B=D.filter((E)=>{return!O0.test(E)});return B.push(u),`$0 ${B.join(" ")}`}handleValidationAndGetResult(D,F,u,B,E,C,$,X){if(!C.getInternalMethods().getHasOutput()){let Q=C.getInternalMethods().runValidation(E,X,C.parsed.error,D);u=lD(u,(z)=>{return Q(z),z})}if(F.handler&&!C.getInternalMethods().getHasOutput()){C.getInternalMethods().setHasOutput();let Q=!!C.getOptions().configuration["populate--"];if(C.getInternalMethods().postProcess(u,Q,!1,!1),u=cD(u,C,$,!1),u=lD(u,(z)=>{let Y=F.handler(z);return s(Y)?Y.then(()=>z):z}),!D)C.getInternalMethods().getUsageInstance().cacheHelpMessage();if(s(u)&&!C.getInternalMethods().hasParseCallback())u.catch((z)=>{try{C.getInternalMethods().getUsageInstance().fail(null,z)}catch(Y){}})}if(!D)B.commands.pop(),B.fullCommands.pop();return u}applyMiddlewareAndGetResult(D,F,u,B,E,C,$){let X={};if(E)return u;if(!$.getInternalMethods().getHasOutput())X=this.populatePositionals(F,u,B,$);let Q=this.globalMiddleware.getMiddleware().slice(0).concat(F.middlewares),z=cD(u,$,Q,!0);return s(z)?z.then((Y)=>this.handleValidationAndGetResult(D,F,Y,B,C,$,Q,X)):this.handleValidationAndGetResult(D,F,z,B,C,$,Q,X)}populatePositionals(D,F,u,B){F._=F._.slice(u.commands.length);let E=D.demanded.slice(0),C=D.optional.slice(0),$={};this.validation.positionalCount(E.length,F._.length);while(E.length){let X=E.shift();this.populatePositional(X,F,$)}while(C.length){let X=C.shift();this.populatePositional(X,F,$)}return F._=u.commands.concat(F._.map((X)=>""+X)),this.postProcessPositionals(F,$,this.cmdToParseOptions(D.original),B),$}populatePositional(D,F,u){let B=D.cmd[0];if(D.variadic)u[B]=F._.splice(0).map(String);else if(F._.length)u[B]=[String(F._.shift())]}cmdToParseOptions(D){let F={array:[],default:{},alias:{},demand:{}},u=PD(D);return u.demanded.forEach((B)=>{let[E,...C]=B.cmd;if(B.variadic)F.array.push(E),F.default[E]=[];F.alias[E]=C,F.demand[E]=!0}),u.optional.forEach((B)=>{let[E,...C]=B.cmd;if(B.variadic)F.array.push(E),F.default[E]=[];F.alias[E]=C}),F}postProcessPositionals(D,F,u,B){let E=Object.assign({},B.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 C=[];if(Object.keys(F).forEach((Q)=>{F[Q].map((z)=>{if(E.configuration["unknown-options-as-args"])E.key[Q]=!0;C.push(`--${Q}`),C.push(z)})}),!C.length)return;let $=Object.assign({},E.configuration,{"populate--":!1}),X=this.shim.Parser.detailed(C,Object.assign({},E,{configuration:$}));if(X.error)B.getInternalMethods().getUsageInstance().fail(X.error.message,X.error);else{let Q=Object.keys(F);Object.keys(F).forEach((z)=>{Q.push(...X.aliases[z])}),Object.keys(X.argv).forEach((z)=>{if(Q.includes(z)){if(!F[z])F[z]=X.argv[z];if(!this.isInConfigs(B,z)&&!this.isDefaulted(B,z)&&Object.prototype.hasOwnProperty.call(D,z)&&Object.prototype.hasOwnProperty.call(X.argv,z)&&(Array.isArray(D[z])||Array.isArray(X.argv[z])))D[z]=[].concat(D[z],X.argv[z]);else D[z]=X.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((B)=>Object.prototype.hasOwnProperty.call(B,F))||u.some((B)=>Object.prototype.hasOwnProperty.call(B,this.shim.Parser.camelCase(F)))}runDefaultBuilderOn(D){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(D)){let u=O0.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(!g1(F))Object.keys(F).forEach((u)=>{D.option(u,F[u])});return}extractDesc({describe:D,description:F,desc:u}){for(let B of[D,F,u]){if(typeof B==="string"||B===!1)return B;YD(B,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let D=this.frozens.pop();YD(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 c1(D,F,u,B){return new m1(D,F,u,B)}function g1(D){return typeof D==="object"&&!!D.builder&&typeof D.handler==="function"}function I6(D){return D.every((F)=>typeof F==="string")}function f0(D){return typeof D==="function"}function L6(D){return typeof D==="object"}function N6(D){return typeof D==="object"&&!Array.isArray(D)}function SD(D={},F=()=>!0){let u={};return z0(D).forEach((B)=>{if(F(B,D[B]))u[B]=D[B]}),u}function vD(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 T6(D){return typeof D==="boolean"}function n1(D,F){let u=F.y18n.__,B={},E=[];B.failFn=function(K){E.push(K)};let C=null,$=null,X=!0;B.showHelpOnFail=function(K=!0,w){let[y,n]=typeof K==="string"?[!0,K]:[K,w];if(D.getInternalMethods().isGlobalContext())$=n;return C=n,X=y,B};let Q=!1;B.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(T6(uD)){if(w)throw w;else if(K)throw Error(K)}else uD(K,w,B)}else{if(D.getExitProcess())vD(!0);if(!Q){if(Q=!0,X)D.showHelp("error"),y.error();if(K||w)y.error(K||w);let n=C||$;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=[],Y=!1;B.usage=(I,K)=>{if(I===null)return Y=!0,z=[],B;return Y=!1,z.push([I,K||""]),B},B.getUsage=()=>{return z},B.getUsageDisabled=()=>{return Y},B.getPositionalGroupName=()=>{return u("Positionals:")};let W=[];B.example=(I,K)=>{W.push([I,K||""])};let J=[];B.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])},B.getCommands=()=>J;let M={};B.describe=function(K,w){if(Array.isArray(K))K.forEach((y)=>{B.describe(y,w)});else if(typeof K==="object")Object.keys(K).forEach((y)=>{B.describe(y,K[y])});else M[K]=w},B.getDescriptions=()=>M;let q=[];B.epilog=(I)=>{q.push(I)};let H=!1,P;B.wrap=(I)=>{H=!0,P=I},B.getWrap=()=>{if(F.getEnv("YARGS_DISABLE_WRAP"))return null;if(!H)P=l(),H=!0;return P};let c="__yargsString__:";B.deferY18nLookup=(I)=>c+I,B.help=function(){if(h)return h;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(),BD=[];BD=BD.concat(Object.keys(M)),BD=BD.concat(Object.keys(w)),BD=BD.concat(Object.keys(y)),BD=BD.concat(Object.keys(o.default)),BD=BD.filter(j),BD=Object.keys(BD.reduce((f,i)=>{if(i!=="_")f[i]=!0;return f},{}));let xD=B.getWrap(),t=F.cliui({width:xD,wrap:!!xD});if(!Y){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,xD,`${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)||[]);BD=BD.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(BD,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===B.getPositionalGroupName())return e;else return(/^[0-9]$/.test(e)?o.boolean.includes(zD)?"-":"--":e.length>1?"--":"-")+e}).sort((e,CD)=>v(e)===v(CD)?0:v(e)?1:-1).join(", "),m},{});return{groupName:f,normalizedKeys:i,switches:ED}});if(Q0.filter(({groupName:f})=>f!==B.getPositionalGroupName()).some(({normalizedKeys:f,switches:i})=>!f.every((ED)=>v(i[ED]))))Q0.filter(({groupName:f})=>f!==B.getPositionalGroupName()).forEach(({normalizedKeys:f,switches:i})=>{f.forEach((ED)=>{if(v(i[ED]))i[ED]=w6(i[ED],4)})});if(Q0.forEach(({groupName:f,normalizedKeys:i,switches:ED})=>{t.div(f),i.forEach((m)=>{let zD=ED[m],e=M[m]||"",CD=null;if(e.includes(c))e=u(e.substring(c.length));if(o.boolean.includes(m))CD=`[${u("boolean")}]`;if(o.count.includes(m))CD=`[${u("count")}]`;if(o.string.includes(m))CD=`[${u("string")}]`;if(o.normalize.includes(m))CD=`[${u("string")}]`;if(o.array.includes(m))CD=`[${u("array")}]`;if(o.number.includes(m))CD=`[${u("number")}]`;let _F=(V)=>typeof V==="string"?`[${u("deprecated: %s",V)}]`:`[${u("deprecated")}]`,O=[m in n?_F(n[m]):null,CD,m in w?`[${u("required")}]`:null,o.choices&&o.choices[m]?`[${u("choices:")} ${B.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+o1(zD)],width:p(ED,xD)+4},e);let A=D.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(O&&!A)t.div({text:O,padding:[0,0,0,2],align:"right"});else t.div()}),t.div()}),W.length)t.div(u("Examples:")),W.forEach((f)=>{f[0]=f[0].replace(/\$0/g,K)}),W.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(W,xD)+4},{text:f[1]})}),t.div();if(q.length>0){let f=q.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]))+o1(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(M[y])B.describe(w,M[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 h;B.cacheHelpMessage=function(){h=this.help()},B.clearCachedHelpMessage=function(){h=void 0},B.hasCachedHelpMessage=function(){return!!h};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((BD)=>n.indexOf(BD)!==-1))w[y].push(o)}),n}function j(I){return D.getOptions().hiddenOptions.indexOf(I)<0||D.parsed.argv[D.getOptions().showHiddenOpt]}B.showHelp=(I)=>{let K=D.getInternalMethods().getLoggerInstance();if(!I)I="error";(typeof I==="function"?I:K[I])(B.help())},B.functionDescription=(I)=>{return["(",I.name?F.Parser.decamelize(I.name,"-"):u("generated-value"),")"].join("")},B.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;B.version=(I)=>{g=I},B.showVersion=(I)=>{let K=D.getInternalMethods().getLoggerInstance();if(!I)I="error";(typeof I==="function"?I:K[I])(g)},B.reset=function(K){return C=null,Q=!1,z=[],Y=!1,q=[],W=[],J=[],M=SD(M,(w)=>!K[w]),B};let LD=[];return B.freeze=function(){LD.push({failMessage:C,failureOutput:Q,usages:z,usageDisabled:Y,epilogs:q,examples:W,commands:J,descriptions:M})},B.unfreeze=function(K=!1){let w=LD.pop();if(!w)return;if(K)M={...w.descriptions,...M},J=[...w.commands,...J],z=[...w.usages,...z],W=[...w.examples,...W],q=[...w.epilogs,...q];else({failMessage:C,failureOutput:Q,usages:z,usageDisabled:Y,epilogs:q,examples:W,commands:J,descriptions:M}=w)},B}function gF(D){return typeof D==="object"}function w6(D,F){return gF(D)?{text:D.text,indentation:D.indentation+F}:{text:D,indentation:F}}function o1(D){return gF(D)?D.indentation:0}function k0(D){return gF(D)?D.text:D}var i1=`###-begin-{{app_name}}-completions-###
|
|
30
30
|
#
|
|
31
31
|
# yargs command completion script
|
|
32
32
|
#
|
|
@@ -82,15 +82,15 @@ else
|
|
|
82
82
|
compdef _{{app_name}}_yargs_completions {{app_name}}
|
|
83
83
|
fi
|
|
84
84
|
###-end-{{app_name}}-completions-###
|
|
85
|
-
`;class s1{constructor(D,F,u,B){var E,C,$;this.yargs=D,this.usage=F,this.command=u,this.shim=B,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"))||((C=this.shim.getEnv("ZSH_NAME"))===null||C===void 0?void 0:C.includes("zsh")))!==null&&$!==void 0?$:!1}defaultCompletion(D,F,u,B){let E=this.command.getCommandHandlers();for(let $=0,X=D.length;$<X;++$)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 C=[];this.commandCompletions(C,D,u),this.optionCompletions(C,D,F,u),this.choicesFromOptionsCompletions(C,D,F,u),this.choicesFromPositionalsCompletions(C,D,F,u),B(null,C)}commandCompletions(D,F,u){let B=this.yargs.getInternalMethods().getContext().commands;if(!u.match(/^-/)&&B[B.length-1]!==u&&!this.previousArgHasChoices(F))this.usage.getCommands().forEach((E)=>{let C=PD(E[0]).cmd;if(F.indexOf(C)===-1)if(!this.zshShell)D.push(C);else{let $=E[1]||"";D.push(C.replace(/:/g,"\\:")+":"+$)}})}optionCompletions(D,F,u,B){if((B.match(/^-/)||B===""&&D.length===0)&&!this.previousArgHasChoices(F)){let E=this.yargs.getOptions(),C=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(E.key).forEach(($)=>{let X=!!E.configuration["boolean-negation"]&&E.boolean.includes($);if(!C.includes($)&&!E.hiddenOptions.includes($)&&!this.argsContainKey(F,$,X))this.completeOptionKey($,D,B,X&&!!E.default[$])})}}choicesFromOptionsCompletions(D,F,u,B){if(this.previousArgHasChoices(F)){let E=this.getPreviousArgChoices(F);if(E&&E.length>0)D.push(...E.map((C)=>C.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(D,F,u,B){if(B===""&&D.length>0&&this.previousArgHasChoices(F))return;let E=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],C=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),$=E[u._.length-C-1];if(!$)return;let X=this.yargs.getOptions().choices[$]||[];for(let Q of X)if(Q.startsWith(B))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 B=F.replace(/^-+/,""),E=this.yargs.getOptions(),C=[B,...this.yargs.getAliases()[B]||[]],$;for(let X of C)if(Object.prototype.hasOwnProperty.call(E.key,X)&&Array.isArray(E.choices[X])){$=E.choices[X];break}if($)return $.filter((X)=>!u||X.startsWith(u))}previousArgHasChoices(D){let F=this.getPreviousArgChoices(D);return F!==void 0&&F.length>0}argsContainKey(D,F,u){let B=(E)=>D.indexOf((/^[^0-9]$/.test(E)?"-":"--")+E)!==-1;if(B(F))return!0;if(u&&B(`no-${F}`))return!0;if(this.aliases){for(let E of this.aliases[F])if(B(E))return!0}return!1}completeOptionKey(D,F,u,B){var E,C,$,X;let Q=D;if(this.zshShell){let J=this.usage.getDescriptions(),
|
|
86
|
-
${
|
|
87
|
-
`)}`:"";F.fail(E("Missing required argument: %s","Missing required arguments: %s",Object.keys(
|
|
88
|
-
${B("Argument: %s, Given: %s, Choices: %s",P,F.stringifiedValues(
|
|
89
|
-
`;J.forEach((_)=>{q+=_}),F.fail(q)}};let Q={};C.conflicts=function(W,J){if(I("<string|object> [array|string]",[W,J],arguments.length),typeof W==="object")Object.keys(W).forEach((q)=>{C.conflicts(q,W[q])});else{if(D.global(W),!Q[W])Q[W]=[];if(Array.isArray(J))J.forEach((q)=>C.conflicts(W,q));else Q[W].push(J)}},C.getConflicting=()=>Q,C.conflicting=function(W){if(Object.keys(W).forEach((J)=>{if(Q[J])Q[J].forEach((q)=>{if(q&&W[J]!==void 0&&W[q]!==void 0)F.fail(B("Arguments %s and %s are mutually exclusive",J,q))})}),D.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(Q).forEach((J)=>{Q[J].forEach((q)=>{if(q&&W[u.Parser.camelCase(J)]!==void 0&&W[u.Parser.camelCase(q)]!==void 0)F.fail(B("Arguments %s and %s are mutually exclusive",J,q))})})},C.recommendCommands=function(W,J){J=J.sort((P,m)=>m.length-P.length);let _=null,H=1/0;for(let P=0,m;(m=J[P])!==void 0;P++){let p=a1(W,m);if(p<=3&&p<H)H=p,_=m}if(_)F.fail(B("Did you mean %s?",_))},C.reset=function(W){return $=SD($,(J)=>!W[J]),Q=SD(Q,(J)=>!W[J]),C};let z=[];return C.freeze=function(){z.push({implied:$,conflicting:Q})},C.unfreeze=function(){let W=z.pop();YD(W,void 0,u),{implied:$,conflicting:Q}=W},C}var hF=[],_0;function V0(D,F,u,B){_0=B;let E={};if(Object.prototype.hasOwnProperty.call(D,"extends")){if(typeof D.extends!=="string")return E;let C=/\.json|\..*rc$/.test(D.extends),$=null;if(!C)try{$=import.meta.resolve(D.extends)}catch(X){return D}else $=v6(F,D.extends);S6($),hF.push($),E=C?JSON.parse(_0.readFileSync($,"utf8")):B.require(D.extends),delete D.extends,E=V0(E,_0.path.dirname($),u,_0)}return hF=[],u?F3(E,D):Object.assign({},E,D)}function S6(D){if(hF.indexOf(D)>-1)throw new DD(`Circular extended configurations: '${D}'.`)}function v6(D,F){return _0.path.resolve(D,F)}function F3(D,F){let u={};function B(E){return E&&typeof E==="object"&&!Array.isArray(E)}Object.assign(u,D);for(let E of Object.keys(F))if(B(F[E])&&B(u[E]))u[E]=F3(D[E],F[E]);else u[E]=F[E];return u}var L=function(D,F,u,B,E){if(B==="m")throw TypeError("Private method is not writable");if(B==="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 B==="a"?E.call(D,u):E?E.value=u:F.set(D,u),u},Z=function(D,F,u,B){if(u==="a"&&!B)throw TypeError("Private accessor was defined without a getter");if(typeof F==="function"?D!==F||!B:!F.has(D))throw TypeError("Cannot read private member from an object whose class did not declare it");return u==="m"?B:u==="a"?B.call(D):B?B.value:F.get(D)},FD,nD,K0,JD,AD,y0,fD,iD,d0,MD,h0,_D,ND,GD,VD,p0,tD,ZD,b,g0,m0,HD,sD,Y0,rD,kD,c0,k,aD,eD,D0,h,l0,TD,a;function V3(D){return(F=[],u=D.process.cwd(),B)=>{let E=new K3(F,u,B,D);return Object.defineProperty(E,"argv",{get:()=>{return E.parse()},enumerable:!0}),E.help(),E.version(),E}}var u3=Symbol("copyDoubleDash"),B3=Symbol("copyDoubleDash"),pF=Symbol("deleteFromParserHintObject"),E3=Symbol("emitWarning"),C3=Symbol("freeze"),$3=Symbol("getDollarZero"),F0=Symbol("getParserConfiguration"),X3=Symbol("getUsageConfiguration"),gF=Symbol("guessLocale"),Z3=Symbol("guessVersion"),Q3=Symbol("parsePositionalNumbers"),mF=Symbol("pkgUp"),yD=Symbol("populateParserHintArray"),J0=Symbol("populateParserHintSingleValueDictionary"),cF=Symbol("populateParserHintArrayDictionary"),lF=Symbol("populateParserHintDictionary"),oF=Symbol("sanitizeKey"),nF=Symbol("setKey"),iF=Symbol("unfreeze"),z3=Symbol("validateAsync"),O3=Symbol("getCommandInstance"),Y3=Symbol("getContext"),J3=Symbol("getHasOutput"),W3=Symbol("getLoggerInstance"),A3=Symbol("getParseContext"),G3=Symbol("getUsageInstance"),H3=Symbol("getValidationInstance"),o0=Symbol("hasParseCallback"),q3=Symbol("isGlobalContext"),u0=Symbol("postProcess"),M3=Symbol("rebase"),tF=Symbol("reset"),R0=Symbol("runYargsParserAndExecuteCommands"),sF=Symbol("runValidation"),_3=Symbol("setHasOutput"),B0=Symbol("kTrackManuallySetKeys"),f6="en_US";class K3{constructor(D=[],F,u,B){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"),fD.set(this,null),iD.set(this,!0),d0.set(this,{}),MD.set(this,!0),h0.set(this,[]),_D.set(this,void 0),ND.set(this,{}),GD.set(this,!1),VD.set(this,null),p0.set(this,!0),tD.set(this,void 0),ZD.set(this,""),b.set(this,void 0),g0.set(this,void 0),m0.set(this,{}),HD.set(this,null),sD.set(this,null),Y0.set(this,{}),rD.set(this,{}),kD.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),L(this,k,B,"f"),L(this,kD,D,"f"),L(this,nD,F,"f"),L(this,g0,u,"f"),L(this,_D,new yF(this),"f"),this.$0=this[$3](),this[tF](),L(this,FD,Z(this,FD,"f"),"f"),L(this,h,Z(this,h,"f"),"f"),L(this,a,Z(this,a,"f"),"f"),L(this,b,Z(this,b,"f"),"f"),Z(this,b,"f").showHiddenOpt=Z(this,y0,"f"),L(this,tD,this[B3](),"f"),Z(this,k,"f").y18n.setLocale(f6)}addHelpOpt(D,F){if(I("[string|boolean] [string]",[D,F],arguments.length),Z(this,VD,"f"))this[pF](Z(this,VD,"f")),L(this,VD,null,"f");if(D===!1&&F===void 0)return this;return L(this,VD,typeof D==="string"?D:"help","f"),this.boolean(Z(this,VD,"f")),this.describe(Z(this,VD,"f"),F||Z(this,h,"f").deferY18nLookup("Show help")),this}help(D,F){return this.addHelpOpt(D,F)}addShowHiddenOpt(D,F){if(I("[string|boolean] [string]",[D,F],arguments.length),D===!1&&F===void 0)return this;let u=typeof D==="string"?D:Z(this,y0,"f");return this.boolean(u),this.describe(u,F||Z(this,h,"f").deferY18nLookup("Show hidden options")),Z(this,b,"f").showHiddenOpt=u,this}showHidden(D,F){return this.addShowHiddenOpt(D,F)}alias(D,F){return I("<object|string|array> [string|array]",[D,F],arguments.length),this[cF](this.alias.bind(this),"alias",D,F),this}array(D){return I("<array|string>",[D],arguments.length),this[yD]("array",D),this[B0](D),this}boolean(D){return I("<array|string>",[D],arguments.length),this[yD]("boolean",D),this[B0](D),this}check(D,F){return I("<function> [boolean]",[D,F],arguments.length),this.middleware((u,B)=>{return oD(()=>{return D(u,B.getOptions())},(E)=>{if(!E)Z(this,h,"f").fail(Z(this,k,"f").y18n.__("Argument check failed: %s",D.toString()));else if(typeof E==="string"||E instanceof Error)Z(this,h,"f").fail(E.toString(),E);return u},(E)=>{return Z(this,h,"f").fail(E.message?E.message:E.toString(),E),u})},!1,F),this}choices(D,F){return I("<object|string|array> [string|array]",[D,F],arguments.length),this[cF](this.choices.bind(this),"choices",D,F),this}coerce(D,F){if(I("<object|string|array> [function]",[D,F],arguments.length),Array.isArray(D)){if(!F)throw new DD("coerce callback must be provided");for(let B of D)this.coerce(B,F);return this}else if(typeof D==="object"){for(let B of Object.keys(D))this.coerce(B,D[B]);return this}if(!F)throw new DD("coerce callback must be provided");let u=D;return Z(this,b,"f").key[u]=!0,Z(this,_D,"f").addCoerceMiddleware((B,E)=>{var C;let $=(C=E.getAliases()[u])!==null&&C!==void 0?C:[],X=[u,...$].filter((Q)=>Object.prototype.hasOwnProperty.call(B,Q));if(X.length===0)return B;return oD(()=>{return F(B[X[0]])},(Q)=>{return X.forEach((z)=>{B[z]=Q}),B},(Q)=>{throw new DD(Q.message)})},u),this}conflicts(D,F){return I("<string|object> [string|array]",[D,F],arguments.length),Z(this,a,"f").conflicts(D,F),this}config(D="config",F,u){if(I("[object|string] [string|function] [function]",[D,F,u],arguments.length),typeof D==="object"&&!Array.isArray(D))return D=V0(D,Z(this,nD,"f"),this[F0]()["deep-merge-config"]||!1,Z(this,k,"f")),Z(this,b,"f").configObjects=(Z(this,b,"f").configObjects||[]).concat(D),this;if(typeof F==="function")u=F,F=void 0;return this.describe(D,F||Z(this,h,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(D)?D:[D]).forEach((B)=>{Z(this,b,"f").config[B]=u||!0}),this}completion(D,F,u){if(I("[string] [string|boolean|function] [function]",[D,F,u],arguments.length),typeof F==="function")u=F,F=void 0;if(L(this,AD,D||Z(this,AD,"f")||"completion","f"),!F&&F!==!1)F="generate completion script";if(this.command(Z(this,AD,"f"),F),u)Z(this,JD,"f").registerFunction(u);return this}command(D,F,u,B,E,C){return I("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[D,F,u,B,E,C],arguments.length),Z(this,FD,"f").addHandler(D,F,u,B,E,C),this}commands(D,F,u,B,E,C){return this.command(D,F,u,B,E,C)}commandDir(D,F){I("<string> [object]",[D,F],arguments.length);let u=Z(this,g0,"f")||Z(this,k,"f").require;return Z(this,FD,"f").addDirectory(D,u,Z(this,k,"f").getCallerFile(),F),this}count(D){return I("<array|string>",[D],arguments.length),this[yD]("count",D),this[B0](D),this}default(D,F,u){if(I("<object|string|array> [*] [string]",[D,F,u],arguments.length),u)kF(D,Z(this,k,"f")),Z(this,b,"f").defaultDescription[D]=u;if(typeof F==="function"){if(kF(D,Z(this,k,"f")),!Z(this,b,"f").defaultDescription[D])Z(this,b,"f").defaultDescription[D]=Z(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,B){if(I("[number] [number|string] [string|null|undefined] [string|null|undefined]",[D,F,u,B],arguments.length),typeof F!=="number")u=F,F=1/0;return this.global("_",!1),Z(this,b,"f").demandedCommands._={min:D,max:F,minMsg:u,maxMsg:B},this}demand(D,F,u){if(Array.isArray(F))F.forEach((B)=>{YD(u,!0,Z(this,k,"f")),this.demandOption(B,u)}),F=1/0;else if(typeof F!=="number")u=F,F=1/0;if(typeof D==="number")YD(u,!0,Z(this,k,"f")),this.demandCommand(D,F,u,u);else if(Array.isArray(D))D.forEach((B)=>{YD(u,!0,Z(this,k,"f")),this.demandOption(B,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 I("<object|string|array> [string]",[D,F],arguments.length),this[J0](this.demandOption.bind(this),"demandedOptions",D,F),this}deprecateOption(D,F){return I("<string> [string|boolean]",[D,F],arguments.length),Z(this,b,"f").deprecatedOptions[D]=F,this}describe(D,F){return I("<object|string|array> [string]",[D,F],arguments.length),this[nF](D,!0),Z(this,h,"f").describe(D,F),this}detectLocale(D){return I("<boolean>",[D],arguments.length),L(this,iD,D,"f"),this}env(D){if(I("[string|boolean]",[D],arguments.length),D===!1)delete Z(this,b,"f").envPrefix;else Z(this,b,"f").envPrefix=D||"";return this}epilogue(D){return I("<string>",[D],arguments.length),Z(this,h,"f").epilog(D),this}epilog(D){return this.epilogue(D)}example(D,F){if(I("<string|array> [string]",[D,F],arguments.length),Array.isArray(D))D.forEach((u)=>this.example(...u));else Z(this,h,"f").example(D,F);return this}exit(D,F){if(L(this,GD,!0,"f"),L(this,fD,F,"f"),Z(this,MD,"f"))Z(this,k,"f").process.exit(D)}exitProcess(D=!0){return I("[boolean]",[D],arguments.length),L(this,MD,D,"f"),this}fail(D){if(I("<function|boolean>",[D],arguments.length),typeof D==="boolean"&&D!==!1)throw new DD("Invalid first argument. Expected function or boolean 'false'");return Z(this,h,"f").failFn(D),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(D,F){if(I("<array> [function]",[D,F],arguments.length),!F)return new Promise((u,B)=>{Z(this,JD,"f").getCompletion(D,(E,C)=>{if(E)B(E);else u(C)})});else return Z(this,JD,"f").getCompletion(D,F)}getDemandedOptions(){return I([],0),Z(this,b,"f").demandedOptions}getDemandedCommands(){return I([],0),Z(this,b,"f").demandedCommands}getDeprecatedOptions(){return I([],0),Z(this,b,"f").deprecatedOptions}getDetectLocale(){return Z(this,iD,"f")}getExitProcess(){return Z(this,MD,"f")}getGroups(){return Object.assign({},Z(this,ND,"f"),Z(this,rD,"f"))}getHelp(){if(L(this,GD,!0,"f"),!Z(this,h,"f").hasCachedHelpMessage()){if(!this.parsed){let F=this[R0](Z(this,kD,"f"),void 0,void 0,0,!0);if(s(F))return F.then(()=>{return Z(this,h,"f").help()})}let D=Z(this,FD,"f").runDefaultBuilderOn(this);if(s(D))return D.then(()=>{return Z(this,h,"f").help()})}return Promise.resolve(Z(this,h,"f").help())}getOptions(){return Z(this,b,"f")}getStrict(){return Z(this,aD,"f")}getStrictCommands(){return Z(this,eD,"f")}getStrictOptions(){return Z(this,D0,"f")}global(D,F){if(I("<string|array> [boolean]",[D,F],arguments.length),D=[].concat(D),F!==!1)Z(this,b,"f").local=Z(this,b,"f").local.filter((u)=>D.indexOf(u)===-1);else D.forEach((u)=>{if(!Z(this,b,"f").local.includes(u))Z(this,b,"f").local.push(u)});return this}group(D,F){I("<string|array> <string>",[D,F],arguments.length);let u=Z(this,rD,"f")[F]||Z(this,ND,"f")[F];if(Z(this,rD,"f")[F])delete Z(this,rD,"f")[F];let B={};return Z(this,ND,"f")[F]=(u||[]).concat(D).filter((E)=>{if(B[E])return!1;return B[E]=!0}),this}hide(D){return I("<string>",[D],arguments.length),Z(this,b,"f").hiddenOptions.push(D),this}implies(D,F){return I("<string|object> [number|string|array]",[D,F],arguments.length),Z(this,a,"f").implies(D,F),this}locale(D){if(I("[string]",[D],arguments.length),D===void 0)return this[gF](),Z(this,k,"f").y18n.getLocale();return L(this,iD,!1,"f"),Z(this,k,"f").y18n.setLocale(D),this}middleware(D,F,u){return Z(this,_D,"f").addMiddleware(D,!!F,u)}nargs(D,F){return I("<string|object|array> [number]",[D,F],arguments.length),this[J0](this.nargs.bind(this),"narg",D,F),this}normalize(D){return I("<array|string>",[D],arguments.length),this[yD]("normalize",D),this}number(D){return I("<array|string>",[D],arguments.length),this[yD]("number",D),this[B0](D),this}option(D,F){if(I("<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[B0](D),Z(this,TD,"f")&&(D==="version"||(F===null||F===void 0?void 0:F.alias)==="version"))this[E3](['"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(Z(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 B=F.demand||F.required||F.require;if(B)this.demand(D,B);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)Z(this,b,"f").defaultDescription[D]=F.defaultDescription;if(F.skipValidation)this.skipValidation(D);let E=F.describe||F.description||F.desc,C=Z(this,
|
|
91
|
-
`,"f");
|
|
92
|
-
`,"f");L(this,ZD,Z(this,ZD,"f")+D.join(" "),"f")}}}[pF](D){z0(Z(this,b,"f")).forEach((F)=>{if(((B)=>B==="configObjects")(F))return;let u=Z(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 Z(this,h,"f").getDescriptions()[D]}[E3](D,F,u){if(!Z(this,d0,"f")[u])Z(this,k,"f").process.emitWarning(D,F),Z(this,d0,"f")[u]=!0}[C3](){Z(this,h0,"f").push({options:Z(this,b,"f"),configObjects:Z(this,b,"f").configObjects.slice(0),exitProcess:Z(this,MD,"f"),groups:Z(this,ND,"f"),strict:Z(this,aD,"f"),strictCommands:Z(this,eD,"f"),strictOptions:Z(this,D0,"f"),completionCommand:Z(this,AD,"f"),output:Z(this,ZD,"f"),exitError:Z(this,fD,"f"),hasOutput:Z(this,GD,"f"),parsed:this.parsed,parseFn:Z(this,HD,"f"),parseContext:Z(this,sD,"f")}),Z(this,h,"f").freeze(),Z(this,a,"f").freeze(),Z(this,FD,"f").freeze(),Z(this,_D,"f").freeze()}[$3](){let D="",F;if(/\b(node|iojs|electron)(\.exe)?$/.test(Z(this,k,"f").process.argv()[0]))F=Z(this,k,"f").process.argv().slice(1,2);else F=Z(this,k,"f").process.argv().slice(0,1);if(D=F.map((u)=>{let B=this[M3](Z(this,nD,"f"),u);return u.match(/^(\/|([a-zA-Z]:)?\\)/)&&B.length<u.length?B:u}).join(" ").trim(),Z(this,k,"f").getEnv("_")&&Z(this,k,"f").getProcessArgvBin()===Z(this,k,"f").getEnv("_"))D=Z(this,k,"f").getEnv("_").replace(`${Z(this,k,"f").path.dirname(Z(this,k,"f").process.execPath())}/`,"");return D}[F0](){return Z(this,m0,"f")}[X3](){return Z(this,l0,"f")}[gF](){if(!Z(this,iD,"f"))return;let D=Z(this,k,"f").getEnv("LC_ALL")||Z(this,k,"f").getEnv("LC_MESSAGES")||Z(this,k,"f").getEnv("LANG")||Z(this,k,"f").getEnv("LANGUAGE")||"en_US";this.locale(D.replace(/[.:].*/,""))}[Z3](){return this[mF]().version||"unknown"}[Q3](D){let F=D["--"]?D["--"]:D._;for(let u=0,B;(B=F[u])!==void 0;u++)if(Z(this,k,"f").Parser.looksLikeNumber(B)&&Number.isSafeInteger(Math.floor(parseFloat(`${B}`))))F[u]=Number(B);return D}[mF](D){let F=D||"*";if(Z(this,Y0,"f")[F])return Z(this,Y0,"f")[F];let u={};try{let B=D||Z(this,k,"f").mainFilename;if(Z(this,k,"f").path.extname(B))B=Z(this,k,"f").path.dirname(B);let E=Z(this,k,"f").findUp(B,(C,$)=>{if($.includes("package.json"))return"package.json";else return});YD(E,void 0,Z(this,k,"f")),u=JSON.parse(Z(this,k,"f").readFileSync(E,"utf8"))}catch(B){}return Z(this,Y0,"f")[F]=u||{},Z(this,Y0,"f")[F]}[yD](D,F){F=[].concat(F),F.forEach((u)=>{u=this[oF](u),Z(this,b,"f")[D].push(u)})}[J0](D,F,u,B){this[lF](D,F,u,B,(E,C,$)=>{Z(this,b,"f")[E][C]=$})}[cF](D,F,u,B){this[lF](D,F,u,B,(E,C,$)=>{Z(this,b,"f")[E][C]=(Z(this,b,"f")[E][C]||[]).concat($)})}[lF](D,F,u,B,E){if(Array.isArray(u))u.forEach((C)=>{D(C,B)});else if(((C)=>typeof C==="object")(u))for(let C of z0(u))D(C,u[C]);else E(F,this[oF](u),B)}[oF](D){if(D==="__proto__")return"___proto___";return D}[nF](D,F){return this[J0](this[nF].bind(this),"key",D,F),this}[iF](){var D,F,u,B,E,C,$,X,Q,z,Y,W;let J=Z(this,h0,"f").pop();YD(J,void 0,Z(this,k,"f"));let q;D=this,F=this,u=this,B=this,E=this,C=this,$=this,X=this,Q=this,z=this,Y=this,W=this,{options:{set value(_){L(D,b,_,"f")}}.value,configObjects:q,exitProcess:{set value(_){L(F,MD,_,"f")}}.value,groups:{set value(_){L(u,ND,_,"f")}}.value,output:{set value(_){L(B,ZD,_,"f")}}.value,exitError:{set value(_){L(E,fD,_,"f")}}.value,hasOutput:{set value(_){L(C,GD,_,"f")}}.value,parsed:this.parsed,strict:{set value(_){L($,aD,_,"f")}}.value,strictCommands:{set value(_){L(X,eD,_,"f")}}.value,strictOptions:{set value(_){L(Q,D0,_,"f")}}.value,completionCommand:{set value(_){L(z,AD,_,"f")}}.value,parseFn:{set value(_){L(Y,HD,_,"f")}}.value,parseContext:{set value(_){L(W,sD,_,"f")}}.value}=J,Z(this,b,"f").configObjects=q,Z(this,h,"f").unfreeze(),Z(this,a,"f").unfreeze(),Z(this,FD,"f").unfreeze(),Z(this,_D,"f").unfreeze()}[z3](D,F){return oD(F,(u)=>{return D(u),u})}getInternalMethods(){return{getCommandInstance:this[O3].bind(this),getContext:this[Y3].bind(this),getHasOutput:this[J3].bind(this),getLoggerInstance:this[W3].bind(this),getParseContext:this[A3].bind(this),getParserConfiguration:this[F0].bind(this),getUsageConfiguration:this[X3].bind(this),getUsageInstance:this[G3].bind(this),getValidationInstance:this[H3].bind(this),hasParseCallback:this[o0].bind(this),isGlobalContext:this[q3].bind(this),postProcess:this[u0].bind(this),reset:this[tF].bind(this),runValidation:this[sF].bind(this),runYargsParserAndExecuteCommands:this[R0].bind(this),setHasOutput:this[_3].bind(this)}}[O3](){return Z(this,FD,"f")}[Y3](){return Z(this,K0,"f")}[J3](){return Z(this,GD,"f")}[W3](){return Z(this,tD,"f")}[A3](){return Z(this,sD,"f")||{}}[G3](){return Z(this,h,"f")}[H3](){return Z(this,a,"f")}[o0](){return!!Z(this,HD,"f")}[q3](){return Z(this,p0,"f")}[u0](D,F,u,B){if(u)return D;if(s(D))return D;if(!F)D=this[u3](D);if(this[F0]()["parse-positional-numbers"]||this[F0]()["parse-positional-numbers"]===void 0)D=this[Q3](D);if(B)D=lD(D,this,Z(this,_D,"f").getMiddleware(),!1);return D}[tF](D={}){L(this,b,Z(this,b,"f")||{},"f");let F={};F.local=Z(this,b,"f").local||[],F.configObjects=Z(this,b,"f").configObjects||[];let u={};F.local.forEach((C)=>{u[C]=!0,(D[C]||[]).forEach(($)=>{u[$]=!0})}),Object.assign(Z(this,rD,"f"),Object.keys(Z(this,ND,"f")).reduce((C,$)=>{let X=Z(this,ND,"f")[$].filter((Q)=>!(Q in u));if(X.length>0)C[$]=X;return C},{})),L(this,ND,{},"f");let B=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],E=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(B.forEach((C)=>{F[C]=(Z(this,b,"f")[C]||[]).filter(($)=>!u[$])}),E.forEach((C)=>{F[C]=SD(Z(this,b,"f")[C],($)=>!u[$])}),F.envPrefix=Z(this,b,"f").envPrefix,L(this,b,F,"f"),L(this,h,Z(this,h,"f")?Z(this,h,"f").reset(u):n1(this,Z(this,k,"f")),"f"),L(this,a,Z(this,a,"f")?Z(this,a,"f").reset(u):D3(this,Z(this,h,"f"),Z(this,k,"f")),"f"),L(this,FD,Z(this,FD,"f")?Z(this,FD,"f").reset():c1(Z(this,h,"f"),Z(this,a,"f"),Z(this,_D,"f"),Z(this,k,"f")),"f"),!Z(this,JD,"f"))L(this,JD,r1(this,Z(this,h,"f"),Z(this,FD,"f"),Z(this,k,"f")),"f");return Z(this,_D,"f").reset(),L(this,AD,null,"f"),L(this,ZD,"","f"),L(this,fD,null,"f"),L(this,GD,!1,"f"),this.parsed=!1,this}[M3](D,F){return Z(this,k,"f").path.relative(D,F)}[R0](D,F,u,B=0,E=!1){var C,$,X,Q;let z=!!u||E;D=D||Z(this,kD,"f"),Z(this,b,"f").__=Z(this,k,"f").y18n.__,Z(this,b,"f").configuration=this[F0]();let Y=!!Z(this,b,"f").configuration["populate--"],W=Object.assign({},Z(this,b,"f").configuration,{"populate--":!0}),J=Z(this,k,"f").Parser.detailed(D,Object.assign({},Z(this,b,"f"),{configuration:{"parse-positional-numbers":!1,...W}})),q=Object.assign(J.argv,Z(this,sD,"f")),_=void 0,H=J.aliases,P=!1,m=!1;if(Object.keys(q).forEach((p)=>{if(p===Z(this,VD,"f")&&q[p])P=!0;else if(p===Z(this,TD,"f")&&q[p])m=!0}),q.$0=this.$0,this.parsed=J,B===0)Z(this,h,"f").clearCachedHelpMessage();try{if(this[gF](),F)return this[u0](q,Y,!!u,!1);if(Z(this,VD,"f")){if([Z(this,VD,"f")].concat(H[Z(this,VD,"f")]||[]).filter((f)=>f.length>1).includes(""+q._[q._.length-1]))q._.pop(),P=!0}L(this,p0,!1,"f");let p=Z(this,FD,"f").getCommands(),QD=((C=Z(this,JD,"f"))===null||C===void 0?void 0:C.completionKey)?[($=Z(this,JD,"f"))===null||$===void 0?void 0:$.completionKey,...(Q=this.getAliases()[(X=Z(this,JD,"f"))===null||X===void 0?void 0:X.completionKey])!==null&&Q!==void 0?Q:[]].some((j)=>Object.prototype.hasOwnProperty.call(q,j)):!1,K=P||QD||E;if(q._.length){if(p.length){let j;for(let f=B||0,d;q._[f]!==void 0;f++)if(d=String(q._[f]),p.includes(d)&&d!==Z(this,AD,"f")){let t=Z(this,FD,"f").runCommand(d,this,J,f+1,E,P||m||E);return this[u0](t,Y,!!u,!1)}else if(!j&&d!==Z(this,AD,"f")){j=d;break}if(!Z(this,FD,"f").hasDefaultCommand()&&Z(this,c0,"f")&&j&&!K)Z(this,a,"f").recommendCommands(j,p)}if(Z(this,AD,"f")&&q._.includes(Z(this,AD,"f"))&&!QD){if(Z(this,MD,"f"))vD(!0);this.showCompletionScript(),this.exit(0)}}if(Z(this,FD,"f").hasDefaultCommand()&&!K){let j=Z(this,FD,"f").runCommand(null,this,J,0,E,P||m||E);return this[u0](j,Y,!!u,!1)}if(QD){if(Z(this,MD,"f"))vD(!0);D=[].concat(D);let j=D.slice(D.indexOf(`--${Z(this,JD,"f").completionKey}`)+1);return Z(this,JD,"f").getCompletion(j,(f,d)=>{if(f)throw new DD(f.message);(d||[]).forEach((t)=>{Z(this,tD,"f").log(t)}),this.exit(0)}),this[u0](q,!Y,!!u,!1)}if(!Z(this,GD,"f")){if(P){if(Z(this,MD,"f"))vD(!0);z=!0,this.showHelp((j)=>{Z(this,tD,"f").log(j),this.exit(0)})}else if(m){if(Z(this,MD,"f"))vD(!0);z=!0,Z(this,h,"f").showVersion("log"),this.exit(0)}}if(!z&&Z(this,b,"f").skipValidation.length>0)z=Object.keys(q).some((j)=>Z(this,b,"f").skipValidation.indexOf(j)>=0&&q[j]===!0);if(!z){if(J.error)throw new DD(J.error.message);if(!QD){let j=this[sF](H,{},J.error);if(!u)_=lD(q,this,Z(this,_D,"f").getMiddleware(),!0);if(_=this[z3](j,_!==null&&_!==void 0?_:q),s(_)&&!u)_=_.then(()=>{return lD(q,this,Z(this,_D,"f").getMiddleware(),!1)})}}}catch(p){if(p instanceof DD)Z(this,h,"f").fail(p.message,p);else throw p}return this[u0](_!==null&&_!==void 0?_:q,Y,!!u,!0)}[sF](D,F,u,B){let E={...this.getDemandedOptions()};return(C)=>{if(u)throw new DD(u.message);Z(this,a,"f").nonOptionCount(C),Z(this,a,"f").requiredArguments(C,E);let $=!1;if(Z(this,eD,"f"))$=Z(this,a,"f").unknownCommands(C);if(Z(this,aD,"f")&&!$)Z(this,a,"f").unknownArguments(C,D,F,!!B);else if(Z(this,D0,"f"))Z(this,a,"f").unknownArguments(C,D,{},!1,!1);Z(this,a,"f").limitedChoices(C),Z(this,a,"f").implications(C),Z(this,a,"f").conflicting(C)}}[_3](){L(this,GD,!0,"f")}[B0](D){if(typeof D==="string")Z(this,b,"f").key[D]=!0;else for(let F of D)Z(this,b,"f").key[F]=!0}}function l1(D){return!!D&&typeof D.getInternalMethods==="function"}var k6=V3(fF),R3=k6;import{performance as I3}from"node:perf_hooks";var dD=b0(aF(),1);class p6{total;message;current=0;barLength=30;startTime=I3.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(I3.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),B=this.barLength-u,E=dD.default.green("█".repeat(u))+dD.default.gray("░".repeat(B)),C=`${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(C)} ${dD.default.yellow(`${F}%`)}${$}`),this.current===this.total)process.stdout.write(`
|
|
93
|
-
`)}}var $D=b0(aF(),1);class t0{options;constructor(D={}){this.options={timestamp:!1,verbose:!1,...D}}formatMessage(D,F,u){let B=this.options.timestamp?`${$D.default.gray(new Date().toLocaleTimeString())} `:"",E=this.options.prefix?`${$D.default.cyan(`[${this.options.prefix}]`)} `:"";return`${B}${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())} `:"",B=this.options.prefix?`${$D.default.cyan(`[${this.options.prefix}]`)} `:"";console.log(`${u}${B}${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 eF(D){E0.warn(D)}function r0(D){E0.info(D)}function D2(D){E0.step(D)}function L3(D){E0.dim(D)}function F2(D){E0.configure(D)}function jD(D={}){return new t0(D)}function u2(D){console.log(),console.log($D.default.cyan($D.default.bold(`━━━ ${D} ━━━`)))}function B2(D,F,u){let B=D;if(F)B+=` ${$D.default.gray(`(${F}ms)`)}`;if(s0(B),u)Object.entries(u).forEach(([E,C])=>{L3(` ${E}: ${C}`)})}function C0(D,F="•"){D.forEach((u)=>{console.log($D.default.gray(` ${F} ${u}`))})}import{existsSync as c8}from"node:fs";import{resolve as l8}from"node:path";import{existsSync as a0,mkdirSync as N3}from"node:fs";import{readdir as T3,readFile as g6,stat as m6,unlink as w3,writeFile as c6}from"node:fs/promises";import{join as E2}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))N3(this.cacheDir,{recursive:!0});await this.loadFromDisk()}}async loadFromDisk(){if(!this.cacheDir||!a0(this.cacheDir))return;try{let F=(await T3(this.cacheDir)).filter((u)=>u.endsWith(".typeschema.json"));for(let u of F){let B=E2(this.cacheDir,u),E=await m6(B);if(this.config.maxAge){if(Date.now()-E.mtimeMs>this.config.maxAge){await w3(B);continue}}try{let C=await g6(B,"utf-8"),$=JSON.parse(C);if(this.config.validateCached){if(!$.schema?.identifier)continue}let X=this.generateKey($.schema.identifier);this.cache.set(X,$.schema)}catch(C){console.warn(`Failed to load cached schema from ${u}:`,C)}}}catch(D){console.warn("Failed to load cached schemas from disk:",D)}}async persistSchema(D){if(!this.cacheDir)return;if(!a0(this.cacheDir))N3(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,"_"),B=E2(this.cacheDir,u);try{await c6(B,JSON.stringify(F,null,2),"utf-8")}catch(E){console.warn(`Failed to persist schema to ${B}:`,E)}}async clearDisk(){if(!this.cacheDir||!a0(this.cacheDir))return;try{let F=(await T3(this.cacheDir)).filter((u)=>u.endsWith(".typeschema.json"));for(let u of F)await w3(E2(this.cacheDir,u))}catch(D){console.warn("Failed to clear cache directory:",D)}}}import{createHash as l6}from"crypto";var C2=(D)=>{let F=`${D.packageName}@${D.packageVersion}:${D.filePath}`;return l6("sha256").update(F).digest("base64url")};var W0=()=>{let D={},F={};return{generateId:C2,get:(E)=>D[E],set:(E,C)=>{if(D[E]=C,C.url){if(!F[C.url])F[C.url]=[];let $=F[C.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,C)=>({id:E,resourceType:C.resourceType}),getAllReferences:()=>D}};import*as V2 from"path";import*as g3 from"fs/promises";var b3="https://fs.get-ig.org/pkgs/";import*as e0 from"fs/promises";import*as x3 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=x3.join(D,".index.json");return A0(F)};import{exec as o6}from"child_process";import{promisify as n6}from"util";var P3=n6(o6);async function $2(){try{return await P3("bun --version"),"bun"}catch{try{return await P3("npm --version"),"npm"}catch{return null}}}import*as v3 from"fs/promises";import*as f3 from"path";import{exec as i6}from"child_process";import{promisify as t6}from"util";var S3=t6(i6),X2=async(D,F,u)=>{await G0(F);let B=f3.join(F,"package.json");if(!await A0(B))await v3.writeFile(B,JSON.stringify({name:"fhir-canonical-manager-workspace",version:"1.0.0",private:!0,dependencies:{}},null,2));let E=await $2();if(!E)throw Error("No package manager found. Please install npm or bun.");for(let C of D)try{if(E==="bun"){let $={...process.env,HOME:F,NPM_CONFIG_USERCONFIG:"/dev/null"},X=u?`cd ${F} && bun add ${C} --registry ${u}`:`cd ${F} && bun add ${C}`;await S3(X,{env:$,maxBuffer:10485760})}else{let $=u?`cd ${F} && npm add ${C} --registry ${u}`:`cd ${F} && npm add ${C}`;await S3($,{maxBuffer:10485760})}}catch($){throw console.error(`Failed to install package ${C}:`,$),$}};var FF=()=>{let D=W0();return{entries:{},packages:{},references:{},referenceManager:D}};import*as uF from"fs/promises";import*as z2 from"path";import*as Z2 from"fs/promises";import*as Q2 from"path";import{createHash as k3}from"crypto";var U0=async(D)=>{try{let F=Q2.join(D,"package-lock.json");try{let u=await Z2.readFile(F,"utf-8");return k3("sha256").update(u).digest("hex")}catch{let u=Q2.join(D,"bun.lock"),B=await Z2.readFile(u,"utf-8");return k3("sha256").update(B).digest("hex")}}catch{return null}};var O2=async(D,F,u)=>{let B=await U0(u),E={entries:D.entries,packages:D.packages,references:D.referenceManager.getAllReferences(),packageLockHash:B||void 0},C=z2.join(F,"index.json");await uF.writeFile(C,JSON.stringify(E,null,2))},Y2=async(D)=>{try{let F=z2.join(D,"index.json"),u=await uF.readFile(F,"utf-8");return JSON.parse(u)}catch{return null}};var y3=(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},d3=(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)=>y3(F))},J2=(D,F)=>{try{let u=JSON.parse(D);if(!d3(u))return null;return u}catch{return null}};import*as h3 from"fs/promises";import*as W2 from"path";var BF=async(D,F,u)=>{let B=W2.join(D,".index.json");try{let E=await h3.readFile(B,"utf-8"),C=J2(E,B);if(!C)return;for(let $ of C.files){if(!$.url)continue;let X=W2.join(D,$.filename),Q=u.referenceManager.generateId({packageName:F.name,packageVersion:F.version,filePath:X});u.referenceManager.set(Q,{packageName:F.name,packageVersion:F.version,filePath:X,resourceType:$.resourceType,url:$.url,version:$.version});let z={id:Q,resourceType:$.resourceType,indexVersion:C["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 Y=u.entries[$.url];if(Y)Y.push(z)}}catch{}};import*as p3 from"fs/promises";import*as EF from"path";var CF=async(D,F)=>{try{let u=EF.join(D,"package.json"),B=await p3.readFile(u,"utf-8"),E=JSON.parse(B),C={id:{name:E.name,version:E.version},path:D,canonical:E.canonical,fhirVersions:E.fhirVersions};F.packages[E.name]=C,await BF(D,E,F);let $=EF.join(D,"examples");if(await A0(EF.join($,".index.json")))await BF($,E,F)}catch{}};import*as A2 from"fs/promises";import*as G2 from"path";var H2=async(D,F)=>{try{let u=await A2.readdir(D,{withFileTypes:!0});for(let B of u){if(!B.isDirectory())continue;let E=G2.join(D,B.name);if(B.name.startsWith("@")){let C=await A2.readdir(E,{withFileTypes:!0});for(let $ of C){if(!$.isDirectory())continue;let X=G2.join(E,$.name);if(await DF(X))await CF(X,F)}}else if(await DF(E))await CF(E,F)}}catch{}};var q2=async(D,F,u,B)=>{if(F.package)try{return await B(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 _2=(D,F)=>{if(F.length===0)return D;let u=F.map((B)=>B.toLowerCase());return D.filter((B)=>{if(!B.url)return!1;let C=[B.url.toLowerCase(),B.type?.toLowerCase()||"",B.resourceType?.toLowerCase()||""].join(" ");return u.every(($)=>{let X=C.split(/[\/\-_\.\s]+/);if(X.some((Y)=>Y.startsWith($)))return!0;let z=M2[$]||[];for(let Y of z)if(X.some((W)=>W.startsWith(Y)))return!0;return C.includes($)})})};var hD=(D)=>{let{packages:F,workingDir:u}=D,B=D.registry?D.registry.endsWith("/")?D.registry:`${D.registry}/`:b3,E=V2.join(u,"node_modules"),C=V2.join(u,".fcm","cache"),$=FF(),X=!1,Q=new Map,z=()=>{if(!X)throw Error("CanonicalManager not initialized. Call init() first.")},Y=async()=>{if(X)return;await G0(u),await G0(C);let K=await U0(u),j=await Y2(C);if(j&&j.packageLockHash===K&&K!==null)$.entries=j.entries,$.packages=j.packages,Object.entries(j.references).forEach(([d,t])=>{$.referenceManager.set(d,t)});else{if(j&&j.packageLockHash!==K)console.log("Package dependencies have changed, rebuilding index...");await X2(F,u,B),$=FF(),await H2(E,$),await O2($,C,u)}X=!0},W=async()=>{$.entries={},$.packages={},$.referenceManager.clear(),Q.clear(),X=!1},J=async()=>{return z(),Object.values($.packages).map((K)=>K.id)},q=async(K,j)=>{if(z(),j?.sourceContext){let t=await q2(K,j.sourceContext,$,q);if(t)return t}let f=$.entries[K]||[];if(f.length===0)throw Error(`Cannot resolve canonical URL: ${K}`);let d=[...f];if(j?.package)d=d.filter((t)=>t.package?.name===j.package);if(j?.version)d=d.filter((t)=>t.version===j.version);if(d.length===0)throw Error(`No matching resource found for ${K} with given options`);return d[0]},_=async(K,j)=>{let f=await q(K,j);return H(f)},H=async(K)=>{z();let j=$.referenceManager.get(K.id);if(!j)throw Error(`Invalid reference ID: ${K.id}`);try{let f=await g3.readFile(j.filePath,"utf-8");return{...JSON.parse(f),id:K.id,resourceType:K.resourceType}}catch(f){throw Error(`Failed to read resource: ${f}`)}},P=async(K)=>{z();let j=[];if(K.url)j=$.entries[K.url]||[];else for(let f of Object.values($.entries))j.push(...f);if(K.kind!==void 0)j=j.filter((f)=>f.kind===K.kind);if(K.type!==void 0)j=j.filter((f)=>f.type===K.type);if(K.version!==void 0)j=j.filter((f)=>f.version===K.version);if(K.package){let f=K.package;j=j.filter((d)=>d.package?.name===f.name&&d.package?.version===f.version)}return j};return{init:Y,destroy:W,packages:J,resolveEntry:q,resolve:_,read:H,searchEntries:P,search:async(K)=>{let j=await P(K);return await Promise.all(j.map((d)=>H(d)))},smartSearch:async(K,j)=>{z();let f=await P({kind:j?.kind,package:j?.package});if(j?.resourceType)f=f.filter((d)=>d.resourceType===j.resourceType);if(j?.type)f=f.filter((d)=>d.type===j.type);return _2(f,K)},getSearchParametersForResource:async(K)=>{if(z(),Q.has(K))return Q.get(K);let f=(await P({})).filter((t)=>t.resourceType==="SearchParameter"),d=[];for(let t of f){let c=await H(t),LD=c.base||[];if(Array.isArray(LD)&&LD.includes(K))d.push(c)}return d.sort((t,c)=>{let LD=t.code||"",N=c.code||"";return LD.localeCompare(N)}),Q.set(K,d),d}}};function K2(D){let B=D.path.split(".").slice(1).map(($)=>({el:$}));if(B.length===0)return[];let E=B.length-1,C={};if(D.slicing){if(C.slicing={...D.slicing},D.min!==void 0)C.slicing.min=D.min;if(D.max&&D.max!=="*")C.slicing.max=parseInt(D.max)}if(D.sliceName){if(C.slice={},D.min!==void 0)C.slice.min=D.min;if(D.max&&D.max!=="*")C.slice.max=parseInt(D.max);C.sliceName=D.sliceName}return B[E]={...B[E],...C},B}function R2(D,F){let u=[],B=Math.min(D.length,F.length);for(let E=0;E<B;E++)if(D[E].el===F[E].el)u.push({el:D[E].el});else break;return u}function U2(D,F){let u=[];for(let B=0;B<F.length;B++)if(B<D.length&&D[B].el===F[B].el)u.push({...D[B],...F[B],...D[B].slicing&&!F[B].slicing&&{slicing:D[B].slicing}});else u.push(F[B]);return u}function s6(D,F){return!!(D.sliceName&&F.sliceName&&D.sliceName!==F.sliceName)}function m3(D){return{type:"exit-slice",sliceName:D.sliceName,...D.slicing&&{slicing:D.slicing},...D.slice&&{slice:D.slice}}}function r6(D,F,u,B){let E=[];for(let C=D-1;C>=F;C--){let $=u[C];if($.sliceName)E.push(m3($));E.push({type:"exit",el:$.el})}if(F>0){let C=u[F-1],$=B[F-1];if(s6(C,$))E.push(m3(C))}return E}function a6(D,F,u,B){let E=[];if(D>0&&D<=F){let C=u[D-1]||{},$=B[D-1];if($.sliceName&&(!C.sliceName||C.sliceName!==$.sliceName))E.push({type:"enter-slice",sliceName:$.sliceName});if(D===F)return E}for(let C=D;C<F;C++){let $=B[C];if(E.push({type:"enter",el:$.el}),$.sliceName)E.push({type:"enter-slice",sliceName:$.sliceName})}return E}function $F(D,F){let u=D.length,B=F.length,C=R2(D,F).length,$=r6(u,C,D,F),X=a6(C,B,D,F);return[...$,...X]}function l3(D,F){if(!D)return;return D.find((u)=>u.url===F)}function c3(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 e6(D){let F={};for(let[u,B]of Object.entries(D))if(typeof u==="string"&&u.startsWith("pattern")){let E=c3(u.replace(/^pattern/,""));F.pattern={type:E,value:B}}else if(typeof u==="string"&&u.startsWith("fixed")){let E=c3(u.replace(/^fixed/,""));F.pattern={type:E,value:B}}else F[u]=B;if(F.pattern?.type&&!F.type)F.type=F.pattern.type;return F}function D8(D){let F=[];for(let u of D)if(u.targetProfile){let B=Array.isArray(u.targetProfile)?u.targetProfile:[u.targetProfile];F.push(...B)}return F.length>0?[...new Set(F)].sort():void 0}function F8(D){if(!D.type||D.type.length===0)return D;if(D.type[0].code==="Reference"){let u=D8(D.type);return{...D,type:[{code:"Reference"}],...u&&{refers:u}}}return D}function u8(D,F){let u=(C)=>{let $={strength:C.strength,...C.valueSet&&{valueSet:C.valueSet}},X=l3(C.extension,"http://hl7.org/fhir/StructureDefinition/elementdefinition-bindingName");if(X?.valueString)$.bindingName=X.valueString;return $};if(D.choices){let{binding:C,...$}=D;return $}if(D.choiceOf&&F.snapshot){let C=`${F.id}.${D.choiceOf}[x]`,$=F.snapshot.element.find((X)=>X.path===C);if($?.binding)return{...D,binding:u($.binding)}}if(D.binding?.valueSet)return{...D,binding:u(D.binding)};let{binding:B,...E}=D;return E}function B8(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 E8(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 B=D.type[0].code,E={...D,type:B};if(F.kind==="logical"){let C=l3(D.extension,"http://hl7.org/fhir/StructureDefinition/elementdefinition-defaulttype");if(C?.valueCanonical)E.defaultType=C.valueCanonical}return E}function C8(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 $8(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,B={...D};if(delete B.min,delete B.max,F){if(B.array=!0,D.min&&D.min>0)B.min=D.min;if(D.max&&D.max!=="*")B.max=parseInt(D.max)}if(u)B._required=!0;return B}function X8(D,F){let u=D.substring(1).split("."),B=[F.url];for(let E of u.slice(1))B.push("elements",E);return B}function Z8(D,F){if(!D.contentReference)return D;let{contentReference:u,...B}=D;return{...B,elementReference:X8(u,F)}}function Q8(D){let{path:F,slicing:u,sliceName:B,id:E,mapping:C,example:$,alias:X,condition:Q,comment:z,definition:Y,requirements:W,extension:J,...q}=D;return q}function j2(D,F){let u=F8(D);return u=Q8(u),u=u8(u,F),u=B8(u),u=Z8(u,F),u=C8(u),u=$8(u),u=E8(u,F),u=e6(u),u}function I2(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 o3(D){if(!D)return D;return D.charAt(0).toUpperCase()+D.slice(1)}function n3(D){let F=D.split("/");return F[F.length-1]}function L2(D){let F=D.path.replace(/\[x\]$/,""),u=F.split(".").pop()||"";if(!D.type)return[];let B=[],E=D.type.map((z)=>u+o3(n3(z.code))),{type:C,binding:$,...X}=D,Q={...X,path:F,choices:E};B.push(Q);for(let z of D.type){let Y=o3(n3(z.code)),W={...D,path:F+Y,type:[z],choiceOf:u};if(D.binding)delete W.binding;B.push(W)}return B}function i3(D,F){let u=D[D.length-1],B=D.slice(0,-1),E=B[B.length-1],C=F(E,u);return[...B.slice(0,-1),C]}function z8(D,F){if(!D.discriminator)return{};let u={};for(let B of D.discriminator){if(!B.type||!["pattern","value",void 0].includes(B.type))continue;let E=B.path.trim();if(E==="$this"){if(F.pattern?.value)Object.assign(u,F.pattern.value)}else{let C=E.split(".").filter((z)=>z),$=Object.keys(F).filter((z)=>z.startsWith("pattern"));for(let z of $){let Y=z.replace("pattern","").toLowerCase();if(C.length===1&&C[0]===Y)u[Y]=F[z]}let X=["elements"];for(let z of C)if(X.push(z),C.indexOf(z)<C.length-1)X.push("elements");X.push("pattern");let Q=F;for(let z of X)Q=Q?.[z];if(Q?.value!==void 0){let z=u;for(let Y=0;Y<C.length-1;Y++){if(!z[C[Y]])z[C[Y]]={};z=z[C[Y]]}z[C[C.length-1]]=Q.value}}}return u}function O8(D,F,u){let B={match:F,schema:D};if(u?.min!==void 0&&u.min!==0)B.min=u.min;if(u?.max!==void 0)B.max=u.max;return B}function Y8(D,F,u){let B=F.slicing||D.slicing||{},E=z8(B,u),C=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]=C,F}function J8(D){if(!D.slicing?.slices)return{};let F={};for(let[u,B]of Object.entries(D.slicing.slices)){let{match:E,schema:C,...$}=B,{slicing:X,elements:Q,type:z,min:Y,...W}=C||{},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,W),Y!==void 0&&Y!==0&&J.min===void 0)J.min=Y;F[u]=J}return F}function W8(D,F,u){let B={...F};if(D==="extension")B.extensions=J8(u);if(!B.elements)B.elements={};let E=u.choiceOf||D,{_required:C,...$}=u;if(B.elements[D]=$,C){if(!B.required)B.required=[];if(!B.required.includes(E))B.required.push(E)}return B}function XF(D,F,u){let B=[...D];for(let E=0;E<F.length;E++){let C=F[E],X=F[E+1]?.type==="enter"?{}:u;switch(C.type){case"enter":B.push(X);break;case"enter-slice":B.push(X);break;case"exit":B=i3(B,(Q,z)=>W8(C.el,Q,z));break;case"exit-slice":B=i3(B,(Q,z)=>Y8(C,Q,z));break}}return B}function t3(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=A8(D),F?.package_meta)u.package_meta=F.package_meta;return u}function A8(D){if(D.kind==="resource"&&D.derivation==="constraint")return"profile";if(D.type==="Extension")return"extension";return D.kind||"unknown"}function G8(D){return(D.differential?.element||[]).filter((u)=>u.path.includes("."))}function s3(D){let u=Object.entries(D).sort((E,C)=>{let $=E[1].index??1/0,X=C[1].index??1/0;return $-X}),B={};for(let[E,C]of u)if(C.elements)B[E]={...C,elements:s3(C.elements)};else B[E]=C;return B}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={},B=Object.keys(D);for(let E of B)if(E==="elements"&&D[E])u[E]=s3(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 N2(D,F){if(D.kind==="primitive-type")return j0(t3(D,F));let u=t3(D,F),B=G8(D),E=[u],C=[],$=[...B],X=0;while($.length>0){let z=$.shift();if(I2(z)){let H=L2(z);$.unshift(...H),X++;continue}let Y=K2(z),W=U2(C,Y),J=$F(C,W),_={...j2(z,D),index:X++};E=XF(E,J,_),C=W}let Q=$F(C,[]);if(E=XF(E,Q,{index:X}),E.length!==1)throw Error(`Invalid stack state: expected 1 element, got ${E.length}`);return j0(E[0])}function T2(D){if(!D)return;return D.split("|")[0]}function q8(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 pD(D){return{kind:q8(D),package:D.package_meta.name,version:D.package_meta.version,name:D.name,url:D.url}}function I0(D,F,u){let B=F.join(".");return{kind:"nested",package:u?.name||D.package_meta.name||"undefined",version:u?.version||D.package_meta.version||"undefined",name:B,url:`${D.url}#${B}`}}function L0(D,F,u){let B=T2(D)||D,E="unknown",C=B.split("/"),$=C[C.length-1];if($&&$.length>0)E=$.split(/[-_]/).map((X)=>X.charAt(0).toUpperCase()+X.slice(1).toLowerCase()).join("");if(E==="unknown"&&F?.id&&!/^[a-zA-Z0-9_-]{20,}$/.test(F.id))E=F.id;return{kind:"value-set",package:u?.name||F?.package_name||"undefined",version:u?.version||F?.package_version||"undefined",name:E,url:B}}function ZF(D,F,u,B){let E=F.join("."),C=u||`${D.name}.${E}_binding`;return{kind:"binding",package:B?.name||D.package_meta.name||"undefined",version:B?.version||D.package_meta.version||"undefined",name:C,url:u?`urn:fhir:binding:${C}`:`${D.url}#${E}_binding`}}async function r3(D,F){let u=pD(D),B=D.package_meta;if(u.kind!=="profile")throw Error(`Expected profile, got ${u.kind} for ${D.name}`);let E;if(D.base){let Y=D.base.includes("/")?D.base:`http://hl7.org/fhir/StructureDefinition/${D.base}`,W=D.base.split("/").pop()||D.base,J=await M8(Y,F),q=Y.startsWith("http://hl7.org/fhir/");E={kind:J,package:q?"hl7.fhir.r4.core":D.package_meta.name||"undefined",version:q?"4.0.1":D.package_meta.version||"undefined",name:W,url:Y}}let C={identifier:u,base:E,dependencies:E?[E]:[]};if(D.description)C.description=D.description;let $=_8(D);if(Object.keys($).length>0)C.metadata=$;if(D.elements){let Y=await QF(D,[],D.elements,F,B);if(Object.keys(Y).length>0)C.fields=Y}let X=await V8(D,F);if(Object.keys(X).length>0)C.constraints=X;let Q=await K8(D,F);if(Q.length>0)C.extensions=Q;let z=R8(D);if(z.length>0)C.validation=z;return C}async function M8(D,F){try{let u=await F.resolve(D);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 _8(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 V8(D,F){let u={};if(!D.elements)return u;for(let[B,E]of Object.entries(D.elements)){let C={};if(E.min!==void 0)C.min=E.min;if(E.max!==void 0)C.max=String(E.max);if(E.mustSupport)C.mustSupport=!0;if(E.fixedValue!==void 0)C.fixedValue=E.fixedValue;if(E.patternValue!==void 0)C.patternValue=E.patternValue;if(E.binding)C.binding={strength:E.binding.strength,valueSet:E.binding.valueSet??""};if(E.type&&Array.isArray(E.type)&&E.type.length>0)C.types=E.type.map(($)=>{let X={code:$.code};if($.profile)X.profile=$.profile;if($.targetProfile)X.targetProfile=$.targetProfile;return X});if(E.slicing)C.slicing={discriminator:E.slicing.discriminator??[],rules:String(E.slicing),ordered:E.slicing.ordered};if(Object.keys(C).length>0)u[B]=C}return u}async function K8(D,F){let u=[];if(!D.elements)return u;for(let[B,E]of Object.entries(D.elements))if(B.includes("extension")&&E.type&&Array.isArray(E.type)){for(let C of E.type)if(C.code==="Extension"&&C.profile)u.push({path:B,profile:C.profile,min:E.min,max:String(E.max),mustSupport:E.mustSupport})}return u}function R8(D){let F=[];if(!D.elements)return F;for(let[u,B]of Object.entries(D.elements))if(B.constraint&&Array.isArray(B.constraint))for(let E of B.constraint)F.push({path:u,key:E.key,severity:E.severity,human:E.human,expression:E.expression});return F}function a3(D,F,u){let B=[],E=D.elements;for(let C of F)if(E=E?.[C],!E)break;if(E)B.push(E);return B}function e3(D){if(D.length===0)return{};let F={...D[0]};for(let u=D.length-1;u>=0;u--){let B=D[u],E=["choices","short","index","elements","required","excluded","binding","refers","elementReference","mustSupport","slices","slicing","url","extensions"];for(let[C,$]of Object.entries(B))if(!E.includes(C)&&$!==void 0)F[C]=$}for(let u of["choices","binding","refers","elementReference"])if(D[0]&&D[0][u]!==void 0)F[u]=D[0][u];return F}function Du(D,F,u){if(F.length===0)return!1;let B=F[F.length-1],E=F.slice(0,-1),C=D;for(let $ of E)if(C=C.elements?.[$],!C)break;if(C?.required?.includes(B))return!0;if(E.length===0&&B&&D.required?.includes(B))return!0;return!1}function Fu(D,F,u){if(F.length===0)return!1;let B=F[F.length-1],E=F.slice(0,-1),C=D;for(let $ of E)if(C=C.elements?.[$],!C)break;if(C?.excluded?.includes(B))return!0;if(E.length===0&&B&&D.excluded?.includes(B))return!0;return!1}async function U8(D,F,u){if(!D.refers||D.refers.length===0)return;let B=[];for(let E of D.refers)try{let C=await F.resolve(E);if(C)B.push(pD(C))}catch{}return B}function w2(D,F,u,B,E){if(u.elementReference){let C=u.elementReference.filter(($,X)=>X%2===1).map(($)=>$).filter(($)=>$!=="elements");if(C.length>0)return I0(D,C,E)}if(u.type){let C=u.type.includes("/")?u.type:`http://hl7.org/fhir/StructureDefinition/${u.type}`,$=u.type.match(/^[a-z]/)?"primitive-type":"complex-type",X=C.startsWith("http://hl7.org/fhir/");return{kind:$,package:X?"hl7.fhir.r4.core":E?.name||"undefined",version:X?"4.0.1":E?.version||"undefined",name:u.type,url:C}}return}async function zF(D,F,u,B,E){let C={array:u.array||!1,required:Du(D,F,B),excluded:Fu(D,F,B)},$=w2(D,F,u,B,E);if($)C.type=$;if(u.min!==void 0)C.min=u.min;if(u.max!==void 0)C.max=u.max;if(u.choices)C.choices=u.choices;if(u.choiceOf)C.choiceOf=u.choiceOf;if(u.binding){if(C.binding=ZF(D,F,u.binding.bindingName,E),u.binding.strength==="required"&&u.type==="code"){let Q=await b2(u,B);if(Q&&Q.length>0)C.enum=Q}}let X=await U8(u,B,E);if(X)C.reference=X;return j8(C)}function j8(D){let F={};for(let[u,B]of Object.entries(D))if(B!==void 0&&B!==null){if(Array.isArray(B)&&B.length===0)continue;F[u]=B}return F}function N0(D){return D.type==="BackboneElement"||D.elements&&Object.keys(D.elements).length>0||!1}function OF(D,F,u,B,E){return{type:I0(D,F,E),array:u.array||!1,required:Du(D,F,B),excluded:Fu(D,F,B)}}async function I8(D,F){try{let u=T2(D)||D,B=await F.resolve(u);if(!B)return;if(B.expansion?.contains)return B.expansion.contains.map((C)=>({system:C.system,code:C.code,display:C.display}));let E=[];if(B.compose?.include){for(let C of B.compose.include)if(C.concept)for(let $ of C.concept)E.push({system:C.system,code:$.code,display:$.display});else if(C.system&&!C.filter)try{let $=await F.resolve(C.system);if($?.concept){let X=(Q,z)=>{for(let Y of Q)if(E.push({system:z,code:Y.code,display:Y.display}),Y.concept)X(Y.concept,z)};X($.concept,C.system)}}catch{}}return E.length>0?E:void 0}catch{return}}async function b2(D,F){if(!D.binding)return;let{strength:u,valueSet:B}=D.binding;if(!B)return;if(!(u==="required"||u==="extensible"&&(D.type==="code"||D.type==="Coding")||u==="preferred"&&(D.type==="code"||D.type==="Coding")))return;if(!F.resolve)return;try{let C=await I8(B,F);if(!C||C.length===0)return;let $=C.map((X)=>X.code).filter((X)=>X&&typeof X==="string"&&X.trim().length>0);return $.length>0&&$.length<=100?$:void 0}catch(C){console.debug(`Failed to extract enum values for ${B}: ${C}`);return}}async function L8(D,F,u,B,E){if(!u.binding?.valueSet)return;let C=ZF(D,F,u.binding.bindingName,E),$=w2(D,F,u,B,E),X=L0(u.binding.valueSet,void 0,E),Q={identifier:C,type:$,valueset:X,strength:u.binding.strength,dependencies:[]};if($)Q.dependencies.push($);Q.dependencies.push(X);let z=await b2(u,B);if(z)Q.enum=z;return Q}async function x2(D,F,u){let B=[],E=new Set;async function C(Q,z){for(let[Y,W]of Object.entries(Q)){let J=[...z,Y],q=J.join(".");if(E.has(q))continue;if(E.add(q),W.binding){let _=await L8(D,J,W,F,u);if(_)B.push(_)}if(W.elements)await C(W.elements,J)}}if(D.elements)await C(D.elements,[]);B.sort((Q,z)=>Q.identifier.name.localeCompare(z.identifier.name));let $=[],X=new Set;for(let Q of B)if(!X.has(Q.identifier.url))X.add(Q.identifier.url),$.push(Q);return $}function uu(D,F,u){let B=[];for(let[E,C]of Object.entries(u)){let $=[...F,E];if(N0(C))B.push([$,C]);if(C.elements)B.push(...uu(D,$,C.elements))}return B}async function N8(D,F,u,B,E){let C={};for(let[$,X]of Object.entries(u)){let Q=[...F,$];if(N0(X))C[$]=OF(D,Q,X,B,E);else C[$]=await zF(D,Q,X,B,E)}return C}async function P2(D,F,u){if(!D.elements)return[];let B=[],C=uu(D,[],D.elements).filter(([$,X])=>X.elements&&Object.keys(X.elements).length>0);for(let[$,X]of C){let Q=I0(D,$,u),z;if(X.type==="BackboneElement"||!X.type)z={kind:"complex-type",package:u?.name||"hl7.fhir.r4.core",version:u?.version||"4.0.1",name:"BackboneElement",url:"http://hl7.org/fhir/StructureDefinition/BackboneElement"};else z={kind:"complex-type",package:u?.name||"hl7.fhir.r4.core",version:u?.version||"4.0.1",name:X.type,url:`http://hl7.org/fhir/StructureDefinition/${X.type}`};let Y=await N8(D,$,X.elements,F,u),W={identifier:Q,base:z,fields:Y};B.push(W)}return B.sort(($,X)=>$.identifier.url.localeCompare(X.identifier.url)),B}function S2(D){let F=[];for(let u of D){if(F.push(u.identifier),u.base)F.push(u.base);for(let B of Object.values(u.fields)){if("type"in B&&B.type)F.push(B.type);if("binding"in B&&B.binding)F.push(B.binding)}}return F}async function QF(D,F,u,B,E){let C={};for(let[$,X]of Object.entries(u)){let Q=[...F,$],z=a3(D,Q,B),Y=z.length>0?e3(z):X;if(N0(Y))C[$]=OF(D,Q,Y,B,E);else C[$]=await zF(D,Q,Y,B,E)}return C}function Bu(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 Eu(D){let F=new Set,u=[];for(let B of D){let E=B.url;if(!F.has(E))F.add(E),u.push(B)}return u.sort((B,E)=>B.name.localeCompare(E.name)),u}function T8(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 w8(D,F,u){try{let B=pD(D);B.kind="value-set";let E={identifier:B,description:D.description};if(D.elements){let C=[];for(let[$,X]of Object.entries(D.elements))if("code"in X&&X.code)C.push({code:X.code,display:X.short||X.definition,system:X.system});if(C.length>0)E.concept=C}return E}catch(B){return console.warn(`Failed to transform value set ${D.name}: ${B}`),null}}async function b8(D,F,u){try{let B=pD(D),E;if(D.base&&D.base!=="Extension"){let X=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:X}}else E={kind:"complex-type",package:"hl7.fhir.r4.core",version:"4.0.1",name:"Extension",url:"http://hl7.org/fhir/StructureDefinition/Extension"};let C={identifier:B,base:E,description:D.description,dependencies:[],metadata:{isExtension:!0}};if(E)C.dependencies.push(E);if(D.elements){let X=await QF(D,[],D.elements,F,u);if(Object.keys(X).length>0)C.fields=X,C.dependencies.push(...Bu(X))}let $=await P2(D,F,u);if($.length>0)C.nested=$,C.dependencies.push(...S2($));return C.dependencies=Eu(C.dependencies),C.dependencies=C.dependencies.filter((X)=>X.url!==B.url),C}catch(B){return console.warn(`Failed to transform extension ${D.name}: ${B}`),null}}async function Cu(D,F){let u=[],B=pD(F);if(B.kind==="profile"){let Q=await r3(F,D,F.package_meta);u.push(Q);let z=await x2(F,D,F.package_meta);return u.push(...z),u}if(B.kind==="value-set"||F.kind==="value-set"){let Q=await w8(F,D,F.package_meta);if(Q)u.push(Q);return u}if(T8(F,B)){let Q=await b8(F,D,F.package_meta);if(Q)u.push(Q);return u}let E;if(F.base&&F.type!=="Element"){let Q=F.base.includes("/")?F.base:`http://hl7.org/fhir/StructureDefinition/${F.base}`,z=F.base.split("/").pop()||F.base,W=new Set(["Element","BackboneElement","Quantity","Duration","Distance","Count","Age","Address","Annotation","Attachment","CodeableConcept","Coding","ContactPoint","HumanName","Identifier","Period","Range","Ratio","Reference","Timing","Money","SampledData","Signature","ContactDetail","Contributor","DataRequirement","Expression","ParameterDefinition","RelatedArtifact","TriggerDefinition","UsageContext","Dosage","Meta","Extension"]).has(z)?"complex-type":"resource",J=Q.startsWith("http://hl7.org/fhir/");E={kind:W,package:J?"hl7.fhir.r4.core":F.package_meta.name||"undefined",version:J?"4.0.1":F.package_meta.version||"undefined",name:z,url:Q}}let C={identifier:B,dependencies:[]},$=[];if(E)C.base=E,$.push(E);if(F.description)C.description=F.description;if(F.kind!=="primitive-type"&&F.elements){let Q=await QF(F,[],F.elements,D,F.package_meta);if(Object.keys(Q).length>0)C.fields=Q;$.push(...Bu(Q));let z=await P2(F,D,F.package_meta);if(z.length>0)C.nested=z,$.push(...S2(z))}C.dependencies=$,C.dependencies=Eu(C.dependencies),C.dependencies=C.dependencies.filter((Q)=>Q.url!==B.url),u.push(C);let X=await x2(F,D,F.package_meta);return u.push(...X),u}var $u=(D)=>{return{...D,package_meta:{name:D.package_name||D.package_meta.name||"undefined",version:D.package_version||D.package_meta.version||"undefined"}}};function v2(D){return D.identifier.kind==="binding"}async function x8(D,F){try{let u=await F.resolve(D);if(!u||u.resourceType!=="CodeSystem")return;let B=[],E=(C,$)=>{for(let X of C)if(B.push({system:$,code:X.code,display:X.display}),X.concept)E(X.concept,$)};if(u.concept)E(u.concept,D);return B}catch{return}}async function Xu(D,F){let u=[];if(D.concept){for(let B of D.concept)u.push({system:D.system,code:B.code,display:B.display});return u}if(D.system&&!D.filter){let B=await x8(D.system,F);if(B)u.push(...B)}if(D.valueSet)for(let B of D.valueSet)try{let E=await F.resolve(B);if(E){let C=await Zu(E,F);if(C)u.push(...C)}}catch{}return u}async function Zu(D,F){try{let u=[];if(D.compose){if(D.compose.include)for(let B of D.compose.include){let E=await Xu(B,F);u.push(...E)}if(D.compose.exclude){let B=new Set;for(let E of D.compose.exclude){let C=await Xu(E,F);for(let $ of C)B.add(`${$.system}|${$.code}`)}return u.filter((E)=>!B.has(`${E.system}|${E.code}`))}}return u.length>0?u:void 0}catch(u){console.error("Error extracting ValueSet concepts:",u);return}}async function Qu(D,F,u){let E={identifier:L0(D.url,D,u)};if(D.description)E.description=D.description;let C=await Zu(D,F);if(C&&C.length>0)E.concept=C;else if(D.compose)E.compose=D.compose;if(D.compose){let $=[],X=(Q)=>{for(let z of Q){if(z.system)$.push({kind:"value-set",package:u?.name||"undefined",version:u?.version||"undefined",name:z.system.split("/").pop()||"unknown",url:z.system});if(z.valueSet)for(let Y of z.valueSet)$.push(L0(Y,void 0,u))}};if(D.compose.include)X(D.compose.include);if(D.compose.exclude)X(D.compose.exclude)}return E}class gD{manager;options;cacheConfig;cache;logger;constructor(D={},F){this.options={verbose:!1,...D},this.manager=hD({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 fetchPackage(D,F){this.logger.step(`Loading FHIR package: ${D}${F?`@${F}`:""}`),this.manager=hD({packages:[`${D}${F?`@${F}`:""}`],workingDir:"tmp/fhir"}),await this.manager.init();let u=await this.manager.search({}),B=u.filter((C)=>C.resourceType==="StructureDefinition"),E=u.filter((C)=>C.resourceType==="ValueSet");return this.logger.info(`Found ${B.length} StructureDefinitions and ${E.length} ValueSets in package`),{structureDefinitions:B,valueSets:E}}generateFhirSchemas(D){this.logger.progress(`Converting ${D.length} StructureDefinitions to FHIRSchemas`);let F=this.applyStructureDefinitionTreeshaking(D),u=[],B=0,E=0;for(let C of F)try{let $=N2(C);u.push($),B++,this.logger.debug(`Converted StructureDefinition: ${C.name||C.id} (${C.resourceType})`)}catch($){E++,this.logger.warn(`Failed to convert StructureDefinition ${C.name||C.id}: ${$ instanceof Error?$.message:String($)}`)}return this.logger.success(`FHIR Schema conversion completed: ${B}/${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 B=0,E=0;for(let C of D)try{let $=await Qu(C,this.manager,F);if($)u.push($),B++,this.logger.debug(`Converted ValueSet: ${C.name||C.id}`)}catch($){E++,this.logger.warn(`Failed to convert ValueSet ${C.name||C.id}: ${$ instanceof Error?$.message:String($)}`)}this.logger.success(`ValueSet conversion completed: ${B}/${D.length} successful, ${E} failed`)}return u}async generateFromPackage(D,F){if(await this.initializeCache(),this.cache&&!(this.cacheConfig?.forceRegenerate??!1)){let z=this.cache.getByPackage(D);if(z.length>0)return this.logger.info(`Using cached TypeSchemas for package: ${D} (${z.length} schemas)`),z}let u={name:D,version:F||"latest"},{valueSets:B,structureDefinitions:E}=await this.fetchPackage(D,F),C=this.generateFhirSchemas(E).map($u),$=await this.generateValueSetSchemas(B,u),Q=[...await this.generateResourceTypeSchemas(C),...$];if(this.cache)for(let z of Q)await this.cache.set(z);return Q}async generateResourceTypeSchemas(D){this.logger.info(`Transforming ${D.length} FHIR schemas to Type Schema`);let F=[];for(let u of D)F.push(...await Cu(this.manager,u));return F}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,B=new Map,E=new Map;for(let z of D){let Y=z.name||z.id;if(Y)u.set(Y,z),B.set(Y,new Set),E.set(Y,new Set)}for(let z of D){let Y=z.name||z.id;if(!Y)continue;let{realDeps:W,refTargets:J}=this.extractStructureDefinitionDependenciesWithReferences(z);B.set(Y,new Set(W)),E.set(Y,new Set(J))}let C=new Set;for(let z of F)if(u.has(z))C.add(z);else this.logger.warn(`ResourceType '${z}' not found in structure definitions`);let $=(z,Y=new Set)=>{if(Y.has(z)||!B.has(z))return;Y.add(z);let W=B.get(z)||new Set;for(let J of Array.from(W))if(u.has(J))C.add(J),$(J,Y)};for(let z of Array.from(C))$(z);let X=D.filter((z)=>{let Y=z.name||z.id;return Y&&C.has(Y)}),Q=new Set;for(let z of D){let Y=z.name||z.id;if(Y&&!C.has(Y)){if(Array.from(E.values()).some((J)=>J.has(Y)))Q.add(Y)}}if(Q.size>0)this.logger.info(`Excluded reference-only targets: ${Array.from(Q).join(", ")}`);return this.logger.success(`Treeshaking completed: kept ${X.length}/${D.length} structure definitions`),X}extractStructureDefinitionDependenciesWithReferences(D){let F=new Set,u=new Set;if(D.baseDefinition){let B=this.extractResourceNameFromUrl(D.baseDefinition);if(B)F.add(B)}if(D.snapshot?.element||D.differential?.element){let B=D.snapshot?.element||D.differential?.element;for(let E of B)if(E.type)for(let C of E.type){if(C.code){if(F.add(C.code),C.code==="Reference"&&C.targetProfile)for(let $ of C.targetProfile){let X=this.extractResourceNameFromUrl($);if(X)u.add(X)}}if(C.profile)for(let $ of C.profile){let X=this.extractResourceNameFromUrl($);if(X)F.add(X)}}}return{realDeps:Array.from(F),refTargets:Array.from(u)}}extractResourceNameFromUrl(D){let F=D.match(/\/([^/]+)$/);return F?F[1]??null:null}}import{readFile as P8}from"node:fs/promises";class T0{options;constructor(D={}){this.options={format:"auto",validate:!0,strict:!1,...D}}async parseFromFile(D){let F=await P8(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),B;if(u==="ndjson")B=this.parseNDJSON(D);else B=this.parseJSON(D);if(this.options.validate)this.validateSchemas(B);return B}async parseFromFiles(D){let F=[];for(let u of D){let B=await this.parseFromFile(u);F.push(...B)}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)}getDependencies(D){let F=[];if("base"in D&&D.base)F.push(D.base);if("dependencies"in D&&D.dependencies)F.push(...D.dependencies);if("fields"in D&&D.fields)for(let u of Object.values(D.fields)){if("type"in u&&u.type)F.push(u.type);if("binding"in u&&u.binding)F.push(u.binding);if("reference"in u&&u.reference)F.push(...u.reference)}if("nested"in D&&D.nested)for(let u of D.nested){F.push(u.identifier),F.push(u.base);for(let B of Object.values(u.fields)){if("type"in B&&B.type)F.push(B.type);if("binding"in B&&B.binding)F.push(B.binding);if("reference"in B&&B.reference)F.push(...B.reference)}}if("valueset"in D){let u=D;if(F.push(u.valueset),u.type)F.push(u.type)}return this.deduplicateDependencies(F)}resolveDependencies(D,F){let u=this.getDependencies(F),B=[];for(let E of u){let C=this.findByUrl(D,E.url);if(C)B.push(C)}return B}detectFormat(D,F){if(F){if(F.endsWith(".ndjson"))return"ndjson";if(F.endsWith(".json"))return"json"}let u=D.trim();if(u.includes(`
|
|
85
|
+
`;class s1{constructor(D,F,u,B){var E,C,$;this.yargs=D,this.usage=F,this.command=u,this.shim=B,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"))||((C=this.shim.getEnv("ZSH_NAME"))===null||C===void 0?void 0:C.includes("zsh")))!==null&&$!==void 0?$:!1}defaultCompletion(D,F,u,B){let E=this.command.getCommandHandlers();for(let $=0,X=D.length;$<X;++$)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 C=[];this.commandCompletions(C,D,u),this.optionCompletions(C,D,F,u),this.choicesFromOptionsCompletions(C,D,F,u),this.choicesFromPositionalsCompletions(C,D,F,u),B(null,C)}commandCompletions(D,F,u){let B=this.yargs.getInternalMethods().getContext().commands;if(!u.match(/^-/)&&B[B.length-1]!==u&&!this.previousArgHasChoices(F))this.usage.getCommands().forEach((E)=>{let C=PD(E[0]).cmd;if(F.indexOf(C)===-1)if(!this.zshShell)D.push(C);else{let $=E[1]||"";D.push(C.replace(/:/g,"\\:")+":"+$)}})}optionCompletions(D,F,u,B){if((B.match(/^-/)||B===""&&D.length===0)&&!this.previousArgHasChoices(F)){let E=this.yargs.getOptions(),C=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(E.key).forEach(($)=>{let X=!!E.configuration["boolean-negation"]&&E.boolean.includes($);if(!C.includes($)&&!E.hiddenOptions.includes($)&&!this.argsContainKey(F,$,X))this.completeOptionKey($,D,B,X&&!!E.default[$])})}}choicesFromOptionsCompletions(D,F,u,B){if(this.previousArgHasChoices(F)){let E=this.getPreviousArgChoices(F);if(E&&E.length>0)D.push(...E.map((C)=>C.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(D,F,u,B){if(B===""&&D.length>0&&this.previousArgHasChoices(F))return;let E=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],C=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),$=E[u._.length-C-1];if(!$)return;let X=this.yargs.getOptions().choices[$]||[];for(let Q of X)if(Q.startsWith(B))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 B=F.replace(/^-+/,""),E=this.yargs.getOptions(),C=[B,...this.yargs.getAliases()[B]||[]],$;for(let X of C)if(Object.prototype.hasOwnProperty.call(E.key,X)&&Array.isArray(E.choices[X])){$=E.choices[X];break}if($)return $.filter((X)=>!u||X.startsWith(u))}previousArgHasChoices(D){let F=this.getPreviousArgChoices(D);return F!==void 0&&F.length>0}argsContainKey(D,F,u){let B=(E)=>D.indexOf((/^[^0-9]$/.test(E)?"-":"--")+E)!==-1;if(B(F))return!0;if(u&&B(`no-${F}`))return!0;if(this.aliases){for(let E of this.aliases[F])if(B(E))return!0}return!1}completeOptionKey(D,F,u,B){var E,C,$,X;let Q=D;if(this.zshShell){let J=this.usage.getDescriptions(),M=(C=(E=this===null||this===void 0?void 0:this.aliases)===null||E===void 0?void 0:E[D])===null||C===void 0?void 0:C.find((P)=>{let c=J[P];return typeof c==="string"&&c.length>0}),q=M?J[M]:void 0,H=(X=($=J[D])!==null&&$!==void 0?$:q)!==null&&X!==void 0?X:"";Q=`${D.replace(/:/g,"\\:")}:${H.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let z=(J)=>/^--/.test(J),Y=(J)=>/^[^0-9]$/.test(J),W=!z(u)&&Y(D)?"-":"--";if(F.push(W+Q),B)F.push(W+"no-"+Q)}customCompletion(D,F,u,B){if(YD(this.customCompletionFunction,null,this.shim),x6(this.customCompletionFunction)){let E=this.customCompletionFunction(u,F);if(s(E))return E.then((C)=>{this.shim.process.nextTick(()=>{B(null,C)})}).catch((C)=>{this.shim.process.nextTick(()=>{B(C,void 0)})});return B(null,E)}else if(P6(this.customCompletionFunction))return this.customCompletionFunction(u,F,(E=B)=>this.defaultCompletion(D,F,u,E),(E)=>{B(null,E)});else return this.customCompletionFunction(u,F,(E)=>{B(null,E)})}getCompletion(D,F){let u=D.length?D[D.length-1]:"",B=this.yargs.parse(D,!0),E=this.customCompletionFunction?(C)=>this.customCompletion(D,C,u,F):(C)=>this.defaultCompletion(D,C,u,F);return s(B)?B.then(E):E(B)}generateCompletionScript(D,F){let u=this.zshShell?t1:i1,B=this.shim.path.basename(D);if(D.match(/\.js$/))D=`./${D}`;return u=u.replace(/{{app_name}}/g,B),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 r1(D,F,u,B){return new s1(D,F,u,B)}function x6(D){return D.length<3}function P6(D){return D.length>3}function a1(D,F){if(D.length===0)return F.length;if(F.length===0)return D.length;let u=[],B;for(B=0;B<=F.length;B++)u[B]=[B];let E;for(E=0;E<=D.length;E++)u[0][E]=E;for(B=1;B<=F.length;B++)for(E=1;E<=D.length;E++)if(F.charAt(B-1)===D.charAt(E-1))u[B][E]=u[B-1][E-1];else if(B>1&&E>1&&F.charAt(B-2)===D.charAt(E-1)&&F.charAt(B-1)===D.charAt(E-2))u[B][E]=u[B-2][E-2]+1;else u[B][E]=Math.min(u[B-1][E-1]+1,Math.min(u[B][E-1]+1,u[B-1][E]+1));return u[F.length][D.length]}var e1=["$0","--","_"];function D3(D,F,u){let B=u.y18n.__,E=u.y18n.__n,C={};C.nonOptionCount=function(W){let J=D.getDemandedCommands(),q=W._.length+(W["--"]?W["--"].length:0)-D.getInternalMethods().getContext().commands.length;if(J._&&(q<J._.min||q>J._.max)){if(q<J._.min)if(J._.minMsg!==void 0)F.fail(J._.minMsg?J._.minMsg.replace(/\$0/g,q.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",q,q.toString(),J._.min.toString()));else if(q>J._.max)if(J._.maxMsg!==void 0)F.fail(J._.maxMsg?J._.maxMsg.replace(/\$0/g,q.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",q,q.toString(),J._.max.toString()))}},C.positionalCount=function(W,J){if(J<W)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+"",W+""))},C.requiredArguments=function(W,J){let M=null;for(let q of Object.keys(J))if(!Object.prototype.hasOwnProperty.call(W,q)||typeof W[q]>"u")M=M||{},M[q]=J[q];if(M){let q=[];for(let P of Object.keys(M)){let c=M[P];if(c&&q.indexOf(c)<0)q.push(c)}let H=q.length?`
|
|
86
|
+
${q.join(`
|
|
87
|
+
`)}`:"";F.fail(E("Missing required argument: %s","Missing required arguments: %s",Object.keys(M).length,Object.keys(M).join(", ")+H))}},C.unknownArguments=function(W,J,M,q,H=!0){var P;let c=D.getInternalMethods().getCommandInstance().getCommands(),p=[],QD=D.getInternalMethods().getContext();if(Object.keys(W).forEach((h)=>{if(!e1.includes(h)&&!Object.prototype.hasOwnProperty.call(M,h)&&!Object.prototype.hasOwnProperty.call(D.getInternalMethods().getParseContext(),h)&&!C.isValidAndSomeAliasIsNotNew(h,J))p.push(h)}),H&&(QD.commands.length>0||c.length>0||q))W._.slice(QD.commands.length).forEach((h)=>{if(!c.includes(""+h))p.push(""+h)});if(H){let U=((P=D.getDemandedCommands()._)===null||P===void 0?void 0:P.max)||0,j=QD.commands.length+U;if(j<W._.length)W._.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((h)=>h.trim()?h:`"${h}"`).join(", ")))},C.unknownCommands=function(W){let J=D.getInternalMethods().getCommandInstance().getCommands(),M=[],q=D.getInternalMethods().getContext();if(q.commands.length>0||J.length>0)W._.slice(q.commands.length).forEach((H)=>{if(!J.includes(""+H))M.push(""+H)});if(M.length>0)return F.fail(E("Unknown command: %s","Unknown commands: %s",M.length,M.join(", "))),!0;else return!1},C.isValidAndSomeAliasIsNotNew=function(W,J){if(!Object.prototype.hasOwnProperty.call(J,W))return!1;let M=D.parsed.newAliases;return[W,...J[W]].some((q)=>!Object.prototype.hasOwnProperty.call(M,q)||!M[W])},C.limitedChoices=function(W){let J=D.getOptions(),M={};if(!Object.keys(J.choices).length)return;Object.keys(W).forEach((P)=>{if(e1.indexOf(P)===-1&&Object.prototype.hasOwnProperty.call(J.choices,P))[].concat(W[P]).forEach((c)=>{if(J.choices[P].indexOf(c)===-1&&c!==void 0)M[P]=(M[P]||[]).concat(c)})});let q=Object.keys(M);if(!q.length)return;let H=B("Invalid values:");q.forEach((P)=>{H+=`
|
|
88
|
+
${B("Argument: %s, Given: %s, Choices: %s",P,F.stringifiedValues(M[P]),F.stringifiedValues(J.choices[P]))}`}),F.fail(H)};let $={};C.implies=function(W,J){if(L("<string|object> [array|number|string]",[W,J],arguments.length),typeof W==="object")Object.keys(W).forEach((M)=>{C.implies(M,W[M])});else{if(D.global(W),!$[W])$[W]=[];if(Array.isArray(J))J.forEach((M)=>C.implies(W,M));else YD(J,void 0,u),$[W].push(J)}},C.getImplied=function(){return $};function X(Y,W){let J=Number(W);if(W=isNaN(J)?W:J,typeof W==="number")W=Y._.length>=W;else if(W.match(/^--no-.+/))W=W.match(/^--no-(.+)/)[1],W=!Object.prototype.hasOwnProperty.call(Y,W);else W=Object.prototype.hasOwnProperty.call(Y,W);return W}C.implications=function(W){let J=[];if(Object.keys($).forEach((M)=>{let q=M;($[M]||[]).forEach((H)=>{let P=q,c=H;if(P=X(W,P),H=X(W,H),P&&!H)J.push(` ${q} -> ${c}`)})}),J.length){let M=`${B("Implications failed:")}
|
|
89
|
+
`;J.forEach((q)=>{M+=q}),F.fail(M)}};let Q={};C.conflicts=function(W,J){if(L("<string|object> [array|string]",[W,J],arguments.length),typeof W==="object")Object.keys(W).forEach((M)=>{C.conflicts(M,W[M])});else{if(D.global(W),!Q[W])Q[W]=[];if(Array.isArray(J))J.forEach((M)=>C.conflicts(W,M));else Q[W].push(J)}},C.getConflicting=()=>Q,C.conflicting=function(W){if(Object.keys(W).forEach((J)=>{if(Q[J])Q[J].forEach((M)=>{if(M&&W[J]!==void 0&&W[M]!==void 0)F.fail(B("Arguments %s and %s are mutually exclusive",J,M))})}),D.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(Q).forEach((J)=>{Q[J].forEach((M)=>{if(M&&W[u.Parser.camelCase(J)]!==void 0&&W[u.Parser.camelCase(M)]!==void 0)F.fail(B("Arguments %s and %s are mutually exclusive",J,M))})})},C.recommendCommands=function(W,J){J=J.sort((P,c)=>c.length-P.length);let q=null,H=1/0;for(let P=0,c;(c=J[P])!==void 0;P++){let p=a1(W,c);if(p<=3&&p<H)H=p,q=c}if(q)F.fail(B("Did you mean %s?",q))},C.reset=function(W){return $=SD($,(J)=>!W[J]),Q=SD(Q,(J)=>!W[J]),C};let z=[];return C.freeze=function(){z.push({implied:$,conflicting:Q})},C.unfreeze=function(){let W=z.pop();YD(W,void 0,u),{implied:$,conflicting:Q}=W},C}var mF=[],_0;function V0(D,F,u,B){_0=B;let E={};if(Object.prototype.hasOwnProperty.call(D,"extends")){if(typeof D.extends!=="string")return E;let C=/\.json|\..*rc$/.test(D.extends),$=null;if(!C)try{$=import.meta.resolve(D.extends)}catch(X){return D}else $=v6(F,D.extends);S6($),mF.push($),E=C?JSON.parse(_0.readFileSync($,"utf8")):B.require(D.extends),delete D.extends,E=V0(E,_0.path.dirname($),u,_0)}return mF=[],u?F3(E,D):Object.assign({},E,D)}function S6(D){if(mF.indexOf(D)>-1)throw new DD(`Circular extended configurations: '${D}'.`)}function v6(D,F){return _0.path.resolve(D,F)}function F3(D,F){let u={};function B(E){return E&&typeof E==="object"&&!Array.isArray(E)}Object.assign(u,D);for(let E of Object.keys(F))if(B(F[E])&&B(u[E]))u[E]=F3(D[E],F[E]);else u[E]=F[E];return u}var N=function(D,F,u,B,E){if(B==="m")throw TypeError("Private method is not writable");if(B==="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 B==="a"?E.call(D,u):E?E.value=u:F.set(D,u),u},Z=function(D,F,u,B){if(u==="a"&&!B)throw TypeError("Private accessor was defined without a getter");if(typeof F==="function"?D!==F||!B:!F.has(D))throw TypeError("Cannot read private member from an object whose class did not declare it");return u==="m"?B:u==="a"?B.call(D):B?B.value:F.get(D)},FD,oD,K0,JD,GD,y0,fD,nD,d0,qD,h0,_D,ND,AD,VD,p0,iD,ZD,b,g0,m0,HD,tD,Y0,sD,kD,c0,k,rD,aD,eD,d,l0,TD,a;function V3(D){return(F=[],u=D.process.cwd(),B)=>{let E=new K3(F,u,B,D);return Object.defineProperty(E,"argv",{get:()=>{return E.parse()},enumerable:!0}),E.help(),E.version(),E}}var u3=Symbol("copyDoubleDash"),B3=Symbol("copyDoubleDash"),cF=Symbol("deleteFromParserHintObject"),E3=Symbol("emitWarning"),C3=Symbol("freeze"),$3=Symbol("getDollarZero"),D0=Symbol("getParserConfiguration"),X3=Symbol("getUsageConfiguration"),lF=Symbol("guessLocale"),Z3=Symbol("guessVersion"),Q3=Symbol("parsePositionalNumbers"),oF=Symbol("pkgUp"),yD=Symbol("populateParserHintArray"),J0=Symbol("populateParserHintSingleValueDictionary"),nF=Symbol("populateParserHintArrayDictionary"),iF=Symbol("populateParserHintDictionary"),tF=Symbol("sanitizeKey"),sF=Symbol("setKey"),rF=Symbol("unfreeze"),z3=Symbol("validateAsync"),O3=Symbol("getCommandInstance"),Y3=Symbol("getContext"),J3=Symbol("getHasOutput"),W3=Symbol("getLoggerInstance"),G3=Symbol("getParseContext"),A3=Symbol("getUsageInstance"),H3=Symbol("getValidationInstance"),o0=Symbol("hasParseCallback"),M3=Symbol("isGlobalContext"),F0=Symbol("postProcess"),q3=Symbol("rebase"),aF=Symbol("reset"),R0=Symbol("runYargsParserAndExecuteCommands"),eF=Symbol("runValidation"),_3=Symbol("setHasOutput"),u0=Symbol("kTrackManuallySetKeys"),f6="en_US";class K3{constructor(D=[],F,u,B){this.customScriptName=!1,this.parsed=!1,FD.set(this,void 0),oD.set(this,void 0),K0.set(this,{commands:[],fullCommands:[]}),JD.set(this,null),GD.set(this,null),y0.set(this,"show-hidden"),fD.set(this,null),nD.set(this,!0),d0.set(this,{}),qD.set(this,!0),h0.set(this,[]),_D.set(this,void 0),ND.set(this,{}),AD.set(this,!1),VD.set(this,null),p0.set(this,!0),iD.set(this,void 0),ZD.set(this,""),b.set(this,void 0),g0.set(this,void 0),m0.set(this,{}),HD.set(this,null),tD.set(this,null),Y0.set(this,{}),sD.set(this,{}),kD.set(this,void 0),c0.set(this,!1),k.set(this,void 0),rD.set(this,!1),aD.set(this,!1),eD.set(this,!1),d.set(this,void 0),l0.set(this,{}),TD.set(this,null),a.set(this,void 0),N(this,k,B,"f"),N(this,kD,D,"f"),N(this,oD,F,"f"),N(this,g0,u,"f"),N(this,_D,new pF(this),"f"),this.$0=this[$3](),this[aF](),N(this,FD,Z(this,FD,"f"),"f"),N(this,d,Z(this,d,"f"),"f"),N(this,a,Z(this,a,"f"),"f"),N(this,b,Z(this,b,"f"),"f"),Z(this,b,"f").showHiddenOpt=Z(this,y0,"f"),N(this,iD,this[B3](),"f"),Z(this,k,"f").y18n.setLocale(f6)}addHelpOpt(D,F){if(L("[string|boolean] [string]",[D,F],arguments.length),Z(this,VD,"f"))this[cF](Z(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(Z(this,VD,"f")),this.describe(Z(this,VD,"f"),F||Z(this,d,"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:Z(this,y0,"f");return this.boolean(u),this.describe(u,F||Z(this,d,"f").deferY18nLookup("Show hidden options")),Z(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[nF](this.alias.bind(this),"alias",D,F),this}array(D){return L("<array|string>",[D],arguments.length),this[yD]("array",D),this[u0](D),this}boolean(D){return L("<array|string>",[D],arguments.length),this[yD]("boolean",D),this[u0](D),this}check(D,F){return L("<function> [boolean]",[D,F],arguments.length),this.middleware((u,B)=>{return lD(()=>{return D(u,B.getOptions())},(E)=>{if(!E)Z(this,d,"f").fail(Z(this,k,"f").y18n.__("Argument check failed: %s",D.toString()));else if(typeof E==="string"||E instanceof Error)Z(this,d,"f").fail(E.toString(),E);return u},(E)=>{return Z(this,d,"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[nF](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 B of D)this.coerce(B,F);return this}else if(typeof D==="object"){for(let B of Object.keys(D))this.coerce(B,D[B]);return this}if(!F)throw new DD("coerce callback must be provided");let u=D;return Z(this,b,"f").key[u]=!0,Z(this,_D,"f").addCoerceMiddleware((B,E)=>{var C;let $=(C=E.getAliases()[u])!==null&&C!==void 0?C:[],X=[u,...$].filter((Q)=>Object.prototype.hasOwnProperty.call(B,Q));if(X.length===0)return B;return lD(()=>{return F(B[X[0]])},(Q)=>{return X.forEach((z)=>{B[z]=Q}),B},(Q)=>{throw new DD(Q.message)})},u),this}conflicts(D,F){return L("<string|object> [string|array]",[D,F],arguments.length),Z(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,Z(this,oD,"f"),this[D0]()["deep-merge-config"]||!1,Z(this,k,"f")),Z(this,b,"f").configObjects=(Z(this,b,"f").configObjects||[]).concat(D),this;if(typeof F==="function")u=F,F=void 0;return this.describe(D,F||Z(this,d,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(D)?D:[D]).forEach((B)=>{Z(this,b,"f").config[B]=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,GD,D||Z(this,GD,"f")||"completion","f"),!F&&F!==!1)F="generate completion script";if(this.command(Z(this,GD,"f"),F),u)Z(this,JD,"f").registerFunction(u);return this}command(D,F,u,B,E,C){return L("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[D,F,u,B,E,C],arguments.length),Z(this,FD,"f").addHandler(D,F,u,B,E,C),this}commands(D,F,u,B,E,C){return this.command(D,F,u,B,E,C)}commandDir(D,F){L("<string> [object]",[D,F],arguments.length);let u=Z(this,g0,"f")||Z(this,k,"f").require;return Z(this,FD,"f").addDirectory(D,u,Z(this,k,"f").getCallerFile(),F),this}count(D){return L("<array|string>",[D],arguments.length),this[yD]("count",D),this[u0](D),this}default(D,F,u){if(L("<object|string|array> [*] [string]",[D,F,u],arguments.length),u)hF(D,Z(this,k,"f")),Z(this,b,"f").defaultDescription[D]=u;if(typeof F==="function"){if(hF(D,Z(this,k,"f")),!Z(this,b,"f").defaultDescription[D])Z(this,b,"f").defaultDescription[D]=Z(this,d,"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,B){if(L("[number] [number|string] [string|null|undefined] [string|null|undefined]",[D,F,u,B],arguments.length),typeof F!=="number")u=F,F=1/0;return this.global("_",!1),Z(this,b,"f").demandedCommands._={min:D,max:F,minMsg:u,maxMsg:B},this}demand(D,F,u){if(Array.isArray(F))F.forEach((B)=>{YD(u,!0,Z(this,k,"f")),this.demandOption(B,u)}),F=1/0;else if(typeof F!=="number")u=F,F=1/0;if(typeof D==="number")YD(u,!0,Z(this,k,"f")),this.demandCommand(D,F,u,u);else if(Array.isArray(D))D.forEach((B)=>{YD(u,!0,Z(this,k,"f")),this.demandOption(B,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),Z(this,b,"f").deprecatedOptions[D]=F,this}describe(D,F){return L("<object|string|array> [string]",[D,F],arguments.length),this[sF](D,!0),Z(this,d,"f").describe(D,F),this}detectLocale(D){return L("<boolean>",[D],arguments.length),N(this,nD,D,"f"),this}env(D){if(L("[string|boolean]",[D],arguments.length),D===!1)delete Z(this,b,"f").envPrefix;else Z(this,b,"f").envPrefix=D||"";return this}epilogue(D){return L("<string>",[D],arguments.length),Z(this,d,"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 Z(this,d,"f").example(D,F);return this}exit(D,F){if(N(this,AD,!0,"f"),N(this,fD,F,"f"),Z(this,qD,"f"))Z(this,k,"f").process.exit(D)}exitProcess(D=!0){return L("[boolean]",[D],arguments.length),N(this,qD,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 Z(this,d,"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,B)=>{Z(this,JD,"f").getCompletion(D,(E,C)=>{if(E)B(E);else u(C)})});else return Z(this,JD,"f").getCompletion(D,F)}getDemandedOptions(){return L([],0),Z(this,b,"f").demandedOptions}getDemandedCommands(){return L([],0),Z(this,b,"f").demandedCommands}getDeprecatedOptions(){return L([],0),Z(this,b,"f").deprecatedOptions}getDetectLocale(){return Z(this,nD,"f")}getExitProcess(){return Z(this,qD,"f")}getGroups(){return Object.assign({},Z(this,ND,"f"),Z(this,sD,"f"))}getHelp(){if(N(this,AD,!0,"f"),!Z(this,d,"f").hasCachedHelpMessage()){if(!this.parsed){let F=this[R0](Z(this,kD,"f"),void 0,void 0,0,!0);if(s(F))return F.then(()=>{return Z(this,d,"f").help()})}let D=Z(this,FD,"f").runDefaultBuilderOn(this);if(s(D))return D.then(()=>{return Z(this,d,"f").help()})}return Promise.resolve(Z(this,d,"f").help())}getOptions(){return Z(this,b,"f")}getStrict(){return Z(this,rD,"f")}getStrictCommands(){return Z(this,aD,"f")}getStrictOptions(){return Z(this,eD,"f")}global(D,F){if(L("<string|array> [boolean]",[D,F],arguments.length),D=[].concat(D),F!==!1)Z(this,b,"f").local=Z(this,b,"f").local.filter((u)=>D.indexOf(u)===-1);else D.forEach((u)=>{if(!Z(this,b,"f").local.includes(u))Z(this,b,"f").local.push(u)});return this}group(D,F){L("<string|array> <string>",[D,F],arguments.length);let u=Z(this,sD,"f")[F]||Z(this,ND,"f")[F];if(Z(this,sD,"f")[F])delete Z(this,sD,"f")[F];let B={};return Z(this,ND,"f")[F]=(u||[]).concat(D).filter((E)=>{if(B[E])return!1;return B[E]=!0}),this}hide(D){return L("<string>",[D],arguments.length),Z(this,b,"f").hiddenOptions.push(D),this}implies(D,F){return L("<string|object> [number|string|array]",[D,F],arguments.length),Z(this,a,"f").implies(D,F),this}locale(D){if(L("[string]",[D],arguments.length),D===void 0)return this[lF](),Z(this,k,"f").y18n.getLocale();return N(this,nD,!1,"f"),Z(this,k,"f").y18n.setLocale(D),this}middleware(D,F,u){return Z(this,_D,"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[yD]("normalize",D),this}number(D){return L("<array|string>",[D],arguments.length),this[yD]("number",D),this[u0](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[u0](D),Z(this,TD,"f")&&(D==="version"||(F===null||F===void 0?void 0:F.alias)==="version"))this[E3](['"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(Z(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 B=F.demand||F.required||F.require;if(B)this.demand(D,B);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)Z(this,b,"f").defaultDescription[D]=F.defaultDescription;if(F.skipValidation)this.skipValidation(D);let E=F.describe||F.description||F.desc,C=Z(this,d,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(C,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[C3](),typeof D>"u")D=Z(this,kD,"f");if(typeof F==="object")N(this,tD,F,"f"),F=u;if(typeof F==="function")N(this,HD,F,"f"),F=!1;if(!F)N(this,kD,D,"f");if(Z(this,HD,"f"))N(this,qD,!1,"f");let B=this[R0](D,!!F),E=this.parsed;if(Z(this,JD,"f").setParsed(this.parsed),s(B))return B.then((C)=>{if(Z(this,HD,"f"))Z(this,HD,"f").call(this,Z(this,fD,"f"),C,Z(this,ZD,"f"));return C}).catch((C)=>{if(Z(this,HD,"f"))Z(this,HD,"f")(C,this.parsed.argv,Z(this,ZD,"f"));throw C}).finally(()=>{this[rF](),this.parsed=E});else{if(Z(this,HD,"f"))Z(this,HD,"f").call(this,Z(this,fD,"f"),B,Z(this,ZD,"f"));this[rF](),this.parsed=E}return B}parseAsync(D,F,u){let B=this.parse(D,F,u);return!s(B)?Promise.resolve(B):B}parseSync(D,F,u){let B=this.parse(D,F,u);if(s(B))throw new DD(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return B}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,B=this[oF](F||Z(this,oD,"f"));if(B[D]&&typeof B[D]==="object")u=V0(B[D],F||Z(this,oD,"f"),this[D0]()["deep-merge-config"]||!1,Z(this,k,"f")),Z(this,b,"f").configObjects=(Z(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=SD(F,(C,$)=>{if(C==="type"&&!["string","number","boolean"].includes($))return!1;return u.includes(C)});let B=Z(this,K0,"f").fullCommands[Z(this,K0,"f").fullCommands.length-1],E=B?Z(this,FD,"f").cmdToParseOptions(B):{array:[],alias:{},default:{},demand:{}};return z0(E).forEach((C)=>{let $=E[C];if(Array.isArray($)){if($.indexOf(D)!==-1)F[C]=!0}else if($[D]&&!(C in F))F[C]=$[D]}),this.group(D,Z(this,d,"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"&&Z(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,Z(this,iD,"f").log(Z(this,JD,"f").generateCompletionScript(D,F||Z(this,GD,"f")||"completion")),this}showHelp(D){if(L("[string|function]",[D],arguments.length),N(this,AD,!0,"f"),!Z(this,d,"f").hasCachedHelpMessage()){if(!this.parsed){let u=this[R0](Z(this,kD,"f"),void 0,void 0,0,!0);if(s(u))return u.then(()=>{Z(this,d,"f").showHelp(D)}),this}let F=Z(this,FD,"f").runDefaultBuilderOn(this);if(s(F))return F.then(()=>{Z(this,d,"f").showHelp(D)}),this}return Z(this,d,"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),Z(this,d,"f").showHelpOnFail(D,F),this}showVersion(D){return L("[string|function]",[D],arguments.length),Z(this,d,"f").showVersion(D),this}skipValidation(D){return L("<array|string>",[D],arguments.length),this[yD]("skipValidation",D),this}strict(D){return L("[boolean]",[D],arguments.length),N(this,rD,D!==!1,"f"),this}strictCommands(D){return L("[boolean]",[D],arguments.length),N(this,aD,D!==!1,"f"),this}strictOptions(D){return L("[boolean]",[D],arguments.length),N(this,eD,D!==!1,"f"),this}string(D){return L("<array|string>",[D],arguments.length),this[yD]("string",D),this[u0](D),this}terminalWidth(){return L([],0),Z(this,k,"f").process.stdColumns}updateLocale(D){return this.updateStrings(D)}updateStrings(D){return L("<object>",[D],arguments.length),N(this,nD,!1,"f"),Z(this,k,"f").y18n.updateLocale(D),this}usage(D,F,u,B){if(L("<string|null|undefined> [string|boolean] [function|object] [function]",[D,F,u,B],arguments.length),F!==void 0)if(YD(D,null,Z(this,k,"f")),(D||"").match(/^\$0( |$)/))return this.command(D,F,u,B);else throw new DD(".usage() description must start with $0 if being used as alias for .command()");else return Z(this,d,"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),Z(this,TD,"f"))this[cF](Z(this,TD,"f")),Z(this,d,"f").version(void 0),N(this,TD,null,"f");if(arguments.length===0)u=this[Z3](),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||Z(this,d,"f").deferY18nLookup("Show version number"),Z(this,d,"f").version(u||void 0),this.boolean(Z(this,TD,"f")),this.describe(Z(this,TD,"f"),F),this}wrap(D){return L("<number|null|undefined>",[D],arguments.length),Z(this,d,"f").wrap(D),this}[(FD=new WeakMap,oD=new WeakMap,K0=new WeakMap,JD=new WeakMap,GD=new WeakMap,y0=new WeakMap,fD=new WeakMap,nD=new WeakMap,d0=new WeakMap,qD=new WeakMap,h0=new WeakMap,_D=new WeakMap,ND=new WeakMap,AD=new WeakMap,VD=new WeakMap,p0=new WeakMap,iD=new WeakMap,ZD=new WeakMap,b=new WeakMap,g0=new WeakMap,m0=new WeakMap,HD=new WeakMap,tD=new WeakMap,Y0=new WeakMap,sD=new WeakMap,kD=new WeakMap,c0=new WeakMap,k=new WeakMap,rD=new WeakMap,aD=new WeakMap,eD=new WeakMap,d=new WeakMap,l0=new WeakMap,TD=new WeakMap,a=new WeakMap,u3)](D){if(!D._||!D["--"])return D;D._.push.apply(D._,D["--"]);try{delete D["--"]}catch(F){}return D}[B3](){return{log:(...D)=>{if(!this[o0]())console.log(...D);if(N(this,AD,!0,"f"),Z(this,ZD,"f").length)N(this,ZD,Z(this,ZD,"f")+`
|
|
91
|
+
`,"f");N(this,ZD,Z(this,ZD,"f")+D.join(" "),"f")},error:(...D)=>{if(!this[o0]())console.error(...D);if(N(this,AD,!0,"f"),Z(this,ZD,"f").length)N(this,ZD,Z(this,ZD,"f")+`
|
|
92
|
+
`,"f");N(this,ZD,Z(this,ZD,"f")+D.join(" "),"f")}}}[cF](D){z0(Z(this,b,"f")).forEach((F)=>{if(((B)=>B==="configObjects")(F))return;let u=Z(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 Z(this,d,"f").getDescriptions()[D]}[E3](D,F,u){if(!Z(this,d0,"f")[u])Z(this,k,"f").process.emitWarning(D,F),Z(this,d0,"f")[u]=!0}[C3](){Z(this,h0,"f").push({options:Z(this,b,"f"),configObjects:Z(this,b,"f").configObjects.slice(0),exitProcess:Z(this,qD,"f"),groups:Z(this,ND,"f"),strict:Z(this,rD,"f"),strictCommands:Z(this,aD,"f"),strictOptions:Z(this,eD,"f"),completionCommand:Z(this,GD,"f"),output:Z(this,ZD,"f"),exitError:Z(this,fD,"f"),hasOutput:Z(this,AD,"f"),parsed:this.parsed,parseFn:Z(this,HD,"f"),parseContext:Z(this,tD,"f")}),Z(this,d,"f").freeze(),Z(this,a,"f").freeze(),Z(this,FD,"f").freeze(),Z(this,_D,"f").freeze()}[$3](){let D="",F;if(/\b(node|iojs|electron)(\.exe)?$/.test(Z(this,k,"f").process.argv()[0]))F=Z(this,k,"f").process.argv().slice(1,2);else F=Z(this,k,"f").process.argv().slice(0,1);if(D=F.map((u)=>{let B=this[q3](Z(this,oD,"f"),u);return u.match(/^(\/|([a-zA-Z]:)?\\)/)&&B.length<u.length?B:u}).join(" ").trim(),Z(this,k,"f").getEnv("_")&&Z(this,k,"f").getProcessArgvBin()===Z(this,k,"f").getEnv("_"))D=Z(this,k,"f").getEnv("_").replace(`${Z(this,k,"f").path.dirname(Z(this,k,"f").process.execPath())}/`,"");return D}[D0](){return Z(this,m0,"f")}[X3](){return Z(this,l0,"f")}[lF](){if(!Z(this,nD,"f"))return;let D=Z(this,k,"f").getEnv("LC_ALL")||Z(this,k,"f").getEnv("LC_MESSAGES")||Z(this,k,"f").getEnv("LANG")||Z(this,k,"f").getEnv("LANGUAGE")||"en_US";this.locale(D.replace(/[.:].*/,""))}[Z3](){return this[oF]().version||"unknown"}[Q3](D){let F=D["--"]?D["--"]:D._;for(let u=0,B;(B=F[u])!==void 0;u++)if(Z(this,k,"f").Parser.looksLikeNumber(B)&&Number.isSafeInteger(Math.floor(parseFloat(`${B}`))))F[u]=Number(B);return D}[oF](D){let F=D||"*";if(Z(this,Y0,"f")[F])return Z(this,Y0,"f")[F];let u={};try{let B=D||Z(this,k,"f").mainFilename;if(Z(this,k,"f").path.extname(B))B=Z(this,k,"f").path.dirname(B);let E=Z(this,k,"f").findUp(B,(C,$)=>{if($.includes("package.json"))return"package.json";else return});YD(E,void 0,Z(this,k,"f")),u=JSON.parse(Z(this,k,"f").readFileSync(E,"utf8"))}catch(B){}return Z(this,Y0,"f")[F]=u||{},Z(this,Y0,"f")[F]}[yD](D,F){F=[].concat(F),F.forEach((u)=>{u=this[tF](u),Z(this,b,"f")[D].push(u)})}[J0](D,F,u,B){this[iF](D,F,u,B,(E,C,$)=>{Z(this,b,"f")[E][C]=$})}[nF](D,F,u,B){this[iF](D,F,u,B,(E,C,$)=>{Z(this,b,"f")[E][C]=(Z(this,b,"f")[E][C]||[]).concat($)})}[iF](D,F,u,B,E){if(Array.isArray(u))u.forEach((C)=>{D(C,B)});else if(((C)=>typeof C==="object")(u))for(let C of z0(u))D(C,u[C]);else E(F,this[tF](u),B)}[tF](D){if(D==="__proto__")return"___proto___";return D}[sF](D,F){return this[J0](this[sF].bind(this),"key",D,F),this}[rF](){var D,F,u,B,E,C,$,X,Q,z,Y,W;let J=Z(this,h0,"f").pop();YD(J,void 0,Z(this,k,"f"));let M;D=this,F=this,u=this,B=this,E=this,C=this,$=this,X=this,Q=this,z=this,Y=this,W=this,{options:{set value(q){N(D,b,q,"f")}}.value,configObjects:M,exitProcess:{set value(q){N(F,qD,q,"f")}}.value,groups:{set value(q){N(u,ND,q,"f")}}.value,output:{set value(q){N(B,ZD,q,"f")}}.value,exitError:{set value(q){N(E,fD,q,"f")}}.value,hasOutput:{set value(q){N(C,AD,q,"f")}}.value,parsed:this.parsed,strict:{set value(q){N($,rD,q,"f")}}.value,strictCommands:{set value(q){N(X,aD,q,"f")}}.value,strictOptions:{set value(q){N(Q,eD,q,"f")}}.value,completionCommand:{set value(q){N(z,GD,q,"f")}}.value,parseFn:{set value(q){N(Y,HD,q,"f")}}.value,parseContext:{set value(q){N(W,tD,q,"f")}}.value}=J,Z(this,b,"f").configObjects=M,Z(this,d,"f").unfreeze(),Z(this,a,"f").unfreeze(),Z(this,FD,"f").unfreeze(),Z(this,_D,"f").unfreeze()}[z3](D,F){return lD(F,(u)=>{return D(u),u})}getInternalMethods(){return{getCommandInstance:this[O3].bind(this),getContext:this[Y3].bind(this),getHasOutput:this[J3].bind(this),getLoggerInstance:this[W3].bind(this),getParseContext:this[G3].bind(this),getParserConfiguration:this[D0].bind(this),getUsageConfiguration:this[X3].bind(this),getUsageInstance:this[A3].bind(this),getValidationInstance:this[H3].bind(this),hasParseCallback:this[o0].bind(this),isGlobalContext:this[M3].bind(this),postProcess:this[F0].bind(this),reset:this[aF].bind(this),runValidation:this[eF].bind(this),runYargsParserAndExecuteCommands:this[R0].bind(this),setHasOutput:this[_3].bind(this)}}[O3](){return Z(this,FD,"f")}[Y3](){return Z(this,K0,"f")}[J3](){return Z(this,AD,"f")}[W3](){return Z(this,iD,"f")}[G3](){return Z(this,tD,"f")||{}}[A3](){return Z(this,d,"f")}[H3](){return Z(this,a,"f")}[o0](){return!!Z(this,HD,"f")}[M3](){return Z(this,p0,"f")}[F0](D,F,u,B){if(u)return D;if(s(D))return D;if(!F)D=this[u3](D);if(this[D0]()["parse-positional-numbers"]||this[D0]()["parse-positional-numbers"]===void 0)D=this[Q3](D);if(B)D=cD(D,this,Z(this,_D,"f").getMiddleware(),!1);return D}[aF](D={}){N(this,b,Z(this,b,"f")||{},"f");let F={};F.local=Z(this,b,"f").local||[],F.configObjects=Z(this,b,"f").configObjects||[];let u={};F.local.forEach((C)=>{u[C]=!0,(D[C]||[]).forEach(($)=>{u[$]=!0})}),Object.assign(Z(this,sD,"f"),Object.keys(Z(this,ND,"f")).reduce((C,$)=>{let X=Z(this,ND,"f")[$].filter((Q)=>!(Q in u));if(X.length>0)C[$]=X;return C},{})),N(this,ND,{},"f");let B=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],E=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(B.forEach((C)=>{F[C]=(Z(this,b,"f")[C]||[]).filter(($)=>!u[$])}),E.forEach((C)=>{F[C]=SD(Z(this,b,"f")[C],($)=>!u[$])}),F.envPrefix=Z(this,b,"f").envPrefix,N(this,b,F,"f"),N(this,d,Z(this,d,"f")?Z(this,d,"f").reset(u):n1(this,Z(this,k,"f")),"f"),N(this,a,Z(this,a,"f")?Z(this,a,"f").reset(u):D3(this,Z(this,d,"f"),Z(this,k,"f")),"f"),N(this,FD,Z(this,FD,"f")?Z(this,FD,"f").reset():c1(Z(this,d,"f"),Z(this,a,"f"),Z(this,_D,"f"),Z(this,k,"f")),"f"),!Z(this,JD,"f"))N(this,JD,r1(this,Z(this,d,"f"),Z(this,FD,"f"),Z(this,k,"f")),"f");return Z(this,_D,"f").reset(),N(this,GD,null,"f"),N(this,ZD,"","f"),N(this,fD,null,"f"),N(this,AD,!1,"f"),this.parsed=!1,this}[q3](D,F){return Z(this,k,"f").path.relative(D,F)}[R0](D,F,u,B=0,E=!1){var C,$,X,Q;let z=!!u||E;D=D||Z(this,kD,"f"),Z(this,b,"f").__=Z(this,k,"f").y18n.__,Z(this,b,"f").configuration=this[D0]();let Y=!!Z(this,b,"f").configuration["populate--"],W=Object.assign({},Z(this,b,"f").configuration,{"populate--":!0}),J=Z(this,k,"f").Parser.detailed(D,Object.assign({},Z(this,b,"f"),{configuration:{"parse-positional-numbers":!1,...W}})),M=Object.assign(J.argv,Z(this,tD,"f")),q=void 0,H=J.aliases,P=!1,c=!1;if(Object.keys(M).forEach((p)=>{if(p===Z(this,VD,"f")&&M[p])P=!0;else if(p===Z(this,TD,"f")&&M[p])c=!0}),M.$0=this.$0,this.parsed=J,B===0)Z(this,d,"f").clearCachedHelpMessage();try{if(this[lF](),F)return this[F0](M,Y,!!u,!1);if(Z(this,VD,"f")){if([Z(this,VD,"f")].concat(H[Z(this,VD,"f")]||[]).filter((j)=>j.length>1).includes(""+M._[M._.length-1]))M._.pop(),P=!0}N(this,p0,!1,"f");let p=Z(this,FD,"f").getCommands(),QD=((C=Z(this,JD,"f"))===null||C===void 0?void 0:C.completionKey)?[($=Z(this,JD,"f"))===null||$===void 0?void 0:$.completionKey,...(Q=this.getAliases()[(X=Z(this,JD,"f"))===null||X===void 0?void 0:X.completionKey])!==null&&Q!==void 0?Q:[]].some((U)=>Object.prototype.hasOwnProperty.call(M,U)):!1,h=P||QD||E;if(M._.length){if(p.length){let U;for(let j=B||0,S;M._[j]!==void 0;j++)if(S=String(M._[j]),p.includes(S)&&S!==Z(this,GD,"f")){let l=Z(this,FD,"f").runCommand(S,this,J,j+1,E,P||c||E);return this[F0](l,Y,!!u,!1)}else if(!U&&S!==Z(this,GD,"f")){U=S;break}if(!Z(this,FD,"f").hasDefaultCommand()&&Z(this,c0,"f")&&U&&!h)Z(this,a,"f").recommendCommands(U,p)}if(Z(this,GD,"f")&&M._.includes(Z(this,GD,"f"))&&!QD){if(Z(this,qD,"f"))vD(!0);this.showCompletionScript(),this.exit(0)}}if(Z(this,FD,"f").hasDefaultCommand()&&!h){let U=Z(this,FD,"f").runCommand(null,this,J,0,E,P||c||E);return this[F0](U,Y,!!u,!1)}if(QD){if(Z(this,qD,"f"))vD(!0);D=[].concat(D);let U=D.slice(D.indexOf(`--${Z(this,JD,"f").completionKey}`)+1);return Z(this,JD,"f").getCompletion(U,(j,S)=>{if(j)throw new DD(j.message);(S||[]).forEach((l)=>{Z(this,iD,"f").log(l)}),this.exit(0)}),this[F0](M,!Y,!!u,!1)}if(!Z(this,AD,"f")){if(P){if(Z(this,qD,"f"))vD(!0);z=!0,this.showHelp((U)=>{Z(this,iD,"f").log(U),this.exit(0)})}else if(c){if(Z(this,qD,"f"))vD(!0);z=!0,Z(this,d,"f").showVersion("log"),this.exit(0)}}if(!z&&Z(this,b,"f").skipValidation.length>0)z=Object.keys(M).some((U)=>Z(this,b,"f").skipValidation.indexOf(U)>=0&&M[U]===!0);if(!z){if(J.error)throw new DD(J.error.message);if(!QD){let U=this[eF](H,{},J.error);if(!u)q=cD(M,this,Z(this,_D,"f").getMiddleware(),!0);if(q=this[z3](U,q!==null&&q!==void 0?q:M),s(q)&&!u)q=q.then(()=>{return cD(M,this,Z(this,_D,"f").getMiddleware(),!1)})}}}catch(p){if(p instanceof DD)Z(this,d,"f").fail(p.message,p);else throw p}return this[F0](q!==null&&q!==void 0?q:M,Y,!!u,!0)}[eF](D,F,u,B){let E={...this.getDemandedOptions()};return(C)=>{if(u)throw new DD(u.message);Z(this,a,"f").nonOptionCount(C),Z(this,a,"f").requiredArguments(C,E);let $=!1;if(Z(this,aD,"f"))$=Z(this,a,"f").unknownCommands(C);if(Z(this,rD,"f")&&!$)Z(this,a,"f").unknownArguments(C,D,F,!!B);else if(Z(this,eD,"f"))Z(this,a,"f").unknownArguments(C,D,{},!1,!1);Z(this,a,"f").limitedChoices(C),Z(this,a,"f").implications(C),Z(this,a,"f").conflicting(C)}}[_3](){N(this,AD,!0,"f")}[u0](D){if(typeof D==="string")Z(this,b,"f").key[D]=!0;else for(let F of D)Z(this,b,"f").key[F]=!0}}function l1(D){return!!D&&typeof D.getInternalMethods==="function"}var k6=V3(dF),R3=k6;import{performance as I3}from"node:perf_hooks";var dD=b0(F2(),1);class p6{total;message;current=0;barLength=30;startTime=I3.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(I3.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),B=this.barLength-u,E=dD.default.green("█".repeat(u))+dD.default.gray("░".repeat(B)),C=`${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(C)} ${dD.default.yellow(`${F}%`)}${$}`),this.current===this.total)process.stdout.write(`
|
|
93
|
+
`)}}var $D=b0(F2(),1);class t0{options;constructor(D={}){this.options={timestamp:!1,verbose:!1,...D}}formatMessage(D,F,u){let B=this.options.timestamp?`${$D.default.gray(new Date().toLocaleTimeString())} `:"",E=this.options.prefix?`${$D.default.cyan(`[${this.options.prefix}]`)} `:"";return`${B}${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())} `:"",B=this.options.prefix?`${$D.default.cyan(`[${this.options.prefix}]`)} `:"";console.log(`${u}${B}${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 B0=new t0;function s0(D){B0.success(D)}function KD(D,F){B0.error(D,F)}function u2(D){B0.warn(D)}function r0(D){B0.info(D)}function B2(D){B0.step(D)}function L3(D){B0.dim(D)}function E2(D){B0.configure(D)}function jD(D={}){return new t0(D)}function C2(D){console.log(),console.log($D.default.cyan($D.default.bold(`━━━ ${D} ━━━`)))}function $2(D,F,u){let B=D;if(F)B+=` ${$D.default.gray(`(${F}ms)`)}`;if(s0(B),u)Object.entries(u).forEach(([E,C])=>{L3(` ${E}: ${C}`)})}function E0(D,F="•"){D.forEach((u)=>{console.log($D.default.gray(` ${F} ${u}`))})}import{existsSync as c8}from"node:fs";import{resolve as l8}from"node:path";import{existsSync as a0,mkdirSync as N3}from"node:fs";import{readdir as T3,readFile as g6,stat as m6,unlink as w3,writeFile as c6}from"node:fs/promises";import{join as X2}from"node:path";class C0{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))N3(this.cacheDir,{recursive:!0});await this.loadFromDisk()}}async loadFromDisk(){if(!this.cacheDir||!a0(this.cacheDir))return;try{let F=(await T3(this.cacheDir)).filter((u)=>u.endsWith(".typeschema.json"));for(let u of F){let B=X2(this.cacheDir,u),E=await m6(B);if(this.config.maxAge){if(Date.now()-E.mtimeMs>this.config.maxAge){await w3(B);continue}}try{let C=await g6(B,"utf-8"),$=JSON.parse(C);if(this.config.validateCached){if(!$.schema?.identifier)continue}let X=this.generateKey($.schema.identifier);this.cache.set(X,$.schema)}catch(C){console.warn(`Failed to load cached schema from ${u}:`,C)}}}catch(D){console.warn("Failed to load cached schemas from disk:",D)}}async persistSchema(D){if(!this.cacheDir)return;if(!a0(this.cacheDir))N3(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,"_"),B=X2(this.cacheDir,u);try{await c6(B,JSON.stringify(F,null,2),"utf-8")}catch(E){console.warn(`Failed to persist schema to ${B}:`,E)}}async clearDisk(){if(!this.cacheDir||!a0(this.cacheDir))return;try{let F=(await T3(this.cacheDir)).filter((u)=>u.endsWith(".typeschema.json"));for(let u of F)await w3(X2(this.cacheDir,u))}catch(D){console.warn("Failed to clear cache directory:",D)}}}import{createHash as l6}from"crypto";var Z2=(D)=>{let F=`${D.packageName}@${D.packageVersion}:${D.filePath}`;return l6("sha256").update(F).digest("base64url")};var W0=()=>{let D={},F={};return{generateId:Z2,get:(E)=>D[E],set:(E,C)=>{if(D[E]=C,C.url){if(!F[C.url])F[C.url]=[];let $=F[C.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,C)=>({id:E,resourceType:C.resourceType}),getAllReferences:()=>D}};import*as V2 from"path";import*as g3 from"fs/promises";var b3="https://fs.get-ig.org/pkgs/";import*as e0 from"fs/promises";import*as x3 from"path";var G0=async(D)=>{try{return await e0.access(D),!0}catch{return!1}},A0=async(D)=>{try{await e0.mkdir(D,{recursive:!0})}catch{}},DF=async(D)=>{let F=x3.join(D,".index.json");return G0(F)};import{exec as o6}from"child_process";import{promisify as n6}from"util";var P3=n6(o6);async function Q2(){try{return await P3("bun --version"),"bun"}catch{try{return await P3("npm --version"),"npm"}catch{return null}}}import*as v3 from"fs/promises";import*as f3 from"path";import{exec as i6}from"child_process";import{promisify as t6}from"util";var S3=t6(i6),FF=async(D,F,u)=>{await A0(F);let B=f3.join(F,"package.json");if(!await G0(B))await v3.writeFile(B,JSON.stringify({name:"fhir-canonical-manager-workspace",version:"1.0.0",private:!0,dependencies:{}},null,2));let E=await Q2();if(!E)throw Error("No package manager found. Please install npm or bun.");for(let C of D)try{if(E==="bun"){let $={...process.env,HOME:F,NPM_CONFIG_USERCONFIG:"/dev/null"},X=u?`cd ${F} && bun add ${C} --registry ${u}`:`cd ${F} && bun add ${C}`;await S3(X,{env:$,maxBuffer:10485760})}else{let $=u?`cd ${F} && npm add ${C} --registry ${u}`:`cd ${F} && npm add ${C}`;await S3($,{maxBuffer:10485760})}}catch($){throw console.error(`Failed to install package ${C}:`,$),$}};var uF=()=>{let D=W0();return{entries:{},packages:{},references:{},referenceManager:D}};import*as BF from"fs/promises";import*as Y2 from"path";import*as z2 from"fs/promises";import*as O2 from"path";import{createHash as k3}from"crypto";var U0=async(D)=>{try{let F=O2.join(D,"package-lock.json");try{let u=await z2.readFile(F,"utf-8");return k3("sha256").update(u).digest("hex")}catch{let u=O2.join(D,"bun.lock"),B=await z2.readFile(u,"utf-8");return k3("sha256").update(B).digest("hex")}}catch{return null}};var EF=async(D,F,u)=>{let B=await U0(u),E={entries:D.entries,packages:D.packages,references:D.referenceManager.getAllReferences(),packageLockHash:B||void 0},C=Y2.join(F,"index.json");await BF.writeFile(C,JSON.stringify(E,null,2))},J2=async(D)=>{try{let F=Y2.join(D,"index.json"),u=await BF.readFile(F,"utf-8");return JSON.parse(u)}catch{return null}};var y3=(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},d3=(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)=>y3(F))},W2=(D,F)=>{try{let u=JSON.parse(D);if(!d3(u))return null;return u}catch{return null}};import*as h3 from"fs/promises";import*as G2 from"path";var CF=async(D,F,u)=>{let B=G2.join(D,".index.json");try{let E=await h3.readFile(B,"utf-8"),C=W2(E,B);if(!C)return;for(let $ of C.files){if(!$.url)continue;let X=G2.join(D,$.filename),Q=u.referenceManager.generateId({packageName:F.name,packageVersion:F.version,filePath:X});u.referenceManager.set(Q,{packageName:F.name,packageVersion:F.version,filePath:X,resourceType:$.resourceType,url:$.url,version:$.version});let z={id:Q,resourceType:$.resourceType,indexVersion:C["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 Y=u.entries[$.url];if(Y)Y.push(z)}}catch{}};import*as p3 from"fs/promises";import*as $F from"path";var XF=async(D,F)=>{try{let u=$F.join(D,"package.json"),B=await p3.readFile(u,"utf-8"),E=JSON.parse(B),C={id:{name:E.name,version:E.version},path:D,canonical:E.canonical,fhirVersions:E.fhirVersions};F.packages[E.name]=C,await CF(D,E,F);let $=$F.join(D,"examples");if(await G0($F.join($,".index.json")))await CF($,E,F)}catch{}};import*as A2 from"fs/promises";import*as H2 from"path";var ZF=async(D,F)=>{try{let u=await A2.readdir(D,{withFileTypes:!0});for(let B of u){if(!B.isDirectory())continue;let E=H2.join(D,B.name);if(B.name.startsWith("@")){let C=await A2.readdir(E,{withFileTypes:!0});for(let $ of C){if(!$.isDirectory())continue;let X=H2.join(E,$.name);if(await DF(X))await XF(X,F)}}else if(await DF(E))await XF(E,F)}}catch{}};var M2=async(D,F,u,B)=>{if(F.package)try{return await B(D,{package:F.package.name,version:F.package.version})}catch{}return null};var q2={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 _2=(D,F)=>{if(F.length===0)return D;let u=F.map((B)=>B.toLowerCase());return D.filter((B)=>{if(!B.url)return!1;let C=[B.url.toLowerCase(),B.type?.toLowerCase()||"",B.resourceType?.toLowerCase()||""].join(" ");return u.every(($)=>{let X=C.split(/[\/\-_\.\s]+/);if(X.some((Y)=>Y.startsWith($)))return!0;let z=q2[$]||[];for(let Y of z)if(X.some((W)=>W.startsWith(Y)))return!0;return C.includes($)})})};var $0=(D)=>{let{packages:F=[],workingDir:u}=D,B=D.registry?D.registry.endsWith("/")?D.registry:`${D.registry}/`:b3,E=V2.join(u,"node_modules"),C=V2.join(u,".fcm","cache"),$=uF(),X=!1,Q=new Map,z=()=>{if(!X)throw Error("CanonicalManager not initialized. Call init() first.")},Y=async()=>{if(X)return;await A0(u),await A0(C);let U=await U0(u),j=await J2(C);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,B),$=uF(),await ZF(E,$),await EF($,C,u)}X=!0},W=async()=>{$.entries={},$.packages={},$.referenceManager.clear(),Q.clear(),X=!1},J=async()=>{return z(),Object.values($.packages).map((U)=>U.id)},M=async(...U)=>{if(U.length===0)return;let j=U.filter((S)=>!F.includes(S));if(j.length!==0)F.push(...j);if(!X){await Y();return}if(j.length===0)return;await FF(F,u,B),await ZF(E,$),await EF($,C,u)},q=async(U,j)=>{if(z(),j?.sourceContext){let g=await M2(U,j.sourceContext,$,q);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]},H=async(U,j)=>{let S=await q(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 g3.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:Y,destroy:W,packages:J,addPackages:M,resolveEntry:q,resolve:H,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 _2(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 K2(D){let B=D.path.split(".").slice(1).map(($)=>({el:$}));if(B.length===0)return[];let E=B.length-1,C={};if(D.slicing){if(C.slicing={...D.slicing},D.min!==void 0)C.slicing.min=D.min;if(D.max&&D.max!=="*")C.slicing.max=parseInt(D.max)}if(D.sliceName){if(C.slice={},D.min!==void 0)C.slice.min=D.min;if(D.max&&D.max!=="*")C.slice.max=parseInt(D.max);C.sliceName=D.sliceName}return B[E]={...B[E],...C},B}function R2(D,F){let u=[],B=Math.min(D.length,F.length);for(let E=0;E<B;E++)if(D[E].el===F[E].el)u.push({el:D[E].el});else break;return u}function U2(D,F){let u=[];for(let B=0;B<F.length;B++)if(B<D.length&&D[B].el===F[B].el)u.push({...D[B],...F[B],...D[B].slicing&&!F[B].slicing&&{slicing:D[B].slicing}});else u.push(F[B]);return u}function s6(D,F){return!!(D.sliceName&&F.sliceName&&D.sliceName!==F.sliceName)}function m3(D){return{type:"exit-slice",sliceName:D.sliceName,...D.slicing&&{slicing:D.slicing},...D.slice&&{slice:D.slice}}}function r6(D,F,u,B){let E=[];for(let C=D-1;C>=F;C--){let $=u[C];if($.sliceName)E.push(m3($));E.push({type:"exit",el:$.el})}if(F>0){let C=u[F-1],$=B[F-1];if(s6(C,$))E.push(m3(C))}return E}function a6(D,F,u,B){let E=[];if(D>0&&D<=F){let C=u[D-1]||{},$=B[D-1];if($.sliceName&&(!C.sliceName||C.sliceName!==$.sliceName))E.push({type:"enter-slice",sliceName:$.sliceName});if(D===F)return E}for(let C=D;C<F;C++){let $=B[C];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,B=F.length,C=R2(D,F).length,$=r6(u,C,D,F),X=a6(C,B,D,F);return[...$,...X]}function l3(D,F){if(!D)return;return D.find((u)=>u.url===F)}function c3(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 e6(D){let F={};for(let[u,B]of Object.entries(D))if(typeof u==="string"&&u.startsWith("pattern")){let E=c3(u.replace(/^pattern/,""));F.pattern={type:E,value:B}}else if(typeof u==="string"&&u.startsWith("fixed")){let E=c3(u.replace(/^fixed/,""));F.pattern={type:E,value:B}}else F[u]=B;if(F.pattern?.type&&!F.type)F.type=F.pattern.type;return F}function D8(D){let F=[];for(let u of D)if(u.targetProfile){let B=Array.isArray(u.targetProfile)?u.targetProfile:[u.targetProfile];F.push(...B)}return F.length>0?[...new Set(F)].sort():void 0}function F8(D){if(!D.type||D.type.length===0)return D;if(D.type[0].code==="Reference"){let u=D8(D.type);return{...D,type:[{code:"Reference"}],...u&&{refers:u}}}return D}function u8(D,F){let u=(C)=>{let $={strength:C.strength,...C.valueSet&&{valueSet:C.valueSet}},X=l3(C.extension,"http://hl7.org/fhir/StructureDefinition/elementdefinition-bindingName");if(X?.valueString)$.bindingName=X.valueString;return $};if(D.choices){let{binding:C,...$}=D;return $}if(D.choiceOf&&F.snapshot){let C=`${F.id}.${D.choiceOf}[x]`,$=F.snapshot.element.find((X)=>X.path===C);if($?.binding)return{...D,binding:u($.binding)}}if(D.binding?.valueSet)return{...D,binding:u(D.binding)};let{binding:B,...E}=D;return E}function B8(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 E8(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 B=D.type[0].code,E={...D,type:B};if(F.kind==="logical"){let C=l3(D.extension,"http://hl7.org/fhir/StructureDefinition/elementdefinition-defaulttype");if(C?.valueCanonical)E.defaultType=C.valueCanonical}return E}function C8(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 $8(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,B={...D};if(delete B.min,delete B.max,F){if(B.array=!0,D.min&&D.min>0)B.min=D.min;if(D.max&&D.max!=="*")B.max=parseInt(D.max)}if(u)B._required=!0;return B}function X8(D,F){let u=D.substring(1).split("."),B=[F.url];for(let E of u.slice(1))B.push("elements",E);return B}function Z8(D,F){if(!D.contentReference)return D;let{contentReference:u,...B}=D;return{...B,elementReference:X8(u,F)}}function Q8(D){let{path:F,slicing:u,sliceName:B,id:E,mapping:C,example:$,alias:X,condition:Q,comment:z,definition:Y,requirements:W,extension:J,...M}=D;return M}function j2(D,F){let u=F8(D);return u=Q8(u),u=u8(u,F),u=B8(u),u=Z8(u,F),u=C8(u),u=$8(u),u=E8(u,F),u=e6(u),u}function I2(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 o3(D){if(!D)return D;return D.charAt(0).toUpperCase()+D.slice(1)}function n3(D){let F=D.split("/");return F[F.length-1]}function L2(D){let F=D.path.replace(/\[x\]$/,""),u=F.split(".").pop()||"";if(!D.type)return[];let B=[],E=D.type.map((z)=>u+o3(n3(z.code))),{type:C,binding:$,...X}=D,Q={...X,path:F,choices:E};B.push(Q);for(let z of D.type){let Y=o3(n3(z.code)),W={...D,path:F+Y,type:[z],choiceOf:u};if(D.binding)delete W.binding;B.push(W)}return B}function i3(D,F){let u=D[D.length-1],B=D.slice(0,-1),E=B[B.length-1],C=F(E,u);return[...B.slice(0,-1),C]}function z8(D,F){if(!D.discriminator)return{};let u={};for(let B of D.discriminator){if(!B.type||!["pattern","value",void 0].includes(B.type))continue;let E=B.path.trim();if(E==="$this"){if(F.pattern?.value)Object.assign(u,F.pattern.value)}else{let C=E.split(".").filter((z)=>z),$=Object.keys(F).filter((z)=>z.startsWith("pattern"));for(let z of $){let Y=z.replace("pattern","").toLowerCase();if(C.length===1&&C[0]===Y)u[Y]=F[z]}let X=["elements"];for(let z of C)if(X.push(z),C.indexOf(z)<C.length-1)X.push("elements");X.push("pattern");let Q=F;for(let z of X)Q=Q?.[z];if(Q?.value!==void 0){let z=u;for(let Y=0;Y<C.length-1;Y++){if(!z[C[Y]])z[C[Y]]={};z=z[C[Y]]}z[C[C.length-1]]=Q.value}}}return u}function O8(D,F,u){let B={match:F,schema:D};if(u?.min!==void 0&&u.min!==0)B.min=u.min;if(u?.max!==void 0)B.max=u.max;return B}function Y8(D,F,u){let B=F.slicing||D.slicing||{},E=z8(B,u),C=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]=C,F}function J8(D){if(!D.slicing?.slices)return{};let F={};for(let[u,B]of Object.entries(D.slicing.slices)){let{match:E,schema:C,...$}=B,{slicing:X,elements:Q,type:z,min:Y,...W}=C||{},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,W),Y!==void 0&&Y!==0&&J.min===void 0)J.min=Y;F[u]=J}return F}function W8(D,F,u){let B={...F};if(D==="extension")B.extensions=J8(u);if(!B.elements)B.elements={};let E=u.choiceOf||D,{_required:C,...$}=u;if(B.elements[D]=$,C){if(!B.required)B.required=[];if(!B.required.includes(E))B.required.push(E)}return B}function zF(D,F,u){let B=[...D];for(let E=0;E<F.length;E++){let C=F[E],X=F[E+1]?.type==="enter"?{}:u;switch(C.type){case"enter":B.push(X);break;case"enter-slice":B.push(X);break;case"exit":B=i3(B,(Q,z)=>W8(C.el,Q,z));break;case"exit-slice":B=i3(B,(Q,z)=>Y8(C,Q,z));break}}return B}function t3(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 A8(D){return(D.differential?.element||[]).filter((u)=>u.path.includes("."))}function s3(D){let u=Object.entries(D).sort((E,C)=>{let $=E[1].index??1/0,X=C[1].index??1/0;return $-X}),B={};for(let[E,C]of u)if(C.elements)B[E]={...C,elements:s3(C.elements)};else B[E]=C;return B}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={},B=Object.keys(D);for(let E of B)if(E==="elements"&&D[E])u[E]=s3(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 N2(D,F){if(D.kind==="primitive-type")return j0(t3(D,F));let u=t3(D,F),B=A8(D),E=[u],C=[],$=[...B],X=0;while($.length>0){let z=$.shift();if(I2(z)){let H=L2(z);$.unshift(...H),X++;continue}let Y=K2(z),W=U2(C,Y),J=QF(C,W),q={...j2(z,D),index:X++};E=zF(E,J,q),C=W}let Q=QF(C,[]);if(E=zF(E,Q,{index:X}),E.length!==1)throw Error(`Invalid stack state: expected 1 element, got ${E.length}`);return j0(E[0])}function T2(D){if(!D)return;return D.split("|")[0]}function M8(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 hD(D){return{kind:M8(D),package:D.package_meta.name,version:D.package_meta.version,name:D.name,url:D.url}}function I0(D,F,u){let B=F.join(".");return{kind:"nested",package:u?.name||D.package_meta.name||"undefined",version:u?.version||D.package_meta.version||"undefined",name:B,url:`${D.url}#${B}`}}function L0(D,F,u){let B=T2(D)||D,E="unknown",C=B.split("/"),$=C[C.length-1];if($&&$.length>0)E=$.split(/[-_]/).map((X)=>X.charAt(0).toUpperCase()+X.slice(1).toLowerCase()).join("");if(E==="unknown"&&F?.id&&!/^[a-zA-Z0-9_-]{20,}$/.test(F.id))E=F.id;return{kind:"value-set",package:u?.name||F?.package_name||"undefined",version:u?.version||F?.package_version||"undefined",name:E,url:B}}function OF(D,F,u,B){let E=F.join("."),C=u||`${D.name}.${E}_binding`;return{kind:"binding",package:B?.name||D.package_meta.name||"undefined",version:B?.version||D.package_meta.version||"undefined",name:C,url:u?`urn:fhir:binding:${C}`:`${D.url}#${E}_binding`}}async function r3(D,F){let u=hD(D),B=D.package_meta;if(u.kind!=="profile")throw Error(`Expected profile, got ${u.kind} for ${D.name}`);let E;if(D.base){let Y=D.base.includes("/")?D.base:`http://hl7.org/fhir/StructureDefinition/${D.base}`,W=D.base.split("/").pop()||D.base,J=await q8(Y,F),M=Y.startsWith("http://hl7.org/fhir/");E={kind:J,package:M?"hl7.fhir.r4.core":D.package_meta.name||"undefined",version:M?"4.0.1":D.package_meta.version||"undefined",name:W,url:Y}}let C={identifier:u,base:E,dependencies:E?[E]:[]};if(D.description)C.description=D.description;let $=_8(D);if(Object.keys($).length>0)C.metadata=$;if(D.elements){let Y=await YF(D,[],D.elements,F,B);if(Object.keys(Y).length>0)C.fields=Y}let X=await V8(D,F);if(Object.keys(X).length>0)C.constraints=X;let Q=await K8(D,F);if(Q.length>0)C.extensions=Q;let z=R8(D);if(z.length>0)C.validation=z;return C}async function q8(D,F){try{let u=await F.resolve(D);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 _8(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 V8(D,F){let u={};if(!D.elements)return u;for(let[B,E]of Object.entries(D.elements)){let C={};if(E.min!==void 0)C.min=E.min;if(E.max!==void 0)C.max=String(E.max);if(E.mustSupport)C.mustSupport=!0;if(E.fixedValue!==void 0)C.fixedValue=E.fixedValue;if(E.patternValue!==void 0)C.patternValue=E.patternValue;if(E.binding)C.binding={strength:E.binding.strength,valueSet:E.binding.valueSet??""};if(E.type&&Array.isArray(E.type)&&E.type.length>0)C.types=E.type.map(($)=>{let X={code:$.code};if($.profile)X.profile=$.profile;if($.targetProfile)X.targetProfile=$.targetProfile;return X});if(E.slicing)C.slicing={discriminator:E.slicing.discriminator??[],rules:String(E.slicing),ordered:E.slicing.ordered};if(Object.keys(C).length>0)u[B]=C}return u}async function K8(D,F){let u=[];if(!D.elements)return u;for(let[B,E]of Object.entries(D.elements))if(B.includes("extension")&&E.type&&Array.isArray(E.type)){for(let C of E.type)if(C.code==="Extension"&&C.profile)u.push({path:B,profile:C.profile,min:E.min,max:String(E.max),mustSupport:E.mustSupport})}return u}function R8(D){let F=[];if(!D.elements)return F;for(let[u,B]of Object.entries(D.elements))if(B.constraint&&Array.isArray(B.constraint))for(let E of B.constraint)F.push({path:u,key:E.key,severity:E.severity,human:E.human,expression:E.expression});return F}function a3(D,F,u){let B=[],E=D.elements;for(let C of F)if(E=E?.[C],!E)break;if(E)B.push(E);return B}function e3(D){if(D.length===0)return{};let F={...D[0]};for(let u=D.length-1;u>=0;u--){let B=D[u],E=["choices","short","index","elements","required","excluded","binding","refers","elementReference","mustSupport","slices","slicing","url","extensions"];for(let[C,$]of Object.entries(B))if(!E.includes(C)&&$!==void 0)F[C]=$}for(let u of["choices","binding","refers","elementReference"])if(D[0]&&D[0][u]!==void 0)F[u]=D[0][u];return F}function Du(D,F,u){if(F.length===0)return!1;let B=F[F.length-1],E=F.slice(0,-1),C=D;for(let $ of E)if(C=C.elements?.[$],!C)break;if(C?.required?.includes(B))return!0;if(E.length===0&&B&&D.required?.includes(B))return!0;return!1}function Fu(D,F,u){if(F.length===0)return!1;let B=F[F.length-1],E=F.slice(0,-1),C=D;for(let $ of E)if(C=C.elements?.[$],!C)break;if(C?.excluded?.includes(B))return!0;if(E.length===0&&B&&D.excluded?.includes(B))return!0;return!1}async function U8(D,F,u){if(!D.refers||D.refers.length===0)return;let B=[];for(let E of D.refers)try{let C=await F.resolve(E);if(C)B.push(hD(C))}catch{}return B}function w2(D,F,u,B,E){if(u.elementReference){let C=u.elementReference.filter(($,X)=>X%2===1).map(($)=>$).filter(($)=>$!=="elements");if(C.length>0)return I0(D,C,E)}if(u.type){let C=u.type.includes("/")?u.type:`http://hl7.org/fhir/StructureDefinition/${u.type}`,$=u.type.match(/^[a-z]/)?"primitive-type":"complex-type",X=C.startsWith("http://hl7.org/fhir/");return{kind:$,package:X?"hl7.fhir.r4.core":E?.name||"undefined",version:X?"4.0.1":E?.version||"undefined",name:u.type,url:C}}return}async function JF(D,F,u,B,E){let C={array:u.array||!1,required:Du(D,F,B),excluded:Fu(D,F,B)},$=w2(D,F,u,B,E);if($)C.type=$;if(u.min!==void 0)C.min=u.min;if(u.max!==void 0)C.max=u.max;if(u.choices)C.choices=u.choices;if(u.choiceOf)C.choiceOf=u.choiceOf;if(u.binding){if(C.binding=OF(D,F,u.binding.bindingName,E),u.binding.strength==="required"&&u.type==="code"){let Q=await b2(u,B);if(Q&&Q.length>0)C.enum=Q}}let X=await U8(u,B,E);if(X)C.reference=X;return j8(C)}function j8(D){let F={};for(let[u,B]of Object.entries(D))if(B!==void 0&&B!==null){if(Array.isArray(B)&&B.length===0)continue;F[u]=B}return F}function N0(D){return D.type==="BackboneElement"||D.elements&&Object.keys(D.elements).length>0||!1}function WF(D,F,u,B,E){return{type:I0(D,F,E),array:u.array||!1,required:Du(D,F,B),excluded:Fu(D,F,B)}}async function I8(D,F){try{let u=T2(D)||D,B=await F.resolve(u);if(!B)return;if(B.expansion?.contains)return B.expansion.contains.map((C)=>({system:C.system,code:C.code,display:C.display}));let E=[];if(B.compose?.include){for(let C of B.compose.include)if(C.concept)for(let $ of C.concept)E.push({system:C.system,code:$.code,display:$.display});else if(C.system&&!C.filter)try{let $=await F.resolve(C.system);if($?.concept){let X=(Q,z)=>{for(let Y of Q)if(E.push({system:z,code:Y.code,display:Y.display}),Y.concept)X(Y.concept,z)};X($.concept,C.system)}}catch{}}return E.length>0?E:void 0}catch{return}}async function b2(D,F){if(!D.binding)return;let{strength:u,valueSet:B}=D.binding;if(!B)return;if(!(u==="required"||u==="extensible"&&(D.type==="code"||D.type==="Coding")||u==="preferred"&&(D.type==="code"||D.type==="Coding")))return;if(!F.resolve)return;try{let C=await I8(B,F);if(!C||C.length===0)return;let $=C.map((X)=>X.code).filter((X)=>X&&typeof X==="string"&&X.trim().length>0);return $.length>0&&$.length<=100?$:void 0}catch(C){console.debug(`Failed to extract enum values for ${B}: ${C}`);return}}async function L8(D,F,u,B,E){if(!u.binding?.valueSet)return;let C=OF(D,F,u.binding.bindingName,E),$=w2(D,F,u,B,E),X=L0(u.binding.valueSet,void 0,E),Q={identifier:C,type:$,valueset:X,strength:u.binding.strength,dependencies:[]};if($)Q.dependencies.push($);Q.dependencies.push(X);let z=await b2(u,B);if(z)Q.enum=z;return Q}async function x2(D,F,u){let B=[],E=new Set;async function C(Q,z){for(let[Y,W]of Object.entries(Q)){let J=[...z,Y],M=J.join(".");if(E.has(M))continue;if(E.add(M),W.binding){let q=await L8(D,J,W,F,u);if(q)B.push(q)}if(W.elements)await C(W.elements,J)}}if(D.elements)await C(D.elements,[]);B.sort((Q,z)=>Q.identifier.name.localeCompare(z.identifier.name));let $=[],X=new Set;for(let Q of B)if(!X.has(Q.identifier.url))X.add(Q.identifier.url),$.push(Q);return $}function uu(D,F,u){let B=[];for(let[E,C]of Object.entries(u)){let $=[...F,E];if(N0(C))B.push([$,C]);if(C.elements)B.push(...uu(D,$,C.elements))}return B}async function N8(D,F,u,B,E){let C={};for(let[$,X]of Object.entries(u)){let Q=[...F,$];if(N0(X))C[$]=WF(D,Q,X,B,E);else C[$]=await JF(D,Q,X,B,E)}return C}async function P2(D,F,u){if(!D.elements)return[];let B=[],C=uu(D,[],D.elements).filter(([$,X])=>X.elements&&Object.keys(X.elements).length>0);for(let[$,X]of C){let Q=I0(D,$,u),z;if(X.type==="BackboneElement"||!X.type)z={kind:"complex-type",package:u?.name||"hl7.fhir.r4.core",version:u?.version||"4.0.1",name:"BackboneElement",url:"http://hl7.org/fhir/StructureDefinition/BackboneElement"};else z={kind:"complex-type",package:u?.name||"hl7.fhir.r4.core",version:u?.version||"4.0.1",name:X.type,url:`http://hl7.org/fhir/StructureDefinition/${X.type}`};let Y=await N8(D,$,X.elements,F,u),W={identifier:Q,base:z,fields:Y};B.push(W)}return B.sort(($,X)=>$.identifier.url.localeCompare(X.identifier.url)),B}function S2(D){let F=[];for(let u of D){if(F.push(u.identifier),u.base)F.push(u.base);for(let B of Object.values(u.fields)){if("type"in B&&B.type)F.push(B.type);if("binding"in B&&B.binding)F.push(B.binding)}}return F}async function YF(D,F,u,B,E){let C={};for(let[$,X]of Object.entries(u)){let Q=[...F,$],z=a3(D,Q,B),Y=z.length>0?e3(z):X;if(N0(Y))C[$]=WF(D,Q,Y,B,E);else C[$]=await JF(D,Q,Y,B,E)}return C}function Bu(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 Eu(D){let F=new Set,u=[];for(let B of D){let E=B.url;if(!F.has(E))F.add(E),u.push(B)}return u.sort((B,E)=>B.name.localeCompare(E.name)),u}function T8(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 w8(D,F,u){try{let B=hD(D);B.kind="value-set";let E={identifier:B,description:D.description};if(D.elements){let C=[];for(let[$,X]of Object.entries(D.elements))if("code"in X&&X.code)C.push({code:X.code,display:X.short||X.definition,system:X.system});if(C.length>0)E.concept=C}return E}catch(B){return console.warn(`Failed to transform value set ${D.name}: ${B}`),null}}async function b8(D,F,u){try{let B=hD(D),E;if(D.base&&D.base!=="Extension"){let X=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:X}}else E={kind:"complex-type",package:"hl7.fhir.r4.core",version:"4.0.1",name:"Extension",url:"http://hl7.org/fhir/StructureDefinition/Extension"};let C={identifier:B,base:E,description:D.description,dependencies:[],metadata:{isExtension:!0}};if(E)C.dependencies.push(E);if(D.elements){let X=await YF(D,[],D.elements,F,u);if(Object.keys(X).length>0)C.fields=X,C.dependencies.push(...Bu(X))}let $=await P2(D,F,u);if($.length>0)C.nested=$,C.dependencies.push(...S2($));return C.dependencies=Eu(C.dependencies),C.dependencies=C.dependencies.filter((X)=>X.url!==B.url),C}catch(B){return console.warn(`Failed to transform extension ${D.name}: ${B}`),null}}async function Cu(D,F){let u=[],B=hD(F);if(B.kind==="profile"){let Q=await r3(F,D,F.package_meta);u.push(Q);let z=await x2(F,D,F.package_meta);return u.push(...z),u}if(B.kind==="value-set"||F.kind==="value-set"){let Q=await w8(F,D,F.package_meta);if(Q)u.push(Q);return u}if(T8(F,B)){let Q=await b8(F,D,F.package_meta);if(Q)u.push(Q);return u}let E;if(F.base&&F.type!=="Element"){let Q=F.base.includes("/")?F.base:`http://hl7.org/fhir/StructureDefinition/${F.base}`,z=F.base.split("/").pop()||F.base,W=new Set(["Element","BackboneElement","Quantity","Duration","Distance","Count","Age","Address","Annotation","Attachment","CodeableConcept","Coding","ContactPoint","HumanName","Identifier","Period","Range","Ratio","Reference","Timing","Money","SampledData","Signature","ContactDetail","Contributor","DataRequirement","Expression","ParameterDefinition","RelatedArtifact","TriggerDefinition","UsageContext","Dosage","Meta","Extension"]).has(z)?"complex-type":"resource",J=Q.startsWith("http://hl7.org/fhir/");E={kind:W,package:J?"hl7.fhir.r4.core":F.package_meta.name||"undefined",version:J?"4.0.1":F.package_meta.version||"undefined",name:z,url:Q}}let C={identifier:B,dependencies:[]},$=[];if(E)C.base=E,$.push(E);if(F.description)C.description=F.description;if(F.kind!=="primitive-type"&&F.elements){let Q=await YF(F,[],F.elements,D,F.package_meta);if(Object.keys(Q).length>0)C.fields=Q;$.push(...Bu(Q));let z=await P2(F,D,F.package_meta);if(z.length>0)C.nested=z,$.push(...S2(z))}C.dependencies=$,C.dependencies=Eu(C.dependencies),C.dependencies=C.dependencies.filter((Q)=>Q.url!==B.url),u.push(C);let X=await x2(F,D,F.package_meta);return u.push(...X),u}var $u=(D)=>{return{...D,package_meta:{name:D.package_name||D.package_meta?.name||"undefined",version:D.package_version||D.package_meta?.version||"undefined"}}};function v2(D){return D.identifier.kind==="binding"}async function x8(D,F){try{let u=await F.resolve(D);if(!u||u.resourceType!=="CodeSystem")return;let B=[],E=(C,$)=>{for(let X of C)if(B.push({system:$,code:X.code,display:X.display}),X.concept)E(X.concept,$)};if(u.concept)E(u.concept,D);return B}catch{return}}async function Xu(D,F){let u=[];if(D.concept){for(let B of D.concept)u.push({system:D.system,code:B.code,display:B.display});return u}if(D.system&&!D.filter){let B=await x8(D.system,F);if(B)u.push(...B)}if(D.valueSet)for(let B of D.valueSet)try{let E=await F.resolve(B);if(E){let C=await Zu(E,F);if(C)u.push(...C)}}catch{}return u}async function Zu(D,F){try{let u=[];if(D.compose){if(D.compose.include)for(let B of D.compose.include){let E=await Xu(B,F);u.push(...E)}if(D.compose.exclude){let B=new Set;for(let E of D.compose.exclude){let C=await Xu(E,F);for(let $ of C)B.add(`${$.system}|${$.code}`)}return u.filter((E)=>!B.has(`${E.system}|${E.code}`))}}return u.length>0?u:void 0}catch(u){console.error("Error extracting ValueSet concepts:",u);return}}async function Qu(D,F,u){let E={identifier:L0(D.url,D,u)};if(D.description)E.description=D.description;let C=await Zu(D,F);if(C&&C.length>0)E.concept=C;else if(D.compose)E.compose=D.compose;if(D.compose){let $=[],X=(Q)=>{for(let z of Q){if(z.system)$.push({kind:"value-set",package:u?.name||"undefined",version:u?.version||"undefined",name:z.system.split("/").pop()||"unknown",url:z.system});if(z.valueSet)for(let Y of z.valueSet)$.push(L0(Y,void 0,u))}};if(D.compose.include)X(D.compose.include);if(D.compose.exclude)X(D.compose.exclude)}return E}class pD{manager;options;cacheConfig;cache;logger;constructor(D={},F){this.options={verbose:!1,...D},this.manager=D.manager||$0({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 C0(this.cacheConfig),await this.cache.initialize()}async fetchPackage(D,F){this.logger.step(`Loading FHIR package: ${D}${F?`@${F}`:""}`),await this.manager.addPackages(`${D}${F?`@${F}`:""}`);let u=await this.manager.search({}),B=u.filter((C)=>C.resourceType==="StructureDefinition"),E=u.filter((C)=>C.resourceType==="ValueSet");return this.logger.info(`Found ${B.length} StructureDefinitions and ${E.length} ValueSets in package`),{structureDefinitions:B,valueSets:E}}generateFhirSchemas(D){this.logger.progress(`Converting ${D.length} StructureDefinitions to FHIRSchemas`);let F=this.applyStructureDefinitionTreeshaking(D),u=[],B=0,E=0;for(let C of F)try{let $=N2(C);u.push($),B++,this.logger.debug(`Converted StructureDefinition: ${C.name||C.id} (${C.resourceType})`)}catch($){E++,this.logger.warn(`Failed to convert StructureDefinition ${C.name||C.id}: ${$ instanceof Error?$.message:String($)}`)}return this.logger.success(`FHIR Schema conversion completed: ${B}/${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 B=0,E=0;for(let C of D)try{let $=await Qu(C,this.manager,F);if($)u.push($),B++,this.logger.debug(`Converted ValueSet: ${C.name||C.id}`)}catch($){E++,this.logger.warn(`Failed to convert ValueSet ${C.name||C.id}: ${$ instanceof Error?$.message:String($)}`)}this.logger.success(`ValueSet conversion completed: ${B}/${D.length} successful, ${E} failed`)}return u}async generateFromPackage(D,F){if(await this.initializeCache(),this.cache&&!(this.cacheConfig?.forceRegenerate??!1)){let z=this.cache.getByPackage(D);if(z.length>0)return this.logger.info(`Using cached TypeSchemas for package: ${D} (${z.length} schemas)`),z}let u={name:D,version:F||"latest"},{valueSets:B,structureDefinitions:E}=await this.fetchPackage(D,F),C=this.generateFhirSchemas(E).map($u),$=await this.generateValueSetSchemas(B,u),Q=[...await this.generateResourceTypeSchemas(C),...$];if(this.cache)for(let z of Q)await this.cache.set(z);return Q}async generateResourceTypeSchemas(D){this.logger.info(`Transforming ${D.length} FHIR schemas to Type Schema`);let F=[];for(let u of D)F.push(...await Cu(this.manager,u));return F}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,B=new Map,E=new Map;for(let z of D){let Y=z.name||z.id;if(Y)u.set(Y,z),B.set(Y,new Set),E.set(Y,new Set)}for(let z of D){let Y=z.name||z.id;if(!Y)continue;let{realDeps:W,refTargets:J}=this.extractStructureDefinitionDependenciesWithReferences(z);B.set(Y,new Set(W)),E.set(Y,new Set(J))}let C=new Set;for(let z of F)if(u.has(z))C.add(z);else this.logger.warn(`ResourceType '${z}' not found in structure definitions`);let $=(z,Y=new Set)=>{if(Y.has(z)||!B.has(z))return;Y.add(z);let W=B.get(z)||new Set;for(let J of Array.from(W))if(u.has(J))C.add(J),$(J,Y)};for(let z of Array.from(C))$(z);let X=D.filter((z)=>{let Y=z.name||z.id;return Y&&C.has(Y)}),Q=new Set;for(let z of D){let Y=z.name||z.id;if(Y&&!C.has(Y)){if(Array.from(E.values()).some((J)=>J.has(Y)))Q.add(Y)}}if(Q.size>0)this.logger.info(`Excluded reference-only targets: ${Array.from(Q).join(", ")}`);return this.logger.success(`Treeshaking completed: kept ${X.length}/${D.length} structure definitions`),X}extractStructureDefinitionDependenciesWithReferences(D){let F=new Set,u=new Set;if(D.baseDefinition){let B=this.extractResourceNameFromUrl(D.baseDefinition);if(B)F.add(B)}if(D.snapshot?.element||D.differential?.element){let B=D.snapshot?.element||D.differential?.element;for(let E of B)if(E.type)for(let C of E.type){if(C.code){if(F.add(C.code),C.code==="Reference"&&C.targetProfile)for(let $ of C.targetProfile){let X=this.extractResourceNameFromUrl($);if(X)u.add(X)}}if(C.profile)for(let $ of C.profile){let X=this.extractResourceNameFromUrl($);if(X)F.add(X)}}}return{realDeps:Array.from(F),refTargets:Array.from(u)}}extractResourceNameFromUrl(D){let F=D.match(/\/([^/]+)$/);return F?F[1]??null:null}}import{readFile as P8}from"node:fs/promises";class T0{options;constructor(D={}){this.options={format:"auto",validate:!0,strict:!1,...D}}async parseFromFile(D){let F=await P8(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),B;if(u==="ndjson")B=this.parseNDJSON(D);else B=this.parseJSON(D);if(this.options.validate)this.validateSchemas(B);return B}async parseFromFiles(D){let F=[];for(let u of D){let B=await this.parseFromFile(u);F.push(...B)}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)}getDependencies(D){let F=[];if("base"in D&&D.base)F.push(D.base);if("dependencies"in D&&D.dependencies)F.push(...D.dependencies);if("fields"in D&&D.fields)for(let u of Object.values(D.fields)){if("type"in u&&u.type)F.push(u.type);if("binding"in u&&u.binding)F.push(u.binding);if("reference"in u&&u.reference)F.push(...u.reference)}if("nested"in D&&D.nested)for(let u of D.nested){F.push(u.identifier),F.push(u.base);for(let B of Object.values(u.fields)){if("type"in B&&B.type)F.push(B.type);if("binding"in B&&B.binding)F.push(B.binding);if("reference"in B&&B.reference)F.push(...B.reference)}}if("valueset"in D){let u=D;if(F.push(u.valueset),u.type)F.push(u.type)}return this.deduplicateDependencies(F)}resolveDependencies(D,F){let u=this.getDependencies(F),B=[];for(let E of u){let C=this.findByUrl(D,E.url);if(C)B.push(C)}return B}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
94
|
`)){let B=u.split(`
|
|
95
95
|
`).filter((E)=>E.trim());if(B.length>1)try{if(B[0])JSON.parse(B[0]);return"ndjson"}catch{}}return"json"}parseNDJSON(D){let F=[],u=D.split(`
|
|
96
96
|
`).filter((B)=>B.trim());for(let B of u)try{let E=JSON.parse(B);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)}deduplicateDependencies(D){let F=new Set,u=[];for(let B of D)if(!F.has(B.url))F.add(B.url),u.push(B);return u.sort((B,E)=>B.name.localeCompare(E.name))}}w0();class d2{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((B)=>B instanceof ID),u=D.filter((B)=>!(B instanceof ID));if(F.length>0)this.reportBatchErrors(F);u.forEach((B)=>{this.handleUnknownError(B)})}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(`
|
|
@@ -101,7 +101,7 @@ ${_.join(`
|
|
|
101
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
102
|
❌ ${D.length} errors occurred during generation:`);let F=new Map;D.forEach((u)=>{let B=u.constructor.name;if(!F.has(B))F.set(B,[]);F.get(B)?.push(u)});for(let[u,B]of F){console.error(`
|
|
103
103
|
\uD83D\uDCCB ${u} (${B.length} occurrences):`),B.forEach((C,$)=>{if(console.error(` ${$+1}. ${C.message}`),C.context?.schemaName)console.error(` Schema: ${C.context.schemaName}`)});let E=this.getCommonSuggestions(B);if(E.length>0)console.error(`
|
|
104
|
-
\uD83D\uDCA1 Common suggestions:`),E.forEach((C)=>{console.error(` • ${C}`)})}}getCommonSuggestions(D){let F=D.flatMap((E)=>E.getSuggestions()),u=new Map;F.forEach((E)=>{u.set(E,(u.get(E)||0)+1)});let B=Math.ceil(D.length/2);return Array.from(u.entries()).filter(([E,C])=>C>=B).map(([E,C])=>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 h2{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=[],B=[];for(let E of D)try{let C=await E();u.push(C)}catch(C){B.push(C instanceof Error?C:Error(String(C)))}if(B.length>0)throw this.errorHandler.handleBatchErrors(B),new y2(`${B.length} operations failed`,B.filter((E)=>E instanceof ID));return u}}w0();w0();import{access as p2,mkdir as S8,rm as v8,stat as zu,writeFile as f8}from"node:fs/promises";import{dirname as g2,join as Z0,relative as k8}from"node:path";class m2{options;logger;constructor(D){this.options={overwrite:!0,batchSize:10,...D},this.logger=D.logger}async writeFile(D,F,u={}){let B=performance.now(),E=Z0(this.options.outputDir,D),C=u.encoding||"utf-8",$=u.overwrite??this.options.overwrite;try{if(!$)try{await p2(E),this.logger.debug(`Skipping existing file: ${D}`);let z=await zu(E);return{path:E,size:z.size,writeTime:0}}catch{}await this.ensureDirectory(g2(E)),await f8(E,F,C);let X=performance.now()-B,Q=Buffer.byteLength(F,C);return this.logger.debug(`Written ${D} (${Q} bytes, ${X.toFixed(2)}ms)`),{path:E,size:Q,writeTime:X}}catch(X){throw new X0(`Failed to write file '${D}': ${X}`,"write",E,X instanceof Error?X:void 0,{canRetry:!0,alternativePaths:[Z0(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 B=0;B<F.length;B+=this.options.batchSize){let C=F.slice(B,B+this.options.batchSize).map(([X,Q])=>this.writeFile(X,Q)),$=await Promise.all(C);if(u.push(...$),B+this.options.batchSize<F.length)await new Promise((X)=>setTimeout(X,10))}return u}async ensureDirectory(D){try{await S8(D,{recursive:!0})}catch(F){throw new X0(`Failed to create directory '${D}': ${F}`,"create",D,F instanceof Error?F:void 0,{canRetry:!0,permissionFix:`chmod 755 "${g2(D)}"`})}}async cleanDirectory(D="."){let F=Z0(this.options.outputDir,D);try{await p2(F),this.logger.debug(`Cleaning directory: ${D}`),await v8(F,{recursive:!0,force:!0})}catch(u){if(u?.code!=="ENOENT")throw new X0(`Failed to clean directory '${D}': ${u}`,"delete",F,u instanceof Error?u:void 0,{canRetry:!0})}}getRelativeImportPath(D,F){let u=g2(Z0(this.options.outputDir,D)),B=Z0(this.options.outputDir,F),E=k8(u,B);if(!E.startsWith("."))E=`./${E}`;return E.replace(/\.(d\.ts|ts|tsx|js|jsx)$/,"")}async wouldOverwrite(D){let F=Z0(this.options.outputDir,D);try{return await p2(F),!0}catch{return!1}}async getFileStats(D){let F=Z0(this.options.outputDir,D);try{return{size:(await zu(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 o2{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 k2(`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 d2({logger:this.logger,verbose:this.options.verbose||!1,beginnerMode:this.options.beginnerMode||!1,outputFormat:this.options.errorFormat||"console"}),this.errorBoundary=new h2(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 m2({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(B,E)=>{let C={path:`${this.options.outputDir}/${B}`,size:Buffer.byteLength(E,"utf-8"),writeTime:0};return u.set(B,C),C};try{let B=await this.generate(D);return B.forEach((E)=>{let C=u.get(E.filename);if(C)E.path=C.path,E.size=C.size}),B}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}=(Ju(),qF(Yu));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}=qF(Wu);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}=qF(Gu);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=[],B=[];if(!D.outputDir)F.push("outputDir is required"),B.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&&!VF("node:path").isAbsolute(D.outputDir))u.push("Using relative path for outputDir - consider using absolute path"),B.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"),B.push("Consider enabling validation for better code quality");return{isValid:F.length===0,errors:F,warnings:u,suggestions:B}}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 B=["resource","complex-type","profile","primitive-type","logical","value-set","binding","extension"];if(!B.includes(D.identifier.kind))F.push(`Schema identifier.kind must be one of: ${B.join(", ")}`)}}if("fields"in D&&D.fields)for(let[B,E]of Object.entries(D.fields)){if(!B.trim())F.push("Field name cannot be empty");if(!E)F.push(`Field '${B}' 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 f2(`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 C=E.identifier?.name;if(!C)return!1;if(u.has(C))return!0;if(F.has(C))return!1;if(u.add(C),"fields"in E&&E.fields){for(let $ of Object.values(E.fields))if($?.type?.name===C)return!0}return u.delete(C),F.add(C),!1})(D)}async generateFiles(D){let F=D.map((u,B)=>()=>this.errorBoundary.withErrorBoundary(async()=>{let E=await this.generateFileForSchema(u,B,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 B=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},C=await this.generateSchemaContent(D,E);if(this.options.validate)await this.validateContent(C,E);let $=E.filename+this.getFileExtension(),X=await this.fileManager.writeFile($,C),Q=performance.now()-B;return this.reportProgress("writing",F+1,u,`Generated ${$} (${X.size} bytes)`),{path:X.path,filename:$,content:C,exports:this.extractExports(C),size:X.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,B;while((B=u.exec(D))!==null)if(B[1]){let C=B[1].split(",").map(($)=>$.trim()).filter(Boolean);F.push(...C)}let E=/export\s+(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/g;while((B=E.exec(D))!==null)if(B[1])F.push(B[1]);return[...new Set(F)]}reportProgress(D,F,u,B,E){if(this.progressCallback)this.progressCallback(D,F,u,B,E);if(B&&this.options.verbose)this.logger.debug(`[${D}] ${B} (${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((B)=>{return this.cache.set(D,B),B});else return this.cache.set(D,u),u}clearCache(){this.cache.clear()}getGenerationStats(){let D=this.generatedFiles.reduce((u,B)=>u+B.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 n2{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 Hu(D);case"PascalCase":return y8(D);case"snake_case":return qu(D);case"kebab-case":return d8(D);default:return D}}getCustomMapping(D){return this.options.customMappings[D]}shouldBeNullable(D){return!D&&this.options.generateNullable}}function Hu(D){return D.replace(/[-_\s]+(.)?/g,(F,u)=>u?.toUpperCase()||"")}function y8(D){let F=Hu(D);return F.charAt(0).toUpperCase()+F.slice(1)}function qu(D){return D.replace(/([A-Z])/g,"_$1").replace(/[-\s]+/g,"_").toLowerCase().replace(/^_/,"")}function d8(D){return qu(D).replace(/_/g,"-")}class i2 extends n2{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 B={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(!B)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!==B)return{name:`${B} & { readonly __brand: '${D}' }`,isPrimitive:!1,importPath:"./brands",nullable:!1,metadata:{isBranded:!0,originalFhirType:D}};return{name:B,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 B=u.name||"unknown";return B==="unknown"?"unknown":`'${B}'`}).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 h8(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 B=this.generateImportStatement(u);if(B)F.add(B)}return Array.from(F).sort()}}function h8(D){return D.replace(/[-_\s]+(.)?/g,(F,u)=>u?.toUpperCase()||"")}class JF extends o2{profilesByPackage=new Map;resourceTypes=new Set;collectedValueSets=new Map;get tsOptions(){return this.options}getLanguageName(){return"TypeScript"}getFileExtension(){return".ts"}createTypeMapper(){let D=this.options;return new i2({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),B="";if("nested"in D&&D.nested&&Array.isArray(D.nested))B=D.nested.map((C)=>this.generateNestedTypeInterface(D.identifier.name,C)).join(`
|
|
104
|
+
\uD83D\uDCA1 Common suggestions:`),E.forEach((C)=>{console.error(` • ${C}`)})}}getCommonSuggestions(D){let F=D.flatMap((E)=>E.getSuggestions()),u=new Map;F.forEach((E)=>{u.set(E,(u.get(E)||0)+1)});let B=Math.ceil(D.length/2);return Array.from(u.entries()).filter(([E,C])=>C>=B).map(([E,C])=>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 h2{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=[],B=[];for(let E of D)try{let C=await E();u.push(C)}catch(C){B.push(C instanceof Error?C:Error(String(C)))}if(B.length>0)throw this.errorHandler.handleBatchErrors(B),new y2(`${B.length} operations failed`,B.filter((E)=>E instanceof ID));return u}}w0();w0();import{access as p2,mkdir as S8,rm as v8,stat as zu,writeFile as f8}from"node:fs/promises";import{dirname as g2,join as Z0,relative as k8}from"node:path";class m2{options;logger;constructor(D){this.options={overwrite:!0,batchSize:10,...D},this.logger=D.logger}async writeFile(D,F,u={}){let B=performance.now(),E=Z0(this.options.outputDir,D),C=u.encoding||"utf-8",$=u.overwrite??this.options.overwrite;try{if(!$)try{await p2(E),this.logger.debug(`Skipping existing file: ${D}`);let z=await zu(E);return{path:E,size:z.size,writeTime:0}}catch{}await this.ensureDirectory(g2(E)),await f8(E,F,C);let X=performance.now()-B,Q=Buffer.byteLength(F,C);return this.logger.debug(`Written ${D} (${Q} bytes, ${X.toFixed(2)}ms)`),{path:E,size:Q,writeTime:X}}catch(X){throw new X0(`Failed to write file '${D}': ${X}`,"write",E,X instanceof Error?X:void 0,{canRetry:!0,alternativePaths:[Z0(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 B=0;B<F.length;B+=this.options.batchSize){let C=F.slice(B,B+this.options.batchSize).map(([X,Q])=>this.writeFile(X,Q)),$=await Promise.all(C);if(u.push(...$),B+this.options.batchSize<F.length)await new Promise((X)=>setTimeout(X,10))}return u}async ensureDirectory(D){try{await S8(D,{recursive:!0})}catch(F){throw new X0(`Failed to create directory '${D}': ${F}`,"create",D,F instanceof Error?F:void 0,{canRetry:!0,permissionFix:`chmod 755 "${g2(D)}"`})}}async cleanDirectory(D="."){let F=Z0(this.options.outputDir,D);try{await p2(F),this.logger.debug(`Cleaning directory: ${D}`),await v8(F,{recursive:!0,force:!0})}catch(u){if(u?.code!=="ENOENT")throw new X0(`Failed to clean directory '${D}': ${u}`,"delete",F,u instanceof Error?u:void 0,{canRetry:!0})}}getRelativeImportPath(D,F){let u=g2(Z0(this.options.outputDir,D)),B=Z0(this.options.outputDir,F),E=k8(u,B);if(!E.startsWith("."))E=`./${E}`;return E.replace(/\.(d\.ts|ts|tsx|js|jsx)$/,"")}async wouldOverwrite(D){let F=Z0(this.options.outputDir,D);try{return await p2(F),!0}catch{return!1}}async getFileStats(D){let F=Z0(this.options.outputDir,D);try{return{size:(await zu(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 o2{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 k2(`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 d2({logger:this.logger,verbose:this.options.verbose||!1,beginnerMode:this.options.beginnerMode||!1,outputFormat:this.options.errorFormat||"console"}),this.errorBoundary=new h2(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 m2({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(B,E)=>{let C={path:`${this.options.outputDir}/${B}`,size:Buffer.byteLength(E,"utf-8"),writeTime:0};return u.set(B,C),C};try{let B=await this.generate(D);return B.forEach((E)=>{let C=u.get(E.filename);if(C)E.path=C.path,E.size=C.size}),B}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}=(Ju(),VF(Yu));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}=VF(Wu);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}=VF(Au);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=[],B=[];if(!D.outputDir)F.push("outputDir is required"),B.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&&!UF("node:path").isAbsolute(D.outputDir))u.push("Using relative path for outputDir - consider using absolute path"),B.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"),B.push("Consider enabling validation for better code quality");return{isValid:F.length===0,errors:F,warnings:u,suggestions:B}}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 B=["resource","complex-type","profile","primitive-type","logical","value-set","binding","extension"];if(!B.includes(D.identifier.kind))F.push(`Schema identifier.kind must be one of: ${B.join(", ")}`)}}if("fields"in D&&D.fields)for(let[B,E]of Object.entries(D.fields)){if(!B.trim())F.push("Field name cannot be empty");if(!E)F.push(`Field '${B}' 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 f2(`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 C=E.identifier?.name;if(!C)return!1;if(u.has(C))return!0;if(F.has(C))return!1;if(u.add(C),"fields"in E&&E.fields){for(let $ of Object.values(E.fields))if($?.type?.name===C)return!0}return u.delete(C),F.add(C),!1})(D)}async generateFiles(D){let F=D.map((u,B)=>()=>this.errorBoundary.withErrorBoundary(async()=>{let E=await this.generateFileForSchema(u,B,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 B=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},C=await this.generateSchemaContent(D,E);if(this.options.validate)await this.validateContent(C,E);let $=E.filename+this.getFileExtension(),X=await this.fileManager.writeFile($,C),Q=performance.now()-B;return this.reportProgress("writing",F+1,u,`Generated ${$} (${X.size} bytes)`),{path:X.path,filename:$,content:C,exports:this.extractExports(C),size:X.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,B;while((B=u.exec(D))!==null)if(B[1]){let C=B[1].split(",").map(($)=>$.trim()).filter(Boolean);F.push(...C)}let E=/export\s+(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/g;while((B=E.exec(D))!==null)if(B[1])F.push(B[1]);return[...new Set(F)]}reportProgress(D,F,u,B,E){if(this.progressCallback)this.progressCallback(D,F,u,B,E);if(B&&this.options.verbose)this.logger.debug(`[${D}] ${B} (${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((B)=>{return this.cache.set(D,B),B});else return this.cache.set(D,u),u}clearCache(){this.cache.clear()}getGenerationStats(){let D=this.generatedFiles.reduce((u,B)=>u+B.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 n2{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 Hu(D);case"PascalCase":return y8(D);case"snake_case":return Mu(D);case"kebab-case":return d8(D);default:return D}}getCustomMapping(D){return this.options.customMappings[D]}shouldBeNullable(D){return!D&&this.options.generateNullable}}function Hu(D){return D.replace(/[-_\s]+(.)?/g,(F,u)=>u?.toUpperCase()||"")}function y8(D){let F=Hu(D);return F.charAt(0).toUpperCase()+F.slice(1)}function Mu(D){return D.replace(/([A-Z])/g,"_$1").replace(/[-\s]+/g,"_").toLowerCase().replace(/^_/,"")}function d8(D){return Mu(D).replace(/_/g,"-")}class i2 extends n2{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 B={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(!B)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!==B)return{name:`${B} & { readonly __brand: '${D}' }`,isPrimitive:!1,importPath:"./brands",nullable:!1,metadata:{isBranded:!0,originalFhirType:D}};return{name:B,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 B=u.name||"unknown";return B==="unknown"?"unknown":`'${B}'`}).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 h8(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 B=this.generateImportStatement(u);if(B)F.add(B)}return Array.from(F).sort()}}function h8(D){return D.replace(/[-_\s]+(.)?/g,(F,u)=>u?.toUpperCase()||"")}class AF extends o2{profilesByPackage=new Map;resourceTypes=new Set;collectedValueSets=new Map;get tsOptions(){return this.options}getLanguageName(){return"TypeScript"}getFileExtension(){return".ts"}createTypeMapper(){let D=this.options;return new i2({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),B="";if("nested"in D&&D.nested&&Array.isArray(D.nested))B=D.nested.map((C)=>this.generateNestedTypeInterface(D.identifier.name,C)).join(`
|
|
105
105
|
|
|
106
106
|
`);if(B)return`${u}
|
|
107
107
|
|
|
@@ -113,9 +113,9 @@ ${B}`;return u}filterAndSortSchemas(D){return this.collectedValueSets=this.colle
|
|
|
113
113
|
`)||"",B=[];if(this.options.includeDocuments){if(B.push("/**"),B.push(` * ${D.identifier.name} value set`),D.description)B.push(` * ${D.description}`);if(D.valueset?.url)B.push(` * @see ${D.valueset.url}`);if(D.identifier.package)B.push(` * @package ${D.identifier.package}`);B.push(" * @generated This file is auto-generated. Do not edit manually."),B.push(" */"),B.push("")}if(B.push(`export const ${F}Values = [`),u)B.push(u);if(B.push("] as const;"),B.push(""),B.push(`export type ${F} = typeof ${F}Values[number];`),this.tsOptions.includeValueSetHelpers)B.push(""),B.push(`export const isValid${F} = (value: string): value is ${F} =>`),B.push(` ${F}Values.includes(value as ${F});`);return B.join(`
|
|
114
114
|
`)}async generateValueSetFiles(){if(!this.tsOptions.generateValueSets||this.collectedValueSets.size===0)return;for(let[D,F]of this.collectedValueSets){let u=this.generateValueSetFile(F),B=`valuesets/${D}.ts`;await this.fileManager.writeFile(B,u),this.logger.info(`Generated value set: ${B}`)}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 B of F)D.push(`export * from './${B}.js';`);let u=D.join(`
|
|
115
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 WF{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},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 JF({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},this.typeSchemaConfig);this.typeSchemaGenerator=u;let B=await u.generateFromPackage(D,F);if(this.schemas=[...this.schemas,...B],this.cache)this.cache.setMany(B)}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[B,E]of this.generators.entries()){this.reportProgress("Generating",2+u/F,4,`Generating ${B}...`);try{let C=await E.generate(this.schemas);D.filesGenerated.push(...C.map(($)=>$.path||$.filename))}catch(C){D.errors.push(`${B} generator failed: ${C instanceof Error?C.message:String(C)}`)}u++}}reportProgress(D,F,u,B){if(this.progressCallback)this.progressCallback(D,F,u,B);if(this.options.verbose&&B)this.logger.debug(`[${D}] ${B}`)}}import{existsSync as p8}from"node:fs";import{readFile as g8}from"node:fs/promises";import{resolve as Mu}from"node:path";var t2={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:""},AF=["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 _u{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 B=["verbose","overwrite","validate","cache"];for(let E of B)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,C)=>{if(typeof E!=="string")F.errors.push({path:`packages[${C}]`,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,C)=>{if(typeof E!=="string")F.errors.push({path:`files[${C}]`,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 B=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let E of B)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,B=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let E of B)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 B=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let E of B)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 B=["includeConstraints","includeDocumentation","strictMode"];for(let E of B)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,B=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let C of B)if(u[C]!==void 0&&typeof u[C]!=="boolean")F.push({path:`typeSchema.${C}`,message:`${C} must be a boolean`,value:u[C]});let E=["cacheDir","cacheKeyPrefix"];for(let C of E)if(u[C]!==void 0&&typeof u[C]!=="string")F.push({path:`typeSchema.${C}`,message:`${C} must be a string`,value:u[C]});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 C=u.profiles;if(C.autoDetect!==void 0&&typeof C.autoDetect!=="boolean")F.push({path:"typeSchema.profiles.autoDetect",message:"autoDetect must be a boolean",value:C.autoDetect})}return F}}class Vu{validator=new _u;async autoload(D=process.cwd()){let F=await this.findConfigFile(D);if(F)return this.loadFromFile(F);return{...t2}}async loadFromFile(D){try{let F;if(D.endsWith(".ts")||D.endsWith("")){let E=await import(Mu(D));F=E.default||E}else{let B=await g8(D,"utf-8");F=JSON.parse(B)}let u=this.validator.validate(F);if(!u.valid){let B=u.errors.map((E)=>`${E.path}: ${E.message}`).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 HF{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 C0(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 AF({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 pD({verbose:this.options.verbose,logger:this.logger.child("Schema"),treeshake:this.typeSchemaConfig?.treeshake,manager:this.options.manager},this.typeSchemaConfig);this.typeSchemaGenerator=u;let B=await u.generateFromPackage(D,F);if(this.schemas=[...this.schemas,...B],this.cache)this.cache.setMany(B)}async loadFromFiles(D){if(!this.typeSchemaGenerator)this.typeSchemaGenerator=new pD({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[B,E]of this.generators.entries()){this.reportProgress("Generating",2+u/F,4,`Generating ${B}...`);try{let C=await E.generate(this.schemas);D.filesGenerated.push(...C.map(($)=>$.path||$.filename))}catch(C){D.errors.push(`${B} generator failed: ${C instanceof Error?C.message:String(C)}`)}u++}}reportProgress(D,F,u,B){if(this.progressCallback)this.progressCallback(D,F,u,B);if(this.options.verbose&&B)this.logger.debug(`[${D}] ${B}`)}}import{existsSync as p8}from"node:fs";import{readFile as g8}from"node:fs/promises";import{resolve as qu}from"node:path";var t2={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:""},MF=["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 _u{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 B=["verbose","overwrite","validate","cache"];for(let E of B)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,C)=>{if(typeof E!=="string")F.errors.push({path:`packages[${C}]`,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,C)=>{if(typeof E!=="string")F.errors.push({path:`files[${C}]`,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 B=["generateIndex","includeDocuments","strictMode","includeProfiles","includeExtensions","includeCodeSystems","includeOperations","generateValueSets","includeValueSetHelpers"];for(let E of B)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,B=["includeCardinality","includeTypes","includeConstraints","includeInvariants","validateRequired","allowAdditional","strictValidation","collectMetrics","generateAssertions","generatePartialValidators","optimizePerformance","includeJSDoc","generateCompositeValidators"];for(let E of B)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 B=["includeRuntimeValidation","includeErrorMessages","treeShakeable","strictGuards","includeNullChecks","verbose"];for(let E of B)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 B=["includeConstraints","includeDocumentation","strictMode"];for(let E of B)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,B=["enablePersistence","validateCached","forceRegenerate","shareCache"];for(let C of B)if(u[C]!==void 0&&typeof u[C]!=="boolean")F.push({path:`typeSchema.${C}`,message:`${C} must be a boolean`,value:u[C]});let E=["cacheDir","cacheKeyPrefix"];for(let C of E)if(u[C]!==void 0&&typeof u[C]!=="string")F.push({path:`typeSchema.${C}`,message:`${C} must be a string`,value:u[C]});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 C=u.profiles;if(C.autoDetect!==void 0&&typeof C.autoDetect!=="boolean")F.push({path:"typeSchema.profiles.autoDetect",message:"autoDetect must be a boolean",value:C.autoDetect})}return F}}class Vu{validator=new _u;async autoload(D=process.cwd()){let F=await this.findConfigFile(D);if(F)return this.loadFromFile(F);return{...t2}}async loadFromFile(D){try{let F;if(D.endsWith(".ts")||D.endsWith("")){let E=await import(qu(D));F=E.default||E}else{let B=await g8(D,"utf-8");F=JSON.parse(B)}let u=this.validator.validate(F);if(!u.valid){let B=u.errors.map((E)=>`${E.path}: ${E.message}`).join(`
|
|
117
117
|
`);throw Error(`Configuration validation failed:
|
|
118
|
-
${B}`)}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
|
|
118
|
+
${B}`)}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 MF){let u=qu(D,F);if(p8(u))return u}return null}mergeWithDefaults(D){return{...t2,...D,typescript:{...t2.typescript,...D.typescript}}}}var m8=new Vu;async function qF(D){return m8.autoload(D)}var Ku={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 ${$}'
|
|
119
119
|
|
|
120
120
|
The CLI has been simplified and no longer uses subcommands.
|
|
121
121
|
|
|
@@ -123,7 +123,7 @@ The CLI has been simplified and no longer uses subcommands.
|
|
|
123
123
|
`+`❌ Old: atomic-codegen generate typescript
|
|
124
124
|
|
|
125
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 o8(F);if(!u){let $=
|
|
126
|
+
Create an atomic-codegen.config.ts file to get started.`),process.exit(1)}let F=process.cwd(),u=await o8(F);if(!u){let $=MF.map((X)=>` - ${X}`).join(`
|
|
127
127
|
`);KD(`No configuration file found. Please create one of the following files in your project root:
|
|
128
128
|
${$}
|
|
129
129
|
|
|
@@ -136,13 +136,13 @@ export default defineConfig({
|
|
|
136
136
|
typescript: {
|
|
137
137
|
generateIndex: true
|
|
138
138
|
}
|
|
139
|
-
});`),process.exit(1)}let B=await
|
|
140
|
-
`);await i8(z,Y,"utf-8");let W=Date.now()-$;if(
|
|
139
|
+
});`),process.exit(1)}let B=await qF(F),E=D.verbose??B.verbose??!1,C=jD({verbose:E,prefix:"Generate"});try{if(B2("Starting generation from config"),E)C.info(`Config file: ${u}`),C.info(`Output directory: ${B.outputDir||"./generated"}`),C.info(`Packages: ${B.packages?.length||0}`),C.info(`Files: ${B.files?.length||0}`),C.info(`TypeScript generation: ${B.typescript?"enabled":"disabled"}`);let $=new HF({outputDir:B.outputDir||"./generated",verbose:E,overwrite:B.overwrite??!0,validate:B.validate??!0,cache:B.cache??!0,typeSchemaConfig:B.typeSchema,logger:C});if(B.packages&&B.packages.length>0){C.info(`Loading packages from config: ${B.packages.join(", ")}`);for(let Q of B.packages){let[z,Y]=Q.includes("@")?Q.split("@"):[Q,void 0];$.fromPackage(z,Y)}}else if(B.files&&B.files.length>0){C.info(`Loading files from config: ${B.files.join(", ")}`);for(let Q of B.files)$.fromFiles(Q)}else throw Error("No data source specified in config. Please configure 'packages' or 'files' in your config file.");if(B.typescript){if(E)C.info("Configuring TypeScript generation from config"),C.debug(`Module format: ${B.typescript.moduleFormat||"esm"}`),C.debug(`Generate index: ${B.typescript.generateIndex??!0}`),C.debug(`Include docs: ${B.typescript.includeDocuments??!1}`),C.debug(`Naming convention: ${B.typescript.namingConvention||"PascalCase"}`);$.typescript(B.typescript)}if(!B.typescript)throw Error("No generators configured. Please enable 'typescript' in your config file.");if(E)$.onProgress((Q,z,Y,W)=>{let J=Math.round(z/Y*100);C.progress(`[${Q}] ${J}% - ${W||"Processing..."}`)});C.step("Executing generation...");let X=await $.generate();if(X.success){if(s0(`Generated ${X.filesGenerated.length} files in ${X.duration.toFixed(2)}ms`),C.dim(`Output directory: ${X.outputDir}`),X.warnings.length>0)for(let Q of X.warnings)u2(Q)}else{KD(`Generation failed with ${X.errors.length} errors`);for(let Q of X.errors)C.dim(` ${Q}`);process.exit(1)}}catch($){KD("Generation failed with unexpected error",$ instanceof Error?$:Error(String($))),process.exit(1)}}};async function o8(D){for(let F of MF){let u=l8(D,F);if(c8(u))return u}return null}import{mkdir as n8,writeFile as i8}from"node:fs/promises";import{dirname as t8}from"node:path";var Ru={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 qF(process.cwd());F.step("Generating TypeSchema from FHIR packages"),F.info(`Packages: ${D.packages.join(", ")}`),F.info(`Output: ${D.output}`);let B=D.singleFile!==void 0?D.singleFile:u.typeSchema?.singleFile??!1,E=B?"ndjson":D.format;F.debug(`Format: ${E}${B&&D.format==="json"?" (forced from json due to singleFile)":""}`);let C=D.treeshake&&D.treeshake.length>0?D.treeshake:u.typeSchema?.treeshake;if(C&&C.length>0)F.info(`Treeshaking enabled for ResourceTypes: ${C.join(", ")}`);if(B)F.info("Single file output enabled (NDJSON format)");let $=Date.now(),X=new pD({verbose:D.verbose,treeshake:C}),Q=[];for(let J of D.packages){let[M,q]=J.includes("@")?J.split("@"):[J,void 0];F.progress(`Processing package: ${M}${q?`@${q}`:""}`);let H=await X.generateFromPackage(M,q);Q.push(...H)}if(Q.length===0)throw Error("No schemas were generated from the specified packages");let z=D.output;await n8(t8(z),{recursive:!0});let Y;if(E==="json")Y=JSON.stringify(Q,null,2);else Y=Q.map((J)=>JSON.stringify(J)).join(`
|
|
140
|
+
`);await i8(z,Y,"utf-8");let W=Date.now()-$;if($2(`Generated ${Q.length} TypeSchema definitions`,W,{schemas:Q.length}),F.dim(`Output: ${z}`),D.verbose){F.debug("Generated schemas:");let J=Q.map((M)=>`${M.identifier?.name||"Unknown"} (${M.identifier?.kind||"unknown"})`);E0(J)}}catch(u){F.error("Failed to generate TypeSchema",u instanceof Error?u:Error(String(u))),process.exit(1)}}};var Uu={command:"typeschema [subcommand]",describe:"TypeSchema operations - generate, validate and merge schemas",builder:(D)=>{return D.command(Ru).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:"),E0(["generate Generate TypeSchema files from FHIR packages"]),console.log(`
|
|
141
141
|
Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),console.log(`
|
|
142
|
-
Examples:`),
|
|
143
|
-
`),r0("Available typeschema subcommands:"),
|
|
144
|
-
Use 'atomic-codegen typeschema <subcommand> --help' for more information about a subcommand.`),process.exit(1)}};async function s8(D){
|
|
142
|
+
Examples:`),E0(["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:"),E0(["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 s8(D){E2({verbose:D.verbose||D.debug,timestamp:D.debug})}function r8(){return R3(kF(process.argv)).scriptName("atomic-codegen").usage("$0 <command> [options]").middleware(s8).command(Uu).command(Ku).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)C2("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
145
|
Use 'atomic-codegen <command> --help' for more information about a command.`),console.log(`
|
|
146
146
|
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
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 ju(){await r8().parseAsync()}if(
|
|
148
|
+
Use --help for usage information`),process.exit(1)}).wrap(Math.min(120,process.stdout.columns||80))}async function ju(){await r8().parseAsync()}if(UF.main==UF.module)ju().catch((D)=>{console.error("CLI Error:",D instanceof Error?D.message:D),process.exit(1)});
|