@visulima/vis 1.0.0-alpha.15 → 1.0.0-alpha.16
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/CHANGELOG.md +49 -0
- package/LICENSE.md +44 -233
- package/dist/bin.js +1 -1
- package/dist/config/index.d.ts +121 -94
- package/dist/config/index.js +1 -1
- package/dist/packem_chunks/bin.js +271 -271
- package/dist/packem_chunks/config.js +18 -0
- package/dist/packem_chunks/fix.js +1 -1
- package/dist/packem_chunks/handler.js +1 -1
- package/dist/packem_chunks/handler10.js +1 -1
- package/dist/packem_chunks/handler11.js +1 -1
- package/dist/packem_chunks/handler12.js +1 -1
- package/dist/packem_chunks/handler13.js +1 -1
- package/dist/packem_chunks/handler14.js +4 -4
- package/dist/packem_chunks/handler15.js +1 -1
- package/dist/packem_chunks/handler16.js +1 -1
- package/dist/packem_chunks/handler17.js +1 -1
- package/dist/packem_chunks/handler18.js +1 -1
- package/dist/packem_chunks/handler19.js +5 -5
- package/dist/packem_chunks/handler2.js +1 -1
- package/dist/packem_chunks/handler20.js +2 -1
- package/dist/packem_chunks/handler21.js +18 -1
- package/dist/packem_chunks/handler22.js +1 -5
- package/dist/packem_chunks/handler23.js +1 -1
- package/dist/packem_chunks/handler24.js +5 -3
- package/dist/packem_chunks/handler25.js +1 -1
- package/dist/packem_chunks/handler26.js +3 -1
- package/dist/packem_chunks/handler27.js +1 -7
- package/dist/packem_chunks/handler28.js +1 -23
- package/dist/packem_chunks/handler29.js +7 -3
- package/dist/packem_chunks/handler3.js +1 -1
- package/dist/packem_chunks/handler30.js +23 -18
- package/dist/packem_chunks/handler31.js +3 -1
- package/dist/packem_chunks/handler32.js +1 -2
- package/dist/packem_chunks/handler33.js +2 -25
- package/dist/packem_chunks/handler34.js +25 -2
- package/dist/packem_chunks/handler35.js +2 -2
- package/dist/packem_chunks/handler36.js +8 -8
- package/dist/packem_chunks/handler37.js +3 -3
- package/dist/packem_chunks/handler38.js +4 -4
- package/dist/packem_chunks/handler39.js +6 -6
- package/dist/packem_chunks/handler40.js +5 -5
- package/dist/packem_chunks/handler41.js +9 -9
- package/dist/packem_chunks/handler42.js +10 -10
- package/dist/packem_chunks/handler43.js +1 -1
- package/dist/packem_chunks/handler44.js +5 -5
- package/dist/packem_chunks/handler45.js +3 -3
- package/dist/packem_chunks/handler46.js +9 -9
- package/dist/packem_chunks/handler47.js +161 -36
- package/dist/packem_chunks/handler48.js +1 -1
- package/dist/packem_chunks/handler5.js +5 -5
- package/dist/packem_chunks/handler6.js +1 -1
- package/dist/packem_chunks/handler7.js +1 -1
- package/dist/packem_chunks/handler8.js +1 -1
- package/dist/packem_chunks/handler9.js +1 -1
- package/dist/packem_chunks/heal-accept.js +2 -2
- package/dist/packem_chunks/heal.js +1 -1
- package/dist/packem_chunks/help-command.js +16 -16
- package/dist/packem_chunks/index.js +1 -1
- package/dist/packem_chunks/loader.js +1 -1
- package/dist/packem_shared/{ai-analysis-CGVjqwdc.js → ai-analysis-C_GpXikx.js} +3 -3
- package/dist/packem_shared/ai-cache-DrCLD4gc.js +1 -0
- package/dist/packem_shared/ai-fix-CWOz12Om.js +43 -0
- package/dist/packem_shared/applyDefaults-DLY94gWA.js +1 -0
- package/dist/packem_shared/cache-directory-C_U1qsIw.js +1 -0
- package/dist/packem_shared/definePlugin-CWm4Dv_t.js +1 -0
- package/dist/packem_shared/dependency-scan-YdgNVvoz.js +2 -0
- package/dist/packem_shared/docker-Dl0AoVTZ.js +60 -0
- package/dist/packem_shared/failure-log-CSC6KfcO.js +2 -0
- package/dist/packem_shared/flakiness-Dzz-I3dB.js +1 -0
- package/dist/packem_shared/lifecycle-BC6Nst6i.js +2 -0
- package/dist/packem_shared/{lockfile-B7JJzxnL.js → lockfile-i-qvq_k8.js} +1 -1
- package/dist/packem_shared/otelPlugin-CJR2T_lk.js +1 -0
- package/dist/packem_shared/{readTomlSync-1fKo0R52-DAKNI1Me.js → readTomlSync-1fKo0R52-DtxWULlF.js} +1 -1
- package/dist/packem_shared/run-summary-utils-CJv75pla.js +1 -0
- package/dist/packem_shared/runtime-check-CBU6W8qG.js +1 -0
- package/dist/packem_shared/{selectors-Sem2CTYA.js → selectors-B2ISH581.js} +1 -1
- package/dist/packem_shared/toolchain-B7dckBQ1.js +5 -0
- package/dist/packem_shared/typosquats-B3A38-qx.js +1 -0
- package/dist/packem_shared/verify-WDStBFvK.js +1 -0
- package/dist/packem_shared/vis-update-app-D0uL3eO5.js +1 -0
- package/package.json +13 -13
- package/schemas/project.schema.json +12 -2
- package/schemas/vis-config.schema.json +248 -3
- package/dist/packem_chunks/applyDefaults.js +0 -2
- package/dist/packem_shared/ai-cache-BdPgSfg2.js +0 -1
- package/dist/packem_shared/ai-fix-iHtGLkJS.js +0 -43
- package/dist/packem_shared/cache-directory-DTfMSzT9.js +0 -1
- package/dist/packem_shared/dependency-scan-SQeRzrpJ.js +0 -2
- package/dist/packem_shared/docker-D5p9mRPU.js +0 -2
- package/dist/packem_shared/failure-log-CElcbnb9.js +0 -2
- package/dist/packem_shared/flakiness-C4t4_NoA.js +0 -1
- package/dist/packem_shared/otel-CO8UEfTa.js +0 -17
- package/dist/packem_shared/otelPlugin-DTynZDWh.js +0 -1
- package/dist/packem_shared/registry-D04iOQ5H.js +0 -2
- package/dist/packem_shared/run-summary-utils-BPraMTcm.js +0 -1
- package/dist/packem_shared/runtime-check-l4qFpo08.js +0 -1
- package/dist/packem_shared/toolchain-BhZNts--.js +0 -5
- package/dist/packem_shared/typosquats-Dr7VIL2B.js +0 -1
- package/dist/packem_shared/verify-C6NNOhTA.js +0 -1
- package/dist/packem_shared/vis-update-app-DGiMc5kb.js +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var re=Object.defineProperty;var E=(e,r)=>re(e,"name",{value:r,configurable:!0});import{createRequire as te}from"node:module";import{C as se,i as G,M,$ as Q,z as V,Q as le}from"../packem_shared/otel-CO8UEfTa.js";import{Box as a,Text as c,ScrollView as ce,ScrollBar as ae,useApp as de,useWindowSize as ue,useInput as fe,render as he}from"@visulima/tui";import{aH as ge,aI as J,aJ as pe,aK as me,aL as we,aM as ye,p as k,s as xe}from"./bin.js";import be,{useSyncExternalStore as Se,useRef as F,useCallback as _}from"react";import{o as ke}from"../packem_shared/index-DH-5hsrC.js";import{sortPackageJsonStringWithOptions as Y}from"#native";import{jsxs as f,jsx as s,Fragment as ve}from"react/jsx-runtime";import{f as N}from"../packem_shared/utils-DrNg0XTR.js";const oe=te(import.meta.url),T=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,ne=E(e=>{if(typeof T<"u"&&T.versions&&T.versions.node){const[r,t]=T.versions.node.split(".").map(Number);if(r>22||r===22&&t>=3||r===20&&t>=16)return T.getBuiltinModule(e)}return oe(e)},"__cjs_getBuiltinModule"),{writeFileSync:ie}=ne("node:fs");var $e=Object.defineProperty,I=E((e,r)=>$e(e,"name",{value:r,configurable:!0}),"i$1");const q={error:0,rewritten:1,"would-rewrite":1,unchanged:2},Pe=I(e=>[...e].sort((r,t)=>q[r.status]-q[t.status]),"sortByStatusRank"),Ee=I((e,r)=>r==="all"?e:r==="errors"?e.filter(t=>t.status==="error"):r==="rewritten"?e.filter(t=>t.status==="rewritten"||t.status==="would-rewrite"):e.filter(t=>t.status==="unchanged"),"filterEntries");class Oe{static{E(this,"a")}static{I(this,"SortPackageJsonStore")}#e;#r=new Set;constructor(r){this.#e={entries:Pe(r),filterType:"all",focusedPanel:"list",selectedIndex:0}}getSnapshot=I(()=>this.#e,"getSnapshot");subscribe=I(r=>(this.#r.add(r),()=>{this.#r.delete(r)}),"subscribe");getFilteredEntries=I(()=>Ee(this.#e.entries,this.#e.filterType),"getFilteredEntries");#t(){this.#e={...this.#e};for(const r of this.#r)r()}select(r){const t=this.getFilteredEntries();this.#e.selectedIndex=t.length===0?-1:Math.max(0,Math.min(r,t.length-1)),this.#t()}selectStep(r){this.select(this.#e.selectedIndex+r)}setFilter(r){this.#e.filterType=r,this.#e.selectedIndex=0,this.#t()}setFocusedPanel(r){this.#e.focusedPanel=r,this.#t()}}var je=Object.defineProperty,Ce=E((e,r)=>je(e,"name",{value:r,configurable:!0}),"c$2");const Re=Ce(({checkMode:e,entry:r,focused:t,scrollRef:l})=>r?f(a,{borderColor:t?"white":"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,children:[s(a,{flexShrink:0,paddingTop:1,paddingX:2,children:s(c,{bold:!0,color:"white",children:r.relativePath})}),f(ce,{flexGrow:1,flexShrink:1,paddingX:2,ref:l,scrollbar:!0,scrollbarColor:"gray",children:[s(c,{}),f(a,{children:[s(a,{width:10,children:s(c,{dimColor:!0,children:"Status:"})}),r.status==="error"?s(c,{bold:!0,color:"red",children:"error"}):r.status==="unchanged"?s(c,{bold:!0,color:"green",children:"already sorted"}):r.status==="rewritten"?s(c,{bold:!0,color:"yellow",children:"rewritten"}):s(c,{bold:!0,color:"yellow",children:"would rewrite (--check)"})]}),f(a,{children:[s(a,{width:10,children:s(c,{dimColor:!0,children:"Path:"})}),s(c,{children:r.filePath})]}),r.error?f(ve,{children:[f(a,{flexDirection:"column",marginTop:1,children:[s(c,{dimColor:!0,children:"── "}),s(c,{bold:!0,color:"red",children:"ERROR"}),f(a,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[f(a,{children:[s(a,{width:10,children:s(c,{dimColor:!0,children:"Step:"})}),s(c,{color:"yellow",children:r.error.step})]}),r.error.context&&f(a,{children:[s(a,{width:10,children:s(c,{dimColor:!0,children:"Position:"})}),s(c,{children:`line ${String(r.error.context.line)}, column ${String(r.error.context.column)}`})]}),s(a,{marginTop:1,children:s(c,{color:"red",children:r.error.message})})]})]}),r.error.context&&r.error.context.snippet.length>0&&f(a,{flexDirection:"column",marginTop:1,children:[s(c,{dimColor:!0,children:"── "}),s(c,{bold:!0,color:"white",children:"SNIPPET"}),f(a,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[r.error.context.snippet.map(n=>{const i=`${n.isErrorLine?"❯":" "} ${String(n.lineNumber).padStart(4)} `;return f(a,{children:[s(c,{color:n.isErrorLine?"red":"gray",children:i}),s(c,{color:n.isErrorLine?"white":"gray",wrap:"truncate-end",children:n.content||" "})]},n.lineNumber)}),r.error.context.column>0&&s(a,{children:s(c,{color:"red",children:`${" ".repeat(7+r.error.context.column-1)}↑`})})]})]})]}):f(a,{flexDirection:"column",marginTop:1,children:[s(c,{dimColor:!0,children:"── "}),s(c,{bold:!0,color:"white",children:"KEY DIFF"}),s(a,{flexDirection:"column",marginTop:1,paddingLeft:2,children:r.diff.length===0?s(c,{dimColor:!0,children:"No top-level keys moved (sub-key reorder only)."}):r.diff.map(n=>{const i=n.toIndex-n.fromIndex,d=i<0?`↑ ${String(Math.abs(i))}`:`↓ ${String(i)}`,g=i<0?"green":"yellow";return f(a,{children:[s(a,{width:28,children:s(c,{wrap:"truncate",children:n.key})}),s(a,{width:10,children:f(c,{dimColor:!0,children:[String(n.fromIndex)," → ",String(n.toIndex)]})}),s(c,{color:g,children:d})]},n.key)})}),e&&r.status==="would-rewrite"&&s(a,{marginTop:1,paddingLeft:2,children:s(c,{dimColor:!0,children:"--check mode: no write performed."})})]})]})]}):s(a,{alignItems:"center",borderColor:"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,justifyContent:"center",children:s(c,{dimColor:!0,children:"No entry selected"})}),"SortDetailPanel");var Ie=Object.defineProperty,O=E((e,r)=>Ie(e,"name",{value:r,configurable:!0}),"i");const Te={error:"red",rewritten:"yellow",unchanged:"green","would-rewrite":"yellow"},Me={error:"ERROR",rewritten:"REWROTE",unchanged:"SORTED","would-rewrite":"REWRITE"},U={error:"errors",rewritten:"rewrites",unchanged:"sorted","would-rewrite":"rewrites"},Fe={errors:"Errors",rewrites:"Rewrites",sorted:"Sorted"},Ne=[{count:O(e=>e.errors+e.rewrites+e.sorted,"count"),key:"all",label:"All",shortcut:"1"},{count:O(e=>e.rewrites,"count"),key:"rewritten",label:"Rewrites",shortcut:"2"},{count:O(e=>e.errors,"count"),key:"errors",label:"Errors",shortcut:"3"},{count:O(e=>e.sorted,"count"),key:"unchanged",label:"Sorted",shortcut:"4"}],Z=O(e=>{const r={errors:0,rewrites:0,sorted:0};for(const t of e)r[U[t.status]]++;return r},"computeGroupCounts"),De=O(({entry:e,isSelected:r})=>{const t=Te[e.status],l=Me[e.status];return f(a,{flexShrink:0,height:1,children:[s(c,{children:r?">":" "}),s(c,{children:" "}),s(c,{bold:!0,color:t,children:`[${l}]`.padEnd(10)}),s(c,{children:" "}),s(a,{flexGrow:1,children:s(c,{bold:r,inverse:r,wrap:"truncate",children:e.relativePath})}),e.status!=="error"&&e.diff.length>0&&s(c,{dimColor:!0,children:` ${String(e.diff.length)} key${e.diff.length===1?"":"s"}`})]})},"EntryRow"),Ae=O(({color:e,count:r,label:t})=>s(a,{flexShrink:0,height:1,children:s(c,{bold:!0,color:e,children:`${t} (${String(r)})`})}),"SectionHeader"),Le=O(({counts:e,entries:r,filterType:t,focused:l,selectedIndex:o,totalEntries:n,viewportHeight:i})=>{const d=l?"white":"gray",g=Z(r),b=(g.errors>0?1:0)+(g.rewrites>0?1:0)+(g.sorted>0?1:0),w=t==="all"&&b>1,p=[];let m;for(const[u,y]of r.entries()){const S=U[y.status];w&&S!==m&&(m!==void 0&&p.push({kind:"spacer"}),p.push({color:S==="errors"?"red":S==="rewrites"?"yellow":"green",count:g[S],kind:"header",label:Fe[S]}),m=S),p.push({entry:y,entryIndex:u,kind:"entry"})}const v=p.findIndex(u=>u.kind==="entry"&&u.entryIndex===o),$=v!==-1,P=p.length,h=Math.max(0,P-i);let C=0;$&&i>0&&(C=Math.min(h,Math.max(0,v-i+1)));const R=P>i&&i>0;return f(a,{borderColor:d,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[f(a,{flexShrink:0,gap:1,paddingX:1,children:[s(c,{bold:!0,inverse:!0,children:" VIS SORT "}),f(c,{wrap:"truncate",children:[n," ","file",n===1?"":"s"]})]}),s(a,{flexShrink:0,gap:1,paddingX:1,paddingY:1,children:Ne.map(u=>{const y=t===u.key,S=u.count(e);return f(a,{children:[s(c,{dimColor:!y,children:"["}),s(c,{bold:y,color:y?"cyan":"gray",children:u.shortcut}),s(c,{dimColor:!y,children:"]"}),f(c,{color:y?"white":"gray",children:[" ",u.label]}),f(c,{dimColor:!0,children:[" ","(",S,")"]})]},u.key)})}),f(a,{flexDirection:"row",flexGrow:1,overflow:"hidden",children:[s(a,{flexDirection:"column",flexGrow:1,overflow:"hidden",paddingLeft:1,children:s(a,{flexDirection:"column",marginTop:-C,children:p.map((u,y)=>u.kind==="spacer"?s(a,{flexShrink:0,height:1},`s-${String(y)}`):u.kind==="header"?s(Ae,{color:u.color,count:u.count,label:u.label},`h-${u.label}`):s(De,{entry:u.entry,isSelected:u.entryIndex===o},u.entry.filePath))})}),R&&s(a,{flexShrink:0,marginLeft:1,marginRight:1,children:s(ae,{contentHeight:P,placement:"inset",scrollOffset:C,style:"block",viewportHeight:i})})]})]})},"SortListPanel");var Be=Object.defineProperty,Ge=E((e,r)=>Be(e,"name",{value:r,configurable:!0}),"T");const Je=100,H=10,_e=6,qe=1,z={1:"all",2:"rewritten",3:"errors",4:"unchanged"},He=Ge(({checkMode:e,store:r})=>{const{exit:t}=de(),{columns:l,rows:o}=ue(),n=Se(r.subscribe,r.getSnapshot),i=F(null),d=r.getFilteredEntries(),g=d[n.selectedIndex]??null,b=Z(n.entries),w=l>=Je,p=Math.max(0,o-qe),m=w?p:Math.floor(p/2),v=Math.max(0,m-_e),$=_(()=>{t()},[t]),P=F(0),h=F(void 0),C=F(!1),R=_((u,y)=>{P.current+=y,h.current=u,!C.current&&(C.current=!0,queueMicrotask(()=>{C.current=!1;const S=P.current,B=h.current;P.current=0,h.current=void 0,!(S===0||B===void 0)&&(B==="list"?r.selectStep(Math.sign(S)):i.current?.scrollBy(Math.sign(S)))}))},[r]);return fe((u,y)=>{if(u==="q"||y.escape){$();return}if(z[u]){r.setFilter(z[u]);return}if(y.tab){r.setFocusedPanel(n.focusedPanel==="list"?"detail":"list");return}n.focusedPanel==="list"?y.upArrow||u==="k"?R("list",-1):(y.downArrow||u==="j")&&R("list",1):n.focusedPanel==="detail"&&(y.upArrow||u==="k"?R("detail",-1):(y.downArrow||u==="j")&&R("detail",1))}),o<H?s(a,{alignItems:"center",justifyContent:"center",children:f(c,{color:"yellow",children:["Terminal too small. Resize to at least",H," ","rows."]})}):f(a,{flexDirection:"column",height:o,width:l,children:[f(a,{flexDirection:w?"row":"column",flexGrow:1,children:[s(a,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:s(Le,{counts:b,entries:d,filterType:n.filterType,focused:n.focusedPanel==="list",selectedIndex:n.selectedIndex,totalEntries:n.entries.length,viewportHeight:v})}),s(a,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:s(Re,{checkMode:e,entry:g,focused:n.focusedPanel==="detail",scrollRef:i})})]}),s(a,{flexShrink:0,paddingX:1,children:s(c,{dimColor:!0,children:"↑/↓ or j/k:navigate | tab:switch panel | 1-4:filter | q:quit"})})]})},"VisSortPackageJsonApp");var ze=Object.defineProperty,j=E((e,r)=>ze(e,"name",{value:r,configurable:!0}),"c$1");const W=["types","node-addons","node","import","require","default"],We=/^git\+https:\/\/github\.com\/([^/]+)\/([^/.]+(?:\.git)?)$/,Xe=/^git\+ssh:\/\/git@github\.com\/([^/]+)\/([^/.]+(?:\.git)?)$/,D=j(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isPlainObject"),L=j(e=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(t=>L(t));const r={};for(const[t,l]of Object.entries(e))r[t]=L(l);return r},"cloneDeep"),Ke=j(e=>{if(!D(e))return{changed:!1,value:e};const r=Object.keys(e);return r.length===1&&r[0]==="url"&&typeof e.url=="string"?{changed:!0,value:e.url}:{changed:!1,value:e}},"tryFormatBugs"),Qe=j(e=>e.endsWith(".git")?e.slice(0,-4):e,"stripGitSuffix"),Ve=j(e=>{if(!D(e))return{changed:!1,value:e};if(typeof e.directory=="string"&&e.directory.length>0)return{changed:!1,value:e};const{type:r}=e;if(r!==void 0&&r!=="git")return{changed:!1,value:e};const{url:t}=e;if(typeof t!="string")return{changed:!1,value:e};const l=We.exec(t)??Xe.exec(t);if(!l)return{changed:!1,value:e};const o=l[1],n=Qe(l[2]??"");if(!o||!n)return{changed:!1,value:e};const i=new Set(["type","url"]);for(const d of Object.keys(e))if(!i.has(d))return{changed:!1,value:e};return{changed:!0,value:`${o}/${n}`}},"tryFormatRepository"),Ye=j(e=>{const r=Object.keys(e),t=[],l=[];for(const i of W)Object.hasOwn(e,i)&&t.push(i);for(const i of r)W.includes(i)||l.push(i);const o=[...t,...l];if(o.length===r.length&&o.every((i,d)=>i===r[d]))return{changed:!1,value:e};const n={};for(const i of o)n[i]=e[i];return{changed:!0,value:n}},"orderConditions"),ee=j(e=>{if(!D(e))return{changed:!1,value:e};let r=!1;const t={};for(const[o,n]of Object.entries(e)){const i=ee(n);t[o]=i.value,i.changed&&(r=!0)}const l=Ye(t);return{changed:r||l.changed,value:l.value}},"sortExportsRecursive"),Ue=j((e,r)=>{const t=L(e);let l=!1;if(r.formatBugs!==!1&&Object.hasOwn(t,"bugs")){const o=Ke(t.bugs);o.changed&&(t.bugs=o.value,l=!0)}if(r.formatRepository!==!1&&Object.hasOwn(t,"repository")){const o=Ve(t.repository);o.changed&&(t.repository=o.value,l=!0)}if(r.sortExports!==!1&&Object.hasOwn(t,"exports")&&D(t.exports)){const o=ee(t.exports);o.changed&&(t.exports=o.value,l=!0)}return{changed:l,pkg:t}},"formatPackageJsonFields");var Ze=Object.defineProperty,x=E((e,r)=>Ze(e,"name",{value:r,configurable:!0}),"c");const er=/at position (\d+)/,rr=/\(?line (\d+) column (\d+)\)?/,tr=x(e=>{const r=new Set,t=[],l=x(n=>{const i=se(n);!r.has(i)&&G(i)&&(r.add(i),t.push(i))},"addFile");l(M(e,"package.json"));const o=ge(e);if(o){const n=J(e,o);for(const i of n)l(M(e,i,"package.json"))}else{const n=M(e,"package.json");if(G(n)){const i=JSON.parse(Q(n)),d=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;if(d){const g=J(e,d);for(const b of g)l(M(e,b,"package.json"))}}}return t},"findPackageJsonFiles"),or=x(e=>/\n([ \t]+)/.exec(e)?.[1]??" ","detectIndent"),nr=x(e=>{if(!(e===void 0||e===""))return e==="tab"||e===String.raw`\t`?" ":/^\d+$/.test(e)?" ".repeat(Number.parseInt(e,10)):e},"resolveIndentOverride"),A=x(e=>e===void 0?[]:(Array.isArray(e)?e:[e]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0),"splitList"),ir=x(e=>e.includes(`\r
|
|
2
|
-
`)?"crlf":"lf","detectLineEnding"),sr=new Set(["auto","crlf","lf"]),lr=x(e=>{if(e===void 0||e==="")return"auto";if(sr.has(e))return e;throw new Error(`--line-ending must be one of: auto, lf, crlf (got "${e}")`)},"validateLineEnding"),cr=x((e,r,t)=>r.length===0?e:e.filter(l=>{const o=V(t,l),n=le(l);return!r.some(i=>{const d=i.includes("/")?o:n;return
|
|
3
|
-
`);if(r<1||r>l.length)return[];const o=Math.max(0,r-1-t),n=Math.min(l.length,r+t),i=[];for(let d=o;d<n;d++)i.push({content:l[d]??"",isErrorLine:d+1===r,lineNumber:d+1});return i},"buildSnippet"),
|
|
1
|
+
var re=Object.defineProperty;var E=(e,r)=>re(e,"name",{value:r,configurable:!0});import{createRequire as te}from"node:module";import{C as se,a as G,M as T,$ as K,z as V,Q as le}from"./config.js";import{render as ce}from"@visulima/tui";import{aM as ae,aN as J,aO as de,aP as ue,aQ as fe,aR as he,p as k,s as ge}from"./bin.js";import pe,{useSyncExternalStore as me,useRef as F,useCallback as _}from"react";import{o as we}from"../packem_shared/index-DH-5hsrC.js";import{sortPackageJsonStringWithOptions as Y}from"#native";import{jsxs as f,jsx as s,Fragment as ye}from"react/jsx-runtime";import{Box as a}from"@visulima/tui/components/box";import{Text as c}from"@visulima/tui/components/text";import{useApp as xe}from"@visulima/tui/hooks/use-app";import{useInput as be}from"@visulima/tui/hooks/use-input";import{useWindowSize as Se}from"@visulima/tui/hooks/use-window-size";import{ScrollView as ke}from"@visulima/tui/components/scroll-view";import{ScrollBar as ve}from"@visulima/tui/components/scroll-bar";import{f as N}from"../packem_shared/utils-DrNg0XTR.js";const oe=te(import.meta.url),M=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,ne=E(e=>{if(typeof M<"u"&&M.versions&&M.versions.node){const[r,t]=M.versions.node.split(".").map(Number);if(r>22||r===22&&t>=3||r===20&&t>=16)return M.getBuiltinModule(e)}return oe(e)},"__cjs_getBuiltinModule"),{writeFileSync:ie}=ne("node:fs");var $e=Object.defineProperty,I=E((e,r)=>$e(e,"name",{value:r,configurable:!0}),"i$1");const q={error:0,rewritten:1,"would-rewrite":1,unchanged:2},Pe=I(e=>[...e].sort((r,t)=>q[r.status]-q[t.status]),"sortByStatusRank"),Ee=I((e,r)=>r==="all"?e:r==="errors"?e.filter(t=>t.status==="error"):r==="rewritten"?e.filter(t=>t.status==="rewritten"||t.status==="would-rewrite"):e.filter(t=>t.status==="unchanged"),"filterEntries");class Oe{static{E(this,"a")}static{I(this,"SortPackageJsonStore")}#e;#r=new Set;constructor(r){this.#e={entries:Pe(r),filterType:"all",focusedPanel:"list",selectedIndex:0}}getSnapshot=I(()=>this.#e,"getSnapshot");subscribe=I(r=>(this.#r.add(r),()=>{this.#r.delete(r)}),"subscribe");getFilteredEntries=I(()=>Ee(this.#e.entries,this.#e.filterType),"getFilteredEntries");#t(){this.#e={...this.#e};for(const r of this.#r)r()}select(r){const t=this.getFilteredEntries();this.#e.selectedIndex=t.length===0?-1:Math.max(0,Math.min(r,t.length-1)),this.#t()}selectStep(r){this.select(this.#e.selectedIndex+r)}setFilter(r){this.#e.filterType=r,this.#e.selectedIndex=0,this.#t()}setFocusedPanel(r){this.#e.focusedPanel=r,this.#t()}}var je=Object.defineProperty,Ce=E((e,r)=>je(e,"name",{value:r,configurable:!0}),"c$2");const Re=Ce(({checkMode:e,entry:r,focused:t,scrollRef:l})=>r?f(a,{borderColor:t?"white":"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,children:[s(a,{flexShrink:0,paddingTop:1,paddingX:2,children:s(c,{bold:!0,color:"white",children:r.relativePath})}),f(ke,{flexGrow:1,flexShrink:1,paddingX:2,ref:l,scrollbar:!0,scrollbarColor:"gray",children:[s(c,{}),f(a,{children:[s(a,{width:10,children:s(c,{dimColor:!0,children:"Status:"})}),r.status==="error"?s(c,{bold:!0,color:"red",children:"error"}):r.status==="unchanged"?s(c,{bold:!0,color:"green",children:"already sorted"}):r.status==="rewritten"?s(c,{bold:!0,color:"yellow",children:"rewritten"}):s(c,{bold:!0,color:"yellow",children:"would rewrite (--check)"})]}),f(a,{children:[s(a,{width:10,children:s(c,{dimColor:!0,children:"Path:"})}),s(c,{children:r.filePath})]}),r.error?f(ye,{children:[f(a,{flexDirection:"column",marginTop:1,children:[s(c,{dimColor:!0,children:"── "}),s(c,{bold:!0,color:"red",children:"ERROR"}),f(a,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[f(a,{children:[s(a,{width:10,children:s(c,{dimColor:!0,children:"Step:"})}),s(c,{color:"yellow",children:r.error.step})]}),r.error.context&&f(a,{children:[s(a,{width:10,children:s(c,{dimColor:!0,children:"Position:"})}),s(c,{children:`line ${String(r.error.context.line)}, column ${String(r.error.context.column)}`})]}),s(a,{marginTop:1,children:s(c,{color:"red",children:r.error.message})})]})]}),r.error.context&&r.error.context.snippet.length>0&&f(a,{flexDirection:"column",marginTop:1,children:[s(c,{dimColor:!0,children:"── "}),s(c,{bold:!0,color:"white",children:"SNIPPET"}),f(a,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[r.error.context.snippet.map(n=>{const i=`${n.isErrorLine?"❯":" "} ${String(n.lineNumber).padStart(4)} `;return f(a,{children:[s(c,{color:n.isErrorLine?"red":"gray",children:i}),s(c,{color:n.isErrorLine?"white":"gray",wrap:"truncate-end",children:n.content||" "})]},n.lineNumber)}),r.error.context.column>0&&s(a,{children:s(c,{color:"red",children:`${" ".repeat(7+r.error.context.column-1)}↑`})})]})]})]}):f(a,{flexDirection:"column",marginTop:1,children:[s(c,{dimColor:!0,children:"── "}),s(c,{bold:!0,color:"white",children:"KEY DIFF"}),s(a,{flexDirection:"column",marginTop:1,paddingLeft:2,children:r.diff.length===0?s(c,{dimColor:!0,children:"No top-level keys moved (sub-key reorder only)."}):r.diff.map(n=>{const i=n.toIndex-n.fromIndex,d=i<0?`↑ ${String(Math.abs(i))}`:`↓ ${String(i)}`,g=i<0?"green":"yellow";return f(a,{children:[s(a,{width:28,children:s(c,{wrap:"truncate",children:n.key})}),s(a,{width:10,children:f(c,{dimColor:!0,children:[String(n.fromIndex)," → ",String(n.toIndex)]})}),s(c,{color:g,children:d})]},n.key)})}),e&&r.status==="would-rewrite"&&s(a,{marginTop:1,paddingLeft:2,children:s(c,{dimColor:!0,children:"--check mode: no write performed."})})]})]})]}):s(a,{alignItems:"center",borderColor:"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,justifyContent:"center",children:s(c,{dimColor:!0,children:"No entry selected"})}),"SortDetailPanel");var Ie=Object.defineProperty,O=E((e,r)=>Ie(e,"name",{value:r,configurable:!0}),"i");const Me={error:"red",rewritten:"yellow",unchanged:"green","would-rewrite":"yellow"},Te={error:"ERROR",rewritten:"REWROTE",unchanged:"SORTED","would-rewrite":"REWRITE"},U={error:"errors",rewritten:"rewrites",unchanged:"sorted","would-rewrite":"rewrites"},Fe={errors:"Errors",rewrites:"Rewrites",sorted:"Sorted"},Ne=[{count:O(e=>e.errors+e.rewrites+e.sorted,"count"),key:"all",label:"All",shortcut:"1"},{count:O(e=>e.rewrites,"count"),key:"rewritten",label:"Rewrites",shortcut:"2"},{count:O(e=>e.errors,"count"),key:"errors",label:"Errors",shortcut:"3"},{count:O(e=>e.sorted,"count"),key:"unchanged",label:"Sorted",shortcut:"4"}],Z=O(e=>{const r={errors:0,rewrites:0,sorted:0};for(const t of e)r[U[t.status]]++;return r},"computeGroupCounts"),De=O(({entry:e,isSelected:r})=>{const t=Me[e.status],l=Te[e.status];return f(a,{flexShrink:0,height:1,children:[s(c,{children:r?">":" "}),s(c,{children:" "}),s(c,{bold:!0,color:t,children:`[${l}]`.padEnd(10)}),s(c,{children:" "}),s(a,{flexGrow:1,children:s(c,{bold:r,inverse:r,wrap:"truncate",children:e.relativePath})}),e.status!=="error"&&e.diff.length>0&&s(c,{dimColor:!0,children:` ${String(e.diff.length)} key${e.diff.length===1?"":"s"}`})]})},"EntryRow"),Ae=O(({color:e,count:r,label:t})=>s(a,{flexShrink:0,height:1,children:s(c,{bold:!0,color:e,children:`${t} (${String(r)})`})}),"SectionHeader"),Le=O(({counts:e,entries:r,filterType:t,focused:l,selectedIndex:o,totalEntries:n,viewportHeight:i})=>{const d=l?"white":"gray",g=Z(r),b=(g.errors>0?1:0)+(g.rewrites>0?1:0)+(g.sorted>0?1:0),w=t==="all"&&b>1,p=[];let m;for(const[u,y]of r.entries()){const S=U[y.status];w&&S!==m&&(m!==void 0&&p.push({kind:"spacer"}),p.push({color:S==="errors"?"red":S==="rewrites"?"yellow":"green",count:g[S],kind:"header",label:Fe[S]}),m=S),p.push({entry:y,entryIndex:u,kind:"entry"})}const v=p.findIndex(u=>u.kind==="entry"&&u.entryIndex===o),$=v!==-1,P=p.length,h=Math.max(0,P-i);let C=0;$&&i>0&&(C=Math.min(h,Math.max(0,v-i+1)));const R=P>i&&i>0;return f(a,{borderColor:d,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[f(a,{flexShrink:0,gap:1,paddingX:1,children:[s(c,{bold:!0,inverse:!0,children:" VIS SORT "}),f(c,{wrap:"truncate",children:[n," ","file",n===1?"":"s"]})]}),s(a,{flexShrink:0,gap:1,paddingX:1,paddingY:1,children:Ne.map(u=>{const y=t===u.key,S=u.count(e);return f(a,{children:[s(c,{dimColor:!y,children:"["}),s(c,{bold:y,color:y?"cyan":"gray",children:u.shortcut}),s(c,{dimColor:!y,children:"]"}),f(c,{color:y?"white":"gray",children:[" ",u.label]}),f(c,{dimColor:!0,children:[" ","(",S,")"]})]},u.key)})}),f(a,{flexDirection:"row",flexGrow:1,overflow:"hidden",children:[s(a,{flexDirection:"column",flexGrow:1,overflow:"hidden",paddingLeft:1,children:s(a,{flexDirection:"column",marginTop:-C,children:p.map((u,y)=>u.kind==="spacer"?s(a,{flexShrink:0,height:1},`s-${String(y)}`):u.kind==="header"?s(Ae,{color:u.color,count:u.count,label:u.label},`h-${u.label}`):s(De,{entry:u.entry,isSelected:u.entryIndex===o},u.entry.filePath))})}),R&&s(a,{flexShrink:0,marginLeft:1,marginRight:1,children:s(ve,{contentHeight:P,placement:"inset",scrollOffset:C,style:"block",viewportHeight:i})})]})]})},"SortListPanel");var Be=Object.defineProperty,Ge=E((e,r)=>Be(e,"name",{value:r,configurable:!0}),"T");const Je=100,H=10,_e=6,qe=1,z={1:"all",2:"rewritten",3:"errors",4:"unchanged"},He=Ge(({checkMode:e,store:r})=>{const{exit:t}=xe(),{columns:l,rows:o}=Se(),n=me(r.subscribe,r.getSnapshot),i=F(null),d=r.getFilteredEntries(),g=d[n.selectedIndex]??null,b=Z(n.entries),w=l>=Je,p=Math.max(0,o-qe),m=w?p:Math.floor(p/2),v=Math.max(0,m-_e),$=_(()=>{t()},[t]),P=F(0),h=F(void 0),C=F(!1),R=_((u,y)=>{P.current+=y,h.current=u,!C.current&&(C.current=!0,queueMicrotask(()=>{C.current=!1;const S=P.current,B=h.current;P.current=0,h.current=void 0,!(S===0||B===void 0)&&(B==="list"?r.selectStep(Math.sign(S)):i.current?.scrollBy(Math.sign(S)))}))},[r]);return be((u,y)=>{if(u==="q"||y.escape){$();return}if(z[u]){r.setFilter(z[u]);return}if(y.tab){r.setFocusedPanel(n.focusedPanel==="list"?"detail":"list");return}n.focusedPanel==="list"?y.upArrow||u==="k"?R("list",-1):(y.downArrow||u==="j")&&R("list",1):n.focusedPanel==="detail"&&(y.upArrow||u==="k"?R("detail",-1):(y.downArrow||u==="j")&&R("detail",1))}),o<H?s(a,{alignItems:"center",justifyContent:"center",children:f(c,{color:"yellow",children:["Terminal too small. Resize to at least",H," ","rows."]})}):f(a,{flexDirection:"column",height:o,width:l,children:[f(a,{flexDirection:w?"row":"column",flexGrow:1,children:[s(a,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:s(Le,{counts:b,entries:d,filterType:n.filterType,focused:n.focusedPanel==="list",selectedIndex:n.selectedIndex,totalEntries:n.entries.length,viewportHeight:v})}),s(a,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:s(Re,{checkMode:e,entry:g,focused:n.focusedPanel==="detail",scrollRef:i})})]}),s(a,{flexShrink:0,paddingX:1,children:s(c,{dimColor:!0,children:"↑/↓ or j/k:navigate | tab:switch panel | 1-4:filter | q:quit"})})]})},"VisSortPackageJsonApp");var ze=Object.defineProperty,j=E((e,r)=>ze(e,"name",{value:r,configurable:!0}),"c$1");const W=["types","node-addons","node","import","require","default"],We=/^git\+https:\/\/github\.com\/([^/]+)\/([^/.]+(?:\.git)?)$/,Xe=/^git\+ssh:\/\/git@github\.com\/([^/]+)\/([^/.]+(?:\.git)?)$/,D=j(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isPlainObject"),L=j(e=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(t=>L(t));const r={};for(const[t,l]of Object.entries(e))r[t]=L(l);return r},"cloneDeep"),Qe=j(e=>{if(!D(e))return{changed:!1,value:e};const r=Object.keys(e);return r.length===1&&r[0]==="url"&&typeof e.url=="string"?{changed:!0,value:e.url}:{changed:!1,value:e}},"tryFormatBugs"),Ke=j(e=>e.endsWith(".git")?e.slice(0,-4):e,"stripGitSuffix"),Ve=j(e=>{if(!D(e))return{changed:!1,value:e};if(typeof e.directory=="string"&&e.directory.length>0)return{changed:!1,value:e};const{type:r}=e;if(r!==void 0&&r!=="git")return{changed:!1,value:e};const{url:t}=e;if(typeof t!="string")return{changed:!1,value:e};const l=We.exec(t)??Xe.exec(t);if(!l)return{changed:!1,value:e};const o=l[1],n=Ke(l[2]??"");if(!o||!n)return{changed:!1,value:e};const i=new Set(["type","url"]);for(const d of Object.keys(e))if(!i.has(d))return{changed:!1,value:e};return{changed:!0,value:`${o}/${n}`}},"tryFormatRepository"),Ye=j(e=>{const r=Object.keys(e),t=[],l=[];for(const i of W)Object.hasOwn(e,i)&&t.push(i);for(const i of r)W.includes(i)||l.push(i);const o=[...t,...l];if(o.length===r.length&&o.every((i,d)=>i===r[d]))return{changed:!1,value:e};const n={};for(const i of o)n[i]=e[i];return{changed:!0,value:n}},"orderConditions"),ee=j(e=>{if(!D(e))return{changed:!1,value:e};let r=!1;const t={};for(const[o,n]of Object.entries(e)){const i=ee(n);t[o]=i.value,i.changed&&(r=!0)}const l=Ye(t);return{changed:r||l.changed,value:l.value}},"sortExportsRecursive"),Ue=j((e,r)=>{const t=L(e);let l=!1;if(r.formatBugs!==!1&&Object.hasOwn(t,"bugs")){const o=Qe(t.bugs);o.changed&&(t.bugs=o.value,l=!0)}if(r.formatRepository!==!1&&Object.hasOwn(t,"repository")){const o=Ve(t.repository);o.changed&&(t.repository=o.value,l=!0)}if(r.sortExports!==!1&&Object.hasOwn(t,"exports")&&D(t.exports)){const o=ee(t.exports);o.changed&&(t.exports=o.value,l=!0)}return{changed:l,pkg:t}},"formatPackageJsonFields");var Ze=Object.defineProperty,x=E((e,r)=>Ze(e,"name",{value:r,configurable:!0}),"c");const er=/at position (\d+)/,rr=/\(?line (\d+) column (\d+)\)?/,tr=x(e=>{const r=new Set,t=[],l=x(n=>{const i=se(n);!r.has(i)&&G(i)&&(r.add(i),t.push(i))},"addFile");l(T(e,"package.json"));const o=ae(e);if(o){const n=J(e,o);for(const i of n)l(T(e,i,"package.json"))}else{const n=T(e,"package.json");if(G(n)){const i=JSON.parse(K(n)),d=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;if(d){const g=J(e,d);for(const b of g)l(T(e,b,"package.json"))}}}return t},"findPackageJsonFiles"),or=x(e=>/\n([ \t]+)/.exec(e)?.[1]??" ","detectIndent"),nr=x(e=>{if(!(e===void 0||e===""))return e==="tab"||e===String.raw`\t`?" ":/^\d+$/.test(e)?" ".repeat(Number.parseInt(e,10)):e},"resolveIndentOverride"),A=x(e=>e===void 0?[]:(Array.isArray(e)?e:[e]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0),"splitList"),ir=x(e=>e.includes(`\r
|
|
2
|
+
`)?"crlf":"lf","detectLineEnding"),sr=new Set(["auto","crlf","lf"]),lr=x(e=>{if(e===void 0||e==="")return"auto";if(sr.has(e))return e;throw new Error(`--line-ending must be one of: auto, lf, crlf (got "${e}")`)},"validateLineEnding"),cr=x((e,r,t)=>r.length===0?e:e.filter(l=>{const o=V(t,l),n=le(l);return!r.some(i=>{const d=i.includes("/")?o:n;return we(i,d)})}),"filterByIgnore"),ar=x((e,r)=>{if(r.length===0)return e;const t={},l=new Set;for(const o of r)Object.hasOwn(e,o)&&(t[o]=e[o],l.add(o));for(const o of Object.keys(e))l.has(o)||(t[o]=e[o]);return t},"applySortOrder"),dr=x((e,r,t)=>{if(t.length===0)return e;const l={...e};for(const o of t)Object.hasOwn(r,o)&&(l[o]=r[o]);return l},"restoreUnsortedSections"),ur=x((e,r)=>{let t=1,l=1;const o=Math.min(r,e.length);for(let n=0;n<o;n++)e.codePointAt(n)===10?(t++,l=1):l++;return{column:l,line:t}},"computeLineColumn"),X=x((e,r,t=2)=>{const l=e.split(`
|
|
3
|
+
`);if(r<1||r>l.length)return[];const o=Math.max(0,r-1-t),n=Math.min(l.length,r+t),i=[];for(let d=o;d<n;d++)i.push({content:l[d]??"",isErrorLine:d+1===r,lineNumber:d+1});return i},"buildSnippet"),Q=x((e,r)=>{if(!(e instanceof Error))return;const t=er.exec(e.message);if(t){const{column:o,line:n}=ur(r,Number.parseInt(t[1]??"0",10));return{column:o,line:n,snippet:X(r,n)}}const l=rr.exec(e.message);if(l){const o=Number.parseInt(l[1]??"1",10);return{column:Number.parseInt(l[2]??"1",10),line:o,snippet:X(r,o)}}},"extractParseErrorContext"),fr=x((e,r)=>{const t=Object.keys(JSON.parse(e)),l=Object.keys(JSON.parse(r)),o=new Map(t.map((i,d)=>[i,d])),n=[];for(const[i,d]of l.entries()){const g=o.get(d);g!==void 0&&g!==i&&n.push({fromIndex:g,key:d,toIndex:i})}return n},"computeKeyDiff"),hr=x((e,r,t)=>{const l=r.indent??t.indent??or(e),o=r.lineEnding==="auto"?t.lineEnding??ir(e):r.lineEnding,n=Y(e,{pretty:!1,sortScripts:r.sortScripts});let i=JSON.parse(n);if(r.unsorted.length>0){const w=JSON.parse(e);i=dr(i,w,r.unsorted)}i=ar(i,r.sortOrder);const d={formatBugs:r.formatBugs,formatRepository:r.formatRepository,sortExports:r.sortExports},g=Ue(i,d);let b=JSON.stringify(g.pkg,null,l);return r.finalNewline&&(b+=`
|
|
4
4
|
`),o==="crlf"&&(b=b.replaceAll(`
|
|
5
5
|
`,`\r
|
|
6
|
-
`)),b},"sortContents"),gr=x((e,r)=>{const t=tr(e),l=
|
|
6
|
+
`)),b},"sortContents"),gr=x((e,r)=>{const t=tr(e),l=de(e),o=ue({cwd:e,extraPatterns:fe(l)}),n=t.filter(d=>!o.ignores(d)),i=cr(n,r,e);return{afterGitignore:n,allFiles:t,files:i}},"discoverPackageJsonFiles"),pr=x((e,{checkMode:r,cwd:t,normalized:l})=>{const o=V(t,e)||e;let n;try{n=K(e)}catch(w){return{diff:[],error:{message:N(w),step:"read"},filePath:e,relativePath:o,status:"error"}}let i;try{i=Y(n,{pretty:!1,sortScripts:l.sortScripts})}catch(w){const p={message:N(w),step:"native-sort"},m=Q(w,n);return m&&(p.context=m),{diff:[],error:p,filePath:e,relativePath:o,status:"error"}}const d=l.editorconfig?he(e):{};let g;try{g=hr(n,l,d)}catch(w){const p={message:N(w),step:"json-parse"},m=Q(w,n);return m&&(p.context=m),{diff:[],error:p,filePath:e,relativePath:o,status:"error"}}if(n===g)return{diff:[],filePath:e,relativePath:o,status:"unchanged"};let b;try{b=fr(n,i)}catch{b=[]}if(r)return{diff:b,filePath:e,relativePath:o,status:"would-rewrite"};try{ie(e,g,"utf8")}catch(w){return{diff:b,error:{message:N(w),step:"write"},filePath:e,relativePath:o,status:"error"}}return{diff:b,filePath:e,relativePath:o,status:"rewritten"}},"processFile"),mr=x(e=>{if(e.error&&(k.error(`${e.filePath}: ${e.error.message}`),k.info(` step: ${e.error.step}`),e.error.context)){k.info(` at line ${String(e.error.context.line)}, column ${String(e.error.context.column)}`);for(const r of e.error.context.snippet){const t=r.isErrorLine?">":" ";k.info(` ${t} ${String(r.lineNumber).padStart(4)} | ${r.content}`)}}},"printStaticError"),Fr=x(async({options:e,visConfig:r,workspaceRoot:t})=>{const l=t??process.cwd(),o=r?.sortPackageJson,n=e.check||!1,i={editorconfig:e.editorconfig===!1?!1:o?.editorconfig??!0,finalNewline:e.finalNewline??o?.finalNewline??!0,formatBugs:e.formatBugs===!1?!1:o?.formatBugs??!0,formatRepository:e.formatRepository===!1?!1:o?.formatRepository??!0,ignore:[...A(e.ignore),...o?.ignore??[]],indent:nr(e.indent??o?.indent),lineEnding:lr(e.lineEnding??o?.lineEnding),sortExports:e.sortExports===!1?!1:o?.sortExports??!0,sortOrder:[...A(e.sortOrder),...o?.sortOrder??[]],sortScripts:e.sortScripts||o?.sortScripts||!1,unsorted:[...A(e.unsorted),...o?.unsorted??[]]},d=gr(l,i.ignore),{afterGitignore:g,allFiles:b,files:w}=d;if(w.length===0){b.length===0?k.info("No package.json files found."):g.length===0?k.info("All package.json files were excluded by .gitignore or workspace exclusions."):k.info("All package.json files were excluded by --ignore.");return}const p=[];for(const h of w)p.push(pr(h,{checkMode:n,cwd:l,normalized:i}));let m=0,v=0,$=0;for(const h of p)h.status==="error"?$++:h.status==="rewritten"||h.status==="would-rewrite"?m++:v++;const P=m>0||$>0;if(process.stdout.isTTY&&!ge&&P){const h=new Oe(p);await ce(pe.createElement(He,{checkMode:n,store:h}),{alternateScreen:!0,exitOnCtrlC:!1,interactive:!0,patchConsole:!0}).waitUntilExit()}else for(const h of p)switch(h.status){case"error":{mr(h);break}case"rewritten":{k.success(`Sorted ${h.filePath}`);break}case"would-rewrite":{k.warn(`${h.filePath} is not sorted`);break}}if(n)m>0?(k.info(`${String(m)} file${m===1?"":"s"} not sorted, ${String(v)} already sorted`),process.exitCode=1):$===0&&k.info(`All ${String(v)} package.json file${v===1?" is":"s are"} sorted`);else{const h=[];m>0&&h.push(`sorted ${String(m)} file${m===1?"":"s"}`),v>0&&h.push(`${String(v)} already sorted`),$>0&&h.push(`${String($)} error${$===1?"":"s"}`),h.length>0&&k.info(h.join(", "))}$>0&&(process.exitCode=1)},"execute");export{X as buildSnippet,fr as computeKeyDiff,ur as computeLineColumn,Fr as default,gr as discoverPackageJsonFiles,Q as extractParseErrorContext,pr as processFile};
|
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
var ee=Object.defineProperty;var v=(e,t)=>ee(e,"name",{value:t,configurable:!0});import{createRequire as te}from"node:module";import{M as l,
|
|
1
|
+
var ee=Object.defineProperty;var v=(e,t)=>ee(e,"name",{value:t,configurable:!0});import{createRequire as te}from"node:module";import{M as l,a as y,$ as A,h as G}from"./config.js";import{aS as z,aT as ae,aU as le,aV as ce,aW as fe,aX as ue,aY as de,aZ as pe,a_ as K,a$ as J,b0 as U,b1 as Y}from"./bin.js";import{d as ge}from"../packem_shared/readTomlSync-1fKo0R52-DtxWULlF.js";const se=te(import.meta.url),F=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,B=v(e=>{if(typeof F<"u"&&F.versions&&F.versions.node){const[t,s]=F.versions.node.split(".").map(Number);if(t>22||t===22&&s>=3||t===20&&s>=16)return F.getBuiltinModule(e)}return se(e)},"__cjs_getBuiltinModule"),{readdirSync:q,statSync:C,writeFileSync:S,unlinkSync:ne,rmSync:re,chmodSync:ie}=B("node:fs"),{cwd:j}=F,{createInterface:oe}=B("node:readline"),{spawnSync:w}=B("node:child_process");var he=Object.defineProperty,N=v((e,t)=>he(e,"name",{value:t,configurable:!0}),"c$2");const me=/^# ([^:\s]\S*)(?::\s+(.+))?$/,ke=N(e=>{const t=[],s=e.split(`
|
|
2
2
|
`);let n;for(const r of s){if(r.startsWith("#!")||r.startsWith("# Generated by")||r.startsWith("# NOTE:")||r==="set -e"||r==="")continue;const i=me.exec(r);if(i){n&&t.push(n),n={command:"",id:i[1]??"",...i[2]?{name:i[2]}:{}};continue}n?n.command=n.command.length>0?`${n.command}
|
|
3
3
|
${r}`:r:n={command:r,id:"(custom)"}}return n&&t.push(n),t},"parseStageScript"),ye=N((e,t)=>{const s=l(e,t),n=[],r=new Set(z);if(y(s))for(const i of q(s)){if(i.startsWith(".")||i==="_"||!r.has(i))continue;const o=l(s,i);if(!C(o).isFile())continue;const a=A(o),c=ke(a);n.push({blocks:c,rawLineCount:a.split(`
|
|
4
4
|
`).length,stage:i})}return n.sort((i,o)=>i.stage.localeCompare(o.stage)),{hooksDirectory:t,stages:n}},"listHooks"),be=N(e=>{const t=[];if(e.stages.length===0)return t.push(`No hooks installed in ${e.hooksDirectory}/.`),t;t.push(`Hooks in ${e.hooksDirectory}/:`);for(const s of e.stages)if(t.push("",`${s.stage} (${s.rawLineCount} lines)`),s.blocks.length===0)t.push(" (empty)");else for(const n of s.blocks){const r=n.name?`${n.id} — ${n.name}`:n.id;t.push(` - ${r}`);const i=n.command.split(`
|
|
5
|
-
`).find(o=>o.trim()!=="");if(i){const o=i.length>120?`${i.slice(0,117)}...`:i;t.push(` ${o}`)}}return t},"formatListResult"),we=N((e,t)=>{const s=ye(j(),e);for(const n of be(s))t.info(n)},"runList"),E="prek-runner.mjs",xe={css:["css","scss","sass","less"],dockerfile:["dockerfile"],html:["htm","html"],javascript:["cjs","js","jsx","mjs"],json:["json"],jsx:["jsx","tsx"],makefile:["mk","makefile"],markdown:["markdown","md","mdown","mdx"],python:["py","pyi","pyw"],python3:["py","pyi","pyw"],ruby:["rb"],rust:["rs"],shell:["bash","sh","zsh"],sql:["sql"],svg:["svg"],systemd:["service","socket","timer"],toml:["toml"],tsx:["tsx"],typescript:["cts","mts","ts","tsx"],xml:["xml"],yaml:["yaml","yml"]},$e=["binary","directory","executable","non-executable","symlink","text"],ve={bash:["bash","shell"],node:["javascript"],nodejs:["javascript"],perl:["perl"],python:["python"],python3:["python","python3"],ruby:["ruby"],sh:["shell"],zsh:["shell","zsh"]},Ee=["check-json","check-merge-conflict","end-of-file-fixer","mixed-line-ending","trailing-whitespace"],Se=[...Object.keys(xe),...Object.values(ve).flat(),...$e],Re=["#!/usr/bin/env node","// Auto-generated by `vis hook migrate`. Do not edit by hand.","// Replicates the subset of prek / pre-commit framework semantics that a vis","// hook script needs: staged-file discovery, regex + type filters, chunked","// argv dispatch, and a handful of built-in hook implementations.","","import { spawnSync } from 'node:child_process';","import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';","import { basename, extname, join } from 'node:path';","import process from 'node:process';","","const TYPES_EXTENSION_MAP = {"," css: ['css', 'scss', 'sass', 'less'],"," dockerfile: ['dockerfile'],"," html: ['htm', 'html'],"," javascript: ['cjs', 'js', 'jsx', 'mjs'],"," json: ['json'],"," jsx: ['jsx', 'tsx'],"," makefile: ['mk', 'makefile'],"," markdown: ['markdown', 'md', 'mdown', 'mdx'],"," python: ['py', 'pyi', 'pyw'],"," python3: ['py', 'pyi', 'pyw'],"," ruby: ['rb'],"," rust: ['rs'],"," shell: ['bash', 'sh', 'zsh'],"," sql: ['sql'],"," svg: ['svg'],"," systemd: ['service', 'socket', 'timer'],"," toml: ['toml'],"," tsx: ['tsx'],"," typescript: ['cts', 'mts', 'ts', 'tsx'],"," xml: ['xml'],"," yaml: ['yaml', 'yml'],","};","","const FILENAME_TYPE_MAP = {"," dockerfile: 'dockerfile',"," makefile: 'makefile',"," 'gnumakefile': 'makefile',","};","","const SHEBANG_INTERPRETER_MAP = {"," bash: ['bash', 'shell'],"," node: ['javascript'],"," nodejs: ['javascript'],"," perl: ['perl'],"," python: ['python'],"," python3: ['python', 'python3'],"," ruby: ['ruby'],"," sh: ['shell'],"," zsh: ['shell', 'zsh'],","};","","const BUILTINS = {"," 'check-json': runCheckJson,"," 'check-merge-conflict': runCheckMergeConflict,"," 'end-of-file-fixer': runEndOfFileFixer,"," 'mixed-line-ending': runMixedLineEnding,"," 'trailing-whitespace': runTrailingWhitespace,","};","","const parseArgs = (argv) => {"," const flags = {"," allFiles: process.env.VIS_HOOK_ALL_FILES === '1',"," alwaysRun: false,"," builtin: null,"," exclude: null,"," excludeTypes: [],"," files: null,"," fromRef: process.env.VIS_HOOK_FROM_REF || null,"," passFilenames: true,"," toRef: process.env.VIS_HOOK_TO_REF || null,"," types: [],"," typesOr: [],"," };"," const rest = [];"," let seenDoubleDash = false;",""," for (let i = 0; i < argv.length; i += 1) {"," const arg = argv[i];",""," if (seenDoubleDash) {"," rest.push(arg);"," continue;"," }",""," switch (arg) {"," case '--':"," seenDoubleDash = true;"," break;"," case '--all-files':"," flags.allFiles = true;"," break;"," case '--always-run':"," flags.alwaysRun = true;"," break;"," case '--builtin':"," i += 1;"," flags.builtin = argv[i];"," break;"," case '--exclude':"," i += 1;"," flags.exclude = argv[i];"," break;"," case '--from-ref':"," i += 1;"," flags.fromRef = argv[i];"," break;"," case '--to-ref':"," i += 1;"," flags.toRef = argv[i];"," break;"," case '--exclude-types':"," i += 1;"," flags.excludeTypes = (argv[i] || '').split(',').filter(Boolean);"," break;"," case '--files':"," i += 1;"," flags.files = argv[i];"," break;"," case '--no-pass-filenames':"," flags.passFilenames = false;"," break;"," case '--types':"," i += 1;"," flags.types = (argv[i] || '').split(',').filter(Boolean);"," break;"," case '--types-or':"," i += 1;"," flags.typesOr = (argv[i] || '').split(',').filter(Boolean);"," break;"," default:"," process.stderr.write('prek-runner: unknown flag ' + arg + '\\n');"," process.exit(2);"," }"," }",""," return { flags, rest };","};","","const gitListFiles = (args, errorHint) => {"," const result = spawnSync('git', args, { encoding: 'buffer' });"," if (result.status !== 0) {"," process.stderr.write('prek-runner: git ' + errorHint + ' failed\\n');"," process.stderr.write(result.stderr ? result.stderr.toString() : '');"," process.exit(result.status === null ? 1 : result.status);"," }"," const raw = result.stdout.toString('utf8');"," if (raw.length === 0) { return []; }"," return raw.split('\\0').filter(function (f) { return f.length > 0; });","};","","const discoverFiles = (flags) => {"," if (flags.allFiles) {"," return gitListFiles(['ls-files', '-z'], 'ls-files');"," }"," if (flags.fromRef && flags.toRef) {"," return gitListFiles("," ['diff', '--name-only', '--diff-filter=ACM', '-z', flags.fromRef, flags.toRef],"," 'diff --from-ref/--to-ref'"," );"," }"," return gitListFiles(['diff', '--cached', '--name-only', '--diff-filter=ACM', '-z'], 'diff --cached');","};","","const buildRegex = (pattern) => {"," try {"," return new RegExp(pattern);"," } catch (error) {"," process.stderr.write('prek-runner: invalid regex ' + JSON.stringify(pattern) + ': ' + error.message + '\\n');"," process.exit(2);"," }","};","","const readShebang = (file) => {"," try {"," const fd = readFileSync(file, { encoding: null });"," if (fd.length < 2 || fd[0] !== 0x23 || fd[1] !== 0x21) { return null; }"," const nl = fd.indexOf(0x0a);"," const end = nl === -1 ? Math.min(fd.length, 256) : Math.min(nl, 256);"," return fd.slice(2, end).toString('utf8').trim();"," } catch (error) {"," return null;"," }","};","","const interpreterFromShebang = (shebang) => {"," if (!shebang) { return null; }"," const parts = shebang.split(/\\s+/).filter(Boolean);"," if (parts.length === 0) { return null; }"," const first = parts[0];"," let candidate = basename(first);"," if (candidate === 'env' && parts.length > 1) {"," candidate = basename(parts[1].split('=')[0] || parts[1]);"," }"," return candidate.toLowerCase();","};","","const fileMetadataTags = (file) => {"," const tags = new Set();"," let info;"," try { info = statSync(file, { throwIfNoEntry: false }); } catch (error) { info = null; }"," if (!info) { return tags; }"," if (info.isSymbolicLink()) { tags.add('symlink'); }"," if (info.isDirectory()) { tags.add('directory'); }"," if (info.isFile()) {"," if ((info.mode & 0o111) !== 0) { tags.add('executable'); } else { tags.add('non-executable'); }"," }"," return tags;","};","","const isBinaryFile = (file) => {"," try {"," const buf = readFileSync(file);"," const slice = buf.subarray(0, Math.min(buf.length, 8192));"," for (let i = 0; i < slice.length; i += 1) {"," if (slice[i] === 0) { return true; }"," }"," return false;"," } catch (error) {"," return false;"," }","};","","const typesForFile = (file) => {"," const tags = new Set();"," const baseName = basename(file).toLowerCase();"," const ext = extname(file).slice(1).toLowerCase();",""," if (baseName in FILENAME_TYPE_MAP) {"," tags.add(FILENAME_TYPE_MAP[baseName]);"," }",""," for (const [type, extensions] of Object.entries(TYPES_EXTENSION_MAP)) {"," if (extensions.includes(ext) || extensions.includes(baseName)) {"," tags.add(type);"," }"," }",""," const metaTags = fileMetadataTags(file);"," for (const tag of metaTags) { tags.add(tag); }",""," if (tags.size === 0 || tags.has('executable') || tags.has('shell')) {"," const interpreter = interpreterFromShebang(readShebang(file));"," if (interpreter) {"," const interpreterTags = SHEBANG_INTERPRETER_MAP[interpreter];"," if (interpreterTags) {"," for (const tag of interpreterTags) { tags.add(tag); }"," }"," }"," }",""," if (!tags.has('symlink') && !tags.has('directory')) {"," tags.add(isBinaryFile(file) ? 'binary' : 'text');"," }",""," return tags;","};","","const applyFilters = (files, flags) => {"," let filtered = files;",""," if (flags.files) {"," const rx = buildRegex(flags.files);"," filtered = filtered.filter(function (f) { return rx.test(f); });"," }",""," if (flags.exclude) {"," const rx = buildRegex(flags.exclude);"," filtered = filtered.filter(function (f) { return !rx.test(f); });"," }",""," if (flags.types.length > 0) {"," filtered = filtered.filter(function (f) {"," const tags = typesForFile(f);"," return flags.types.every(function (t) { return tags.has(t); });"," });"," }",""," if (flags.typesOr.length > 0) {"," filtered = filtered.filter(function (f) {"," const tags = typesForFile(f);"," return flags.typesOr.some(function (t) { return tags.has(t); });"," });"," }",""," if (flags.excludeTypes.length > 0) {"," filtered = filtered.filter(function (f) {"," const tags = typesForFile(f);"," return !flags.excludeTypes.some(function (t) { return tags.has(t); });"," });"," }",""," return filtered;","};","","// Conservative per-call argv budget. POSIX guarantees 4 KiB, Linux gives ~2 MiB","// in practice. 32 KiB keeps us well clear of Windows' 32767-char limit too.","const ARG_BUDGET = 32 * 1024;","","const chunkFiles = (files) => {"," const chunks = [];"," let current = [];"," let size = 0;",""," for (const file of files) {"," const cost = Buffer.byteLength(file, 'utf8') + 8;",""," if (size + cost > ARG_BUDGET && current.length > 0) {"," chunks.push(current);"," current = [];"," size = 0;"," }",""," current.push(file);"," size += cost;"," }",""," if (current.length > 0) {"," chunks.push(current);"," }",""," return chunks;","};","","const runCommand = (cmd, files, passFilenames) => {"," if (!cmd || cmd.length === 0) {"," process.stderr.write('prek-runner: no command specified after --\\n');"," return 2;"," }",""," const bin = cmd[0];"," const baseArgs = cmd.slice(1);",""," if (!passFilenames) {"," const result = spawnSync(bin, baseArgs, { stdio: 'inherit' });"," return result.status === null ? 1 : result.status;"," }",""," let rc = 0;"," const chunks = files.length === 0 ? [[]] : chunkFiles(files);",""," for (const chunk of chunks) {"," const result = spawnSync(bin, baseArgs.concat(chunk), { stdio: 'inherit' });"," rc = rc | (result.status === null ? 1 : result.status);"," }",""," return rc;","};","","// ─── Built-in hook implementations ──────────────────────────────────","// Each receives the already-filtered file list and returns an exit code.","","function runTrailingWhitespace(files) {"," // Mirrors pre-commit/pre-commit-hooks/trailing_whitespace_fixer.py:"," // strip trailing whitespace from each line, preserve original endings,"," // preserve markdown hard-break trailing two-spaces on non-blank lines."," const WS = new Set([0x20, 0x09, 0x0b, 0x0c, 0x0d]); // SP, TAB, VT, FF, CR"," const MD_RE = /\\.(md|markdown|mdown|mdx)$/i;"," let rc = 0;",""," for (const file of files) {"," const isMarkdown = MD_RE.test(file);"," const buf = readFileSync(file);"," const out = [];"," let i = 0;",""," while (i <= buf.length) {"," let end = i;",""," while (end < buf.length && buf[end] !== 0x0a) {"," end += 1;"," }",""," const hadLf = end < buf.length && buf[end] === 0x0a;"," let contentEnd = end;"," let hadCr = false;",""," if (hadLf && end > i && buf[end - 1] === 0x0d) {"," hadCr = true;"," contentEnd = end - 1;"," }",""," const content = buf.subarray(i, contentEnd);"," let stripEnd = content.length;",""," while (stripEnd > 0 && WS.has(content[stripEnd - 1])) {"," stripEnd -= 1;"," }",""," const nonWhitespace = content.some(function (b) { return !WS.has(b); });",""," if (isMarkdown && content.length >= 2 && content[content.length - 1] === 0x20 && content[content.length - 2] === 0x20 && nonWhitespace) {"," stripEnd = Math.min(stripEnd + 2, content.length);"," }",""," out.push(content.subarray(0, stripEnd));",""," if (hadCr) {"," out.push(Buffer.from([0x0d]));"," }",""," if (hadLf) {"," out.push(Buffer.from([0x0a]));"," }",""," if (!hadLf) {"," break;"," }",""," i = end + 1;"," }",""," const next = Buffer.concat(out);",""," if (!next.equals(buf)) {"," writeFileSync(file, next);"," process.stdout.write('Fixing ' + file + '\\n');"," rc = 1;"," }"," }",""," return rc;","}","","function runEndOfFileFixer(files) {"," // Mirrors pre-commit/pre-commit-hooks/end_of_file_fixer.py: collapse"," // trailing \\n / \\r\\n / \\r runs to a single newline; add a newline if"," // missing; leave empty files alone."," let rc = 0;",""," for (const file of files) {"," const buf = readFileSync(file);",""," if (buf.length === 0) {"," continue;"," }",""," let end = buf.length;"," const last = buf[end - 1];",""," if (last !== 0x0a && last !== 0x0d) {"," writeFileSync(file, Buffer.concat([buf, Buffer.from([0x0a])]));"," process.stdout.write('Fixing ' + file + '\\n');"," rc = 1;"," continue;"," }",""," while (end > 0 && (buf[end - 1] === 0x0a || buf[end - 1] === 0x0d)) {"," end -= 1;"," }",""," if (end === 0) {"," writeFileSync(file, Buffer.alloc(0));"," process.stdout.write('Fixing ' + file + '\\n');"," rc = 1;"," continue;"," }",""," const trailing = buf.subarray(end);"," let keep;",""," if (trailing[0] === 0x0d && trailing[1] === 0x0a) {"," keep = Buffer.from([0x0d, 0x0a]);"," } else if (trailing[0] === 0x0d) {"," keep = Buffer.from([0x0d]);"," } else {"," keep = Buffer.from([0x0a]);"," }",""," if (trailing.equals(keep)) {"," continue;"," }",""," writeFileSync(file, Buffer.concat([buf.subarray(0, end), keep]));"," process.stdout.write('Fixing ' + file + '\\n');"," rc = 1;"," }",""," return rc;","}","","function isInMerge() {"," // Mirrors pre-commit/pre-commit-hooks/check_merge_conflict.py:is_in_merge."," const gitDirResult = spawnSync('git', ['rev-parse', '--git-dir'], { encoding: 'utf8' });"," if (gitDirResult.status !== 0) { return false; }"," const gitDir = gitDirResult.stdout.trim();"," if (!existsSync(join(gitDir, 'MERGE_MSG'))) { return false; }"," return existsSync(join(gitDir, 'MERGE_HEAD'))"," || existsSync(join(gitDir, 'rebase-apply'))"," || existsSync(join(gitDir, 'rebase-merge'));","}","","function runCheckMergeConflict(files, args) {"," // Mirrors pre-commit/pre-commit-hooks/check_merge_conflict.py: only"," // scans for conflict markers when git is mid-merge/rebase, unless the"," // caller passes --assume-in-merge. Skipping the guard means every"," // legit `<<<<<<<` in docs would fail the hook."," const assumeInMerge = Array.isArray(args) && args.includes('--assume-in-merge');"," if (!assumeInMerge && !isInMerge()) { return 0; }",""," const PATTERNS = ['<<<<<<< ', '======= ', '=======\\r\\n', '=======\\n', '>>>>>>> '];"," let rc = 0;",""," for (const file of files) {"," const content = readFileSync(file, 'utf8');"," const lines = content.split('\\n');",""," for (let i = 0; i < lines.length; i += 1) {"," const line = lines[i] + (i < lines.length - 1 ? '\\n' : '');",""," for (const pattern of PATTERNS) {"," if (line.startsWith(pattern)) {"," process.stdout.write(file + ':' + (i + 1) + ': Merge conflict string ' + JSON.stringify(pattern.trim()) + ' found\\n');"," rc = 1;"," }"," }"," }"," }",""," return rc;","}","","function runCheckJson(files) {"," // Mirrors pre-commit/pre-commit-hooks/check_json.py: parse each file"," // and additionally reject duplicate keys."," let rc = 0;",""," for (const file of files) {"," const content = readFileSync(file, 'utf8');",""," try {"," JSON.parse(content);"," detectDuplicateJsonKeys(content, file);"," } catch (error) {"," process.stdout.write(file + ': Failed to json decode (' + error.message + ')\\n');"," rc = 1;"," }"," }",""," return rc;","}","","function detectDuplicateJsonKeys(source, file) {"," // Minimal tokeniser that walks the already-valid JSON source and throws"," // with a message compatible with the Python hook when a duplicate key"," // appears at any object level."," let i = 0;"," const length = source.length;",""," const skipWs = function () {"," while (i < length && /\\s/.test(source[i])) {"," i += 1;"," }"," };",""," const parseString = function () {",` if (source[i] !== '"') {`," throw new Error('expected string at ' + i);"," }"," i += 1;"," let start = i;",` while (i < length && source[i] !== '"') {`," if (source[i] === '\\\\') {"," i += 2;"," } else {"," i += 1;"," }"," }"," const raw = source.slice(start, i);"," i += 1;",` return JSON.parse('"' + raw + '"');`," };",""," const parseValue = function () {"," skipWs();"," const ch = source[i];"," if (ch === '{') { parseObject(); }"," else if (ch === '[') { parseArray(); }",` else if (ch === '"') { parseString(); }`," else {"," while (i < length && ',}]'.indexOf(source[i]) === -1 && !/\\s/.test(source[i])) {"," i += 1;"," }"," }"," };",""," const parseArray = function () {"," i += 1;"," skipWs();"," if (source[i] === ']') { i += 1; return; }"," while (i < length) {"," parseValue();"," skipWs();"," if (source[i] === ',') { i += 1; skipWs(); }"," else if (source[i] === ']') { i += 1; return; }"," }"," };",""," const parseObject = function () {"," i += 1;"," skipWs();"," const seen = new Set();"," if (source[i] === '}') { i += 1; return; }"," while (i < length) {"," skipWs();"," const key = parseString();"," if (seen.has(key)) {"," throw new Error('Duplicate key: ' + key);"," }"," seen.add(key);"," skipWs();"," if (source[i] !== ':') {"," throw new Error('expected colon at ' + i);"," }"," i += 1;"," parseValue();"," skipWs();"," if (source[i] === ',') { i += 1; skipWs(); }"," else if (source[i] === '}') { i += 1; return; }"," }"," };",""," skipWs();"," parseValue();","}","","function runMixedLineEnding(files, args) {"," // Mirrors pre-commit/pre-commit-hooks/mixed_line_ending.py."," const ENDING = { cr: Buffer.from([0x0d]), crlf: Buffer.from([0x0d, 0x0a]), lf: Buffer.from([0x0a]) };"," let fixArg = 'auto';",""," for (let idx = 0; idx < args.length; idx += 1) {"," const a = args[idx];"," if (a === '-f' || a === '--fix') {"," idx += 1;"," fixArg = args[idx];"," } else if (a.indexOf('--fix=') === 0) {"," fixArg = a.slice('--fix='.length);"," }"," }",""," let rc = 0;",""," for (const file of files) {"," const buf = readFileSync(file);"," const counts = { cr: 0, crlf: 0, lf: 0 };"," const lines = [];"," let start = 0;",""," for (let i = 0; i < buf.length; i += 1) {"," const b = buf[i];",""," if (b === 0x0d && buf[i + 1] === 0x0a) {"," lines.push({ content: buf.subarray(start, i), ending: 'crlf' });"," counts.crlf += 1;"," i += 1;"," start = i + 1;"," } else if (b === 0x0d) {"," lines.push({ content: buf.subarray(start, i), ending: 'cr' });"," counts.cr += 1;"," start = i + 1;"," } else if (b === 0x0a) {"," lines.push({ content: buf.subarray(start, i), ending: 'lf' });"," counts.lf += 1;"," start = i + 1;"," }"," }",""," if (start < buf.length) {"," lines.push({ content: buf.subarray(start), ending: null });"," }",""," const distinct = Object.values(counts).filter(function (c) { return c > 0; }).length;"," const mixed = distinct > 1;",""," if (fixArg === 'no') {"," if (mixed) {"," process.stdout.write(file + ': mixed line endings\\n');"," rc = 1;"," }"," continue;"," }",""," let target;",""," if (fixArg === 'auto') {"," if (!mixed) { continue; }"," let max = -1;"," for (const key of ['cr', 'crlf', 'lf']) {"," if (counts[key] >= max) {"," max = counts[key];"," target = key;"," }"," }"," } else if (!(fixArg in ENDING)) {"," process.stderr.write('prek-runner: invalid --fix value ' + fixArg + '\\n');"," return 2;"," } else {"," target = fixArg;"," const other = Object.entries(counts).some(function (entry) { return entry[0] !== target && entry[1] > 0; });"," if (!other) { continue; }"," }",""," const ending = ENDING[target];"," const chunks = [];",""," for (const line of lines) {"," chunks.push(line.content);"," if (line.ending !== null) {"," chunks.push(ending);"," }"," }",""," writeFileSync(file, Buffer.concat(chunks));"," process.stdout.write(file + ': fixed mixed line endings\\n');"," rc = 1;"," }",""," return rc;","}","","// ─── Entry point ────────────────────────────────────────────────────","","const parsed = parseArgs(process.argv.slice(2));","const candidateFiles = discoverFiles(parsed.flags);","const filtered = applyFilters(candidateFiles, parsed.flags);","","if (filtered.length === 0 && !parsed.flags.alwaysRun) {"," process.exit(0);","}","","let code;","","if (parsed.flags.builtin) {"," const impl = BUILTINS[parsed.flags.builtin];"," if (!impl) {"," process.stderr.write('prek-runner: unknown builtin ' + parsed.flags.builtin + '\\n');"," process.exit(2);"," }"," code = impl(filtered, parsed.rest);","} else {"," code = runCommand(parsed.rest, filtered, parsed.flags.passFilenames);","}","","process.exit(code);",""],_e=Re.join(`
|
|
5
|
+
`).find(o=>o.trim()!=="");if(i){const o=i.length>120?`${i.slice(0,117)}...`:i;t.push(` ${o}`)}}return t},"formatListResult"),we=N((e,t)=>{const s=ye(j(),e);for(const n of be(s))t.info(n)},"runList"),E="prek-runner.mjs",xe={css:["css","scss","sass","less"],dockerfile:["dockerfile"],html:["htm","html"],javascript:["cjs","js","jsx","mjs"],json:["json"],jsx:["jsx","tsx"],makefile:["mk","makefile"],markdown:["markdown","md","mdown","mdx"],python:["py","pyi","pyw"],python3:["py","pyi","pyw"],ruby:["rb"],rust:["rs"],shell:["bash","sh","zsh"],sql:["sql"],svg:["svg"],systemd:["service","socket","timer"],toml:["toml"],tsx:["tsx"],typescript:["cts","mts","ts","tsx"],xml:["xml"],yaml:["yaml","yml"]},$e=["binary","directory","executable","non-executable","symlink","text"],ve={bash:["bash","shell"],node:["javascript"],nodejs:["javascript"],perl:["perl"],python:["python"],python3:["python","python3"],ruby:["ruby"],sh:["shell"],zsh:["shell","zsh"]},Ee=["check-json","check-merge-conflict","end-of-file-fixer","mixed-line-ending","trailing-whitespace"],Se=[...Object.keys(xe),...Object.values(ve).flat(),...$e],_e=["#!/usr/bin/env node","// Auto-generated by `vis hook migrate`. Do not edit by hand.","// Replicates the subset of prek / pre-commit framework semantics that a vis","// hook script needs: staged-file discovery, regex + type filters, chunked","// argv dispatch, and a handful of built-in hook implementations.","","import { spawnSync } from 'node:child_process';","import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';","import { basename, extname, join } from 'node:path';","import process from 'node:process';","","const TYPES_EXTENSION_MAP = {"," css: ['css', 'scss', 'sass', 'less'],"," dockerfile: ['dockerfile'],"," html: ['htm', 'html'],"," javascript: ['cjs', 'js', 'jsx', 'mjs'],"," json: ['json'],"," jsx: ['jsx', 'tsx'],"," makefile: ['mk', 'makefile'],"," markdown: ['markdown', 'md', 'mdown', 'mdx'],"," python: ['py', 'pyi', 'pyw'],"," python3: ['py', 'pyi', 'pyw'],"," ruby: ['rb'],"," rust: ['rs'],"," shell: ['bash', 'sh', 'zsh'],"," sql: ['sql'],"," svg: ['svg'],"," systemd: ['service', 'socket', 'timer'],"," toml: ['toml'],"," tsx: ['tsx'],"," typescript: ['cts', 'mts', 'ts', 'tsx'],"," xml: ['xml'],"," yaml: ['yaml', 'yml'],","};","","const FILENAME_TYPE_MAP = {"," dockerfile: 'dockerfile',"," makefile: 'makefile',"," 'gnumakefile': 'makefile',","};","","const SHEBANG_INTERPRETER_MAP = {"," bash: ['bash', 'shell'],"," node: ['javascript'],"," nodejs: ['javascript'],"," perl: ['perl'],"," python: ['python'],"," python3: ['python', 'python3'],"," ruby: ['ruby'],"," sh: ['shell'],"," zsh: ['shell', 'zsh'],","};","","const BUILTINS = {"," 'check-json': runCheckJson,"," 'check-merge-conflict': runCheckMergeConflict,"," 'end-of-file-fixer': runEndOfFileFixer,"," 'mixed-line-ending': runMixedLineEnding,"," 'trailing-whitespace': runTrailingWhitespace,","};","","const parseArgs = (argv) => {"," const flags = {"," allFiles: process.env.VIS_HOOK_ALL_FILES === '1',"," alwaysRun: false,"," builtin: null,"," exclude: null,"," excludeTypes: [],"," files: null,"," fromRef: process.env.VIS_HOOK_FROM_REF || null,"," passFilenames: true,"," toRef: process.env.VIS_HOOK_TO_REF || null,"," types: [],"," typesOr: [],"," };"," const rest = [];"," let seenDoubleDash = false;",""," for (let i = 0; i < argv.length; i += 1) {"," const arg = argv[i];",""," if (seenDoubleDash) {"," rest.push(arg);"," continue;"," }",""," switch (arg) {"," case '--':"," seenDoubleDash = true;"," break;"," case '--all-files':"," flags.allFiles = true;"," break;"," case '--always-run':"," flags.alwaysRun = true;"," break;"," case '--builtin':"," i += 1;"," flags.builtin = argv[i];"," break;"," case '--exclude':"," i += 1;"," flags.exclude = argv[i];"," break;"," case '--from-ref':"," i += 1;"," flags.fromRef = argv[i];"," break;"," case '--to-ref':"," i += 1;"," flags.toRef = argv[i];"," break;"," case '--exclude-types':"," i += 1;"," flags.excludeTypes = (argv[i] || '').split(',').filter(Boolean);"," break;"," case '--files':"," i += 1;"," flags.files = argv[i];"," break;"," case '--no-pass-filenames':"," flags.passFilenames = false;"," break;"," case '--types':"," i += 1;"," flags.types = (argv[i] || '').split(',').filter(Boolean);"," break;"," case '--types-or':"," i += 1;"," flags.typesOr = (argv[i] || '').split(',').filter(Boolean);"," break;"," default:"," process.stderr.write('prek-runner: unknown flag ' + arg + '\\n');"," process.exit(2);"," }"," }",""," return { flags, rest };","};","","const gitListFiles = (args, errorHint) => {"," const result = spawnSync('git', args, { encoding: 'buffer' });"," if (result.status !== 0) {"," process.stderr.write('prek-runner: git ' + errorHint + ' failed\\n');"," process.stderr.write(result.stderr ? result.stderr.toString() : '');"," process.exit(result.status === null ? 1 : result.status);"," }"," const raw = result.stdout.toString('utf8');"," if (raw.length === 0) { return []; }"," return raw.split('\\0').filter(function (f) { return f.length > 0; });","};","","const discoverFiles = (flags) => {"," if (flags.allFiles) {"," return gitListFiles(['ls-files', '-z'], 'ls-files');"," }"," if (flags.fromRef && flags.toRef) {"," return gitListFiles("," ['diff', '--name-only', '--diff-filter=ACM', '-z', flags.fromRef, flags.toRef],"," 'diff --from-ref/--to-ref'"," );"," }"," return gitListFiles(['diff', '--cached', '--name-only', '--diff-filter=ACM', '-z'], 'diff --cached');","};","","const buildRegex = (pattern) => {"," try {"," return new RegExp(pattern);"," } catch (error) {"," process.stderr.write('prek-runner: invalid regex ' + JSON.stringify(pattern) + ': ' + error.message + '\\n');"," process.exit(2);"," }","};","","const readShebang = (file) => {"," try {"," const fd = readFileSync(file, { encoding: null });"," if (fd.length < 2 || fd[0] !== 0x23 || fd[1] !== 0x21) { return null; }"," const nl = fd.indexOf(0x0a);"," const end = nl === -1 ? Math.min(fd.length, 256) : Math.min(nl, 256);"," return fd.slice(2, end).toString('utf8').trim();"," } catch (error) {"," return null;"," }","};","","const interpreterFromShebang = (shebang) => {"," if (!shebang) { return null; }"," const parts = shebang.split(/\\s+/).filter(Boolean);"," if (parts.length === 0) { return null; }"," const first = parts[0];"," let candidate = basename(first);"," if (candidate === 'env' && parts.length > 1) {"," candidate = basename(parts[1].split('=')[0] || parts[1]);"," }"," return candidate.toLowerCase();","};","","const fileMetadataTags = (file) => {"," const tags = new Set();"," let info;"," try { info = statSync(file, { throwIfNoEntry: false }); } catch (error) { info = null; }"," if (!info) { return tags; }"," if (info.isSymbolicLink()) { tags.add('symlink'); }"," if (info.isDirectory()) { tags.add('directory'); }"," if (info.isFile()) {"," if ((info.mode & 0o111) !== 0) { tags.add('executable'); } else { tags.add('non-executable'); }"," }"," return tags;","};","","const isBinaryFile = (file) => {"," try {"," const buf = readFileSync(file);"," const slice = buf.subarray(0, Math.min(buf.length, 8192));"," for (let i = 0; i < slice.length; i += 1) {"," if (slice[i] === 0) { return true; }"," }"," return false;"," } catch (error) {"," return false;"," }","};","","const typesForFile = (file) => {"," const tags = new Set();"," const baseName = basename(file).toLowerCase();"," const ext = extname(file).slice(1).toLowerCase();",""," if (baseName in FILENAME_TYPE_MAP) {"," tags.add(FILENAME_TYPE_MAP[baseName]);"," }",""," for (const [type, extensions] of Object.entries(TYPES_EXTENSION_MAP)) {"," if (extensions.includes(ext) || extensions.includes(baseName)) {"," tags.add(type);"," }"," }",""," const metaTags = fileMetadataTags(file);"," for (const tag of metaTags) { tags.add(tag); }",""," if (tags.size === 0 || tags.has('executable') || tags.has('shell')) {"," const interpreter = interpreterFromShebang(readShebang(file));"," if (interpreter) {"," const interpreterTags = SHEBANG_INTERPRETER_MAP[interpreter];"," if (interpreterTags) {"," for (const tag of interpreterTags) { tags.add(tag); }"," }"," }"," }",""," if (!tags.has('symlink') && !tags.has('directory')) {"," tags.add(isBinaryFile(file) ? 'binary' : 'text');"," }",""," return tags;","};","","const applyFilters = (files, flags) => {"," let filtered = files;",""," if (flags.files) {"," const rx = buildRegex(flags.files);"," filtered = filtered.filter(function (f) { return rx.test(f); });"," }",""," if (flags.exclude) {"," const rx = buildRegex(flags.exclude);"," filtered = filtered.filter(function (f) { return !rx.test(f); });"," }",""," if (flags.types.length > 0) {"," filtered = filtered.filter(function (f) {"," const tags = typesForFile(f);"," return flags.types.every(function (t) { return tags.has(t); });"," });"," }",""," if (flags.typesOr.length > 0) {"," filtered = filtered.filter(function (f) {"," const tags = typesForFile(f);"," return flags.typesOr.some(function (t) { return tags.has(t); });"," });"," }",""," if (flags.excludeTypes.length > 0) {"," filtered = filtered.filter(function (f) {"," const tags = typesForFile(f);"," return !flags.excludeTypes.some(function (t) { return tags.has(t); });"," });"," }",""," return filtered;","};","","// Conservative per-call argv budget. POSIX guarantees 4 KiB, Linux gives ~2 MiB","// in practice. 32 KiB keeps us well clear of Windows' 32767-char limit too.","const ARG_BUDGET = 32 * 1024;","","const chunkFiles = (files) => {"," const chunks = [];"," let current = [];"," let size = 0;",""," for (const file of files) {"," const cost = Buffer.byteLength(file, 'utf8') + 8;",""," if (size + cost > ARG_BUDGET && current.length > 0) {"," chunks.push(current);"," current = [];"," size = 0;"," }",""," current.push(file);"," size += cost;"," }",""," if (current.length > 0) {"," chunks.push(current);"," }",""," return chunks;","};","","const runCommand = (cmd, files, passFilenames) => {"," if (!cmd || cmd.length === 0) {"," process.stderr.write('prek-runner: no command specified after --\\n');"," return 2;"," }",""," const bin = cmd[0];"," const baseArgs = cmd.slice(1);",""," if (!passFilenames) {"," const result = spawnSync(bin, baseArgs, { stdio: 'inherit' });"," return result.status === null ? 1 : result.status;"," }",""," let rc = 0;"," const chunks = files.length === 0 ? [[]] : chunkFiles(files);",""," for (const chunk of chunks) {"," const result = spawnSync(bin, baseArgs.concat(chunk), { stdio: 'inherit' });"," rc = rc | (result.status === null ? 1 : result.status);"," }",""," return rc;","};","","// ─── Built-in hook implementations ──────────────────────────────────","// Each receives the already-filtered file list and returns an exit code.","","function runTrailingWhitespace(files) {"," // Mirrors pre-commit/pre-commit-hooks/trailing_whitespace_fixer.py:"," // strip trailing whitespace from each line, preserve original endings,"," // preserve markdown hard-break trailing two-spaces on non-blank lines."," const WS = new Set([0x20, 0x09, 0x0b, 0x0c, 0x0d]); // SP, TAB, VT, FF, CR"," const MD_RE = /\\.(md|markdown|mdown|mdx)$/i;"," let rc = 0;",""," for (const file of files) {"," const isMarkdown = MD_RE.test(file);"," const buf = readFileSync(file);"," const out = [];"," let i = 0;",""," while (i <= buf.length) {"," let end = i;",""," while (end < buf.length && buf[end] !== 0x0a) {"," end += 1;"," }",""," const hadLf = end < buf.length && buf[end] === 0x0a;"," let contentEnd = end;"," let hadCr = false;",""," if (hadLf && end > i && buf[end - 1] === 0x0d) {"," hadCr = true;"," contentEnd = end - 1;"," }",""," const content = buf.subarray(i, contentEnd);"," let stripEnd = content.length;",""," while (stripEnd > 0 && WS.has(content[stripEnd - 1])) {"," stripEnd -= 1;"," }",""," const nonWhitespace = content.some(function (b) { return !WS.has(b); });",""," if (isMarkdown && content.length >= 2 && content[content.length - 1] === 0x20 && content[content.length - 2] === 0x20 && nonWhitespace) {"," stripEnd = Math.min(stripEnd + 2, content.length);"," }",""," out.push(content.subarray(0, stripEnd));",""," if (hadCr) {"," out.push(Buffer.from([0x0d]));"," }",""," if (hadLf) {"," out.push(Buffer.from([0x0a]));"," }",""," if (!hadLf) {"," break;"," }",""," i = end + 1;"," }",""," const next = Buffer.concat(out);",""," if (!next.equals(buf)) {"," writeFileSync(file, next);"," process.stdout.write('Fixing ' + file + '\\n');"," rc = 1;"," }"," }",""," return rc;","}","","function runEndOfFileFixer(files) {"," // Mirrors pre-commit/pre-commit-hooks/end_of_file_fixer.py: collapse"," // trailing \\n / \\r\\n / \\r runs to a single newline; add a newline if"," // missing; leave empty files alone."," let rc = 0;",""," for (const file of files) {"," const buf = readFileSync(file);",""," if (buf.length === 0) {"," continue;"," }",""," let end = buf.length;"," const last = buf[end - 1];",""," if (last !== 0x0a && last !== 0x0d) {"," writeFileSync(file, Buffer.concat([buf, Buffer.from([0x0a])]));"," process.stdout.write('Fixing ' + file + '\\n');"," rc = 1;"," continue;"," }",""," while (end > 0 && (buf[end - 1] === 0x0a || buf[end - 1] === 0x0d)) {"," end -= 1;"," }",""," if (end === 0) {"," writeFileSync(file, Buffer.alloc(0));"," process.stdout.write('Fixing ' + file + '\\n');"," rc = 1;"," continue;"," }",""," const trailing = buf.subarray(end);"," let keep;",""," if (trailing[0] === 0x0d && trailing[1] === 0x0a) {"," keep = Buffer.from([0x0d, 0x0a]);"," } else if (trailing[0] === 0x0d) {"," keep = Buffer.from([0x0d]);"," } else {"," keep = Buffer.from([0x0a]);"," }",""," if (trailing.equals(keep)) {"," continue;"," }",""," writeFileSync(file, Buffer.concat([buf.subarray(0, end), keep]));"," process.stdout.write('Fixing ' + file + '\\n');"," rc = 1;"," }",""," return rc;","}","","function isInMerge() {"," // Mirrors pre-commit/pre-commit-hooks/check_merge_conflict.py:is_in_merge."," const gitDirResult = spawnSync('git', ['rev-parse', '--git-dir'], { encoding: 'utf8' });"," if (gitDirResult.status !== 0) { return false; }"," const gitDir = gitDirResult.stdout.trim();"," if (!existsSync(join(gitDir, 'MERGE_MSG'))) { return false; }"," return existsSync(join(gitDir, 'MERGE_HEAD'))"," || existsSync(join(gitDir, 'rebase-apply'))"," || existsSync(join(gitDir, 'rebase-merge'));","}","","function runCheckMergeConflict(files, args) {"," // Mirrors pre-commit/pre-commit-hooks/check_merge_conflict.py: only"," // scans for conflict markers when git is mid-merge/rebase, unless the"," // caller passes --assume-in-merge. Skipping the guard means every"," // legit `<<<<<<<` in docs would fail the hook."," const assumeInMerge = Array.isArray(args) && args.includes('--assume-in-merge');"," if (!assumeInMerge && !isInMerge()) { return 0; }",""," const PATTERNS = ['<<<<<<< ', '======= ', '=======\\r\\n', '=======\\n', '>>>>>>> '];"," let rc = 0;",""," for (const file of files) {"," const content = readFileSync(file, 'utf8');"," const lines = content.split('\\n');",""," for (let i = 0; i < lines.length; i += 1) {"," const line = lines[i] + (i < lines.length - 1 ? '\\n' : '');",""," for (const pattern of PATTERNS) {"," if (line.startsWith(pattern)) {"," process.stdout.write(file + ':' + (i + 1) + ': Merge conflict string ' + JSON.stringify(pattern.trim()) + ' found\\n');"," rc = 1;"," }"," }"," }"," }",""," return rc;","}","","function runCheckJson(files) {"," // Mirrors pre-commit/pre-commit-hooks/check_json.py: parse each file"," // and additionally reject duplicate keys."," let rc = 0;",""," for (const file of files) {"," const content = readFileSync(file, 'utf8');",""," try {"," JSON.parse(content);"," detectDuplicateJsonKeys(content, file);"," } catch (error) {"," process.stdout.write(file + ': Failed to json decode (' + error.message + ')\\n');"," rc = 1;"," }"," }",""," return rc;","}","","function detectDuplicateJsonKeys(source, file) {"," // Minimal tokeniser that walks the already-valid JSON source and throws"," // with a message compatible with the Python hook when a duplicate key"," // appears at any object level."," let i = 0;"," const length = source.length;",""," const skipWs = function () {"," while (i < length && /\\s/.test(source[i])) {"," i += 1;"," }"," };",""," const parseString = function () {",` if (source[i] !== '"') {`," throw new Error('expected string at ' + i);"," }"," i += 1;"," let start = i;",` while (i < length && source[i] !== '"') {`," if (source[i] === '\\\\') {"," i += 2;"," } else {"," i += 1;"," }"," }"," const raw = source.slice(start, i);"," i += 1;",` return JSON.parse('"' + raw + '"');`," };",""," const parseValue = function () {"," skipWs();"," const ch = source[i];"," if (ch === '{') { parseObject(); }"," else if (ch === '[') { parseArray(); }",` else if (ch === '"') { parseString(); }`," else {"," while (i < length && ',}]'.indexOf(source[i]) === -1 && !/\\s/.test(source[i])) {"," i += 1;"," }"," }"," };",""," const parseArray = function () {"," i += 1;"," skipWs();"," if (source[i] === ']') { i += 1; return; }"," while (i < length) {"," parseValue();"," skipWs();"," if (source[i] === ',') { i += 1; skipWs(); }"," else if (source[i] === ']') { i += 1; return; }"," }"," };",""," const parseObject = function () {"," i += 1;"," skipWs();"," const seen = new Set();"," if (source[i] === '}') { i += 1; return; }"," while (i < length) {"," skipWs();"," const key = parseString();"," if (seen.has(key)) {"," throw new Error('Duplicate key: ' + key);"," }"," seen.add(key);"," skipWs();"," if (source[i] !== ':') {"," throw new Error('expected colon at ' + i);"," }"," i += 1;"," parseValue();"," skipWs();"," if (source[i] === ',') { i += 1; skipWs(); }"," else if (source[i] === '}') { i += 1; return; }"," }"," };",""," skipWs();"," parseValue();","}","","function runMixedLineEnding(files, args) {"," // Mirrors pre-commit/pre-commit-hooks/mixed_line_ending.py."," const ENDING = { cr: Buffer.from([0x0d]), crlf: Buffer.from([0x0d, 0x0a]), lf: Buffer.from([0x0a]) };"," let fixArg = 'auto';",""," for (let idx = 0; idx < args.length; idx += 1) {"," const a = args[idx];"," if (a === '-f' || a === '--fix') {"," idx += 1;"," fixArg = args[idx];"," } else if (a.indexOf('--fix=') === 0) {"," fixArg = a.slice('--fix='.length);"," }"," }",""," let rc = 0;",""," for (const file of files) {"," const buf = readFileSync(file);"," const counts = { cr: 0, crlf: 0, lf: 0 };"," const lines = [];"," let start = 0;",""," for (let i = 0; i < buf.length; i += 1) {"," const b = buf[i];",""," if (b === 0x0d && buf[i + 1] === 0x0a) {"," lines.push({ content: buf.subarray(start, i), ending: 'crlf' });"," counts.crlf += 1;"," i += 1;"," start = i + 1;"," } else if (b === 0x0d) {"," lines.push({ content: buf.subarray(start, i), ending: 'cr' });"," counts.cr += 1;"," start = i + 1;"," } else if (b === 0x0a) {"," lines.push({ content: buf.subarray(start, i), ending: 'lf' });"," counts.lf += 1;"," start = i + 1;"," }"," }",""," if (start < buf.length) {"," lines.push({ content: buf.subarray(start), ending: null });"," }",""," const distinct = Object.values(counts).filter(function (c) { return c > 0; }).length;"," const mixed = distinct > 1;",""," if (fixArg === 'no') {"," if (mixed) {"," process.stdout.write(file + ': mixed line endings\\n');"," rc = 1;"," }"," continue;"," }",""," let target;",""," if (fixArg === 'auto') {"," if (!mixed) { continue; }"," let max = -1;"," for (const key of ['cr', 'crlf', 'lf']) {"," if (counts[key] >= max) {"," max = counts[key];"," target = key;"," }"," }"," } else if (!(fixArg in ENDING)) {"," process.stderr.write('prek-runner: invalid --fix value ' + fixArg + '\\n');"," return 2;"," } else {"," target = fixArg;"," const other = Object.entries(counts).some(function (entry) { return entry[0] !== target && entry[1] > 0; });"," if (!other) { continue; }"," }",""," const ending = ENDING[target];"," const chunks = [];",""," for (const line of lines) {"," chunks.push(line.content);"," if (line.ending !== null) {"," chunks.push(ending);"," }"," }",""," writeFileSync(file, Buffer.concat(chunks));"," process.stdout.write(file + ': fixed mixed line endings\\n');"," rc = 1;"," }",""," return rc;","}","","// ─── Entry point ────────────────────────────────────────────────────","","const parsed = parseArgs(process.argv.slice(2));","const candidateFiles = discoverFiles(parsed.flags);","const filtered = applyFilters(candidateFiles, parsed.flags);","","if (filtered.length === 0 && !parsed.flags.alwaysRun) {"," process.exit(0);","}","","let code;","","if (parsed.flags.builtin) {"," const impl = BUILTINS[parsed.flags.builtin];"," if (!impl) {"," process.stderr.write('prek-runner: unknown builtin ' + parsed.flags.builtin + '\\n');"," process.exit(2);"," }"," code = impl(filtered, parsed.rest);","} else {"," code = runCommand(parsed.rest, filtered, parsed.flags.passFilenames);","}","","process.exit(code);",""],Re=_e.join(`
|
|
6
6
|
`);var Fe=Object.defineProperty,d=v((e,t)=>Fe(e,"name",{value:t,configurable:!0}),"a$1");const je=new Map([["pre-commit/pre-commit-hooks#check-json","check-json"],["pre-commit/pre-commit-hooks#check-merge-conflict","check-merge-conflict"],["pre-commit/pre-commit-hooks#end-of-file-fixer","end-of-file-fixer"],["pre-commit/pre-commit-hooks#mixed-line-ending","mixed-line-ending"],["pre-commit/pre-commit-hooks#trailing-whitespace","trailing-whitespace"]]),Ae=/[<>=!~]=/,Me=/github\.com[/:]([^/\s]+\/[^/\s.]+)/i,X=`node "$(dirname "$0")/.builtins/${E}"`,Oe="# Generated by `vis hook migrate` from prek",$=d(e=>`'${e.replaceAll("'",String.raw`'\''`)}'`,"shellQuote"),L=d(e=>{for(const t of ae)if(y(l(e,t)))return t},"detectPrekConfig"),Ie=d(e=>le[e]??e,"mapPrekStage"),De=d(e=>Me.exec(e)?.[1]??e,"normalizeRepoKey"),Pe=d(e=>{if(Ae.test(e))return;if(e.startsWith("@")){const n=e.indexOf("@",1);if(n===-1)return{name:e,version:"latest"};const r=e.slice(n+1).trim();return{name:e.slice(0,n),version:r||"latest"}}const t=e.indexOf("@");if(t===-1)return{name:e,version:"latest"};const s=e.slice(t+1).trim();return{name:e.slice(0,t),version:s||"latest"}},"parseAdditionalDep"),Ne=new Set(Se),Te=d(e=>{const t=[];for(const s of[e.types,e.types_or,e.exclude_types])for(const n of s??[])Ne.has(n)||t.push(n);return t},"unknownTypes"),Ce=d((e,t)=>(e.stages&&e.stages.length>0?e.stages:t??["pre-commit"]).map(s=>Ie(s)),"resolveStages"),We=d(e=>{const t=[];return e.files&&t.push("--files",$(e.files)),e.exclude&&t.push("--exclude",$(e.exclude)),e.types&&e.types.length>0&&t.push("--types",$(e.types.join(","))),e.types_or&&e.types_or.length>0&&t.push("--types-or",$(e.types_or.join(","))),e.exclude_types&&e.exclude_types.length>0&&t.push("--exclude-types",$(e.exclude_types.join(","))),e.always_run&&t.push("--always-run"),e.pass_filenames===!1&&t.push("--no-pass-filenames"),t},"buildRunnerFilterFlags"),H=d((e,t)=>{const s=[X,...We(e)];if(t)return s.push("--builtin",t),Array.isArray(e.args)&&e.args.length>0&&s.push("--",...e.args.map(n=>$(n))),s.join(" ");if(s.push("--",e.entry??""),Array.isArray(e.args))for(const n of e.args)s.push($(n));return s.join(" ")},"buildRunnerInvocation"),Be=d((e,t,s)=>{if(e.language==="fail"){const n=e.entry??e.name??e.id??"hook failed";return`echo ${$(n)}; exit 1`}if(s)return H(e,s);if(ce.has(t)){const n=[];if(e.entry&&n.push(e.entry),Array.isArray(e.args))for(const r of e.args)n.push($(r));return(e.pass_filenames??!0)&&!e.always_run&&n.push('"$@"'),n.join(" ")}return H(e)},"buildHookCommand"),Le=d((e,t,s,n)=>{if(Array.isArray(e.additional_dependencies))for(const r of e.additional_dependencies){const i=Pe(r);if(!i){n.push(`"${t}": additional_dependency "${r}" uses a pip-style pin and cannot be added to package.json — install manually.`);continue}s.push({hookId:t,name:i.name,raw:r,version:i.version})}},"collectAdditionalDeps"),He=d(e=>{const t=new Map,s=[],n=[],r=[],i=[];let o=!1;(e.files||e.exclude)&&n.push("top-level files/exclude filter dropped — apply it per hook if needed");for(const c of e.repos??[]){const f=c.repo??"<unknown>",b=f==="local",k=b?void 0:De(f);for(const h of c.hooks??[]){const g=h.id??"<unknown>";let M;if(b){const p=h.language??"system";if(!fe.has(p)){s.push({hookId:g,reason:`language "${p}" needs an isolated toolchain — run via prek or reimplement as a system command`,repo:f});continue}if(p!=="fail"&&!h.entry){s.push({hookId:g,reason:"missing `entry`",repo:f});continue}}else if(k&&(M=je.get(`${k}#${g}`)),!M){s.push({hookId:g,reason:`remote repo "${f}"@${c.rev??"?"} has no bundled equivalent — run via prek or replace with a system command`,repo:f});continue}Le(h,g,i,r);const O=Te(h);O.length>0&&n.push(`hook "${g}": unsupported types ${O.join(", ")} — those entries are ignored by the runner`);const I=Ce(h,e.default_stages);for(const p of I){if(p==="manual")continue;if(!ue.has(p)){s.push({hookId:g,reason:`unsupported stage "${p}"`,repo:f});continue}let x=Be(h,p,M);x.startsWith(X)&&(o=!0),h.verbose&&(x=`(set -x; ${x})`);const D=`${`# ${g}${h.name?`: ${h.name}`:""}`}
|
|
7
7
|
${x}`,u=t.get(p);u?u.push(D):t.set(p,[D])}}}const a=new Map;for(const[c,f]of t){const b=["#!/usr/bin/env sh",Oe];e.fail_fast&&b.push("set -e"),b.push("",f.join(`
|
|
8
8
|
|
|
9
9
|
`),""),a.set(c,b.join(`
|
|
10
10
|
`))}return{additionalDeps:i,droppedFilters:n,manualSteps:r,scripts:a,skippedHooks:s,usesRunner:o}},"convertPrekConfig"),Ve=d(e=>{const t=de(e);if(t&&typeof t=="object")return t},"parsePrekConfig"),qe=d(e=>{if(e.endsWith(".toml")){const s=ge(e);return s&&typeof s=="object"?s:void 0}const t=A(e);return Ve(t)},"loadPrekConfig"),Ge=d((e,t,s)=>{const n=l(e,"package.json"),r=[],i=[];if(!y(n)||t.length===0)return{added:r,skipped:i};const o=A(n),a=JSON.parse(o),c=a.devDependencies??{},f=a.dependencies??{};for(const k of t){if(k.name in c||k.name in f){i.push(k.name);continue}c[k.name]=k.version,r.push(k.name)}if(r.length===0)return{added:r,skipped:i};a.devDependencies=c;const b=pe(n,o,{defaultIndent:" ",useEditorconfig:s});return S(n,`${JSON.stringify(a,void 0,b)}
|
|
11
|
-
`,"utf8"),{added:r,skipped:i}},"mergeAdditionalDependencies"),ze=d((e,t)=>{const s=l(e,t,".builtins");G(s),S(l(s,E),
|
|
12
|
-
`),"utf8")},"writeRunnerAssets"),Ke=d((e,t)=>{w("prek",["--version"],{cwd:e,encoding:"utf8"}).status===0?w("prek",["uninstall"],{cwd:e,encoding:"utf8"}).status===0?t.info("Detached prek via `prek uninstall`."):t.info("`prek uninstall` did not exit cleanly — continuing. You may need to run it manually."):t.info("prek binary not found on PATH — skipping `prek uninstall`. Run it manually if prek is installed elsewhere.")},"detachPrek"),Q=d((e,t,s,n={})=>{const r=L(e),i=n.dryRun===!0;if(!r)return{isError:!0,message:"No prek configuration found (.pre-commit-config.yaml, .pre-commit-config.yml, or prek.toml)"};s.info(`Found prek config at ${r}`);const o=l(e,r),a=A(o),c=qe(o);if(!c)return{isError:!0,message:`Could not parse ${r}`};const{additionalDeps:f,droppedFilters:b,manualSteps:k,scripts:h,skippedHooks:g,usesRunner:M}=He(c);if(h.size===0&&g.length===0)return{isError:!0,message:`${r} has no hooks to migrate`};if(!i){const u=w("git",["config","--local","core.hooksPath"],{cwd:e,encoding:"utf8"});if(u.status===0){const T=u.stdout?.toString().trim();T&&(T.includes(".prek")||T.includes("prek-hooks"))&&w("git",["config","--local","--unset","core.hooksPath"],{cwd:e})}const
|
|
13
|
-
`).length} lines)`):(S(l(O,u),
|
|
11
|
+
`,"utf8"),{added:r,skipped:i}},"mergeAdditionalDependencies"),ze=d((e,t)=>{const s=l(e,t,".builtins");G(s),S(l(s,E),Re,{mode:493}),S(l(s,"README.md"),["# Vis prek runner","","Auto-generated by `vis hook migrate` from a prek/pre-commit config.","This directory is owned by the migrator — do not edit by hand.","",`Supported built-in hooks: ${Ee.join(", ")}`,""].join(`
|
|
12
|
+
`),"utf8")},"writeRunnerAssets"),Ke=d((e,t)=>{w("prek",["--version"],{cwd:e,encoding:"utf8"}).status===0?w("prek",["uninstall"],{cwd:e,encoding:"utf8"}).status===0?t.info("Detached prek via `prek uninstall`."):t.info("`prek uninstall` did not exit cleanly — continuing. You may need to run it manually."):t.info("prek binary not found on PATH — skipping `prek uninstall`. Run it manually if prek is installed elsewhere.")},"detachPrek"),Q=d((e,t,s,n={})=>{const r=L(e),i=n.dryRun===!0;if(!r)return{isError:!0,message:"No prek configuration found (.pre-commit-config.yaml, .pre-commit-config.yml, or prek.toml)"};s.info(`Found prek config at ${r}`);const o=l(e,r),a=A(o),c=qe(o);if(!c)return{isError:!0,message:`Could not parse ${r}`};const{additionalDeps:f,droppedFilters:b,manualSteps:k,scripts:h,skippedHooks:g,usesRunner:M}=He(c);if(h.size===0&&g.length===0)return{isError:!0,message:`${r} has no hooks to migrate`};if(!i){const u=w("git",["config","--local","core.hooksPath"],{cwd:e,encoding:"utf8"});if(u.status===0){const T=u.stdout?.toString().trim();T&&(T.includes(".prek")||T.includes("prek-hooks"))&&w("git",["config","--local","--unset","core.hooksPath"],{cwd:e})}const _=K(t);if(_.isError)return _;_.message&&s.info(_.message)}const O=l(e,t);i||G(O),M&&(i?s.info(` (would write) ${t}/.builtins/${E}`):(ze(e,t),s.info(` Wrote ${t}/.builtins/${E}`)));let I=0;for(const[u,_]of h)i?s.info(` (would write) ${t}/${u} (${_.split(`
|
|
13
|
+
`).length} lines)`):(S(l(O,u),_,{mode:493}),s.info(` Wrote ${t}/${u}`)),I+=1;const{added:p,skipped:x}=i?{added:f.map(u=>u.name),skipped:[]}:Ge(e,f,n.useEditorconfig);if(p.length>0){const u=i?"would add":"Added";s.info(`${u} ${p.length} package${p.length===1?"":"s"} to devDependencies: ${p.join(", ")}`),i||s.info("Run your package manager's install (e.g. `pnpm install`) to pick up the new devDependencies.")}x.length>0&&s.info(`Skipped ${x.length} already-declared package${x.length===1?"":"s"}: ${x.join(", ")}`),i||Ke(e,s);const D=`${o}.bak`;if(i?s.info(` (would remove) ${r} and back it up to ${r}.bak`):(y(D)||S(D,a,"utf8"),ne(o),s.info(`Removed ${r} (backup at ${r}.bak)`)),g.length>0){s.warn(`Skipped ${g.length} hook${g.length===1?"":"s"} that cannot run without prek:`);for(const u of g)s.warn(` - ${u.repo}::${u.hookId} — ${u.reason}`)}if(b.length>0){s.warn("Partial filter translations:");for(const u of b)s.warn(` - ${u}`)}if(k.length>0){s.warn("Manual follow-up required:");for(const u of k)s.warn(` - ${u}`)}return{isError:!1,message:`${i?"would migrate":"Migration complete:"} ${I} stage script${I===1?"":"s"} ${i?"into":"written to"} ${t}/`}},"migrateFromPrek");var Je=Object.defineProperty,Z=v((e,t)=>Je(e,"name",{value:t,configurable:!0}),"a");const Ue="pre-commit",Ye=Z((e,t,s,n)=>{const r=s.stage??Ue,i=l(e,t,r);if(!y(i))throw new Error(`No script found at ${t}/${r}. Install or migrate hooks first.`);if(s.lastCommit&&(s.fromRef||s.toRef))throw new Error("--last-commit cannot be combined with --from-ref or --to-ref");const o=s.lastCommit?"HEAD~1":s.fromRef,a=s.lastCommit?"HEAD":s.toRef;if(o&&!a)throw new Error("--from-ref requires --to-ref");if(a&&!o)throw new Error("--to-ref requires --from-ref");const c={...process.env};s.allFiles&&(c.VIS_HOOK_ALL_FILES="1"),o&&(c.VIS_HOOK_FROM_REF=o),a&&(c.VIS_HOOK_TO_REF=a),n.info(`Running ${t}/${r}${s.allFiles?" (--all-files)":""}${o?` (${o}..${a})`:""}`);const f=w("sh",["-e",i],{cwd:e,env:c,stdio:"inherit"});if(f.error)throw f.error;return f.status??1},"runHookStage"),Xe=Z((e,t,s)=>{const n=Ye(j(),e,t,s);if(n!==0)throw new Error(`Hook stage exited with code ${n}`)},"runRun");var Qe=Object.defineProperty,Ze=v((e,t)=>Qe(e,"name",{value:t,configurable:!0}),"e");const et=Ze((e=J)=>{if(w("git",["config","--local","core.hooksPath"]).status!==0)return{isError:!1,message:"No custom hooks path configured"};const{status:t,stderr:s}=w("git",["config","--local","--unset","core.hooksPath"]);if(t===null)return{isError:!0,message:"git command not found"};if(t&&t!==5)return{isError:!0,message:String(s)};const n=l(e,"_");return y(n)&&re(n,{force:!0,recursive:!0}),{isError:!1,message:""}},"uninstallHooks");var tt=Object.defineProperty,P=v((e,t)=>tt(e,"name",{value:t,configurable:!0}),"u");const st=new Set(z),nt=P(e=>{const t=w("sh",["-n",e],{encoding:"utf8"});if(t.status===null)return`failed to run "sh -n" (${t.error?.message??"unknown error"})`;if(t.status!==0)return t.stderr.trim()||`sh -n exited with ${t.status}`},"runSyntaxCheck"),rt=P(e=>{const t=w("node",["--check",e],{encoding:"utf8"});if(t.status===null)return`failed to run "node --check" (${t.error?.message??"unknown error"})`;if(t.status!==0)return t.stderr.trim()||`node --check exited with ${t.status}`},"runNodeCheck"),it=P((e,t)=>{const s=[],n=l(e,t),r=w("git",["config","--local","core.hooksPath"],{cwd:e,encoding:"utf8"});if(r.status===0){const o=r.stdout.trim(),a=`${t}/_`;o&&o!==a&&s.push({kind:"warning",message:`core.hooksPath is "${o}" — expected "${a}". Re-run \`vis hook install\` to fix.`})}else s.push({kind:"warning",message:"core.hooksPath is not set — run `vis hook install`."});if(y(l(n,"_"))||s.push({kind:"error",message:`Dispatcher directory ${t}/_ is missing. Run \`vis hook install\`.`}),!y(n))return s.push({kind:"error",message:`Hooks directory ${t}/ is missing.`}),{issues:s,ok:!1};let i=!1;for(const o of q(n)){if(o.startsWith(".")||o==="_")continue;if(!st.has(o)){s.push({kind:"warning",message:`Unknown hook "${o}" — not a standard git hook.`,path:l(t,o)});continue}const a=l(n,o);if(!C(a).isFile())continue;const c=C(a).mode&511;(c&64)===0&&s.push({kind:"warning",message:`Script is not owner-executable (mode ${c.toString(8)}).`,path:l(t,o)});const f=nt(a);f&&s.push({kind:"error",message:`Shell syntax error: ${f}`,path:l(t,o)}),A(a).includes(`/.builtins/${E}`)&&(i=!0)}if(i){const o=l(n,".builtins",E);if(y(o)){const a=rt(o);a&&s.push({kind:"error",message:`prek-runner.mjs has a syntax error: ${a}`,path:l(t,".builtins",E)})}else s.push({kind:"error",message:`Hook scripts reference ${t}/.builtins/${E} but the file is missing. Re-run \`vis hook migrate\`.`})}return{issues:s,ok:!s.some(o=>o.kind==="error")}},"validateHooks"),ot=P((e,t)=>{if(e.issues.length===0)return[`Hook directory ${t}/ looks good.`];const s=[];for(const n of e.issues){const r=n.kind==="error"?"ERROR":"WARN ",i=n.path?` (${n.path})`:"";s.push(`${r} ${n.message}${i}`)}return s.push("",e.ok?"No errors — warnings only.":`${e.issues.filter(n=>n.kind==="error").length} error(s).`),s},"formatValidationResult"),at=P((e,t)=>{const s=it(j(),e),n=ot(s,e);for(const r of n)r.startsWith("ERROR")||r.startsWith("WARN")?t.warn(r):t.info(r);if(!s.ok)throw new Error("Hook validation failed")},"runValidate");var lt=Object.defineProperty,m=v((e,t)=>lt(e,"name",{value:t,configurable:!0}),"i");const R=m(e=>e.hooksDir??J,"resolveHooksDirectory"),V=m(e=>new Promise(t=>{const s=oe({input:process.stdin,output:process.stdout});s.question(`${e} (y/N) `,n=>{s.close();const r=n.trim().toLowerCase();t(r==="y"||r==="yes")})}),"confirmPrompt"),ct=m(async(e,t,s)=>{const n=j(),r=U(n),i=L(n);if(r&&i)throw new Error(`Found both husky (${r}/) and prek (${i}). Remove or migrate one before running \`vis hook install\`.`);if(r){if(t.info(`Existing husky installation found at ${r}/`),await V("Would you like to migrate your husky hooks to vis?")){const a=Y(n,e,t,{useEditorconfig:s});if(a.isError)throw new Error(a.message);a.message&&t.info(a.message);return}t.info("Aborting install. Remove husky first or run 'vis hook migrate' to migrate.");return}if(i){if(t.info(`Existing prek configuration found at ${i}`),await V("Would you like to migrate your prek hooks to vis?")){const a=Q(n,e,t,{useEditorconfig:s});if(a.isError)throw new Error(a.message);a.message&&t.info(a.message);return}t.info("Aborting install. Remove the prek config first or run 'vis hook migrate' to migrate.");return}t.info(`Installing git hooks in ${e}/...`);const o=K(e);if(o.message){if(o.isError)throw new Error(o.message);t.info(o.message);return}y(l(n,e,"pre-commit"))||S(l(n,e,"pre-commit"),`#!/usr/bin/env sh
|
|
14
14
|
`,{mode:493}),t.info("Git hooks installed successfully.")},"executeInstall"),ft=m((e,t,s,n)=>{const r=j(),i=U(r),o=L(r);if(i&&o)throw new Error(`Found both husky (${i}/) and prek (${o}). Migrate one at a time — rename or remove one before retrying.`);if(!i&&!o)throw new Error("No husky (.husky/) or prek (.pre-commit-config.yaml / prek.toml) configuration found to migrate.");t&&s.info("(dry-run) no files will be written");const a=i?Y(r,e,s,{dryRun:t,useEditorconfig:n}):Q(r,e,s,{dryRun:t,useEditorconfig:n});if(a.isError)throw new Error(a.message);a.message&&s.info(a.message)},"executeMigrate"),W="# vis:secrets-hook",ut=`#!/usr/bin/env sh
|
|
15
15
|
${W}
|
|
16
16
|
# Scan staged files for secrets before each commit. Remove this block or the whole file to disable.
|
|
@@ -19,4 +19,4 @@ pnpm exec vis secrets --staged --quiet || exit 1
|
|
|
19
19
|
|
|
20
20
|
${W}
|
|
21
21
|
pnpm exec vis secrets --staged --quiet || exit 1
|
|
22
|
-
`;S(r,o),ie(r,493),s.info(`Appended secrets scan to ${r}.`);return}S(r,ut,{mode:493}),s.info(`Created ${r} with a secrets-scan pre-commit check.`)},"executeAdd"),pt=m((e,t)=>{t.info("Removing git hooks...");const s=et(e);if(s.message){if(s.isError)throw new Error(s.message);t.info(s.message);return}t.info("Git hooks removed successfully.")},"executeUninstall"),gt=m(async({logger:e,options:t,visConfig:s})=>{await ct(
|
|
22
|
+
`;S(r,o),ie(r,493),s.info(`Appended secrets scan to ${r}.`);return}S(r,ut,{mode:493}),s.info(`Created ${r} with a secrets-scan pre-commit check.`)},"executeAdd"),pt=m((e,t)=>{t.info("Removing git hooks...");const s=et(e);if(s.message){if(s.isError)throw new Error(s.message);t.info(s.message);return}t.info("Git hooks removed successfully.")},"executeUninstall"),gt=m(async({logger:e,options:t,visConfig:s})=>{await ct(R(t),e,s?.editorconfig??!0)},"hookInstallImpl"),ht=m(({logger:e,options:t})=>{pt(R(t),e)},"hookUninstallImpl"),mt=m(({logger:e,options:t,visConfig:s})=>{ft(R(t),!!t.dryRun,e,s?.editorconfig??!0)},"hookMigrateImpl"),kt=m(({logger:e,options:t})=>{we(R(t),e)},"hookListImpl"),yt=m(({logger:e,options:t})=>{at(R(t),e)},"hookValidateImpl"),bt=m(({argument:e,logger:t,options:s})=>{Xe(R(s),{allFiles:!!s.allFiles,fromRef:s.fromRef,lastCommit:!!s.lastCommit,stage:e[0],toRef:s.toRef},t)},"hookRunImpl"),wt=m(({argument:e,logger:t,options:s})=>{dt(e[0],R(s),t)},"hookAddImpl"),_t=gt,Rt=ht,Ft=mt,jt=kt,At=yt,Mt=bt,Ot=wt;export{Ot as hookAddExecute,_t as hookInstallExecute,jt as hookListExecute,Ft as hookMigrateExecute,Mt as hookRunExecute,Rt as hookUninstallExecute,At as hookValidateExecute};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var _e=Object.defineProperty;var L=(e,n)=>_e(e,"name",{value:n,configurable:!0});import{createRequire as $e}from"node:module";import{n as pe,M as F,$ as je,C as ke,h as Ce,
|
|
2
|
-
`:"";let v="";switch(Y){case f.JSTOXML_OBJECT:{const{_name:g,_content:l}=e;if(l===null&&typeof P!="function"){v=`${I}${
|
|
3
|
-
${
|
|
4
|
-
`},"serializeBomToXml"),
|
|
5
|
-
`,P=e.output??(m==="xml"?"sbom.cdx.xml":"sbom.cdx.json");if(P==="-"){process.stdout.write(B);return}const k=ke(t,P);Ce(Le(k)),Se(k,B,"utf8");const E=h.components?.length??0,G=h.dependencies?.length??0;se.success(`SBOM written to ${k}`),se.notice(`${E} components, ${G} dependency edges`)},"execute");export{
|
|
1
|
+
var _e=Object.defineProperty;var L=(e,n)=>_e(e,"name",{value:n,configurable:!0});import{createRequire as $e}from"node:module";import{n as pe,M as F,$ as je,C as ke,h as Ce,K as Le}from"./config.js";import{b2 as Pe,y as we,m as Te,p as se}from"./bin.js";import{r as xe}from"../packem_shared/docker-Dl0AoVTZ.js";import{F as De}from"../packem_shared/lockfile-i-qvq_k8.js";const ve=$e(import.meta.url),H=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,ie=L(e=>{if(typeof H<"u"&&H.versions&&H.versions.node){const[n,t]=H.versions.node.split(".").map(Number);if(n>22||n===22&&t>=3||n===20&&t>=16)return H.getBuiltinModule(e)}return ve(e)},"__cjs_getBuiltinModule"),{readdirSync:Oe,writeFileSync:Se}=ie("node:fs"),{randomUUID:Ae}=ie("node:crypto");var Be=Object.defineProperty,j=L((e,n)=>Be(e,"name",{value:n,configurable:!0}),"a$1");const f={ARRAY:"array",BOOLEAN:"boolean",DATE:"date",FUNCTION:"function",JSTOXML_OBJECT:"jstoxml-object",NULL:"null",NUMBER:"number",OBJECT:"object",STRING:"string"},Me=[f.STRING,f.NUMBER,f.BOOLEAN],Re='<?xml version="1.0" encoding="UTF-8"?>',re=["_selfCloseTag","_attrs"],Ee=j((e="",n=0)=>e.repeat(n),"getIndentStr"),Z=j(e=>Array.isArray(e)&&f.ARRAY||typeof e===f.OBJECT&&e!==null&&e._name&&f.JSTOXML_OBJECT||e instanceof Date&&f.DATE||e===null&&f.NULL||typeof e,"getType"),le=j(e=>e.startsWith("<![CDATA["),"isCDATA"),ue=j((e="",n={},t)=>{let o=e;if(typeof e===f.STRING){if(le(e))return e;const s=new RegExp(`(${Object.keys(n).join("|")})(?!(\\w|#)*;)`,"g");o=String(e).replace(s,(p,d)=>n[d]||"")}return typeof t=="function"?t(o):o},"mapStr"),Ne=j((e={},n,t,o)=>(Array.isArray(e)?e:Object.entries(e).map(([s,p])=>({[s]:p}))).reduce((s,p)=>{const d=Object.keys(p)[0],b=p[d];if(typeof t===f.FUNCTION&&t(d,b))return s;const m=n?ue(b,n):b,h=!o&&m===!0?"":`="${m}"`;return s.push(`${d}${h}`),s},[]),"getAttributeKeyVals"),Ie=j((e={},n,t,o)=>{const s=Ne(e,n,t,o);return s.length===0?"":` ${s.join(" ")}`},"formatAttributes"),Ue=j((e={})=>Object.keys(e).map(n=>({_name:n,_content:e[n]})),"objToArray"),Fe=j(e=>Me.includes(Z(e)),"isPrimitive"),Ge=j(e=>!e.match("<"),"isSimpleXML"),Je=j(({header:e,isOutputStart:n})=>e&&n?typeof e===f.BOOLEAN?Re:e:"","getHeaderString"),ce={"<":"<",">":">","&":"&",'"':"""},q=j((e={},n={})=>{const{depth:t=0,indent:o,_isFirstItem:s,_isOutputStart:p=!0,header:d,attributeReplacements:b={},attributeFilter:m,attributeExplicitTrue:h=!1,contentReplacements:B={},contentMap:P,selfCloseTags:k=!0}=n,E=typeof b=="boolean"&&!b?{}:{...ce,...b},G=typeof B=="boolean"&&!B?{}:{...ce,...B},w=typeof o=="string",T=Ee(o,t),Y=Z(e),J=Je({header:d,indent:o,depth:t,isOutputStart:p}),N=p&&!J&&s&&t===0,I=w&&!N?`
|
|
2
|
+
`:"";let v="";switch(Y){case f.JSTOXML_OBJECT:{const{_name:g,_content:l}=e;if(l===null&&typeof P!="function"){v=`${I}${T}${g}`;break}if(Array.isArray(l)&&l.every(Fe))return l.map(C=>q({_name:g,_content:C},{...n,depth:t,_isOutputStart:!1})).join("");if(re.includes(g))break;const $=q(l,{...n,depth:t+1,_isOutputStart:N}),M=Z($),O=Ge($),S=le($),R=`${I}${T}`;if(g==="_comment"){v+=`${R}<!-- ${l} -->`;break}const K=M==="undefined"||$==="",c=k,r=e._selfCloseTag,i=typeof r===f.BOOLEAN?K&&r:K&&c,a=i?"/":"",u=Ie(e._attrs,E,m,h),y=`<${g}${u}${a}>`,A=w&&!O&&!S?`
|
|
3
|
+
${T}`:"",x=i?"":`${$}${A}</${g}>`;v+=`${R}${y}${x}`;break}case f.OBJECT:{const g=Object.keys(e);v=g.map((l,$)=>{const M={...n,_isFirstItem:$===0,_isLastItem:$+1===g.length,_isOutputStart:N},O={_name:l};if(Z(e[l])===f.OBJECT&&(re.forEach(S=>{const R=e[l][S];typeof R<"u"&&(O[S]=R,delete e[l][S])}),typeof e[l]._content<"u"&&Object.keys(e[l]).length>1)){const S=Object.assign({},e[l]);delete S._content,O._content=[...Ue(S),e[l]._content]}return typeof O._content>"u"&&(O._content=e[l]),q(O,M)},n).join("");break}case f.FUNCTION:{const g=e(n);v=q(g,n);break}case f.ARRAY:{v=e.map((g,l)=>{const $={...n,_isFirstItem:l===0,_isLastItem:l+1===e.length,_isOutputStart:N};return q(g,$)}).join("");break}default:{v=ue(e,G,P);break}}return`${J}${v}`},"toXML");var Xe=Object.defineProperty,z=L((e,n)=>Xe(e,"name",{value:n,configurable:!0}),"r$1");const te=z(e=>{try{return pe(e)}catch{return}},"readJsonSafe"),qe=z(e=>{if(e.length===0||e.includes("..")||e.startsWith(".")||e.includes("\0")||e.includes("\\"))return!1;if(e.startsWith("@")){const n=e.indexOf("/");return n>1&&!e.includes("/",n+1)}return!e.includes("/")},"isSafePackageName"),ze=z(e=>e.length>0&&!e.includes("/")&&!e.includes("\\")&&!e.includes("..")&&!e.includes("\0"),"isSafeVersion"),We=z((e,n,t)=>{const o=`${n.replaceAll("/","+")}@${t}`,s=F(e,"node_modules",".pnpm"),p=te(F(s,o,"node_modules",n,"package.json"));if(p)return p;let d;try{d=Oe(s)}catch{return}const b=`${o}_`;for(const m of d){if(!m.startsWith(b))continue;const h=te(F(s,m,"node_modules",n,"package.json"));if(h)return h}},"readPnpmVirtualStore"),He=z((e,n,t)=>{const o=te(F(e,"node_modules",n,"package.json"));return o?.version===t?o:void 0},"readHoistedCopy"),Ve=z((e,n,t)=>{if(!(!qe(n)||!ze(t)))return We(e,n,t)??He(e,n,t)},"readInstalledPackageMetadata");var Ye=Object.defineProperty,me=L((e,n)=>Ye(e,"name",{value:n,configurable:!0}),"i");const fe=new Set(["0BSD","AGPL-3.0","AGPL-3.0-only","AGPL-3.0-or-later","Apache-1.1","Apache-2.0","Artistic-2.0","BlueOak-1.0.0","BSD-2-Clause","BSD-3-Clause","BSL-1.0","CC0-1.0","CC-BY-3.0","CC-BY-4.0","CDDL-1.0","CDDL-1.1","EPL-1.0","EPL-2.0","GPL-2.0","GPL-2.0-only","GPL-2.0-or-later","GPL-3.0","GPL-3.0-only","GPL-3.0-or-later","ISC","LGPL-2.0","LGPL-2.1","LGPL-3.0","MIT","MIT-0","MPL-1.1","MPL-2.0","Python-2.0","Unlicense","WTFPL","Zlib"]),Ke={apache2:"Apache-2.0","apache 2.0":"Apache-2.0",bsd:"BSD-3-Clause","bsd-2":"BSD-2-Clause","bsd-3":"BSD-3-Clause",mit:"MIT",public:"Unlicense","public domain":"Unlicense"},Ze=(()=>{const e=new Map;for(const n of fe)e.set(n.toLowerCase(),n);for(const[n,t]of Object.entries(Ke))e.set(n,t);return e})(),Qe=me(e=>{const n=e.trim();if(n.length!==0)return fe.has(n)?n:Ze.get(n.toLowerCase())},"normalizeSpdxId"),en=me(e=>{let n;if(typeof e.license=="string")n=e.license;else if(e.license&&typeof e.license=="object"&&typeof e.license.type=="string")n=e.license.type;else if(Array.isArray(e.licenses)&&e.licenses.length>0){const s=e.licenses[0];s&&typeof s.type=="string"&&(n=s.type)}if(!n)return;const t=n.trim();if(t.length===0)return;if(/[()]|\b(?:and|or|with)\b/i.test(t))return[{expression:t}];const o=Qe(t);return o?[{license:{id:o}}]:[{license:{name:t}}]},"extractLicenseChoice");var nn=Object.defineProperty,de=L((e,n)=>nn(e,"name",{value:n,configurable:!0}),"t");const tn={sha256:"SHA-256",sha384:"SHA-384",sha512:"SHA-512"},on={sha256:64,sha384:96,sha512:128},sn=de(e=>{const n={name:e.name,version:e.version},{integrity:t}=e;return t&&t.hex.length===on[t.algorithm]&&(n.hash={alg:tn[t.algorithm],content:t.hex}),e.dependencies&&(n.dependencies=e.dependencies),e.peerDependencies&&(n.peerDependencies=e.peerDependencies),e.optionalDependencies&&(n.optionalDependencies=e.optionalDependencies),n},"toResolvedPackage"),rn=[{file:"pnpm-lock.yaml",type:"pnpm"},{file:"package-lock.json",type:"npm"},{file:"yarn.lock",type:"yarn"},{file:"bun.lock",type:"bun"}],cn=de(e=>{for(const{file:n,type:t}of rn){let o;try{o=je(F(e,n))}catch{continue}const s=new Map;for(const p of De(o,t))s.set(`${p.name}@${p.version}`,sn(p));return{packages:s,type:t}}},"readLockfilePackages");var an=Object.defineProperty,he=L((e,n)=>an(e,"name",{value:n,configurable:!0}),"r");const V=he(e=>e.replaceAll(/[^\w.~-]/g,n=>`%${(n.codePointAt(0)??0).toString(16).toUpperCase().padStart(2,"0")}`),"encodeSegment"),U=he((e,n)=>{const t=e.toLowerCase();if(t.startsWith("@")){const o=t.indexOf("/");if(o>0){const s=t.slice(0,o),p=t.slice(o+1);return`pkg:npm/${V(s)}/${V(p)}@${V(n)}`}}return`pkg:npm/${V(t)}@${V(n)}`},"toNpmPurl");var pn=Object.defineProperty,ge=L((e,n)=>pn(e,"name",{value:n,configurable:!0}),"s");const ln=ge(e=>{const n=e.indexOf(":");return n<=0?e:e.slice(0,n)==="npm"?e.slice(n+1):e},"stripProtocolPrefix"),ee=ge((e,n,t)=>{const o=t.get(e);if(!o||o.size===0)return;if(o.has(n))return n;const s=ln(n);if(s!==n&&o.has(s))return s;const p=[...o];return Pe.maxSatisfying(p,s,{includePrerelease:!0})||p[0]},"resolveSpecifier");var un=Object.defineProperty,_=L((e,n)=>un(e,"name",{value:n,configurable:!0}),"p");const mn="1.6",fn="CycloneDX",dn="http://cyclonedx.org/schema/bom-1.6.schema.json",hn="@visulima/vis",ae=_(e=>{try{return pe(e)}catch{return}},"readPackageJson"),gn=_(e=>{if(e){if(typeof e=="string")return e;if(typeof e=="object"&&e.name)return e.email?`${e.name} <${e.email}>`:e.name}},"toAuthorString"),yn=_(e=>{if(e)return typeof e=="string"?e:e.url},"toRepositoryUrl"),bn=_(e=>{if(e)return typeof e=="string"?e:e.url},"toBugsUrl"),_n=_(e=>{const n=[];e.homepage&&n.push({type:"website",url:e.homepage});const t=yn(e.repository);t&&n.push({type:"vcs",url:t});const o=bn(e.bugs);return o&&n.push({type:"issue-tracker",url:o}),n.length>0?n:void 0},"buildExternalReferences"),$n=_(e=>e==="application"||e==="service"||e==="tool"?"application":"library","toCycloneDxComponentType"),ne=_((e,n)=>{if(!n)return;n.description&&(e.description=n.description);const t=gn(n.author);t&&(e.author=t);const o=en(n);o&&(e.licenses=o);const s=_n(n);s&&(e.externalReferences=s)},"decoratePackageComponent"),vn=_(e=>{const{focus:n,generatorVersion:t,includeDev:o=!1,now:s=new Date,projectGraph:p,serialNumber:d,workspace:b,workspaceRoot:m}=e,h=n&&n.length>0?[...xe(n,p)].sort():Object.keys(b.projects).sort(),B=new Set(h),P=new Map;for(const c of h){const r=b.projects[c];r&&P.set(c,ae(F(m,r.root,"package.json")))}const k=[],E=new Map;for(const c of h){const r=b.projects[c];if(!r)continue;const i=P.get(c),a=i?.version??"0.0.0",u=U(c,a);E.set(c,u);const y={"bom-ref":u,name:c,purl:u,type:$n(r.projectType),version:a};ne(y,i),k.push(y)}const G=cn(m),w=new Map,T=new Map;if(G)for(const c of G.packages.values()){w.set(`${c.name}@${c.version}`,c);let r=T.get(c.name);r||(r=new Set,T.set(c.name,r)),r.add(c.version)}const Y=[],J=[],N=new Map;for(const c of h){const r=P.get(c);if(!r)continue;const i=[r.dependencies,r.peerDependencies];o&&i.push(r.devDependencies);const a=new Set,u=_((y,A)=>{if(A)for(const[x,C]of Object.entries(A)){if(B.has(x)){const X=E.get(x);X&&a.add(X);continue}const D=ee(x,C,T);D&&(a.add(U(x,D)),y.push(`${x}@${D}`))}},"seedRef");for(const y of i)u(Y,y);u(J,r.optionalDependencies),N.set(c,a)}const I=new Map,v=new Map,g=_((c,r)=>{const i=[...c];for(;i.length>0;){const a=i.pop(),u=I.get(a);if(u==="required"||u==="optional"&&r==="optional")continue;I.set(a,r);const y=w.get(a);if(!y)continue;const A=v.get(a)??new Set,x=[y.dependencies,y.peerDependencies];for(const C of x)if(C)for(const[D,X]of Object.entries(C))for(const W of X){const Q=ee(D,W,T);Q&&(A.add(U(D,Q)),i.push(`${D}@${Q}`))}if(y.optionalDependencies)for(const[C,D]of Object.entries(y.optionalDependencies))for(const X of D){const W=ee(C,X,T);W&&(A.add(U(C,W)),J.push(`${C}@${W}`))}A.size>0&&v.set(a,A)}},"walk");g(Y,"required"),g(J,"optional");const l=[],$=[...I.keys()].sort();for(const c of $){const r=w.get(c);if(!r)continue;const i=U(r.name,r.version),a={"bom-ref":i,name:r.name,purl:i,scope:I.get(c)??"required",type:"library",version:r.version};r.hash&&(a.hashes=[r.hash]),ne(a,Ve(m,r.name,r.version)),l.push(a)}const M=[];for(const[c,r]of N){const i=E.get(c);if(!i)continue;const a=[...r].sort();M.push(a.length>0?{dependsOn:a,ref:i}:{ref:i})}for(const c of $){const r=w.get(c);if(!r)continue;const i=U(r.name,r.version),a=v.get(c),u=a?[...a].sort():[];M.push(u.length>0?{dependsOn:u,ref:i}:{ref:i})}M.sort((c,r)=>c.ref.localeCompare(r.ref));const O=ae(F(m,"package.json")),S=(()=>{if(n?.length===1){const u=k.find(y=>y.name===n[0]);if(u)return{"bom-ref":u["bom-ref"],name:u.name,purl:u.purl,type:u.type,version:u.version}}const c=O?.name??"workspace",r=O?.version??"0.0.0",i=U(c,r),a={"bom-ref":i,name:c,purl:i,type:"application",version:r};return ne(a,O),a})(),R=S["bom-ref"],K=R?k.filter(c=>c["bom-ref"]!==R):k;return{$schema:dn,bomFormat:fn,components:[...K,...l],dependencies:M,metadata:{component:S,lifecycles:[{phase:"build"}],timestamp:s.toISOString(),tools:{components:[{name:hn,type:"application",...t?{version:t}:{}}]}},serialNumber:d??`urn:uuid:${Ae()}`,specVersion:mn,version:1}},"buildCycloneDxBom"),On=_(e=>{const n={version:e.version??1,xmlns:"http://cyclonedx.org/schema/bom/1.6"};e.serialNumber&&(n.serialNumber=e.serialNumber);const t=[];return e.metadata&&t.push(Sn(e.metadata)),e.components&&e.components.length>0&&t.push({_content:e.components.map(o=>oe(o)),_name:"components"}),e.dependencies&&e.dependencies.length>0&&t.push({_content:e.dependencies.map(o=>kn(o)),_name:"dependencies"}),`${q({_attrs:n,_content:t,_name:"bom"},{header:!0,indent:" ",selfCloseTags:!0})}
|
|
4
|
+
`},"serializeBomToXml"),Sn=_(e=>{const n=[];return e.timestamp&&n.push({timestamp:e.timestamp}),e.lifecycles&&e.lifecycles.length>0&&n.push({_content:e.lifecycles.map(t=>{const o=[];return t.phase&&o.push({phase:t.phase}),t.name&&o.push({name:t.name}),t.description&&o.push({description:t.description}),{_content:o,_name:"lifecycle"}}),_name:"lifecycles"}),e.tools?.components&&n.push({_content:[{_content:e.tools.components.map(t=>oe(t)),_name:"components"}],_name:"tools"}),e.component&&n.push(oe(e.component)),{_content:n,_name:"metadata"}},"metadataToXmlElement"),oe=_(e=>{const n={type:e.type};e["bom-ref"]&&(n["bom-ref"]=e["bom-ref"]);const t=[];e.group&&t.push({group:e.group}),t.push({name:e.name}),e.version&&t.push({version:e.version}),e.description&&t.push({description:e.description}),e.author&&t.push({author:e.author}),e.hashes&&e.hashes.length>0&&t.push({_content:e.hashes.map(s=>({_attrs:{alg:s.alg},_content:s.content,_name:"hash"})),_name:"hashes"});const o=jn(e.licenses);return o&&t.push(o),e.purl&&t.push({purl:e.purl}),e.scope&&t.push({scope:e.scope}),e.externalReferences&&e.externalReferences.length>0&&t.push({_content:e.externalReferences.map(s=>({_attrs:{type:s.type},_content:[{url:s.url}],_name:"reference"})),_name:"externalReferences"}),{_attrs:n,_content:t,_name:"component"}},"componentToXmlElement"),jn=_(e=>{if(!e||e.length===0)return;const n=[];for(const t of e){if("expression"in t){n.push({expression:t.expression});continue}const o=[];"id"in t.license&&t.license.id?o.push({id:t.license.id}):"name"in t.license&&t.license.name&&o.push({name:t.license.name}),n.push({_content:o,_name:"license"})}return{_content:n,_name:"licenses"}},"licensesToXmlElement"),kn=_(e=>e.dependsOn&&e.dependsOn.length>0?{_attrs:{ref:e.ref},_content:e.dependsOn.map(n=>({_attrs:{ref:n},_name:"dependency"})),_name:"dependency"}:{_attrs:{ref:e.ref},_name:"dependency"},"dependencyToXmlElement");var Cn=Object.defineProperty,ye=L((e,n)=>Cn(e,"name",{value:n,configurable:!0}),"m");const be=["json","xml"],Ln=ye(e=>be.includes(e),"isSbomFormat"),Bn=ye(async({options:e,visConfig:n,workspaceRoot:t})=>{if(!t)throw new Error("Could not determine workspace root. Run inside a monorepo.");const{packageJsons:o,workspace:s}=we(t,n),p=Te(t,s,o),d=e.focus,b=d?d.split(",").map(w=>w.trim()).filter(Boolean):void 0,m=(e.format??"json").toLowerCase();if(!Ln(m))throw new Error(`Unknown --format: "${m}". Expected one of: ${be.join(", ")}.`);const h=vn({focus:b,includeDev:!!e.includeDev,projectGraph:p,workspace:s,workspaceRoot:t}),B=m==="xml"?On(h):`${JSON.stringify(h,void 0,2)}
|
|
5
|
+
`,P=e.output??(m==="xml"?"sbom.cdx.xml":"sbom.cdx.json");if(P==="-"){process.stdout.write(B);return}const k=ke(t,P);Ce(Le(k)),Se(k,B,"utf8");const E=h.components?.length??0,G=h.dependencies?.length??0;se.success(`SBOM written to ${k}`),se.notice(`${E} components, ${G} dependency edges`)},"execute");export{Bn as default};
|