@weadmin/weixin-minigame-helper-mcp 0.1.22 → 0.1.23

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.
@@ -1 +1,2879 @@
1
- 'use strict';const _0x484728=_0x1520,_0x57ff92=_0x1520;(function(_0x13c491,_0x4190c0){const _0x37884d=_0x1520,_0x4daea0=_0x1520,_0x3a21aa=_0x13c491();while(!![]){try{const _0x23bb90=parseInt(_0x37884d(0x131,'DJH3'))/0x1*(parseInt(_0x37884d(0x22a,'X9AZ'))/0x2)+parseInt(_0x37884d(0x159,'z#x!'))/0x3+-parseInt(_0x37884d(0x14e,'2Gw^'))/0x4*(parseInt(_0x37884d(0x132,'V(Ka'))/0x5)+parseInt(_0x4daea0(0x185,'1fA@'))/0x6+-parseInt(_0x4daea0(0x13c,'ehxD'))/0x7*(parseInt(_0x37884d(0x1eb,'Qsq6'))/0x8)+-parseInt(_0x4daea0(0x133,'#*WC'))/0x9*(parseInt(_0x4daea0(0x1d9,'ehxD'))/0xa)+parseInt(_0x4daea0(0x147,'z]G['))/0xb*(parseInt(_0x37884d(0x1cb,'2Gw^'))/0xc);if(_0x23bb90===_0x4190c0)break;else _0x3a21aa['push'](_0x3a21aa['shift']());}catch(_0xb42867){_0x3a21aa['push'](_0x3a21aa['shift']());}}}(_0x3795,0x82939));var path,fs,os,import_child_process,CI_PACKAGE,CI_VERSION,_installDir,_extensionDir,_installing,_statusInfo,_statusListeners,__create=Object['create'],__defProp=Object[_0x484728(0x11b,'%7Du')],__getOwnPropDesc=Object[_0x484728(0x192,'DJH3')],__getOwnPropNames=Object[_0x57ff92(0x1e0,'7P(v')],__getProtoOf=Object[_0x57ff92(0x16d,'1fA@')],__hasOwnProp=Object['prototype'][_0x484728(0x1f2,'WV6r')],__esm=(_0x259238,_0x4fbcd2)=>function(){return _0x259238&&(_0x4fbcd2=(0x0,_0x259238[__getOwnPropNames(_0x259238)[0x0]])(_0x259238=0x0)),_0x4fbcd2;},__export=(_0x37de89,_0x333618)=>{for(var name in _0x333618)__defProp(_0x37de89,name,{'get':_0x333618[name],'enumerable':!0x0});},__copyProps=(_0x5ed90f,_0x1f0405,_0x48076d,desc)=>{const _0x2fbc52=_0x57ff92,_0x2411df=_0x484728,_0x5e2456={'dUbfL':function(_0x59cf84,_0x1b98f0){return _0x59cf84==_0x1b98f0;},'PMCbN':function(_0x100bcf,_0x202124){return _0x100bcf===_0x202124;}};if(_0x1f0405&&'object'==typeof _0x1f0405||_0x5e2456[_0x2fbc52(0x126,'X&aX')](_0x2411df(0x176,'u5VZ'),typeof _0x1f0405)){for(let _0x8a2f8f of __getOwnPropNames(_0x1f0405))__hasOwnProp[_0x2411df(0x160,'UxQ*')](_0x5ed90f,_0x8a2f8f)||_0x5e2456['PMCbN'](_0x8a2f8f,_0x48076d)||__defProp(_0x5ed90f,_0x8a2f8f,{'get':()=>_0x1f0405[_0x8a2f8f],'enumerable':!(desc=__getOwnPropDesc(_0x1f0405,_0x8a2f8f))||desc[_0x2411df(0xfb,'X9AZ')]});}return _0x5ed90f;},__toESM=(_0x4f31e5,_0x99e344,_0x1f94cf)=>(_0x1f94cf=null!=_0x4f31e5?__create(__getProtoOf(_0x4f31e5)):{},__copyProps(!_0x99e344&&_0x4f31e5&&_0x4f31e5[_0x484728(0x10f,'6t$Q')]?_0x1f94cf:__defProp(_0x1f94cf,_0x484728(0x1e3,'z]G['),{'value':_0x4f31e5,'enumerable':!0x0}),_0x4f31e5)),__toCommonJS=_0x3b939b=>__copyProps(__defProp({},_0x57ff92(0x1bb,'%7Du'),{'value':!0x0}),_0x3b939b),ci_installer_exports={};function setStatus(_0x4fcc47){_statusInfo=_0x4fcc47;for(const _0x4e45b4 of _statusListeners)try{_0x4e45b4(_0x4fcc47);}catch{}}function onCiInstallStatusChange(_0x247e18){const _0x2762fe={'dzMjE':function(_0x3cfa82,_0x4aad3b){return _0x3cfa82(_0x4aad3b);}};_statusListeners['add'](_0x247e18);try{_0x2762fe['dzMjE'](_0x247e18,_statusInfo);}catch{}return()=>_statusListeners['delete'](_0x247e18);}function _0x3795(){const _0x5885d1=['BmkBimoCf8kOWRmhWRFdUgS8','eeamls8BWOPlW4xcVSoafYPJ','awtdTmk3','gmk3WRLv','WOJdRSomsHa','WRWUCfu','W4PwW4pdQsKKWRe','WPFdRSkgqSk0kHFdPq','lN50W4S0hSk6W4VdGCoPfmkmWR0','k8kgvgNcUhW','W7hcUqmhWQy','WQe6ALm','s8o/W6BcNW','imkHW4BdM8oUhIFcL0JdMSoijq','p8oNW7qZWPG','ESkvWPZdLwu','W5lcGqq','WPjNWQaVW5tdNCkJhW','pSoQW605WO3dTCkq','fCkepG','WRpdISo9W55yW4BdSdiy','WOhcT8oIW5RcJa','iSkXW5tdLW','W7HwsHW','fh/dS8kTW4y','aSoGW7VdGxK','rSo+W7aF','WOCTksmB','W5RcSmkyeuS9pCo0W6dcS8oTW5m','zSogoKGhW7nlWQxdJXSfW64SWQLPWQ3cSW','WPuQW69AhSoQW4HjWPCgf8kXs8kp','a8keex8EW6fUWOC','e0RcLq','WQHbtbRcIgTOrSozu0tdHmkXymoyWPXSrSoFWQy','aMxdTCk2W5ePh2VcNG','W6aKshbIWQ3dJ3mmW5BdKLi','imoVWPq3','ohpcGxjpW6i','dKNcI8k/WO8','WOVdRmozwWO','W5JcNI0MWPNdU8oEng3cTunf','WQSQauuZFSobWP4/hmodW4G','WRO0W6nbha','WO/cNrhdM8obE8kFWRpcIq','gYhcMYpcS8kmWP7dSqhcJmk2WRBcGSovwCoJW4lcGCkAW73cNI/cI8kYBIPoWQHUWRFdNHtdTY9eW6RcLSkCWRlcUCk/bCoxsmoYa2TDWR9DWPhdImkIW5xdVCkromk+W41aW6bC','lCo2W5xdT3hdJ8oOW6atwNvRfmocggVdHtb8qq','W6hdG8k0WOtdTmoeWPy1W47dPmk1at0','WRFdJ8oQW4nlW7NdPtKF','WRHWbmkj','r0CBkJOmWQCxW57dPq','W7qxgem','qmkoWPxdT0i','WO9jcCkixG','WQ86B1e','W7dcJ8k2','jHrPxG','WOJdOJZdJ8ovzSoDW5i','sSoVebS','nSkgyW/dQq','W7FcGCoCW4vyW7RdU3Wsq8kUWPm','WOZcMWZdMmokF8kcW7VcGmktpwBcSmkupsGgxmkWcSkhCmk8W7tcICkPW6O','kmotfCkPWOy','WQddRCktfgDBWOScWRZcMJOrwSoJz+w1O+wVSUIGLW','WR1YesC','W6dcVmoNWPSxzmoe','f8o/W7W2WOFdT8kskmkMaWJdKa','WQ58BmkKWPjSaZKTmwnqkhq','pSoVWPW','qJyLWPPUr8oSW4xdGSofE8or','W4K8WPas','WOtdT8oSFCkSjZBcI8k5axBdLCkpWP9lySkNW5RdSuZdV8oACq','zSoyW4VcTue','rCo5W73cN1GZja','W5JIGzFcOuyDW7hdIuNdHrqvW6LAWOvgkmkbWQ3cK8o9zq','bmorW7VdLK4','W78dh07dP8kTW69v','WR/dQ8kscq','W5FcT8kgu8kn','jMaNkqG','g8oNW53dUG','WP3dJSoSW7nq','i8o5m8kFWQ4','oab3uW','W5nWW6tdSIKeWQJdHmoaW43cKsulhSkdW75qW6NcU2fRW4/dMW','WQn2CCkA','smo4W6SFm8kNiq','BCkNWPBdQ2q5cCojD8k1','emkIW6xdP8o7','qIBcS8oTWO9+b0VcL8k2WRDR','xmoKW6Oz','W7SSlSohW5G7qZGZaN5ZnW','iSoHWPGOa1f1CmoafIVdNa','a8kbwxVcUgi3','D8kqmSommmkTWRmhWOa','WPvKhWKX','bmk0WOzBnW','WR0YsxxcGa','d0dcHSkPWOKv','WQf8eZy','WQJdQSkiehjBWOuhWQlcNG','W6vWBdZcLa','WRKxaL7dTSkWW7ms','g8oVWQmbdSoWd3NcJG58','WPPIW7xdLcydWPBcM8ocW5tcMJ4ybSkQW74oW6lcRgrRW57dHSkj','fwe7wG','W6RcUmo5WO1yACos','zCo2W6hdLCoIlJ/cQa','k2/cNwm','mmk+WR59bq','WRCGlHqv','n8k8W47dJmoCbbJcI3xdGa','e8knWRaSWPm','wmo4W7S','W67cU8kGA8k7oNVdHCkIhtpcK8kfWOrrDmo+WPpdUqxdVSowmCoxWQRdNmokcSoWACkgW4RdKG4sW5tdRmoTn8oaW4FdJmkF','phlcGhHj','vCkbkCkxyMhdKL3cJ8kJW5me','WRVdJ8oTW4vtWRxdUt0ixSo6W5NcJsKDDaNcVCkE','WR1Uc8kp','nCkxtq/dJ8kLiWOzDtddLKKkWP7dOmoWzZrywmo6WPBcTtbMW6C','WOOxsvxcPG','imkRW4JdIW','cMVdKSozW7tdN38p','cu4tiW','e8k4WQbclq','vSkbkCkhuwNdRvJcJSkNW78zW4CKW7C','CcdcL3LpW6pcSCkpz8k0W6JdT10/kJFdRdmAwMa5t8kSWO7cUcO9WRHWhmotWRNdUZKmDSoYW7xdUa','WQHcsGFcIxmLuCoqeGS','WOZcNbddMG','zSo+aXz1WRhdGCopsSopWRtcNG','umoReqz/WRFdGW','WQi6BLG','W6fnsGdcJwTHr8kD','ww7cRa','zCk0WPVdSwizi8oEEG','DYCPWPW','u8oqpW','aMpcMZPsW7/cU8oBB8kRWQtdOuOoBhFdPZiCxMeIwSk/WP/cPw4WWRzWf8ovW63cTtaxi8o1W7/cQ8kQW6qfW4bIgHftWOr6WQKrfmoKwmodw8oAWQddLrvbk190dCohtSoct0ZcJmoJW5uJW63cSmoTySoKWRTbza','AokhPYq','bSo3hCkYWOFcGa','ffSFnd4AWOjwW5NcPa','WOhdTt4','tSkAk8oFbq','bae7WPpcNCkMhL/dIqBdK3pdVY5ud8klgq','cSo5hCkW','iNRcH8kVWQCFWQldUr7cLq','xmorWPiho8oCcW','hSk4WQ8FWR4','WPiSW6HD','W7PgsrJcJwrO','zCk6WOZdQ3eTpW','WPNdO8oFrW','hSoPW5NdSx7dH8o9','W6m6pw/dMW','jSkxqH7dImkUjG','aSoZWPyCl8oW','wSkMW5ldOxtdJCo7W6WoAx1jemoqbMpdKdbWq1m+WQK1WOhdO8kigCosW7GZzeldL8kYWPddMmk+WOe','dSoUWQqhoG','WRldHmo3W5bEW70','nSk0WRvsmCkmW6HdW67dQSkcW485rG','W6hdHCkYWOldVmojWPSuW7FdOmkzhJu','W6qHoIGyW4tdIM8','aSkKWR1DeCkoWQm','r8kCdColhG','W4FdUCourH0','rCogmLirW4vlWQxdJ2GzW7i9','hCoRgGfSWRhcHSohv8o2W6hdMK7dLCk4WQRcImkVW43cMmov','BokcM8k9imkFW7/cMYRdTc1hWO1HW4hcTmojWPRcS8oVW5ZcKq','WQpcSmoWWO0x','cmkWW6RcN00SodjB','ACk7WPS','qCo6W7O/iG','bSkpuwlcR0m9ss8','wLSmWRJcJq','qmorp1mxW6y','WPjJWPS3W5hdMmkUca','W4O9WOOiW6FdKSkxgXP3','WR/dOCknexzkWOe','fmk6WQKA','W4ZcQSkR','W5BcQrSgWRO','j8kmW4tdUSo4','k8oQW6KAWPVdUmkLp8k7lK3cIMFdM8kFWOJcLSkLWRe','W7bMW7JdI3W','qmoDf3iw','WORdP8olsazMjG','WO7cR8k/','bmoRW6FdRxtdJq','W43dQs3dJCoOE8osW53dG8khWRzuWQu','zCk2WPhdSwa4nCoxA8k3e39SW4bp5A6L6kg25AEC6lEC','wCoReGy','WQ7cPSkQqSkS','BCkNWPRdUW','WQKRWRhcPsxcHCkpWOpcGmkBpSoR','eSk5WRPv','WQ9YfSkd','W4uCWPCiW7i','Fdq2WPz3','mmkMW4BdImod','WRNcN8oTW58','WORcOCkRw8kTFSkniSkEW7lcL8k3a3W','q0auWPC','W7mtnwRdLG','WOVdIaGRWQG','WRHKa8kj','eSoIWPOHb1O/lmoFcZddM8oprW','W5Kuee/dTSkOWQ9jWOOfu8k7wbDD','pmoVWP8MpvT/oSoFcshdGq','DMtcM2rpWR7cPCoaASkYWQtdOuT8l3xdVdKwqx49vmkHWPVcUMW8WQ05gCopWQpcUJnmACoVWR7cVCkWW60iW4jKgW','WOpdTt3dICozCSoCW5xdMCkfWRyl','W6vGcq','mCkRW5FdHSoUhIFcL0JdMSoijq','C8kBmSolmmkMWRO','WRaUcKHI','WRxdS8kBlLq','BmoUW64MWONdOSkg','WPtdTCopW4ni','sCoReqe','WPBcJ8kUBSkC','WO9IW6ddVXCeWQRcJmo+W53cKs8','B8k+WPldVt4GkCoFDW','W5ZcMHFdK8obEmkxWRNcN8kpmtdcOSkdkM8vr8o2h8oho8kY','pqfIfMm','WR8VyK/cP8k8WRPmsxe','WPdcJa3dLCoBDa','ymoZpu08','WR18gcCnW7ddKvejW6NdLgy','FCk/W78EWRVdSmkGnW','WQXZf8kcCIv4W4ug','WOddUYe','g8krrMm','gCoLWQmAl8oJgq','o8oUWP8MgNL2','WQVdPCkuexjn','oColW5m4WQ0','WRNcSmk5D8kXCCk6nCkdW5/dKSkagxhdJ8oPWPiLfuCvnvbag8o1AYO8EqSUiq','WOpdMXmQ','5Q6F5z+b5A+Q6kg3WO9XWP/cU8kzWPeMF8k2WPi5A0HqWRFVVAtPPBJMRlBKV63NLRBVV7BNUAdPNOtdISolB23NPPdVV7dIGkq','mmkxqaldHCkU','tCo1W6hcLK02','W6SJt3DQW6VdRhmzW4JdTa','W7hcL8k2AmkY','x8orkfuvW6rh','zgJcKJVcNG','l8kbbokbO8kg','EmkQWOZdSa','kxxcGx8','WOavthZcTG','s8klWQ3dOvO','W7D8W6NdVW','kmoVWQuXoq','hmk5WR1E','W7T/W6hdSN4','cCkUWRmC','WR7dSmkCcwjA','cCkfv27cSu82uIldL0bQhq','W6BcKCkQWOisW6pdMXOEymol','wmoBmKG','W6u4gqS+FmoxWO5+hCoaWOW9W5TJW7ZcUmkycCoq','t8oXW6lcLa','W4z0W6hdVhJcKmkoWOhcR8k5n8oIWOFcU0rZWOriW57cPdGScNnaWQaOgL7dGCkDB0dcMqdcNCkGl28FW5BcJCoHWOevzSkRsbieWQqzmwa+WO3dKgr/tXeeW6fKrNqWbfX9W5rKk1tdPmkHW4VdLSkOW7nUWOZcKSohquf1WO7dQmkymCoZhuO9qSosW4dcKCoDW4ueW6lcMsJdTuWtaW','WPZdLruW','WPZdP8oCxbP4n8ks','A1ClWPhcIG','WQJdTSkpeMu','WO/dSZFdIa','WOtdRCoerW','bwRdN8oe','ySoLW64','lqD2vcK','W7b2W7pdONZdMSkB','gSk5WRm','W65NW6hdPwJdJG','W6S5nSoAW44','CYKTWPC','sfmlWP3cJq','f8k0WRC','mCkgrqxdKSk4wq4eCW','WOVdO8o7uWq','WOPMW7pdTq','jhSSpWa','WQjQhSkp','EZRdKG','g8oHWRmEiSoYgstcHrP2eW','WQFcIGRcN8ogCSkfWQhcKCknohxcO8k9EeaewSkYcCkkn8oMW7hdMSkVW6RcMCkmpIeUW5K','guZcKCkO','g8kfr27cS2qusd7dLW','W7KQWRutW4C','WPVcIa7dL8kbDSkf','t8oReHL/WRpdGW','WRVdJ8oSW5PpW6FdQd4xsa','fmoLW4tdMwS','FmkJW47dIW','fCk+WR1Cmmk/WRDdW7tdP8ktW5uN','WQD+W43dTba','WQrYdIW','W6KehKFdTSkNW7qvWPWesCk0xbvCxmkiy8kH','gSoPW5m','WRf+dcWu','aCoyWRiNjq','WPlcTCkRFa','WQy0ALm','W4u6WPuiW6pdJa','gCoVWR8b','W7NcTSoirs8EWOSRWP7cOq9X','uSkym8oUjW','t8k/mSoBpG','WP0TW7vbfW','W4yHWOStW7q','cgW/xfO','jSkeWQuhWPLfWPqVCSkF','n8k2W5xdKmoA','q2tcPsVcUCkF','WRvMeIeMW7tdKvS','aMtdPCkpW54ThwZcGmkaWQC','hx7dOa','WPzGnc0w','iSoGW6L4WOxdUmkgoCk1mKtcNxC','nCkatqpdG8knzWSvscddN0S','WRBdK8oRW4jV','yCkXWOZdRheMnSovFq','xSkwjmkbsx/dRKdcLmkS','gudcHmk1WOqvWPBdVH3cGmkRu8oiWPK','WQpcN8o3W4xcICkuW5WjW7ZdJCkr','h2tdLCobW4ldKw5jWR7dGHFdOW','W77dKCo4W5rbW7tdRJLtxSkNWP3dNW','aLCxnt4AWOzgW4pcRW','vCknnmkqAq','WPaiW6jGda','WQpdQ8kjuh5hWPCrWQ/cLZTzxq','o2/cO0rZ','W6iXCa','W6lcH8k8EmkM','rCofW63cL3u','xmo4W6Ku','W4igee7dUmkLW6DEWO02b8kwwHWxfSksySoV','W67cJYuR','WOC7dGa2mmogWOiSfCoyW5jO'];_0x3795=function(){return _0x5885d1;};return _0x3795();}function getCiInstallStatus(){return _statusInfo;}function setCiDepsDir(_0x3911d5){const _0x4b1a90=_0x57ff92,_0x1de84e=_0x57ff92,_0x24af7c={'YcUjl':function(_0x46d7b4){return _0x46d7b4();},'PPkhc':function(_0x1dd873,_0x5a86c9){return _0x1dd873!==_0x5a86c9;},'QAsco':_0x4b1a90(0x119,'lcpC'),'dzWVk':function(_0x211f02,_0x25979d){return _0x211f02(_0x25979d);},'CoGAL':'miniprogram-ci\x20已安装'};_installDir=_0x3911d5,_0x24af7c['YcUjl'](isCiInstalled)&&_0x24af7c['PPkhc'](_0x24af7c[_0x4b1a90(0x10b,'7t$W')],_statusInfo['status'])&&_0x24af7c['dzWVk'](setStatus,{'status':_0x1de84e(0x15a,'X9AZ'),'message':_0x24af7c[_0x4b1a90(0x17c,'p1s3')]});}function setCiExtensionDir(_0x2e948c){_extensionDir=_0x2e948c;}async function ensureCiInstalled(_0x2c54dc){const _0x51181a=_0x484728,_0x2b619d=_0x484728,_0x1de9e6={'jVpXG':'package.json','gluZq':'installed','xwfSC':_0x51181a(0x169,'4tX)')},_0x5c916d=getBundledCiPath();if(_0x5c916d)return _0x5c916d;const _0x13c161=getDepsDir(),_0x411f97=path[_0x51181a(0x1f1,'z#x!')](_0x13c161,_0x2b619d(0x1fb,'1pOf'),CI_PACKAGE);if(fs['existsSync'](path['join'](_0x411f97,_0x1de9e6[_0x51181a(0x19a,'6t$Q')])))return _0x1de9e6['gluZq']!==_statusInfo[_0x51181a(0x228,'4tX)')]&&setStatus({'status':_0x2b619d(0x1ae,'aMWz'),'message':_0x1de9e6[_0x51181a(0x200,'4tX)')]}),_0x411f97;if(_installing)return _installing;_installing=doInstall(_0x13c161,_0x2c54dc);try{return await _installing;}finally{_installing=null;}}async function retryCiInstall(_0x1b0563){const _0x5ec3f1=_0x57ff92,_0x43721e=_0x57ff92;return _installing||(_0x5ec3f1(0x1b5,'p1s3')===_statusInfo[_0x43721e(0xe9,'Qsq6')]&&setStatus({'status':_0x43721e(0x122,'4tX)')}),ensureCiInstalled(_0x1b0563));}function isCiInstalled(){const _0x1e82e6=_0x484728,_0x58e23b=_0x484728,_0xa1c6f7={'umvAv':function(_0x4d3d10,_0xd572c1){return _0x4d3d10==_0xd572c1;},'cRVkh':function(_0x4247f7,_0x5ac8ba){return _0x4247f7===_0x5ac8ba;},'bmpnF':function(_0x639b1c,_0x450d2c,_0x16c8b2){return _0x639b1c(_0x450d2c,_0x16c8b2);},'tlOHV':function(_0x341802){return _0x341802();},'rbRkc':function(_0x1d7f3c){return _0x1d7f3c();}};try{if(_0x1e82e6(0x120,'jOm#')!==_0x58e23b(0x1e2,'FfOy')){if(_0xa1c6f7['tlOHV'](getBundledCiPath))return!0x0;const _0x4bb8f7=_0xa1c6f7[_0x58e23b(0x18a,'BcTO')](getDepsDir);return fs['existsSync'](path[_0x1e82e6(0x17f,'1fA@')](_0x4bb8f7,_0x1e82e6(0x20c,'2Gw^'),CI_PACKAGE,'package.json'));}else{if(_0x30fd47&&_0xa1c6f7['umvAv']('object',typeof _0x157033)||_0x1e82e6(0x112,'2Gw^')==typeof _0x91262d){for(let _0x1ef317 of _0x31e769(_0x59a685))_0x1aae5b['call'](_0x572a59,_0x1ef317)||_0xa1c6f7['cRVkh'](_0x1ef317,_0x4f60bb)||_0x27c916(_0x78f4ff,_0x1ef317,{'get':()=>_0x2039b7[_0x1ef317],'enumerable':!(desc=_0xa1c6f7[_0x1e82e6(0x103,'2Gw^')](_0x114723,_0x5b8457,_0x1ef317))||desc[_0x58e23b(0x18e,'4tX)')]});}return _0x73f97e;}}catch{return!0x1;}}function getCiDepsDir(){return _installDir;}function getCiExtensionDir(){return _extensionDir;}function getCiRequirePath(){const _0x58ee65=_0x484728,_0x4138b3=_0x484728,_0x22aa81={'uDNmA':function(_0x331bc0){return _0x331bc0();},'kovtT':_0x58ee65(0x19e,'jOm#')},_0x157f29=_0x22aa81[_0x58ee65(0x214,'7P(v')](getBundledCiPath);if(_0x157f29)return _0x157f29;const _0xf9d542=getDepsDir(),_0x1ce816=path['join'](_0xf9d542,_0x22aa81['kovtT'],CI_PACKAGE);if(!fs[_0x58ee65(0x199,'1Ecb')](path['join'](_0x1ce816,_0x58ee65(0x186,'QHh6'))))throw new Error(_0x58ee65(0x1b3,'S!bC'));return _0x1ce816;}function getBundledCiPath(){const _0x38b242=_0x57ff92,_0x1f1272=_0x484728,_0x5f436b={'FLJhu':_0x38b242(0xf4,'kBZE')};if(!_extensionDir)return null;const _0x341cb0=path[_0x38b242(0x234,'z]G[')](_extensionDir,'node_modules',CI_PACKAGE);return fs[_0x38b242(0x181,'lcpC')](path[_0x38b242(0x235,'H[Jq')](_0x341cb0,_0x5f436b[_0x1f1272(0x1a2,'UxQ*')]))?_0x341cb0:null;}function getDepsDir(){const _0xf7ba5c=_0x57ff92,_0x1b506a=_0x57ff92,_0x45c8b9={'ssNXE':_0xf7ba5c(0x1e8,'Ci&]')};return _installDir||(_installDir=path[_0xf7ba5c(0x106,'UxQ*')](os[_0x1b506a(0x1c2,'7&T9')](),_0xf7ba5c(0x17e,'DJH3'),_0x45c8b9['ssNXE'])),_installDir;}async function doInstall(_0x27982f,_0x166fac){const _0x503a76=_0x484728,_0x52f1e5=_0x57ff92,_0x586591={'AOYoB':'installing','XYQlw':function(_0x2e6d23,_0x482b82){return _0x2e6d23?.(_0x482b82);},'wzuJr':function(_0x55d5e8,_0x37eca1){return _0x55d5e8 instanceof _0x37eca1;},'GHDDx':'failed','LNOAe':_0x503a76(0x1e7,'lcpC'),'hrruE':'package.json','ttGxO':function(_0x1320f3,_0xc9f52f){return _0x1320f3?.(_0xc9f52f);}},_0x1b9fc3=_0x52f1e5(0x217,'Dp@c');setStatus({'status':_0x586591[_0x52f1e5(0x179,'xKPP')],'message':_0x1b9fc3}),_0x586591['XYQlw'](_0x166fac,_0x1b9fc3),fs[_0x503a76(0x1d6,'idnR')](_0x27982f,{'recursive':!0x0});const _0x4e7541=path['join'](_0x27982f,_0x52f1e5(0x11d,'H[Jq'));fs[_0x52f1e5(0x11f,'xKPP')](_0x4e7541)||fs[_0x52f1e5(0x1cf,'FfOy')](_0x4e7541,JSON[_0x503a76(0x14d,'@pDF')]({'name':_0x503a76(0x1a1,'RTFh'),'private':!0x0,'dependencies':{}},null,0x2));const _0x3c767a=_0x52f1e5(0x154,'#v(C')+CI_PACKAGE+'@\x22'+CI_VERSION+'\x22\x20--save\x20--prefer-offline';var _0x5e87f4;setStatus({'status':_0x503a76(0x1da,'ehxD'),'message':_0x5e87f4='执行:\x20npm\x20install\x20'+CI_PACKAGE+'@\x22'+CI_VERSION+_0x503a76(0xea,'1fA@')}),_0x166fac?.(_0x5e87f4);try{(0x0,import_child_process[_0x52f1e5(0x163,'1pOf')])(_0x3c767a,{'cwd':_0x27982f,'stdio':_0x503a76(0x127,'^BhC'),'timeout':0x2bf20,'env':{...process['env'],'NODE_ENV':''}});}catch(_0x239df4){const _0x46c669=_0x586591[_0x52f1e5(0x1d7,'eJMp')](_0x239df4,Error)?_0x239df4[_0x52f1e5(0x1ac,'Ci&]')]:String(_0x239df4),_0x7adc76=_0x503a76(0xf5,'Dp@c')+CI_PACKAGE+_0x503a76(0x157,'0eOn')+_0x46c669;throw setStatus({'status':_0x586591[_0x52f1e5(0x172,'X&aX')],'message':_0x586591[_0x52f1e5(0x221,'UxQ*')],'error':_0x7adc76}),new Error(_0x7adc76);}const _0x53ea01=path[_0x503a76(0x137,'X&aX')](_0x27982f,_0x52f1e5(0x1f9,'QHh6'),CI_PACKAGE);if(!fs['existsSync'](path[_0x52f1e5(0x22b,'FfOy')](_0x53ea01,_0x586591[_0x52f1e5(0x118,'X9AZ')]))){const _0x46ad05='[ci-installer]\x20npm\x20install\x20succeeded\x20but\x20'+CI_PACKAGE+'\x20was\x20not\x20found\x20at\x20'+_0x53ea01+'.';throw setStatus({'status':_0x503a76(0x213,'4tX)'),'message':'miniprogram-ci\x20安装失败','error':_0x46ad05}),new Error(_0x46ad05);}const _0x5b84a1='miniprogram-ci\x20安装完成\x20✓';return setStatus({'status':_0x503a76(0x188,'7t$W'),'message':_0x5b84a1}),_0x586591[_0x503a76(0x165,'RTFh')](_0x166fac,_0x5b84a1),_0x53ea01;}__export(ci_installer_exports,{'ensureCiInstalled':()=>ensureCiInstalled,'getCiDepsDir':()=>getCiDepsDir,'getCiExtensionDir':()=>getCiExtensionDir,'getCiInstallStatus':()=>getCiInstallStatus,'getCiRequirePath':()=>getCiRequirePath,'isCiInstalled':()=>isCiInstalled,'onCiInstallStatusChange':()=>onCiInstallStatusChange,'retryCiInstall':()=>retryCiInstall,'setCiDepsDir':()=>setCiDepsDir,'setCiExtensionDir':()=>setCiExtensionDir});var init_ci_installer=__esm({'core/real-device/ci-installer.ts'(){const _0x23e366=_0x57ff92,_0x4781ab=_0x484728,_0x21b067={'HQjoR':function(_0x1a8215,_0x86fc72){return _0x1a8215(_0x86fc72);},'CouDz':function(_0x138a57,_0x1e9143){return _0x138a57(_0x1e9143);},'YULOK':_0x23e366(0xfe,'BcTO'),'tOvzF':_0x23e366(0x149,'39$#')};path=__toESM(_0x21b067[_0x23e366(0x15e,'lcpC')](require,'path')),fs=_0x21b067[_0x4781ab(0x224,'kBZE')](__toESM,require('fs')),os=__toESM(_0x21b067[_0x23e366(0x17b,'X9AZ')](require,'os')),import_child_process=require(_0x21b067['YULOK']),CI_PACKAGE=_0x21b067[_0x4781ab(0x204,'WV6r')],CI_VERSION='^2.1.31',_installDir=null,_extensionDir=null,_installing=null,_statusInfo={'status':_0x4781ab(0x116,'7P(v')},_statusListeners=new Set();}}),game_bundler_worker_exports={};module['exports']=__toCommonJS(game_bundler_worker_exports);var import_worker_threads=require(_0x484728(0x12c,'xKPP')),fs2=__toESM(require('fs')),path2=__toESM(require(_0x57ff92(0x1f6,'0c9r')));init_ci_installer();var _enhanceTransform=null,_ciDir=null;function getCiDir(){const _0x53236e=_0x57ff92,_0x4471c4={'TKKyA':function(_0x3195f6){return _0x3195f6();},'LFROs':'miniprogram-ci'};return _ciDir||(_ciDir=isCiInstalled()?_0x4471c4['TKKyA'](getCiRequirePath):require[_0x53236e(0x211,'kBZE')](_0x4471c4['LFROs'])['replace'](/[/\\]dist[/\\]index\.js$/,'')),_ciDir;}function getEnhanceTransform(){const _0x418e4c=_0x484728,_0x31c7fe=_0x484728,_0x2fca89={'OZkYj':function(_0x184b35,_0x5e1797){return _0x184b35(_0x5e1797);},'Bwbrr':_0x418e4c(0x1cd,'7t$W')};if(!_enhanceTransform)try{if(_0x2fca89[_0x31c7fe(0x155,'39$#')]===_0x31c7fe(0x1c3,'u5VZ')){_0x2c57f4=_0x5eb560;for(const _0x34dd11 of _0xdbd1e)try{_0x2fca89['OZkYj'](_0x34dd11,_0x2b8c28);}catch{}}else{const _0x10e78b=getCiDir();_enhanceTransform=require(_0x10e78b+_0x418e4c(0x1fa,'S!bC'));}}catch(_0x42d714){throw new Error(_0x418e4c(0x22e,'Qsq6')+_0x42d714);}return _enhanceTransform;}function readBabelHelper(_0x1edde0){const _0x1576c9=_0x57ff92,_0x61c682=_0x57ff92,_0x405cd3={'rzBqO':_0x1576c9(0x1c9,'BcTO'),'eaVzw':_0x61c682(0x111,'0eOn'),'yRDte':function(_0x42f452,_0x3a32a6){return _0x42f452+_0x3a32a6;}},_0x6e336b=getCiDir(),_0x34443f=_0x1edde0['replace'](_0x405cd3[_0x1576c9(0x198,'#v(C')],'babel_runtime'),_0x545abb=path2[_0x1576c9(0x145,'^BhC')](_0x6e336b,_0x1576c9(0xf6,'%7Du'),_0x405cd3[_0x1576c9(0xef,'z]G[')],_0x405cd3['yRDte'](_0x34443f,_0x61c682(0x1dd,'WV6r')));return fs2[_0x61c682(0x138,'1Ecb')](_0x545abb,_0x1576c9(0x1b8,'jOm#'));}function _0x1520(_0x91c07b,_0xb2c43d){_0x91c07b=_0x91c07b-0xe6;const _0x3795ac=_0x3795();let _0x1520d9=_0x3795ac[_0x91c07b];if(_0x1520['CTIBwm']===undefined){var _0xba18a1=function(_0x2069e6){const _0x10d9a4='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let _0x59e17e='',_0x32d489='';for(let _0x1e7489=0x0,_0x39ed14,_0x2c38ac,_0x3e4716=0x0;_0x2c38ac=_0x2069e6['charAt'](_0x3e4716++);~_0x2c38ac&&(_0x39ed14=_0x1e7489%0x4?_0x39ed14*0x40+_0x2c38ac:_0x2c38ac,_0x1e7489++%0x4)?_0x59e17e+=String['fromCharCode'](0xff&_0x39ed14>>(-0x2*_0x1e7489&0x6)):0x0){_0x2c38ac=_0x10d9a4['indexOf'](_0x2c38ac);}for(let _0x328b29=0x0,_0x4e7c92=_0x59e17e['length'];_0x328b29<_0x4e7c92;_0x328b29++){_0x32d489+='%'+('00'+_0x59e17e['charCodeAt'](_0x328b29)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x32d489);};const _0x5aa33d=function(_0x39a58f,_0x2e925c){let _0x452b8e=[],_0x2a7e3d=0x0,_0x1f3a11,_0xf4fe42='';_0x39a58f=_0xba18a1(_0x39a58f);let _0x39793b;for(_0x39793b=0x0;_0x39793b<0x100;_0x39793b++){_0x452b8e[_0x39793b]=_0x39793b;}for(_0x39793b=0x0;_0x39793b<0x100;_0x39793b++){_0x2a7e3d=(_0x2a7e3d+_0x452b8e[_0x39793b]+_0x2e925c['charCodeAt'](_0x39793b%_0x2e925c['length']))%0x100,_0x1f3a11=_0x452b8e[_0x39793b],_0x452b8e[_0x39793b]=_0x452b8e[_0x2a7e3d],_0x452b8e[_0x2a7e3d]=_0x1f3a11;}_0x39793b=0x0,_0x2a7e3d=0x0;for(let _0x32efda=0x0;_0x32efda<_0x39a58f['length'];_0x32efda++){_0x39793b=(_0x39793b+0x1)%0x100,_0x2a7e3d=(_0x2a7e3d+_0x452b8e[_0x39793b])%0x100,_0x1f3a11=_0x452b8e[_0x39793b],_0x452b8e[_0x39793b]=_0x452b8e[_0x2a7e3d],_0x452b8e[_0x2a7e3d]=_0x1f3a11,_0xf4fe42+=String['fromCharCode'](_0x39a58f['charCodeAt'](_0x32efda)^_0x452b8e[(_0x452b8e[_0x39793b]+_0x452b8e[_0x2a7e3d])%0x100]);}return _0xf4fe42;};_0x1520['vxAcXm']=_0x5aa33d,_0x1520['XeBqpW']={},_0x1520['CTIBwm']=!![];}const _0x4d9742=_0x3795ac[0x0],_0x325d7c=_0x91c07b+_0x4d9742,_0x431dcc=_0x1520['XeBqpW'][_0x325d7c];return!_0x431dcc?(_0x1520['qvkaOE']===undefined&&(_0x1520['qvkaOE']=!![]),_0x1520d9=_0x1520['vxAcXm'](_0x1520d9,_0xb2c43d),_0x1520['XeBqpW'][_0x325d7c]=_0x1520d9):_0x1520d9=_0x431dcc,_0x1520d9;}var BABEL_RUNTIME_ROOT=_0x57ff92(0x1f7,'QHh6');function silenceBabelDeopt(_0x3dbbad){const _0x832bd5=_0x484728,_0x25dae1=_0x57ff92,_0x2dd892={'RGfkH':function(_0x1bf41b,_0x8380ae){return _0x1bf41b(_0x8380ae);}},_0x1c240c=console[_0x832bd5(0xf0,'DJH3')][_0x25dae1(0x1a0,'4aeH')](console),_0x52480d=console[_0x832bd5(0x16e,'QHh6')][_0x25dae1(0x233,'1pOf')](console),_0x56baa1=/deoptimised the styling/i;console['warn']=(..._0x58084b)=>{const _0x468457=_0x25dae1;_0x56baa1['test'](_0x2dd892['RGfkH'](String,_0x58084b[0x0]))||_0x2dd892[_0x468457(0x140,'z#x!')](_0x1c240c,..._0x58084b);},console[_0x832bd5(0x114,'@pDF')]=(..._0x133edc)=>{const _0x5203da=_0x25dae1;_0x56baa1['test'](String(_0x133edc[0x0]))||_0x2dd892[_0x5203da(0x20b,'FfOy')](_0x52480d,..._0x133edc);};try{return _0x3dbbad();}finally{console['warn']=_0x1c240c,console[_0x832bd5(0x1e4,'WV6r')]=_0x52480d;}}function extractBabelRuntimeRequires(_0x4b8481){const _0x1f2f9a=_0x57ff92,_0x58491c=_0x484728,_0x1754dd={'mkcNp':function(_0x52c21a,_0x486dc5){return _0x52c21a!==_0x486dc5;}},_0x1d6f99=[],_0x545477=/\brequire\s*\(\s*['"](@babel\/runtime\/[^'"]+)['"]\s*\)/g;let _0x4c24a9;for(;_0x1754dd[_0x1f2f9a(0x1d5,'^BhC')](null,_0x4c24a9=_0x545477[_0x58491c(0x1ea,'lcpC')](_0x4b8481));)_0x1d6f99[_0x58491c(0x17d,'j[5B')](_0x4c24a9[0x1]);return _0x1d6f99;}function extractHelperDependencies(_0x20ff64,_0x10d708){const _0x5dfa23=_0x484728,_0x446ca6=_0x484728,_0x4655e4={'GBfTH':_0x5dfa23(0x161,'X9AZ'),'HEABL':function(_0x28e315,_0x5d5daa){return _0x28e315+_0x5d5daa;}},_0x2829de=_0x20ff64[_0x446ca6(0x1db,'4tX)')](/\/[^/]+$/,''),_0x1e1a7a=[],_0x4c9df9=/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g;let _0x5adfc2;for(;null!==(_0x5adfc2=_0x4c9df9['exec'](_0x10d708));){const _0x5d0c38=_0x5adfc2[0x1];if(_0x5d0c38[_0x5dfa23(0x209,'UxQ*')](_0x5dfa23(0x1f8,'u5VZ')))_0x1e1a7a[_0x5dfa23(0x210,'idnR')](_0x5d0c38);else{if(_0x5d0c38[_0x5dfa23(0xee,'RTFh')]('./'))_0x1e1a7a[_0x5dfa23(0x227,'6t$Q')](_0x2829de+'/'+_0x5d0c38[_0x5dfa23(0x151,'%7Du')](0x2));else{if(_0x5d0c38[_0x5dfa23(0x1b6,'xKPP')](_0x4655e4['GBfTH'])){let _0x506569=_0x2829de,_0x186f52=_0x5d0c38;for(;_0x186f52['startsWith'](_0x446ca6(0x19b,'BcTO'));)_0x506569=_0x506569[_0x5dfa23(0x1bf,'aMWz')](/\/[^/]+$/,''),_0x186f52=_0x186f52['slice'](0x3);_0x1e1a7a[_0x5dfa23(0x1aa,'Dp@c')](_0x4655e4['HEABL'](_0x506569,'/')+_0x186f52);}}}}return _0x1e1a7a;}function normaliseRoot(_0x5731ff){return _0x5731ff['replace'](/^\/+/,'')['replace'](/\/+$/,'');}function discoverPackages(_0x5c2064){const _0x2ecccd=_0x57ff92,_0x1426f3=_0x484728,_0x4916e6={'muxZa':'game.json','DYpcx':_0x2ecccd(0x1ff,'#v(C'),'STCsG':function(_0x5abe97,_0xe1ac94){return _0x5abe97==_0xe1ac94;}},_0x55f4fc=path2['join'](_0x5c2064,_0x4916e6[_0x2ecccd(0x1e1,'Qsq6')]);let _0x96ca18={};try{_0x96ca18=JSON['parse'](fs2[_0x1426f3(0x12b,'7t$W')](_0x55f4fc,_0x4916e6[_0x1426f3(0x125,'V(Ka')]));}catch{}const _0x35e9bd=[];_0x35e9bd['push']({'name':'','root':'','entry':'game.js'});const _0x929991=_0x96ca18[_0x2ecccd(0x113,'@pDF')]??_0x96ca18['subpackages']??[];for(const _0xccf110 of _0x929991){const _0x315657=_0x4916e6['STCsG']('string',typeof _0xccf110[_0x2ecccd(0x14f,'QHh6')])?_0xccf110[_0x2ecccd(0x196,'S!bC')]:'',name='string'==typeof _0xccf110['name']?_0xccf110[_0x2ecccd(0x193,']65Y')]:_0x315657,_0x54a135=normaliseRoot(_0x315657);_0x54a135&&_0x35e9bd[_0x1426f3(0x220,'S!bC')]({'name':name,'root':_0x54a135,'entry':_0x2ecccd(0x194,'!Ens')});}return _0x35e9bd;}function isSystemJsCarrier(_0x46b25c){const _0xf32e0d=_0x57ff92,_0x545e38=_0x484728,_0x196498={'rWOBT':function(_0x4f31a3,_0xca9fa6){return _0x4f31a3<_0xca9fa6;},'rJcMu':_0xf32e0d(0x1c4,'RTFh'),'WJytc':function(_0x85057e,_0x59d7d3){return _0x85057e<_0x59d7d3;}},_0x387ff5=_0x46b25c['indexOf']('System.register(');if(_0x196498[_0xf32e0d(0x175,'7&T9')](_0x387ff5,0x0))return!0x1;const _0x258f7c=_0x46b25c[_0xf32e0d(0x212,'QHh6')](_0x196498[_0xf32e0d(0x13a,'lcpC')]);return _0x196498['WJytc'](_0x258f7c,0x0)||_0x196498[_0x545e38(0x135,'4SdE')](_0x387ff5,_0x258f7c);}function isSelfBootstrappingEntry(_0x2b841c,_0x286e37){const _0x31628a=_0x484728,_0x2e85d3=_0x57ff92,_0x540154={'pTBlT':function(_0x2dbde1,_0x24f080){return _0x2dbde1>=_0x24f080;}},_0x56c772=_0x2b841c[_0x31628a(0x1cc,'BcTO')](),_0x30d6b6=_0x56c772[_0x31628a(0x10e,']65Y')](Math[_0x2e85d3(0x20f,'1pOf')](0x0,_0x56c772['length']-0x80))['match'](/require\(\s*(["'])([^"']+)\1\s*\)\s*;?\s*$/);if(!_0x30d6b6)return!0x1;const _0x4e5ff3=_0x30d6b6[0x2],_0x1d5ef6='define(\x22'+_0x4e5ff3+'\x22',_0x4c377e='define(\x27'+_0x4e5ff3+'\x27';return _0x540154['pTBlT'](_0x2b841c['indexOf'](_0x1d5ef6),0x0)||_0x2b841c['indexOf'](_0x4c377e)>=0x0;}var SKIP_DIRS=new Set(['node_modules',_0x57ff92(0xfd,'1Ecb'),'.svn',_0x57ff92(0x13b,'Dp@c'),_0x484728(0x1d2,'!Ens'),'.vscode']);function walkFiles(_0xc1da6c,_0x2aecec,_0x4fcc9f,_0xbf0770){const _0x48e03d=_0x57ff92,_0x4288bb=_0x57ff92;let _0x56b347;try{_0x56b347=fs2['readdirSync'](_0xc1da6c,{'withFileTypes':!0x0});}catch{return;}for(const _0x494d8f of _0x56b347){if(_0x494d8f['name']['startsWith']('.'))continue;if(SKIP_DIRS['has'](_0x494d8f['name']))continue;const _0x421955=_0x2aecec?_0x2aecec+'/'+_0x494d8f['name']:_0x494d8f[_0x48e03d(0x1ad,'UxQ*')];if(_0x4fcc9f['has'](_0x421955))continue;const _0x51caf3=path2[_0x4288bb(0x225,'BcTO')](_0xc1da6c,_0x494d8f['name']);_0x494d8f['isDirectory']()?walkFiles(_0x51caf3,_0x421955,_0x4fcc9f,_0xbf0770):_0x494d8f[_0x48e03d(0x1c5,'kBZE')]()&&_0xbf0770[_0x4288bb(0x141,'1Ecb')](_0x421955);}}function wrapAsDefine(_0xe9e6da,_0xd04ed){const _0xb30fae=_0x57ff92,_0x427fc8=_0x484728;return'define('+JSON[_0xb30fae(0x156,'Dp@c')](_0xe9e6da)+_0x427fc8(0x1c6,'7&T9')+_0xd04ed+_0xb30fae(0x1ce,'4tX)');}function copyFile(_0x2335f5,_0x1016e8){const _0x41e519=_0x484728,_0x2c0dfb=_0x484728;fs2[_0x41e519(0x1d6,'idnR')](path2[_0x41e519(0x180,'^BhC')](_0x1016e8),{'recursive':!0x0}),fs2[_0x41e519(0x1fd,'1Ecb')](_0x2335f5,_0x1016e8);}function transformJs(_0x3dbbaa,_0x514e51,_0x4473e9,_0x221a97,_0x32ae30){const _0x11c2db=_0x57ff92,_0xf5341c=_0x57ff92,_0x24bddc={'gcokj':function(_0x4a5a24,_0x49d614){return _0x4a5a24(_0x49d614);},'bbawk':'warn','wFxJx':function(_0x42c28f,_0x47b794){return _0x42c28f||_0x47b794;},'DsmpS':_0x11c2db(0x1dc,'6t$Q')},_0x42a6c9=getEnhanceTransform();let _0x128129;try{_0x128129=silenceBabelDeopt(()=>_0x42a6c9({'code':_0x3dbbaa,'filePath':_0x514e51,'babelRoot':BABEL_RUNTIME_ROOT}));}catch(_0x3fa55c){const _0x2a6690=_0x3fa55c instanceof Error?_0x3fa55c[_0x11c2db(0x16b,'!Ens')]:_0x24bddc[_0x11c2db(0x1bd,'6t$Q')](String,_0x3fa55c);return _0x4473e9[_0x11c2db(0x184,'^BhC')]({'pkg':_0x221a97,'file':_0x514e51,'level':_0x24bddc[_0x11c2db(0x1f0,'1Ecb')],'message':_0xf5341c(0x12a,'#v(C')+_0x2a6690+_0x11c2db(0x1d1,'7P(v')}),_0x32ae30('warn',_0x11c2db(0x1ab,'Ci&]')+(_0x221a97||_0x11c2db(0x136,'UxQ*'))+_0xf5341c(0x1b9,'eJMp')+_0x514e51+'\x22:\x20'+_0x2a6690+'\x20—\x20using\x20source\x20as-is'),{'code':_0x3dbbaa,'helpers':[]};}if(_0x128129[_0xf5341c(0xe6,'j[5B')])return _0x4473e9[_0xf5341c(0x130,'UxQ*')]({'pkg':_0x221a97,'file':_0x514e51,'level':'error','message':_0x11c2db(0x148,'FfOy')+_0x128129['error']['message']}),_0x32ae30(_0xf5341c(0x1ef,'#*WC'),_0xf5341c(0x16c,'7P(v')+_0x24bddc['wFxJx'](_0x221a97,_0x24bddc['DsmpS'])+_0x11c2db(0x166,'X9AZ')+_0x514e51+_0x11c2db(0xf3,'S!bC')+_0x128129[_0xf5341c(0x110,'1Ecb')][_0x11c2db(0xe7,'Qsq6')]),{'code':_0x3dbbaa,'helpers':[]};const _0x37c44c=_0x128129['code']??_0x3dbbaa,_0xe3e335=_0x128129[_0xf5341c(0x187,'idnR')]??[];for(const _0x4cc4f6 of extractBabelRuntimeRequires(_0x37c44c))_0xe3e335['includes'](_0x4cc4f6)||_0xe3e335['push'](_0x4cc4f6);return{'code':_0x37c44c,'helpers':_0xe3e335};}function materialiseHelpers(_0xb4e325,_0x152c20,_0x4dc0f9){const _0x48b7c1=_0x57ff92,_0x410038=_0x484728,_0x2aaf4d={'IGxaC':function(_0x3e5abd,_0x1e5ad9){return _0x3e5abd!==_0x1e5ad9;},'uHcEP':'bcpMq','mSUHx':function(_0x188c4c,_0x2bf985){return _0x188c4c(_0x2bf985);},'Fvrcu':_0x48b7c1(0x124,'UxQ*')},_0x40233b=new Set(),_0x12be96=[];for(const _0x3e98bd of _0xb4e325){if(_0x2aaf4d['IGxaC'](_0x48b7c1(0xfc,'7&T9'),_0x2aaf4d[_0x48b7c1(0x1df,'1Ecb')]))_0x4fcf2e[_0x48b7c1(0x142,'aMWz')](_0xb17e62(_0x150f47,_0x45adc0,_0x2890a5,_0x3b246a,_0x525acb,_0x483549));else{const _0x4cd8d8=_0x3e98bd['endsWith'](_0x48b7c1(0x13e,'jOm#'))?_0x3e98bd[_0x48b7c1(0xfa,'Ci&]')](/\.js$/,''):_0x3e98bd;_0x40233b['has'](_0x4cd8d8)||(_0x40233b[_0x48b7c1(0x1d4,'lcpC')](_0x4cd8d8),_0x12be96['push'](_0x4cd8d8));}}for(;_0x12be96['length']>0x0;){const _0x55a45e=_0x12be96[_0x410038(0x139,'7P(v')]();let _0x1eb1bb;try{_0x1eb1bb=_0x2aaf4d['mSUHx'](readBabelHelper,_0x55a45e);}catch{_0x152c20['push']({'pkg':_0x4dc0f9,'file':_0x55a45e,'level':'warn','message':_0x48b7c1(0x19c,'V(Ka')+_0x55a45e});continue;}for(const _0x44f575 of extractHelperDependencies(_0x55a45e,_0x1eb1bb)){const _0x3b7a69=_0x44f575[_0x410038(0x1a4,'H[Jq')](_0x2aaf4d[_0x410038(0x231,'eJMp')])?_0x44f575[_0x48b7c1(0x13d,'7P(v')](/\.js$/,''):_0x44f575;_0x40233b['has'](_0x3b7a69)||(_0x40233b['add'](_0x3b7a69),_0x12be96[_0x48b7c1(0x1ed,'4aeH')](_0x3b7a69));}}const _0x2e4e7d=[];for(const _0x8cfd2c of _0x40233b)try{const _0x16f1fb=_0x2aaf4d[_0x410038(0x18f,'aMWz')](readBabelHelper,_0x8cfd2c);_0x2e4e7d[_0x410038(0x130,'UxQ*')]({'modulePathInPkg':_0x8cfd2c+_0x410038(0x236,'7P(v'),'source':_0x16f1fb});}catch{}return _0x2e4e7d;}function packOnePackage(_0x151ec8,_0xb2ca44,_0x3216c5,_0x195147,_0x2ceb67,_0x180d7c){const _0x138114=_0x484728,_0x3728a7=_0x57ff92,_0x189309={'ZyLoA':'main','cOlTd':function(_0x8d1081,_0x4a83e6,_0x59ecf9,_0x5a1b9a,_0x1ea863){return _0x8d1081(_0x4a83e6,_0x59ecf9,_0x5a1b9a,_0x1ea863);},'LfrVv':function(_0xa94791,_0x53989d,_0x5aa194){return _0xa94791(_0x53989d,_0x5aa194);},'LcrGN':function(_0x37f981,_0x373df0){return _0x37f981===_0x373df0;},'flacc':function(_0x550cef,_0x112503){return _0x550cef===_0x112503;},'QiYtH':_0x138114(0x134,'idnR'),'jeDGE':function(_0x3c17aa,_0x5c88b3){return _0x3c17aa(_0x5c88b3);},'PNAcG':function(_0x221a07,_0x580ea3,_0x102a77,_0x5cb5b7){return _0x221a07(_0x580ea3,_0x102a77,_0x5cb5b7);},'PNlcB':function(_0x4c4c99,_0x211699){return _0x4c4c99>_0x211699;},'CTRyJ':function(_0x581318,_0x136c68,_0x3df476){return _0x581318(_0x136c68,_0x3df476);},'tfOUc':_0x138114(0x100,'2Gw^'),'BfBXS':function(_0x58f8ed,_0x57a3e8){return _0x58f8ed+_0x57a3e8;}},_0x347a2b=_0x3216c5[_0x3728a7(0x22f,'84Wz')]?path2[_0x3728a7(0xf2,'0c9r')](_0x151ec8,_0x3216c5['root']):_0x151ec8,_0xa4a901=_0x3216c5['root']?path2['join'](_0xb2ca44,_0x3216c5[_0x138114(0x1a3,'1Ecb')]):_0xb2ca44;if(!fs2['existsSync'](_0x347a2b))return _0x180d7c('warn',_0x3728a7(0x158,'7&T9')+(_0x3216c5['name']||_0x189309[_0x3728a7(0xff,'DJH3')])+'\x22\x20root\x20does\x20not\x20exist:\x20'+_0x347a2b),{'name':_0x3216c5[_0x138114(0x1f3,'eJMp')],'root':_0x3216c5[_0x138114(0x177,'4tX)')],'entry':_0x3216c5[_0x138114(0x1c7,'kBZE')],'modules':0x0,'assets':0x0,'helpers':0x0,'scripts':0x0};fs2['mkdirSync'](_0xa4a901,{'recursive':!0x0});const _0x1ceffe=[];_0x189309['cOlTd'](walkFiles,_0x347a2b,'',_0x195147,_0x1ceffe);const _0x96c3f2=[];let _0x48eafe=0x0;for(const _0x257c8d of _0x1ceffe)/\.(?:js|mjs|cjs)$/[_0x138114(0x203,'Ci&]')](_0x257c8d)?_0x96c3f2[_0x138114(0x105,'WV6r')](_0x257c8d):(_0x189309[_0x3728a7(0x10a,'7t$W')](copyFile,path2[_0x138114(0x1be,'39$#')](_0x347a2b,_0x257c8d),path2['join'](_0xa4a901,_0x257c8d)),_0x48eafe++);const _0x4dbb55=path2[_0x3728a7(0xf2,'0c9r')](_0x347a2b,_0x3216c5[_0x3728a7(0x1a6,'BcTO')]);let _0x20df2d=!0x1;if(fs2[_0x3728a7(0x11a,'jOm#')](_0x4dbb55)){const _0x51b974=fs2[_0x3728a7(0x205,'DJH3')](_0x4dbb55,'utf-8');if(isSelfBootstrappingEntry(_0x51b974,_0x3216c5['entry'])){_0x20df2d=!0x0;const _0x1fc97d=path2[_0x138114(0xeb,'#*WC')](_0xa4a901,_0x3216c5[_0x3728a7(0x10c,'39$#')]);fs2[_0x138114(0x1b0,'lcpC')](path2['dirname'](_0x1fc97d),{'recursive':!0x0}),fs2[_0x3728a7(0x117,'RTFh')](_0x1fc97d,_0x51b974,'utf-8'),_0x180d7c(_0x3728a7(0x102,'7&T9'),_0x3728a7(0x16f,'#*WC')+(_0x3216c5[_0x138114(0x162,'j[5B')]||'main')+_0x138114(0x1d3,'X&aX')+_0x3216c5['entry']+'\x22\x20is\x20a\x20self-bootstrapping\x20CI\x20bundle\x20—\x20copied\x20verbatim,\x20no\x20re-wrapping.');}}const _0x4e5b34=new Set(),_0x406b97=[];let _0x4418a8=0x0,_0x334955=0x0;for(const _0x4fcfa2 of _0x96c3f2){const _0x4ab79d=path2[_0x3728a7(0x170,'ehxD')](_0x347a2b,_0x4fcfa2),_0x4ce04c=fs2['readFileSync'](_0x4ab79d,_0x138114(0x208,'j[5B')),_0x2cc4c4=_0x189309['LcrGN'](_0x4fcfa2,_0x3216c5['entry']);if(_0x2cc4c4&&_0x20df2d)continue;if(!_0x2cc4c4&&isSystemJsCarrier(_0x4ce04c)){copyFile(_0x4ab79d,path2[_0x3728a7(0x225,'BcTO')](_0xa4a901,_0x4fcfa2)),_0x4418a8++;for(const _0x5eae68 of extractBabelRuntimeRequires(_0x4ce04c))_0x4e5b34['add'](_0x5eae68);continue;}const _0x202a9c=_0x4fcfa2['split']('/')[0x0];if(_0x189309[_0x138114(0x12f,'z]G[')](_0x189309[_0x3728a7(0x21d,'0eOn')],_0x202a9c)||_0x189309[_0x3728a7(0x226,'Qsq6')](_0x3728a7(0x229,'idnR'),_0x202a9c)){_0x406b97[_0x138114(0x1ed,'4aeH')](_0x189309[_0x138114(0x1e9,'WV6r')](wrapAsDefine,_0x4fcfa2,_0x4ce04c)),_0x334955++;for(const _0x12bdf8 of _0x189309[_0x3728a7(0x1f4,'u5VZ')](extractBabelRuntimeRequires,_0x4ce04c))_0x4e5b34[_0x3728a7(0x1b2,'FfOy')](_0x12bdf8);continue;}const {code:_0x5aa40c,helpers:_0x2cc4fe}=transformJs(_0x4ce04c,_0x4fcfa2,_0x2ceb67,_0x3216c5['name'],_0x180d7c);for(const _0x11c97c of _0x2cc4fe)_0x4e5b34['add'](_0x11c97c);_0x406b97[_0x3728a7(0x12d,'@pDF')](_0x189309['LfrVv'](wrapAsDefine,_0x4fcfa2,_0x5aa40c)),_0x334955++;}const _0xdee3f0=_0x189309['PNAcG'](materialiseHelpers,_0x4e5b34,_0x2ceb67,_0x3216c5[_0x3728a7(0x1a5,'xKPP')]);for(const _0x35b862 of _0xdee3f0)_0x406b97['push'](wrapAsDefine(_0x35b862[_0x3728a7(0x1a7,'jOm#')],_0x35b862['source']));if(_0x20df2d)(_0x406b97[_0x138114(0x20a,'Dp@c')]>0x0||_0x189309[_0x3728a7(0x15f,'4aeH')](_0xdee3f0['length'],0x0))&&_0x189309[_0x138114(0x222,'lcpC')](_0x180d7c,_0x189309[_0x3728a7(0x144,'7&T9')],'[packager]\x20('+(_0x3216c5['name']||_0x3728a7(0x216,'84Wz'))+_0x3728a7(0x1a8,'S!bC')+_0x334955+_0x138114(0x1d0,'Ci&]')+_0xdee3f0[_0x138114(0x1c8,'X9AZ')]+'\x20helper(s)\x20that\x20will\x20be\x20ignored.\x20Remove\x20them\x20from\x20the\x20package\x20or\x20remove\x20the\x20trailing\x20require(\x22'+_0x3216c5[_0x138114(0x143,'@pDF')]+_0x138114(0x171,'V(Ka'));else{const _0x29c3a2='//\x20Packaged\x20by\x20ai-minigame-engine\x20('+(_0x3216c5[_0x138114(0x1b1,'#*WC')]||_0x189309[_0x138114(0xf8,'ehxD')])+'\x20package)\x20—\x20'+_0x334955+_0x138114(0x22c,'#v(C')+_0x4418a8+'\x20standalone\x20script(s),\x20'+_0xdee3f0['length']+'\x20helper(s)\x0a',_0x132a50=_0x138114(0x230,'z]G[')+JSON[_0x3728a7(0x20e,'4aeH')](_0x3216c5['entry'])+_0x3728a7(0x1fc,'UxQ*'),_0x353dfb=_0x29c3a2+_0x406b97['join']('')+_0x132a50,_0x38e38b=path2[_0x3728a7(0x1ba,'p1s3')](_0xa4a901,_0x3216c5['entry']);fs2[_0x3728a7(0x13f,'X9AZ')](path2[_0x138114(0x173,'X&aX')](_0x38e38b),{'recursive':!0x0}),fs2['writeFileSync'](_0x38e38b,_0x353dfb,'utf-8');}return _0x189309[_0x138114(0xf1,'xKPP')](_0x180d7c,_0x3728a7(0xe8,'BcTO'),_0x189309[_0x3728a7(0x182,'1Ecb')]('[packager]\x20('+(_0x3216c5[_0x3728a7(0x16a,'2Gw^')]||_0x3728a7(0x129,'4SdE'))+')\x20',_0x20df2d?_0x138114(0x19f,'X9AZ')+_0x48eafe+_0x138114(0x190,'u5VZ'):_0x334955+'\x20bundled,\x20'+_0x4418a8+_0x138114(0x1e6,'1pOf')+_0xdee3f0['length']+'\x20helpers,\x20'+_0x48eafe+_0x138114(0x201,'7P(v'))),{'name':_0x3216c5[_0x3728a7(0x12e,'BcTO')],'root':_0x3216c5[_0x3728a7(0x108,'kBZE')],'entry':_0x3216c5[_0x3728a7(0x152,'z]G[')],'modules':_0x334955,'assets':_0x48eafe,'helpers':_0xdee3f0['length'],'scripts':_0x4418a8};}function packageGameToDir(_0x36ea68,_0x56c996,_0x512d2e){const _0x5687e8=_0x57ff92,_0x18df8a=_0x484728,_0x1914ce={'jXbRf':_0x5687e8(0x10d,'ehxD'),'boQSH':_0x18df8a(0x1c1,'z]G['),'fOntt':_0x5687e8(0x1b7,'1pOf'),'UGWCH':_0x18df8a(0x206,'lcpC'),'JTVtb':_0x5687e8(0x167,'Dp@c'),'MQwnt':function(_0x2e6229,_0x58f776,_0x2ada59){return _0x2e6229(_0x58f776,_0x2ada59);},'WIzsl':_0x18df8a(0x15d,'u5VZ'),'esFkn':'<package>','FhjMQ':function(_0x1393da,_0x5331f0){return _0x1393da-_0x5331f0;}},_0x548799=Date[_0x18df8a(0xed,'6t$Q')](),_0xeff7fd=_0x512d2e??((_0x25d412,_0xa137a1)=>{const _0x1d4d38=_0x18df8a,_0x4b37ec=_0x18df8a;_0x1914ce[_0x1d4d38(0x104,'kBZE')]===_0x25d412?console[_0x4b37ec(0x19d,'S!bC')](_0xa137a1):_0x1914ce[_0x1d4d38(0x123,'S!bC')]===_0x25d412?console['warn'](_0xa137a1):console['log'](_0xa137a1);});if(_0xeff7fd(_0x1914ce[_0x18df8a(0x1ee,'ehxD')],'[packager]\x20Packaging\x20'+_0x36ea68+_0x18df8a(0x1b4,'j[5B')+_0x56c996),!fs2['existsSync'](path2[_0x5687e8(0x1be,'39$#')](_0x36ea68,_0x5687e8(0xf9,'Dp@c'))))throw new Error(_0x18df8a(0x215,'WV6r')+path2['join'](_0x36ea68,'game.js'));fs2[_0x5687e8(0x1e5,'7&T9')](_0x56c996,{'recursive':!0x0,'force':!0x0}),fs2['mkdirSync'](_0x56c996,{'recursive':!0x0});for(const name of[_0x1914ce[_0x5687e8(0x1de,'4SdE')],_0x18df8a(0x101,'u5VZ'),_0x1914ce[_0x5687e8(0x202,'X9AZ')],'app-config.json']){const _0x40f630=path2[_0x18df8a(0x223,'Qsq6')](_0x36ea68,name);fs2['existsSync'](_0x40f630)&&copyFile(_0x40f630,path2['join'](_0x56c996,name));}const _0x4e4ab7=discoverPackages(_0x36ea68),_0x252ee4=new Set(_0x4e4ab7[_0x5687e8(0x107,'ehxD')](_0x50da3d=>''!==_0x50da3d[_0x18df8a(0x18d,'2Gw^')])['map'](_0x238e4d=>_0x238e4d['root'])),_0x562d91=[],_0x22e289=[];for(const _0x567d33 of _0x4e4ab7){const _0x192eae=''===_0x567d33['root']?_0x252ee4:new Set();try{_0x22e289[_0x18df8a(0x21f,'lcpC')](packOnePackage(_0x36ea68,_0x56c996,_0x567d33,_0x192eae,_0x562d91,_0xeff7fd));}catch(_0x47decb){const _0x160d0e=_0x47decb instanceof Error?_0x47decb[_0x5687e8(0x1fe,'7t$W')]:String(_0x47decb);throw _0x1914ce['MQwnt'](_0xeff7fd,_0x18df8a(0xec,'eJMp'),'[packager]\x20Package\x20\x22'+(_0x567d33['name']||_0x1914ce[_0x18df8a(0x21b,'V(Ka')])+'\x22\x20failed:\x20'+_0x160d0e),_0x562d91[_0x18df8a(0x227,'6t$Q')]({'pkg':_0x567d33[_0x5687e8(0x22d,'X&aX')],'file':_0x1914ce['esFkn'],'level':_0x18df8a(0x1f5,'84Wz'),'message':_0x160d0e}),_0x47decb;}}const _0x5e77ee=_0x1914ce[_0x5687e8(0x197,'BcTO')](Date[_0x5687e8(0x14b,'%7Du')](),_0x548799),_0x51f53c=_0x22e289[_0x5687e8(0x218,'RTFh')]((_0x401a81,_0x548dc1)=>_0x401a81+_0x548dc1['modules'],0x0),_0x120021=_0x22e289['reduce']((_0x1e9780,_0x1261ef)=>_0x1e9780+_0x1261ef[_0x18df8a(0x150,'S!bC')],0x0),_0x12c830=_0x22e289[_0x5687e8(0x18c,'%7Du')]((_0x1fc2cd,_0x174285)=>_0x1fc2cd+_0x174285['helpers'],0x0),_0x1f11c4=_0x22e289[_0x5687e8(0x1d8,'FfOy')]((_0x44b9f2,_0x125c0c)=>_0x44b9f2+_0x125c0c['scripts'],0x0);return _0xeff7fd('log',_0x5687e8(0x128,'u5VZ')+_0x5e77ee+_0x18df8a(0x21e,'RTFh')+_0x22e289[_0x5687e8(0x219,'X&aX')]+_0x5687e8(0x11e,'X9AZ')+_0x51f53c+_0x5687e8(0x14c,'aMWz')+_0x1f11c4+_0x5687e8(0x207,'Dp@c')+_0x120021+_0x5687e8(0x1a9,'aMWz')+_0x12c830+_0x18df8a(0x15c,'xKPP')),{'packages':_0x22e289,'diagnostics':_0x562d91,'elapsed':_0x5e77ee};}if(import_worker_threads[_0x484728(0xf7,'idnR')]){const e=import_worker_threads[_0x484728(0xf7,'idnR')];e['on']('message',_0xa06c68=>{const _0x13377f=_0x57ff92,_0x1bd530=_0x484728,_0x3e76d0={'qiJHS':function(_0x431809,_0x5d9224){return _0x431809(_0x5d9224);},'FwcKc':_0x13377f(0x164,'Ci&]'),'hKcSb':_0x13377f(0x17a,'7&T9'),'LtmLl':function(_0x17ed3d,_0x41baf8){return _0x17ed3d!==_0x41baf8;},'eWVQn':function(_0x2d370a,_0x1854f8){return _0x2d370a||_0x1854f8;},'Xkkku':function(_0x456a06){return _0x456a06();},'gWcfB':function(_0x25bddd,_0x4414a7){return _0x25bddd(_0x4414a7);},'DHMbu':function(_0x30b3a5,_0x3ed8fa,_0x3ad3e5,_0x3919de){return _0x30b3a5(_0x3ed8fa,_0x3ad3e5,_0x3919de);},'sRkin':_0x13377f(0x1ec,'BcTO'),'TyiGs':function(_0x5a2653,_0x5130ed){return _0x5a2653 instanceof _0x5130ed;},'BwEFA':function(_0x5af918,_0x14946f){return _0x5af918 instanceof _0x14946f;}};if(!_0xa06c68||_0x3e76d0['LtmLl']('run',_0xa06c68['kind']))return;const {id:_0x52b41a,gameDir:_0x30e780,outputDir:_0x229ccb,ciDepsDir:_0x357c94,ciExtensionDir:_0x537340}=_0xa06c68;if(_0x3e76d0['eWVQn'](_0x537340,_0x357c94)){if(_0x13377f(0x115,'2Gw^')===_0x13377f(0x168,'p1s3')){const _0x3685aa=_0x4a81fb instanceof _0x513e6c?_0x3832f4[_0x1bd530(0x21c,'FfOy')]:_0x3e76d0[_0x13377f(0x178,'V(Ka')](_0x3e7df0,_0x269ae0);return _0x55da43[_0x1bd530(0x15b,'0c9r')]({'pkg':_0x368a06,'file':_0x3bd0ff,'level':_0x3e76d0['FwcKc'],'message':'Babel\x20threw:\x20'+_0x3685aa+'\x20—\x20using\x20source\x20as-is'}),_0x460fc3(_0x3e76d0[_0x13377f(0x189,'2Gw^')],_0x13377f(0x153,'4SdE')+(_0x483c06||_0x3e76d0[_0x1bd530(0x121,'39$#')])+')\x20Babel\x20threw\x20on\x20\x22'+_0x4ac6e6+'\x22:\x20'+_0x3685aa+_0x1bd530(0x174,'39$#')),{'code':_0x31c979,'helpers':[]};}else{const _0x5c362e=(_0x3e76d0['Xkkku'](init_ci_installer),_0x3e76d0['gWcfB'](__toCommonJS,ci_installer_exports));_0x537340&&_0x5c362e['setCiExtensionDir'](_0x537340),_0x357c94&&_0x5c362e['setCiDepsDir'](_0x357c94);}}const _0x2306b8=(_0x20064f,_0x43b8fd)=>{const _0x3eaf19=_0x13377f,_0x1bf676=_0x1bd530;e[_0x3eaf19(0x11c,'z#x!')]({'kind':_0x1bf676(0x1af,'0eOn'),'id':_0x52b41a,'level':_0x20064f,'message':_0x43b8fd});};try{const _0x573516=_0x3e76d0['DHMbu'](packageGameToDir,_0x30e780,_0x229ccb,_0x2306b8);e['postMessage']({'kind':_0x3e76d0['sRkin'],'id':_0x52b41a,'result':_0x573516});}catch(_0x2863b7){const _0x52be68=_0x3e76d0['TyiGs'](_0x2863b7,Error)?_0x2863b7[_0x13377f(0x1c0,'lcpC')]:_0x3e76d0[_0x13377f(0x18b,'UxQ*')](String,_0x2863b7),_0x50fd89=_0x3e76d0[_0x13377f(0x146,'#v(C')](_0x2863b7,Error)?_0x2863b7['stack']:void 0x0;e[_0x1bd530(0x191,'kBZE')]({'kind':_0x1bd530(0x232,'4tX)'),'id':_0x52b41a,'message':_0x52be68,'stack':_0x50fd89});}});}else console['warn']('[game-bundler-worker]\x20Loaded\x20outside\x20a\x20worker_threads\x20context\x20—\x20doing\x20nothing.');
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __commonJS = (cb, mod) => function __require() {
12
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
+ };
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
+ // If the importer is in node compatibility mode or this is not an ESM
28
+ // file that has been converted to a CommonJS file using a Babel-
29
+ // compatible transform (i.e. "__esModule" has not been set), then set
30
+ // "default" to the CommonJS "module.exports" for node compatibility.
31
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
+ mod
33
+ ));
34
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
35
+
36
+ // core/real-device/ci-installer.ts
37
+ var ci_installer_exports = {};
38
+ __export(ci_installer_exports, {
39
+ ensureCiInstalled: () => ensureCiInstalled,
40
+ getCiDepsDir: () => getCiDepsDir,
41
+ getCiExtensionDir: () => getCiExtensionDir,
42
+ getCiInstallStatus: () => getCiInstallStatus,
43
+ getCiRequirePath: () => getCiRequirePath,
44
+ isCiInstalled: () => isCiInstalled,
45
+ onCiInstallStatusChange: () => onCiInstallStatusChange,
46
+ retryCiInstall: () => retryCiInstall,
47
+ setCiDepsDir: () => setCiDepsDir,
48
+ setCiExtensionDir: () => setCiExtensionDir
49
+ });
50
+ function setStatus(next) {
51
+ _statusInfo = next;
52
+ for (const l of _statusListeners) {
53
+ try {
54
+ l(next);
55
+ } catch {
56
+ }
57
+ }
58
+ }
59
+ function onCiInstallStatusChange(listener) {
60
+ _statusListeners.add(listener);
61
+ try {
62
+ listener(_statusInfo);
63
+ } catch {
64
+ }
65
+ return () => _statusListeners.delete(listener);
66
+ }
67
+ function getCiInstallStatus() {
68
+ return _statusInfo;
69
+ }
70
+ function setCiDepsDir(dir) {
71
+ _installDir = dir;
72
+ if (isCiInstalled()) {
73
+ if (_statusInfo.status !== "installed") {
74
+ setStatus({ status: "installed", message: "miniprogram-ci \u5DF2\u5B89\u88C5" });
75
+ }
76
+ }
77
+ }
78
+ function setCiExtensionDir(dir) {
79
+ _extensionDir = dir;
80
+ }
81
+ async function ensureCiInstalled(onProgress) {
82
+ const bundled = getBundledCiPath();
83
+ if (bundled) return bundled;
84
+ const dir = getDepsDir();
85
+ const ciPath = path.join(dir, "node_modules", CI_PACKAGE);
86
+ if (fs.existsSync(path.join(ciPath, "package.json"))) {
87
+ if (_statusInfo.status !== "installed") {
88
+ setStatus({ status: "installed", message: "miniprogram-ci \u5DF2\u5B89\u88C5" });
89
+ }
90
+ return ciPath;
91
+ }
92
+ if (_installing) return _installing;
93
+ _installing = doInstall(dir, onProgress);
94
+ try {
95
+ return await _installing;
96
+ } finally {
97
+ _installing = null;
98
+ }
99
+ }
100
+ async function retryCiInstall(onProgress) {
101
+ if (_installing) return _installing;
102
+ if (_statusInfo.status === "failed") {
103
+ setStatus({ status: "not-installed" });
104
+ }
105
+ return ensureCiInstalled(onProgress);
106
+ }
107
+ function isCiInstalled() {
108
+ try {
109
+ if (getBundledCiPath()) return true;
110
+ const dir = getDepsDir();
111
+ return fs.existsSync(
112
+ path.join(dir, "node_modules", CI_PACKAGE, "package.json")
113
+ );
114
+ } catch {
115
+ return false;
116
+ }
117
+ }
118
+ function getCiDepsDir() {
119
+ return _installDir;
120
+ }
121
+ function getCiExtensionDir() {
122
+ return _extensionDir;
123
+ }
124
+ function getCiRequirePath() {
125
+ const bundled = getBundledCiPath();
126
+ if (bundled) return bundled;
127
+ const dir = getDepsDir();
128
+ const ciPath = path.join(dir, "node_modules", CI_PACKAGE);
129
+ if (!fs.existsSync(path.join(ciPath, "package.json"))) {
130
+ throw new Error(
131
+ `[ci-installer] miniprogram-ci is not installed yet. Call ensureCiInstalled() first.`
132
+ );
133
+ }
134
+ return ciPath;
135
+ }
136
+ function getBundledCiPath() {
137
+ if (!_extensionDir) return null;
138
+ const bundledPath = path.join(_extensionDir, "node_modules", CI_PACKAGE);
139
+ if (fs.existsSync(path.join(bundledPath, "package.json"))) {
140
+ return bundledPath;
141
+ }
142
+ return null;
143
+ }
144
+ function getDepsDir() {
145
+ if (!_installDir) {
146
+ _installDir = path.join(os.homedir(), ".weixin-minigame-helper", "deps");
147
+ }
148
+ return _installDir;
149
+ }
150
+ async function doInstall(dir, onProgress) {
151
+ const initialMsg = "\u6B63\u5728\u5B89\u88C5 miniprogram-ci\uFF08\u9996\u6B21\u4F7F\u7528\uFF0C\u7EA6\u9700 30 \u79D2\uFF09\u2026";
152
+ setStatus({ status: "installing", message: initialMsg });
153
+ onProgress?.(initialMsg);
154
+ const reportProgress = (msg) => {
155
+ setStatus({ status: "installing", message: msg });
156
+ onProgress?.(msg);
157
+ };
158
+ fs.mkdirSync(dir, { recursive: true });
159
+ const pkgPath = path.join(dir, "package.json");
160
+ if (!fs.existsSync(pkgPath)) {
161
+ fs.writeFileSync(
162
+ pkgPath,
163
+ JSON.stringify(
164
+ { name: "weixin-minigame-helper-deps", private: true, dependencies: {} },
165
+ null,
166
+ 2
167
+ )
168
+ );
169
+ }
170
+ const cmd = `npm install ${CI_PACKAGE}@"${CI_VERSION}" --save --prefer-offline`;
171
+ reportProgress(`\u6267\u884C: npm install ${CI_PACKAGE}@"${CI_VERSION}" ...`);
172
+ try {
173
+ (0, import_child_process.execSync)(cmd, {
174
+ cwd: dir,
175
+ stdio: "pipe",
176
+ timeout: 18e4,
177
+ // 3 min timeout
178
+ env: { ...process.env, NODE_ENV: "" }
179
+ // ensure devDependencies aren't skipped
180
+ });
181
+ } catch (err) {
182
+ const message = err instanceof Error ? err.message : String(err);
183
+ const errorText = `[ci-installer] Failed to install ${CI_PACKAGE}. Please check your network connection and npm configuration.
184
+ ${message}`;
185
+ setStatus({ status: "failed", message: "miniprogram-ci \u5B89\u88C5\u5931\u8D25", error: errorText });
186
+ throw new Error(errorText);
187
+ }
188
+ const ciPath = path.join(dir, "node_modules", CI_PACKAGE);
189
+ if (!fs.existsSync(path.join(ciPath, "package.json"))) {
190
+ const errorText = `[ci-installer] npm install succeeded but ${CI_PACKAGE} was not found at ${ciPath}.`;
191
+ setStatus({ status: "failed", message: "miniprogram-ci \u5B89\u88C5\u5931\u8D25", error: errorText });
192
+ throw new Error(errorText);
193
+ }
194
+ const doneMsg = "miniprogram-ci \u5B89\u88C5\u5B8C\u6210 \u2713";
195
+ setStatus({ status: "installed", message: doneMsg });
196
+ onProgress?.(doneMsg);
197
+ return ciPath;
198
+ }
199
+ var path, fs, os, import_child_process, CI_PACKAGE, CI_VERSION, _installDir, _extensionDir, _installing, _statusInfo, _statusListeners;
200
+ var init_ci_installer = __esm({
201
+ "core/real-device/ci-installer.ts"() {
202
+ "use strict";
203
+ path = __toESM(require("path"));
204
+ fs = __toESM(require("fs"));
205
+ os = __toESM(require("os"));
206
+ import_child_process = require("child_process");
207
+ CI_PACKAGE = "miniprogram-ci";
208
+ CI_VERSION = "^2.1.31";
209
+ _installDir = null;
210
+ _extensionDir = null;
211
+ _installing = null;
212
+ _statusInfo = { status: "not-installed" };
213
+ _statusListeners = /* @__PURE__ */ new Set();
214
+ }
215
+ });
216
+
217
+ // node_modules/esbuild/lib/main.js
218
+ var require_main = __commonJS({
219
+ "node_modules/esbuild/lib/main.js"(exports2, module2) {
220
+ "use strict";
221
+ var __defProp2 = Object.defineProperty;
222
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
223
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
224
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
225
+ var __export2 = (target, all) => {
226
+ for (var name in all)
227
+ __defProp2(target, name, { get: all[name], enumerable: true });
228
+ };
229
+ var __copyProps2 = (to, from, except, desc) => {
230
+ if (from && typeof from === "object" || typeof from === "function") {
231
+ for (let key of __getOwnPropNames2(from))
232
+ if (!__hasOwnProp2.call(to, key) && key !== except)
233
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
234
+ }
235
+ return to;
236
+ };
237
+ var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
238
+ var node_exports = {};
239
+ __export2(node_exports, {
240
+ analyzeMetafile: () => analyzeMetafile,
241
+ analyzeMetafileSync: () => analyzeMetafileSync,
242
+ build: () => build,
243
+ buildSync: () => buildSync,
244
+ context: () => context,
245
+ default: () => node_default,
246
+ formatMessages: () => formatMessages,
247
+ formatMessagesSync: () => formatMessagesSync,
248
+ initialize: () => initialize,
249
+ stop: () => stop,
250
+ transform: () => transform,
251
+ transformSync: () => transformSync,
252
+ version: () => version
253
+ });
254
+ module2.exports = __toCommonJS2(node_exports);
255
+ function encodePacket(packet) {
256
+ let visit = (value) => {
257
+ if (value === null) {
258
+ bb.write8(0);
259
+ } else if (typeof value === "boolean") {
260
+ bb.write8(1);
261
+ bb.write8(+value);
262
+ } else if (typeof value === "number") {
263
+ bb.write8(2);
264
+ bb.write32(value | 0);
265
+ } else if (typeof value === "string") {
266
+ bb.write8(3);
267
+ bb.write(encodeUTF8(value));
268
+ } else if (value instanceof Uint8Array) {
269
+ bb.write8(4);
270
+ bb.write(value);
271
+ } else if (value instanceof Array) {
272
+ bb.write8(5);
273
+ bb.write32(value.length);
274
+ for (let item of value) {
275
+ visit(item);
276
+ }
277
+ } else {
278
+ let keys = Object.keys(value);
279
+ bb.write8(6);
280
+ bb.write32(keys.length);
281
+ for (let key of keys) {
282
+ bb.write(encodeUTF8(key));
283
+ visit(value[key]);
284
+ }
285
+ }
286
+ };
287
+ let bb = new ByteBuffer();
288
+ bb.write32(0);
289
+ bb.write32(packet.id << 1 | +!packet.isRequest);
290
+ visit(packet.value);
291
+ writeUInt32LE(bb.buf, bb.len - 4, 0);
292
+ return bb.buf.subarray(0, bb.len);
293
+ }
294
+ function decodePacket(bytes) {
295
+ let visit = () => {
296
+ switch (bb.read8()) {
297
+ case 0:
298
+ return null;
299
+ case 1:
300
+ return !!bb.read8();
301
+ case 2:
302
+ return bb.read32();
303
+ case 3:
304
+ return decodeUTF8(bb.read());
305
+ case 4:
306
+ return bb.read();
307
+ case 5: {
308
+ let count = bb.read32();
309
+ let value2 = [];
310
+ for (let i = 0; i < count; i++) {
311
+ value2.push(visit());
312
+ }
313
+ return value2;
314
+ }
315
+ case 6: {
316
+ let count = bb.read32();
317
+ let value2 = {};
318
+ for (let i = 0; i < count; i++) {
319
+ value2[decodeUTF8(bb.read())] = visit();
320
+ }
321
+ return value2;
322
+ }
323
+ default:
324
+ throw new Error("Invalid packet");
325
+ }
326
+ };
327
+ let bb = new ByteBuffer(bytes);
328
+ let id = bb.read32();
329
+ let isRequest = (id & 1) === 0;
330
+ id >>>= 1;
331
+ let value = visit();
332
+ if (bb.ptr !== bytes.length) {
333
+ throw new Error("Invalid packet");
334
+ }
335
+ return { id, isRequest, value };
336
+ }
337
+ var ByteBuffer = class {
338
+ constructor(buf = new Uint8Array(1024)) {
339
+ this.buf = buf;
340
+ this.len = 0;
341
+ this.ptr = 0;
342
+ }
343
+ _write(delta) {
344
+ if (this.len + delta > this.buf.length) {
345
+ let clone = new Uint8Array((this.len + delta) * 2);
346
+ clone.set(this.buf);
347
+ this.buf = clone;
348
+ }
349
+ this.len += delta;
350
+ return this.len - delta;
351
+ }
352
+ write8(value) {
353
+ let offset = this._write(1);
354
+ this.buf[offset] = value;
355
+ }
356
+ write32(value) {
357
+ let offset = this._write(4);
358
+ writeUInt32LE(this.buf, value, offset);
359
+ }
360
+ write(bytes) {
361
+ let offset = this._write(4 + bytes.length);
362
+ writeUInt32LE(this.buf, bytes.length, offset);
363
+ this.buf.set(bytes, offset + 4);
364
+ }
365
+ _read(delta) {
366
+ if (this.ptr + delta > this.buf.length) {
367
+ throw new Error("Invalid packet");
368
+ }
369
+ this.ptr += delta;
370
+ return this.ptr - delta;
371
+ }
372
+ read8() {
373
+ return this.buf[this._read(1)];
374
+ }
375
+ read32() {
376
+ return readUInt32LE(this.buf, this._read(4));
377
+ }
378
+ read() {
379
+ let length = this.read32();
380
+ let bytes = new Uint8Array(length);
381
+ let ptr = this._read(bytes.length);
382
+ bytes.set(this.buf.subarray(ptr, ptr + length));
383
+ return bytes;
384
+ }
385
+ };
386
+ var encodeUTF8;
387
+ var decodeUTF8;
388
+ var encodeInvariant;
389
+ if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
390
+ let encoder = new TextEncoder();
391
+ let decoder = new TextDecoder();
392
+ encodeUTF8 = (text) => encoder.encode(text);
393
+ decodeUTF8 = (bytes) => decoder.decode(bytes);
394
+ encodeInvariant = 'new TextEncoder().encode("")';
395
+ } else if (typeof Buffer !== "undefined") {
396
+ encodeUTF8 = (text) => Buffer.from(text);
397
+ decodeUTF8 = (bytes) => {
398
+ let { buffer, byteOffset, byteLength } = bytes;
399
+ return Buffer.from(buffer, byteOffset, byteLength).toString();
400
+ };
401
+ encodeInvariant = 'Buffer.from("")';
402
+ } else {
403
+ throw new Error("No UTF-8 codec found");
404
+ }
405
+ if (!(encodeUTF8("") instanceof Uint8Array))
406
+ throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
407
+
408
+ This indicates that your JavaScript environment is broken. You cannot use
409
+ esbuild in this environment because esbuild relies on this invariant. This
410
+ is not a problem with esbuild. You need to fix your environment instead.
411
+ `);
412
+ function readUInt32LE(buffer, offset) {
413
+ return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24;
414
+ }
415
+ function writeUInt32LE(buffer, value, offset) {
416
+ buffer[offset++] = value;
417
+ buffer[offset++] = value >> 8;
418
+ buffer[offset++] = value >> 16;
419
+ buffer[offset++] = value >> 24;
420
+ }
421
+ var quote = JSON.stringify;
422
+ var buildLogLevelDefault = "warning";
423
+ var transformLogLevelDefault = "silent";
424
+ function validateTarget(target) {
425
+ validateStringValue(target, "target");
426
+ if (target.indexOf(",") >= 0) throw new Error(`Invalid target: ${target}`);
427
+ return target;
428
+ }
429
+ var canBeAnything = () => null;
430
+ var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
431
+ var mustBeString = (value) => typeof value === "string" ? null : "a string";
432
+ var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
433
+ var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
434
+ var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
435
+ var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
436
+ var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
437
+ var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
438
+ var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
439
+ var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
440
+ var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
441
+ var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
442
+ var mustBeStringOrArray = (value) => typeof value === "string" || Array.isArray(value) ? null : "a string or an array";
443
+ var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
444
+ var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL";
445
+ function getFlag(object, keys, key, mustBeFn) {
446
+ let value = object[key];
447
+ keys[key + ""] = true;
448
+ if (value === void 0) return void 0;
449
+ let mustBe = mustBeFn(value);
450
+ if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`);
451
+ return value;
452
+ }
453
+ function checkForInvalidFlags(object, keys, where) {
454
+ for (let key in object) {
455
+ if (!(key in keys)) {
456
+ throw new Error(`Invalid option ${where}: ${quote(key)}`);
457
+ }
458
+ }
459
+ }
460
+ function validateInitializeOptions(options) {
461
+ let keys = /* @__PURE__ */ Object.create(null);
462
+ let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL);
463
+ let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
464
+ let worker = getFlag(options, keys, "worker", mustBeBoolean);
465
+ checkForInvalidFlags(options, keys, "in initialize() call");
466
+ return {
467
+ wasmURL,
468
+ wasmModule,
469
+ worker
470
+ };
471
+ }
472
+ function validateMangleCache(mangleCache) {
473
+ let validated;
474
+ if (mangleCache !== void 0) {
475
+ validated = /* @__PURE__ */ Object.create(null);
476
+ for (let key in mangleCache) {
477
+ let value = mangleCache[key];
478
+ if (typeof value === "string" || value === false) {
479
+ validated[key] = value;
480
+ } else {
481
+ throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`);
482
+ }
483
+ }
484
+ }
485
+ return validated;
486
+ }
487
+ function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) {
488
+ let color = getFlag(options, keys, "color", mustBeBoolean);
489
+ let logLevel = getFlag(options, keys, "logLevel", mustBeString);
490
+ let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
491
+ if (color !== void 0) flags.push(`--color=${color}`);
492
+ else if (isTTY2) flags.push(`--color=true`);
493
+ flags.push(`--log-level=${logLevel || logLevelDefault}`);
494
+ flags.push(`--log-limit=${logLimit || 0}`);
495
+ }
496
+ function validateStringValue(value, what, key) {
497
+ if (typeof value !== "string") {
498
+ throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`);
499
+ }
500
+ return value;
501
+ }
502
+ function pushCommonFlags(flags, options, keys) {
503
+ let legalComments = getFlag(options, keys, "legalComments", mustBeString);
504
+ let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
505
+ let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
506
+ let target = getFlag(options, keys, "target", mustBeStringOrArray);
507
+ let format = getFlag(options, keys, "format", mustBeString);
508
+ let globalName = getFlag(options, keys, "globalName", mustBeString);
509
+ let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
510
+ let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
511
+ let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
512
+ let minify = getFlag(options, keys, "minify", mustBeBoolean);
513
+ let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
514
+ let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
515
+ let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
516
+ let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger);
517
+ let drop = getFlag(options, keys, "drop", mustBeArray);
518
+ let dropLabels = getFlag(options, keys, "dropLabels", mustBeArray);
519
+ let charset = getFlag(options, keys, "charset", mustBeString);
520
+ let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
521
+ let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
522
+ let jsx = getFlag(options, keys, "jsx", mustBeString);
523
+ let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
524
+ let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
525
+ let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString);
526
+ let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean);
527
+ let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean);
528
+ let define = getFlag(options, keys, "define", mustBeObject);
529
+ let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
530
+ let supported = getFlag(options, keys, "supported", mustBeObject);
531
+ let pure = getFlag(options, keys, "pure", mustBeArray);
532
+ let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
533
+ let platform = getFlag(options, keys, "platform", mustBeString);
534
+ let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
535
+ if (legalComments) flags.push(`--legal-comments=${legalComments}`);
536
+ if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`);
537
+ if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`);
538
+ if (target) {
539
+ if (Array.isArray(target)) flags.push(`--target=${Array.from(target).map(validateTarget).join(",")}`);
540
+ else flags.push(`--target=${validateTarget(target)}`);
541
+ }
542
+ if (format) flags.push(`--format=${format}`);
543
+ if (globalName) flags.push(`--global-name=${globalName}`);
544
+ if (platform) flags.push(`--platform=${platform}`);
545
+ if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
546
+ if (minify) flags.push("--minify");
547
+ if (minifySyntax) flags.push("--minify-syntax");
548
+ if (minifyWhitespace) flags.push("--minify-whitespace");
549
+ if (minifyIdentifiers) flags.push("--minify-identifiers");
550
+ if (lineLimit) flags.push(`--line-limit=${lineLimit}`);
551
+ if (charset) flags.push(`--charset=${charset}`);
552
+ if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`);
553
+ if (ignoreAnnotations) flags.push(`--ignore-annotations`);
554
+ if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`);
555
+ if (dropLabels) flags.push(`--drop-labels=${Array.from(dropLabels).map((what) => validateStringValue(what, "dropLabels")).join(",")}`);
556
+ if (mangleProps) flags.push(`--mangle-props=${mangleProps.source}`);
557
+ if (reserveProps) flags.push(`--reserve-props=${reserveProps.source}`);
558
+ if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`);
559
+ if (jsx) flags.push(`--jsx=${jsx}`);
560
+ if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`);
561
+ if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`);
562
+ if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`);
563
+ if (jsxDev) flags.push(`--jsx-dev`);
564
+ if (jsxSideEffects) flags.push(`--jsx-side-effects`);
565
+ if (define) {
566
+ for (let key in define) {
567
+ if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`);
568
+ flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
569
+ }
570
+ }
571
+ if (logOverride) {
572
+ for (let key in logOverride) {
573
+ if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`);
574
+ flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
575
+ }
576
+ }
577
+ if (supported) {
578
+ for (let key in supported) {
579
+ if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`);
580
+ const value = supported[key];
581
+ if (typeof value !== "boolean") throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`);
582
+ flags.push(`--supported:${key}=${value}`);
583
+ }
584
+ }
585
+ if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`);
586
+ if (keepNames) flags.push(`--keep-names`);
587
+ }
588
+ function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) {
589
+ var _a2;
590
+ let flags = [];
591
+ let entries = [];
592
+ let keys = /* @__PURE__ */ Object.create(null);
593
+ let stdinContents = null;
594
+ let stdinResolveDir = null;
595
+ pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
596
+ pushCommonFlags(flags, options, keys);
597
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
598
+ let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
599
+ let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
600
+ let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
601
+ let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
602
+ let outfile = getFlag(options, keys, "outfile", mustBeString);
603
+ let outdir = getFlag(options, keys, "outdir", mustBeString);
604
+ let outbase = getFlag(options, keys, "outbase", mustBeString);
605
+ let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
606
+ let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArray);
607
+ let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArray);
608
+ let mainFields = getFlag(options, keys, "mainFields", mustBeArray);
609
+ let conditions = getFlag(options, keys, "conditions", mustBeArray);
610
+ let external = getFlag(options, keys, "external", mustBeArray);
611
+ let packages = getFlag(options, keys, "packages", mustBeString);
612
+ let alias = getFlag(options, keys, "alias", mustBeObject);
613
+ let loader = getFlag(options, keys, "loader", mustBeObject);
614
+ let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
615
+ let publicPath = getFlag(options, keys, "publicPath", mustBeString);
616
+ let entryNames = getFlag(options, keys, "entryNames", mustBeString);
617
+ let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
618
+ let assetNames = getFlag(options, keys, "assetNames", mustBeString);
619
+ let inject = getFlag(options, keys, "inject", mustBeArray);
620
+ let banner = getFlag(options, keys, "banner", mustBeObject);
621
+ let footer = getFlag(options, keys, "footer", mustBeObject);
622
+ let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
623
+ let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
624
+ let stdin = getFlag(options, keys, "stdin", mustBeObject);
625
+ let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault;
626
+ let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
627
+ let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
628
+ keys.plugins = true;
629
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
630
+ if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
631
+ if (bundle) flags.push("--bundle");
632
+ if (allowOverwrite) flags.push("--allow-overwrite");
633
+ if (splitting) flags.push("--splitting");
634
+ if (preserveSymlinks) flags.push("--preserve-symlinks");
635
+ if (metafile) flags.push(`--metafile`);
636
+ if (outfile) flags.push(`--outfile=${outfile}`);
637
+ if (outdir) flags.push(`--outdir=${outdir}`);
638
+ if (outbase) flags.push(`--outbase=${outbase}`);
639
+ if (tsconfig) flags.push(`--tsconfig=${tsconfig}`);
640
+ if (packages) flags.push(`--packages=${packages}`);
641
+ if (resolveExtensions) {
642
+ let values = [];
643
+ for (let value of resolveExtensions) {
644
+ validateStringValue(value, "resolve extension");
645
+ if (value.indexOf(",") >= 0) throw new Error(`Invalid resolve extension: ${value}`);
646
+ values.push(value);
647
+ }
648
+ flags.push(`--resolve-extensions=${values.join(",")}`);
649
+ }
650
+ if (publicPath) flags.push(`--public-path=${publicPath}`);
651
+ if (entryNames) flags.push(`--entry-names=${entryNames}`);
652
+ if (chunkNames) flags.push(`--chunk-names=${chunkNames}`);
653
+ if (assetNames) flags.push(`--asset-names=${assetNames}`);
654
+ if (mainFields) {
655
+ let values = [];
656
+ for (let value of mainFields) {
657
+ validateStringValue(value, "main field");
658
+ if (value.indexOf(",") >= 0) throw new Error(`Invalid main field: ${value}`);
659
+ values.push(value);
660
+ }
661
+ flags.push(`--main-fields=${values.join(",")}`);
662
+ }
663
+ if (conditions) {
664
+ let values = [];
665
+ for (let value of conditions) {
666
+ validateStringValue(value, "condition");
667
+ if (value.indexOf(",") >= 0) throw new Error(`Invalid condition: ${value}`);
668
+ values.push(value);
669
+ }
670
+ flags.push(`--conditions=${values.join(",")}`);
671
+ }
672
+ if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, "external")}`);
673
+ if (alias) {
674
+ for (let old in alias) {
675
+ if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`);
676
+ flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`);
677
+ }
678
+ }
679
+ if (banner) {
680
+ for (let type in banner) {
681
+ if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`);
682
+ flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
683
+ }
684
+ }
685
+ if (footer) {
686
+ for (let type in footer) {
687
+ if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`);
688
+ flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
689
+ }
690
+ }
691
+ if (inject) for (let path32 of inject) flags.push(`--inject:${validateStringValue(path32, "inject")}`);
692
+ if (loader) {
693
+ for (let ext in loader) {
694
+ if (ext.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext}`);
695
+ flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`);
696
+ }
697
+ }
698
+ if (outExtension) {
699
+ for (let ext in outExtension) {
700
+ if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`);
701
+ flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
702
+ }
703
+ }
704
+ if (entryPoints) {
705
+ if (Array.isArray(entryPoints)) {
706
+ for (let i = 0, n = entryPoints.length; i < n; i++) {
707
+ let entryPoint = entryPoints[i];
708
+ if (typeof entryPoint === "object" && entryPoint !== null) {
709
+ let entryPointKeys = /* @__PURE__ */ Object.create(null);
710
+ let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
711
+ let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
712
+ checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
713
+ if (input === void 0) throw new Error('Missing property "in" for entry point at index ' + i);
714
+ if (output === void 0) throw new Error('Missing property "out" for entry point at index ' + i);
715
+ entries.push([output, input]);
716
+ } else {
717
+ entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
718
+ }
719
+ }
720
+ } else {
721
+ for (let key in entryPoints) {
722
+ entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
723
+ }
724
+ }
725
+ }
726
+ if (stdin) {
727
+ let stdinKeys = /* @__PURE__ */ Object.create(null);
728
+ let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
729
+ let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
730
+ let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
731
+ let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
732
+ checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object');
733
+ if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
734
+ if (loader2) flags.push(`--loader=${loader2}`);
735
+ if (resolveDir) stdinResolveDir = resolveDir;
736
+ if (typeof contents === "string") stdinContents = encodeUTF8(contents);
737
+ else if (contents instanceof Uint8Array) stdinContents = contents;
738
+ }
739
+ let nodePaths = [];
740
+ if (nodePathsInput) {
741
+ for (let value of nodePathsInput) {
742
+ value += "";
743
+ nodePaths.push(value);
744
+ }
745
+ }
746
+ return {
747
+ entries,
748
+ flags,
749
+ write,
750
+ stdinContents,
751
+ stdinResolveDir,
752
+ absWorkingDir,
753
+ nodePaths,
754
+ mangleCache: validateMangleCache(mangleCache)
755
+ };
756
+ }
757
+ function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) {
758
+ let flags = [];
759
+ let keys = /* @__PURE__ */ Object.create(null);
760
+ pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
761
+ pushCommonFlags(flags, options, keys);
762
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
763
+ let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
764
+ let loader = getFlag(options, keys, "loader", mustBeString);
765
+ let banner = getFlag(options, keys, "banner", mustBeString);
766
+ let footer = getFlag(options, keys, "footer", mustBeString);
767
+ let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
768
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
769
+ if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
770
+ if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
771
+ if (loader) flags.push(`--loader=${loader}`);
772
+ if (banner) flags.push(`--banner=${banner}`);
773
+ if (footer) flags.push(`--footer=${footer}`);
774
+ return {
775
+ flags,
776
+ mangleCache: validateMangleCache(mangleCache)
777
+ };
778
+ }
779
+ function createChannel(streamIn) {
780
+ const requestCallbacksByKey = {};
781
+ const closeData = { didClose: false, reason: "" };
782
+ let responseCallbacks = {};
783
+ let nextRequestID = 0;
784
+ let nextBuildKey = 0;
785
+ let stdout = new Uint8Array(16 * 1024);
786
+ let stdoutUsed = 0;
787
+ let readFromStdout = (chunk) => {
788
+ let limit = stdoutUsed + chunk.length;
789
+ if (limit > stdout.length) {
790
+ let swap = new Uint8Array(limit * 2);
791
+ swap.set(stdout);
792
+ stdout = swap;
793
+ }
794
+ stdout.set(chunk, stdoutUsed);
795
+ stdoutUsed += chunk.length;
796
+ let offset = 0;
797
+ while (offset + 4 <= stdoutUsed) {
798
+ let length = readUInt32LE(stdout, offset);
799
+ if (offset + 4 + length > stdoutUsed) {
800
+ break;
801
+ }
802
+ offset += 4;
803
+ handleIncomingPacket(stdout.subarray(offset, offset + length));
804
+ offset += length;
805
+ }
806
+ if (offset > 0) {
807
+ stdout.copyWithin(0, offset, stdoutUsed);
808
+ stdoutUsed -= offset;
809
+ }
810
+ };
811
+ let afterClose = (error) => {
812
+ closeData.didClose = true;
813
+ if (error) closeData.reason = ": " + (error.message || error);
814
+ const text = "The service was stopped" + closeData.reason;
815
+ for (let id in responseCallbacks) {
816
+ responseCallbacks[id](text, null);
817
+ }
818
+ responseCallbacks = {};
819
+ };
820
+ let sendRequest = (refs, value, callback) => {
821
+ if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null);
822
+ let id = nextRequestID++;
823
+ responseCallbacks[id] = (error, response) => {
824
+ try {
825
+ callback(error, response);
826
+ } finally {
827
+ if (refs) refs.unref();
828
+ }
829
+ };
830
+ if (refs) refs.ref();
831
+ streamIn.writeToStdin(encodePacket({ id, isRequest: true, value }));
832
+ };
833
+ let sendResponse = (id, value) => {
834
+ if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason);
835
+ streamIn.writeToStdin(encodePacket({ id, isRequest: false, value }));
836
+ };
837
+ let handleRequest = async (id, request) => {
838
+ try {
839
+ if (request.command === "ping") {
840
+ sendResponse(id, {});
841
+ return;
842
+ }
843
+ if (typeof request.key === "number") {
844
+ const requestCallbacks = requestCallbacksByKey[request.key];
845
+ if (!requestCallbacks) {
846
+ return;
847
+ }
848
+ const callback = requestCallbacks[request.command];
849
+ if (callback) {
850
+ await callback(id, request);
851
+ return;
852
+ }
853
+ }
854
+ throw new Error(`Invalid command: ` + request.command);
855
+ } catch (e) {
856
+ const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")];
857
+ try {
858
+ sendResponse(id, { errors });
859
+ } catch {
860
+ }
861
+ }
862
+ };
863
+ let isFirstPacket = true;
864
+ let handleIncomingPacket = (bytes) => {
865
+ if (isFirstPacket) {
866
+ isFirstPacket = false;
867
+ let binaryVersion = String.fromCharCode(...bytes);
868
+ if (binaryVersion !== "0.21.5") {
869
+ throw new Error(`Cannot start service: Host version "${"0.21.5"}" does not match binary version ${quote(binaryVersion)}`);
870
+ }
871
+ return;
872
+ }
873
+ let packet = decodePacket(bytes);
874
+ if (packet.isRequest) {
875
+ handleRequest(packet.id, packet.value);
876
+ } else {
877
+ let callback = responseCallbacks[packet.id];
878
+ delete responseCallbacks[packet.id];
879
+ if (packet.value.error) callback(packet.value.error, {});
880
+ else callback(null, packet.value);
881
+ }
882
+ };
883
+ let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => {
884
+ let refCount = 0;
885
+ const buildKey = nextBuildKey++;
886
+ const requestCallbacks = {};
887
+ const buildRefs = {
888
+ ref() {
889
+ if (++refCount === 1) {
890
+ if (refs) refs.ref();
891
+ }
892
+ },
893
+ unref() {
894
+ if (--refCount === 0) {
895
+ delete requestCallbacksByKey[buildKey];
896
+ if (refs) refs.unref();
897
+ }
898
+ }
899
+ };
900
+ requestCallbacksByKey[buildKey] = requestCallbacks;
901
+ buildRefs.ref();
902
+ buildOrContextImpl(
903
+ callName,
904
+ buildKey,
905
+ sendRequest,
906
+ sendResponse,
907
+ buildRefs,
908
+ streamIn,
909
+ requestCallbacks,
910
+ options,
911
+ isTTY2,
912
+ defaultWD2,
913
+ (err, res) => {
914
+ try {
915
+ callback(err, res);
916
+ } finally {
917
+ buildRefs.unref();
918
+ }
919
+ }
920
+ );
921
+ };
922
+ let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs32, callback }) => {
923
+ const details = createObjectStash();
924
+ let start = (inputPath) => {
925
+ try {
926
+ if (typeof input !== "string" && !(input instanceof Uint8Array))
927
+ throw new Error('The input to "transform" must be a string or a Uint8Array');
928
+ let {
929
+ flags,
930
+ mangleCache
931
+ } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault);
932
+ let request = {
933
+ command: "transform",
934
+ flags,
935
+ inputFS: inputPath !== null,
936
+ input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
937
+ };
938
+ if (mangleCache) request.mangleCache = mangleCache;
939
+ sendRequest(refs, request, (error, response) => {
940
+ if (error) return callback(new Error(error), null);
941
+ let errors = replaceDetailsInMessages(response.errors, details);
942
+ let warnings = replaceDetailsInMessages(response.warnings, details);
943
+ let outstanding = 1;
944
+ let next = () => {
945
+ if (--outstanding === 0) {
946
+ let result = {
947
+ warnings,
948
+ code: response.code,
949
+ map: response.map,
950
+ mangleCache: void 0,
951
+ legalComments: void 0
952
+ };
953
+ if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments;
954
+ if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache;
955
+ callback(null, result);
956
+ }
957
+ };
958
+ if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
959
+ if (response.codeFS) {
960
+ outstanding++;
961
+ fs32.readFile(response.code, (err, contents) => {
962
+ if (err !== null) {
963
+ callback(err, null);
964
+ } else {
965
+ response.code = contents;
966
+ next();
967
+ }
968
+ });
969
+ }
970
+ if (response.mapFS) {
971
+ outstanding++;
972
+ fs32.readFile(response.map, (err, contents) => {
973
+ if (err !== null) {
974
+ callback(err, null);
975
+ } else {
976
+ response.map = contents;
977
+ next();
978
+ }
979
+ });
980
+ }
981
+ next();
982
+ });
983
+ } catch (e) {
984
+ let flags = [];
985
+ try {
986
+ pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault);
987
+ } catch {
988
+ }
989
+ const error = extractErrorMessageV8(e, streamIn, details, void 0, "");
990
+ sendRequest(refs, { command: "error", flags, error }, () => {
991
+ error.detail = details.load(error.detail);
992
+ callback(failureErrorWithLog("Transform failed", [error], []), null);
993
+ });
994
+ }
995
+ };
996
+ if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
997
+ let next = start;
998
+ start = () => fs32.writeFile(input, next);
999
+ }
1000
+ start(null);
1001
+ };
1002
+ let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
1003
+ if (!options) throw new Error(`Missing second argument in ${callName}() call`);
1004
+ let keys = {};
1005
+ let kind = getFlag(options, keys, "kind", mustBeString);
1006
+ let color = getFlag(options, keys, "color", mustBeBoolean);
1007
+ let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
1008
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
1009
+ if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`);
1010
+ if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
1011
+ let request = {
1012
+ command: "format-msgs",
1013
+ messages: sanitizeMessages(messages, "messages", null, "", terminalWidth),
1014
+ isWarning: kind === "warning"
1015
+ };
1016
+ if (color !== void 0) request.color = color;
1017
+ if (terminalWidth !== void 0) request.terminalWidth = terminalWidth;
1018
+ sendRequest(refs, request, (error, response) => {
1019
+ if (error) return callback(new Error(error), null);
1020
+ callback(null, response.messages);
1021
+ });
1022
+ };
1023
+ let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
1024
+ if (options === void 0) options = {};
1025
+ let keys = {};
1026
+ let color = getFlag(options, keys, "color", mustBeBoolean);
1027
+ let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
1028
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
1029
+ let request = {
1030
+ command: "analyze-metafile",
1031
+ metafile
1032
+ };
1033
+ if (color !== void 0) request.color = color;
1034
+ if (verbose !== void 0) request.verbose = verbose;
1035
+ sendRequest(refs, request, (error, response) => {
1036
+ if (error) return callback(new Error(error), null);
1037
+ callback(null, response.result);
1038
+ });
1039
+ };
1040
+ return {
1041
+ readFromStdout,
1042
+ afterClose,
1043
+ service: {
1044
+ buildOrContext,
1045
+ transform: transform2,
1046
+ formatMessages: formatMessages2,
1047
+ analyzeMetafile: analyzeMetafile2
1048
+ }
1049
+ };
1050
+ }
1051
+ function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) {
1052
+ const details = createObjectStash();
1053
+ const isContext = callName === "context";
1054
+ const handleError = (e, pluginName) => {
1055
+ const flags = [];
1056
+ try {
1057
+ pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault);
1058
+ } catch {
1059
+ }
1060
+ const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName);
1061
+ sendRequest(refs, { command: "error", flags, error: message }, () => {
1062
+ message.detail = details.load(message.detail);
1063
+ callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
1064
+ });
1065
+ };
1066
+ let plugins;
1067
+ if (typeof options === "object") {
1068
+ const value = options.plugins;
1069
+ if (value !== void 0) {
1070
+ if (!Array.isArray(value)) return handleError(new Error(`"plugins" must be an array`), "");
1071
+ plugins = value;
1072
+ }
1073
+ }
1074
+ if (plugins && plugins.length > 0) {
1075
+ if (streamIn.isSync) return handleError(new Error("Cannot use plugins in synchronous API calls"), "");
1076
+ handlePlugins(
1077
+ buildKey,
1078
+ sendRequest,
1079
+ sendResponse,
1080
+ refs,
1081
+ streamIn,
1082
+ requestCallbacks,
1083
+ options,
1084
+ plugins,
1085
+ details
1086
+ ).then(
1087
+ (result) => {
1088
+ if (!result.ok) return handleError(result.error, result.pluginName);
1089
+ try {
1090
+ buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
1091
+ } catch (e) {
1092
+ handleError(e, "");
1093
+ }
1094
+ },
1095
+ (e) => handleError(e, "")
1096
+ );
1097
+ return;
1098
+ }
1099
+ try {
1100
+ buildOrContextContinue(null, (result, done) => done([], []), () => {
1101
+ });
1102
+ } catch (e) {
1103
+ handleError(e, "");
1104
+ }
1105
+ function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
1106
+ const writeDefault = streamIn.hasFS;
1107
+ const {
1108
+ entries,
1109
+ flags,
1110
+ write,
1111
+ stdinContents,
1112
+ stdinResolveDir,
1113
+ absWorkingDir,
1114
+ nodePaths,
1115
+ mangleCache
1116
+ } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault);
1117
+ if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`);
1118
+ const request = {
1119
+ command: "build",
1120
+ key: buildKey,
1121
+ entries,
1122
+ flags,
1123
+ write,
1124
+ stdinContents,
1125
+ stdinResolveDir,
1126
+ absWorkingDir: absWorkingDir || defaultWD2,
1127
+ nodePaths,
1128
+ context: isContext
1129
+ };
1130
+ if (requestPlugins) request.plugins = requestPlugins;
1131
+ if (mangleCache) request.mangleCache = mangleCache;
1132
+ const buildResponseToResult = (response, callback2) => {
1133
+ const result = {
1134
+ errors: replaceDetailsInMessages(response.errors, details),
1135
+ warnings: replaceDetailsInMessages(response.warnings, details),
1136
+ outputFiles: void 0,
1137
+ metafile: void 0,
1138
+ mangleCache: void 0
1139
+ };
1140
+ const originalErrors = result.errors.slice();
1141
+ const originalWarnings = result.warnings.slice();
1142
+ if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles);
1143
+ if (response.metafile) result.metafile = JSON.parse(response.metafile);
1144
+ if (response.mangleCache) result.mangleCache = response.mangleCache;
1145
+ if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
1146
+ runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
1147
+ if (originalErrors.length > 0 || onEndErrors.length > 0) {
1148
+ const error = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings));
1149
+ return callback2(error, null, onEndErrors, onEndWarnings);
1150
+ }
1151
+ callback2(null, result, onEndErrors, onEndWarnings);
1152
+ });
1153
+ };
1154
+ let latestResultPromise;
1155
+ let provideLatestResult;
1156
+ if (isContext)
1157
+ requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => {
1158
+ buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
1159
+ const response = {
1160
+ errors: onEndErrors,
1161
+ warnings: onEndWarnings
1162
+ };
1163
+ if (provideLatestResult) provideLatestResult(err, result);
1164
+ latestResultPromise = void 0;
1165
+ provideLatestResult = void 0;
1166
+ sendResponse(id, response);
1167
+ resolve();
1168
+ });
1169
+ });
1170
+ sendRequest(refs, request, (error, response) => {
1171
+ if (error) return callback(new Error(error), null);
1172
+ if (!isContext) {
1173
+ return buildResponseToResult(response, (err, res) => {
1174
+ scheduleOnDisposeCallbacks();
1175
+ return callback(err, res);
1176
+ });
1177
+ }
1178
+ if (response.errors.length > 0) {
1179
+ return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
1180
+ }
1181
+ let didDispose = false;
1182
+ const result = {
1183
+ rebuild: () => {
1184
+ if (!latestResultPromise) latestResultPromise = new Promise((resolve, reject) => {
1185
+ let settlePromise;
1186
+ provideLatestResult = (err, result2) => {
1187
+ if (!settlePromise) settlePromise = () => err ? reject(err) : resolve(result2);
1188
+ };
1189
+ const triggerAnotherBuild = () => {
1190
+ const request2 = {
1191
+ command: "rebuild",
1192
+ key: buildKey
1193
+ };
1194
+ sendRequest(refs, request2, (error2, response2) => {
1195
+ if (error2) {
1196
+ reject(new Error(error2));
1197
+ } else if (settlePromise) {
1198
+ settlePromise();
1199
+ } else {
1200
+ triggerAnotherBuild();
1201
+ }
1202
+ });
1203
+ };
1204
+ triggerAnotherBuild();
1205
+ });
1206
+ return latestResultPromise;
1207
+ },
1208
+ watch: (options2 = {}) => new Promise((resolve, reject) => {
1209
+ if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`);
1210
+ const keys = {};
1211
+ checkForInvalidFlags(options2, keys, `in watch() call`);
1212
+ const request2 = {
1213
+ command: "watch",
1214
+ key: buildKey
1215
+ };
1216
+ sendRequest(refs, request2, (error2) => {
1217
+ if (error2) reject(new Error(error2));
1218
+ else resolve(void 0);
1219
+ });
1220
+ }),
1221
+ serve: (options2 = {}) => new Promise((resolve, reject) => {
1222
+ if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`);
1223
+ const keys = {};
1224
+ const port = getFlag(options2, keys, "port", mustBeInteger);
1225
+ const host = getFlag(options2, keys, "host", mustBeString);
1226
+ const servedir = getFlag(options2, keys, "servedir", mustBeString);
1227
+ const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
1228
+ const certfile = getFlag(options2, keys, "certfile", mustBeString);
1229
+ const fallback = getFlag(options2, keys, "fallback", mustBeString);
1230
+ const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
1231
+ checkForInvalidFlags(options2, keys, `in serve() call`);
1232
+ const request2 = {
1233
+ command: "serve",
1234
+ key: buildKey,
1235
+ onRequest: !!onRequest
1236
+ };
1237
+ if (port !== void 0) request2.port = port;
1238
+ if (host !== void 0) request2.host = host;
1239
+ if (servedir !== void 0) request2.servedir = servedir;
1240
+ if (keyfile !== void 0) request2.keyfile = keyfile;
1241
+ if (certfile !== void 0) request2.certfile = certfile;
1242
+ if (fallback !== void 0) request2.fallback = fallback;
1243
+ sendRequest(refs, request2, (error2, response2) => {
1244
+ if (error2) return reject(new Error(error2));
1245
+ if (onRequest) {
1246
+ requestCallbacks["serve-request"] = (id, request3) => {
1247
+ onRequest(request3.args);
1248
+ sendResponse(id, {});
1249
+ };
1250
+ }
1251
+ resolve(response2);
1252
+ });
1253
+ }),
1254
+ cancel: () => new Promise((resolve) => {
1255
+ if (didDispose) return resolve();
1256
+ const request2 = {
1257
+ command: "cancel",
1258
+ key: buildKey
1259
+ };
1260
+ sendRequest(refs, request2, () => {
1261
+ resolve();
1262
+ });
1263
+ }),
1264
+ dispose: () => new Promise((resolve) => {
1265
+ if (didDispose) return resolve();
1266
+ didDispose = true;
1267
+ const request2 = {
1268
+ command: "dispose",
1269
+ key: buildKey
1270
+ };
1271
+ sendRequest(refs, request2, () => {
1272
+ resolve();
1273
+ scheduleOnDisposeCallbacks();
1274
+ refs.unref();
1275
+ });
1276
+ })
1277
+ };
1278
+ refs.ref();
1279
+ callback(null, result);
1280
+ });
1281
+ }
1282
+ }
1283
+ var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => {
1284
+ let onStartCallbacks = [];
1285
+ let onEndCallbacks = [];
1286
+ let onResolveCallbacks = {};
1287
+ let onLoadCallbacks = {};
1288
+ let onDisposeCallbacks = [];
1289
+ let nextCallbackID = 0;
1290
+ let i = 0;
1291
+ let requestPlugins = [];
1292
+ let isSetupDone = false;
1293
+ plugins = [...plugins];
1294
+ for (let item of plugins) {
1295
+ let keys = {};
1296
+ if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`);
1297
+ const name = getFlag(item, keys, "name", mustBeString);
1298
+ if (typeof name !== "string" || name === "") throw new Error(`Plugin at index ${i} is missing a name`);
1299
+ try {
1300
+ let setup = getFlag(item, keys, "setup", mustBeFunction);
1301
+ if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`);
1302
+ checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`);
1303
+ let plugin = {
1304
+ name,
1305
+ onStart: false,
1306
+ onEnd: false,
1307
+ onResolve: [],
1308
+ onLoad: []
1309
+ };
1310
+ i++;
1311
+ let resolve = (path32, options = {}) => {
1312
+ if (!isSetupDone) throw new Error('Cannot call "resolve" before plugin setup has completed');
1313
+ if (typeof path32 !== "string") throw new Error(`The path to resolve must be a string`);
1314
+ let keys2 = /* @__PURE__ */ Object.create(null);
1315
+ let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
1316
+ let importer = getFlag(options, keys2, "importer", mustBeString);
1317
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1318
+ let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
1319
+ let kind = getFlag(options, keys2, "kind", mustBeString);
1320
+ let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
1321
+ let importAttributes = getFlag(options, keys2, "with", mustBeObject);
1322
+ checkForInvalidFlags(options, keys2, "in resolve() call");
1323
+ return new Promise((resolve2, reject) => {
1324
+ const request = {
1325
+ command: "resolve",
1326
+ path: path32,
1327
+ key: buildKey,
1328
+ pluginName: name
1329
+ };
1330
+ if (pluginName != null) request.pluginName = pluginName;
1331
+ if (importer != null) request.importer = importer;
1332
+ if (namespace != null) request.namespace = namespace;
1333
+ if (resolveDir != null) request.resolveDir = resolveDir;
1334
+ if (kind != null) request.kind = kind;
1335
+ else throw new Error(`Must specify "kind" when calling "resolve"`);
1336
+ if (pluginData != null) request.pluginData = details.store(pluginData);
1337
+ if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with");
1338
+ sendRequest(refs, request, (error, response) => {
1339
+ if (error !== null) reject(new Error(error));
1340
+ else resolve2({
1341
+ errors: replaceDetailsInMessages(response.errors, details),
1342
+ warnings: replaceDetailsInMessages(response.warnings, details),
1343
+ path: response.path,
1344
+ external: response.external,
1345
+ sideEffects: response.sideEffects,
1346
+ namespace: response.namespace,
1347
+ suffix: response.suffix,
1348
+ pluginData: details.load(response.pluginData)
1349
+ });
1350
+ });
1351
+ });
1352
+ };
1353
+ let promise = setup({
1354
+ initialOptions,
1355
+ resolve,
1356
+ onStart(callback) {
1357
+ let registeredText = `This error came from the "onStart" callback registered here:`;
1358
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart");
1359
+ onStartCallbacks.push({ name, callback, note: registeredNote });
1360
+ plugin.onStart = true;
1361
+ },
1362
+ onEnd(callback) {
1363
+ let registeredText = `This error came from the "onEnd" callback registered here:`;
1364
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd");
1365
+ onEndCallbacks.push({ name, callback, note: registeredNote });
1366
+ plugin.onEnd = true;
1367
+ },
1368
+ onResolve(options, callback) {
1369
+ let registeredText = `This error came from the "onResolve" callback registered here:`;
1370
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve");
1371
+ let keys2 = {};
1372
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1373
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1374
+ checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`);
1375
+ if (filter == null) throw new Error(`onResolve() call is missing a filter`);
1376
+ let id = nextCallbackID++;
1377
+ onResolveCallbacks[id] = { name, callback, note: registeredNote };
1378
+ plugin.onResolve.push({ id, filter: filter.source, namespace: namespace || "" });
1379
+ },
1380
+ onLoad(options, callback) {
1381
+ let registeredText = `This error came from the "onLoad" callback registered here:`;
1382
+ let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad");
1383
+ let keys2 = {};
1384
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1385
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1386
+ checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`);
1387
+ if (filter == null) throw new Error(`onLoad() call is missing a filter`);
1388
+ let id = nextCallbackID++;
1389
+ onLoadCallbacks[id] = { name, callback, note: registeredNote };
1390
+ plugin.onLoad.push({ id, filter: filter.source, namespace: namespace || "" });
1391
+ },
1392
+ onDispose(callback) {
1393
+ onDisposeCallbacks.push(callback);
1394
+ },
1395
+ esbuild: streamIn.esbuild
1396
+ });
1397
+ if (promise) await promise;
1398
+ requestPlugins.push(plugin);
1399
+ } catch (e) {
1400
+ return { ok: false, error: e, pluginName: name };
1401
+ }
1402
+ }
1403
+ requestCallbacks["on-start"] = async (id, request) => {
1404
+ let response = { errors: [], warnings: [] };
1405
+ await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => {
1406
+ try {
1407
+ let result = await callback();
1408
+ if (result != null) {
1409
+ if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
1410
+ let keys = {};
1411
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1412
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1413
+ checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
1414
+ if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0));
1415
+ if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0));
1416
+ }
1417
+ } catch (e) {
1418
+ response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
1419
+ }
1420
+ }));
1421
+ sendResponse(id, response);
1422
+ };
1423
+ requestCallbacks["on-resolve"] = async (id, request) => {
1424
+ let response = {}, name = "", callback, note;
1425
+ for (let id2 of request.ids) {
1426
+ try {
1427
+ ({ name, callback, note } = onResolveCallbacks[id2]);
1428
+ let result = await callback({
1429
+ path: request.path,
1430
+ importer: request.importer,
1431
+ namespace: request.namespace,
1432
+ resolveDir: request.resolveDir,
1433
+ kind: request.kind,
1434
+ pluginData: details.load(request.pluginData),
1435
+ with: request.with
1436
+ });
1437
+ if (result != null) {
1438
+ if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
1439
+ let keys = {};
1440
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1441
+ let path32 = getFlag(result, keys, "path", mustBeString);
1442
+ let namespace = getFlag(result, keys, "namespace", mustBeString);
1443
+ let suffix = getFlag(result, keys, "suffix", mustBeString);
1444
+ let external = getFlag(result, keys, "external", mustBeBoolean);
1445
+ let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
1446
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1447
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1448
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1449
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
1450
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
1451
+ checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
1452
+ response.id = id2;
1453
+ if (pluginName != null) response.pluginName = pluginName;
1454
+ if (path32 != null) response.path = path32;
1455
+ if (namespace != null) response.namespace = namespace;
1456
+ if (suffix != null) response.suffix = suffix;
1457
+ if (external != null) response.external = external;
1458
+ if (sideEffects != null) response.sideEffects = sideEffects;
1459
+ if (pluginData != null) response.pluginData = details.store(pluginData);
1460
+ if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
1461
+ if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1462
+ if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1463
+ if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1464
+ break;
1465
+ }
1466
+ } catch (e) {
1467
+ response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
1468
+ break;
1469
+ }
1470
+ }
1471
+ sendResponse(id, response);
1472
+ };
1473
+ requestCallbacks["on-load"] = async (id, request) => {
1474
+ let response = {}, name = "", callback, note;
1475
+ for (let id2 of request.ids) {
1476
+ try {
1477
+ ({ name, callback, note } = onLoadCallbacks[id2]);
1478
+ let result = await callback({
1479
+ path: request.path,
1480
+ namespace: request.namespace,
1481
+ suffix: request.suffix,
1482
+ pluginData: details.load(request.pluginData),
1483
+ with: request.with
1484
+ });
1485
+ if (result != null) {
1486
+ if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
1487
+ let keys = {};
1488
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1489
+ let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
1490
+ let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
1491
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1492
+ let loader = getFlag(result, keys, "loader", mustBeString);
1493
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1494
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1495
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
1496
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
1497
+ checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
1498
+ response.id = id2;
1499
+ if (pluginName != null) response.pluginName = pluginName;
1500
+ if (contents instanceof Uint8Array) response.contents = contents;
1501
+ else if (contents != null) response.contents = encodeUTF8(contents);
1502
+ if (resolveDir != null) response.resolveDir = resolveDir;
1503
+ if (pluginData != null) response.pluginData = details.store(pluginData);
1504
+ if (loader != null) response.loader = loader;
1505
+ if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
1506
+ if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1507
+ if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1508
+ if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1509
+ break;
1510
+ }
1511
+ } catch (e) {
1512
+ response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] };
1513
+ break;
1514
+ }
1515
+ }
1516
+ sendResponse(id, response);
1517
+ };
1518
+ let runOnEndCallbacks = (result, done) => done([], []);
1519
+ if (onEndCallbacks.length > 0) {
1520
+ runOnEndCallbacks = (result, done) => {
1521
+ (async () => {
1522
+ const onEndErrors = [];
1523
+ const onEndWarnings = [];
1524
+ for (const { name, callback, note } of onEndCallbacks) {
1525
+ let newErrors;
1526
+ let newWarnings;
1527
+ try {
1528
+ const value = await callback(result);
1529
+ if (value != null) {
1530
+ if (typeof value !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
1531
+ let keys = {};
1532
+ let errors = getFlag(value, keys, "errors", mustBeArray);
1533
+ let warnings = getFlag(value, keys, "warnings", mustBeArray);
1534
+ checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
1535
+ if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name, void 0);
1536
+ if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1537
+ }
1538
+ } catch (e) {
1539
+ newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
1540
+ }
1541
+ if (newErrors) {
1542
+ onEndErrors.push(...newErrors);
1543
+ try {
1544
+ result.errors.push(...newErrors);
1545
+ } catch {
1546
+ }
1547
+ }
1548
+ if (newWarnings) {
1549
+ onEndWarnings.push(...newWarnings);
1550
+ try {
1551
+ result.warnings.push(...newWarnings);
1552
+ } catch {
1553
+ }
1554
+ }
1555
+ }
1556
+ done(onEndErrors, onEndWarnings);
1557
+ })();
1558
+ };
1559
+ }
1560
+ let scheduleOnDisposeCallbacks = () => {
1561
+ for (const cb of onDisposeCallbacks) {
1562
+ setTimeout(() => cb(), 0);
1563
+ }
1564
+ };
1565
+ isSetupDone = true;
1566
+ return {
1567
+ ok: true,
1568
+ requestPlugins,
1569
+ runOnEndCallbacks,
1570
+ scheduleOnDisposeCallbacks
1571
+ };
1572
+ };
1573
+ function createObjectStash() {
1574
+ const map = /* @__PURE__ */ new Map();
1575
+ let nextID = 0;
1576
+ return {
1577
+ load(id) {
1578
+ return map.get(id);
1579
+ },
1580
+ store(value) {
1581
+ if (value === void 0) return -1;
1582
+ const id = nextID++;
1583
+ map.set(id, value);
1584
+ return id;
1585
+ }
1586
+ };
1587
+ }
1588
+ function extractCallerV8(e, streamIn, ident) {
1589
+ let note;
1590
+ let tried = false;
1591
+ return () => {
1592
+ if (tried) return note;
1593
+ tried = true;
1594
+ try {
1595
+ let lines = (e.stack + "").split("\n");
1596
+ lines.splice(1, 1);
1597
+ let location = parseStackLinesV8(streamIn, lines, ident);
1598
+ if (location) {
1599
+ note = { text: e.message, location };
1600
+ return note;
1601
+ }
1602
+ } catch {
1603
+ }
1604
+ };
1605
+ }
1606
+ function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
1607
+ let text = "Internal error";
1608
+ let location = null;
1609
+ try {
1610
+ text = (e && e.message || e) + "";
1611
+ } catch {
1612
+ }
1613
+ try {
1614
+ location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), "");
1615
+ } catch {
1616
+ }
1617
+ return { id: "", pluginName, text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 };
1618
+ }
1619
+ function parseStackLinesV8(streamIn, lines, ident) {
1620
+ let at = " at ";
1621
+ if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) {
1622
+ for (let i = 1; i < lines.length; i++) {
1623
+ let line = lines[i];
1624
+ if (!line.startsWith(at)) continue;
1625
+ line = line.slice(at.length);
1626
+ while (true) {
1627
+ let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
1628
+ if (match) {
1629
+ line = match[1];
1630
+ continue;
1631
+ }
1632
+ match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
1633
+ if (match) {
1634
+ line = match[1];
1635
+ continue;
1636
+ }
1637
+ match = /^(\S+):(\d+):(\d+)$/.exec(line);
1638
+ if (match) {
1639
+ let contents;
1640
+ try {
1641
+ contents = streamIn.readFileSync(match[1], "utf8");
1642
+ } catch {
1643
+ break;
1644
+ }
1645
+ let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
1646
+ let column = +match[3] - 1;
1647
+ let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
1648
+ return {
1649
+ file: match[1],
1650
+ namespace: "file",
1651
+ line: +match[2],
1652
+ column: encodeUTF8(lineText.slice(0, column)).length,
1653
+ length: encodeUTF8(lineText.slice(column, column + length)).length,
1654
+ lineText: lineText + "\n" + lines.slice(1).join("\n"),
1655
+ suggestion: ""
1656
+ };
1657
+ }
1658
+ break;
1659
+ }
1660
+ }
1661
+ }
1662
+ return null;
1663
+ }
1664
+ function failureErrorWithLog(text, errors, warnings) {
1665
+ let limit = 5;
1666
+ text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => {
1667
+ if (i === limit) return "\n...";
1668
+ if (!e.location) return `
1669
+ error: ${e.text}`;
1670
+ let { file, line, column } = e.location;
1671
+ let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : "";
1672
+ return `
1673
+ ${file}:${line}:${column}: ERROR: ${pluginText}${e.text}`;
1674
+ }).join("");
1675
+ let error = new Error(text);
1676
+ for (const [key, value] of [["errors", errors], ["warnings", warnings]]) {
1677
+ Object.defineProperty(error, key, {
1678
+ configurable: true,
1679
+ enumerable: true,
1680
+ get: () => value,
1681
+ set: (value2) => Object.defineProperty(error, key, {
1682
+ configurable: true,
1683
+ enumerable: true,
1684
+ value: value2
1685
+ })
1686
+ });
1687
+ }
1688
+ return error;
1689
+ }
1690
+ function replaceDetailsInMessages(messages, stash) {
1691
+ for (const message of messages) {
1692
+ message.detail = stash.load(message.detail);
1693
+ }
1694
+ return messages;
1695
+ }
1696
+ function sanitizeLocation(location, where, terminalWidth) {
1697
+ if (location == null) return null;
1698
+ let keys = {};
1699
+ let file = getFlag(location, keys, "file", mustBeString);
1700
+ let namespace = getFlag(location, keys, "namespace", mustBeString);
1701
+ let line = getFlag(location, keys, "line", mustBeInteger);
1702
+ let column = getFlag(location, keys, "column", mustBeInteger);
1703
+ let length = getFlag(location, keys, "length", mustBeInteger);
1704
+ let lineText = getFlag(location, keys, "lineText", mustBeString);
1705
+ let suggestion = getFlag(location, keys, "suggestion", mustBeString);
1706
+ checkForInvalidFlags(location, keys, where);
1707
+ if (lineText) {
1708
+ const relevantASCII = lineText.slice(
1709
+ 0,
1710
+ (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80)
1711
+ );
1712
+ if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) {
1713
+ lineText = relevantASCII;
1714
+ }
1715
+ }
1716
+ return {
1717
+ file: file || "",
1718
+ namespace: namespace || "",
1719
+ line: line || 0,
1720
+ column: column || 0,
1721
+ length: length || 0,
1722
+ lineText: lineText || "",
1723
+ suggestion: suggestion || ""
1724
+ };
1725
+ }
1726
+ function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) {
1727
+ let messagesClone = [];
1728
+ let index = 0;
1729
+ for (const message of messages) {
1730
+ let keys = {};
1731
+ let id = getFlag(message, keys, "id", mustBeString);
1732
+ let pluginName = getFlag(message, keys, "pluginName", mustBeString);
1733
+ let text = getFlag(message, keys, "text", mustBeString);
1734
+ let location = getFlag(message, keys, "location", mustBeObjectOrNull);
1735
+ let notes = getFlag(message, keys, "notes", mustBeArray);
1736
+ let detail = getFlag(message, keys, "detail", canBeAnything);
1737
+ let where = `in element ${index} of "${property}"`;
1738
+ checkForInvalidFlags(message, keys, where);
1739
+ let notesClone = [];
1740
+ if (notes) {
1741
+ for (const note of notes) {
1742
+ let noteKeys = {};
1743
+ let noteText = getFlag(note, noteKeys, "text", mustBeString);
1744
+ let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
1745
+ checkForInvalidFlags(note, noteKeys, where);
1746
+ notesClone.push({
1747
+ text: noteText || "",
1748
+ location: sanitizeLocation(noteLocation, where, terminalWidth)
1749
+ });
1750
+ }
1751
+ }
1752
+ messagesClone.push({
1753
+ id: id || "",
1754
+ pluginName: pluginName || fallbackPluginName,
1755
+ text: text || "",
1756
+ location: sanitizeLocation(location, where, terminalWidth),
1757
+ notes: notesClone,
1758
+ detail: stash ? stash.store(detail) : -1
1759
+ });
1760
+ index++;
1761
+ }
1762
+ return messagesClone;
1763
+ }
1764
+ function sanitizeStringArray(values, property) {
1765
+ const result = [];
1766
+ for (const value of values) {
1767
+ if (typeof value !== "string") throw new Error(`${quote(property)} must be an array of strings`);
1768
+ result.push(value);
1769
+ }
1770
+ return result;
1771
+ }
1772
+ function sanitizeStringMap(map, property) {
1773
+ const result = /* @__PURE__ */ Object.create(null);
1774
+ for (const key in map) {
1775
+ const value = map[key];
1776
+ if (typeof value !== "string") throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`);
1777
+ result[key] = value;
1778
+ }
1779
+ return result;
1780
+ }
1781
+ function convertOutputFiles({ path: path32, contents, hash }) {
1782
+ let text = null;
1783
+ return {
1784
+ path: path32,
1785
+ contents,
1786
+ hash,
1787
+ get text() {
1788
+ const binary = this.contents;
1789
+ if (text === null || binary !== contents) {
1790
+ contents = binary;
1791
+ text = decodeUTF8(binary);
1792
+ }
1793
+ return text;
1794
+ }
1795
+ };
1796
+ }
1797
+ var fs3 = require("fs");
1798
+ var os2 = require("os");
1799
+ var path3 = require("path");
1800
+ var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
1801
+ var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
1802
+ var packageDarwin_arm64 = "@esbuild/darwin-arm64";
1803
+ var packageDarwin_x64 = "@esbuild/darwin-x64";
1804
+ var knownWindowsPackages = {
1805
+ "win32 arm64 LE": "@esbuild/win32-arm64",
1806
+ "win32 ia32 LE": "@esbuild/win32-ia32",
1807
+ "win32 x64 LE": "@esbuild/win32-x64"
1808
+ };
1809
+ var knownUnixlikePackages = {
1810
+ "aix ppc64 BE": "@esbuild/aix-ppc64",
1811
+ "android arm64 LE": "@esbuild/android-arm64",
1812
+ "darwin arm64 LE": "@esbuild/darwin-arm64",
1813
+ "darwin x64 LE": "@esbuild/darwin-x64",
1814
+ "freebsd arm64 LE": "@esbuild/freebsd-arm64",
1815
+ "freebsd x64 LE": "@esbuild/freebsd-x64",
1816
+ "linux arm LE": "@esbuild/linux-arm",
1817
+ "linux arm64 LE": "@esbuild/linux-arm64",
1818
+ "linux ia32 LE": "@esbuild/linux-ia32",
1819
+ "linux mips64el LE": "@esbuild/linux-mips64el",
1820
+ "linux ppc64 LE": "@esbuild/linux-ppc64",
1821
+ "linux riscv64 LE": "@esbuild/linux-riscv64",
1822
+ "linux s390x BE": "@esbuild/linux-s390x",
1823
+ "linux x64 LE": "@esbuild/linux-x64",
1824
+ "linux loong64 LE": "@esbuild/linux-loong64",
1825
+ "netbsd x64 LE": "@esbuild/netbsd-x64",
1826
+ "openbsd x64 LE": "@esbuild/openbsd-x64",
1827
+ "sunos x64 LE": "@esbuild/sunos-x64"
1828
+ };
1829
+ var knownWebAssemblyFallbackPackages = {
1830
+ "android arm LE": "@esbuild/android-arm",
1831
+ "android x64 LE": "@esbuild/android-x64"
1832
+ };
1833
+ function pkgAndSubpathForCurrentPlatform() {
1834
+ let pkg;
1835
+ let subpath;
1836
+ let isWASM = false;
1837
+ let platformKey = `${process.platform} ${os2.arch()} ${os2.endianness()}`;
1838
+ if (platformKey in knownWindowsPackages) {
1839
+ pkg = knownWindowsPackages[platformKey];
1840
+ subpath = "esbuild.exe";
1841
+ } else if (platformKey in knownUnixlikePackages) {
1842
+ pkg = knownUnixlikePackages[platformKey];
1843
+ subpath = "bin/esbuild";
1844
+ } else if (platformKey in knownWebAssemblyFallbackPackages) {
1845
+ pkg = knownWebAssemblyFallbackPackages[platformKey];
1846
+ subpath = "bin/esbuild";
1847
+ isWASM = true;
1848
+ } else {
1849
+ throw new Error(`Unsupported platform: ${platformKey}`);
1850
+ }
1851
+ return { pkg, subpath, isWASM };
1852
+ }
1853
+ function pkgForSomeOtherPlatform() {
1854
+ const libMainJS = require.resolve("esbuild");
1855
+ const nodeModulesDirectory = path3.dirname(path3.dirname(path3.dirname(libMainJS)));
1856
+ if (path3.basename(nodeModulesDirectory) === "node_modules") {
1857
+ for (const unixKey in knownUnixlikePackages) {
1858
+ try {
1859
+ const pkg = knownUnixlikePackages[unixKey];
1860
+ if (fs3.existsSync(path3.join(nodeModulesDirectory, pkg))) return pkg;
1861
+ } catch {
1862
+ }
1863
+ }
1864
+ for (const windowsKey in knownWindowsPackages) {
1865
+ try {
1866
+ const pkg = knownWindowsPackages[windowsKey];
1867
+ if (fs3.existsSync(path3.join(nodeModulesDirectory, pkg))) return pkg;
1868
+ } catch {
1869
+ }
1870
+ }
1871
+ }
1872
+ return null;
1873
+ }
1874
+ function downloadedBinPath(pkg, subpath) {
1875
+ const esbuildLibDir = path3.dirname(require.resolve("esbuild"));
1876
+ return path3.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path3.basename(subpath)}`);
1877
+ }
1878
+ function generateBinPath() {
1879
+ if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
1880
+ if (!fs3.existsSync(ESBUILD_BINARY_PATH)) {
1881
+ console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
1882
+ } else {
1883
+ return { binPath: ESBUILD_BINARY_PATH, isWASM: false };
1884
+ }
1885
+ }
1886
+ const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
1887
+ let binPath;
1888
+ try {
1889
+ binPath = require.resolve(`${pkg}/${subpath}`);
1890
+ } catch (e) {
1891
+ binPath = downloadedBinPath(pkg, subpath);
1892
+ if (!fs3.existsSync(binPath)) {
1893
+ try {
1894
+ require.resolve(pkg);
1895
+ } catch {
1896
+ const otherPkg = pkgForSomeOtherPlatform();
1897
+ if (otherPkg) {
1898
+ let suggestions = `
1899
+ Specifically the "${otherPkg}" package is present but this platform
1900
+ needs the "${pkg}" package instead. People often get into this
1901
+ situation by installing esbuild on Windows or macOS and copying "node_modules"
1902
+ into a Docker image that runs Linux, or by copying "node_modules" between
1903
+ Windows and WSL environments.
1904
+
1905
+ If you are installing with npm, you can try not copying the "node_modules"
1906
+ directory when you copy the files over, and running "npm ci" or "npm install"
1907
+ on the destination platform after the copy. Or you could consider using yarn
1908
+ instead of npm which has built-in support for installing a package on multiple
1909
+ platforms simultaneously.
1910
+
1911
+ If you are installing with yarn, you can try listing both this platform and the
1912
+ other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
1913
+ feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
1914
+ Keep in mind that this means multiple copies of esbuild will be present.
1915
+ `;
1916
+ if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) {
1917
+ suggestions = `
1918
+ Specifically the "${otherPkg}" package is present but this platform
1919
+ needs the "${pkg}" package instead. People often get into this
1920
+ situation by installing esbuild with npm running inside of Rosetta 2 and then
1921
+ trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
1922
+ 2 is Apple's on-the-fly x86_64-to-arm64 translation service).
1923
+
1924
+ If you are installing with npm, you can try ensuring that both npm and node are
1925
+ not running under Rosetta 2 and then reinstalling esbuild. This likely involves
1926
+ changing how you installed npm and/or node. For example, installing node with
1927
+ the universal installer here should work: https://nodejs.org/en/download/. Or
1928
+ you could consider using yarn instead of npm which has built-in support for
1929
+ installing a package on multiple platforms simultaneously.
1930
+
1931
+ If you are installing with yarn, you can try listing both "arm64" and "x64"
1932
+ in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
1933
+ https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
1934
+ Keep in mind that this means multiple copies of esbuild will be present.
1935
+ `;
1936
+ }
1937
+ throw new Error(`
1938
+ You installed esbuild for another platform than the one you're currently using.
1939
+ This won't work because esbuild is written with native code and needs to
1940
+ install a platform-specific binary executable.
1941
+ ${suggestions}
1942
+ Another alternative is to use the "esbuild-wasm" package instead, which works
1943
+ the same way on all platforms. But it comes with a heavy performance cost and
1944
+ can sometimes be 10x slower than the "esbuild" package, so you may also not
1945
+ want to do that.
1946
+ `);
1947
+ }
1948
+ throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
1949
+
1950
+ If you are installing esbuild with npm, make sure that you don't specify the
1951
+ "--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
1952
+ of "package.json" is used by esbuild to install the correct binary executable
1953
+ for your current platform.`);
1954
+ }
1955
+ throw e;
1956
+ }
1957
+ }
1958
+ if (/\.zip\//.test(binPath)) {
1959
+ let pnpapi;
1960
+ try {
1961
+ pnpapi = require("pnpapi");
1962
+ } catch (e) {
1963
+ }
1964
+ if (pnpapi) {
1965
+ const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
1966
+ const binTargetPath = path3.join(
1967
+ root,
1968
+ "node_modules",
1969
+ ".cache",
1970
+ "esbuild",
1971
+ `pnpapi-${pkg.replace("/", "-")}-${"0.21.5"}-${path3.basename(subpath)}`
1972
+ );
1973
+ if (!fs3.existsSync(binTargetPath)) {
1974
+ fs3.mkdirSync(path3.dirname(binTargetPath), { recursive: true });
1975
+ fs3.copyFileSync(binPath, binTargetPath);
1976
+ fs3.chmodSync(binTargetPath, 493);
1977
+ }
1978
+ return { binPath: binTargetPath, isWASM };
1979
+ }
1980
+ }
1981
+ return { binPath, isWASM };
1982
+ }
1983
+ var child_process = require("child_process");
1984
+ var crypto = require("crypto");
1985
+ var path22 = require("path");
1986
+ var fs22 = require("fs");
1987
+ var os22 = require("os");
1988
+ var tty = require("tty");
1989
+ var worker_threads;
1990
+ if (process.env.ESBUILD_WORKER_THREADS !== "0") {
1991
+ try {
1992
+ worker_threads = require("worker_threads");
1993
+ } catch {
1994
+ }
1995
+ let [major, minor] = process.versions.node.split(".");
1996
+ if (
1997
+ // <v12.17.0 does not work
1998
+ +major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13
1999
+ ) {
2000
+ worker_threads = void 0;
2001
+ }
2002
+ }
2003
+ var _a;
2004
+ var isInternalWorkerThread = ((_a = worker_threads == null ? void 0 : worker_threads.workerData) == null ? void 0 : _a.esbuildVersion) === "0.21.5";
2005
+ var esbuildCommandAndArgs = () => {
2006
+ if ((!ESBUILD_BINARY_PATH || false) && (path22.basename(__filename) !== "main.js" || path22.basename(__dirname) !== "lib")) {
2007
+ throw new Error(
2008
+ `The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle.
2009
+
2010
+ More information: The file containing the code for esbuild's JavaScript API (${__filename}) does not appear to be inside the esbuild package on the file system, which usually means that the esbuild package was bundled into another file. This is problematic because the API needs to run a binary executable inside the esbuild package which is located using a relative path from the API code to the executable. If the esbuild package is bundled, the relative path will be incorrect and the executable won't be found.`
2011
+ );
2012
+ }
2013
+ if (false) {
2014
+ return ["node", [path22.join(__dirname, "..", "bin", "esbuild")]];
2015
+ } else {
2016
+ const { binPath, isWASM } = generateBinPath();
2017
+ if (isWASM) {
2018
+ return ["node", [binPath]];
2019
+ } else {
2020
+ return [binPath, []];
2021
+ }
2022
+ }
2023
+ };
2024
+ var isTTY = () => tty.isatty(2);
2025
+ var fsSync = {
2026
+ readFile(tempFile, callback) {
2027
+ try {
2028
+ let contents = fs22.readFileSync(tempFile, "utf8");
2029
+ try {
2030
+ fs22.unlinkSync(tempFile);
2031
+ } catch {
2032
+ }
2033
+ callback(null, contents);
2034
+ } catch (err) {
2035
+ callback(err, null);
2036
+ }
2037
+ },
2038
+ writeFile(contents, callback) {
2039
+ try {
2040
+ let tempFile = randomFileName();
2041
+ fs22.writeFileSync(tempFile, contents);
2042
+ callback(tempFile);
2043
+ } catch {
2044
+ callback(null);
2045
+ }
2046
+ }
2047
+ };
2048
+ var fsAsync = {
2049
+ readFile(tempFile, callback) {
2050
+ try {
2051
+ fs22.readFile(tempFile, "utf8", (err, contents) => {
2052
+ try {
2053
+ fs22.unlink(tempFile, () => callback(err, contents));
2054
+ } catch {
2055
+ callback(err, contents);
2056
+ }
2057
+ });
2058
+ } catch (err) {
2059
+ callback(err, null);
2060
+ }
2061
+ },
2062
+ writeFile(contents, callback) {
2063
+ try {
2064
+ let tempFile = randomFileName();
2065
+ fs22.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
2066
+ } catch {
2067
+ callback(null);
2068
+ }
2069
+ }
2070
+ };
2071
+ var version = "0.21.5";
2072
+ var build = (options) => ensureServiceIsRunning().build(options);
2073
+ var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
2074
+ var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
2075
+ var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
2076
+ var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options);
2077
+ var buildSync = (options) => {
2078
+ if (worker_threads && !isInternalWorkerThread) {
2079
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2080
+ return workerThreadService.buildSync(options);
2081
+ }
2082
+ let result;
2083
+ runServiceSync((service) => service.buildOrContext({
2084
+ callName: "buildSync",
2085
+ refs: null,
2086
+ options,
2087
+ isTTY: isTTY(),
2088
+ defaultWD,
2089
+ callback: (err, res) => {
2090
+ if (err) throw err;
2091
+ result = res;
2092
+ }
2093
+ }));
2094
+ return result;
2095
+ };
2096
+ var transformSync = (input, options) => {
2097
+ if (worker_threads && !isInternalWorkerThread) {
2098
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2099
+ return workerThreadService.transformSync(input, options);
2100
+ }
2101
+ let result;
2102
+ runServiceSync((service) => service.transform({
2103
+ callName: "transformSync",
2104
+ refs: null,
2105
+ input,
2106
+ options: options || {},
2107
+ isTTY: isTTY(),
2108
+ fs: fsSync,
2109
+ callback: (err, res) => {
2110
+ if (err) throw err;
2111
+ result = res;
2112
+ }
2113
+ }));
2114
+ return result;
2115
+ };
2116
+ var formatMessagesSync = (messages, options) => {
2117
+ if (worker_threads && !isInternalWorkerThread) {
2118
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2119
+ return workerThreadService.formatMessagesSync(messages, options);
2120
+ }
2121
+ let result;
2122
+ runServiceSync((service) => service.formatMessages({
2123
+ callName: "formatMessagesSync",
2124
+ refs: null,
2125
+ messages,
2126
+ options,
2127
+ callback: (err, res) => {
2128
+ if (err) throw err;
2129
+ result = res;
2130
+ }
2131
+ }));
2132
+ return result;
2133
+ };
2134
+ var analyzeMetafileSync = (metafile, options) => {
2135
+ if (worker_threads && !isInternalWorkerThread) {
2136
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2137
+ return workerThreadService.analyzeMetafileSync(metafile, options);
2138
+ }
2139
+ let result;
2140
+ runServiceSync((service) => service.analyzeMetafile({
2141
+ callName: "analyzeMetafileSync",
2142
+ refs: null,
2143
+ metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2144
+ options,
2145
+ callback: (err, res) => {
2146
+ if (err) throw err;
2147
+ result = res;
2148
+ }
2149
+ }));
2150
+ return result;
2151
+ };
2152
+ var stop = () => {
2153
+ if (stopService) stopService();
2154
+ if (workerThreadService) workerThreadService.stop();
2155
+ return Promise.resolve();
2156
+ };
2157
+ var initializeWasCalled = false;
2158
+ var initialize = (options) => {
2159
+ options = validateInitializeOptions(options || {});
2160
+ if (options.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`);
2161
+ if (options.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`);
2162
+ if (options.worker) throw new Error(`The "worker" option only works in the browser`);
2163
+ if (initializeWasCalled) throw new Error('Cannot call "initialize" more than once');
2164
+ ensureServiceIsRunning();
2165
+ initializeWasCalled = true;
2166
+ return Promise.resolve();
2167
+ };
2168
+ var defaultWD = process.cwd();
2169
+ var longLivedService;
2170
+ var stopService;
2171
+ var ensureServiceIsRunning = () => {
2172
+ if (longLivedService) return longLivedService;
2173
+ let [command, args] = esbuildCommandAndArgs();
2174
+ let child = child_process.spawn(command, args.concat(`--service=${"0.21.5"}`, "--ping"), {
2175
+ windowsHide: true,
2176
+ stdio: ["pipe", "pipe", "inherit"],
2177
+ cwd: defaultWD
2178
+ });
2179
+ let { readFromStdout, afterClose, service } = createChannel({
2180
+ writeToStdin(bytes) {
2181
+ child.stdin.write(bytes, (err) => {
2182
+ if (err) afterClose(err);
2183
+ });
2184
+ },
2185
+ readFileSync: fs22.readFileSync,
2186
+ isSync: false,
2187
+ hasFS: true,
2188
+ esbuild: node_exports
2189
+ });
2190
+ child.stdin.on("error", afterClose);
2191
+ child.on("error", afterClose);
2192
+ const stdin = child.stdin;
2193
+ const stdout = child.stdout;
2194
+ stdout.on("data", readFromStdout);
2195
+ stdout.on("end", afterClose);
2196
+ stopService = () => {
2197
+ stdin.destroy();
2198
+ stdout.destroy();
2199
+ child.kill();
2200
+ initializeWasCalled = false;
2201
+ longLivedService = void 0;
2202
+ stopService = void 0;
2203
+ };
2204
+ let refCount = 0;
2205
+ child.unref();
2206
+ if (stdin.unref) {
2207
+ stdin.unref();
2208
+ }
2209
+ if (stdout.unref) {
2210
+ stdout.unref();
2211
+ }
2212
+ const refs = {
2213
+ ref() {
2214
+ if (++refCount === 1) child.ref();
2215
+ },
2216
+ unref() {
2217
+ if (--refCount === 0) child.unref();
2218
+ }
2219
+ };
2220
+ longLivedService = {
2221
+ build: (options) => new Promise((resolve, reject) => {
2222
+ service.buildOrContext({
2223
+ callName: "build",
2224
+ refs,
2225
+ options,
2226
+ isTTY: isTTY(),
2227
+ defaultWD,
2228
+ callback: (err, res) => err ? reject(err) : resolve(res)
2229
+ });
2230
+ }),
2231
+ context: (options) => new Promise((resolve, reject) => service.buildOrContext({
2232
+ callName: "context",
2233
+ refs,
2234
+ options,
2235
+ isTTY: isTTY(),
2236
+ defaultWD,
2237
+ callback: (err, res) => err ? reject(err) : resolve(res)
2238
+ })),
2239
+ transform: (input, options) => new Promise((resolve, reject) => service.transform({
2240
+ callName: "transform",
2241
+ refs,
2242
+ input,
2243
+ options: options || {},
2244
+ isTTY: isTTY(),
2245
+ fs: fsAsync,
2246
+ callback: (err, res) => err ? reject(err) : resolve(res)
2247
+ })),
2248
+ formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({
2249
+ callName: "formatMessages",
2250
+ refs,
2251
+ messages,
2252
+ options,
2253
+ callback: (err, res) => err ? reject(err) : resolve(res)
2254
+ })),
2255
+ analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({
2256
+ callName: "analyzeMetafile",
2257
+ refs,
2258
+ metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2259
+ options,
2260
+ callback: (err, res) => err ? reject(err) : resolve(res)
2261
+ }))
2262
+ };
2263
+ return longLivedService;
2264
+ };
2265
+ var runServiceSync = (callback) => {
2266
+ let [command, args] = esbuildCommandAndArgs();
2267
+ let stdin = new Uint8Array();
2268
+ let { readFromStdout, afterClose, service } = createChannel({
2269
+ writeToStdin(bytes) {
2270
+ if (stdin.length !== 0) throw new Error("Must run at most one command");
2271
+ stdin = bytes;
2272
+ },
2273
+ isSync: true,
2274
+ hasFS: true,
2275
+ esbuild: node_exports
2276
+ });
2277
+ callback(service);
2278
+ let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.21.5"}`), {
2279
+ cwd: defaultWD,
2280
+ windowsHide: true,
2281
+ input: stdin,
2282
+ // We don't know how large the output could be. If it's too large, the
2283
+ // command will fail with ENOBUFS. Reserve 16mb for now since that feels
2284
+ // like it should be enough. Also allow overriding this with an environment
2285
+ // variable.
2286
+ maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
2287
+ });
2288
+ readFromStdout(stdout);
2289
+ afterClose(null);
2290
+ };
2291
+ var randomFileName = () => {
2292
+ return path22.join(os22.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`);
2293
+ };
2294
+ var workerThreadService = null;
2295
+ var startWorkerThreadService = (worker_threads2) => {
2296
+ let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel();
2297
+ let worker = new worker_threads2.Worker(__filename, {
2298
+ workerData: { workerPort, defaultWD, esbuildVersion: "0.21.5" },
2299
+ transferList: [workerPort],
2300
+ // From node's documentation: https://nodejs.org/api/worker_threads.html
2301
+ //
2302
+ // Take care when launching worker threads from preload scripts (scripts loaded
2303
+ // and run using the `-r` command line flag). Unless the `execArgv` option is
2304
+ // explicitly set, new Worker threads automatically inherit the command line flags
2305
+ // from the running process and will preload the same preload scripts as the main
2306
+ // thread. If the preload script unconditionally launches a worker thread, every
2307
+ // thread spawned will spawn another until the application crashes.
2308
+ //
2309
+ execArgv: []
2310
+ });
2311
+ let nextID = 0;
2312
+ let fakeBuildError = (text) => {
2313
+ let error = new Error(`Build failed with 1 error:
2314
+ error: ${text}`);
2315
+ let errors = [{ id: "", pluginName: "", text, location: null, notes: [], detail: void 0 }];
2316
+ error.errors = errors;
2317
+ error.warnings = [];
2318
+ return error;
2319
+ };
2320
+ let validateBuildSyncOptions = (options) => {
2321
+ if (!options) return;
2322
+ let plugins = options.plugins;
2323
+ if (plugins && plugins.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
2324
+ };
2325
+ let applyProperties = (object, properties) => {
2326
+ for (let key in properties) {
2327
+ object[key] = properties[key];
2328
+ }
2329
+ };
2330
+ let runCallSync = (command, args) => {
2331
+ let id = nextID++;
2332
+ let sharedBuffer = new SharedArrayBuffer(8);
2333
+ let sharedBufferView = new Int32Array(sharedBuffer);
2334
+ let msg = { sharedBuffer, id, command, args };
2335
+ worker.postMessage(msg);
2336
+ let status = Atomics.wait(sharedBufferView, 0, 0);
2337
+ if (status !== "ok" && status !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status);
2338
+ let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
2339
+ if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
2340
+ if (reject) {
2341
+ applyProperties(reject, properties);
2342
+ throw reject;
2343
+ }
2344
+ return resolve;
2345
+ };
2346
+ worker.unref();
2347
+ return {
2348
+ buildSync(options) {
2349
+ validateBuildSyncOptions(options);
2350
+ return runCallSync("build", [options]);
2351
+ },
2352
+ transformSync(input, options) {
2353
+ return runCallSync("transform", [input, options]);
2354
+ },
2355
+ formatMessagesSync(messages, options) {
2356
+ return runCallSync("formatMessages", [messages, options]);
2357
+ },
2358
+ analyzeMetafileSync(metafile, options) {
2359
+ return runCallSync("analyzeMetafile", [metafile, options]);
2360
+ },
2361
+ stop() {
2362
+ worker.terminate();
2363
+ workerThreadService = null;
2364
+ }
2365
+ };
2366
+ };
2367
+ var startSyncServiceWorker = () => {
2368
+ let workerPort = worker_threads.workerData.workerPort;
2369
+ let parentPort2 = worker_threads.parentPort;
2370
+ let extractProperties = (object) => {
2371
+ let properties = {};
2372
+ if (object && typeof object === "object") {
2373
+ for (let key in object) {
2374
+ properties[key] = object[key];
2375
+ }
2376
+ }
2377
+ return properties;
2378
+ };
2379
+ try {
2380
+ let service = ensureServiceIsRunning();
2381
+ defaultWD = worker_threads.workerData.defaultWD;
2382
+ parentPort2.on("message", (msg) => {
2383
+ (async () => {
2384
+ let { sharedBuffer, id, command, args } = msg;
2385
+ let sharedBufferView = new Int32Array(sharedBuffer);
2386
+ try {
2387
+ switch (command) {
2388
+ case "build":
2389
+ workerPort.postMessage({ id, resolve: await service.build(args[0]) });
2390
+ break;
2391
+ case "transform":
2392
+ workerPort.postMessage({ id, resolve: await service.transform(args[0], args[1]) });
2393
+ break;
2394
+ case "formatMessages":
2395
+ workerPort.postMessage({ id, resolve: await service.formatMessages(args[0], args[1]) });
2396
+ break;
2397
+ case "analyzeMetafile":
2398
+ workerPort.postMessage({ id, resolve: await service.analyzeMetafile(args[0], args[1]) });
2399
+ break;
2400
+ default:
2401
+ throw new Error(`Invalid command: ${command}`);
2402
+ }
2403
+ } catch (reject) {
2404
+ workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
2405
+ }
2406
+ Atomics.add(sharedBufferView, 0, 1);
2407
+ Atomics.notify(sharedBufferView, 0, Infinity);
2408
+ })();
2409
+ });
2410
+ } catch (reject) {
2411
+ parentPort2.on("message", (msg) => {
2412
+ let { sharedBuffer, id } = msg;
2413
+ let sharedBufferView = new Int32Array(sharedBuffer);
2414
+ workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
2415
+ Atomics.add(sharedBufferView, 0, 1);
2416
+ Atomics.notify(sharedBufferView, 0, Infinity);
2417
+ });
2418
+ }
2419
+ };
2420
+ if (isInternalWorkerThread) {
2421
+ startSyncServiceWorker();
2422
+ }
2423
+ var node_default = node_exports;
2424
+ }
2425
+ });
2426
+
2427
+ // core/bundler/game-bundler-worker.ts
2428
+ var game_bundler_worker_exports = {};
2429
+ module.exports = __toCommonJS(game_bundler_worker_exports);
2430
+ var import_worker_threads = require("worker_threads");
2431
+
2432
+ // core/bundler/game-packager.ts
2433
+ var fs2 = __toESM(require("fs"));
2434
+ var path2 = __toESM(require("path"));
2435
+ init_ci_installer();
2436
+ var _esbuild = null;
2437
+ function getEsbuild() {
2438
+ if (!_esbuild) {
2439
+ try {
2440
+ _esbuild = require_main();
2441
+ } catch (e) {
2442
+ throw new Error(
2443
+ `[game-packager] Failed to load esbuild fallback transpiler. Ensure esbuild is installed: ${e}`
2444
+ );
2445
+ }
2446
+ }
2447
+ return _esbuild;
2448
+ }
2449
+ var _enhanceTransform = null;
2450
+ var _ciDir = null;
2451
+ function getCiDir() {
2452
+ if (!_ciDir) {
2453
+ if (isCiInstalled()) {
2454
+ _ciDir = getCiRequirePath();
2455
+ } else {
2456
+ _ciDir = require.resolve("miniprogram-ci").replace(/[/\\]dist[/\\]index\.js$/, "");
2457
+ }
2458
+ }
2459
+ return _ciDir;
2460
+ }
2461
+ function getEnhanceTransform() {
2462
+ if (!_enhanceTransform) {
2463
+ try {
2464
+ const ciDir = getCiDir();
2465
+ _enhanceTransform = require(`${ciDir}/dist/modules/corecompiler/original/js/enhance`);
2466
+ } catch (e) {
2467
+ throw new Error(
2468
+ `[game-packager] Failed to load miniprogram-ci enhanced babel7 transform. Ensure miniprogram-ci is installed: ${e}`
2469
+ );
2470
+ }
2471
+ }
2472
+ return _enhanceTransform;
2473
+ }
2474
+ function readBabelHelper(helperPath) {
2475
+ const ciDir = getCiDir();
2476
+ const vendorRelative = helperPath.replace("@babel/runtime", "babel_runtime");
2477
+ const absPath = path2.join(ciDir, "dist", "vendor", vendorRelative + ".js");
2478
+ return fs2.readFileSync(absPath, "utf-8");
2479
+ }
2480
+ var BABEL_RUNTIME_ROOT = "@babel/runtime";
2481
+ function silenceBabelDeopt(fn) {
2482
+ const _origWarn = console.warn.bind(console);
2483
+ const _origLog = console.log.bind(console);
2484
+ const _noteRe = /deoptimised the styling/i;
2485
+ console.warn = (...args) => {
2486
+ if (!_noteRe.test(String(args[0]))) _origWarn(...args);
2487
+ };
2488
+ console.log = (...args) => {
2489
+ if (!_noteRe.test(String(args[0]))) _origLog(...args);
2490
+ };
2491
+ try {
2492
+ return fn();
2493
+ } finally {
2494
+ console.warn = _origWarn;
2495
+ console.log = _origLog;
2496
+ }
2497
+ }
2498
+ function extractBabelRuntimeRequires(source) {
2499
+ const results = [];
2500
+ const re = /\brequire\s*\(\s*['"](@babel\/runtime\/[^'"]+)['"]\s*\)/g;
2501
+ let m;
2502
+ while ((m = re.exec(source)) !== null) results.push(m[1]);
2503
+ return results;
2504
+ }
2505
+ function extractHelperDependencies(currentHelperPath, source) {
2506
+ const dir = currentHelperPath.replace(/\/[^/]+$/, "");
2507
+ const results = [];
2508
+ const re = /\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
2509
+ let m;
2510
+ while ((m = re.exec(source)) !== null) {
2511
+ const spec = m[1];
2512
+ if (spec.startsWith("@babel/runtime/")) {
2513
+ results.push(spec);
2514
+ } else if (spec.startsWith("./")) {
2515
+ results.push(dir + "/" + spec.slice(2));
2516
+ } else if (spec.startsWith("../")) {
2517
+ let base = dir;
2518
+ let rest = spec;
2519
+ while (rest.startsWith("../")) {
2520
+ base = base.replace(/\/[^/]+$/, "");
2521
+ rest = rest.slice(3);
2522
+ }
2523
+ results.push(base + "/" + rest);
2524
+ }
2525
+ }
2526
+ return results;
2527
+ }
2528
+ function normaliseRoot(raw) {
2529
+ return raw.replace(/^\/+/, "").replace(/\/+$/, "");
2530
+ }
2531
+ function discoverPackages(gameDir) {
2532
+ const gameJsonPath = path2.join(gameDir, "game.json");
2533
+ let gameJson = {};
2534
+ try {
2535
+ gameJson = JSON.parse(fs2.readFileSync(gameJsonPath, "utf-8"));
2536
+ } catch {
2537
+ }
2538
+ const packages = [];
2539
+ packages.push({ name: "", root: "", entry: "game.js" });
2540
+ const rawSubs = gameJson["subPackages"] ?? gameJson["subpackages"] ?? [];
2541
+ for (const sp of rawSubs) {
2542
+ const rawRoot = typeof sp.root === "string" ? sp.root : "";
2543
+ const name = typeof sp.name === "string" ? sp.name : rawRoot;
2544
+ const root = normaliseRoot(rawRoot);
2545
+ if (!root) continue;
2546
+ packages.push({ name, root, entry: "game.js" });
2547
+ }
2548
+ return packages;
2549
+ }
2550
+ function isSystemJsCarrier(source) {
2551
+ const sysIdx = source.indexOf("System.register(");
2552
+ if (sysIdx < 0) return false;
2553
+ const defIdx = source.indexOf("define(");
2554
+ if (defIdx < 0) return true;
2555
+ return sysIdx < defIdx;
2556
+ }
2557
+ function isSelfBootstrappingEntry(source, _entry) {
2558
+ const tail = source.trimEnd();
2559
+ const tailSlice = tail.slice(Math.max(0, tail.length - 128));
2560
+ const m = tailSlice.match(/require\(\s*(["'])([^"']+)\1\s*\)\s*;?\s*$/);
2561
+ if (!m) return false;
2562
+ const bootId = m[2];
2563
+ const defSig1 = `define("${bootId}"`;
2564
+ const defSig2 = `define('${bootId}'`;
2565
+ return source.indexOf(defSig1) >= 0 || source.indexOf(defSig2) >= 0;
2566
+ }
2567
+ var SKIP_DIRS = /* @__PURE__ */ new Set([
2568
+ "node_modules",
2569
+ ".git",
2570
+ ".svn",
2571
+ ".hg",
2572
+ ".idea",
2573
+ ".vscode"
2574
+ ]);
2575
+ function walkFiles(absDir, relDirFromPkgRoot, excludeRoots, out) {
2576
+ let entries;
2577
+ try {
2578
+ entries = fs2.readdirSync(absDir, { withFileTypes: true });
2579
+ } catch {
2580
+ return;
2581
+ }
2582
+ for (const entry of entries) {
2583
+ if (entry.name.startsWith(".")) continue;
2584
+ if (SKIP_DIRS.has(entry.name)) continue;
2585
+ const nextRel = relDirFromPkgRoot ? `${relDirFromPkgRoot}/${entry.name}` : entry.name;
2586
+ if (excludeRoots.has(nextRel)) continue;
2587
+ const childAbs = path2.join(absDir, entry.name);
2588
+ if (entry.isDirectory()) {
2589
+ walkFiles(childAbs, nextRel, excludeRoots, out);
2590
+ } else if (entry.isFile()) {
2591
+ out.push(nextRel);
2592
+ }
2593
+ }
2594
+ }
2595
+ function wrapAsDefine(modulePathInPkg, body) {
2596
+ const key = JSON.stringify(modulePathInPkg);
2597
+ return `define(${key}, function(require, module, exports) {
2598
+ ${body}
2599
+ });
2600
+ `;
2601
+ }
2602
+ function copyFile(srcAbs, dstAbs) {
2603
+ fs2.mkdirSync(path2.dirname(dstAbs), { recursive: true });
2604
+ fs2.copyFileSync(srcAbs, dstAbs);
2605
+ }
2606
+ function transformJs(src, relPath, diagnostics, pkgName, log) {
2607
+ const transform = getEnhanceTransform();
2608
+ let result;
2609
+ try {
2610
+ result = silenceBabelDeopt(
2611
+ () => transform({
2612
+ code: src,
2613
+ filePath: relPath,
2614
+ babelRoot: BABEL_RUNTIME_ROOT
2615
+ })
2616
+ );
2617
+ } catch (e) {
2618
+ const msg = e instanceof Error ? e.message : String(e);
2619
+ diagnostics.push({ pkg: pkgName, file: relPath, level: "warn", message: `Babel threw: ${msg} \u2014 trying esbuild fallback` });
2620
+ log("warn", `[packager] (${pkgName || "main"}) Babel threw on "${relPath}": ${msg} \u2014 trying esbuild fallback`);
2621
+ return esbuildFallbackTransform(src, relPath, diagnostics, pkgName, log);
2622
+ }
2623
+ if (result.error) {
2624
+ diagnostics.push({
2625
+ pkg: pkgName,
2626
+ file: relPath,
2627
+ level: "warn",
2628
+ message: `Babel transpile error: ${result.error.message} \u2014 trying esbuild fallback`
2629
+ });
2630
+ log("warn", `[packager] (${pkgName || "main"}) Babel error in "${relPath}": ${result.error.message} \u2014 trying esbuild fallback`);
2631
+ return esbuildFallbackTransform(src, relPath, diagnostics, pkgName, log);
2632
+ }
2633
+ const code = result.code ?? src;
2634
+ const helpers = result.helpers ?? [];
2635
+ for (const h of extractBabelRuntimeRequires(code)) {
2636
+ if (!helpers.includes(h)) helpers.push(h);
2637
+ }
2638
+ return { code, helpers };
2639
+ }
2640
+ function esbuildFallbackTransform(src, relPath, diagnostics, pkgName, log) {
2641
+ try {
2642
+ const esb = getEsbuild();
2643
+ const result = esb.transformSync(src, {
2644
+ loader: "js",
2645
+ // Target ES2015 to ensure compatibility with `new Function()` + `with()` in sandboxExec.
2646
+ // ES2015 removes most syntax that causes issues (optional chaining, nullish coalescing, etc.)
2647
+ // while still being broadly parseable.
2648
+ target: "es2015",
2649
+ format: "cjs",
2650
+ sourcefile: relPath,
2651
+ // Avoid injecting "use strict" which conflicts with `with()` statement
2652
+ banner: "/* esbuild-fallback */"
2653
+ });
2654
+ log("log", `[packager] (${pkgName || "main"}) esbuild fallback succeeded for "${relPath}"`);
2655
+ const code = result.code.replace(/^\s*"use strict";\s*\n?/m, "");
2656
+ return { code, helpers: [] };
2657
+ } catch (e) {
2658
+ const msg = e instanceof Error ? e.message : String(e);
2659
+ diagnostics.push({
2660
+ pkg: pkgName,
2661
+ file: relPath,
2662
+ level: "error",
2663
+ message: `esbuild fallback also failed: ${msg} \u2014 using source as-is (may cause SyntaxError at runtime)`
2664
+ });
2665
+ log("error", `[packager] (${pkgName || "main"}) esbuild fallback failed for "${relPath}": ${msg} \u2014 using source as-is`);
2666
+ return { code: src, helpers: [] };
2667
+ }
2668
+ }
2669
+ function materialiseHelpers(initial, diagnostics, pkgName) {
2670
+ const all = /* @__PURE__ */ new Set();
2671
+ const queue = [];
2672
+ for (const h of initial) {
2673
+ const norm = h.endsWith(".js") ? h.replace(/\.js$/, "") : h;
2674
+ if (!all.has(norm)) {
2675
+ all.add(norm);
2676
+ queue.push(norm);
2677
+ }
2678
+ }
2679
+ while (queue.length > 0) {
2680
+ const h = queue.shift();
2681
+ let src;
2682
+ try {
2683
+ src = readBabelHelper(h);
2684
+ } catch {
2685
+ diagnostics.push({ pkg: pkgName, file: h, level: "warn", message: `Helper not found in miniprogram-ci vendor: ${h}` });
2686
+ continue;
2687
+ }
2688
+ for (const dep of extractHelperDependencies(h, src)) {
2689
+ const norm = dep.endsWith(".js") ? dep.replace(/\.js$/, "") : dep;
2690
+ if (!all.has(norm)) {
2691
+ all.add(norm);
2692
+ queue.push(norm);
2693
+ }
2694
+ }
2695
+ }
2696
+ const out = [];
2697
+ for (const h of all) {
2698
+ try {
2699
+ const src = readBabelHelper(h);
2700
+ out.push({ modulePathInPkg: h + ".js", source: src });
2701
+ } catch {
2702
+ }
2703
+ }
2704
+ return out;
2705
+ }
2706
+ function packOnePackage(gameDir, outRoot, spec, excludeRoots, diagnostics, log) {
2707
+ const pkgAbsSrc = spec.root ? path2.join(gameDir, spec.root) : gameDir;
2708
+ const pkgAbsDst = spec.root ? path2.join(outRoot, spec.root) : outRoot;
2709
+ if (!fs2.existsSync(pkgAbsSrc)) {
2710
+ log("warn", `[packager] Package "${spec.name || "main"}" root does not exist: ${pkgAbsSrc}`);
2711
+ return { name: spec.name, root: spec.root, entry: spec.entry, modules: 0, assets: 0, helpers: 0, scripts: 0 };
2712
+ }
2713
+ fs2.mkdirSync(pkgAbsDst, { recursive: true });
2714
+ const files = [];
2715
+ walkFiles(pkgAbsSrc, "", excludeRoots, files);
2716
+ const jsFiles = [];
2717
+ let assetCount = 0;
2718
+ for (const rel of files) {
2719
+ if (/\.(?:js|mjs|cjs)$/.test(rel)) {
2720
+ jsFiles.push(rel);
2721
+ } else {
2722
+ const srcAbs = path2.join(pkgAbsSrc, rel);
2723
+ const dstAbs = path2.join(pkgAbsDst, rel);
2724
+ copyFile(srcAbs, dstAbs);
2725
+ assetCount++;
2726
+ }
2727
+ }
2728
+ const entryAbsSrc = path2.join(pkgAbsSrc, spec.entry);
2729
+ let entryPassthrough = false;
2730
+ if (fs2.existsSync(entryAbsSrc)) {
2731
+ const entrySrc = fs2.readFileSync(entryAbsSrc, "utf-8");
2732
+ if (isSelfBootstrappingEntry(entrySrc, spec.entry)) {
2733
+ entryPassthrough = true;
2734
+ const entryAbsDst = path2.join(pkgAbsDst, spec.entry);
2735
+ fs2.mkdirSync(path2.dirname(entryAbsDst), { recursive: true });
2736
+ fs2.writeFileSync(entryAbsDst, entrySrc, "utf-8");
2737
+ log(
2738
+ "log",
2739
+ `[packager] (${spec.name || "main"}) entry "${spec.entry}" is a self-bootstrapping CI bundle \u2014 copied verbatim, no re-wrapping.`
2740
+ );
2741
+ }
2742
+ }
2743
+ const collectedHelpers = /* @__PURE__ */ new Set();
2744
+ const moduleChunks = [];
2745
+ let scriptCount = 0;
2746
+ let moduleCount = 0;
2747
+ for (const rel of jsFiles) {
2748
+ const srcAbs = path2.join(pkgAbsSrc, rel);
2749
+ const src = fs2.readFileSync(srcAbs, "utf-8");
2750
+ const isEntryFile = rel === spec.entry;
2751
+ if (isEntryFile && entryPassthrough) continue;
2752
+ if (!isEntryFile && isSystemJsCarrier(src)) {
2753
+ const dstAbs = path2.join(pkgAbsDst, rel);
2754
+ copyFile(srcAbs, dstAbs);
2755
+ scriptCount++;
2756
+ for (const h of extractBabelRuntimeRequires(src)) collectedHelpers.add(h);
2757
+ continue;
2758
+ }
2759
+ const first = rel.split("/")[0];
2760
+ const alreadyCompiled = first === "@babel" || first === "babel_runtime";
2761
+ if (alreadyCompiled) {
2762
+ moduleChunks.push(wrapAsDefine(rel, src));
2763
+ moduleCount++;
2764
+ for (const h of extractBabelRuntimeRequires(src)) collectedHelpers.add(h);
2765
+ continue;
2766
+ }
2767
+ const { code, helpers } = transformJs(src, rel, diagnostics, spec.name, log);
2768
+ for (const h of helpers) collectedHelpers.add(h);
2769
+ moduleChunks.push(wrapAsDefine(rel, code));
2770
+ moduleCount++;
2771
+ }
2772
+ const helperEntries = materialiseHelpers(collectedHelpers, diagnostics, spec.name);
2773
+ for (const h of helperEntries) {
2774
+ moduleChunks.push(wrapAsDefine(h.modulePathInPkg, h.source));
2775
+ }
2776
+ if (!entryPassthrough) {
2777
+ const banner = `// Packaged by ai-minigame-engine (${spec.name || "main"} package) \u2014 ${moduleCount} bundled module(s), ${scriptCount} standalone script(s), ${helperEntries.length} helper(s)
2778
+ `;
2779
+ const footer = `require(${JSON.stringify(spec.entry)});
2780
+ `;
2781
+ const payload = banner + moduleChunks.join("") + footer;
2782
+ const entryAbsDst = path2.join(pkgAbsDst, spec.entry);
2783
+ fs2.mkdirSync(path2.dirname(entryAbsDst), { recursive: true });
2784
+ fs2.writeFileSync(entryAbsDst, payload, "utf-8");
2785
+ } else if (moduleChunks.length > 0 || helperEntries.length > 0) {
2786
+ log(
2787
+ "warn",
2788
+ `[packager] (${spec.name || "main"}) entry is self-bootstrapping but found ${moduleCount} extra module(s) and ${helperEntries.length} helper(s) that will be ignored. Remove them from the package or remove the trailing require("${spec.entry}") from the entry file.`
2789
+ );
2790
+ }
2791
+ log(
2792
+ "log",
2793
+ `[packager] (${spec.name || "main"}) ` + (entryPassthrough ? `entry passthrough (${assetCount} assets)` : `${moduleCount} bundled, ${scriptCount} standalone, ${helperEntries.length} helpers, ${assetCount} assets`)
2794
+ );
2795
+ return {
2796
+ name: spec.name,
2797
+ root: spec.root,
2798
+ entry: spec.entry,
2799
+ modules: moduleCount,
2800
+ assets: assetCount,
2801
+ helpers: helperEntries.length,
2802
+ scripts: scriptCount
2803
+ };
2804
+ }
2805
+ function packageGameToDir(gameDir, outputDir, logger) {
2806
+ const start = Date.now();
2807
+ const log = logger ?? ((level, msg) => {
2808
+ if (level === "error") console.error(msg);
2809
+ else if (level === "warn") console.warn(msg);
2810
+ else console.log(msg);
2811
+ });
2812
+ log("log", `[packager] Packaging ${gameDir} \u2192 ${outputDir}`);
2813
+ if (!fs2.existsSync(path2.join(gameDir, "game.js"))) {
2814
+ throw new Error(`[packager] Entry file not found: ${path2.join(gameDir, "game.js")}`);
2815
+ }
2816
+ fs2.rmSync(outputDir, { recursive: true, force: true });
2817
+ fs2.mkdirSync(outputDir, { recursive: true });
2818
+ for (const name of ["game.json", "project.config.json", "project.private.config.json", "app-config.json"]) {
2819
+ const src = path2.join(gameDir, name);
2820
+ if (fs2.existsSync(src)) {
2821
+ copyFile(src, path2.join(outputDir, name));
2822
+ }
2823
+ }
2824
+ const packages = discoverPackages(gameDir);
2825
+ const mainExcludeRoots = new Set(
2826
+ packages.filter((p) => p.root !== "").map((p) => p.root)
2827
+ );
2828
+ const diagnostics = [];
2829
+ const results = [];
2830
+ for (const spec of packages) {
2831
+ const excludeRoots = spec.root === "" ? mainExcludeRoots : /* @__PURE__ */ new Set();
2832
+ try {
2833
+ results.push(packOnePackage(gameDir, outputDir, spec, excludeRoots, diagnostics, log));
2834
+ } catch (e) {
2835
+ const msg = e instanceof Error ? e.message : String(e);
2836
+ log("error", `[packager] Package "${spec.name || "main"}" failed: ${msg}`);
2837
+ diagnostics.push({ pkg: spec.name, file: "<package>", level: "error", message: msg });
2838
+ throw e;
2839
+ }
2840
+ }
2841
+ const elapsed = Date.now() - start;
2842
+ const modulesSum = results.reduce((a, r) => a + r.modules, 0);
2843
+ const assetsSum = results.reduce((a, r) => a + r.assets, 0);
2844
+ const helpersSum = results.reduce((a, r) => a + r.helpers, 0);
2845
+ const scriptsSum = results.reduce((a, r) => a + r.scripts, 0);
2846
+ log(
2847
+ "log",
2848
+ `[packager] Done in ${elapsed}ms \u2014 ${results.length} package(s), ${modulesSum} bundled module(s), ${scriptsSum} standalone script(s), ${assetsSum} asset(s), ${helpersSum} helper(s)`
2849
+ );
2850
+ return { packages: results, diagnostics, elapsed };
2851
+ }
2852
+
2853
+ // core/bundler/game-bundler-worker.ts
2854
+ if (!import_worker_threads.parentPort) {
2855
+ console.warn("[game-bundler-worker] Loaded outside a worker_threads context \u2014 doing nothing.");
2856
+ } else {
2857
+ const port = import_worker_threads.parentPort;
2858
+ port.on("message", (msg) => {
2859
+ if (!msg || msg.kind !== "run") return;
2860
+ const { id, gameDir, outputDir, ciDepsDir, ciExtensionDir } = msg;
2861
+ if (ciExtensionDir || ciDepsDir) {
2862
+ const installer = (init_ci_installer(), __toCommonJS(ci_installer_exports));
2863
+ if (ciExtensionDir) installer.setCiExtensionDir(ciExtensionDir);
2864
+ if (ciDepsDir) installer.setCiDepsDir(ciDepsDir);
2865
+ }
2866
+ const logger = (level, message) => {
2867
+ port.postMessage({ kind: "log", id, level, message });
2868
+ };
2869
+ try {
2870
+ const result = packageGameToDir(gameDir, outputDir, logger);
2871
+ port.postMessage({ kind: "done", id, result });
2872
+ } catch (err) {
2873
+ const message = err instanceof Error ? err.message : String(err);
2874
+ const stack = err instanceof Error ? err.stack : void 0;
2875
+ port.postMessage({ kind: "error", id, message, stack });
2876
+ }
2877
+ });
2878
+ }
2879
+ //# sourceMappingURL=game-bundler-worker.js.map