vercel 59.20.0 → 59.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{add-CC6U36WJ.js → add-JVSHQKWC.js} +1 -1
- package/dist/chunks/{add-PSEVULRF.js → add-UKFIETLE.js} +1 -1
- package/dist/chunks/{add-UO2IFTKH.js → add-Z3CJT63N.js} +1 -1
- package/dist/chunks/{build-G54Y245T.js → build-SMQYQX23.js} +1 -1
- package/dist/chunks/{chunk-NYEPIN3U.js → chunk-2HEC5TDU.js} +1 -1
- package/dist/chunks/{chunk-NUVOJI4D.js → chunk-2SLHYWMC.js} +1 -1
- package/dist/chunks/{chunk-6V3JGAVJ.js → chunk-32QBGZ2Z.js} +1 -1
- package/dist/chunks/{chunk-GWPIATTW.js → chunk-3GUBYJN6.js} +1 -1
- package/dist/chunks/{chunk-IERVS47L.js → chunk-4WSAOLBH.js} +1 -1
- package/dist/chunks/{chunk-YHN4IZVJ.js → chunk-4YVA7TSY.js} +2 -2
- package/dist/chunks/{chunk-WDO3QBQI.js → chunk-5YA32S6K.js} +1 -1
- package/dist/chunks/{chunk-6ARDCI6T.js → chunk-64NJHVA3.js} +4 -4
- package/dist/chunks/{chunk-X446JLEO.js → chunk-66RYR2GI.js} +1 -1
- package/dist/chunks/{chunk-DLKR2CG6.js → chunk-6BZCSVH6.js} +1 -1
- package/dist/chunks/{chunk-XNQR2W4A.js → chunk-6C7LA5RA.js} +1 -1
- package/dist/chunks/{chunk-U6TAKLJ6.js → chunk-6LE3FU2P.js} +1 -1
- package/dist/chunks/{chunk-IH2HZFLM.js → chunk-6LE44WCK.js} +1 -1
- package/dist/chunks/{chunk-RVJ2E3BM.js → chunk-6OI6SRHZ.js} +1 -1
- package/dist/chunks/{chunk-IESZKIFF.js → chunk-6SA6SOHU.js} +1 -1
- package/dist/chunks/{chunk-4Q2FGJAG.js → chunk-73G2MHUX.js} +1 -1
- package/dist/chunks/{chunk-PNRWNSM2.js → chunk-7B5NNJ2P.js} +1 -1
- package/dist/chunks/{chunk-W2XUH2WW.js → chunk-A5VLP25I.js} +1 -1
- package/dist/chunks/chunk-ABSRS5KC.js +9 -0
- package/dist/chunks/chunk-AZ6NRDHG.js +7 -0
- package/dist/chunks/{chunk-WR5OOWD6.js → chunk-BX5KDMLT.js} +1 -1
- package/dist/chunks/{chunk-NPMNS7IG.js → chunk-DL665Q3Z.js} +1 -1
- package/dist/chunks/{chunk-EGG7SPNM.js → chunk-DQ2KI6FO.js} +1 -1
- package/dist/chunks/{chunk-QFFD4LBE.js → chunk-E4X2DH4K.js} +1 -1
- package/dist/chunks/{chunk-HOD3FQAX.js → chunk-EHTHHCNG.js} +2 -0
- package/dist/chunks/{chunk-RTRCTYW6.js → chunk-EWWFNMPZ.js} +4 -3
- package/dist/chunks/{chunk-ZVFZIWBV.js → chunk-FA6O7FPC.js} +1 -1
- package/dist/chunks/chunk-FB5TMOLQ.js +7 -0
- package/dist/chunks/{chunk-3XIEKCNF.js → chunk-FZH7RIRX.js} +4 -4
- package/dist/chunks/{chunk-QPCDEH6H.js → chunk-GGNZLN4R.js} +1 -1
- package/dist/chunks/{chunk-E4CRGS56.js → chunk-GHULCYAR.js} +1 -1
- package/dist/chunks/{chunk-JDR2WXM4.js → chunk-GL2AUBAI.js} +1 -1
- package/dist/chunks/{chunk-YWFECCBH.js → chunk-GR3DLKYP.js} +1 -1
- package/dist/chunks/{chunk-HBF4YJR2.js → chunk-GRDPI246.js} +1 -1
- package/dist/chunks/{chunk-Q2Z6EXCT.js → chunk-GTJ2OLYI.js} +1 -1
- package/dist/chunks/{chunk-GUSSSCV7.js → chunk-HOYHUMBD.js} +1 -1
- package/dist/chunks/{chunk-7O3KGTQ3.js → chunk-HWWHR7H3.js} +1 -1
- package/dist/chunks/{chunk-5ZIZD5ZG.js → chunk-J5X5YRBH.js} +1 -1
- package/dist/chunks/{chunk-QQNFAXDX.js → chunk-JGPECEYY.js} +1 -1
- package/dist/chunks/{chunk-OXH3RM6U.js → chunk-KBKN7EI7.js} +1 -1
- package/dist/chunks/{chunk-JDQP267R.js → chunk-KUVMCIR4.js} +1 -1
- package/dist/chunks/{chunk-BQU3N4EK.js → chunk-KXYR43H5.js} +1 -1
- package/dist/chunks/{chunk-GI6G3FJJ.js → chunk-LKI6FRNM.js} +1 -1
- package/dist/chunks/{chunk-GGZODU6S.js → chunk-LQBC5QPO.js} +1 -1
- package/dist/chunks/{chunk-ONOSMF2T.js → chunk-M6A7UH4U.js} +1 -1
- package/dist/chunks/{chunk-DBBMJTPG.js → chunk-NYOQMU3P.js} +3 -3
- package/dist/chunks/{chunk-CFY5RS7I.js → chunk-NZKBBY2A.js} +1 -1
- package/dist/chunks/{chunk-UXTHEQVJ.js → chunk-OI263FBO.js} +1 -1
- package/dist/chunks/chunk-PS645CWM.js +32 -0
- package/dist/chunks/{chunk-J2ONOQCQ.js → chunk-QI3JSWD6.js} +1 -1
- package/dist/chunks/{chunk-7NYQ7CTP.js → chunk-R3B67TKQ.js} +1 -1
- package/dist/chunks/chunk-RRQTVE2P.js +31 -0
- package/dist/chunks/{chunk-74CMQMYR.js → chunk-SFTXBTMI.js} +1 -1
- package/dist/chunks/{chunk-PIKD5KTH.js → chunk-SOQ5DE44.js} +1 -1
- package/dist/chunks/{chunk-ZRS5X7M2.js → chunk-T4AZ3U7O.js} +1 -1
- package/dist/chunks/{chunk-4P66SQRS.js → chunk-TBBU37TD.js} +1 -1
- package/dist/chunks/{chunk-Q3LIZ6SZ.js → chunk-TJKM3345.js} +1 -1
- package/dist/chunks/{chunk-MNACJRE7.js → chunk-TOGR3HUB.js} +1 -1
- package/dist/chunks/{chunk-2Q47GHFX.js → chunk-U6N2RNDI.js} +1 -1
- package/dist/chunks/{chunk-KEFIUUAJ.js → chunk-UGXNE4YE.js} +1 -1
- package/dist/chunks/{chunk-TM3W2CAF.js → chunk-UUM2N6IG.js} +2 -2
- package/dist/chunks/{chunk-LKVMIJCF.js → chunk-UWZ5VIIQ.js} +1 -1
- package/dist/chunks/{chunk-LZTGSYL3.js → chunk-UXCTETFN.js} +1 -1
- package/dist/chunks/{chunk-GTK7TBLW.js → chunk-V5DCSHYJ.js} +1 -1
- package/dist/chunks/{chunk-XV6SDZIO.js → chunk-V6IKQCOT.js} +1 -1
- package/dist/chunks/{chunk-NNP5NITU.js → chunk-V6MR45PD.js} +1 -1
- package/dist/chunks/{chunk-BW24TEUN.js → chunk-VIR3KDCQ.js} +1 -1
- package/dist/chunks/{chunk-QYPQGOSO.js → chunk-WDVSYGZS.js} +1 -1
- package/dist/chunks/{chunk-CWTXZPUV.js → chunk-WHYH7DVI.js} +2 -1
- package/dist/chunks/{chunk-TKBORMUF.js → chunk-WKZ6JSGZ.js} +1 -1
- package/dist/chunks/{chunk-DWSG55I2.js → chunk-X4X5RB2V.js} +1 -1
- package/dist/chunks/{chunk-EHEMFUGQ.js → chunk-YGJO25LP.js} +1 -1
- package/dist/chunks/{chunk-4VGOAPFY.js → chunk-YMM3VY3J.js} +1 -1
- package/dist/chunks/{chunk-TCS3FDID.js → chunk-Z4VR6CQ2.js} +1 -1
- package/dist/chunks/{chunk-CTO5XEIQ.js → chunk-Z6LKARXP.js} +1 -1
- package/dist/chunks/chunk-Z7PBDQNR.js +65 -0
- package/dist/chunks/{chunk-OWEH7BYO.js → chunk-ZDORSGCG.js} +1 -1
- package/dist/chunks/{chunk-XKNCIFFB.js → chunk-ZKWM4JBE.js} +1 -1
- package/dist/chunks/{clear-TJQM33RO.js → clear-6IXTTZO6.js} +1 -1
- package/dist/chunks/{compile-vercel-config-UQGJ4WJF.js → compile-vercel-config-ZFMPTU47.js} +1 -1
- package/dist/chunks/config-HLVJQKP7.js +7 -0
- package/dist/chunks/{config-SRY5IPK6.js → config-XXHMPW46.js} +1 -1
- package/dist/chunks/{connect-git-provider-LSTDI4TC.js → connect-git-provider-P3SGOW6X.js} +1 -1
- package/dist/chunks/{constants-NCE2LWSS.js → constants-G4UYVLOF.js} +1 -1
- package/dist/chunks/{delete-V45ALBXM.js → delete-52QKO73X.js} +1 -1
- package/dist/chunks/{delete-TSYNQ23W.js → delete-6VOUZDIR.js} +1 -1
- package/dist/chunks/{detect-projects-64MZJZ6M.js → detect-projects-WLAFT5HC.js} +1 -1
- package/dist/chunks/detect-services-YYT3LUUX.js +7 -0
- package/dist/chunks/{disable-WD4S6HSS.js → disable-7FGR2S56.js} +1 -1
- package/dist/chunks/{discard-KFBXLAVB.js → discard-XKPTY3DC.js} +1 -1
- package/dist/chunks/{edit-TJ4JLJRE.js → edit-A3HJCNPW.js} +1 -1
- package/dist/chunks/{edit-AWY54Q7X.js → edit-A7WGTO6K.js} +1 -1
- package/dist/chunks/{enable-ANIHAF35.js → enable-NGKLGHJ2.js} +1 -1
- package/dist/chunks/{exec-ZLT5KH2Z.js → exec-YH5WUJ4C.js} +1 -1
- package/dist/chunks/{export-RPFCJCOY.js → export-QCBAQNTT.js} +1 -1
- package/dist/chunks/{future-LU77KNDL.js → future-BB7OE645.js} +1 -1
- package/dist/chunks/{generate-cert-for-deploy-NVQ43MLT.js → generate-cert-for-deploy-U7JF3HF3.js} +1 -1
- package/dist/chunks/{image-WWX3Q3GG.js → image-DU7GJZR2.js} +1 -1
- package/dist/chunks/import-builders-IFZM44NL.js +7 -0
- package/dist/chunks/{inspect-WIXPYMMS.js → inspect-CPOFKE4X.js} +1 -1
- package/dist/chunks/{inspect-YG2GUQH2.js → inspect-EMWJLBAW.js} +1 -1
- package/dist/chunks/{inspect-7LLKIX3Q.js → inspect-IVJOEZC4.js} +1 -1
- package/dist/chunks/{inspect-QVPDZHUE.js → inspect-PHUMEO4A.js} +1 -1
- package/dist/chunks/{inspect-67J25RHR.js → inspect-Q7OVSWFO.js} +1 -1
- package/dist/chunks/{list-HKOHGU6B.js → list-G4JM2TYX.js} +1 -1
- package/dist/chunks/{list-UGNPHXFH.js → list-KYZNCXBM.js} +1 -1
- package/dist/chunks/{list-LY73G263.js → list-ZE2VPPXI.js} +1 -1
- package/dist/chunks/{login-IMHVC657.js → login-AVVJFLSC.js} +1 -1
- package/dist/chunks/{login-YQ7QPK4A.js → login-RMAISH4F.js} +1 -1
- package/dist/chunks/{logs-4GPA2QJ2.js → logs-3LTU2N25.js} +1 -1
- package/dist/chunks/{ls-GXGGGB3C.js → ls-4M2OBNG6.js} +1 -1
- package/dist/chunks/{ls-PSZDUCI4.js → ls-7O63WIES.js} +1 -1
- package/dist/chunks/{ls-XZYIM72L.js → ls-AKGRKWHM.js} +1 -1
- package/dist/chunks/{ls-IDH4SZXE.js → ls-DU5QTKKA.js} +1 -1
- package/dist/chunks/{ls-JAD3EACY.js → ls-HWUYP3XY.js} +1 -1
- package/dist/chunks/{ls-MO2Y6TNW.js → ls-P6LKMT33.js} +1 -1
- package/dist/chunks/{ls-XZ25NS63.js → ls-Y4QR3I6O.js} +1 -1
- package/dist/chunks/{mutate-FKH7JHLN.js → mutate-KOAALPIL.js} +1 -1
- package/dist/chunks/{notifications-JI6HIQYR.js → notifications-3RDFNJSD.js} +1 -1
- package/dist/chunks/{open-WVYJ6DJS.js → open-VD4F6MAO.js} +1 -1
- package/dist/chunks/{openapi-YEDROCHV.js → openapi-DKMCRF2V.js} +1 -1
- package/dist/chunks/{permissions-TALTFA2U.js → permissions-AE5JO26V.js} +1 -1
- package/dist/chunks/{prompt-missing-credentials-YVS4S7X2.js → prompt-missing-credentials-QY4MZDT6.js} +1 -1
- package/dist/chunks/{publish-ZE5GEK7Q.js → publish-YXVJXBQT.js} +1 -1
- package/dist/chunks/pull-QLC2CV4J.js +7 -0
- package/dist/chunks/{purchase-domain-if-available-6HLN6HG2.js → purchase-domain-if-available-74ZYVVBE.js} +1 -1
- package/dist/chunks/{push-ETAA3BQY.js → push-TMPPU5NU.js} +1 -1
- package/dist/chunks/{query-2FV3SCH5.js → query-PHAGR43V.js} +1 -1
- package/dist/chunks/{reauthenticate-APC7ZYFC.js → reauthenticate-O6C2AW3J.js} +1 -1
- package/dist/chunks/{reorder-GHLKIK3C.js → reorder-OAJ3NXQQ.js} +1 -1
- package/dist/chunks/{reply-2PEJJCP7.js → reply-Q3JFRFA3.js} +1 -1
- package/dist/chunks/{resolve-APTMIYGJ.js → resolve-XXJVOXNE.js} +1 -1
- package/dist/chunks/{restore-N6O2H27S.js → restore-MO4B2EQV.js} +1 -1
- package/dist/chunks/{rm-CWEDAZXF.js → rm-63LFH6NA.js} +1 -1
- package/dist/chunks/{rm-Y3PIBNO3.js → rm-F2XD2XKB.js} +1 -1
- package/dist/chunks/{rm-QJDB2QO6.js → rm-GMG2DZOV.js} +1 -1
- package/dist/chunks/{rm-ZWCGOTK3.js → rm-P6KA5RSP.js} +1 -1
- package/dist/chunks/{rm-ZUOJPP33.js → rm-SZ4HWA4R.js} +1 -1
- package/dist/chunks/{routes-ZD7XUKLY.js → routes-IPGKJ2E4.js} +1 -1
- package/dist/chunks/{rule-inspect-AHQRHKO3.js → rule-inspect-JKAXOBII.js} +1 -1
- package/dist/chunks/{rules-LFVEAZJ7.js → rules-6TZ6GSKT.js} +1 -1
- package/dist/chunks/{schema-ET4DYRVX.js → schema-5CZLK6NI.js} +1 -1
- package/dist/chunks/{schema-OKQUOZEH.js → schema-S2ZAREKF.js} +1 -1
- package/dist/chunks/{select-org-5OUQKTNI.js → select-org-F2A5JJFH.js} +1 -1
- package/dist/chunks/{set-OQCFBVJB.js → set-PIKLGKT6.js} +1 -1
- package/dist/chunks/setup-and-link-O5QSQ5K2.js +7 -0
- package/dist/chunks/{tags-23ZFVGUC.js → tags-C3HWJLJ4.js} +1 -1
- package/dist/chunks/{types-BTHJ46LC.js → types-H3B56MH6.js} +1 -1
- package/dist/chunks/{update-GUA544N4.js → update-5HE4X45O.js} +1 -1
- package/dist/chunks/{utils-BG3TNJBX.js → utils-5BFO5HC4.js} +1 -1
- package/dist/commands/build/index.js +1 -1
- package/dist/commands/deploy/index.js +7 -7
- package/dist/commands/dev/index.js +20 -19
- package/dist/commands/env/index.js +1 -1
- package/dist/commands/link/index.js +2 -2
- package/dist/commands/list/index.js +1 -1
- package/dist/commands-bulk.js +698 -699
- package/dist/help.js +1 -1
- package/dist/index.js +3 -3
- package/dist/version.mjs +1 -1
- package/package.json +25 -24
- package/dist/chunks/chunk-DB2P55YY.js +0 -9
- package/dist/chunks/chunk-JEIMW3CO.js +0 -7
- package/dist/chunks/chunk-K2RAW5DI.js +0 -10
- package/dist/chunks/chunk-LASMHNUP.js +0 -62
- package/dist/chunks/chunk-XQWBEAKZ.js +0 -9
- package/dist/chunks/chunk-XZYKYDQO.js +0 -7
- package/dist/chunks/config-XEI4UIQD.js +0 -7
- package/dist/chunks/detect-services-3DFPW53F.js +0 -7
- package/dist/chunks/import-builders-FUR24WH3.js +0 -7
- package/dist/chunks/pull-33THLIV4.js +0 -7
- package/dist/chunks/setup-and-link-YCM7WRCA.js +0 -7
|
@@ -18,4 +18,4 @@ import{__esm}from"./chunk-6L236MNA.js";function createScanner(text,ignoreTrivia=
|
|
|
18
18
|
`)return`
|
|
19
19
|
`}return options&&options.eol||`
|
|
20
20
|
`}function isEOL(text,offset){return`\r
|
|
21
|
-
`.indexOf(text.charAt(offset))!==-1}var init_format=__esm({"../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/format.js"(){"use strict";init_scanner();init_string_intern()}});function parse(text,errors=[],options=ParseOptions.DEFAULT){let currentProperty=null,currentParent=[],previousParents=[];function onValue(value){Array.isArray(currentParent)?currentParent.push(value):currentProperty!==null&&(currentParent[currentProperty]=value)}return visit(text,{onObjectBegin:()=>{let object={};onValue(object),previousParents.push(currentParent),currentParent=object,currentProperty=null},onObjectProperty:name=>{currentProperty=name},onObjectEnd:()=>{currentParent=previousParents.pop()},onArrayBegin:()=>{let array=[];onValue(array),previousParents.push(currentParent),currentParent=array,currentProperty=null},onArrayEnd:()=>{currentParent=previousParents.pop()},onLiteralValue:onValue,onError:(error,offset,length)=>{errors.push({error,offset,length})}},options),currentParent[0]}function parseTree(text,errors=[],options=ParseOptions.DEFAULT){let currentParent={type:"array",offset:-1,length:-1,children:[],parent:void 0};function ensurePropertyComplete(endOffset){currentParent.type==="property"&&(currentParent.length=endOffset-currentParent.offset,currentParent=currentParent.parent)}function onValue(valueNode){return currentParent.children.push(valueNode),valueNode}visit(text,{onObjectBegin:offset=>{currentParent=onValue({type:"object",offset,length:-1,parent:currentParent,children:[]})},onObjectProperty:(name,offset,length)=>{currentParent=onValue({type:"property",offset,length:-1,parent:currentParent,children:[]}),currentParent.children.push({type:"string",value:name,offset,length,parent:currentParent})},onObjectEnd:(offset,length)=>{ensurePropertyComplete(offset+length),currentParent.length=offset+length-currentParent.offset,currentParent=currentParent.parent,ensurePropertyComplete(offset+length)},onArrayBegin:(offset,length)=>{currentParent=onValue({type:"array",offset,length:-1,parent:currentParent,children:[]})},onArrayEnd:(offset,length)=>{currentParent.length=offset+length-currentParent.offset,currentParent=currentParent.parent,ensurePropertyComplete(offset+length)},onLiteralValue:(value,offset,length)=>{onValue({type:getNodeType(value),offset,length,parent:currentParent,value}),ensurePropertyComplete(offset+length)},onSeparator:(sep,offset,length)=>{currentParent.type==="property"&&(sep===":"?currentParent.colonOffset=offset:sep===","&&ensurePropertyComplete(offset))},onError:(error,offset,length)=>{errors.push({error,offset,length})}},options);let result=currentParent.children[0];return result&&delete result.parent,result}function findNodeAtLocation(root,path){if(!root)return;let node=root;for(let segment of path)if(typeof segment=="string"){if(node.type!=="object"||!Array.isArray(node.children))return;let found=!1;for(let propertyNode of node.children)if(Array.isArray(propertyNode.children)&&propertyNode.children[0].value===segment&&propertyNode.children.length===2){node=propertyNode.children[1],found=!0;break}if(!found)return}else{let index=segment;if(node.type!=="array"||index<0||!Array.isArray(node.children)||index>=node.children.length)return;node=node.children[index]}return node}function visit(text,visitor,options=ParseOptions.DEFAULT){let _scanner=createScanner(text,!1),_jsonPath=[],suppressedCallbacks=0;function toNoArgVisit(visitFunction){return visitFunction?()=>suppressedCallbacks===0&&visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>!0}function toOneArgVisit(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>!0}function toOneArgVisitWithPath(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice()):()=>!0}function toBeginVisit(visitFunction){return visitFunction?()=>{suppressedCallbacks>0?suppressedCallbacks++:visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice())===!1&&(suppressedCallbacks=1)}:()=>!0}function toEndVisit(visitFunction){return visitFunction?()=>{suppressedCallbacks>0&&suppressedCallbacks--,suppressedCallbacks===0&&visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter())}:()=>!0}let onObjectBegin=toBeginVisit(visitor.onObjectBegin),onObjectProperty=toOneArgVisitWithPath(visitor.onObjectProperty),onObjectEnd=toEndVisit(visitor.onObjectEnd),onArrayBegin=toBeginVisit(visitor.onArrayBegin),onArrayEnd=toEndVisit(visitor.onArrayEnd),onLiteralValue=toOneArgVisitWithPath(visitor.onLiteralValue),onSeparator=toOneArgVisit(visitor.onSeparator),onComment=toNoArgVisit(visitor.onComment),onError=toOneArgVisit(visitor.onError),disallowComments=options&&options.disallowComments,allowTrailingComma=options&&options.allowTrailingComma;function scanNext(){for(;;){let token=_scanner.scan();switch(_scanner.getTokenError()){case 4:handleError(14);break;case 5:handleError(15);break;case 3:handleError(13);break;case 1:disallowComments||handleError(11);break;case 2:handleError(12);break;case 6:handleError(16);break}switch(token){case 12:case 13:disallowComments?handleError(10):onComment();break;case 16:handleError(1);break;case 15:case 14:break;default:return token}}}function handleError(error,skipUntilAfter=[],skipUntil=[]){if(onError(error),skipUntilAfter.length+skipUntil.length>0){let token=_scanner.getToken();for(;token!==17;){if(skipUntilAfter.indexOf(token)!==-1){scanNext();break}else if(skipUntil.indexOf(token)!==-1)break;token=scanNext()}}}function parseString(isValue){let value=_scanner.getTokenValue();return isValue?onLiteralValue(value):(onObjectProperty(value),_jsonPath.push(value)),scanNext(),!0}function parseLiteral(){switch(_scanner.getToken()){case 11:let tokenValue=_scanner.getTokenValue(),value=Number(tokenValue);isNaN(value)&&(handleError(2),value=0),onLiteralValue(value);break;case 7:onLiteralValue(null);break;case 8:onLiteralValue(!0);break;case 9:onLiteralValue(!1);break;default:return!1}return scanNext(),!0}function parseProperty(){return _scanner.getToken()!==10?(handleError(3,[],[2,5]),!1):(parseString(!1),_scanner.getToken()===6?(onSeparator(":"),scanNext(),parseValue()||handleError(4,[],[2,5])):handleError(5,[],[2,5]),_jsonPath.pop(),!0)}function parseObject(){onObjectBegin(),scanNext();let needsComma=!1;for(;_scanner.getToken()!==2&&_scanner.getToken()!==17;){if(_scanner.getToken()===5){if(needsComma||handleError(4,[],[]),onSeparator(","),scanNext(),_scanner.getToken()===2&&allowTrailingComma)break}else needsComma&&handleError(6,[],[]);parseProperty()||handleError(4,[],[2,5]),needsComma=!0}return onObjectEnd(),_scanner.getToken()!==2?handleError(7,[2],[]):scanNext(),!0}function parseArray(){onArrayBegin(),scanNext();let isFirstElement=!0,needsComma=!1;for(;_scanner.getToken()!==4&&_scanner.getToken()!==17;){if(_scanner.getToken()===5){if(needsComma||handleError(4,[],[]),onSeparator(","),scanNext(),_scanner.getToken()===4&&allowTrailingComma)break}else needsComma&&handleError(6,[],[]);isFirstElement?(_jsonPath.push(0),isFirstElement=!1):_jsonPath[_jsonPath.length-1]++,parseValue()||handleError(4,[],[4,5]),needsComma=!0}return onArrayEnd(),isFirstElement||_jsonPath.pop(),_scanner.getToken()!==4?handleError(8,[4],[]):scanNext(),!0}function parseValue(){switch(_scanner.getToken()){case 3:return parseArray();case 1:return parseObject();case 10:return parseString(!0);default:return parseLiteral()}}return scanNext(),_scanner.getToken()===17?options.allowEmptyContent?!0:(handleError(4,[],[]),!1):parseValue()?(_scanner.getToken()!==17&&handleError(9,[],[]),!0):(handleError(4,[],[]),!1)}function getNodeType(value){switch(typeof value){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(value){if(Array.isArray(value))return"array"}else return"null";return"object"}default:return"null"}}var ParseOptions,init_parser=__esm({"../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/parser.js"(){"use strict";init_scanner();(function(ParseOptions2){ParseOptions2.DEFAULT={allowTrailingComma:!1}})(ParseOptions||(ParseOptions={}))}});function setProperty(text,originalPath,value,options){let path=originalPath.slice(),root=parseTree(text,[]),parent,lastSegment;for(;path.length>0&&(lastSegment=path.pop(),parent=findNodeAtLocation(root,path),parent===void 0&&value!==void 0);)typeof lastSegment=="string"?value={[lastSegment]:value}:value=[value];if(parent)if(parent.type==="object"&&typeof lastSegment=="string"&&Array.isArray(parent.children)){let existing=findNodeAtLocation(parent,[lastSegment]);if(existing!==void 0)if(value===void 0){if(!existing.parent)throw new Error("Malformed AST");let propertyIndex=parent.children.indexOf(existing.parent),removeBegin,removeEnd=existing.parent.offset+existing.parent.length;if(propertyIndex>0){let previous=parent.children[propertyIndex-1];removeBegin=previous.offset+previous.length}else removeBegin=parent.offset+1,parent.children.length>1&&(removeEnd=parent.children[1].offset);return withFormatting(text,{offset:removeBegin,length:removeEnd-removeBegin,content:""},options)}else return withFormatting(text,{offset:existing.offset,length:existing.length,content:JSON.stringify(value)},options);else{if(value===void 0)return[];let newProperty=`${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`,index=options.getInsertionIndex?options.getInsertionIndex(parent.children.map(p=>p.children[0].value)):parent.children.length,edit;if(index>0){let previous=parent.children[index-1];edit={offset:previous.offset+previous.length,length:0,content:","+newProperty}}else parent.children.length===0?edit={offset:parent.offset+1,length:0,content:newProperty}:edit={offset:parent.offset+1,length:0,content:newProperty+","};return withFormatting(text,edit,options)}}else if(parent.type==="array"&&typeof lastSegment=="number"&&Array.isArray(parent.children)){let insertIndex=lastSegment;if(insertIndex===-1){let newProperty=`${JSON.stringify(value)}`,edit;if(parent.children.length===0)edit={offset:parent.offset+1,length:0,content:newProperty};else{let previous=parent.children[parent.children.length-1];edit={offset:previous.offset+previous.length,length:0,content:","+newProperty}}return withFormatting(text,edit,options)}else if(value===void 0&&parent.children.length>=0){let removalIndex=lastSegment,toRemove=parent.children[removalIndex],edit;if(parent.children.length===1)edit={offset:parent.offset+1,length:parent.length-2,content:""};else if(parent.children.length-1===removalIndex){let previous=parent.children[removalIndex-1],offset=previous.offset+previous.length,parentEndOffset=parent.offset+parent.length;edit={offset,length:parentEndOffset-2-offset,content:""}}else edit={offset:toRemove.offset,length:parent.children[removalIndex+1].offset-toRemove.offset,content:""};return withFormatting(text,edit,options)}else if(value!==void 0){let edit,newProperty=`${JSON.stringify(value)}`;if(!options.isArrayInsertion&&parent.children.length>lastSegment){let toModify=parent.children[lastSegment];edit={offset:toModify.offset,length:toModify.length,content:newProperty}}else if(parent.children.length===0||lastSegment===0)edit={offset:parent.offset+1,length:0,content:parent.children.length===0?newProperty:newProperty+","};else{let index=lastSegment>parent.children.length?parent.children.length:lastSegment,previous=parent.children[index-1];edit={offset:previous.offset+previous.length,length:0,content:","+newProperty}}return withFormatting(text,edit,options)}else throw new Error(`Can not ${value===void 0?"remove":options.isArrayInsertion?"insert":"modify"} Array index ${insertIndex} as length is not sufficient`)}else throw new Error(`Can not add ${typeof lastSegment!="number"?"index":"property"} to parent of type ${parent.type}`);else{if(value===void 0)throw new Error("Can not delete in empty document");return withFormatting(text,{offset:root?root.offset:0,length:root?root.length:0,content:JSON.stringify(value)},options)}}function withFormatting(text,edit,options){if(!options.formattingOptions)return[edit];let newText=applyEdit(text,edit),begin=edit.offset,end=edit.offset+edit.content.length;if(edit.length===0||edit.content.length===0){for(;begin>0&&!isEOL(newText,begin-1);)begin--;for(;end<newText.length&&!isEOL(newText,end);)end++}let edits=format(newText,{offset:begin,length:end-begin},{...options.formattingOptions,keepLines:!1});for(let i=edits.length-1;i>=0;i--){let edit2=edits[i];newText=applyEdit(newText,edit2),begin=Math.min(begin,edit2.offset),end=Math.max(end,edit2.offset+edit2.length),end+=edit2.content.length-edit2.length}let editLength=text.length-(newText.length-end)-begin;return[{offset:begin,length:editLength,content:newText.substring(begin,end)}]}function applyEdit(text,edit){return text.substring(0,edit.offset)+edit.content+text.substring(edit.offset+edit.length)}var init_edit=__esm({"../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/edit.js"(){"use strict";init_format();init_parser()}});function printParseErrorCode(code){switch(code){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}function modify(text,path,value,options){return setProperty(text,path,value,options)}function applyEdits(text,edits){let sortedEdits=edits.slice(0).sort((a,b)=>{let diff=a.offset-b.offset;return diff===0?a.length-b.length:diff}),lastModifiedOffset=text.length;for(let i=sortedEdits.length-1;i>=0;i--){let e=sortedEdits[i];if(e.offset+e.length<=lastModifiedOffset)text=applyEdit(text,e);else throw new Error("Overlapping edit");lastModifiedOffset=e.offset}return text}var ScanError,SyntaxKind,parse2,ParseErrorCode,init_main=__esm({"../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js"(){"use strict";init_format();init_edit();init_scanner();init_parser();(function(ScanError2){ScanError2[ScanError2.None=0]="None",ScanError2[ScanError2.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",ScanError2[ScanError2.UnexpectedEndOfString=2]="UnexpectedEndOfString",ScanError2[ScanError2.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",ScanError2[ScanError2.InvalidUnicode=4]="InvalidUnicode",ScanError2[ScanError2.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",ScanError2[ScanError2.InvalidCharacter=6]="InvalidCharacter"})(ScanError||(ScanError={}));(function(SyntaxKind2){SyntaxKind2[SyntaxKind2.OpenBraceToken=1]="OpenBraceToken",SyntaxKind2[SyntaxKind2.CloseBraceToken=2]="CloseBraceToken",SyntaxKind2[SyntaxKind2.OpenBracketToken=3]="OpenBracketToken",SyntaxKind2[SyntaxKind2.CloseBracketToken=4]="CloseBracketToken",SyntaxKind2[SyntaxKind2.CommaToken=5]="CommaToken",SyntaxKind2[SyntaxKind2.ColonToken=6]="ColonToken",SyntaxKind2[SyntaxKind2.NullKeyword=7]="NullKeyword",SyntaxKind2[SyntaxKind2.TrueKeyword=8]="TrueKeyword",SyntaxKind2[SyntaxKind2.FalseKeyword=9]="FalseKeyword",SyntaxKind2[SyntaxKind2.StringLiteral=10]="StringLiteral",SyntaxKind2[SyntaxKind2.NumericLiteral=11]="NumericLiteral",SyntaxKind2[SyntaxKind2.LineCommentTrivia=12]="LineCommentTrivia",SyntaxKind2[SyntaxKind2.BlockCommentTrivia=13]="BlockCommentTrivia",SyntaxKind2[SyntaxKind2.LineBreakTrivia=14]="LineBreakTrivia",SyntaxKind2[SyntaxKind2.Trivia=15]="Trivia",SyntaxKind2[SyntaxKind2.Unknown=16]="Unknown",SyntaxKind2[SyntaxKind2.EOF=17]="EOF"})(SyntaxKind||(SyntaxKind={}));parse2=parse;(function(ParseErrorCode2){ParseErrorCode2[ParseErrorCode2.InvalidSymbol=1]="InvalidSymbol",ParseErrorCode2[ParseErrorCode2.InvalidNumberFormat=2]="InvalidNumberFormat",ParseErrorCode2[ParseErrorCode2.PropertyNameExpected=3]="PropertyNameExpected",ParseErrorCode2[ParseErrorCode2.ValueExpected=4]="ValueExpected",ParseErrorCode2[ParseErrorCode2.ColonExpected=5]="ColonExpected",ParseErrorCode2[ParseErrorCode2.CommaExpected=6]="CommaExpected",ParseErrorCode2[ParseErrorCode2.CloseBraceExpected=7]="CloseBraceExpected",ParseErrorCode2[ParseErrorCode2.CloseBracketExpected=8]="CloseBracketExpected",ParseErrorCode2[ParseErrorCode2.EndOfFileExpected=9]="EndOfFileExpected",ParseErrorCode2[ParseErrorCode2.InvalidCommentToken=10]="InvalidCommentToken",ParseErrorCode2[ParseErrorCode2.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",ParseErrorCode2[ParseErrorCode2.UnexpectedEndOfString=12]="UnexpectedEndOfString",ParseErrorCode2[ParseErrorCode2.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",ParseErrorCode2[ParseErrorCode2.InvalidUnicode=14]="InvalidUnicode",ParseErrorCode2[ParseErrorCode2.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",ParseErrorCode2[ParseErrorCode2.InvalidCharacter=16]="InvalidCharacter"})(ParseErrorCode||(ParseErrorCode={}))}});export{parse2 as parse,printParseErrorCode,modify,applyEdits,init_main};
|
|
21
|
+
`.indexOf(text.charAt(offset))!==-1}var init_format=__esm({"../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/format.js"(){"use strict";init_scanner();init_string_intern()}});function parse(text,errors=[],options=ParseOptions.DEFAULT){let currentProperty=null,currentParent=[],previousParents=[];function onValue(value){Array.isArray(currentParent)?currentParent.push(value):currentProperty!==null&&(currentParent[currentProperty]=value)}return visit(text,{onObjectBegin:()=>{let object={};onValue(object),previousParents.push(currentParent),currentParent=object,currentProperty=null},onObjectProperty:name=>{currentProperty=name},onObjectEnd:()=>{currentParent=previousParents.pop()},onArrayBegin:()=>{let array=[];onValue(array),previousParents.push(currentParent),currentParent=array,currentProperty=null},onArrayEnd:()=>{currentParent=previousParents.pop()},onLiteralValue:onValue,onError:(error,offset,length)=>{errors.push({error,offset,length})}},options),currentParent[0]}function parseTree(text,errors=[],options=ParseOptions.DEFAULT){let currentParent={type:"array",offset:-1,length:-1,children:[],parent:void 0};function ensurePropertyComplete(endOffset){currentParent.type==="property"&&(currentParent.length=endOffset-currentParent.offset,currentParent=currentParent.parent)}function onValue(valueNode){return currentParent.children.push(valueNode),valueNode}visit(text,{onObjectBegin:offset=>{currentParent=onValue({type:"object",offset,length:-1,parent:currentParent,children:[]})},onObjectProperty:(name,offset,length)=>{currentParent=onValue({type:"property",offset,length:-1,parent:currentParent,children:[]}),currentParent.children.push({type:"string",value:name,offset,length,parent:currentParent})},onObjectEnd:(offset,length)=>{ensurePropertyComplete(offset+length),currentParent.length=offset+length-currentParent.offset,currentParent=currentParent.parent,ensurePropertyComplete(offset+length)},onArrayBegin:(offset,length)=>{currentParent=onValue({type:"array",offset,length:-1,parent:currentParent,children:[]})},onArrayEnd:(offset,length)=>{currentParent.length=offset+length-currentParent.offset,currentParent=currentParent.parent,ensurePropertyComplete(offset+length)},onLiteralValue:(value,offset,length)=>{onValue({type:getNodeType(value),offset,length,parent:currentParent,value}),ensurePropertyComplete(offset+length)},onSeparator:(sep,offset,length)=>{currentParent.type==="property"&&(sep===":"?currentParent.colonOffset=offset:sep===","&&ensurePropertyComplete(offset))},onError:(error,offset,length)=>{errors.push({error,offset,length})}},options);let result=currentParent.children[0];return result&&delete result.parent,result}function findNodeAtLocation(root,path){if(!root)return;let node=root;for(let segment of path)if(typeof segment=="string"){if(node.type!=="object"||!Array.isArray(node.children))return;let found=!1;for(let propertyNode of node.children)if(Array.isArray(propertyNode.children)&&propertyNode.children[0].value===segment&&propertyNode.children.length===2){node=propertyNode.children[1],found=!0;break}if(!found)return}else{let index=segment;if(node.type!=="array"||index<0||!Array.isArray(node.children)||index>=node.children.length)return;node=node.children[index]}return node}function visit(text,visitor,options=ParseOptions.DEFAULT){let _scanner=createScanner(text,!1),_jsonPath=[],suppressedCallbacks=0;function toNoArgVisit(visitFunction){return visitFunction?()=>suppressedCallbacks===0&&visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>!0}function toOneArgVisit(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>!0}function toOneArgVisitWithPath(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice()):()=>!0}function toBeginVisit(visitFunction){return visitFunction?()=>{suppressedCallbacks>0?suppressedCallbacks++:visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice())===!1&&(suppressedCallbacks=1)}:()=>!0}function toEndVisit(visitFunction){return visitFunction?()=>{suppressedCallbacks>0&&suppressedCallbacks--,suppressedCallbacks===0&&visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter())}:()=>!0}let onObjectBegin=toBeginVisit(visitor.onObjectBegin),onObjectProperty=toOneArgVisitWithPath(visitor.onObjectProperty),onObjectEnd=toEndVisit(visitor.onObjectEnd),onArrayBegin=toBeginVisit(visitor.onArrayBegin),onArrayEnd=toEndVisit(visitor.onArrayEnd),onLiteralValue=toOneArgVisitWithPath(visitor.onLiteralValue),onSeparator=toOneArgVisit(visitor.onSeparator),onComment=toNoArgVisit(visitor.onComment),onError=toOneArgVisit(visitor.onError),disallowComments=options&&options.disallowComments,allowTrailingComma=options&&options.allowTrailingComma;function scanNext(){for(;;){let token=_scanner.scan();switch(_scanner.getTokenError()){case 4:handleError(14);break;case 5:handleError(15);break;case 3:handleError(13);break;case 1:disallowComments||handleError(11);break;case 2:handleError(12);break;case 6:handleError(16);break}switch(token){case 12:case 13:disallowComments?handleError(10):onComment();break;case 16:handleError(1);break;case 15:case 14:break;default:return token}}}function handleError(error,skipUntilAfter=[],skipUntil=[]){if(onError(error),skipUntilAfter.length+skipUntil.length>0){let token=_scanner.getToken();for(;token!==17;){if(skipUntilAfter.indexOf(token)!==-1){scanNext();break}else if(skipUntil.indexOf(token)!==-1)break;token=scanNext()}}}function parseString(isValue){let value=_scanner.getTokenValue();return isValue?onLiteralValue(value):(onObjectProperty(value),_jsonPath.push(value)),scanNext(),!0}function parseLiteral(){switch(_scanner.getToken()){case 11:let tokenValue=_scanner.getTokenValue(),value=Number(tokenValue);isNaN(value)&&(handleError(2),value=0),onLiteralValue(value);break;case 7:onLiteralValue(null);break;case 8:onLiteralValue(!0);break;case 9:onLiteralValue(!1);break;default:return!1}return scanNext(),!0}function parseProperty(){return _scanner.getToken()!==10?(handleError(3,[],[2,5]),!1):(parseString(!1),_scanner.getToken()===6?(onSeparator(":"),scanNext(),parseValue()||handleError(4,[],[2,5])):handleError(5,[],[2,5]),_jsonPath.pop(),!0)}function parseObject(){onObjectBegin(),scanNext();let needsComma=!1;for(;_scanner.getToken()!==2&&_scanner.getToken()!==17;){if(_scanner.getToken()===5){if(needsComma||handleError(4,[],[]),onSeparator(","),scanNext(),_scanner.getToken()===2&&allowTrailingComma)break}else needsComma&&handleError(6,[],[]);parseProperty()||handleError(4,[],[2,5]),needsComma=!0}return onObjectEnd(),_scanner.getToken()!==2?handleError(7,[2],[]):scanNext(),!0}function parseArray(){onArrayBegin(),scanNext();let isFirstElement=!0,needsComma=!1;for(;_scanner.getToken()!==4&&_scanner.getToken()!==17;){if(_scanner.getToken()===5){if(needsComma||handleError(4,[],[]),onSeparator(","),scanNext(),_scanner.getToken()===4&&allowTrailingComma)break}else needsComma&&handleError(6,[],[]);isFirstElement?(_jsonPath.push(0),isFirstElement=!1):_jsonPath[_jsonPath.length-1]++,parseValue()||handleError(4,[],[4,5]),needsComma=!0}return onArrayEnd(),isFirstElement||_jsonPath.pop(),_scanner.getToken()!==4?handleError(8,[4],[]):scanNext(),!0}function parseValue(){switch(_scanner.getToken()){case 3:return parseArray();case 1:return parseObject();case 10:return parseString(!0);default:return parseLiteral()}}return scanNext(),_scanner.getToken()===17?options.allowEmptyContent?!0:(handleError(4,[],[]),!1):parseValue()?(_scanner.getToken()!==17&&handleError(9,[],[]),!0):(handleError(4,[],[]),!1)}function getNodeType(value){switch(typeof value){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(value){if(Array.isArray(value))return"array"}else return"null";return"object"}default:return"null"}}var ParseOptions,init_parser=__esm({"../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/parser.js"(){"use strict";init_scanner();(function(ParseOptions2){ParseOptions2.DEFAULT={allowTrailingComma:!1}})(ParseOptions||(ParseOptions={}))}});function setProperty(text,originalPath,value,options){let path=originalPath.slice(),root=parseTree(text,[]),parent,lastSegment;for(;path.length>0&&(lastSegment=path.pop(),parent=findNodeAtLocation(root,path),parent===void 0&&value!==void 0);)typeof lastSegment=="string"?value={[lastSegment]:value}:value=[value];if(parent)if(parent.type==="object"&&typeof lastSegment=="string"&&Array.isArray(parent.children)){let existing=findNodeAtLocation(parent,[lastSegment]);if(existing!==void 0)if(value===void 0){if(!existing.parent)throw new Error("Malformed AST");let propertyIndex=parent.children.indexOf(existing.parent),removeBegin,removeEnd=existing.parent.offset+existing.parent.length;if(propertyIndex>0){let previous=parent.children[propertyIndex-1];removeBegin=previous.offset+previous.length}else removeBegin=parent.offset+1,parent.children.length>1&&(removeEnd=parent.children[1].offset);return withFormatting(text,{offset:removeBegin,length:removeEnd-removeBegin,content:""},options)}else return withFormatting(text,{offset:existing.offset,length:existing.length,content:JSON.stringify(value)},options);else{if(value===void 0)return[];let newProperty=`${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`,index=options.getInsertionIndex?options.getInsertionIndex(parent.children.map(p=>p.children[0].value)):parent.children.length,edit;if(index>0){let previous=parent.children[index-1];edit={offset:previous.offset+previous.length,length:0,content:","+newProperty}}else parent.children.length===0?edit={offset:parent.offset+1,length:0,content:newProperty}:edit={offset:parent.offset+1,length:0,content:newProperty+","};return withFormatting(text,edit,options)}}else if(parent.type==="array"&&typeof lastSegment=="number"&&Array.isArray(parent.children)){let insertIndex=lastSegment;if(insertIndex===-1){let newProperty=`${JSON.stringify(value)}`,edit;if(parent.children.length===0)edit={offset:parent.offset+1,length:0,content:newProperty};else{let previous=parent.children[parent.children.length-1];edit={offset:previous.offset+previous.length,length:0,content:","+newProperty}}return withFormatting(text,edit,options)}else if(value===void 0&&parent.children.length>=0){let removalIndex=lastSegment,toRemove=parent.children[removalIndex],edit;if(parent.children.length===1)edit={offset:parent.offset+1,length:parent.length-2,content:""};else if(parent.children.length-1===removalIndex){let previous=parent.children[removalIndex-1],offset=previous.offset+previous.length,parentEndOffset=parent.offset+parent.length;edit={offset,length:parentEndOffset-2-offset,content:""}}else edit={offset:toRemove.offset,length:parent.children[removalIndex+1].offset-toRemove.offset,content:""};return withFormatting(text,edit,options)}else if(value!==void 0){let edit,newProperty=`${JSON.stringify(value)}`;if(!options.isArrayInsertion&&parent.children.length>lastSegment){let toModify=parent.children[lastSegment];edit={offset:toModify.offset,length:toModify.length,content:newProperty}}else if(parent.children.length===0||lastSegment===0)edit={offset:parent.offset+1,length:0,content:parent.children.length===0?newProperty:newProperty+","};else{let index=lastSegment>parent.children.length?parent.children.length:lastSegment,previous=parent.children[index-1];edit={offset:previous.offset+previous.length,length:0,content:","+newProperty}}return withFormatting(text,edit,options)}else throw new Error(`Can not ${value===void 0?"remove":options.isArrayInsertion?"insert":"modify"} Array index ${insertIndex} as length is not sufficient`)}else throw new Error(`Can not add ${typeof lastSegment!="number"?"index":"property"} to parent of type ${parent.type}`);else{if(value===void 0)throw new Error("Can not delete in empty document");return withFormatting(text,{offset:root?root.offset:0,length:root?root.length:0,content:JSON.stringify(value)},options)}}function withFormatting(text,edit,options){if(!options.formattingOptions)return[edit];let newText=applyEdit(text,edit),begin=edit.offset,end=edit.offset+edit.content.length;if(edit.length===0||edit.content.length===0){for(;begin>0&&!isEOL(newText,begin-1);)begin--;for(;end<newText.length&&!isEOL(newText,end);)end++}let edits=format(newText,{offset:begin,length:end-begin},{...options.formattingOptions,keepLines:!1});for(let i=edits.length-1;i>=0;i--){let edit2=edits[i];newText=applyEdit(newText,edit2),begin=Math.min(begin,edit2.offset),end=Math.max(end,edit2.offset+edit2.length),end+=edit2.content.length-edit2.length}let editLength=text.length-(newText.length-end)-begin;return[{offset:begin,length:editLength,content:newText.substring(begin,end)}]}function applyEdit(text,edit){return text.substring(0,edit.offset)+edit.content+text.substring(edit.offset+edit.length)}var init_edit=__esm({"../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/edit.js"(){"use strict";init_format();init_parser()}});function printParseErrorCode(code){switch(code){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}function modify(text,path,value,options){return setProperty(text,path,value,options)}function applyEdits(text,edits){let sortedEdits=edits.slice(0).sort((a,b)=>{let diff=a.offset-b.offset;return diff===0?a.length-b.length:diff}),lastModifiedOffset=text.length;for(let i=sortedEdits.length-1;i>=0;i--){let e=sortedEdits[i];if(e.offset+e.length<=lastModifiedOffset)text=applyEdit(text,e);else throw new Error("Overlapping edit");lastModifiedOffset=e.offset}return text}var ScanError,SyntaxKind,parse2,parseTree2,findNodeAtLocation2,ParseErrorCode,init_main=__esm({"../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js"(){"use strict";init_format();init_edit();init_scanner();init_parser();(function(ScanError2){ScanError2[ScanError2.None=0]="None",ScanError2[ScanError2.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",ScanError2[ScanError2.UnexpectedEndOfString=2]="UnexpectedEndOfString",ScanError2[ScanError2.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",ScanError2[ScanError2.InvalidUnicode=4]="InvalidUnicode",ScanError2[ScanError2.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",ScanError2[ScanError2.InvalidCharacter=6]="InvalidCharacter"})(ScanError||(ScanError={}));(function(SyntaxKind2){SyntaxKind2[SyntaxKind2.OpenBraceToken=1]="OpenBraceToken",SyntaxKind2[SyntaxKind2.CloseBraceToken=2]="CloseBraceToken",SyntaxKind2[SyntaxKind2.OpenBracketToken=3]="OpenBracketToken",SyntaxKind2[SyntaxKind2.CloseBracketToken=4]="CloseBracketToken",SyntaxKind2[SyntaxKind2.CommaToken=5]="CommaToken",SyntaxKind2[SyntaxKind2.ColonToken=6]="ColonToken",SyntaxKind2[SyntaxKind2.NullKeyword=7]="NullKeyword",SyntaxKind2[SyntaxKind2.TrueKeyword=8]="TrueKeyword",SyntaxKind2[SyntaxKind2.FalseKeyword=9]="FalseKeyword",SyntaxKind2[SyntaxKind2.StringLiteral=10]="StringLiteral",SyntaxKind2[SyntaxKind2.NumericLiteral=11]="NumericLiteral",SyntaxKind2[SyntaxKind2.LineCommentTrivia=12]="LineCommentTrivia",SyntaxKind2[SyntaxKind2.BlockCommentTrivia=13]="BlockCommentTrivia",SyntaxKind2[SyntaxKind2.LineBreakTrivia=14]="LineBreakTrivia",SyntaxKind2[SyntaxKind2.Trivia=15]="Trivia",SyntaxKind2[SyntaxKind2.Unknown=16]="Unknown",SyntaxKind2[SyntaxKind2.EOF=17]="EOF"})(SyntaxKind||(SyntaxKind={}));parse2=parse,parseTree2=parseTree,findNodeAtLocation2=findNodeAtLocation;(function(ParseErrorCode2){ParseErrorCode2[ParseErrorCode2.InvalidSymbol=1]="InvalidSymbol",ParseErrorCode2[ParseErrorCode2.InvalidNumberFormat=2]="InvalidNumberFormat",ParseErrorCode2[ParseErrorCode2.PropertyNameExpected=3]="PropertyNameExpected",ParseErrorCode2[ParseErrorCode2.ValueExpected=4]="ValueExpected",ParseErrorCode2[ParseErrorCode2.ColonExpected=5]="ColonExpected",ParseErrorCode2[ParseErrorCode2.CommaExpected=6]="CommaExpected",ParseErrorCode2[ParseErrorCode2.CloseBraceExpected=7]="CloseBraceExpected",ParseErrorCode2[ParseErrorCode2.CloseBracketExpected=8]="CloseBracketExpected",ParseErrorCode2[ParseErrorCode2.EndOfFileExpected=9]="EndOfFileExpected",ParseErrorCode2[ParseErrorCode2.InvalidCommentToken=10]="InvalidCommentToken",ParseErrorCode2[ParseErrorCode2.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",ParseErrorCode2[ParseErrorCode2.UnexpectedEndOfString=12]="UnexpectedEndOfString",ParseErrorCode2[ParseErrorCode2.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",ParseErrorCode2[ParseErrorCode2.InvalidUnicode=14]="InvalidUnicode",ParseErrorCode2[ParseErrorCode2.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",ParseErrorCode2[ParseErrorCode2.InvalidCharacter=16]="InvalidCharacter"})(ParseErrorCode||(ParseErrorCode={}))}});export{parse2 as parse,parseTree2 as parseTree,findNodeAtLocation2 as findNodeAtLocation,printParseErrorCode,modify,applyEdits,init_main};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{require_dist as require_dist2,validateConfig}from"./chunk-FB5TMOLQ.js";import{require_dist2 as require_dist}from"./chunk-Z7PBDQNR.js";import{compileVercelConfig,findSourceVercelConfigFile}from"./chunk-73G2MHUX.js";import{applyEdits,findNodeAtLocation,init_main,modify,parse,parseTree}from"./chunk-OI263FBO.js";import{printAlignedLabel}from"./chunk-YMM3VY3J.js";import{code}from"./chunk-LKI6FRNM.js";import{link_default,output_manager_default,require_build_utils}from"./chunk-EWWFNMPZ.js";import{require_source}from"./chunk-U7KCDTCH.js";import{__toESM}from"./chunk-6L236MNA.js";var import_chalk=__toESM(require_source(),1);init_main();var import_build_utils=__toESM(require_build_utils(),1),import_fs_detectors=__toESM(require_dist(),1),import_service_topology=__toESM(require_dist2(),1);import{readFile,writeFile}from"fs/promises";import{basename}from"path";import{stringify as tomlStringify}from"smol-toml";var EXPERIMENTAL_SERVICES_DOCS_URL="https://vercel.com/docs/services/experimental";async function prepareExperimentalServicesMigration(cwd,detectServicesResult){let compileResult=await compileVercelConfig(cwd);if(!compileResult.configPath)return null;let rawConfig=await readFile(compileResult.configPath,"utf8"),config=parse(rawConfig);if(!config||!(0,import_service_topology.hasLegacyServicesConfig)(config))return null;let resolvedServices=detectServicesResult?.resolved?.source==="configured"?detectServicesResult.services.filter(s=>(0,import_build_utils.isExperimentalService)(s)):void 0,plan=await(0,import_service_topology.migrateExperimentalServices)({fs:new import_fs_detectors.LocalFileSystemDetector(cwd),config,resolvedServices:resolvedServices&&resolvedServices.length>0?resolvedServices:void 0}),sourceFile=compileResult.sourceFile??basename(compileResult.configPath),preparation={plan,sourceFile,snippet:renderSnippet(sourceFile,plan)};if(plan.errors.length>0)return preparation;if(compileResult.wasCompiled)return preparation.writeBlocker=`${sourceFile} can't be updated automatically.`,preparation;let content=applyPlanToJson(rawConfig,config,plan),parseErrors=[],nextConfig=parse(content,parseErrors);if(parseErrors.length>0)return preparation.writeBlocker=`Couldn't produce a valid ${sourceFile}.`,preparation;let validationError=validateConfig(nextConfig);return validationError?(preparation.writeBlocker=validationError.message,preparation):(preparation.write={configPath:compileResult.configPath,content},preparation)}function applyPlanToJson(rawConfig,config,plan){let eol=rawConfig.includes(`\r
|
|
8
|
+
`)?`\r
|
|
9
|
+
`:`
|
|
10
|
+
`,indent2=/^([ \t]+)\S/m.exec(rawConfig)?.[1]??" ",formattingOptions={eol,insertSpaces:!indent2.startsWith(" "),tabSize:indent2.startsWith(" ")?1:indent2.length},legacyKey=config.experimentalServices?"experimentalServices":"experimentalServicesV2",key=findNodeAtLocation(parseTree(rawConfig),[legacyKey]).parent.children[0],text=applyEdits(rawConfig,[{offset:key.offset,length:key.length,content:'"services"'}]);text=applyEdits(text,modify(text,["services"],plan.patch.services,{formattingOptions}));for(let key2 of plan.removeKeys)key2!==legacyKey&&(text=applyEdits(text,modify(text,[key2],void 0,{formattingOptions})));for(let[key2,value]of Object.entries(plan.patch.build?.env??{}))text=applyEdits(text,modify(text,["build","env",key2],value,{formattingOptions}));if(plan.patch.rewrites.length>0)if(Array.isArray(config.rewrites))for(let rewrite of plan.patch.rewrites)text=applyEdits(text,modify(text,["rewrites",-1],rewrite,{formattingOptions}));else text=applyEdits(text,modify(text,["rewrites"],plan.patch.rewrites,{formattingOptions,getInsertionIndex:keys=>keys.indexOf("services")+1}));return text.endsWith(`
|
|
11
|
+
`)?text:`${text}${eol}`}function renderSnippet(sourceFile,plan){let patch={services:plan.patch.services};return plan.patch.rewrites.length>0&&(patch.rewrites=plan.patch.rewrites),plan.patch.build&&(patch.build=plan.patch.build),sourceFile==="vercel.toml"?tomlStringify(patch).trimEnd():JSON.stringify(patch,null,2)}function displayExperimentalServicesMigration(preparation){let{plan,sourceFile,snippet}=preparation,legacyKey=plan.removeKeys.includes("experimentalServices")?"experimentalServices":"experimentalServicesV2";if(output_manager_default.print(`${import_chalk.default.yellow("!")} ${sourceFile} uses ${code(legacyKey)}, which is replaced by ${code("services")}. ${link_default(EXPERIMENTAL_SERVICES_DOCS_URL)}
|
|
12
|
+
`),plan.errors.length>0){output_manager_default.print(` ${import_chalk.default.bold(`Can't migrate ${sourceFile} automatically:`)}
|
|
13
|
+
`);for(let error of plan.errors)output_manager_default.print(` ${import_chalk.default.red("\u2717")} ${error.message}
|
|
14
|
+
`);return}output_manager_default.print(`
|
|
15
|
+
${import_chalk.default.bold(`Suggested ${sourceFile} configuration:`)}
|
|
16
|
+
`),output_manager_default.print(`${indent(snippet,2)}
|
|
17
|
+
`),plan.patch.build&&!preparation.write&&output_manager_default.print(" Merge these `build.env` defaults with any existing build settings.\n");let removed=plan.removeKeys.filter(k=>k!==legacyKey);removed.length>0&&output_manager_default.print(`
|
|
18
|
+
Also removes top-level ${removed.map(k=>code(k)).join(", ")}.
|
|
19
|
+
`);for(let rename of plan.renamedServices)output_manager_default.print(` Service ${code(rename.from)} is renamed to ${code(rename.to)}.
|
|
20
|
+
`);for(let[heading,notes]of[["Review before deploying:",plan.warnings],["Not migrated:",plan.unmigrated]])if(notes.length>0){output_manager_default.print(`
|
|
21
|
+
${import_chalk.default.bold(heading)}
|
|
22
|
+
`);for(let note of notes){let link=note.link?` ${link_default(note.link)}`:"";output_manager_default.print(`${import_chalk.default.yellow("!")} ${note.message}${link}
|
|
23
|
+
`)}}output_manager_default.print(`
|
|
24
|
+
`)}function indent(text,spaces){let pad=" ".repeat(spaces);return text.split(`
|
|
25
|
+
`).map(line=>`${pad}${line}`).join(`
|
|
26
|
+
`)}async function promptExperimentalServicesMigration({client,cwd,autoConfirm=!1,nonInteractive=!1,allowConfigExecution=!0,detectServicesResult}){let preparation;try{if(!allowConfigExecution){let sourceFile=await findSourceVercelConfigFile(cwd);if(sourceFile&&sourceFile!=="vercel.toml")return!1}preparation=await prepareExperimentalServicesMigration(cwd,detectServicesResult)}catch(error){return output_manager_default.debug(`Skipping services migration suggestion: ${error}`),!1}if(!preparation||(displayExperimentalServicesMigration(preparation),preparation.plan.errors.length>0))return!1;if(!preparation.write)return preparation.writeBlocker&&output_manager_default.print(` ${preparation.writeBlocker} Apply the configuration above to ${preparation.sourceFile} manually.
|
|
27
|
+
|
|
28
|
+
`),!1;let interactive=client.stdin.isTTY&&!nonInteractive,confirmed=autoConfirm;return!confirmed&&interactive&&(confirmed=await client.input.confirm(`Update ${preparation.sourceFile} with this configuration?`,!0)),confirmed?(await writeFile(preparation.write.configPath,preparation.write.content,"utf8"),printAlignedLabel("Updated",preparation.sourceFile,{gutter:"\u2713"}),preparation.plan.unmigrated.length>0&&output_manager_default.print(` ${preparation.plan.unmigrated.length} service${preparation.plan.unmigrated.length===1?" was":"s were"} left out. Migrate ${preparation.plan.unmigrated.length===1?"it":"them"} manually before deploying.
|
|
29
|
+
`),output_manager_default.print(`
|
|
30
|
+
`),!0):(!interactive&&!autoConfirm&&output_manager_default.print(` Run this command in a terminal to apply it, pass ${code("--yes")} to accept the migration, or update ${preparation.sourceFile} manually.
|
|
31
|
+
|
|
32
|
+
`),!1)}export{promptExperimentalServicesMigration};
|
|
@@ -4,7 +4,7 @@ import { dirname as __dirname_ } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
const __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
const __dirname = __dirname_(__filename);
|
|
7
|
-
import{
|
|
7
|
+
import{readJSONFile}from"./chunk-TJKM3345.js";import{require_dist as require_dist2,validateConfig}from"./chunk-FB5TMOLQ.js";import{require_dist2 as require_dist}from"./chunk-Z7PBDQNR.js";import{compileVercelConfig}from"./chunk-73G2MHUX.js";import{CantParseJSONFile}from"./chunk-LKI6FRNM.js";import{require_build_utils}from"./chunk-EWWFNMPZ.js";import{__toESM}from"./chunk-6L236MNA.js";var import_fs_detectors=__toESM(require_dist(),1),import_service_topology=__toESM(require_dist2(),1);import{readFile,writeFile}from"fs/promises";import{basename,join as join2}from"path";import{parse as tomlParse,stringify as tomlStringify}from"smol-toml";var import_build_utils=__toESM(require_build_utils(),1);import{join}from"path";function createDetectEntrypoint(projectRoot){return async({workPath,framework})=>{let absWorkPath=(0,import_build_utils.normalizePath)(join(projectRoot,workPath)),builderName;if((0,import_build_utils.isPythonFramework)(framework))builderName="@vercel/python";else if((0,import_build_utils.isNodeBackendFramework)(framework))builderName="@vercel/backends";else if(framework==="go")builderName="@vercel/go";else if(framework==="rust")builderName="@vercel/rust";else return null;let detectEntrypoint=await loadBuilderDetectEntrypoint(builderName,projectRoot);return detectEntrypoint?detectEntrypoint(builderName==="@vercel/python"?{workPath:absWorkPath,framework}:{workPath:absWorkPath}):null}}async function loadBuilderDetectEntrypoint(name,projectRoot){let{importBuilders}=await import("./import-builders-IFZM44NL.js"),loaded=(await importBuilders(new Set([name]),projectRoot)).get(name);if(!loaded)return;let detect=loaded.builder.detectEntrypoint;return typeof detect=="function"?detect:void 0}function getServicesConfiguration(config){let configuredServices=config?.services??config?.experimentalServicesV2??config?.experimentalServices,configuredServicesType=config?.services?"services":config?.experimentalServicesV2?"experimentalServicesV2":config?.experimentalServices?"experimentalServices":void 0;return{configuredServices,configuredServicesType}}async function loadVercelConfig(cwd){try{let{configPath}=await compileVercelConfig(cwd);if(!configPath)return null;let config=await readJSONFile(configPath);return config instanceof Error?null:config}catch{return null}}function isServicesEnvEnabled(){let value=process.env.VERCEL_USE_EXPERIMENTAL_SERVICES;return value==="1"||value?.toLowerCase()==="true"}async function isExperimentalServicesEnabled(cwd){let{configuredServices}=getServicesConfiguration(await loadVercelConfig(cwd));return isServicesEnvEnabled()||configuredServices!==void 0}async function tryDetectServices(cwd,config){config===void 0&&(config=await loadVercelConfig(cwd));let configuration=getServicesConfiguration(config);if(!isServicesEnvEnabled()&&!configuration.configuredServices)return null;let fs=new import_fs_detectors.LocalFileSystemDetector(cwd),result=await(0,import_service_topology.detectServices)({fs,configuredServices:configuration.configuredServices,configuredServicesType:configuration.configuredServicesType,detectEntrypoint:createDetectEntrypoint(cwd)});return result.errors.some(e=>e.code==="NO_SERVICES_CONFIGURED")?null:result}async function writeServicesConfig(cwd,config){let prepared=await prepareServicesConfigWrite(cwd,config);return await writeFile(prepared.configPath,prepared.content,"utf8"),{configFileName:basename(prepared.configPath)}}async function getServicesConfigWriteBlocker(cwd,config){try{return await prepareServicesConfigWrite(cwd,config),null}catch(error){return getServicesConfigWriteBlockerFromError(error)}}function toProjectServicesConfigPatch(config){let services={};for(let[name,svc]of Object.entries(config)){let buildCommand=svc.preDeployCommand&&svc.buildCommand?`${svc.buildCommand} && ${svc.preDeployCommand}`:svc.preDeployCommand||svc.buildCommand;services[name]={root:svc.root,...svc.framework?{framework:svc.framework}:{},...svc.entrypoint?{entrypoint:svc.entrypoint}:{},...buildCommand?{buildCommand}:{}}}let rewrites=(0,import_service_topology.generateServiceRewrites)(config);return{services,...rewrites.length>0?{rewrites}:{}}}async function prepareServicesConfigWrite(cwd,config){let compileResult=await compileVercelConfig(cwd),configPath=join2(cwd,"vercel.json");if(compileResult.sourceFile==="vercel.toml")return prepareTomlServicesConfigWrite(join2(cwd,"vercel.toml"),config);if(compileResult.wasCompiled)throw new Error(`Cannot automatically update ${compileResult.sourceFile??"the current Vercel config"}.`);let existingConfig={};if(compileResult.configPath&&basename(compileResult.configPath)==="vercel.json"){let result=await readJSONFile(configPath);if(result instanceof CantParseJSONFile)throw result;existingConfig=result??{}}let patch=toProjectServicesConfigPatch(config),nextConfig={...existingConfig,...patch,...patch.rewrites?{rewrites:[...existingConfig.rewrites??[],...patch.rewrites]}:{}},validationError=validateConfig(nextConfig);if(validationError)throw validationError;return{configPath,content:JSON.stringify(nextConfig,null,2)+`
|
|
8
8
|
`}}async function prepareTomlServicesConfigWrite(configPath,config){let patch=toProjectServicesConfigPatch(config),patchKeys=Object.keys(patch),existingContent;try{existingContent=await readFile(configPath,"utf8")}catch{existingContent=""}if(existingContent.trim()){let existingParsed=tomlParse(existingContent),overlapping=patchKeys.filter(key=>key in existingParsed);if(overlapping.length>0){let plural=overlapping.length>1,keyList=overlapping.map(k=>`"${k}"`).join(", ");throw new Error(`Cannot automatically update vercel.toml: key${plural?"s":""} ${keyList} already exist${plural?"":"s"}.`)}}let patchToml=tomlStringify(patch),content=existingContent.trim()?existingContent.trimEnd()+`
|
|
9
9
|
|
|
10
10
|
`+patchToml+`
|
|
@@ -4,4 +4,4 @@ import { dirname as __dirname_ } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
const __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
const __dirname = __dirname_(__filename);
|
|
7
|
-
import{output_manager_default}from"./chunk-
|
|
7
|
+
import{output_manager_default}from"./chunk-EWWFNMPZ.js";function parseTarget({flagName,flags}){let targetFlagName=`--${flagName}`,targetFlagValue=flags[targetFlagName],prodFlagValue=flags["--prod"];if(prodFlagValue&&targetFlagValue&&output_manager_default.warn(`Both \`--prod\` and \`${targetFlagName}\` detected. Ignoring \`--prod\`.`),typeof targetFlagValue=="string")return output_manager_default.debug(`Setting target to ${targetFlagValue}`),targetFlagValue;if(prodFlagValue)return output_manager_default.debug("Setting target to production"),"production"}export{parseTarget};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{applyEdits,init_main,modify,parse,printParseErrorCode}from"./chunk-OI263FBO.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";import{readFile as readFile3,writeFile as writeFile3}from"node:fs/promises";import{access as access2}from"node:fs/promises";import{dirname as dirname3,join as join3,resolve}from"node:path";import{homedir}from"node:os";import{spawn}from"node:child_process";import{KNOWN_AGENTS}from"@vercel/detect-agent";import{z}from"zod";import{join as join2}from"node:path";init_main();import{readFile,writeFile,mkdir,copyFile,access,chmod,lstat,stat,link,unlink}from"node:fs/promises";import{isDeepStrictEqual}from"node:util";import{dirname}from"node:path";import{parse as tomlParse,stringify as tomlStringify}from"smol-toml";async function pathExists(path){try{return await access(path),!0}catch{return!1}}async function isFile(path){try{return(await stat(path)).isFile()}catch{return!1}}async function isSymlink(path){try{return(await lstat(path)).isSymbolicLink()}catch{return!1}}async function readFileOrNull(path){try{return await readFile(path,"utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)&&Object.getPrototypeOf(value)===Object.prototype}function deepMerge(base,patch){let out={...base};for(let[key,patchValue]of Object.entries(patch)){let baseValue=out[key];isPlainObject(baseValue)&&isPlainObject(patchValue)?out[key]=deepMerge(baseValue,patchValue):out[key]=patchValue}return out}function detectJsonFormatting(text){let eol=text.includes(`\r
|
|
8
|
+
`)?`\r
|
|
9
|
+
`:`
|
|
10
|
+
`,indent=text.match(/^([ \t]+)\S/m)?.[1];return indent?.startsWith(" ")?{eol,insertSpaces:!1,tabSize:1}:{eol,insertSpaces:!0,tabSize:indent?.length||2}}function parseJsonObjectOrNull(current,parse2=JSON.parse){if(!current||!current.trim())return null;let raw;try{raw=parse2(current)}catch(err){throw new Error(`existing file is not valid JSON (${err.message})`)}if(!isPlainObject(raw))throw new Error("existing file is not a JSON object");return raw}function mergeJson(current,patch,parse2=JSON.parse){let raw=parseJsonObjectOrNull(current,parse2);if(!current||raw===null)return`${JSON.stringify(deepMerge({},patch),null,2)}
|
|
11
|
+
`;let merged=deepMerge(raw,patch),modifyOptions=current.trim().includes(`
|
|
12
|
+
`)?{formattingOptions:detectJsonFormatting(current)}:{};try{let text=current,splice=(existing,subPatch,path)=>{for(let[key,patchValue]of Object.entries(subPatch)){let existingValue=existing?.[key];isPlainObject(patchValue)&&isPlainObject(existingValue)?splice(existingValue,patchValue,[...path,key]):isDeepStrictEqual(existingValue,patchValue)||(text=applyEdits(text,modify(text,[...path,key],patchValue,modifyOptions)))}};if(splice(raw,patch,[]),isDeepStrictEqual(parse2(text),merged))return text}catch{}return`${JSON.stringify(merged,null,2)}
|
|
13
|
+
`}function mergeJsonc(current,patch){return mergeJson(current,patch,text=>{let errors=[],value=parse(text,errors,{allowTrailingComma:!0}),first=errors[0];if(first)throw new Error(`${printParseErrorCode(first.error)} at offset ${first.offset}`);return value})}function patchSatisfied(existing,patch){for(let[key,patchValue]of Object.entries(patch)){let existingValue=isPlainObject(existing)?existing[key]:void 0;if(isPlainObject(patchValue)&&isPlainObject(existingValue)){if(!patchSatisfied(existingValue,patchValue))return!1}else if(!isDeepStrictEqual(existingValue,patchValue))return!1}return!0}function tomlScalar(value){switch(typeof value){case"string":return JSON.stringify(value);case"number":return Number.isFinite(value)?String(value):null;case"boolean":return String(value);default:return null}}var TOML_BARE_KEY=/^[A-Za-z0-9_-]+$/;function flattenTomlPatch(patch,prefix="",out=new Map){for(let[key,value]of Object.entries(patch)){if(!TOML_BARE_KEY.test(key))return null;if(isPlainObject(value)){if(!flattenTomlPatch(value,prefix?`${prefix}.${key}`:key,out))return null}else{let scalar=tomlScalar(value);if(scalar===null)return null;let section=out.get(prefix);section||(section=new Map,out.set(prefix,section)),section.set(key,scalar)}}return out}var TOML_HEADER=/^\s*\[\[?\s*([^\]]*?)\s*\]\]?\s*(?:#.*)?$/;function mergeToml(current,patch){let parsed={};if(current&¤t.trim())try{parsed=tomlParse(current)}catch(err){throw new Error(`existing file is not valid TOML (${err.message})`)}let legacy=()=>`${tomlStringify(deepMerge(parsed,patch))}
|
|
14
|
+
`;if(!current||!current.trim())return legacy();if(patchSatisfied(parsed,patch))return current;let flat=flattenTomlPatch(patch);if(!flat)return legacy();let crlf=current.includes(`\r
|
|
15
|
+
`),lines=current.split(`
|
|
16
|
+
`),content=line=>line.endsWith("\r")?line.slice(0,-1):line,finish=(line,i)=>i<lines.length&&lines[i]?.endsWith("\r")?`${line}\r`:line,headerAt=i=>{let m=content(lines[i]).match(TOML_HEADER);return m?m[1].split(".").map(s=>s.trim()).join("."):null},sectionRange=name=>{let start=name===""?0:-1;for(let i=0;i<lines.length;i++){let header=headerAt(i);if(header!==null){if(start!==-1)return[start,i];if(name==="")return[0,i];header===name&&(start=i+1)}}return start===-1?null:[start,lines.length]},appendSections=[];for(let[name,keys]of flat){let range=sectionRange(name);if(!range){appendSections.push(`[${name}]`,...[...keys].map(([k,v])=>`${k} = ${v}`));continue}let[start,end]=range,inserts=[];for(let[key,value]of keys){let assignment=new RegExp(`^(\\s*)${key}\\s*=`),replaced=!1;for(let i=start;i<end;i++){let m=content(lines[i]).match(assignment);if(m){lines[i]=finish(`${m[1]}${key} = ${value}`,i),replaced=!0;break}}replaced||inserts.push(`${key} = ${value}`)}if(inserts.length>0){let at=start;for(let i=start;i<end;i++)content(lines[i]).trim()!==""&&(at=i+1);lines.splice(at,0,...inserts.map(l=>finish(l,at)))}}if(appendSections.length>0){for(;lines.length>0&&content(lines[lines.length-1]).trim()==="";)lines.pop();let eol=crlf?"\r":"";lines.push(...["",...appendSections,""].map(l=>l===""?l:`${l}${eol}`))}let result=lines.join(`
|
|
17
|
+
`);try{if(isDeepStrictEqual(tomlParse(result),deepMerge(parsed,patch)))return result}catch{}return legacy()}var MANAGED_BLOCK_START="# >>> vercel ai-gateway >>>",MANAGED_BLOCK_END="# <<< vercel ai-gateway <<<";function upsertManagedBlock(current,body){let block=`${MANAGED_BLOCK_START}
|
|
18
|
+
${body}
|
|
19
|
+
${MANAGED_BLOCK_END}`,existing=current??"",start=existing.indexOf(MANAGED_BLOCK_START),end=existing.indexOf(MANAGED_BLOCK_END);if(start!==-1&&end!==-1&&end>start){let before=existing.slice(0,start),after=existing.slice(end+MANAGED_BLOCK_END.length);return`${before}${block}${after}`}if(existing.length===0)return`${block}
|
|
20
|
+
`;let prefix=existing.endsWith(`
|
|
21
|
+
|
|
22
|
+
`)?"":existing.endsWith(`
|
|
23
|
+
`)?`
|
|
24
|
+
`:`
|
|
25
|
+
|
|
26
|
+
`;return`${existing}${prefix}${block}
|
|
27
|
+
`}async function publishNoClobber(temporary,destination){try{return await link(temporary,destination),!0}catch(error){if(error.code==="EEXIST")return!1;throw error}finally{await unlink(temporary).catch(()=>{})}}async function ensureMode(path,mode){try{await chmod(path,mode)}catch{}}async function backupFile(path,mode){let backupPath=`${path}.bak`;return mode===void 0?(await copyFile(path,backupPath),backupPath):(await ensureMode(backupPath,mode),await writeFile(backupPath,await readFile(path,"utf8"),{mode}),backupPath)}async function writeConfigFile(path,content,mode){await mkdir(dirname(path),{recursive:!0}),mode!==void 0&&await ensureMode(path,mode),await writeFile(path,content,mode===void 0?"utf8":{mode})}var GATEWAY_ANTHROPIC_BASE_URL="https://ai-gateway.vercel.sh",GATEWAY_CODING_AGENT_BASE_URL="https://ai-gateway.vercel.sh/coding-agent/v1",GATEWAY_CURSOR_BASE_URL="https://ai-gateway.vercel.sh/cursor/v1",GATEWAY_CODEX_BASE_URL="https://ai-gateway.vercel.sh/codex/v1",GATEWAY_CLAUDE_CODE_BASE_URL="https://ai-gateway.vercel.sh/claude-code",GATEWAY_API_KEY_ENV="AI_GATEWAY_API_KEY",GATEWAY_DEFAULT_MODEL="anthropic/claude-fable-5",KEY_PLACEHOLDER="__AI_GATEWAY_API_KEY__";function resolveGatewayBaseUrl(override,agentDefault){let trimmed=override?.trim();return trimmed||agentDefault}function maskSecret(secret){return secret&&(secret===KEY_PLACEHOLDER||secret.length<=8?"\u2022\u2022\u2022\u2022":`${secret.slice(0,4)}\u2022\u2022\u2022\u2022${secret.slice(-4)}`)}import{randomUUID}from"node:crypto";import*as fs from"node:fs/promises";import{dirname as dirname2,join}from"node:path";var MAX_RECORD_BYTES=1024*1024;function codeSpan(value){return`\`${value.replace(/[`\r\n]/g,"")}\``}var RECORD_PATTERN=/\.json$/;function claudeAppSupportRoot(home){return process.platform==="darwin"?join(home,"Library","Application Support"):process.platform==="win32"?process.env.APPDATA||join(home,"AppData","Roaming"):join(home,".config")}function toGatewayModelId(model){return model.includes("/")?model:`anthropic/${model}`}async function listSubdirectories(path){try{return(await fs.readdir(path,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function findDestinationIdentity(root){let best=null;for(let account of await listSubdirectories(root))for(let org of await listSubdirectories(join(root,account))){let path=join(root,account,org);try{let stat3=await fs.stat(path);(!best||stat3.mtimeMs>best.mtime)&&(best={path,mtime:stat3.mtimeMs})}catch{}}return best?.path??null}async function readRecord(path){let stat3;try{stat3=await fs.stat(path)}catch{return null}if(!stat3.isFile()||stat3.size>MAX_RECORD_BYTES)return null;try{let raw=await fs.readFile(path,"utf8"),record=JSON.parse(raw);return typeof record!="object"||record===null||Array.isArray(record)?null:{record,bytes:stat3.size}}catch{return null}}async function writeRecordNoClobber(destination,contents){if(await pathExists(destination))return"skipped";await fs.mkdir(dirname2(destination),{recursive:!0});let temp=join(dirname2(destination),`.migrate-${randomUUID()}.tmp`);return await fs.writeFile(temp,contents,{mode:384}),await publishNoClobber(temp,destination)?"copied":"skipped"}async function planClaudeDesktopSessionMigration(home,appSupportRoot=claudeAppSupportRoot(home)){let subscriptionRoot=join(appSupportRoot,"Claude","claude-code-sessions"),gatewayRoot=join(appSupportRoot,"Claude-3p","claude-code-sessions"),destinationDir=await findDestinationIdentity(gatewayRoot);if(!destinationDir)return null;let copies=[],totalBytes=0;for(let account of await listSubdirectories(subscriptionRoot))for(let org of await listSubdirectories(join(subscriptionRoot,account))){let identityDir=join(subscriptionRoot,account,org),names;try{names=await fs.readdir(identityDir)}catch{continue}for(let name of names){if(!RECORD_PATTERN.test(name))continue;let source=join(identityDir,name),destination=join(destinationDir,name);if(await pathExists(destination))continue;let read=await readRecord(source);read&&(copies.push({source,destination,bytes:read.bytes}),totalBytes+=read.bytes)}}return copies.length===0?null:{label:"Claude Desktop sessions",itemCount:copies.length,totalBytes,sourceRoots:[subscriptionRoot],destinationRoots:[destinationDir],prompt:[`Copy the ${copies.length} Claude Desktop session record${copies.length===1?"":"s"} (per-session \`.json\` files) under ${codeSpan(subscriptionRoot)} into ${codeSpan(destinationDir)}, keeping each filename.`,"In each copy, rewrite the top-level `model` field to its AI Gateway id by prefixing `anthropic/` when the value has no provider prefix (e.g. `claude-opus-4-8` \u2192 `anthropic/claude-opus-4-8`); keep any suffix such as `[1m]` intact. Leave every other field unchanged.","Use atomic, no-clobber writes with mode 0600; skip records whose destination already exists. Never move, edit, delete, or overwrite an original record."],async apply(){let copied=0,skipped=0,errors=[];for(let copy of copies)try{let read=await readRecord(copy.source);if(!read){skipped+=1;continue}let record={...read.record};typeof record.model=="string"&&(record.model=toGatewayModelId(record.model)),await writeRecordNoClobber(copy.destination,`${JSON.stringify(record)}
|
|
28
|
+
`)==="copied"?copied+=1:skipped+=1}catch(error){errors.push(`${copy.source}: ${error instanceof Error?error.message:String(error)}`)}return errors.length>0?{copied,skipped,errors}:{copied,skipped}}}}function claudeDir(home){let dir=process.env.CLAUDE_CONFIG_DIR;return dir&&dir.trim()?dir:join2(home,".claude")}var claudeCode={id:"claude-code",displayName:"Claude Code",sessionMigration:{plan:({home})=>planClaudeDesktopSessionMigration(home)},async detect(home){return pathExists(claudeDir(home))},configPath(ctx){return ctx.overrides?.["claude-code"]??join2(claudeDir(ctx.home),"settings.json")},buildPlan(ctx){let path=this.configPath(ctx),env={ANTHROPIC_BASE_URL:resolveGatewayBaseUrl(ctx.baseUrlOverride,GATEWAY_CLAUDE_CODE_BASE_URL),ANTHROPIC_API_KEY:"",CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY:"1"},envExports=[];return ctx.useKeychain?envExports.push({name:"ANTHROPIC_AUTH_TOKEN",value:ctx.apiKey}):env.ANTHROPIC_AUTH_TOKEN=ctx.apiKey,{fileChanges:[{path,label:"Claude Code settings",format:"json",...ctx.useKeychain?{}:{mode:384},transform:current=>mergeJson(current,{env})}],envExports,notes:[...ctx.useKeychain?["The Anthropic auth token is read from your shell environment (Keychain-backed).","Open a new terminal so ANTHROPIC_AUTH_TOKEN is loaded, then restart Claude Code."]:["Restart Claude Code to pick up the new settings."],"The Claude Desktop app switches providers in its own settings (Developer \u2192 Configure Third-Party Inference\u2026). After its first gateway launch, re-run this command to copy your existing desktop sessions over."]}}};var PREFS_FILE="agent-preferences.json",CLAUDE_LEGACY_PLUGIN_ID="vercel-plugin@vercel",CLAUDE_OFFICIAL_PLUGIN_ID="vercel@claude-plugins-official",VERCEL_PLUGIN_VERSION_URL="https://raw.githubusercontent.com/vercel/vercel-plugin/main/.claude-plugin/plugin.json",AGENT_TO_TARGET={[KNOWN_AGENTS.CLAUDE]:"claude-code",[KNOWN_AGENTS.COWORK]:"claude-code"};function getPluginTargetForAgent(agentName){if(agentName)return agentName===KNOWN_AGENTS.CLAUDE||agentName.startsWith("claude-code")||agentName===KNOWN_AGENTS.COWORK?"claude-code":AGENT_TO_TARGET[agentName]}var promptedAtSchema=z.codec(z.union([z.iso.date(),z.iso.datetime()]),z.date(),{decode:value=>new Date(value),encode:value=>value.toISOString()}),agentPreferencesSchema=z.object({pluginDeclined:z.boolean().optional(),pluginAutoUpdate:z.boolean().optional(),lastPromptedAt:promptedAtSchema.optional(),lastPluginAutoUpdateAttemptedAt:promptedAtSchema.optional(),lastPluginAutoUpdateAttemptedKey:z.string().optional()});async function fileExists(filePath){try{return await access2(filePath),!0}catch{return!1}}async function readPrefs(client){return await client.maybeReadConfig(PREFS_FILE,agentPreferencesSchema)??{}}async function writePrefs(client,prefs){try{await client.writeConfig(PREFS_FILE,agentPreferencesSchema,prefs)}catch{}}function encodeClaudeProjectDir(projectPath){return projectPath.replace(/[^A-Za-z0-9]/g,"-")}async function projectHasUsedClaudeCode(cwd){let home=homedir(),projectsDir=join3(home,".claude","projects"),dir=resolve(cwd);for(;dir!==home;){if(await fileExists(join3(projectsDir,encodeClaudeProjectDir(dir))))return!0;let parent=dirname3(dir);if(parent===dir)break;dir=parent}return!1}async function getPluginTargets(agentName,cwd){let targetForAgent=getPluginTargetForAgent(agentName);return targetForAgent?[targetForAgent]:agentName?[]:cwd&&await projectHasUsedClaudeCode(cwd)?["claude-code"]:[]}async function readClaudeInstalledPluginsFromRegistry(){try{let raw=await readFile3(getClaudeInstalledPluginsRegistryPath(),"utf-8"),plugins=JSON.parse(raw)?.plugins??{},entries=[];for(let[id,installs]of Object.entries(plugins))if(Array.isArray(installs))for(let install of installs)!install||typeof install!="object"||entries.push({id,...install,enabled:!0});return entries}catch{return[]}}function getClaudeInstalledPluginsRegistryPath(){return join3(homedir(),".claude","plugins","installed_plugins.json")}async function markStaleClaudePluginInstalls(plugins){return Promise.all(plugins.map(async plugin=>plugin.installPath&&!await fileExists(plugin.installPath)?{...plugin,stale:!0}:plugin))}async function removeClaudePluginFromRegistry(pluginId){try{let registryPath=getClaudeInstalledPluginsRegistryPath(),raw=await readFile3(registryPath,"utf-8"),data=JSON.parse(raw);return!data.plugins||!(pluginId in data.plugins)?!1:(delete data.plugins[pluginId],await writeFile3(registryPath,`${JSON.stringify(data,null,2)}
|
|
29
|
+
`,"utf-8"),!0)}catch(err){return output_manager_default.debug(`Failed to remove Claude plugin registry entry: ${err}`),!1}}async function isPluginInstalledForTarget(target){return target==="claude-code"?(await getClaudePluginStatus()).state==="official-only":!1}async function confirm(client,message){return client.nonInteractive||!client.stdin.isTTY?!1:client.input.confirm(message,!0)}function isSameDay(left,right){return left.getFullYear()===right.getFullYear()&&left.getMonth()===right.getMonth()&&left.getDate()===right.getDate()}function wasPromptedToday(prefs){return prefs.lastPromptedAt?isSameDay(prefs.lastPromptedAt,new Date):!1}function wasPluginAutoUpdateAttemptedToday(prefs,attemptKey){return prefs.lastPluginAutoUpdateAttemptedKey===attemptKey&&!!prefs.lastPluginAutoUpdateAttemptedAt&&isSameDay(prefs.lastPluginAutoUpdateAttemptedAt,new Date)}async function markPromptedToday(client,prefs){prefs.lastPromptedAt=new Date,await writePrefs(client,prefs)}function markPluginAutoUpdateAttempted(prefs,attemptKey){attemptKey&&(prefs.lastPluginAutoUpdateAttemptedAt=new Date,prefs.lastPluginAutoUpdateAttemptedKey=attemptKey)}async function runCommand(command,args){return await new Promise(resolve2=>{let child=spawn(command,args,{stdio:"pipe"}),stdout="",stderr="";child.stdout.on("data",chunk=>{stdout+=chunk.toString()}),child.stderr.on("data",chunk=>{stderr+=chunk.toString()}),child.on("close",code=>{resolve2({exitCode:code??1,stdout,stderr})}),child.on("error",err=>{resolve2({exitCode:1,stdout,stderr:`${stderr}${String(err)}`})})})}async function getClaudeInstalledPlugins(){let result=await runCommand("claude",["plugins","list","--json"]);if(result.exitCode===0)try{let parsed=JSON.parse(result.stdout);if(Array.isArray(parsed))return markStaleClaudePluginInstalls(parsed)}catch(err){output_manager_default.debug(`Failed to parse Claude plugin list JSON: ${err}`)}else result.stderr.trim().length>0&&output_manager_default.debug(`Failed to run 'claude plugins list --json': ${result.stderr}`);return markStaleClaudePluginInstalls(await readClaudeInstalledPluginsFromRegistry())}async function fetchLatestVercelPluginVersion(){try{let response=await fetch(VERCEL_PLUGIN_VERSION_URL);if(!response.ok){output_manager_default.debug(`Failed to fetch latest Vercel plugin version: ${response.status}`);return}let manifest=await response.json();return typeof manifest.version=="string"?manifest.version:void 0}catch(err){output_manager_default.debug(`Failed to fetch latest Vercel plugin version: ${err}`);return}}function comparePluginVersions(a,b){if(!a&&!b)return 0;if(!a)return-1;if(!b)return 1;let parse2=value=>value.split(".").map(part=>Number.parseInt(part,10)||0),left=parse2(a),right=parse2(b),maxLength=Math.max(left.length,right.length);for(let i=0;i<maxLength;i++){let l=left[i]??0,r=right[i]??0;if(l>r)return 1;if(l<r)return-1}return 0}function buildClaudePluginStatus(installedPlugins,latestVersion){let legacy=installedPlugins.find(plugin=>plugin.id===CLAUDE_LEGACY_PLUGIN_ID),official=installedPlugins.find(plugin=>plugin.id===CLAUDE_OFFICIAL_PLUGIN_ID),state="none";return legacy&&official?state="both":legacy?state="legacy-only":official&&(state="official-only"),{state,legacy,official,latestVersion}}function buildClaudePluginMigrationPlan(status){let plan={installOfficial:!1,updateOfficial:!1,removeLegacy:!1,removeLegacyMarketplace:!1};switch(status.state){case"none":plan.installOfficial=!0;break;case"legacy-only":plan.installOfficial=!0,plan.removeLegacy=!0,plan.removeLegacyMarketplace=!0;break;case"both":plan.removeLegacy=!0,plan.removeLegacyMarketplace=!0;break;case"official-only":break}return status.official?.version&&status.latestVersion&&comparePluginVersions(status.official.version,status.latestVersion)<0&&(plan.updateOfficial=!0),plan}function hasClaudeMigrationActions(plan){return plan.installOfficial||plan.updateOfficial||plan.removeLegacy||plan.removeLegacyMarketplace}function getClaudeAutoUpdateAttemptKey(status,plan){return[status.state,status.legacy?.version??"none",status.official?.version??"none",status.latestVersion??"unknown",plan.installOfficial?"install":"",plan.updateOfficial?"update":"",plan.removeLegacy?"remove-legacy":"",plan.removeLegacyMarketplace?"remove-marketplace":""].join(":")}function buildClaudePromptCopy(status,plan){if(plan.installOfficial&&status.state==="none")return{message:"Vercel Plugin for Claude Code is not installed.",confirm:"Would you like to install it now?"};if(plan.installOfficial&&status.state==="legacy-only")return{message:"Update available for Vercel Plugin for Claude Code (legacy -> official).",confirm:"Would you like to update now?"};if(status.state==="both"&&plan.removeLegacy)return{message:"Vercel Plugin for Claude Code has a legacy install to clean up.",confirm:"Would you like to update now?"};if(plan.updateOfficial){let fromVersion=status.official?.version,toVersion=status.latestVersion;return{message:`Update available for Vercel Plugin for Claude Code${fromVersion&&toVersion?` (v${fromVersion} -> v${toVersion})`:""}.`,confirm:"Would you like to update now?"}}return{message:"The Vercel plugin needs attention in Claude Code before your agent harness is fully up to date.",confirm:"Apply the Vercel plugin changes for Claude Code?"}}async function runClaudeCommand(spinnerMessage,successMessage,failureMessage,args,options){output_manager_default.spinner(spinnerMessage);let result=await runCommand("claude",args);return output_manager_default.stopSpinner(),result.exitCode===0?(options?.quietSuccess||output_manager_default.success(successMessage),!0):(output_manager_default.warn(failureMessage),output_manager_default.debug(`Claude command failed: claude ${args.join(" ")}
|
|
30
|
+
${result.stderr||result.stdout}`),!1)}async function removeStaleLegacyClaudePlugin(removeMarketplace){output_manager_default.spinner("Removing the stale legacy Vercel Claude plugin...");let removedRegistryEntry=await removeClaudePluginFromRegistry(CLAUDE_LEGACY_PLUGIN_ID);if(output_manager_default.stopSpinner(),!removedRegistryEntry)return output_manager_default.warn("Could not remove the stale legacy Vercel Claude plugin registry entry."),{removedPlugin:!1,complete:!1};if(output_manager_default.success("Removed the stale legacy Vercel Claude plugin"),removeMarketplace){let removedMarketplace=await runClaudeCommand("Removing the legacy Vercel marketplace...","Removed the legacy Vercel marketplace","Removed the stale legacy Vercel plugin, but could not remove the legacy marketplace.",["plugins","marketplace","remove","vercel"],{quietSuccess:!0});return removedMarketplace||output_manager_default.log("Cleanup command: claude plugins marketplace remove vercel"),{removedPlugin:!0,complete:removedMarketplace}}return{removedPlugin:!0,complete:!0}}async function runClaudeMigration(plan){let removedStaleLegacy=!1,complete=!0;if(plan.removeLegacy&&(await getClaudePluginStatus()).legacy?.stale){let cleanup=await removeStaleLegacyClaudePlugin(plan.removeLegacyMarketplace);removedStaleLegacy=cleanup.removedPlugin,complete=cleanup.complete}if(plan.installOfficial){if(!await runClaudeCommand("Installing the official Vercel Claude plugin...","Updated the Vercel plugin","Failed to install the official Vercel Claude plugin.",["plugins","install",CLAUDE_OFFICIAL_PLUGIN_ID]))return!1}else if(plan.updateOfficial&&!await runClaudeCommand("Updating the official Vercel Claude plugin...","Updated the Vercel plugin","Failed to update the official Vercel Claude plugin.",["plugins","update",CLAUDE_OFFICIAL_PLUGIN_ID]))return!1;let statusAfterInstall=await getClaudePluginStatus();return statusAfterInstall.official?plan.removeLegacy&&statusAfterInstall.legacy&&!await runClaudeCommand("Removing the legacy Vercel Claude plugin...","Removed the legacy Vercel Claude plugin","Installed the official Vercel Claude plugin, but could not remove the legacy install.",["plugins","uninstall",CLAUDE_LEGACY_PLUGIN_ID],{quietSuccess:!0})?(output_manager_default.log(`Cleanup command: claude plugins uninstall ${CLAUDE_LEGACY_PLUGIN_ID}`),!1):plan.removeLegacyMarketplace&&!removedStaleLegacy&&!(await getClaudePluginStatus()).legacy&&!await runClaudeCommand("Removing the legacy Vercel marketplace...","Removed the legacy Vercel marketplace","Removed the legacy Vercel plugin, but could not remove the legacy marketplace.",["plugins","marketplace","remove","vercel"],{quietSuccess:!0})?(output_manager_default.log("Cleanup command: claude plugins marketplace remove vercel"),!1):complete:(output_manager_default.warn("Skipping Claude cleanup because the official Vercel plugin is not installed."),!1)}async function getClaudePluginStatus(){let[installedPlugins,latestVersion]=await Promise.all([getClaudeInstalledPlugins(),fetchLatestVercelPluginVersion()]);return buildClaudePluginStatus(installedPlugins,latestVersion)}async function applyPluginActions(targets,claudePlan){for(let target of targets)target==="claude-code"&&claudePlan?await runClaudeMigration(claudePlan):output_manager_default.debug(`Skipping unsupported plugin target: ${target}`)}function describeClaudePlan(plan){let actions=[];return plan.installOfficial&&actions.push("install the official plugin"),plan.updateOfficial&&actions.push("update the official plugin"),plan.removeLegacy&&actions.push("remove the legacy plugin"),plan.removeLegacyMarketplace&&actions.push("remove the legacy marketplace"),actions.join(", ")}async function setupVercelPlugin(client,opts){if(!await claudeCode.detect(opts.home))return{status:"not_detected",message:"Claude Code was not detected on this machine."};let status=await getClaudePluginStatus();if(status.official?.stale)return{status:"failed",message:"The installed Vercel plugin files are missing. Run `claude plugins uninstall vercel@claude-plugins-official`, then run `vercel setup --plugin --agent claude-code` to reinstall it."};let plan=buildClaudePluginMigrationPlan(status);if(!hasClaudeMigrationActions(plan))return{status:"up_to_date",message:`Vercel plugin for Claude Code is installed${status.official?.version?` (v${status.official.version})`:""}.`};let copy=buildClaudePromptCopy(status,plan);if(opts.dryRun)return{status:"dry_run",message:`${copy.message} Setup would ${describeClaudePlan(plan)}.`,action:plan.installOfficial?"install":"update"};let prefs=await readPrefs(client);if(!opts.yes){if(!opts.canPrompt)return{status:"confirmation_required",message:`${copy.message} Re-run with --yes to apply it.`};output_manager_default.print(` ${copy.message}
|
|
31
|
+
`);let accepted=await client.input.confirm(copy.confirm,!0);if(await markPromptedToday(client,prefs),!accepted)return prefs.pluginDeclined=!0,prefs.pluginAutoUpdate=!1,await writePrefs(client,prefs),{status:"declined",message:"Skipped the Vercel plugin for Claude Code."}}prefs.pluginDeclined=!1,prefs.pluginAutoUpdate=!0,await writePrefs(client,prefs);let migrated=await runClaudeMigration(plan),after=await getClaudePluginStatus();if(!after.official)return{status:"failed",message:"Failed to install the Vercel plugin for Claude Code. Run `claude plugins install vercel@claude-plugins-official` to install it manually."};let remaining=buildClaudePluginMigrationPlan({...after,latestVersion:status.latestVersion});if(!migrated||after.official.stale||hasClaudeMigrationActions(remaining))return{status:"failed",message:"Failed to complete Vercel plugin setup for Claude Code. Re-run `vercel setup --plugin --agent claude-code --yes` to retry."};let version=after.official.version?` v${after.official.version}`:"";return{status:plan.installOfficial?"installed":"updated",message:`${plan.installOfficial?"Installed":"Updated"} the Vercel plugin for Claude Code${version}.`}}async function autoInstallVercelPlugin(client,options){try{let prefs=await readPrefs(client),applyMode=options?.mode==="apply";if(!prefs.pluginDeclined||prefs.pluginAutoUpdate||applyMode){let targets=await getPluginTargets(client.agentName,client.cwd),uninstalledTargets=[],claudeStatus=targets.includes("claude-code")?await getClaudePluginStatus():void 0,claudePlan=claudeStatus?buildClaudePluginMigrationPlan(claudeStatus):void 0,claudeAutoUpdateAttemptKey=claudeStatus&&claudePlan?getClaudeAutoUpdateAttemptKey(claudeStatus,claudePlan):void 0;for(let target of targets){if(target==="claude-code"){claudePlan&&hasClaudeMigrationActions(claudePlan)&&uninstalledTargets.push(target);continue}await isPluginInstalledForTarget(target)||uninstalledTargets.push(target)}if(uninstalledTargets.length>0){if(prefs.pluginAutoUpdate){if(claudeAutoUpdateAttemptKey&&wasPluginAutoUpdateAttemptedToday(prefs,claudeAutoUpdateAttemptKey))return;prefs.pluginDeclined=!1,markPluginAutoUpdateAttempted(prefs,claudeAutoUpdateAttemptKey),await writePrefs(client,prefs),await applyPluginActions(uninstalledTargets,claudePlan);return}if(!applyMode&&wasPromptedToday(prefs))return;if(applyMode){prefs.pluginDeclined=!1,prefs.pluginAutoUpdate=!0,await writePrefs(client,prefs),await applyPluginActions(uninstalledTargets,claudePlan);return}let promptMessages=[],confirmMessage="Install the Vercel plugin?";if(uninstalledTargets.includes("claude-code")&&claudeStatus&&claudePlan){let claudePrompt=buildClaudePromptCopy(claudeStatus,claudePlan);promptMessages.push(claudePrompt.message),confirmMessage=claudePrompt.confirm}let promptMessage=promptMessages.join(" ").trim();promptMessage&&output_manager_default.log(promptMessage);let accepted=await confirm(client,confirmMessage);await markPromptedToday(client,prefs),accepted?(prefs.pluginDeclined=!1,prefs.pluginAutoUpdate=!0,await writePrefs(client,prefs),await applyPluginActions(uninstalledTargets,claudePlan)):(prefs.pluginDeclined=!0,prefs.pluginAutoUpdate=!1,await writePrefs(client,prefs))}}}catch(err){output_manager_default.debug(`Auto-install agent tooling failed: ${err}`)}}export{pathExists,isFile,isSymlink,readFileOrNull,parseJsonObjectOrNull,mergeJson,mergeJsonc,mergeToml,MANAGED_BLOCK_START,MANAGED_BLOCK_END,upsertManagedBlock,publishNoClobber,ensureMode,backupFile,writeConfigFile,GATEWAY_ANTHROPIC_BASE_URL,GATEWAY_CODING_AGENT_BASE_URL,GATEWAY_CURSOR_BASE_URL,GATEWAY_CODEX_BASE_URL,GATEWAY_API_KEY_ENV,GATEWAY_DEFAULT_MODEL,KEY_PLACEHOLDER,resolveGatewayBaseUrl,maskSecret,claudeCode,setupVercelPlugin,autoInstallVercelPlugin};
|
|
@@ -4,4 +4,4 @@ import { dirname as __dirname_ } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
const __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
const __dirname = __dirname_(__filename);
|
|
7
|
-
import{printProjectNotFoundError}from"./chunk-
|
|
7
|
+
import{printProjectNotFoundError}from"./chunk-GR3DLKYP.js";import{param}from"./chunk-SXUEGVWB.js";import{detectExplicitScope}from"./chunk-32QBGZ2Z.js";import{getLinkedProject,resolveProjectCwd}from"./chunk-64NJHVA3.js";import{buildCommandWithYes,outputActionRequired}from"./chunk-BX5KDMLT.js";import{getCommandName,getCommandNamePlain}from"./chunk-FI772UVH.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";var parseEnv=env=>{if(!env)return{};if(typeof env=="string"&&(env=[env]),Array.isArray(env)){let startingDict={};return env.reduce((o,e)=>{let key,value,equalsSign=e.indexOf("=");return equalsSign===-1?key=e:(key=e.slice(0,equalsSign),value=e.slice(equalsSign+1)),o[key]=value,o},startingDict)}return env};async function ensureLink(commandName,client,cwd,opts={}){cwd=await resolveProjectCwd(cwd);let link=opts.link,nonInteractive=opts.nonInteractive??client.nonInteractive??!1;if(opts.nonInteractive=nonInteractive,link||(opts.forceDelete?link={status:"not_linked",org:null,project:null}:link=await getLinkedProject(client,{cwd,projectName:opts.projectName,projectNameIsExplicit:!!(opts.projectName&&opts.failIfNotFound),scopeIsExplicit:detectExplicitScope(client),allowOwnerLookupFallback:opts.allowOwnerLookupFallback,skipRemoteLookup:opts.skipRemoteLookup}),opts.link=link),link.status==="linked"&&opts.forceDelete||link.status==="not_linked"){if(link.status==="not_linked"&&opts.failIfNotFound&&opts.projectName)return await printProjectNotFoundError(client,opts.projectName,commandName,link.orgId),1;if(link.status==="not_linked"&&opts.requireExistingLink)return output_manager_default.error(`Project is not linked. Run ${getCommandName("link")} first.`),1;let{default:setupAndLink}=await import("./setup-and-link-O5QSQ5K2.js");if(link=await setupAndLink(client,cwd,opts),link.status==="not_linked")return 0}return link.status==="error"?(link.reason==="HEADLESS"&&(nonInteractive?outputActionRequired(client,{status:"action_required",reason:"confirmation_required",message:`Command ${getCommandNamePlain(commandName)} requires confirmation. Use option --yes to confirm.`,next:[{command:buildCommandWithYes(client.argv),when:"Confirm and run"}]},link.exitCode):output_manager_default.error(`Command ${getCommandName(commandName)} requires confirmation. Use option ${param("--yes")} to confirm.`)),nonInteractive&&process.exit(link.exitCode),link.exitCode):link}export{parseEnv,ensureLink};
|
|
@@ -4,7 +4,7 @@ import { dirname as __dirname_ } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
const __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
const __dirname = __dirname_(__filename);
|
|
7
|
-
import{humanizeReference,renderAlertTable}from"./chunk-7PNYOSDU.js";import{formatDate}from"./chunk-6PFC3KWQ.js";import{truncateEnd,truncateMiddle}from"./chunk-MBL6TXEJ.js";import{buildCommandWithGlobalFlags,quoteArg}from"./chunk-
|
|
7
|
+
import{humanizeReference,renderAlertTable}from"./chunk-7PNYOSDU.js";import{formatDate}from"./chunk-6PFC3KWQ.js";import{truncateEnd,truncateMiddle}from"./chunk-MBL6TXEJ.js";import{buildCommandWithGlobalFlags,quoteArg}from"./chunk-BX5KDMLT.js";import{printAlignedLabel}from"./chunk-YMM3VY3J.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";import{require_source}from"./chunk-U7KCDTCH.js";import{__toESM}from"./chunk-6L236MNA.js";var import_chalk=__toESM(require_source(),1);function formatBoolean(value){return value?"yes":"no"}function formatOperator(operator){return{gt:">",gte:">=",lt:"<",lte:"<="}[operator]??operator}function formatPublicRuleScope(rule){let scope=rule.ruleScope;return scope.type==="all"?"all projects":scope.type==="project"?`project: ${scope.projectId}`:`${scope.type}: ${scope.projectIds.join(", ")}`}function formatMetricSelection(metric){let modifiers=[metric.per?`per ${metric.per}`:void 0,metric.normalize?`normalize ${metric.normalize}`:void 0,metric.dimensions?.length?`dimensions ${metric.dimensions.join(", ")}`:void 0].filter(Boolean);return`${metric.aggregation} ${metric.metric}${modifiers.length?` (${modifiers.join("; ")})`:""}`}function formatCustomTrigger(trigger){let minimum=trigger.minimum?`; minimum ${trigger.minimum.output} >= ${trigger.minimum.threshold}`:"";return trigger.type==="anomaly"?`${trigger.output} anomaly at ${trigger.standardDeviations} standard deviations${minimum}`:`${trigger.output} ${formatOperator(trigger.operator)} ${trigger.threshold}${minimum}`}function formatCustomCondition(rule){if(!rule.querySupported)return"Query unavailable via API";let query=rule.evaluation.query,output=query.outputs[0];return`${query.formulas?.[output]?`${output} = ${query.formulas[output]}`:query.metrics[output]?formatMetricSelection(query.metrics[output]):output}; ${formatCustomTrigger(rule.trigger)}; ${rule.evaluation.window}`}function formatBuiltInCondition(rule){return`${rule.triggers.mode==="all"?"all triggers":rule.triggers.items.map(trigger=>humanizeReference(trigger.type)).join(", ")}; minimum ${rule.matchMinimumSeverityLevel}`}function formatRuleCondition(rule){return rule.type==="built-in"?formatBuiltInCondition(rule):formatCustomCondition(rule)}function printRules(rules){let rows=[["Name","Rule ID","Type","Scope","Condition"].map(header=>import_chalk.default.cyan(header)),...rules.map(rule=>[import_chalk.default.bold(truncateEnd(rule.name,36)),import_chalk.default.dim(rule.id),rule.isDefault?`${rule.type} (default)`:rule.type,truncateMiddle(formatPublicRuleScope(rule),38),truncateEnd(formatRuleCondition(rule),72)])];output_manager_default.print(`
|
|
8
8
|
${renderAlertTable(rows,2)}
|
|
9
9
|
`)}function commonRows(rule){return[["Name",rule.name],["Rule ID",rule.id],["Type",rule.type],["Scope",formatPublicRuleScope(rule)],["Default",formatBoolean(rule.isDefault)],...rule.createdAt?[["Created",formatDate(rule.createdAt)]]:[],...rule.updatedAt?[["Updated",formatDate(rule.updatedAt)]]:[]]}function notificationRows(rule){return[["Team owner notifications",formatBoolean(rule.notificationSettings.enableTeamOwnerNotifications)],...rule.notificationSettings.incidentIoRoutingKey?[["Incident.io routing key",rule.notificationSettings.incidentIoRoutingKey]]:[]]}function printBuiltInRule(rule){output_manager_default.print(`${import_chalk.default.cyan("Built-in conditions")}
|
|
10
10
|
|
|
@@ -4,4 +4,4 @@ import { dirname as __dirname_ } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
const __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
const __dirname = __dirname_(__filename);
|
|
7
|
-
import{quoteArg}from"./chunk-
|
|
7
|
+
import{quoteArg}from"./chunk-BX5KDMLT.js";import{arg_common_default,stripSensitiveAuthArgs}from"./chunk-JAJW3P42.js";import{packageName}from"./chunk-FI772UVH.js";import{__commonJS,__toESM}from"./chunk-6L236MNA.js";var require_arg=__commonJS({"../../node_modules/.pnpm/arg@5.0.0/node_modules/arg/index.js"(exports,module){var flagSymbol=Symbol("arg flag"),ArgError=class _ArgError extends Error{constructor(msg,code){super(msg),this.name="ArgError",this.code=code,Object.setPrototypeOf(this,_ArgError.prototype)}};function arg2(opts,{argv=process.argv.slice(2),permissive=!1,stopAtPositional=!1}={}){if(!opts)throw new ArgError("argument specification object is required","ARG_CONFIG_NO_SPEC");let result={_:[]},aliases={},handlers={};for(let key of Object.keys(opts)){if(!key)throw new ArgError("argument key cannot be an empty string","ARG_CONFIG_EMPTY_KEY");if(key[0]!=="-")throw new ArgError(`argument key must start with '-' but found: '${key}'`,"ARG_CONFIG_NONOPT_KEY");if(key.length===1)throw new ArgError(`argument key must have a name; singular '-' keys are not allowed: ${key}`,"ARG_CONFIG_NONAME_KEY");if(typeof opts[key]=="string"){aliases[key]=opts[key];continue}let type=opts[key],isFlag=!1;if(Array.isArray(type)&&type.length===1&&typeof type[0]=="function"){let[fn]=type;type=(value,name,prev=[])=>(prev.push(fn(value,name,prev[prev.length-1])),prev),isFlag=fn===Boolean||fn[flagSymbol]===!0}else if(typeof type=="function")isFlag=type===Boolean||type[flagSymbol]===!0;else throw new ArgError(`type missing or not a function or valid array type: ${key}`,"ARG_CONFIG_VAD_TYPE");if(key[1]!=="-"&&key.length>2)throw new ArgError(`short argument keys (with a single hyphen) must have only one character: ${key}`,"ARG_CONFIG_SHORTOPT_TOOLONG");handlers[key]=[type,isFlag]}for(let i=0,len=argv.length;i<len;i++){let wholeArg=argv[i];if(stopAtPositional&&result._.length>0){result._=result._.concat(argv.slice(i));break}if(wholeArg==="--"){result._=result._.concat(argv.slice(i+1));break}if(wholeArg.length>1&&wholeArg[0]==="-"){let separatedArguments=wholeArg[1]==="-"||wholeArg.length===2?[wholeArg]:wholeArg.slice(1).split("").map(a=>`-${a}`);for(let j=0;j<separatedArguments.length;j++){let arg3=separatedArguments[j],[originalArgName,argStr]=arg3[1]==="-"?arg3.split(/=(.*)/,2):[arg3,void 0],argName=originalArgName;for(;argName in aliases;)argName=aliases[argName];if(!(argName in handlers))if(permissive){result._.push(arg3);continue}else throw new ArgError(`unknown or unexpected option: ${originalArgName}`,"ARG_UNKNOWN_OPTION");let[type,isFlag]=handlers[argName];if(!isFlag&&j+1<separatedArguments.length)throw new ArgError(`option requires argument (but was followed by another short argument): ${originalArgName}`,"ARG_MISSING_REQUIRED_SHORTARG");if(isFlag)result[argName]=type(!0,argName,result[argName]);else if(argStr===void 0){if(argv.length<i+2||argv[i+1].length>1&&argv[i+1][0]==="-"&&!(argv[i+1].match(/^-?\d*(\.(?=\d))?\d*$/)&&(type===Number||typeof BigInt<"u"&&type===BigInt))){let extended=originalArgName===argName?"":` (alias for ${argName})`;throw new ArgError(`option requires argument: ${originalArgName}${extended}`,"ARG_MISSING_REQUIRED_LONGARG")}result[argName]=type(argv[i+1],argName,result[argName]),++i}else result[argName]=type(argStr,argName,result[argName])}}else result._.push(wholeArg)}return result}arg2.flag=fn=>(fn[flagSymbol]=!0,fn);arg2.COUNT=arg2.flag((v,name,existingCount)=>(existingCount||0)+1);arg2.ArgError=ArgError;module.exports=arg2}});var import_arg=__toESM(require_arg(),1);function suggestCorrection(input,choices){if(input.replace(/^-+/,"").length<3||choices.includes(input))return;let matches=[...new Set(choices)].filter(choice=>{if(Math.abs(input.length-choice.length)>1)return!1;let i=0;for(;i<input.length&&input[i]===choice[i];)i++;return input.length===choice.length?input.slice(i+1)===choice.slice(i+1)||input[i]===choice[i+1]&&input[i+1]===choice[i]&&input.slice(i+2)===choice.slice(i+2):input.length>choice.length?input.slice(i+1)===choice.slice(i):input.slice(i)===choice.slice(i+1)});return matches.length===1?matches[0]:void 0}var SAFE_VALUE_FLAGS=new Set(["--cwd","--scope","--team","-S","-T","--project","-p","--format","--environment","--since","--until","--limit"]),READ_COMMANDS=new Set(["inspect","list","ls","schema","whoami"]);function buildCorrectedCommand(argv,from,to,flagsSpecification={}){let corrected=argv.slice(2),spec={...arg_common_default(),...flagsSpecification},valuelessFlags=new Set,takesValue=new Set;for(let[name,value]of Object.entries(spec))((typeof value=="string"?spec[value]:value)===Boolean?valuelessFlags:takesValue).add(name);for(let i=0;i<corrected.length;i++){let value=corrected[i];if(value==="--")break;if(value===from||value.startsWith(`${from}=`)){corrected[i]=to+value.slice(from.length);break}takesValue.has(value)&&i++}let args=stripSensitiveAuthArgs(corrected).filter(arg2=>!/^-t[^-=]/.test(arg2)),out=[],positionals=0,readCommand=!1;for(let i=0;i<args.length;i++){let value=args[i];if(value==="--"){out.push("--","<argument>");break}if(value.startsWith("-")){if(/^-[A-Za-z][^=].+/.test(value)&&!value.startsWith("--")){let name2=value.slice(0,2);out.push(name2,SAFE_VALUE_FLAGS.has(name2)?value.slice(2):"<value>");continue}let equals=value.indexOf("="),name=equals<0?value:value.slice(0,equals);equals>=0?out.push(`${name}=${SAFE_VALUE_FLAGS.has(name)||valuelessFlags.has(name)&&/^(true|false)$/.test(value.slice(equals+1))?value.slice(equals+1):"<value>"}`):(out.push(name),!valuelessFlags.has(name)&&i+1<args.length&&(takesValue.has(name)||!args[i+1].startsWith("-"))&&(i++,out.push(SAFE_VALUE_FLAGS.has(name)?args[i]:"<value>")))}else positionals++,positionals<=2&&(readCommand||=READ_COMMANDS.has(value)),out.push(positionals<=2||readCommand?value:"<argument>")}return[packageName,...out].map(quoteArg).join(" ")}var argumentErrors=new WeakSet;function isArgumentError(error){return error instanceof Error&&argumentErrors.has(error)}function parseWithSuggestions(args,spec,options){try{return(0,import_arg.default)(spec,{...options,argv:args})}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ARG_UNKNOWN_OPTION"){let err=error,option=/unknown or unexpected option: (--?[A-Za-z0-9-]+)$/.exec(err.message)?.[1];option&&(argumentErrors.add(err),err.invalidOption=option,err.allowedOptions=Object.keys(spec).filter(name=>name.startsWith("--")).sort(),err.suggestedOption=suggestCorrection(option,err.allowedOptions),err.flagsSpecification=spec)}throw error}}function getArgs(argv,argsOptions,argOptions={}){return parseWithSuggestions(argv,Object.assign({},arg_common_default(),argsOptions),argOptions)}function parseArguments(args,flagsSpecification,parserOptions={}){let{_:positional,...rest}=parseWithSuggestions(args,Object.assign({},arg_common_default(),flagsSpecification),parserOptions);return{args:positional,flags:rest}}export{suggestCorrection,buildCorrectedCommand,isArgumentError,getArgs,parseArguments};
|
|
@@ -4,6 +4,6 @@ import { dirname as __dirname_ } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
const __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
const __dirname = __dirname_(__filename);
|
|
7
|
-
import{buildCorrectedCommand,isArgumentError}from"./chunk-
|
|
7
|
+
import{buildCorrectedCommand,isArgumentError}from"./chunk-T4AZ3U7O.js";import{getErrorRecovery,shouldEmitNonInteractiveCommandError,trackAgentError,writeAgentError}from"./chunk-BX5KDMLT.js";import{InvalidToken,parseRetryAfterHeaderAsMillis,require_bytes}from"./chunk-LKI6FRNM.js";import{getCommandName}from"./chunk-FI772UVH.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";import{pkg_default}from"./chunk-AVSPFBLM.js";import{require_source}from"./chunk-U7KCDTCH.js";import{__toESM}from"./chunk-6L236MNA.js";var import_chalk=__toESM(require_source(),1);var import_bytes=__toESM(require_bytes(),1);async function responseError(res,fallbackMessage=null,parsedBody={}){let message="",bodyError;if(res.status>=400&&res.status<500){let body;try{body=await res.json()}catch{body=parsedBody}bodyError=body.error||body.err||{},message=bodyError.message}message||(message=fallbackMessage===null?"Response Error":fallbackMessage);let err=new Error(`${message} (${res.status})`);if(err.status=res.status,err.serverMessage=message,bodyError)for(let field of Object.keys(bodyError))field!=="message"&&(err[field]=bodyError[field]);if(res.status===429||res.status===503){let parsed=parseRetryAfterHeaderAsMillis(res.headers.get("Retry-After"));err.retryAfterMs=parsed??(res.status===429?0:void 0)}return err}function toEnumerableError(err){let enumerable={};enumerable.name=err.name;for(let key of Object.getOwnPropertyNames(err))enumerable[key]=err[key];return enumerable}function printError(error2,client,options={}){typeof error2=="string"&&(error2=new Error(error2));let apiError=error2,{message,stack,status,code,sizeLimit}=apiError,authenticationError=error2 instanceof InvalidToken||status===401,displayMessage=authenticationError?new InvalidToken(client?.authConfig.tokenSource??(error2 instanceof InvalidToken?error2.tokenSource:void 0)).message:apiError.serverMessage||message,argumentError=isArgumentError(error2)?error2:void 0,suggestion=argumentError?.suggestedOption&&argumentError.invalidOption,correction=suggestion&&client&&argumentError?buildCorrectedCommand(client.argv,argumentError.invalidOption,argumentError.suggestedOption,argumentError.flagsSpecification):void 0,recovery=getErrorRecovery(apiError,client),reason=authenticationError?"not_authorized":status===403?"forbidden":status===402?"payment_required":status===401?"not_authorized":status===429?"rate_limited":code==="ARG_UNKNOWN_OPTION"?"invalid_arguments":"api_error",hint=argumentError?.allowedOptions?`Vercel CLI ${pkg_default.version} accepts: ${argumentError.allowedOptions.join(", ")}.${suggestion?` Did you mean ${argumentError.suggestedOption}?`:""}`:recovery.hint;if(client&&(status||authenticationError||options.json||argumentError?.allowedOptions)){let payload={...recovery,status:"error",reason,message:displayMessage,hint,...argumentError?.allowedOptions&&{allowedOptions:argumentError.allowedOptions,suggestedOption:argumentError.suggestedOption,cliVersion:pkg_default.version},...correction&&{next:[{command:correction,when:correction.includes("<")?"Replace placeholders with the intended values, then run the corrected command":"Run the corrected command"}]}};if(options.json||shouldEmitNonInteractiveCommandError(client)){output_manager_default.stopSpinner(),writeAgentError(client,payload);return}trackAgentError(client,payload)}if(authenticationError){output_manager_default.stopSpinner(),output_manager_default.fatal(displayMessage);return}if(hint){output_manager_default.stopSpinner(),output_manager_default.fatal(apiError.serverMessage||message||"The request failed."),output_manager_default.print(` ${hint}
|
|
8
8
|
`),correction&&output_manager_default.print(` ${correction}
|
|
9
9
|
`);return}output_manager_default.debug(`handling error: ${stack}`),message!=="User force closed the prompt with 0 null"&&(status===403?output_manager_default.error(message||`Authentication error. Run ${getCommandName("login")} to log-in again.`):status===429?output_manager_default.error(message):code==="size_limit_exceeded"?output_manager_default.error(`File size limit exceeded (${(0,import_bytes.default)(sizeLimit)})`):message?output_manager_default.prettyError(apiError):status===500?output_manager_default.error("Unexpected server error. Please retry."):code==="USER_ABORT"?output_manager_default.log("Canceled"):output_manager_default.error(`Unexpected error. Please try again later. (${message})`))}export{responseError,toEnumerableError,printError};
|
|
@@ -4,4 +4,4 @@ import { dirname as __dirname_ } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
const __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
const __dirname = __dirname_(__filename);
|
|
7
|
-
import{require_json_parse_better_errors}from"./chunk-N6CNMMSZ.js";import{require_lib}from"./chunk-
|
|
7
|
+
import{require_json_parse_better_errors}from"./chunk-N6CNMMSZ.js";import{require_lib}from"./chunk-64NJHVA3.js";import{CantParseJSONFile}from"./chunk-LKI6FRNM.js";import{require_dist}from"./chunk-QGIQK47P.js";import{__toESM}from"./chunk-6L236MNA.js";var import_fs_extra=__toESM(require_lib(),1);var import_json_parse_better_errors=__toESM(require_json_parse_better_errors(),1),import_error_utils=__toESM(require_dist(),1);async function readJSONFile(file){let content=await readFileSafe(file);if(content===null)return content;try{return(0,import_json_parse_better_errors.default)(content)}catch(error){return new CantParseJSONFile(file,(0,import_error_utils.errorToString)(error))}}async function readFileSafe(file){try{return await import_fs_extra.default.readFile(file,"utf8")}catch{return null}}export{readJSONFile};
|