@visulima/vis 1.0.0-alpha.45 → 1.0.0-alpha.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/bin.js +1 -1
  3. package/dist/binx.js +1 -1
  4. package/dist/packem_chunks/CONFIG_FILES.js +3 -3
  5. package/dist/packem_chunks/agent-instructions.js +11 -0
  6. package/dist/packem_chunks/bloom-status.js +1 -1
  7. package/dist/packem_chunks/bloom-sync.js +1 -1
  8. package/dist/packem_chunks/catalog.js +1 -1
  9. package/dist/packem_chunks/cli-exec.js +1 -1
  10. package/dist/packem_chunks/cli-main.js +23 -23
  11. package/dist/packem_chunks/defineReleasePlugin.js +3 -0
  12. package/dist/packem_chunks/fix.js +1 -1
  13. package/dist/packem_chunks/group-tags.js +1 -0
  14. package/dist/packem_chunks/handler10.js +1 -1
  15. package/dist/packem_chunks/handler12.js +1 -1
  16. package/dist/packem_chunks/handler13.js +1 -1
  17. package/dist/packem_chunks/handler14.js +1 -1
  18. package/dist/packem_chunks/handler15.js +1 -1
  19. package/dist/packem_chunks/handler19.js +1 -1
  20. package/dist/packem_chunks/handler20.js +1 -1
  21. package/dist/packem_chunks/handler21.js +1 -1
  22. package/dist/packem_chunks/handler24.js +1 -1
  23. package/dist/packem_chunks/handler26.js +1 -1
  24. package/dist/packem_chunks/handler28.js +1 -1
  25. package/dist/packem_chunks/handler32.js +1 -1
  26. package/dist/packem_chunks/handler4.js +1 -1
  27. package/dist/packem_chunks/handler40.js +19 -19
  28. package/dist/packem_chunks/handler5.js +1 -1
  29. package/dist/packem_chunks/handler50.js +1 -1
  30. package/dist/packem_chunks/handler51.js +1 -1
  31. package/dist/packem_chunks/handler54.js +1 -1
  32. package/dist/packem_chunks/handler57.js +11 -5
  33. package/dist/packem_chunks/handler58.js +5 -11
  34. package/dist/packem_chunks/handler59.js +11 -3
  35. package/dist/packem_chunks/handler6.js +1 -1
  36. package/dist/packem_chunks/handler60.js +3 -22
  37. package/dist/packem_chunks/handler61.js +21 -60
  38. package/dist/packem_chunks/handler62.js +61 -3
  39. package/dist/packem_chunks/handler63.js +3 -6
  40. package/dist/packem_chunks/handler64.js +6 -9
  41. package/dist/packem_chunks/handler65.js +9 -2
  42. package/dist/packem_chunks/handler66.js +2 -24
  43. package/dist/packem_chunks/handler67.js +24 -25
  44. package/dist/packem_chunks/handler68.js +25 -153
  45. package/dist/packem_chunks/handler69.js +153 -10
  46. package/dist/packem_chunks/handler7.js +1 -1
  47. package/dist/packem_chunks/handler70.js +10 -23
  48. package/dist/packem_chunks/handler71.js +23 -322
  49. package/dist/packem_chunks/handler72.js +273 -659
  50. package/dist/packem_chunks/handler73.js +708 -48
  51. package/dist/packem_chunks/handler74.js +48 -27
  52. package/dist/packem_chunks/handler75.js +27 -3
  53. package/dist/packem_chunks/handler76.js +3 -190
  54. package/dist/packem_chunks/handler77.js +189 -37
  55. package/dist/packem_chunks/handler78.js +38 -0
  56. package/dist/packem_chunks/heal.js +1 -1
  57. package/dist/packem_chunks/help-command.js +1 -1
  58. package/dist/packem_chunks/index3.js +1 -1
  59. package/dist/packem_chunks/keys-refresh.js +1 -1
  60. package/dist/packem_chunks/list.js +1 -1
  61. package/dist/packem_chunks/orchestrator.js +26 -23
  62. package/dist/packem_chunks/prune.js +1 -1
  63. package/dist/packem_chunks/state.js +3 -3
  64. package/dist/packem_chunks/status.js +1 -1
  65. package/dist/packem_chunks/sync.js +1 -1
  66. package/dist/packem_chunks/sync2.js +1 -1
  67. package/dist/packem_chunks/tripwire.js +1 -1
  68. package/dist/packem_chunks/verify-lockfile.js +1 -1
  69. package/dist/packem_shared/ReleaseClient-BY4OZNCK.js +1 -0
  70. package/dist/packem_shared/{Table-BGIHvenQ-D2oJtNQj.js → Table-CcVkyULl-DLWu6XHL.js} +1 -1
  71. package/dist/packem_shared/{advisories-CefYKEPe.js → advisories-B76fBVL-.js} +1 -1
  72. package/dist/packem_shared/{ai-analysis-rC48NLfB.js → ai-analysis-DF_AfeS3.js} +1 -1
  73. package/dist/packem_shared/{ai-fix-D_ijV3Rn.js → ai-fix-D1bFLkfk.js} +1 -1
  74. package/dist/packem_shared/{bin-CPMo34SM.js → bin-BlGVEhl8.js} +1 -1
  75. package/dist/packem_shared/{build-scripts-MTSK6TNr.js → build-scripts-q__dKE2y.js} +1 -1
  76. package/dist/packem_shared/{cyclonedx-BeUmPgfO.js → cyclonedx-CmrYQ0vx.js} +1 -1
  77. package/dist/packem_shared/{docker-CViFYtmM.js → docker-BYqiD711.js} +1 -1
  78. package/dist/packem_shared/{env-Ct3hMEYB.js → env-DJlbJiFh.js} +1 -1
  79. package/dist/packem_shared/{failure-log-Dy2G-rKi.js → failure-log-Bt7sW4p7.js} +1 -1
  80. package/dist/packem_shared/{index-XAb0QGqA.js → index-C6tpgeIV.js} +2 -2
  81. package/dist/packem_shared/{index-Cntyu-w8.js → index-D6fJJDli.js} +1 -1
  82. package/dist/packem_shared/{lifecycle-CHcFuWf_.js → lifecycle-XeMei1ED.js} +1 -1
  83. package/dist/packem_shared/{manifests-WBnsV_Eb.js → manifests-DSBr3-dw.js} +1 -1
  84. package/dist/packem_shared/{native-config-sync-BFDVK9LH.js → native-config-sync-D-z2Uwqu.js} +1 -1
  85. package/dist/packem_shared/{osv-bloom-DVMlkcAO.js → osv-bloom-DMhXP184.js} +1 -1
  86. package/dist/packem_shared/{packument-C-A3Uhhx.js → packument-CY2QDFml.js} +1 -1
  87. package/dist/packem_shared/plugins.d-ND23R9I3.d.ts +4 -0
  88. package/dist/packem_shared/{provenance-R2csDSNg.js → provenance-DVHiWZrW.js} +1 -1
  89. package/dist/packem_shared/{registry-keys-CMnS_Qt_.js → registry-keys-BKEq72qX.js} +1 -1
  90. package/dist/packem_shared/{resolve-explicit-C4oQMyoB.js → resolve-explicit-UtkNrGKq.js} +1 -1
  91. package/dist/packem_shared/{runtime-check-BXehSP06.js → runtime-check-qnrPTlma.js} +1 -1
  92. package/dist/packem_shared/{s1ngularity-BCDt28u0.js → s1ngularity-DUZtU95L.js} +1 -1
  93. package/dist/packem_shared/{scan-progress-YRpDs90j.js → scan-progress-BgtHexnt.js} +1 -1
  94. package/dist/packem_shared/{signatures-B3srzCEv.js → signatures-QoCuUv9E.js} +1 -1
  95. package/dist/packem_shared/target-merge-Dg25Izl5.js +11 -0
  96. package/dist/packem_shared/{toolchain-C44mPKPu.js → toolchain-Zb3VzZb4.js} +1 -1
  97. package/dist/packem_shared/{typosquats-CQz-1Y6K.js → typosquats-C12CP_2G.js} +1 -1
  98. package/dist/packem_shared/{use-measured-height-DHi0xOPO.js → use-measured-height-BpKmrlkw.js} +1 -1
  99. package/dist/packem_shared/{vis-update-app-B3I14Vfy.js → vis-update-app-BoCQ4ute.js} +1 -1
  100. package/dist/packem_shared/{watch-loop-JfGKIgKB.js → watch-loop-BZudYfcl.js} +1 -1
  101. package/dist/release/index.d.ts +39 -2
  102. package/dist/release/index.js +1 -1
  103. package/dist/release/plugin-sdk.d.ts +2 -1
  104. package/dist/release/plugin-sdk.js +1 -1
  105. package/dist/release/types.d.ts +117 -1
  106. package/dist/release/types.js +1 -1
  107. package/index.js +52 -52
  108. package/package.json +9 -9
  109. package/schemas/vis-config.schema.json +33 -0
  110. package/schemas/vis-release-config.schema.json +33 -0
  111. package/dist/packem_shared/ReleaseClient-YHzBIxYS.js +0 -1
  112. package/dist/packem_shared/target-merge-DOm6h6tW.js +0 -11
  113. /package/dist/packem_shared/{readJsonSync-CvkZyKmL-ihoybKvs.js → readJsonSync-DuMMeB3s-ihoybKvs.js} +0 -0
@@ -1,3 +1,61 @@
1
- import{createRequire as G}from"node:module";import{I as q,j as X,E as O,V as K,s as T,q as D}from"../packem_shared/index.server-J83sowC4.js";import{y as B}from"../packem_shared/index-CE6MsgcV.js";import{X as Q}from"./cli-main.js";import{d as k,f as v,r as Y,a as Z,b as ee,s as ne,c as te,e as ie,u as re,h as se,i as oe,j as ae,k as le,l as ce,m as de,n as ue,v as fe,w as ge,q as pe,t as me}from"../packem_shared/watch-loop-JfGKIgKB.js";import{p as c}from"./catalog.js";const H=G(import.meta.url),w=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,U=e=>{if(typeof w<"u"&&w.versions&&w.versions.node){const[n,t]=w.versions.node.split(".").map(Number);if(n>22||n===22&&t>=3||n===20&&t>=16)return w.getBuiltinModule(e)}return H(e)},{createHash:y}=U("node:crypto"),he={1:"warning",2:"error"},xe={argsCheck:(e,n)=>V(e,n,!1),argsFix:(e,n)=>V(e,n,!0),bin:()=>["pnpm","exec","eslint"],cacheKey:(e,n)=>{const t=["eslint",e.declaredVersion??"unknown",e.configFile??"no-config",n.maxWarnings===void 0?"":`mw=${n.maxWarnings}`,n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=k(n,c.eslint.packageNames[0]),i=v(e,c.eslint.configFiles);if(!(!t&&!i))return{adapter:"eslint",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["cjs","cts","js","jsx","mjs","mts","ts","tsx","vue"],id:"eslint",kind:"lint",parse:(e,n)=>{if(!e.stdout.trim())return[];let t;try{t=JSON.parse(e.stdout)}catch{return[{adapter:"eslint",file:n.root,fixable:!1,message:`eslint output was not valid JSON (exit ${e.exitCode})`,severity:"error"}]}const i=[];for(const r of t)for(const s of r.messages)i.push({adapter:"eslint",column:s.column,endColumn:s.endColumn,endLine:s.endLine,file:r.filePath,fixable:!!s.fix,line:s.line,message:s.message,ruleId:s.ruleId??void 0,severity:s.fatal?"error":he[s.severity]??"warning"});return i}},V=(e,n,t)=>{const i=["--format","json","--no-error-on-unmatched-pattern"];return t&&i.push("--fix"),n.quiet&&i.push("--quiet"),typeof n.maxWarnings=="number"&&i.push("--max-warnings",String(n.maxWarnings)),n.extraArgs?.length&&i.push(...n.extraArgs),i.push(...e),i},we=/^([^:]+):(\d+)(?::(\d+))?\s+([\w/-]+)\s+(.+)$/,ke=e=>{const n=we.exec(e);if(!n)return;const[,t,i,r,s,a]=n;return{column:r===void 0?void 0:Number(r),file:t,line:Number(i),message:a,ruleId:s}},ve=e=>e.startsWith("/")||/^[a-z]:[\\/]/i.test(e),ye={argsCheck:(e,n)=>J(e,n,!1),argsFix:(e,n)=>J(e,n,!0),bin:()=>["pnpm","exec","markdownlint-cli2"],cacheKey:(e,n)=>{const t=["markdownlint",e.declaredVersion??"unknown",e.configFile??"no-config",n.maxWarnings===void 0?"":`mw=${n.maxWarnings}`,n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=c.markdownlint.packageNames.map(r=>k(n,r)).find(r=>r!==void 0),i=v(e,c.markdownlint.configFiles);if(!(!t&&!i))return{adapter:"markdownlint",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["markdown","md"],id:"markdownlint",kind:"lint",parse:(e,n)=>{const t=(e.stderr||e.stdout||"").trim();if(!t)return[];const i=[];for(const r of t.split(/\r?\n/)){const s=ke(r.trim());s&&i.push({adapter:"markdownlint",column:s.column,file:ve(s.file)?s.file:`${n.root}/${s.file}`,fixable:!0,line:s.line,message:s.message,ruleId:s.ruleId,severity:"warning"})}return i}},J=(e,n,t)=>{const i=[];return t&&i.push("--fix"),n.extraArgs?.length&&i.push(...n.extraArgs),e.length===0?i.push("**/*.md"):i.push(...e),i},$e={advice:"info",error:"error",warning:"warning"},be={argsCheck:(e,n)=>R(e,n,!1),argsFix:(e,n)=>R(e,n,!0),bin:()=>["pnpm","exec","oxlint"],cacheKey:(e,n)=>{const t=["oxlint",e.declaredVersion??"unknown",e.configFile??"no-config",n.maxWarnings===void 0?"":`mw=${n.maxWarnings}`,n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=k(n,c.oxlint.packageNames[0]),i=v(e,c.oxlint.configFiles);if(!(!t&&!i))return{adapter:"oxlint",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["astro","cjs","cts","js","jsx","mjs","mts","svelte","ts","tsx","vue"],id:"oxlint",kind:"lint",parse:(e,n)=>{if(!e.stdout.trim())return[];let t;try{t=JSON.parse(e.stdout)}catch{return[{adapter:"oxlint",file:n.root,fixable:!1,message:`oxlint output was not valid JSON (exit ${e.exitCode})`,severity:"error"}]}const i=[];for(const r of t.diagnostics??[]){const s=r.labels?.[0]?.span;i.push({adapter:"oxlint",column:s?.column,file:r.filename??n.root,fixable:!1,line:s?.line,message:r.message??"",ruleId:r.code,severity:$e[r.severity??""]??"warning"})}return i}},R=(e,n,t)=>{const i=["--format","json"];return t&&i.push("--fix"),n.quiet&&i.push("--quiet"),typeof n.maxWarnings=="number"&&i.push(`--max-warnings=${String(n.maxWarnings)}`),n.extraArgs?.length&&i.push(...n.extraArgs),i.push(...e),i},Ae={error:"error",info:"info",style:"info",warning:"warning"},Fe=e=>e.startsWith("/")||/^[a-z]:[\\/]/i.test(e),je=(e,n)=>e?Fe(e)?e:`${n}/${e}`:n,Ce={argsCheck:(e,n)=>L(e,n),argsFix:(e,n)=>L(e,n),bin:()=>["shellcheck"],cacheKey:(e,n)=>{const t=["shellcheck",e.declaredVersion??"unknown",e.configFile??"no-config",n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=k(n,c.shellcheck.packageNames[0]),i=v(e,c.shellcheck.configFiles);if(!(!t&&!i))return{adapter:"shellcheck",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["bash","ksh","sh"],id:"shellcheck",kind:"lint",parse:(e,n)=>{if(!e.stdout.trim())return[];let t;try{t=JSON.parse(e.stdout)}catch{return[{adapter:"shellcheck",file:n.root,fixable:!1,message:`shellcheck output was not valid JSON (exit ${e.exitCode})`,severity:"error"}]}const i=[];for(const r of t.comments??[])i.push({adapter:"shellcheck",column:r.column,endColumn:r.endColumn,endLine:r.endLine,file:je(r.file,n.root),fixable:!!r.fix,line:r.line,message:r.message??"",ruleId:r.code===void 0?void 0:`SC${String(r.code)}`,severity:Ae[r.level??""]??"warning"});return i}},L=(e,n)=>{const t=["--format=json1"];return n.extraArgs?.length&&t.push(...n.extraArgs),t.push(...e),t},Se={error:"error",warning:"warning"},qe={argsCheck:(e,n)=>M(e,n,!1),argsFix:(e,n)=>M(e,n,!0),bin:()=>["pnpm","exec","stylelint"],cacheKey:(e,n)=>{const t=["stylelint",e.declaredVersion??"unknown",e.configFile??"no-config",n.maxWarnings===void 0?"":`mw=${n.maxWarnings}`,n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=k(n,c.stylelint.packageNames[0]),i=v(e,c.stylelint.configFiles);if(!(!t&&!i))return{adapter:"stylelint",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["astro","css","less","sass","scss","svelte","vue"],id:"stylelint",kind:"lint",parse:(e,n)=>{if(!e.stdout.trim())return[];let t;try{t=JSON.parse(e.stdout)}catch{return[{adapter:"stylelint",file:n.root,fixable:!1,message:`stylelint output was not valid JSON (exit ${e.exitCode})`,severity:"error"}]}const i=[];for(const r of t)for(const s of r.warnings??[])i.push({adapter:"stylelint",column:s.column,endColumn:s.endColumn,endLine:s.endLine,file:r.source,fixable:!1,line:s.line,message:s.text??"",ruleId:s.rule,severity:Se[s.severity??""]??"warning"});return i}},M=(e,n,t)=>{const i=["--formatter","json"];return t&&i.push("--fix"),n.quiet&&i.push("--quiet"),typeof n.maxWarnings=="number"&&i.push("--max-warnings",String(n.maxWarnings)),n.extraArgs?.length&&i.push(...n.extraArgs),i.push(...e),i},We=[be,ue,xe,qe,fe,ye,Ce,ge],Be=async({logger:e,options:n,visConfig:t,workspaceRoot:i})=>{const r=i??process.cwd(),s=t?.lint,a=Y(We,s?.order),j=Z(r,a),d=ee(j,a,"lint").filter(({adapter:l})=>s?.adapters?.[l.id]?.enabled!==!1);if(d.length===0){e.warn("vis lint: no linter detected in this workspace (looked for: oxlint, biome, eslint, stylelint, ruff, markdownlint, shellcheck, deno).");return}const C=l=>{const u=s?.adapters?.[l]?.extraArgs;return u&&u.length>0?[...u]:void 0},$={extraArgs:void 0,maxWarnings:typeof n.maxWarnings=="number"?n.maxWarnings:void 0,quiet:n.quiet??!1},b=Ne(n),P=n.fix?"fix":"check";let f;if(n.staged){if(f=ne(r),f===void 0)e.warn("vis lint: could not resolve --staged (not a git repo or git unavailable). Falling back to a workspace-wide run.");else if(f.length===0){e.info(q(" lint: no staged files"));return}}else if(typeof n.since=="string"&&n.since.length>0){if(f=te(r,n.since),f===void 0)e.warn(`vis lint: could not resolve --since ${n.since} (not a git repo or unknown ref). Falling back to a workspace-wide run.`);else if(f.length===0){e.info(q(`✓ lint: no files changed since ${n.since}`));return}}const W=b.length>0?b:void 0,E=Q(r,void 0,void 0,!0),S=n.format??"human";S==="human"&&n.output!==void 0&&e.warn("vis lint: --output is ignored for the human format; pass --format json|minimal|sarif|junit|github to redirect findings to a file.");const N=async l=>{const u=l!==void 0&&l.length>0&&W===void 0,m=[];for(const{adapter:o,presence:x}of d){let g;if(u){if(g=re(l,o.extensions),g.length===0)continue}else g=W??l??["."];const F=C(o.id),I={adapter:o,files:g,presence:x};F&&(I.options={...$,extraArgs:F}),m.push(I)}if(m.length===0)return;const z=await se(m,$,P,{cacheRoot:E}),A=m.map((o,x)=>{const g=z[x],F=o.adapter.parse(g,o.presence);return{adapter:o.adapter,durationMs:g.durationMs,exitCode:g.exitCode,findings:F}}),h=oe(A.map(o=>({adapter:o.adapter.id,durationMs:o.durationMs,exitCode:o.exitCode,findingCount:o.findings.length,findings:o.findings}))),p=S==="human"?void 0:ae({cwd:r,target:n.output});try{switch(S){case"github":{p.write(de({runs:A.map(o=>({findings:o.findings})),workspaceRoot:r}));break}case"json":{p.write(`${JSON.stringify({findings:h.findings,runs:h.runs},null,2)}
2
- `);break}case"junit":{p.write(ce({runs:A.map(o=>({adapter:o.adapter.id,durationMs:o.durationMs,findings:o.findings})),workspaceRoot:r}));break}case"minimal":{Ie(h.findings,r,p);break}case"sarif":{p.write(le({runs:A.map(o=>({adapter:o.adapter.id,findings:o.findings,presence:m.find(x=>x.adapter.id===o.adapter.id)?.presence})),workspaceRoot:r}));break}default:_e(h.findings,r,e)}}finally{p?.close()}const _=me(h);_!==0&&(process.exitCode=_)};if(n.watch){const l=[...new Set(d.flatMap(({adapter:u})=>u.extensions))];await ie({extensions:l,initialFiles:f,label:"lint",log:u=>{e.info(u)},runCycle:N,workspaceRoot:r});return}await N(f)},Ne=e=>{const n=e;return[...n._??n.args??[]]},_e=(e,n,t)=>{if(e.length===0){t.info(q("✓ lint: no findings"));return}const i=pe(e);for(const[a,j]of i){t.info(X(B(n,a)));for(const d of j){const C=Oe(d),$=Ve(d.severity),b=d.ruleId?O(` ${d.ruleId}`):"";t.info(` ${O(C)} ${$} ${d.message}${b}`)}}const r=e.filter(a=>a.severity==="error").length,s=e.filter(a=>a.severity==="warning").length;t.info(""),t.info(`${K(`${String(r)} error${r===1?"":"s"}`)}, ${T(`${String(s)} warning${s===1?"":"s"}`)}`)},Ie=(e,n,t)=>{for(const i of e){const r=B(n,i.file),s=i.line??"",a=i.column??"";t.write(`${i.adapter} ${r} ${String(s)} ${String(a)} ${i.severity} ${i.ruleId??""} ${i.message}
3
- `)}},Oe=e=>e.line===void 0?"":e.column===void 0?String(e.line):`${String(e.line)}:${String(e.column)}`,Ve=e=>e==="error"?K("error"):e==="warning"?T("warn "):D("info ");export{Be as default};
1
+ import{v as F,H as P,y as S,m as b,T as I,O as U,a as T}from"../packem_shared/index-CE6MsgcV.js";import _ from"./index.js";import{b as J,l as M}from"./catalog.js";import{n as q}from"../packem_shared/manifests-DSBr3-dw.js";import{Z as C,a0 as B}from"./cli-main.js";import{s as H}from"../packem_shared/glob-fqg4KepW-1S3z30c8.js";const K=(e,t)=>{const o=t.replace(/^\.?\//,"");return o===""||o==="."?`/${e}/`:e===""||e==="."?`/${o}`:`/${e}/${o}`},v=(e,t,o=[])=>{const s=[],n=new Set;for(const[r,a]of Object.entries(t?.globalPaths??{}))s.push({owners:a,path:r,source:"project-json"}),n.add(r);for(const[r,a]of Object.entries(e.projects)){const i=a.owners??[];for(const c of i){const f=K(a.root??r,c.path);s.push({channel:c.channel,owners:c.owners,path:f,projectId:r,source:"project-json"}),n.add(f)}}for(const r of o)n.has(r.path)||(s.push(r),n.add(r.path));return(t?.orderBy??"file-source")==="project-id"?s.sort((r,a)=>(r.projectId??"").localeCompare(a.projectId??"")||r.path.localeCompare(a.path)):s.sort((r,a)=>r.path.localeCompare(a.path)),s},z="Update each project's project.json `owners` field and re-run the command.",Y=e=>["# CODEOWNERS generated by `vis sync codeowners`. Do not edit by hand.",e?`# Re-run with: ${e}`:`# ${z}`,""],W=e=>{const t=[];for(const o of e){const s=o.owners.join(" "),n=o.channel?` # notify: ${o.channel}`:"";t.push(`${o.path} ${s}${n}`)}return t},Q=(e,t={})=>[...Y(t.regenerationCommand),...W(e),""].join(`
2
+ `),O={begin:"# BEGIN vis-codeowners",end:"# END vis-codeowners"},V=(e,t=O,o={})=>{const s=o.regenerationCommand?`# Generated by vis sync codeowners re-run with: ${o.regenerationCommand}`:"# Generated by `vis sync codeowners` do not edit by hand.";return[t.begin,s,...W(e),t.end].join(`
3
+ `)},X=(e,t,o=O)=>{const s=e.indexOf(o.begin),n=e.indexOf(o.end);if(s!==-1&&n!==-1&&n>s){const a=e.slice(0,s),i=n+o.end.length,c=e.slice(i);return`${a}${t}${c}`}const r=e.replace(/\s+$/u,"");return`${r.length===0?"":`${r}
4
+
5
+ `}${t}
6
+ `},Z=["**/CODEOWNERS"],ee=["**/node_modules/**","**/dist/**","**/build/**","**/coverage/**","**/.git/**","**/.next/**","**/.nuxt/**"],te=e=>{const t=[];for(const o of e.split(/\r?\n/u)){const s=o.indexOf("#"),n=(s===-1?o:o.slice(0,s)).trim();if(n.length===0)continue;const r=n.split(/\s+/u);if(r.length<2)continue;const[a,...i]=r,c=i.filter(f=>f.length>0);!a||c.length===0||t.push({owners:c,path:a})}return t},oe=(e,t)=>{const o=t.replace(/^\.\/?/,"").replace(/\/$/,"");return e.startsWith("/")?o===""?e:`/${o}${e}`:o===""?`/${e}`:`/${o}/${e}`},ne=async(e,t,o)=>{const s=t&&t.length>0?[...t]:[...Z],n=[...ee];if(o){const i=o.replace(/^\.\/?/,"").replace(/^\/+/,"");i.length>0&&n.push(i)}const r=await H(s,{absolute:!0,cwd:e,ignore:n}),a=[];for(const i of r){let c;try{c=F(i)}catch{continue}const f=P(i),h=S(e,f);for(const p of te(c))a.push({owners:p.owners,path:oe(p.path,h)})}return a},re=/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/?#]+)/iu,se=e=>{if(!e)return;const t=e.match(re);if(!t?.[1])return;const o=t[1].trim();if(!(o===""||o.includes(" ")))return`@${o.replace(/^@/,"")}`},ie=(e,t)=>{const o=[];for(const[s,n]of Object.entries(e.projects)){if(n.owners&&n.owners.length>0)continue;const r=n.root??s,a=b(t,r,"package.json"),i=C(a);if(!i)continue;const c=q(i.maintainers);if(!c||c.length===0)continue;const f=[],h=new Set;for(const p of c){const $=se(p.url);$&&!h.has($)&&(h.add($),f.push($))}f.length!==0&&o.push({owners:f,path:r===""||r==="."?"/":`/${r}/`,projectId:s})}return o},ae=["author","bugs","homepage","license","repository","engines"],N=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),E=(e,t)=>{if(e===t)return!0;if(typeof e!=typeof t||e===null||t===null)return!1;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(const[o,s]of e.entries())if(!E(s,t[o]))return!1;return!0}if(typeof e=="object"&&typeof t=="object"){const o=Object.keys(e),s=Object.keys(t);if(o.length!==s.length)return!1;for(const n of o)if(!E(e[n],t[n]))return!1;return!0}return!1},R=e=>e===void 0?e:structuredClone(e),ce=(e,t,o)=>{if(e==="repository"&&N(t)&&N(o)){const s={};for(const[n,r]of Object.entries(t))n!=="directory"&&(s[n]=R(r));return typeof o.directory=="string"&&(s.directory=o.directory),s}return R(t)},de=(e,t,o)=>{const s=[];for(const n of o.fields){if(!Object.hasOwn(e,n))continue;const r=e[n],a=t[n],i=ce(n,r,a);E(i,a)||s.push({after:i,before:a,field:n,packageJsonPath:""})}return s},fe=(e,t)=>{for(const o of t)e[o.field]=o.after},x="Generated by `vis sync codeowners --write-guard`. Do not edit by hand.",le=e=>{const t=e.replace(/^\.?\/+/u,"").replace(/\/+$/u,"");return t===""||t==="."?"**":`${t}/**`},D=e=>{const t=new Set,o=[];for(const s of[...e].sort((n,r)=>n.name.localeCompare(r.name))){const n=le(s.root);t.has(n)||(t.add(n),o.push(n))}return o},pe=e=>{const t=D(e),o=t.map(n=>` - "${n}"`).join(`
7
+ `),s=t.map(n=>` ${n}`).join(`
8
+ `);return`# ${x}
9
+ name: Write Guard
10
+
11
+ on:
12
+ pull_request:
13
+ paths:
14
+ ${o}
15
+
16
+ permissions:
17
+ contents: read
18
+ pull-requests: read
19
+
20
+ jobs:
21
+ write-guard:
22
+ runs-on: ubuntu-latest
23
+ steps:
24
+ - uses: actions/checkout@v4
25
+ with:
26
+ fetch-depth: 0
27
+ - uses: geritol/write-guard@v1
28
+ with:
29
+ codeowners: CODEOWNERS
30
+ paths: |
31
+ ${s}
32
+ `},ue=e=>{const t=D(e).map(o=>` - "${o}/*"`).join(`
33
+ `);return`# ${x}
34
+ #
35
+ # SOFT GUARD ONLY — this job does NOT block a merge by itself.
36
+ # It verifies the generated CODEOWNERS is in sync and flags that a
37
+ # restricted path changed. GitLab CI cannot portably gate a merge on
38
+ # code-owner *approval* from a job, so REAL ENFORCEMENT REQUIRES the
39
+ # native GitLab setting:
40
+ # Settings -> Repository -> Protected branches ->
41
+ # "Require approval from Code Owners" (GitLab Premium / Ultimate)
42
+ # https://docs.gitlab.com/ee/user/project/codeowners/
43
+ # Without that setting enabled, this job is advisory only.
44
+ write-guard:
45
+ stage: test
46
+ image: node:22-alpine
47
+ rules:
48
+ - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
49
+ changes:
50
+ ${t}
51
+ script:
52
+ - corepack enable
53
+ - pnpm install --frozen-lockfile
54
+ - pnpm vis sync codeowners --check
55
+ - >-
56
+ echo "SOFT GUARD: a restricted path changed. This job does NOT enforce
57
+ code-owner approval. Enable 'Require approval from Code Owners' on the
58
+ protected branch (GitLab Premium/Ultimate) for a real merge gate:
59
+ https://docs.gitlab.com/ee/user/project/codeowners/"
60
+ `},he=e=>e.length===0?[]:[{content:pe(e),path:".github/workflows/write-guard.yml"},{content:ue(e),path:".gitlab/write-guard.gitlab-ci.yml"}],L=new Set(["nested-codeowners","package-json-maintainers","project-json"]),A=(e,t,o)=>{const s=new Set,n=[];for(const r of e??[])for(const a of r.split(",")){const i=a.trim();if(i.length===0)continue;if(o&&!o(i))throw new Error(`Unknown codeowners source: "${i}". Known: ${[...L].join(", ")}.`);const c=i;s.has(c)||(s.add(c),n.push(c))}return n.length>0?n:[...t]},ge=e=>L.has(e),G=["codeowners","package-json-fields"],me=(e,t)=>t.some(o=>_(o,e)),we=async(e,t,o,s,n)=>{const r=Object.entries(s.projects).filter(([,i])=>i.restricted===!0).map(([i,c])=>({name:i,root:c.root??i})),a=he(r);if(a.length===0){t.info("No projects flagged `restricted: true` in project.json. Skipping Write Guard.");return}if(n){let i=!1;for(const c of a){const f=b(o,c.path);let h="";try{h=await e.readFile(f,"utf8")}catch(p){if(p.code!=="ENOENT")throw p}h.trim()!==c.content.trim()&&(t.error(`${c.path} is out of date. Run \`vis sync codeowners --write-guard\` to update it.`),i=!0)}i?process.exitCode=1:t.info(`Write Guard CI is up to date (${a.length} files, ${r.length} restricted projects).`);return}for(const i of a){const c=b(o,i.path);T(P(c)),I(c,i.content),t.info(`Wrote ${i.path}`)}t.info(`Write Guard CI scoped to ${r.length} restricted project${r.length===1?"":"s"}.`)},$e=async({fs:e,logger:t,options:o,visConfig:s,workspaceRoot:n})=>{const r=n,{workspace:a}=J(r,s),i=s?.codeowners;o.writeGuard===!0&&await we(e,t,r,a,o.check===!0);const c=A(o.from,i?.sources??["project-json"],ge),f=o.regenerationCommand??i?.regenerationCommand,h=o.preserveBlock===!0||i?.preserveBlock===!0,p=i?.blockMarker??O,$=o.nestedIncludes??i?.nestedIncludes,g=o.out??"CODEOWNERS",w=[];if(c.includes("nested-codeowners")){const m=await ne(r,$,g);for(const j of m)w.push({...j,source:"nested"})}if(c.includes("package-json-maintainers")){const m=ie(a,r);for(const j of m)w.push({...j,source:"maintainers"})}const l=c.includes("project-json")?v(a,i,w):v({projects:{}},i,w);if(l.length===0){t.info("No `owners` entries found in any source. Nothing to sync.");return}const y=b(r,g);let d="";try{d=await e.readFile(y,"utf8")}catch(m){if(m.code!=="ENOENT")throw m}const u={regenerationCommand:f},k=h?X(d,V(l,p,u),p):Q(l,u);if(o.check){if(d.trim()!==k.trim()){t.error(`${y} is out of date. Run \`vis sync codeowners\` to update it.`),process.exitCode=1;return}t.info(`${y} is up to date.`);return}I(y,k),t.info(`Wrote ${l.length} entries to ${y}`)},ke=({logger:e,options:t,visConfig:o,workspaceRoot:s})=>{const n=s,r=o?.editorconfig??!0,a=C(b(n,"package.json"));if(!a){e.error("Could not read root package.json. Nothing to sync."),process.exitCode=1;return}const i=A(t.fields,ae),c=t.ignorePackageName??[],f=t.check===!0,h=(t.format??"human").toLowerCase(),p=t.quiet===!0,$=B(n).filter(d=>d!=="."),g=[];let w=0;for(const d of $){const u=b(n,d,"package.json"),k=C(u);if(!k)continue;const m=typeof k.name=="string"?k.name:void 0;if(m!==void 0&&c.length>0&&me(m,c))continue;w+=1;const j=de(a,k,{fields:i});j.length!==0&&g.push({filePath:u,packageJsonPath:S(n,u),packageName:m,pkg:k,pkgChanges:j})}if(!f)for(const d of g)fe(d.pkg,d.pkgChanges),U(d.filePath,d.pkg,{indent:M(d.filePath,{useEditorconfig:r}),overwrite:!0});const l=g.flatMap(d=>d.pkgChanges.map(u=>({after:u.after,before:u.before,field:u.field,packageJsonPath:d.packageJsonPath,packageName:d.packageName}))),y={changes:l,fields:i,kind:"package-json-fields",mode:f?"check":"write",totalChanges:l.length,totalPackages:w};if(h==="json")process.stdout.write(`${JSON.stringify(y,null,4)}
61
+ `);else if(l.length===0)e.info(`All ${w} package${w===1?"":"s"} in sync (fields: ${i.join(", ")}).`);else if(f){if(!p)for(const d of l)e.error(`${d.packageJsonPath}: ${d.field} drifts from root`);e.error(`Found ${l.length} field drift${l.length===1?"":"s"} across ${g.length} package${g.length===1?"":"s"}. Run \`vis sync package-json-fields\` to fix.`)}else{if(!p)for(const d of g)e.info(`${d.packageJsonPath}: synced ${d.pkgChanges.map(u=>u.field).join(", ")}`);e.info(`Synced ${l.length} field${l.length===1?"":"s"} across ${g.length} package${g.length===1?"":"s"}.`)}f&&l.length>0&&(process.exitCode=1)},ve=async e=>{const t=e.argument[0];if(!t)throw new Error(`Missing sync kind. Usage: vis sync <kind> (known kinds: ${G.join(", ")})`);if(!e.workspaceRoot)throw new Error("Could not determine workspace root. Run inside a monorepo.");if(t==="codeowners"){await $e(e);return}if(t==="package-json-fields"){ke(e);return}throw new Error(`Unknown sync kind: "${t}". Known kinds: ${G.join(", ")}.`)};export{ve as default};
@@ -1,6 +1,3 @@
1
- import{createRequire as z}from"node:module";import{y as J,v as L,m as P,f as M,J as V,B as Y}from"../packem_shared/index-CE6MsgcV.js";import{m as t,n as a,i as c,r as v,$ as K,d as Q,k as U,s as Z,t as ee,u as re,e as te,W as N}from"./catalog.js";import"../packem_shared/env-Ct3hMEYB.js";import{I as se}from"../packem_shared/index-B0EsgdzO.js";import oe from"./index.js";import{sortPackageJsonStringWithOptions as q}from"#native";import{T as ne,_ as ie,U as le,Q as ce,y as ae,p as k}from"./cli-main.js";import{o as O}from"../packem_shared/utils-CRueU43T.js";const Ke=z(import.meta.url),Qe=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process;const A={error:0,rewritten:1,"would-rewrite":1,unchanged:2},de=e=>[...e].sort((r,s)=>A[r.status]-A[s.status]),ue=(e,r)=>r==="all"?e:r==="errors"?e.filter(s=>s.status==="error"):r==="rewritten"?e.filter(s=>s.status==="rewritten"||s.status==="would-rewrite"):e.filter(s=>s.status==="unchanged");class fe{#e;#r=new Set;constructor(r){this.#e={entries:de(r),filterType:"all",focusedPanel:"list",selectedIndex:0}}getSnapshot=()=>this.#e;subscribe=r=>(this.#r.add(r),()=>{this.#r.delete(r)});getFilteredEntries=()=>ue(this.#e.entries,this.#e.filterType);#t(){this.#e={...this.#e};for(const r of this.#r)r()}select(r){const s=this.getFilteredEntries();this.#e.selectedIndex=s.length===0?-1:Math.max(0,Math.min(r,s.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()}}const he=({checkMode:e,entry:r,focused:s,scrollRef:l})=>{const i=s?"white":"gray";return r?t.jsxs(a,{borderColor:i,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[t.jsx(a,{flexShrink:0,paddingTop:1,paddingX:2,children:t.jsx(c,{bold:!0,color:"white",children:r.relativePath})}),t.jsxs(ne,{flexGrow:1,flexShrink:1,paddingX:2,ref:l,scrollbar:!0,scrollbarColor:"gray",children:[t.jsx(c,{}),t.jsxs(a,{children:[t.jsx(a,{width:10,children:t.jsx(c,{dimColor:!0,children:"Status:"})}),r.status==="error"?t.jsx(c,{bold:!0,color:"red",children:"error"}):r.status==="unchanged"?t.jsx(c,{bold:!0,color:"green",children:"already sorted"}):r.status==="rewritten"?t.jsx(c,{bold:!0,color:"yellow",children:"rewritten"}):t.jsx(c,{bold:!0,color:"yellow",children:"would rewrite (--check)"})]}),t.jsxs(a,{children:[t.jsx(a,{width:10,children:t.jsx(c,{dimColor:!0,children:"Path:"})}),t.jsx(c,{children:r.filePath})]}),r.error?t.jsxs(t.Fragment,{children:[t.jsxs(a,{flexDirection:"column",marginTop:1,children:[t.jsx(c,{dimColor:!0,children:"── "}),t.jsx(c,{bold:!0,color:"red",children:"ERROR"}),t.jsxs(a,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[t.jsxs(a,{children:[t.jsx(a,{width:10,children:t.jsx(c,{dimColor:!0,children:"Step:"})}),t.jsx(c,{color:"yellow",children:r.error.step})]}),r.error.context&&t.jsxs(a,{children:[t.jsx(a,{width:10,children:t.jsx(c,{dimColor:!0,children:"Position:"})}),t.jsx(c,{children:`line ${String(r.error.context.line)}, column ${String(r.error.context.column)}`})]}),t.jsx(a,{marginTop:1,children:t.jsx(c,{color:"red",children:r.error.message})})]})]}),r.error.context&&r.error.context.snippet.length>0&&t.jsxs(a,{flexDirection:"column",marginTop:1,children:[t.jsx(c,{dimColor:!0,children:"── "}),t.jsx(c,{bold:!0,color:"white",children:"SNIPPET"}),t.jsxs(a,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[r.error.context.snippet.map(o=>{const n=`${o.isErrorLine?"❯":" "} ${String(o.lineNumber).padStart(4)} `;return t.jsxs(a,{children:[t.jsx(c,{color:o.isErrorLine?"red":"gray",children:n}),t.jsx(c,{color:o.isErrorLine?"white":"gray",wrap:"truncate-end",children:o.content||" "})]},o.lineNumber)}),r.error.context.column>0&&t.jsx(a,{children:t.jsx(c,{color:"red",children:`${" ".repeat(7+r.error.context.column-1)}↑`})})]})]})]}):t.jsxs(a,{flexDirection:"column",marginTop:1,children:[t.jsx(c,{dimColor:!0,children:"── "}),t.jsx(c,{bold:!0,color:"white",children:"KEY DIFF"}),t.jsx(a,{flexDirection:"column",marginTop:1,paddingLeft:2,children:r.diff.length===0?t.jsx(c,{dimColor:!0,children:"No top-level keys moved (sub-key reorder only)."}):r.diff.map(o=>{const n=o.toIndex-o.fromIndex,d=n<0?`↑ ${String(Math.abs(n))}`:`↓ ${String(n)}`,g=n<0?"green":"yellow";return t.jsxs(a,{children:[t.jsx(a,{width:28,children:t.jsx(c,{wrap:"truncate",children:o.key})}),t.jsx(a,{width:10,children:t.jsxs(c,{dimColor:!0,children:[String(o.fromIndex)," → ",String(o.toIndex)]})}),t.jsx(c,{color:g,children:d})]},o.key)})}),e&&r.status==="would-rewrite"&&t.jsx(a,{marginTop:1,paddingLeft:2,children:t.jsx(c,{dimColor:!0,children:"--check mode: no write performed."})})]})]})]}):t.jsx(a,{alignItems:"center",borderColor:"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,justifyContent:"center",children:t.jsx(c,{dimColor:!0,children:"No entry selected"})})},ge={error:"red",rewritten:"yellow",unchanged:"green","would-rewrite":"yellow"},pe={error:"ERROR",rewritten:"REWROTE",unchanged:"SORTED","would-rewrite":"REWRITE"},H={error:"errors",rewritten:"rewrites",unchanged:"sorted","would-rewrite":"rewrites"},xe={errors:"Errors",rewrites:"Rewrites",sorted:"Sorted"},me=[{count:e=>e.errors+e.rewrites+e.sorted,key:"all",label:"All",shortcut:"1"},{count:e=>e.rewrites,key:"rewritten",label:"Rewrites",shortcut:"2"},{count:e=>e.errors,key:"errors",label:"Errors",shortcut:"3"},{count:e=>e.sorted,key:"unchanged",label:"Sorted",shortcut:"4"}],X=e=>{const r={errors:0,rewrites:0,sorted:0};for(const s of e)r[H[s.status]]++;return r},we=({entry:e,isSelected:r})=>{const s=ge[e.status],l=pe[e.status];return t.jsxs(a,{flexShrink:0,height:1,children:[t.jsx(c,{children:r?">":" "}),t.jsx(c,{children:" "}),t.jsx(c,{bold:!0,color:s,children:`[${l}]`.padEnd(10)}),t.jsx(c,{children:" "}),t.jsx(a,{flexGrow:1,children:t.jsx(c,{bold:r,inverse:r,wrap:"truncate",children:e.relativePath})}),e.status!=="error"&&e.diff.length>0&&t.jsx(c,{dimColor:!0,children:` ${String(e.diff.length)} key${e.diff.length===1?"":"s"}`})]})},je=({color:e,count:r,label:s})=>t.jsx(a,{flexShrink:0,height:1,children:t.jsx(c,{bold:!0,color:e,children:`${s} (${String(r)})`})}),ye=({counts:e,entries:r,filterType:s,focused:l,selectedIndex:i,totalEntries:o,viewportHeight:n})=>{const d=l?"white":"gray",g=X(r),m=(g.errors>0?1:0)+(g.rewrites>0?1:0)+(g.sorted>0?1:0),y=s==="all"&&m>1,h=[];let w;for(const[u,x]of r.entries()){const b=H[x.status];y&&b!==w&&(w!==void 0&&h.push({kind:"spacer"}),h.push({color:b==="errors"?"red":b==="rewrites"?"yellow":"green",count:g[b],kind:"header",label:xe[b]}),w=b),h.push({entry:x,entryIndex:u,kind:"entry"})}const p=h.findIndex(u=>u.kind==="entry"&&u.entryIndex===i),S=p!==-1,j=h.length,$=Math.max(0,j-n);let f=0;S&&n>0&&(f=Math.min($,Math.max(0,p-n+1)));const E=j>n&&n>0;return t.jsxs(a,{borderColor:d,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[t.jsxs(a,{flexShrink:0,gap:1,paddingX:1,children:[t.jsx(c,{bold:!0,inverse:!0,children:" VIS SORT "}),t.jsxs(c,{wrap:"truncate",children:[o," ","file",o===1?"":"s"]})]}),t.jsx(a,{flexShrink:0,gap:1,paddingX:1,paddingY:1,children:me.map(u=>{const x=s===u.key,b=u.count(e);return t.jsxs(a,{children:[t.jsx(c,{dimColor:!x,children:"["}),t.jsx(c,{bold:x,color:x?"cyan":"gray",children:u.shortcut}),t.jsx(c,{dimColor:!x,children:"]"}),t.jsxs(c,{color:x?"white":"gray",children:[" ",u.label]}),t.jsxs(c,{dimColor:!0,children:[" ","(",b,")"]})]},u.key)})}),t.jsxs(a,{flexDirection:"row",flexGrow:1,overflow:"hidden",children:[t.jsx(a,{flexDirection:"column",flexGrow:1,overflow:"hidden",paddingLeft:1,children:t.jsx(a,{flexDirection:"column",marginTop:-f,children:h.map((u,x)=>u.kind==="spacer"?t.jsx(a,{flexShrink:0,height:1},`s-${String(x)}`):u.kind==="header"?t.jsx(je,{color:u.color,count:u.count,label:u.label},`h-${u.label}`):t.jsx(we,{entry:u.entry,isSelected:u.entryIndex===i},u.entry.filePath))})}),E&&t.jsx(a,{flexShrink:0,marginLeft:1,marginRight:1,children:t.jsx(ie,{contentHeight:j,placement:"inset",scrollOffset:f,style:"block",viewportHeight:n})})]})]})},be=100,D=10,ke=6,Se=1,F={1:"all",2:"rewritten",3:"errors",4:"unchanged"},$e=({checkMode:e,store:r})=>{const{exit:s}=le(),{columns:l,rows:i}=ce(),o=v.useSyncExternalStore(r.subscribe,r.getSnapshot),n=v.useRef(null),d=r.getFilteredEntries(),g=d[o.selectedIndex]??null,m=X(o.entries),y=l>=be,h=Math.max(0,i-Se),w=y?h:Math.floor(h/2),p=Math.max(0,w-ke),S=v.useCallback(()=>{s()},[s]),j=v.useRef(0),$=v.useRef(void 0),f=v.useRef(!1),E=v.useCallback((u,x)=>{j.current+=x,$.current=u,!f.current&&(f.current=!0,queueMicrotask(()=>{f.current=!1;const b=j.current,T=$.current;j.current=0,$.current=void 0,!(b===0||T===void 0)&&(T==="list"?r.selectStep(Math.sign(b)):n.current?.scrollBy(Math.sign(b)))}))},[r]);return ae((u,x)=>{if(u==="q"||x.escape){S();return}if(F[u]){r.setFilter(F[u]);return}if(x.tab){r.setFocusedPanel(o.focusedPanel==="list"?"detail":"list");return}o.focusedPanel==="list"?x.upArrow||u==="k"?E("list",-1):(x.downArrow||u==="j")&&E("list",1):o.focusedPanel==="detail"&&(x.upArrow||u==="k"?E("detail",-1):(x.downArrow||u==="j")&&E("detail",1))}),i<D?t.jsx(a,{alignItems:"center",justifyContent:"center",children:t.jsxs(c,{color:"yellow",children:["Terminal too small. Resize to at least",D," ","rows."]})}):t.jsxs(a,{flexDirection:"column",height:i,width:l,children:[t.jsxs(a,{flexDirection:y?"row":"column",flexGrow:1,children:[t.jsx(a,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:t.jsx(ye,{counts:m,entries:d,filterType:o.filterType,focused:o.focusedPanel==="list",selectedIndex:o.selectedIndex,totalEntries:o.entries.length,viewportHeight:p})}),t.jsx(a,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:t.jsx(he,{checkMode:e,entry:g,focused:o.focusedPanel==="detail",scrollRef:n})})]}),t.jsx(a,{flexShrink:0,paddingX:1,children:t.jsx(c,{dimColor:!0,children:"↑/↓ or j/k:navigate | tab:switch panel | 1-4:filter | q:quit"})})]})},B=["types","node-addons","node","import","require","default"],ve=/^git\+https:\/\/github\.com\/([^/]+)\/([^/.]+(?:\.git)?)$/,Ee=/^git\+ssh:\/\/git@github\.com\/([^/]+)\/([^/.]+(?:\.git)?)$/,C=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),I=e=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(s=>I(s));const r={};for(const[s,l]of Object.entries(e))r[s]=I(l);return r},Pe=e=>{if(!C(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}},Oe=e=>e.endsWith(".git")?e.slice(0,-4):e,Ce=e=>{if(!C(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:s}=e;if(typeof s!="string")return{changed:!1,value:e};const l=ve.exec(s)??Ee.exec(s);if(!l)return{changed:!1,value:e};const i=l[1],o=Oe(l[2]??"");if(!i||!o)return{changed:!1,value:e};const n=new Set(["type","url"]);for(const d of Object.keys(e))if(!n.has(d))return{changed:!1,value:e};return{changed:!0,value:`${i}/${o}`}},Re=e=>{const r=Object.keys(e),s=[],l=[];for(const n of B)Object.hasOwn(e,n)&&s.push(n);for(const n of r)B.includes(n)||l.push(n);const i=[...s,...l];if(i.length===r.length&&i.every((n,d)=>n===r[d]))return{changed:!1,value:e};const o={};for(const n of i)o[n]=e[n];return{changed:!0,value:o}},W=e=>{if(!C(e))return{changed:!1,value:e};let r=!1;const s={};for(const[i,o]of Object.entries(e)){const n=W(o);s[i]=n.value,n.changed&&(r=!0)}const l=Re(s);return{changed:r||l.changed,value:l.value}},Ie=(e,r)=>{const s=I(e);let l=!1;if(r.formatBugs!==!1&&Object.hasOwn(s,"bugs")){const i=Pe(s.bugs);i.changed&&(s.bugs=i.value,l=!0)}if(r.formatRepository!==!1&&Object.hasOwn(s,"repository")){const i=Ce(s.repository);i.changed&&(s.repository=i.value,l=!0)}if(r.sortExports!==!1&&Object.hasOwn(s,"exports")&&C(s.exports)){const i=W(s.exports);i.changed&&(s.exports=i.value,l=!0)}return{changed:l,pkg:s}},Te=/at position (\d+)/,Me=/\(?line (\d+) column (\d+)\)?/,Ne=e=>{const r=new Set,s=[],l=o=>{const n=Y(o);!r.has(n)&&M(n)&&(r.add(n),s.push(n))};l(P(e,"package.json"));const i=te(e);if(i){const o=N(e,i);for(const n of o)l(P(e,n,"package.json"))}else{const o=P(e,"package.json");if(M(o)){const n=JSON.parse(L(o)),d=Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages;if(d){const g=N(e,d);for(const m of g)l(P(e,m,"package.json"))}}}return s},Ae=e=>/\n([ \t]+)/.exec(e)?.[1]??" ",De=e=>{if(!(e===void 0||e===""))return e==="tab"||e===String.raw`\t`?" ":/^\d+$/.test(e)?" ".repeat(Number.parseInt(e,10)):e},R=e=>e===void 0?[]:(Array.isArray(e)?e:[e]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0),Fe=e=>e.includes(`\r
2
- `)?"crlf":"lf",Be=new Set(["auto","crlf","lf"]),Ge=e=>{if(e===void 0||e==="")return"auto";if(Be.has(e))return e;throw new Error(`--line-ending must be one of: auto, lf, crlf (got "${e}")`)},_e=(e,r,s)=>r.length===0?e:e.filter(l=>{const i=J(s,l),o=V(l);return!r.some(n=>{const d=n.includes("/")?i:o;return oe(n,d)})}),Je=(e,r)=>{if(r.length===0)return e;const s={},l=new Set;for(const i of r)Object.hasOwn(e,i)&&(s[i]=e[i],l.add(i));for(const i of Object.keys(e))l.has(i)||(s[i]=e[i]);return s},Le=(e,r,s)=>{if(s.length===0)return e;const l={...e};for(const i of s)Object.hasOwn(r,i)&&(l[i]=r[i]);return l},qe=(e,r)=>{let s=1,l=1;const i=Math.min(r,e.length);for(let o=0;o<i;o++)e.codePointAt(o)===10?(s++,l=1):l++;return{column:l,line:s}},G=(e,r,s=2)=>{const l=e.split(`
3
- `);if(r<1||r>l.length)return[];const i=Math.max(0,r-1-s),o=Math.min(l.length,r+s),n=[];for(let d=i;d<o;d++)n.push({content:l[d]??"",isErrorLine:d+1===r,lineNumber:d+1});return n},_=(e,r)=>{if(!(e instanceof Error))return;const s=Te.exec(e.message);if(s){const{column:i,line:o}=qe(r,Number.parseInt(s[1]??"0",10));return{column:i,line:o,snippet:G(r,o)}}const l=Me.exec(e.message);if(l){const i=Number.parseInt(l[1]??"1",10);return{column:Number.parseInt(l[2]??"1",10),line:i,snippet:G(r,i)}}},He=(e,r)=>{const s=Object.keys(JSON.parse(e)),l=Object.keys(JSON.parse(r)),i=new Map(s.map((n,d)=>[n,d])),o=[];for(const[n,d]of l.entries()){const g=i.get(d);g!==void 0&&g!==n&&o.push({fromIndex:g,key:d,toIndex:n})}return o},Xe=(e,r,s)=>{const l=r.indent??s.indent??Ae(e),i=r.lineEnding==="auto"?s.lineEnding??Fe(e):r.lineEnding,o=q(e,{pretty:!1,sortScripts:r.sortScripts});let n=JSON.parse(o);if(r.unsorted.length>0){const y=JSON.parse(e);n=Le(n,y,r.unsorted)}n=Je(n,r.sortOrder);const d={formatBugs:r.formatBugs,formatRepository:r.formatRepository,sortExports:r.sortExports},g=Ie(n,d);let m=JSON.stringify(g.pkg,null,l);return r.finalNewline&&(m+=`
4
- `),i==="crlf"&&(m=m.replaceAll(`
5
- `,`\r
6
- `)),m},We=(e,r)=>{const s=Ne(e),l=U(e),i=Z({cwd:e,extraPatterns:ee(l)}),o=s.filter(d=>!i.ignores(d)),n=_e(o,r,e);return{afterGitignore:o,allFiles:s,files:n}},ze=async(e,{checkMode:r,cwd:s,fs:l,normalized:i})=>{const o=J(s,e)||e;let n;try{n=L(e)}catch(h){return{diff:[],error:{message:O(h),step:"read"},filePath:e,relativePath:o,status:"error"}}let d;try{d=q(n,{pretty:!1,sortScripts:i.sortScripts})}catch(h){const w={message:O(h),step:"native-sort"},p=_(h,n);return p&&(w.context=p),{diff:[],error:w,filePath:e,relativePath:o,status:"error"}}const g=i.editorconfig?re(e):{};let m;try{m=Xe(n,i,g)}catch(h){const w={message:O(h),step:"json-parse"},p=_(h,n);return p&&(w.context=p),{diff:[],error:w,filePath:e,relativePath:o,status:"error"}}if(n===m)return{diff:[],filePath:e,relativePath:o,status:"unchanged"};let y;try{y=He(n,d)}catch{y=[]}if(r)return{diff:y,filePath:e,relativePath:o,status:"would-rewrite"};try{await l.writeFile(e,m,"utf8")}catch(h){return{diff:y,error:{message:O(h),step:"write"},filePath:e,relativePath:o,status:"error"}}return{diff:y,filePath:e,relativePath:o,status:"rewritten"}},Ve=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 s=r.isErrorLine?">":" ";k.info(` ${s} ${String(r.lineNumber).padStart(4)} | ${r.content}`)}}},ir=async({fs:e,options:r,visConfig:s,workspaceRoot:l})=>{const i=l??process.cwd(),o=s?.sortPackageJson,n=r.check||!1,d={editorconfig:r.editorconfig===!1?!1:o?.editorconfig??!0,finalNewline:r.finalNewline??o?.finalNewline??!0,formatBugs:r.formatBugs===!1?!1:o?.formatBugs??!0,formatRepository:r.formatRepository===!1?!1:o?.formatRepository??!0,ignore:[...R(r.ignore),...o?.ignore??[]],indent:De(r.indent??o?.indent),lineEnding:Ge(r.lineEnding??o?.lineEnding),sortExports:r.sortExports===!1?!1:o?.sortExports??!0,sortOrder:[...R(r.sortOrder),...o?.sortOrder??[]],sortScripts:r.sortScripts||o?.sortScripts||!1,unsorted:[...R(r.unsorted),...o?.unsorted??[]]},g=We(i,d.ignore),{afterGitignore:m,allFiles:y,files:h}=g;if(h.length===0){y.length===0?k.info("No package.json files found."):m.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 w=[];for(const f of h)w.push(await ze(f,{checkMode:n,cwd:i,fs:e,normalized:d}));let p=0,S=0,j=0;for(const f of w)f.status==="error"?j++:f.status==="rewritten"||f.status==="would-rewrite"?p++:S++;const $=p>0||j>0;if(process.stdout.isTTY&&!se&&$){const f=new fe(w);await K(Q.createElement($e,{checkMode:n,store:f}),{alternateScreen:!0,exitOnCtrlC:!1,interactive:!0,patchConsole:!0}).waitUntilExit()}else for(const f of w)switch(f.status){case"error":{Ve(f);break}case"rewritten":{k.success(`Sorted ${f.filePath}`);break}case"would-rewrite":{k.warn(`${f.filePath} is not sorted`);break}}if(n)p>0?(k.info(`${String(p)} file${p===1?"":"s"} not sorted, ${String(S)} already sorted`),process.exitCode=1):j===0&&k.info(`All ${String(S)} package.json file${S===1?" is":"s are"} sorted`);else{const f=[];p>0&&f.push(`sorted ${String(p)} file${p===1?"":"s"}`),S>0&&f.push(`${String(S)} already sorted`),j>0&&f.push(`${String(j)} error${j===1?"":"s"}`),f.length>0&&k.info(f.join(", "))}j>0&&(process.exitCode=1)};export{G as buildSnippet,He as computeKeyDiff,qe as computeLineColumn,ir as default,We as discoverPackageJsonFiles,_ as extractParseErrorContext,ze as processFile};
1
+ import{createRequire as G}from"node:module";import{I as q,j as X,E as O,V as K,s as T,q as D}from"../packem_shared/index.server-J83sowC4.js";import{y as B}from"../packem_shared/index-CE6MsgcV.js";import{X as Q}from"./cli-main.js";import{d as k,f as v,r as Y,a as Z,b as ee,s as ne,c as te,e as ie,u as re,h as se,i as oe,j as ae,k as le,l as ce,m as de,n as ue,v as fe,w as ge,q as pe,t as me}from"../packem_shared/watch-loop-BZudYfcl.js";import{p as c}from"./catalog.js";const H=G(import.meta.url),w=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,U=e=>{if(typeof w<"u"&&w.versions&&w.versions.node){const[n,t]=w.versions.node.split(".").map(Number);if(n>22||n===22&&t>=3||n===20&&t>=16)return w.getBuiltinModule(e)}return H(e)},{createHash:y}=U("node:crypto"),he={1:"warning",2:"error"},xe={argsCheck:(e,n)=>V(e,n,!1),argsFix:(e,n)=>V(e,n,!0),bin:()=>["pnpm","exec","eslint"],cacheKey:(e,n)=>{const t=["eslint",e.declaredVersion??"unknown",e.configFile??"no-config",n.maxWarnings===void 0?"":`mw=${n.maxWarnings}`,n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=k(n,c.eslint.packageNames[0]),i=v(e,c.eslint.configFiles);if(!(!t&&!i))return{adapter:"eslint",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["cjs","cts","js","jsx","mjs","mts","ts","tsx","vue"],id:"eslint",kind:"lint",parse:(e,n)=>{if(!e.stdout.trim())return[];let t;try{t=JSON.parse(e.stdout)}catch{return[{adapter:"eslint",file:n.root,fixable:!1,message:`eslint output was not valid JSON (exit ${e.exitCode})`,severity:"error"}]}const i=[];for(const r of t)for(const s of r.messages)i.push({adapter:"eslint",column:s.column,endColumn:s.endColumn,endLine:s.endLine,file:r.filePath,fixable:!!s.fix,line:s.line,message:s.message,ruleId:s.ruleId??void 0,severity:s.fatal?"error":he[s.severity]??"warning"});return i}},V=(e,n,t)=>{const i=["--format","json","--no-error-on-unmatched-pattern"];return t&&i.push("--fix"),n.quiet&&i.push("--quiet"),typeof n.maxWarnings=="number"&&i.push("--max-warnings",String(n.maxWarnings)),n.extraArgs?.length&&i.push(...n.extraArgs),i.push(...e),i},we=/^([^:]+):(\d+)(?::(\d+))?\s+([\w/-]+)\s+(.+)$/,ke=e=>{const n=we.exec(e);if(!n)return;const[,t,i,r,s,a]=n;return{column:r===void 0?void 0:Number(r),file:t,line:Number(i),message:a,ruleId:s}},ve=e=>e.startsWith("/")||/^[a-z]:[\\/]/i.test(e),ye={argsCheck:(e,n)=>J(e,n,!1),argsFix:(e,n)=>J(e,n,!0),bin:()=>["pnpm","exec","markdownlint-cli2"],cacheKey:(e,n)=>{const t=["markdownlint",e.declaredVersion??"unknown",e.configFile??"no-config",n.maxWarnings===void 0?"":`mw=${n.maxWarnings}`,n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=c.markdownlint.packageNames.map(r=>k(n,r)).find(r=>r!==void 0),i=v(e,c.markdownlint.configFiles);if(!(!t&&!i))return{adapter:"markdownlint",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["markdown","md"],id:"markdownlint",kind:"lint",parse:(e,n)=>{const t=(e.stderr||e.stdout||"").trim();if(!t)return[];const i=[];for(const r of t.split(/\r?\n/)){const s=ke(r.trim());s&&i.push({adapter:"markdownlint",column:s.column,file:ve(s.file)?s.file:`${n.root}/${s.file}`,fixable:!0,line:s.line,message:s.message,ruleId:s.ruleId,severity:"warning"})}return i}},J=(e,n,t)=>{const i=[];return t&&i.push("--fix"),n.extraArgs?.length&&i.push(...n.extraArgs),e.length===0?i.push("**/*.md"):i.push(...e),i},$e={advice:"info",error:"error",warning:"warning"},be={argsCheck:(e,n)=>R(e,n,!1),argsFix:(e,n)=>R(e,n,!0),bin:()=>["pnpm","exec","oxlint"],cacheKey:(e,n)=>{const t=["oxlint",e.declaredVersion??"unknown",e.configFile??"no-config",n.maxWarnings===void 0?"":`mw=${n.maxWarnings}`,n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=k(n,c.oxlint.packageNames[0]),i=v(e,c.oxlint.configFiles);if(!(!t&&!i))return{adapter:"oxlint",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["astro","cjs","cts","js","jsx","mjs","mts","svelte","ts","tsx","vue"],id:"oxlint",kind:"lint",parse:(e,n)=>{if(!e.stdout.trim())return[];let t;try{t=JSON.parse(e.stdout)}catch{return[{adapter:"oxlint",file:n.root,fixable:!1,message:`oxlint output was not valid JSON (exit ${e.exitCode})`,severity:"error"}]}const i=[];for(const r of t.diagnostics??[]){const s=r.labels?.[0]?.span;i.push({adapter:"oxlint",column:s?.column,file:r.filename??n.root,fixable:!1,line:s?.line,message:r.message??"",ruleId:r.code,severity:$e[r.severity??""]??"warning"})}return i}},R=(e,n,t)=>{const i=["--format","json"];return t&&i.push("--fix"),n.quiet&&i.push("--quiet"),typeof n.maxWarnings=="number"&&i.push(`--max-warnings=${String(n.maxWarnings)}`),n.extraArgs?.length&&i.push(...n.extraArgs),i.push(...e),i},Ae={error:"error",info:"info",style:"info",warning:"warning"},Fe=e=>e.startsWith("/")||/^[a-z]:[\\/]/i.test(e),je=(e,n)=>e?Fe(e)?e:`${n}/${e}`:n,Ce={argsCheck:(e,n)=>L(e,n),argsFix:(e,n)=>L(e,n),bin:()=>["shellcheck"],cacheKey:(e,n)=>{const t=["shellcheck",e.declaredVersion??"unknown",e.configFile??"no-config",n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=k(n,c.shellcheck.packageNames[0]),i=v(e,c.shellcheck.configFiles);if(!(!t&&!i))return{adapter:"shellcheck",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["bash","ksh","sh"],id:"shellcheck",kind:"lint",parse:(e,n)=>{if(!e.stdout.trim())return[];let t;try{t=JSON.parse(e.stdout)}catch{return[{adapter:"shellcheck",file:n.root,fixable:!1,message:`shellcheck output was not valid JSON (exit ${e.exitCode})`,severity:"error"}]}const i=[];for(const r of t.comments??[])i.push({adapter:"shellcheck",column:r.column,endColumn:r.endColumn,endLine:r.endLine,file:je(r.file,n.root),fixable:!!r.fix,line:r.line,message:r.message??"",ruleId:r.code===void 0?void 0:`SC${String(r.code)}`,severity:Ae[r.level??""]??"warning"});return i}},L=(e,n)=>{const t=["--format=json1"];return n.extraArgs?.length&&t.push(...n.extraArgs),t.push(...e),t},Se={error:"error",warning:"warning"},qe={argsCheck:(e,n)=>M(e,n,!1),argsFix:(e,n)=>M(e,n,!0),bin:()=>["pnpm","exec","stylelint"],cacheKey:(e,n)=>{const t=["stylelint",e.declaredVersion??"unknown",e.configFile??"no-config",n.maxWarnings===void 0?"":`mw=${n.maxWarnings}`,n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=k(n,c.stylelint.packageNames[0]),i=v(e,c.stylelint.configFiles);if(!(!t&&!i))return{adapter:"stylelint",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["astro","css","less","sass","scss","svelte","vue"],id:"stylelint",kind:"lint",parse:(e,n)=>{if(!e.stdout.trim())return[];let t;try{t=JSON.parse(e.stdout)}catch{return[{adapter:"stylelint",file:n.root,fixable:!1,message:`stylelint output was not valid JSON (exit ${e.exitCode})`,severity:"error"}]}const i=[];for(const r of t)for(const s of r.warnings??[])i.push({adapter:"stylelint",column:s.column,endColumn:s.endColumn,endLine:s.endLine,file:r.source,fixable:!1,line:s.line,message:s.text??"",ruleId:s.rule,severity:Se[s.severity??""]??"warning"});return i}},M=(e,n,t)=>{const i=["--formatter","json"];return t&&i.push("--fix"),n.quiet&&i.push("--quiet"),typeof n.maxWarnings=="number"&&i.push("--max-warnings",String(n.maxWarnings)),n.extraArgs?.length&&i.push(...n.extraArgs),i.push(...e),i},We=[be,ue,xe,qe,fe,ye,Ce,ge],Be=async({logger:e,options:n,visConfig:t,workspaceRoot:i})=>{const r=i??process.cwd(),s=t?.lint,a=Y(We,s?.order),j=Z(r,a),d=ee(j,a,"lint").filter(({adapter:l})=>s?.adapters?.[l.id]?.enabled!==!1);if(d.length===0){e.warn("vis lint: no linter detected in this workspace (looked for: oxlint, biome, eslint, stylelint, ruff, markdownlint, shellcheck, deno).");return}const C=l=>{const u=s?.adapters?.[l]?.extraArgs;return u&&u.length>0?[...u]:void 0},$={extraArgs:void 0,maxWarnings:typeof n.maxWarnings=="number"?n.maxWarnings:void 0,quiet:n.quiet??!1},b=Ne(n),P=n.fix?"fix":"check";let f;if(n.staged){if(f=ne(r),f===void 0)e.warn("vis lint: could not resolve --staged (not a git repo or git unavailable). Falling back to a workspace-wide run.");else if(f.length===0){e.info(q("✓ lint: no staged files"));return}}else if(typeof n.since=="string"&&n.since.length>0){if(f=te(r,n.since),f===void 0)e.warn(`vis lint: could not resolve --since ${n.since} (not a git repo or unknown ref). Falling back to a workspace-wide run.`);else if(f.length===0){e.info(q(`✓ lint: no files changed since ${n.since}`));return}}const W=b.length>0?b:void 0,E=Q(r,void 0,void 0,!0),S=n.format??"human";S==="human"&&n.output!==void 0&&e.warn("vis lint: --output is ignored for the human format; pass --format json|minimal|sarif|junit|github to redirect findings to a file.");const N=async l=>{const u=l!==void 0&&l.length>0&&W===void 0,m=[];for(const{adapter:o,presence:x}of d){let g;if(u){if(g=re(l,o.extensions),g.length===0)continue}else g=W??l??["."];const F=C(o.id),I={adapter:o,files:g,presence:x};F&&(I.options={...$,extraArgs:F}),m.push(I)}if(m.length===0)return;const z=await se(m,$,P,{cacheRoot:E}),A=m.map((o,x)=>{const g=z[x],F=o.adapter.parse(g,o.presence);return{adapter:o.adapter,durationMs:g.durationMs,exitCode:g.exitCode,findings:F}}),h=oe(A.map(o=>({adapter:o.adapter.id,durationMs:o.durationMs,exitCode:o.exitCode,findingCount:o.findings.length,findings:o.findings}))),p=S==="human"?void 0:ae({cwd:r,target:n.output});try{switch(S){case"github":{p.write(de({runs:A.map(o=>({findings:o.findings})),workspaceRoot:r}));break}case"json":{p.write(`${JSON.stringify({findings:h.findings,runs:h.runs},null,2)}
2
+ `);break}case"junit":{p.write(ce({runs:A.map(o=>({adapter:o.adapter.id,durationMs:o.durationMs,findings:o.findings})),workspaceRoot:r}));break}case"minimal":{Ie(h.findings,r,p);break}case"sarif":{p.write(le({runs:A.map(o=>({adapter:o.adapter.id,findings:o.findings,presence:m.find(x=>x.adapter.id===o.adapter.id)?.presence})),workspaceRoot:r}));break}default:_e(h.findings,r,e)}}finally{p?.close()}const _=me(h);_!==0&&(process.exitCode=_)};if(n.watch){const l=[...new Set(d.flatMap(({adapter:u})=>u.extensions))];await ie({extensions:l,initialFiles:f,label:"lint",log:u=>{e.info(u)},runCycle:N,workspaceRoot:r});return}await N(f)},Ne=e=>{const n=e;return[...n._??n.args??[]]},_e=(e,n,t)=>{if(e.length===0){t.info(q("✓ lint: no findings"));return}const i=pe(e);for(const[a,j]of i){t.info(X(B(n,a)));for(const d of j){const C=Oe(d),$=Ve(d.severity),b=d.ruleId?O(` ${d.ruleId}`):"";t.info(` ${O(C)} ${$} ${d.message}${b}`)}}const r=e.filter(a=>a.severity==="error").length,s=e.filter(a=>a.severity==="warning").length;t.info(""),t.info(`${K(`${String(r)} error${r===1?"":"s"}`)}, ${T(`${String(s)} warning${s===1?"":"s"}`)}`)},Ie=(e,n,t)=>{for(const i of e){const r=B(n,i.file),s=i.line??"",a=i.column??"";t.write(`${i.adapter} ${r} ${String(s)} ${String(a)} ${i.severity} ${i.ruleId??""} ${i.message}
3
+ `)}},Oe=e=>e.line===void 0?"":e.column===void 0?String(e.line):`${String(e.line)}:${String(e.column)}`,Ve=e=>e==="error"?K("error"):e==="warning"?T("warn "):D("info ");export{Be as default};
@@ -1,9 +1,6 @@
1
- import{createRequire as q}from"node:module";import{DEFAULT_CHANGES_DIR as Z}from"./DEFAULT_CLEAN_KEEP.js";import{b as J,f as Q}from"./orchestrator.js";import{createShellRunner as X}from"./shell-runner.js";import{r as ee}from"../packem_shared/slug-DoueYuLo.js";import{maxBump as te}from"../release/types.js";const V=q(import.meta.url),P=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,U=s=>{if(typeof P<"u"&&P.versions&&P.versions.node){const[e,t]=P.versions.node.split(".").map(Number);if(e>22||e===22&&t>=3||e===20&&t>=16)return P.getBuiltinModule(s)}return V(s)},{join:M,relative:Y}=U("node:path"),D=/(?!.*)/;function re(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function S(s){return s.map(e=>typeof e=="string"?re(e.trim()):e.source).filter(Boolean).join("|")}function ne(s,e){if(!s)return D;const t=S(s);return e?e(t):new RegExp(`^[\\s|*]*(${t})[:\\s]+(.*)`,"i")}function se(s,e){if(!s)return D;const t=e?"g":"gi";return new RegExp(`(?:.*?)??\\s*([\\w-\\.\\/]*?)??(${S(s)})([\\w-]+)(?=\\s|$|[,;)\\]])`,t)}function ie(s){if(!s)return/()(.+)/gi;const e=S(s);return new RegExp(`(${e})(?:\\s+(.*?))(?=(?:${e})|$)`,"gi")}function oe(s={}){const e=ne(s.noteKeywords,s.notesPattern),t=se(s.issuePrefixes,s.issuePrefixesCaseSensitive),r=ie(s.referenceActions);return{notes:e,referenceParts:t,references:r,mentions:/@([\w-]+)/g,url:/\b(?:https?):\/\/(?:www\.)?([-a-zA-Z0-9@:%_+.~#?&//=])+\b/}}const ce="------------------------ >8 ------------------------";function j(s){const e=s.match(/[^\r\n]/);if(typeof e?.index!="number")return"";const t=e.index;let r=s.length-1;for(;s[r]==="\r"||s[r]===`
2
- `;)r--;return s.substring(t,r+1)}function A(s,e){return s?`${s}
3
- ${e||""}`:e||""}function ae(s){return s?e=>!e.startsWith(s):()=>!0}function le(s,e){const t=s.indexOf(`${e} ${ce}`);return t===-1?s:s.slice(0,t)}function I(s){return!s.match(/^\s*gpg:/)}function _(s,e,t){const{groups:r}=e;for(let n=0,i=t.length,c;n<i;n++)c=t[n],s[c]=(r?r[c]:e[n+1])||null;return s}const fe={noteKeywords:["BREAKING CHANGE","BREAKING-CHANGE"],issuePrefixes:["#"],referenceActions:["close","closes","closed","fix","fixes","fixed","resolve","resolves","resolved"],headerPattern:/^(\w*)(?:\(([\w$@.\-*/ ]*)\))?: (.*)$/,headerCorrespondence:["type","scope","subject"],revertPattern:/^Revert\s"([\s\S]*)"\s*This reverts commit (\w*)\.?/,revertCorrespondence:["header","hash"],fieldPattern:/^-(.*?)-$/};function T(s={}){return{merge:null,revert:null,header:null,body:null,footer:null,notes:[],mentions:[],references:[],...s}}class he{options;regexes;lines=[];lineIndex=0;commit=T();constructor(e={}){this.options={...fe,...e},this.regexes=oe(this.options)}currentLine(){return this.lines[this.lineIndex]}nextLine(){return this.lines[this.lineIndex++]}isLineAvailable(){return this.lineIndex<this.lines.length}parseReference(e,t){const{regexes:r}=this;if(r.url.test(e))return null;const n=r.referenceParts.exec(e);if(!n)return null;let[i,c=null,u,p]=n,x=null;if(c){const b=c.indexOf("/");b!==-1&&(x=c.slice(0,b),c=c.slice(b+1))}return{raw:i,action:t,owner:x,repository:c,prefix:u,issue:p}}parseReferences(e){const{regexes:t}=this,r=e.match(t.references)?t.references:/()(.+)/gi,n=[];let i,c,u,p;for(;i=r.exec(e),!!i;)for(c=i[1]||null,u=i[2]||"";p=this.parseReference(u,c),!!p;)n.push(p);return n}skipEmptyLines(){let e=this.currentLine();for(;e!==void 0&&!e.trim();)this.nextLine(),e=this.currentLine()}parseMerge(){const{commit:e,options:t}=this,r=t.mergeCorrespondence||[],n=this.currentLine(),i=n&&t.mergePattern?n.match(t.mergePattern):null;return i?(this.nextLine(),e.merge=i[0]||null,_(e,i,r),!0):!1}parseHeader(e){e&&this.skipEmptyLines();const{commit:t,options:r}=this,n=r.headerCorrespondence||[],i=t.header??this.nextLine();let c=null;i&&(r.breakingHeaderPattern&&(c=i.match(r.breakingHeaderPattern)),!c&&r.headerPattern&&(c=i.match(r.headerPattern))),i&&(t.header=i),c&&_(t,c,n)}parseMeta(){const{options:e,commit:t}=this;if(!e.fieldPattern||!this.isLineAvailable())return!1;let r,n=null,i=!1;for(;this.isLineAvailable();){if(r=this.currentLine().match(e.fieldPattern),r){n=r[1]||null,this.nextLine();continue}if(n)i=!0,t[n]=A(t[n],this.currentLine()),this.nextLine();else break}return i}parseNotes(){const{regexes:e,commit:t}=this;if(!this.isLineAvailable())return!1;const r=this.currentLine().match(e.notes);let n=[];if(r){const i={title:r[1],text:r[2]};for(t.notes.push(i),t.footer=A(t.footer,this.currentLine()),this.nextLine();this.isLineAvailable();){if(this.parseMeta()||this.parseNotes())return!0;if(n=this.parseReferences(this.currentLine()),n.length?t.references.push(...n):i.text=A(i.text,this.currentLine()),t.footer=A(t.footer,this.currentLine()),this.nextLine(),n.length)break}return!0}return!1}parseBodyAndFooter(e){const{commit:t}=this;if(!this.isLineAvailable())return e;const r=this.parseReferences(this.currentLine()),n=!r.length&&e;return n?t.body=A(t.body,this.currentLine()):(t.references.push(...r),t.footer=A(t.footer,this.currentLine())),this.nextLine(),n}parseBreakingHeader(){const{commit:e,options:t}=this;if(!t.breakingHeaderPattern||e.notes.length||!e.header)return;const r=e.header.match(t.breakingHeaderPattern);r&&e.notes.push({title:"BREAKING CHANGE",text:r[3]})}parseMentions(e){const{commit:t,regexes:r}=this;let n;for(;n=r.mentions.exec(e),!!n;)t.mentions.push(n[1])}parseRevert(e){const{commit:t,options:r}=this,n=r.revertCorrespondence||[],i=r.revertPattern?e.match(r.revertPattern):null;i&&(t.revert=_({},i,n))}cleanupCommit(){const{commit:e}=this;e.body&&(e.body=j(e.body)),e.footer&&(e.footer=j(e.footer)),e.notes.forEach(r=>{r.text=j(r.text)});const t=new Set;e.references=e.references.filter(r=>{const n=`${r.action} ${r.raw}`.toLocaleLowerCase(),i=!t.has(n);return i&&t.add(n),i})}parse(e){if(!e.trim())throw new TypeError("Expected a raw commit");const{commentChar:t}=this.options,r=ae(t),n=j(e).split(/\r?\n/),i=t?le(n,t).filter(x=>r(x)&&I(x)):n.filter(x=>I(x)),c=T();this.lines=i,this.lineIndex=0,this.commit=c;const u=this.parseMerge();this.parseHeader(u),c.header&&(c.references=this.parseReferences(c.header));let p=!0;for(;this.isLineAvailable();)this.parseMeta(),this.parseNotes()&&(p=!1),this.parseBodyAndFooter(p)||(p=!1);return this.parseBreakingHeader(),this.parseMentions(e),this.parseRevert(e),this.cleanupCommit(),c}}const N={build:"patch",chore:"patch",ci:"patch",docs:"patch",feat:"minor",fix:"patch",perf:"patch",refactor:"patch",style:"patch",test:"patch"},ue=new he,pe=/^Revert\s+"(.+)"\s*$/,de=/This reverts commit\s+([0-9a-f]{7,40})/i,me=/^(?:[\p{Emoji_Presentation}\p{Extended_Pictographic}]|:\w+:)\s+/u,ge=(s,e)=>{const t=s.replace(me,""),r=ue.parse(`${t}
4
-
5
- ${e}`);return{breaking:r.notes.some(n=>/BREAKING/i.test(n.title)),scope:r.scope??void 0,type:r.type??void 0}},xe=(s,e,t)=>{let r,n=!1;if(t.type==="revert"){n=!0;const u=s.indexOf(":");u!==-1&&(r=s.slice(u+1).trim())}else{const u=pe.exec(s.trim());u&&(n=!0,r=u[1]?.trim())}let i;const c=de.exec(e);return c&&(i=c[1]?.toLowerCase()),{isRevert:n,targetSha:i,targetSubject:r}},ve=(s,e=new Set,t)=>{const r=s.map(o=>{const l=ge(o.subject,o.body),{isRevert:a,targetSha:f,targetSubject:d}=xe(o.subject,o.body,l);return{...o,cancelled:!1,parsed:l,revert:a,revertSubject:d,revertTargetSha:f}}),n=r.toReversed(),i=12,c=new Map;for(const o of n)if(c.set(o.hash,o),o.hash.length>=7){const l=Math.min(o.hash.length-1,i);for(let a=7;a<=l;a+=1){const f=o.hash.slice(0,a);if(c.has(f)){const d=c.get(f);d!==null&&d!==o&&c.set(f,null)}else c.set(f,o)}}const u=(o,l)=>{if(o.revertTargetSha){const a=o.revertTargetSha.toLowerCase();let f=c.get(a)??void 0;if(f||(f=n.find(d=>d.hash.startsWith(a))),f&&f!==o)return f}if(o.revertSubject)for(let a=l.length-1;a>=0;a-=1){const f=l[a];if(f.subject===o.revertSubject)return f}},p=64,x=o=>{let l=o;for(let a=0;a<p;a+=1){if(!l.revert)return l;const f=l.cancelledBy;let d;if(f&&(d=c.get(f)??void 0,d||(d=c.get(f.slice(0,7))??void 0)),!d||d===l)return l;l=d}},b=[],w=[];for(const o of n){if(o.revert){const l=u(o,w);if(l){if(e.has(l.hash)){w.push(o);continue}const a=x(l);if(a===void 0){b.push(`Revert chain at ${o.hash} exceeded depth limit (${p}) — skipping cancellation`),w.push(o);continue}if(e.has(a.hash)){w.push(o);continue}a.cancelled=!a.cancelled,a.cancelledBy=a.cancelled?o.hash:void 0,o.cancelled=!0,o.cancelledBy=l.hash}}w.push(o)}const L=r.filter(o=>!o.cancelled&&!o.revert&&!o.subject?.startsWith("Merge ")),C=L.filter(o=>!o.parsed.type);if(L.length>0&&C.length/L.length>.5){const o=t??"<from>..HEAD";b.push(`${C.length}/${L.length} commits in ${o} have no conventional-commits prefix. Consider enabling commit-message linting.`)}return{commits:r,warnings:b}},Ae=async({fs:s,logger:e,options:t,workspaceRoot:r})=>{const n=r??process.cwd(),i=await J({cwd:n,skipRegistryLookup:!0}),{printConfigIfRequested:c}=await import("./print-config.js");if(c(t,i,e))return;const u=X();let p=t.from;if(!p){const h=i.config.baseBranch??"main",m=await u.run("git",["merge-base",`origin/${h}`,"HEAD"],{cwd:n,silent:!0});if(m.exitCode===0&&m.stdout.trim())p=m.stdout.trim();else{const g=await u.run("git",["merge-base",h,"HEAD"],{cwd:n,silent:!0});p=g.exitCode===0?g.stdout.trim():"HEAD~10"}}const x=new Map;for(const h of i.packages){const m=(h.dir.startsWith(n)?h.dir.slice(n.length):h.dir).replaceAll("\\","/").replace(/^\/+/,"");x.set(m,h.name)}const b=h=>{for(const[m,g]of x)if(h.startsWith(`${m}/`)||h===`${m}/package.json`)return g},w=Math.random().toString(16).slice(2,10),L=`@@VIS_RELEASE_COMMIT_${w}@@`,C=`@@VIS_RELEASE_FILES_${w}@@`,o=await u.run("git",["log",`${p}..HEAD`,`--pretty=format:${L}%n%H%n%s%n%b%n${C}`,"--name-only"],{cwd:n,silent:!0});if(o.exitCode!==0){e.error(`git log failed: ${o.stderr}`),process.exitCode=1;return}const l=new Map,a=[],f=[],d=o.stdout.split(L).map(h=>h.trim()).filter(Boolean);for(const h of d){const[m,g=""]=h.split(C).toReversed(),E=g.split(`
6
- `),$=E[0]?.trim()??"",y=E[1]?.trim()??"",v=E.slice(2).join(`
7
- `).trim(),R=(m??"").split(`
8
- `).map(z=>z.trim()).filter(Boolean);$&&f.push({body:v,files:R,hash:$,subject:y})}const{commits:F,warnings:G}=ve(f,void 0,`${p}..HEAD`);for(const h of G)e.warn(h);for(const{cancelled:h,files:m,parsed:g,subject:E}of F){if(h)continue;let $="patch";g.breaking?$="major":g.type&&N[g.type]&&($=N[g.type]??"patch");const y=new Set;if(g.scope)for(const v of i.packages)(v.name===g.scope||v.name.endsWith(`/${g.scope}`))&&y.add(v.name);if(y.size===0)for(const v of m){const R=b(v);R&&y.add(R)}for(const v of y){const R=l.get(v);l.set(v,R?te(R,$):$)}y.size>0&&a.push(`- ${E}`)}if(l.size===0){e.info("No commits affected workspace packages — nothing to generate.");return}const O={bumps:Object.fromEntries(l)},K=a.length>0?a.join(`
9
- `):"Auto-generated change file.",k=Q(O,K);if(t.dryRun){e.info("[dry-run] would write:"),e.info(k);return}const B=i.config.changesDir??Z,W=(t.name??ee()).replaceAll(/[^a-z0-9-]/gi,"-"),H=M(n,B,`${W}.md`);await s.mkdir(M(n,B),{recursive:!0}),await s.writeFile(H,k),e.info(`Created ${Y(n,H)}`);for(const[h,m]of l)e.info(` ${h}: ${m}`)};export{Ae as default};
1
+ import{createRequire as z}from"node:module";import{y as J,v as L,m as P,f as M,J as V,B as Y}from"../packem_shared/index-CE6MsgcV.js";import{m as t,n as a,i as c,r as v,$ as K,d as Q,k as U,s as Z,t as ee,u as re,e as te,W as N}from"./catalog.js";import"../packem_shared/env-DJlbJiFh.js";import{I as se}from"../packem_shared/index-B0EsgdzO.js";import oe from"./index.js";import{sortPackageJsonStringWithOptions as q}from"#native";import{T as ne,_ as ie,U as le,Q as ce,y as ae,p as k}from"./cli-main.js";import{o as O}from"../packem_shared/utils-CRueU43T.js";const Ke=z(import.meta.url),Qe=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process;const A={error:0,rewritten:1,"would-rewrite":1,unchanged:2},de=e=>[...e].sort((r,s)=>A[r.status]-A[s.status]),ue=(e,r)=>r==="all"?e:r==="errors"?e.filter(s=>s.status==="error"):r==="rewritten"?e.filter(s=>s.status==="rewritten"||s.status==="would-rewrite"):e.filter(s=>s.status==="unchanged");class fe{#e;#r=new Set;constructor(r){this.#e={entries:de(r),filterType:"all",focusedPanel:"list",selectedIndex:0}}getSnapshot=()=>this.#e;subscribe=r=>(this.#r.add(r),()=>{this.#r.delete(r)});getFilteredEntries=()=>ue(this.#e.entries,this.#e.filterType);#t(){this.#e={...this.#e};for(const r of this.#r)r()}select(r){const s=this.getFilteredEntries();this.#e.selectedIndex=s.length===0?-1:Math.max(0,Math.min(r,s.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()}}const he=({checkMode:e,entry:r,focused:s,scrollRef:l})=>{const i=s?"white":"gray";return r?t.jsxs(a,{borderColor:i,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[t.jsx(a,{flexShrink:0,paddingTop:1,paddingX:2,children:t.jsx(c,{bold:!0,color:"white",children:r.relativePath})}),t.jsxs(ne,{flexGrow:1,flexShrink:1,paddingX:2,ref:l,scrollbar:!0,scrollbarColor:"gray",children:[t.jsx(c,{}),t.jsxs(a,{children:[t.jsx(a,{width:10,children:t.jsx(c,{dimColor:!0,children:"Status:"})}),r.status==="error"?t.jsx(c,{bold:!0,color:"red",children:"error"}):r.status==="unchanged"?t.jsx(c,{bold:!0,color:"green",children:"already sorted"}):r.status==="rewritten"?t.jsx(c,{bold:!0,color:"yellow",children:"rewritten"}):t.jsx(c,{bold:!0,color:"yellow",children:"would rewrite (--check)"})]}),t.jsxs(a,{children:[t.jsx(a,{width:10,children:t.jsx(c,{dimColor:!0,children:"Path:"})}),t.jsx(c,{children:r.filePath})]}),r.error?t.jsxs(t.Fragment,{children:[t.jsxs(a,{flexDirection:"column",marginTop:1,children:[t.jsx(c,{dimColor:!0,children:"── "}),t.jsx(c,{bold:!0,color:"red",children:"ERROR"}),t.jsxs(a,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[t.jsxs(a,{children:[t.jsx(a,{width:10,children:t.jsx(c,{dimColor:!0,children:"Step:"})}),t.jsx(c,{color:"yellow",children:r.error.step})]}),r.error.context&&t.jsxs(a,{children:[t.jsx(a,{width:10,children:t.jsx(c,{dimColor:!0,children:"Position:"})}),t.jsx(c,{children:`line ${String(r.error.context.line)}, column ${String(r.error.context.column)}`})]}),t.jsx(a,{marginTop:1,children:t.jsx(c,{color:"red",children:r.error.message})})]})]}),r.error.context&&r.error.context.snippet.length>0&&t.jsxs(a,{flexDirection:"column",marginTop:1,children:[t.jsx(c,{dimColor:!0,children:"── "}),t.jsx(c,{bold:!0,color:"white",children:"SNIPPET"}),t.jsxs(a,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[r.error.context.snippet.map(o=>{const n=`${o.isErrorLine?"❯":" "} ${String(o.lineNumber).padStart(4)} `;return t.jsxs(a,{children:[t.jsx(c,{color:o.isErrorLine?"red":"gray",children:n}),t.jsx(c,{color:o.isErrorLine?"white":"gray",wrap:"truncate-end",children:o.content||" "})]},o.lineNumber)}),r.error.context.column>0&&t.jsx(a,{children:t.jsx(c,{color:"red",children:`${" ".repeat(7+r.error.context.column-1)}↑`})})]})]})]}):t.jsxs(a,{flexDirection:"column",marginTop:1,children:[t.jsx(c,{dimColor:!0,children:"── "}),t.jsx(c,{bold:!0,color:"white",children:"KEY DIFF"}),t.jsx(a,{flexDirection:"column",marginTop:1,paddingLeft:2,children:r.diff.length===0?t.jsx(c,{dimColor:!0,children:"No top-level keys moved (sub-key reorder only)."}):r.diff.map(o=>{const n=o.toIndex-o.fromIndex,d=n<0?`↑ ${String(Math.abs(n))}`:`↓ ${String(n)}`,g=n<0?"green":"yellow";return t.jsxs(a,{children:[t.jsx(a,{width:28,children:t.jsx(c,{wrap:"truncate",children:o.key})}),t.jsx(a,{width:10,children:t.jsxs(c,{dimColor:!0,children:[String(o.fromIndex)," → ",String(o.toIndex)]})}),t.jsx(c,{color:g,children:d})]},o.key)})}),e&&r.status==="would-rewrite"&&t.jsx(a,{marginTop:1,paddingLeft:2,children:t.jsx(c,{dimColor:!0,children:"--check mode: no write performed."})})]})]})]}):t.jsx(a,{alignItems:"center",borderColor:"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,justifyContent:"center",children:t.jsx(c,{dimColor:!0,children:"No entry selected"})})},ge={error:"red",rewritten:"yellow",unchanged:"green","would-rewrite":"yellow"},pe={error:"ERROR",rewritten:"REWROTE",unchanged:"SORTED","would-rewrite":"REWRITE"},H={error:"errors",rewritten:"rewrites",unchanged:"sorted","would-rewrite":"rewrites"},xe={errors:"Errors",rewrites:"Rewrites",sorted:"Sorted"},me=[{count:e=>e.errors+e.rewrites+e.sorted,key:"all",label:"All",shortcut:"1"},{count:e=>e.rewrites,key:"rewritten",label:"Rewrites",shortcut:"2"},{count:e=>e.errors,key:"errors",label:"Errors",shortcut:"3"},{count:e=>e.sorted,key:"unchanged",label:"Sorted",shortcut:"4"}],X=e=>{const r={errors:0,rewrites:0,sorted:0};for(const s of e)r[H[s.status]]++;return r},we=({entry:e,isSelected:r})=>{const s=ge[e.status],l=pe[e.status];return t.jsxs(a,{flexShrink:0,height:1,children:[t.jsx(c,{children:r?">":" "}),t.jsx(c,{children:" "}),t.jsx(c,{bold:!0,color:s,children:`[${l}]`.padEnd(10)}),t.jsx(c,{children:" "}),t.jsx(a,{flexGrow:1,children:t.jsx(c,{bold:r,inverse:r,wrap:"truncate",children:e.relativePath})}),e.status!=="error"&&e.diff.length>0&&t.jsx(c,{dimColor:!0,children:` ${String(e.diff.length)} key${e.diff.length===1?"":"s"}`})]})},je=({color:e,count:r,label:s})=>t.jsx(a,{flexShrink:0,height:1,children:t.jsx(c,{bold:!0,color:e,children:`${s} (${String(r)})`})}),ye=({counts:e,entries:r,filterType:s,focused:l,selectedIndex:i,totalEntries:o,viewportHeight:n})=>{const d=l?"white":"gray",g=X(r),m=(g.errors>0?1:0)+(g.rewrites>0?1:0)+(g.sorted>0?1:0),y=s==="all"&&m>1,h=[];let w;for(const[u,x]of r.entries()){const b=H[x.status];y&&b!==w&&(w!==void 0&&h.push({kind:"spacer"}),h.push({color:b==="errors"?"red":b==="rewrites"?"yellow":"green",count:g[b],kind:"header",label:xe[b]}),w=b),h.push({entry:x,entryIndex:u,kind:"entry"})}const p=h.findIndex(u=>u.kind==="entry"&&u.entryIndex===i),S=p!==-1,j=h.length,$=Math.max(0,j-n);let f=0;S&&n>0&&(f=Math.min($,Math.max(0,p-n+1)));const E=j>n&&n>0;return t.jsxs(a,{borderColor:d,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[t.jsxs(a,{flexShrink:0,gap:1,paddingX:1,children:[t.jsx(c,{bold:!0,inverse:!0,children:" VIS SORT "}),t.jsxs(c,{wrap:"truncate",children:[o," ","file",o===1?"":"s"]})]}),t.jsx(a,{flexShrink:0,gap:1,paddingX:1,paddingY:1,children:me.map(u=>{const x=s===u.key,b=u.count(e);return t.jsxs(a,{children:[t.jsx(c,{dimColor:!x,children:"["}),t.jsx(c,{bold:x,color:x?"cyan":"gray",children:u.shortcut}),t.jsx(c,{dimColor:!x,children:"]"}),t.jsxs(c,{color:x?"white":"gray",children:[" ",u.label]}),t.jsxs(c,{dimColor:!0,children:[" ","(",b,")"]})]},u.key)})}),t.jsxs(a,{flexDirection:"row",flexGrow:1,overflow:"hidden",children:[t.jsx(a,{flexDirection:"column",flexGrow:1,overflow:"hidden",paddingLeft:1,children:t.jsx(a,{flexDirection:"column",marginTop:-f,children:h.map((u,x)=>u.kind==="spacer"?t.jsx(a,{flexShrink:0,height:1},`s-${String(x)}`):u.kind==="header"?t.jsx(je,{color:u.color,count:u.count,label:u.label},`h-${u.label}`):t.jsx(we,{entry:u.entry,isSelected:u.entryIndex===i},u.entry.filePath))})}),E&&t.jsx(a,{flexShrink:0,marginLeft:1,marginRight:1,children:t.jsx(ie,{contentHeight:j,placement:"inset",scrollOffset:f,style:"block",viewportHeight:n})})]})]})},be=100,D=10,ke=6,Se=1,F={1:"all",2:"rewritten",3:"errors",4:"unchanged"},$e=({checkMode:e,store:r})=>{const{exit:s}=le(),{columns:l,rows:i}=ce(),o=v.useSyncExternalStore(r.subscribe,r.getSnapshot),n=v.useRef(null),d=r.getFilteredEntries(),g=d[o.selectedIndex]??null,m=X(o.entries),y=l>=be,h=Math.max(0,i-Se),w=y?h:Math.floor(h/2),p=Math.max(0,w-ke),S=v.useCallback(()=>{s()},[s]),j=v.useRef(0),$=v.useRef(void 0),f=v.useRef(!1),E=v.useCallback((u,x)=>{j.current+=x,$.current=u,!f.current&&(f.current=!0,queueMicrotask(()=>{f.current=!1;const b=j.current,T=$.current;j.current=0,$.current=void 0,!(b===0||T===void 0)&&(T==="list"?r.selectStep(Math.sign(b)):n.current?.scrollBy(Math.sign(b)))}))},[r]);return ae((u,x)=>{if(u==="q"||x.escape){S();return}if(F[u]){r.setFilter(F[u]);return}if(x.tab){r.setFocusedPanel(o.focusedPanel==="list"?"detail":"list");return}o.focusedPanel==="list"?x.upArrow||u==="k"?E("list",-1):(x.downArrow||u==="j")&&E("list",1):o.focusedPanel==="detail"&&(x.upArrow||u==="k"?E("detail",-1):(x.downArrow||u==="j")&&E("detail",1))}),i<D?t.jsx(a,{alignItems:"center",justifyContent:"center",children:t.jsxs(c,{color:"yellow",children:["Terminal too small. Resize to at least",D," ","rows."]})}):t.jsxs(a,{flexDirection:"column",height:i,width:l,children:[t.jsxs(a,{flexDirection:y?"row":"column",flexGrow:1,children:[t.jsx(a,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:t.jsx(ye,{counts:m,entries:d,filterType:o.filterType,focused:o.focusedPanel==="list",selectedIndex:o.selectedIndex,totalEntries:o.entries.length,viewportHeight:p})}),t.jsx(a,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:t.jsx(he,{checkMode:e,entry:g,focused:o.focusedPanel==="detail",scrollRef:n})})]}),t.jsx(a,{flexShrink:0,paddingX:1,children:t.jsx(c,{dimColor:!0,children:"↑/↓ or j/k:navigate | tab:switch panel | 1-4:filter | q:quit"})})]})},B=["types","node-addons","node","import","require","default"],ve=/^git\+https:\/\/github\.com\/([^/]+)\/([^/.]+(?:\.git)?)$/,Ee=/^git\+ssh:\/\/git@github\.com\/([^/]+)\/([^/.]+(?:\.git)?)$/,C=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),I=e=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(s=>I(s));const r={};for(const[s,l]of Object.entries(e))r[s]=I(l);return r},Pe=e=>{if(!C(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}},Oe=e=>e.endsWith(".git")?e.slice(0,-4):e,Ce=e=>{if(!C(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:s}=e;if(typeof s!="string")return{changed:!1,value:e};const l=ve.exec(s)??Ee.exec(s);if(!l)return{changed:!1,value:e};const i=l[1],o=Oe(l[2]??"");if(!i||!o)return{changed:!1,value:e};const n=new Set(["type","url"]);for(const d of Object.keys(e))if(!n.has(d))return{changed:!1,value:e};return{changed:!0,value:`${i}/${o}`}},Re=e=>{const r=Object.keys(e),s=[],l=[];for(const n of B)Object.hasOwn(e,n)&&s.push(n);for(const n of r)B.includes(n)||l.push(n);const i=[...s,...l];if(i.length===r.length&&i.every((n,d)=>n===r[d]))return{changed:!1,value:e};const o={};for(const n of i)o[n]=e[n];return{changed:!0,value:o}},W=e=>{if(!C(e))return{changed:!1,value:e};let r=!1;const s={};for(const[i,o]of Object.entries(e)){const n=W(o);s[i]=n.value,n.changed&&(r=!0)}const l=Re(s);return{changed:r||l.changed,value:l.value}},Ie=(e,r)=>{const s=I(e);let l=!1;if(r.formatBugs!==!1&&Object.hasOwn(s,"bugs")){const i=Pe(s.bugs);i.changed&&(s.bugs=i.value,l=!0)}if(r.formatRepository!==!1&&Object.hasOwn(s,"repository")){const i=Ce(s.repository);i.changed&&(s.repository=i.value,l=!0)}if(r.sortExports!==!1&&Object.hasOwn(s,"exports")&&C(s.exports)){const i=W(s.exports);i.changed&&(s.exports=i.value,l=!0)}return{changed:l,pkg:s}},Te=/at position (\d+)/,Me=/\(?line (\d+) column (\d+)\)?/,Ne=e=>{const r=new Set,s=[],l=o=>{const n=Y(o);!r.has(n)&&M(n)&&(r.add(n),s.push(n))};l(P(e,"package.json"));const i=te(e);if(i){const o=N(e,i);for(const n of o)l(P(e,n,"package.json"))}else{const o=P(e,"package.json");if(M(o)){const n=JSON.parse(L(o)),d=Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages;if(d){const g=N(e,d);for(const m of g)l(P(e,m,"package.json"))}}}return s},Ae=e=>/\n([ \t]+)/.exec(e)?.[1]??" ",De=e=>{if(!(e===void 0||e===""))return e==="tab"||e===String.raw`\t`?" ":/^\d+$/.test(e)?" ".repeat(Number.parseInt(e,10)):e},R=e=>e===void 0?[]:(Array.isArray(e)?e:[e]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0),Fe=e=>e.includes(`\r
2
+ `)?"crlf":"lf",Be=new Set(["auto","crlf","lf"]),Ge=e=>{if(e===void 0||e==="")return"auto";if(Be.has(e))return e;throw new Error(`--line-ending must be one of: auto, lf, crlf (got "${e}")`)},_e=(e,r,s)=>r.length===0?e:e.filter(l=>{const i=J(s,l),o=V(l);return!r.some(n=>{const d=n.includes("/")?i:o;return oe(n,d)})}),Je=(e,r)=>{if(r.length===0)return e;const s={},l=new Set;for(const i of r)Object.hasOwn(e,i)&&(s[i]=e[i],l.add(i));for(const i of Object.keys(e))l.has(i)||(s[i]=e[i]);return s},Le=(e,r,s)=>{if(s.length===0)return e;const l={...e};for(const i of s)Object.hasOwn(r,i)&&(l[i]=r[i]);return l},qe=(e,r)=>{let s=1,l=1;const i=Math.min(r,e.length);for(let o=0;o<i;o++)e.codePointAt(o)===10?(s++,l=1):l++;return{column:l,line:s}},G=(e,r,s=2)=>{const l=e.split(`
3
+ `);if(r<1||r>l.length)return[];const i=Math.max(0,r-1-s),o=Math.min(l.length,r+s),n=[];for(let d=i;d<o;d++)n.push({content:l[d]??"",isErrorLine:d+1===r,lineNumber:d+1});return n},_=(e,r)=>{if(!(e instanceof Error))return;const s=Te.exec(e.message);if(s){const{column:i,line:o}=qe(r,Number.parseInt(s[1]??"0",10));return{column:i,line:o,snippet:G(r,o)}}const l=Me.exec(e.message);if(l){const i=Number.parseInt(l[1]??"1",10);return{column:Number.parseInt(l[2]??"1",10),line:i,snippet:G(r,i)}}},He=(e,r)=>{const s=Object.keys(JSON.parse(e)),l=Object.keys(JSON.parse(r)),i=new Map(s.map((n,d)=>[n,d])),o=[];for(const[n,d]of l.entries()){const g=i.get(d);g!==void 0&&g!==n&&o.push({fromIndex:g,key:d,toIndex:n})}return o},Xe=(e,r,s)=>{const l=r.indent??s.indent??Ae(e),i=r.lineEnding==="auto"?s.lineEnding??Fe(e):r.lineEnding,o=q(e,{pretty:!1,sortScripts:r.sortScripts});let n=JSON.parse(o);if(r.unsorted.length>0){const y=JSON.parse(e);n=Le(n,y,r.unsorted)}n=Je(n,r.sortOrder);const d={formatBugs:r.formatBugs,formatRepository:r.formatRepository,sortExports:r.sortExports},g=Ie(n,d);let m=JSON.stringify(g.pkg,null,l);return r.finalNewline&&(m+=`
4
+ `),i==="crlf"&&(m=m.replaceAll(`
5
+ `,`\r
6
+ `)),m},We=(e,r)=>{const s=Ne(e),l=U(e),i=Z({cwd:e,extraPatterns:ee(l)}),o=s.filter(d=>!i.ignores(d)),n=_e(o,r,e);return{afterGitignore:o,allFiles:s,files:n}},ze=async(e,{checkMode:r,cwd:s,fs:l,normalized:i})=>{const o=J(s,e)||e;let n;try{n=L(e)}catch(h){return{diff:[],error:{message:O(h),step:"read"},filePath:e,relativePath:o,status:"error"}}let d;try{d=q(n,{pretty:!1,sortScripts:i.sortScripts})}catch(h){const w={message:O(h),step:"native-sort"},p=_(h,n);return p&&(w.context=p),{diff:[],error:w,filePath:e,relativePath:o,status:"error"}}const g=i.editorconfig?re(e):{};let m;try{m=Xe(n,i,g)}catch(h){const w={message:O(h),step:"json-parse"},p=_(h,n);return p&&(w.context=p),{diff:[],error:w,filePath:e,relativePath:o,status:"error"}}if(n===m)return{diff:[],filePath:e,relativePath:o,status:"unchanged"};let y;try{y=He(n,d)}catch{y=[]}if(r)return{diff:y,filePath:e,relativePath:o,status:"would-rewrite"};try{await l.writeFile(e,m,"utf8")}catch(h){return{diff:y,error:{message:O(h),step:"write"},filePath:e,relativePath:o,status:"error"}}return{diff:y,filePath:e,relativePath:o,status:"rewritten"}},Ve=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 s=r.isErrorLine?">":" ";k.info(` ${s} ${String(r.lineNumber).padStart(4)} | ${r.content}`)}}},ir=async({fs:e,options:r,visConfig:s,workspaceRoot:l})=>{const i=l??process.cwd(),o=s?.sortPackageJson,n=r.check||!1,d={editorconfig:r.editorconfig===!1?!1:o?.editorconfig??!0,finalNewline:r.finalNewline??o?.finalNewline??!0,formatBugs:r.formatBugs===!1?!1:o?.formatBugs??!0,formatRepository:r.formatRepository===!1?!1:o?.formatRepository??!0,ignore:[...R(r.ignore),...o?.ignore??[]],indent:De(r.indent??o?.indent),lineEnding:Ge(r.lineEnding??o?.lineEnding),sortExports:r.sortExports===!1?!1:o?.sortExports??!0,sortOrder:[...R(r.sortOrder),...o?.sortOrder??[]],sortScripts:r.sortScripts||o?.sortScripts||!1,unsorted:[...R(r.unsorted),...o?.unsorted??[]]},g=We(i,d.ignore),{afterGitignore:m,allFiles:y,files:h}=g;if(h.length===0){y.length===0?k.info("No package.json files found."):m.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 w=[];for(const f of h)w.push(await ze(f,{checkMode:n,cwd:i,fs:e,normalized:d}));let p=0,S=0,j=0;for(const f of w)f.status==="error"?j++:f.status==="rewritten"||f.status==="would-rewrite"?p++:S++;const $=p>0||j>0;if(process.stdout.isTTY&&!se&&$){const f=new fe(w);await K(Q.createElement($e,{checkMode:n,store:f}),{alternateScreen:!0,exitOnCtrlC:!1,interactive:!0,patchConsole:!0}).waitUntilExit()}else for(const f of w)switch(f.status){case"error":{Ve(f);break}case"rewritten":{k.success(`Sorted ${f.filePath}`);break}case"would-rewrite":{k.warn(`${f.filePath} is not sorted`);break}}if(n)p>0?(k.info(`${String(p)} file${p===1?"":"s"} not sorted, ${String(S)} already sorted`),process.exitCode=1):j===0&&k.info(`All ${String(S)} package.json file${S===1?" is":"s are"} sorted`);else{const f=[];p>0&&f.push(`sorted ${String(p)} file${p===1?"":"s"}`),S>0&&f.push(`${String(S)} already sorted`),j>0&&f.push(`${String(j)} error${j===1?"":"s"}`),f.length>0&&k.info(f.join(", "))}j>0&&(process.exitCode=1)};export{G as buildSnippet,He as computeKeyDiff,qe as computeLineColumn,ir as default,We as discoverPackageJsonFiles,_ as extractParseErrorContext,ze as processFile};
@@ -1,2 +1,9 @@
1
- import{createRequire as H}from"node:module";import{I as W}from"../packem_shared/index-B0EsgdzO.js";import{p as q}from"../packem_shared/prompt-DjXHVgYU.js";import{f as Y,m as X,a as J,T as U}from"../packem_shared/index-CE6MsgcV.js";import{f as D,A as Q,C as Z,r as ee,_ as te,i as A}from"../packem_shared/env-Ct3hMEYB.js";import{a as se}from"../packem_shared/readJsonSync-CvkZyKmL-ihoybKvs.js";import{g as re,r as oe}from"../packem_shared/packument-C-A3Uhhx.js";import{q as ne,j as ie,E as $,s as k,V as C,I as x}from"../packem_shared/index.server-J83sowC4.js";import{h as ae,W as ce}from"../packem_shared/pm-runner-CQcraCcu.js";import{r as le,a as fe}from"../packem_shared/command-runtime-3FTGuUsK.js";const L=H(import.meta.url),v=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,G=e=>{if(typeof v<"u"&&v.versions&&v.versions.node){const[t,s]=v.versions.node.split(".").map(Number);if(t>22||t===22&&s>=3||t===20&&s>=16)return v.getBuiltinModule(e)}return L(e)},{renameSync:F}=G("node:fs"),{stripVTControlCharacters:P}=G("node:util"),pe=(e={})=>{const t=e.isCi??W;return(e.isTty??!!(process.stdin.isTTY&&process.stdout.isTTY))&&!t},w=X(D(),"dlx-seen.json"),V=(e,t)=>`${e}@${t}`,ue=e=>{if(typeof e!="object"||e===null)return!1;const t=e;return Array.isArray(t.alertKeys)&&t.alertKeys.every(s=>typeof s=="string")&&typeof t.seenAt=="number"},B=()=>{try{if(Y(w)){const e=se(w);if(e&&typeof e=="object"&&e.packages&&typeof e.packages=="object"&&e.version===1){const t={};for(const[s,r]of Object.entries(e.packages))ue(r)&&(t[s]=r);return{packages:t,version:1}}}}catch{}return{packages:{},version:1}},ge=e=>{try{J(D());const t=`${w}.${String(process.pid)}.tmp`;U(t,JSON.stringify(e)),F(t,w)}catch{}},me=(e,t,s)=>e.packages[V(t,s)],de=(e,t)=>{if(!e)return!0;const s=new Set(Array.isArray(e.alertKeys)?e.alertKeys:[]);return t.some(r=>!s.has(r))},E=(e,t,s,r)=>{const o=B();o.packages[V(e,t)]={alertKeys:[...s].sort(),seenAt:r},ge(o)},he=/[\u0000-\u0008\u000B-\u001F\u007F]/g,z=e=>P(e).replaceAll(" "," ").replaceAll(he,""),_=["CHANGELOG.md","CHANGELOG","changelog.md","CHANGES.md","HISTORY.md"],ye=4e3,R=async(e,t,s)=>{if(t?.aborted)return;const r=new AbortController,o=setTimeout(()=>{r.abort()},ye),a=()=>{r.abort()};t?.addEventListener("abort",a,{once:!0});try{const i=await fetch(e,{headers:s,signal:r.signal});return i.ok?await i.text():void 0}catch{return}finally{clearTimeout(o),t?.removeEventListener("abort",a)}},$e=e=>{const t=typeof e=="string"?e:e?.url;if(!t)return;const s=/github\.com[/:]([^/]+)\/([^/#]+?)(?:\.git)?(?:[/#]|$)/i.exec(t)??/^github:([^/]+)\/([^/#]+)/i.exec(t);return s?{directory:typeof e=="object"?e?.directory:void 0,owner:s[1],repo:s[2].replace(/\.git$/,"")}:void 0},I=(e,t)=>{const s=e.split(/\r?\n/),r=/^(#{1,4})\s+(.*)$/,o=t.replaceAll(/[$()*+.?[\\\]^{|}]/g,String.raw`\$&`),a=new RegExp(String.raw`(?<![\w.])${o}(?![\w.])`);let i=-1,u=0;for(const[c,l]of s.entries()){const f=r.exec(l);if(f&&a.test(f[2])){i=c,u=f[1].length;break}}if(i===-1)return;const n=[];for(let c=i+1;c<s.length;c+=1){const l=r.exec(s[c]);if(l&&l[1].length<=u)break;n.push(s[c])}return n},O=(e,t=4)=>e.map(s=>s.trim()).filter(s=>s.length>0).map(s=>z(s.replace(/^#{1,6}\s+/,"").replace(/^[*-]\s+/,"- ")).trim()).filter(s=>s.length>0&&!/^\[.*\]:/.test(s)).slice(0,t),j=(e,t)=>{if(!e)return"";const s=Date.parse(e);if(Number.isNaN(s))return"";const r=Math.floor((t-s)/(1440*60*1e3));if(r<=0)return"today";if(r===1)return"1d ago";if(r<30)return`${String(r)}d ago`;const o=Math.floor(r/30);return o<12?`${String(o)}mo ago`:`${String(Math.floor(o/12))}y ago`},N=(e,t,s)=>{const r=e.time??{},o=j(r[t],s),a=[o?`${e.name}@${t} — published ${o}`:`${e.name}@${t}`],i=Date.parse(r[t]??""),u=Object.entries(r).filter(([n])=>n!=="created"&&n!=="modified"&&n!==t).sort((n,c)=>Date.parse(c[1])-Date.parse(n[1])).filter(([,n])=>Date.parse(n)<i).slice(0,3);for(const[n,c]of u)a.push(`- ${n} (${j(c,s)})`);return{lines:a,source:"npm-diff",version:t}},ve=async e=>{const{name:t,now:s,offline:r,packument:o,signal:a,version:i}=e;if(r)return o?N(o,i,s):void 0;for(const c of _){const l=`https://cdn.jsdelivr.net/npm/${t}@${i}/${c}`,f=await R(l,a);if(f){const d=I(f,i),p=O(d??f.split(/\r?\n/));if(p.length>0)return{lines:p,source:"package-file",url:l,version:i}}}const u=o?.versions[i],n=$e(u?.repository);if(n){const c=n.directory?`${n.directory.replaceAll(/^\/+|\/+$/g,"")}/`:"";for(const l of["HEAD","main","master"])for(const f of _){const d=`https://raw.githubusercontent.com/${n.owner}/${n.repo}/${l}/${c}${f}`,p=await R(d,a);if(p){const h=I(p,i),m=O(h??p.split(/\r?\n/));if(m.length>0){const g=`https://github.com/${n.owner}/${n.repo}/blob/${l}/${c}${f}`;return{lines:m,source:"repo-file",url:g,version:i}}}}}if(o)return N(o,i,s)},ke={dynamicRequire:"dynamic require",envVars:"env access",filesystemAccess:"filesystem",networkAccess:"network",shellAccess:"shell",telemetry:"telemetry",unsafe:"eval/unsafe",usesEval:"eval/unsafe"},be=["preinstall","install","postinstall"],we=(e,t)=>({fileCount:e?.dist?.fileCount,tarballBytes:t?.size,unpackedBytes:e?.dist?.unpackedSize}),Se=(e,t)=>{const s=be.filter(i=>!!e?.scripts?.[i]),r=e?.bin,o=typeof r=="string"?["(default)"]:Object.keys(r??{}).map(i=>z(i)),a=[...new Set(t.map(i=>ke[i.type]).filter(i=>i!==void 0))];return{bins:o,capabilities:a,lifecycleScripts:s}},Te=(e,t,s)=>{const r=e.get(`${t}@${s}`);if(r)return r;for(const o of e.values())if(o.name===t&&o.version===s)return o},Ce=async e=>{const{name:t,now:s,offline:r,signal:o,socketToken:a,spec:i,workspaceRoot:u}=e;let n;try{n=await re(t,{offline:r,signal:o,workspaceRoot:u})}catch{n=void 0}const c=n?oe(n,i):void 0;if(!c)return;const l=n?.versions[c],f=async()=>{if(!(r||!a))try{const y=await Z([{name:t,version:c}],{apiToken:a});return Te(y,t,c)}catch{return}},d=ve({name:t,now:s,offline:r,packument:n,signal:o,version:c}).catch(()=>{}),[p,h]=await Promise.all([f(),d]),m=p?.alerts??[],g=[...new Set(m.filter(y=>y.severity==="critical"||y.severity==="high").map(y=>y.key))].sort(),S=p?Math.round((p.score.overall??Q(p.score))*100):void 0;return{changelog:h,name:t,permissions:Se(l,m),security:{alerts:m,available:!!p,highSeverityKeys:g,score:S},size:we(l,p),version:c}},b=e=>ee(P(e)),Ae={critical:C,high:C,low:$,medium:k},K=e=>{if(!(e===void 0||e<0))return te(e,{decimals:1,space:!0})},xe=e=>{const{fileCount:t,tarballBytes:s,unpackedBytes:r}=e.size,o=K(r),a=K(s);if(o&&a){const i=t===void 0?"":`, ${String(t)} files`;return`${o} unpacked (${a} tarball${i})`}if(o)return`${o} unpacked`;if(a)return`${a} tarball`},Ee=e=>{const{alerts:t,available:s,score:r}=e.security;if(!s)return $("unavailable — set VIS_SOCKET_TOKEN for a Socket.dev score");const o=r===void 0?$:r>=70?x:r>=40?k:C,a=r===void 0?"n/a":`${String(r)}/100`,i=new Map;for(const l of t)i.set(l.severity,(i.get(l.severity)??0)+1);const u=[],n=["critical","high","medium","low"];for(const l of n){const f=i.get(l);f&&u.push(Ae[l](`${String(f)} ${l}`))}const c=u.length>0?` ${k("!")} ${u.join(", ")}`:` ${x("no alerts")}`;return`${o(a)} ${$("(Socket.dev)")}${c}`},_e=e=>{const{bins:t,capabilities:s,lifecycleScripts:r}=e.permissions,o=[];for(const a of r)o.push(k(`${a} script`));for(const a of s)o.push(k(a));return t.length>0&&o.push($(`bins: ${t.join(", ")}`)),o.length>0?o.join($(" · ")):void 0},Re=e=>{const t=[],s=xe(e);s&&t.push({label:"size",values:[s]}),t.push({label:"score",values:[Ee(e)]});const r=_e(e);if(r&&t.push({label:"perms",values:[r]}),e.changelog){const o=e.changelog.source==="npm-diff"?"registry":e.changelog.source==="repo-file"?"repo CHANGELOG":"CHANGELOG";t.push({label:"latest",values:[...e.changelog.lines,$(`source: ${o}`)]})}return t},M=6,Ie=e=>{const t=Re(e),s=` first run: ${e.name}@${e.version} `,r=[];for(const n of t)n.values.forEach((c,l)=>{const f=l===0?ne(n.label.padEnd(M)):" ".repeat(M);r.push(`${f} ${c}`)});const o=Math.max(b(s),...r.map(n=>b(n))),a=n=>`${n}${" ".repeat(Math.max(0,o-b(n)))}`,i=`┌─${ie(s)}${"─".repeat(Math.max(0,o-b(s)))}─┐`,u=`└─${"─".repeat(o)}─┘`;return[i,...r.map(n=>`│ ${a(n)} │`),u]},Oe=e=>{if(e.startsWith("@")){const s=e.indexOf("@",1);return s===-1?{name:e}:{name:e.slice(0,s),spec:e.slice(s+1)}}const t=e.indexOf("@");return t<=0?{name:e}:{name:e.slice(0,t),spec:e.slice(t+1)}},je=e=>e===""||e.startsWith(".")||e.startsWith("/")||e.startsWith("~")?!1:!(e.startsWith("@")?e.slice(1):e).includes(":"),Ne=6e3,Ke=e=>{process.stdout.write(e)},Me=async e=>{const{forceInfo:t=!1,noInfo:s=!1,offline:r=!1,pkg:o,socketToken:a,workspaceRoot:i,yes:u=!1}=e;if(s||!je(o))return{proceed:!0};const n=e.now??Date.now(),c=u||!pe({isCi:e.isCi,isTty:e.isTty}),l=e.output??Ke;if(c&&!t)return{proceed:!0};const{name:f,spec:d}=Oe(o),p=new AbortController;let h;const m=new Promise(T=>{h=setTimeout(()=>{p.abort(),T(void 0)},Ne)}),g=await Promise.race([Ce({name:f,now:n,offline:r,signal:p.signal,socketToken:a,spec:d,workspaceRoot:i}).catch(()=>{}),m]);if(h&&clearTimeout(h),!g)return{proceed:!0};const S=me(B(),g.name,g.version);if(!t&&!de(S,g.security.highSeverityKeys))return{proceed:!0};for(const T of Ie(g))l(`${T}
2
- `);if(c)return E(g.name,g.version,g.security.highSeverityKeys,n),{proceed:!0};const y=await q("? Ok to proceed? (y/N) ",e.readline);return y&&E(g.name,g.version,g.security.highSeverityKeys,n),{proceed:y}},Fe=async({argument:e,logger:t,options:s,visConfig:r,workspaceRoot:o})=>{const a=e;if(!a||a.length===0)throw new Error("No package specified. Usage: vis dlx <package[@version]> [args...]");const[i,...u]=a,n=o??process.cwd(),c=s.package?Array.isArray(s.package)?s.package:[s.package]:[],l=s.shellMode?c:[i,...c];for(const h of l){const m=s.info||!1,g=m?!1:s.noInfo||A(process.env.VIS_DLX_NO_INFO);if(!(await Me({forceInfo:m,noInfo:g,offline:s.offline||!1,pkg:h,socketToken:r?.security?.socket?.apiToken??process.env.VIS_SOCKET_TOKEN,workspaceRoot:n,yes:s.yes||A(process.env.VIS_DLX_YES)})).proceed){t.info("Aborted."),process.exitCode=1;return}}const f=le({logger:t,options:s,visConfig:r},n),d=ae(n,{backend:fe(f),configBackend:r?.install?.backend,configCorepack:r?.install?.corepack}),p=ce(d,{additionalPackages:c,args:u,package:i,shellMode:s.shellMode||!1,silent:s.silent||!1},n,t,{offline:s.offline||!1});p!==0&&(process.exitCode=p)};export{Fe as default};
1
+ import{createRequire as q}from"node:module";import{DEFAULT_CHANGES_DIR as Z}from"./DEFAULT_CLEAN_KEEP.js";import{b as J,f as Q}from"./orchestrator.js";import{createShellRunner as X}from"./shell-runner.js";import{r as ee}from"../packem_shared/slug-DoueYuLo.js";import{maxBump as te}from"../release/types.js";const V=q(import.meta.url),P=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,U=s=>{if(typeof P<"u"&&P.versions&&P.versions.node){const[e,t]=P.versions.node.split(".").map(Number);if(e>22||e===22&&t>=3||e===20&&t>=16)return P.getBuiltinModule(s)}return V(s)},{join:M,relative:Y}=U("node:path"),D=/(?!.*)/;function re(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function S(s){return s.map(e=>typeof e=="string"?re(e.trim()):e.source).filter(Boolean).join("|")}function ne(s,e){if(!s)return D;const t=S(s);return e?e(t):new RegExp(`^[\\s|*]*(${t})[:\\s]+(.*)`,"i")}function se(s,e){if(!s)return D;const t=e?"g":"gi";return new RegExp(`(?:.*?)??\\s*([\\w-\\.\\/]*?)??(${S(s)})([\\w-]+)(?=\\s|$|[,;)\\]])`,t)}function ie(s){if(!s)return/()(.+)/gi;const e=S(s);return new RegExp(`(${e})(?:\\s+(.*?))(?=(?:${e})|$)`,"gi")}function oe(s={}){const e=ne(s.noteKeywords,s.notesPattern),t=se(s.issuePrefixes,s.issuePrefixesCaseSensitive),r=ie(s.referenceActions);return{notes:e,referenceParts:t,references:r,mentions:/@([\w-]+)/g,url:/\b(?:https?):\/\/(?:www\.)?([-a-zA-Z0-9@:%_+.~#?&//=])+\b/}}const ce="------------------------ >8 ------------------------";function j(s){const e=s.match(/[^\r\n]/);if(typeof e?.index!="number")return"";const t=e.index;let r=s.length-1;for(;s[r]==="\r"||s[r]===`
2
+ `;)r--;return s.substring(t,r+1)}function A(s,e){return s?`${s}
3
+ ${e||""}`:e||""}function ae(s){return s?e=>!e.startsWith(s):()=>!0}function le(s,e){const t=s.indexOf(`${e} ${ce}`);return t===-1?s:s.slice(0,t)}function I(s){return!s.match(/^\s*gpg:/)}function _(s,e,t){const{groups:r}=e;for(let n=0,i=t.length,c;n<i;n++)c=t[n],s[c]=(r?r[c]:e[n+1])||null;return s}const fe={noteKeywords:["BREAKING CHANGE","BREAKING-CHANGE"],issuePrefixes:["#"],referenceActions:["close","closes","closed","fix","fixes","fixed","resolve","resolves","resolved"],headerPattern:/^(\w*)(?:\(([\w$@.\-*/ ]*)\))?: (.*)$/,headerCorrespondence:["type","scope","subject"],revertPattern:/^Revert\s"([\s\S]*)"\s*This reverts commit (\w*)\.?/,revertCorrespondence:["header","hash"],fieldPattern:/^-(.*?)-$/};function T(s={}){return{merge:null,revert:null,header:null,body:null,footer:null,notes:[],mentions:[],references:[],...s}}class he{options;regexes;lines=[];lineIndex=0;commit=T();constructor(e={}){this.options={...fe,...e},this.regexes=oe(this.options)}currentLine(){return this.lines[this.lineIndex]}nextLine(){return this.lines[this.lineIndex++]}isLineAvailable(){return this.lineIndex<this.lines.length}parseReference(e,t){const{regexes:r}=this;if(r.url.test(e))return null;const n=r.referenceParts.exec(e);if(!n)return null;let[i,c=null,u,p]=n,x=null;if(c){const b=c.indexOf("/");b!==-1&&(x=c.slice(0,b),c=c.slice(b+1))}return{raw:i,action:t,owner:x,repository:c,prefix:u,issue:p}}parseReferences(e){const{regexes:t}=this,r=e.match(t.references)?t.references:/()(.+)/gi,n=[];let i,c,u,p;for(;i=r.exec(e),!!i;)for(c=i[1]||null,u=i[2]||"";p=this.parseReference(u,c),!!p;)n.push(p);return n}skipEmptyLines(){let e=this.currentLine();for(;e!==void 0&&!e.trim();)this.nextLine(),e=this.currentLine()}parseMerge(){const{commit:e,options:t}=this,r=t.mergeCorrespondence||[],n=this.currentLine(),i=n&&t.mergePattern?n.match(t.mergePattern):null;return i?(this.nextLine(),e.merge=i[0]||null,_(e,i,r),!0):!1}parseHeader(e){e&&this.skipEmptyLines();const{commit:t,options:r}=this,n=r.headerCorrespondence||[],i=t.header??this.nextLine();let c=null;i&&(r.breakingHeaderPattern&&(c=i.match(r.breakingHeaderPattern)),!c&&r.headerPattern&&(c=i.match(r.headerPattern))),i&&(t.header=i),c&&_(t,c,n)}parseMeta(){const{options:e,commit:t}=this;if(!e.fieldPattern||!this.isLineAvailable())return!1;let r,n=null,i=!1;for(;this.isLineAvailable();){if(r=this.currentLine().match(e.fieldPattern),r){n=r[1]||null,this.nextLine();continue}if(n)i=!0,t[n]=A(t[n],this.currentLine()),this.nextLine();else break}return i}parseNotes(){const{regexes:e,commit:t}=this;if(!this.isLineAvailable())return!1;const r=this.currentLine().match(e.notes);let n=[];if(r){const i={title:r[1],text:r[2]};for(t.notes.push(i),t.footer=A(t.footer,this.currentLine()),this.nextLine();this.isLineAvailable();){if(this.parseMeta()||this.parseNotes())return!0;if(n=this.parseReferences(this.currentLine()),n.length?t.references.push(...n):i.text=A(i.text,this.currentLine()),t.footer=A(t.footer,this.currentLine()),this.nextLine(),n.length)break}return!0}return!1}parseBodyAndFooter(e){const{commit:t}=this;if(!this.isLineAvailable())return e;const r=this.parseReferences(this.currentLine()),n=!r.length&&e;return n?t.body=A(t.body,this.currentLine()):(t.references.push(...r),t.footer=A(t.footer,this.currentLine())),this.nextLine(),n}parseBreakingHeader(){const{commit:e,options:t}=this;if(!t.breakingHeaderPattern||e.notes.length||!e.header)return;const r=e.header.match(t.breakingHeaderPattern);r&&e.notes.push({title:"BREAKING CHANGE",text:r[3]})}parseMentions(e){const{commit:t,regexes:r}=this;let n;for(;n=r.mentions.exec(e),!!n;)t.mentions.push(n[1])}parseRevert(e){const{commit:t,options:r}=this,n=r.revertCorrespondence||[],i=r.revertPattern?e.match(r.revertPattern):null;i&&(t.revert=_({},i,n))}cleanupCommit(){const{commit:e}=this;e.body&&(e.body=j(e.body)),e.footer&&(e.footer=j(e.footer)),e.notes.forEach(r=>{r.text=j(r.text)});const t=new Set;e.references=e.references.filter(r=>{const n=`${r.action} ${r.raw}`.toLocaleLowerCase(),i=!t.has(n);return i&&t.add(n),i})}parse(e){if(!e.trim())throw new TypeError("Expected a raw commit");const{commentChar:t}=this.options,r=ae(t),n=j(e).split(/\r?\n/),i=t?le(n,t).filter(x=>r(x)&&I(x)):n.filter(x=>I(x)),c=T();this.lines=i,this.lineIndex=0,this.commit=c;const u=this.parseMerge();this.parseHeader(u),c.header&&(c.references=this.parseReferences(c.header));let p=!0;for(;this.isLineAvailable();)this.parseMeta(),this.parseNotes()&&(p=!1),this.parseBodyAndFooter(p)||(p=!1);return this.parseBreakingHeader(),this.parseMentions(e),this.parseRevert(e),this.cleanupCommit(),c}}const N={build:"patch",chore:"patch",ci:"patch",docs:"patch",feat:"minor",fix:"patch",perf:"patch",refactor:"patch",style:"patch",test:"patch"},ue=new he,pe=/^Revert\s+"(.+)"\s*$/,de=/This reverts commit\s+([0-9a-f]{7,40})/i,me=/^(?:[\p{Emoji_Presentation}\p{Extended_Pictographic}]|:\w+:)\s+/u,ge=(s,e)=>{const t=s.replace(me,""),r=ue.parse(`${t}
4
+
5
+ ${e}`);return{breaking:r.notes.some(n=>/BREAKING/i.test(n.title)),scope:r.scope??void 0,type:r.type??void 0}},xe=(s,e,t)=>{let r,n=!1;if(t.type==="revert"){n=!0;const u=s.indexOf(":");u!==-1&&(r=s.slice(u+1).trim())}else{const u=pe.exec(s.trim());u&&(n=!0,r=u[1]?.trim())}let i;const c=de.exec(e);return c&&(i=c[1]?.toLowerCase()),{isRevert:n,targetSha:i,targetSubject:r}},ve=(s,e=new Set,t)=>{const r=s.map(o=>{const l=ge(o.subject,o.body),{isRevert:a,targetSha:f,targetSubject:d}=xe(o.subject,o.body,l);return{...o,cancelled:!1,parsed:l,revert:a,revertSubject:d,revertTargetSha:f}}),n=r.toReversed(),i=12,c=new Map;for(const o of n)if(c.set(o.hash,o),o.hash.length>=7){const l=Math.min(o.hash.length-1,i);for(let a=7;a<=l;a+=1){const f=o.hash.slice(0,a);if(c.has(f)){const d=c.get(f);d!==null&&d!==o&&c.set(f,null)}else c.set(f,o)}}const u=(o,l)=>{if(o.revertTargetSha){const a=o.revertTargetSha.toLowerCase();let f=c.get(a)??void 0;if(f||(f=n.find(d=>d.hash.startsWith(a))),f&&f!==o)return f}if(o.revertSubject)for(let a=l.length-1;a>=0;a-=1){const f=l[a];if(f.subject===o.revertSubject)return f}},p=64,x=o=>{let l=o;for(let a=0;a<p;a+=1){if(!l.revert)return l;const f=l.cancelledBy;let d;if(f&&(d=c.get(f)??void 0,d||(d=c.get(f.slice(0,7))??void 0)),!d||d===l)return l;l=d}},b=[],w=[];for(const o of n){if(o.revert){const l=u(o,w);if(l){if(e.has(l.hash)){w.push(o);continue}const a=x(l);if(a===void 0){b.push(`Revert chain at ${o.hash} exceeded depth limit (${p}) — skipping cancellation`),w.push(o);continue}if(e.has(a.hash)){w.push(o);continue}a.cancelled=!a.cancelled,a.cancelledBy=a.cancelled?o.hash:void 0,o.cancelled=!0,o.cancelledBy=l.hash}}w.push(o)}const L=r.filter(o=>!o.cancelled&&!o.revert&&!o.subject?.startsWith("Merge ")),C=L.filter(o=>!o.parsed.type);if(L.length>0&&C.length/L.length>.5){const o=t??"<from>..HEAD";b.push(`${C.length}/${L.length} commits in ${o} have no conventional-commits prefix. Consider enabling commit-message linting.`)}return{commits:r,warnings:b}},Ae=async({fs:s,logger:e,options:t,workspaceRoot:r})=>{const n=r??process.cwd(),i=await J({cwd:n,skipRegistryLookup:!0}),{printConfigIfRequested:c}=await import("./print-config.js");if(c(t,i,e))return;const u=X();let p=t.from;if(!p){const h=i.config.baseBranch??"main",m=await u.run("git",["merge-base",`origin/${h}`,"HEAD"],{cwd:n,silent:!0});if(m.exitCode===0&&m.stdout.trim())p=m.stdout.trim();else{const g=await u.run("git",["merge-base",h,"HEAD"],{cwd:n,silent:!0});p=g.exitCode===0?g.stdout.trim():"HEAD~10"}}const x=new Map;for(const h of i.packages){const m=(h.dir.startsWith(n)?h.dir.slice(n.length):h.dir).replaceAll("\\","/").replace(/^\/+/,"");x.set(m,h.name)}const b=h=>{for(const[m,g]of x)if(h.startsWith(`${m}/`)||h===`${m}/package.json`)return g},w=Math.random().toString(16).slice(2,10),L=`@@VIS_RELEASE_COMMIT_${w}@@`,C=`@@VIS_RELEASE_FILES_${w}@@`,o=await u.run("git",["log",`${p}..HEAD`,`--pretty=format:${L}%n%H%n%s%n%b%n${C}`,"--name-only"],{cwd:n,silent:!0});if(o.exitCode!==0){e.error(`git log failed: ${o.stderr}`),process.exitCode=1;return}const l=new Map,a=[],f=[],d=o.stdout.split(L).map(h=>h.trim()).filter(Boolean);for(const h of d){const[m,g=""]=h.split(C).toReversed(),E=g.split(`
6
+ `),$=E[0]?.trim()??"",y=E[1]?.trim()??"",v=E.slice(2).join(`
7
+ `).trim(),R=(m??"").split(`
8
+ `).map(z=>z.trim()).filter(Boolean);$&&f.push({body:v,files:R,hash:$,subject:y})}const{commits:F,warnings:G}=ve(f,void 0,`${p}..HEAD`);for(const h of G)e.warn(h);for(const{cancelled:h,files:m,parsed:g,subject:E}of F){if(h)continue;let $="patch";g.breaking?$="major":g.type&&N[g.type]&&($=N[g.type]??"patch");const y=new Set;if(g.scope)for(const v of i.packages)(v.name===g.scope||v.name.endsWith(`/${g.scope}`))&&y.add(v.name);if(y.size===0)for(const v of m){const R=b(v);R&&y.add(R)}for(const v of y){const R=l.get(v);l.set(v,R?te(R,$):$)}y.size>0&&a.push(`- ${E}`)}if(l.size===0){e.info("No commits affected workspace packages — nothing to generate.");return}const O={bumps:Object.fromEntries(l)},K=a.length>0?a.join(`
9
+ `):"Auto-generated change file.",k=Q(O,K);if(t.dryRun){e.info("[dry-run] would write:"),e.info(k);return}const B=i.config.changesDir??Z,W=(t.name??ee()).replaceAll(/[^a-z0-9-]/gi,"-"),H=M(n,B,`${W}.md`);await s.mkdir(M(n,B),{recursive:!0}),await s.writeFile(H,k),e.info(`Created ${Y(n,H)}`);for(const[h,m]of l)e.info(` ${h}: ${m}`)};export{Ae as default};
@@ -1,24 +1,2 @@
1
- import{createRequire as ce}from"node:module";import{m as O,v as D,f as z,T as A,B as ae}from"../packem_shared/index-CE6MsgcV.js";import{v as le,m as t,n as m,i as a,r as _,$ as de,d as pe,e as fe,W as J}from"./catalog.js";import"../packem_shared/env-Ct3hMEYB.js";import{I as me}from"../packem_shared/index-B0EsgdzO.js";import he from"module-replacements/manifests/micro-utilities.json"with{type:"json"};import ue from"module-replacements/manifests/native.json"with{type:"json"};import ge from"module-replacements/manifests/preferred.json"with{type:"json"};import{s as Q}from"../packem_shared/index-Cg0IHaFI.js";import{T as xe,_ as ye,U as je,Q as ke,y as ve,W as we,p as y}from"./cli-main.js";import"../packem_shared/public-api-WqUCiyIe.js";import{u as be}from"./ts-loader.js";import{A as $e,y as Ce}from"../packem_shared/pm-runner-CQcraCcu.js";import{a as Z}from"../packem_shared/readJsonSync-CvkZyKmL-ihoybKvs.js";import{s as Se}from"../packem_shared/glob-fqg4KepW-1S3z30c8.js";import __cjs_mod__ from "node:module"; // -- packem CommonJS require shim --
2
- const require = __cjs_mod__.createRequire(import.meta.url);
3
- const or=ce(import.meta.url),nr=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process;const Oe=["dependencies","devDependencies","peerDependencies","peerDependenciesMeta","optionalDependencies","bundleDependencies"],Ne=["overrides","pnpm","resolutions"],Ee=["engines","files"],Te=r=>{const e=Q.coerce(r)?.major;return e!==void 0&&e>=10},Pe=r=>{const e=O(r,"pnpm-workspace.yaml");if(!z(e))return{overrides:{},source:"pnpm-workspace.yaml"};try{return{overrides:be(e)?.overrides??{},source:"pnpm-workspace.yaml"}}catch{return{overrides:{},source:"pnpm-workspace.yaml"}}},_e=(r,e)=>{let o={};return e==="deno"?{overrides:{},source:"package.json"}:(e==="pnpm"?o=r.pnpm?.overrides??{}:e==="yarn"||e==="bun"?o=r.resolutions??{}:o=r.overrides??{},{overrides:o,source:"package.json"})},Ae=(r,e,o)=>o.name==="pnpm"&&Te(o.version)?Pe(r):_e(e,o.name),H=(r,e)=>{const o=e;for(const c of Ne){const i=r.indexOf(c);if(i!==-1&&c!==o)return o==="overrides"?i:i+1}let n=-1;for(const c of Oe){const i=r.indexOf(c);i>n&&(n=i)}if(n!==-1)return n+1;for(const c of Ee){const i=r.indexOf(c);if(i!==-1)return i}return r.length},De=(r,e)=>{const o=O(r,"pnpm-workspace.yaml");if(!z(o))throw new Error(`pnpm-workspace.yaml not found at ${o}. Cannot write overrides for pnpm v10+.`);let n=D(o);const c=`overrides:
4
- ${Object.entries(e).map(([i,l])=>` '${i}': '${l}'`).join(`
5
- `)}
6
- `;n=/^overrides:\s*$/m.test(n)||/^overrides:\s*\n/m.test(n)?n.replace(/^overrides:\s*\n(?:(?:[ \t].*)?\n)*/m,c):`${n.trimEnd()}
7
-
8
- ${c}`,A(o,n)},Re=(r,e,o,n,c)=>{const i=D(r),l=le(r,i,{useEditorconfig:c});if(n==="pnpm"){const h=e.pnpm??{};if(h.overrides=o,e.pnpm)e.pnpm=h,A(r,`${JSON.stringify(e,null,l)}
9
- `);else{const k=Object.keys(e),s=H(k,"pnpm"),d=Object.entries(e);d.splice(s,0,["pnpm",h]),A(r,`${JSON.stringify(Object.fromEntries(d),null,l)}
10
- `)}}else{const h=n==="yarn"||n==="bun"?"resolutions":"overrides";if(e[h])e[h]=o,A(r,`${JSON.stringify(e,null,l)}
11
- `);else{const k=Object.keys(e),s=H(k,h),d=Object.entries(e);d.splice(s,0,[h,o]),A(r,`${JSON.stringify(Object.fromEntries(d),null,l)}
12
- `)}}},Ie=(r,e,o,n,c)=>{if(n.name==="deno")return{added:[],updated:[]};const i=D(e),l=JSON.parse(i),{overrides:h,source:k}=Ae(r,l,n),s=[],d=[],u=new Set;if(n.name==="npm")for(const f of["dependencies","devDependencies"]){const x=l[f];if(x)for(const b of Object.keys(x))u.add(b)}for(const f of o){const x=h[f.original];if(typeof x=="object")continue;let b=f.spec;n.name==="npm"&&u.has(f.original)&&(b=`$${f.original}`),x!==b&&(x?d.push(f.original):s.push(f.original),h[f.original]=b)}if(s.length===0&&d.length===0)return{added:s,updated:d};const j=Object.fromEntries(Object.entries(h).sort(([f],[x])=>f.localeCompare(x)));return k==="pnpm-workspace.yaml"?De(r,j):Re(e,l,j,n.name,c),{added:s,updated:d}},Fe=(r,e)=>{const o={bun:["bun.lock"],deno:["deno.lock"],npm:["npm-shrinkwrap.json","package-lock.json"],pnpm:["pnpm-lock.yaml"],yarn:["yarn.lock"]};for(const n of o[e]??[]){const c=O(r,n);try{return D(c)}catch{continue}}return""},Me=(r,e,o)=>{if(!r)return!1;const n=e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);switch(o){case"bun":return r.includes(`"${e}":`)||new RegExp(String.raw`(^|\s|[",])${n}@`,"m").test(r);case"deno":return r.includes(`"${e}"`)||r.includes(`"npm:${e}@`)||r.includes(`"jsr:${e}@`);case"npm":return r.includes(`"${e}":`)||r.includes(`"node_modules/${e}":`);case"pnpm":return new RegExp(String.raw`(^|\s|['"/])${n}(@|['"]?:)`,"m").test(r);case"yarn":return new RegExp(String.raw`(^|\s|[",])${n}@`,"m").test(r);default:return!1}};var q={exports:{}},U,X;function K(){if(X)return U;X=1;var r=Object.defineProperty,e=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,c=(s,d)=>{for(var u in d)r(s,u,{get:d[u],enumerable:!0})},i=(s,d,u,j)=>{if(d&&typeof d=="object"||typeof d=="function")for(let f of o(d))!n.call(s,f)&&f!==u&&r(s,f,{get:()=>d[f],enumerable:!(j=e(d,f))||j.enumerable});return s},l=s=>i(r({},"__esModule",{value:!0}),s),h={};c(h,{PURL_Type:()=>k}),U=l(h);var k=(s=>(s.APK="apk",s.BITBUCKET="bitbucket",s.COCOAPODS="cocoapods",s.CARGO="cargo",s.CHROME="chrome",s.COMPOSER="composer",s.CONAN="conan",s.CONDA="conda",s.CRAN="cran",s.DEB="deb",s.DOCKER="docker",s.GEM="gem",s.GENERIC="generic",s.GITHUB="github",s.GOLANG="golang",s.HACKAGE="hackage",s.HEX="hex",s.HUGGINGFACE="huggingface",s.MAVEN="maven",s.MLFLOW="mlflow",s.NPM="npm",s.NUGET="nuget",s.OCI="oci",s.PUB="pub",s.PYPI="pypi",s.QPKG="qpkg",s.RPM="rpm",s.SWID="swid",s.SWIFT="swift",s.VCS="vcs",s))(k||{});return U}var V;function Ge(){return V||(V=1,(function(r){var e=Object.defineProperty,o=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,c=Object.prototype.hasOwnProperty,i=(d,u)=>{for(var j in u)e(d,j,{get:u[j],enumerable:!0})},l=(d,u,j,f)=>{if(u&&typeof u=="object"||typeof u=="function")for(let x of n(u))!c.call(d,x)&&x!==j&&e(d,x,{get:()=>u[x],enumerable:!(f=o(u,x))||f.enumerable});return d},h=(d,u,j)=>(l(d,u,"default"),j&&l(j,u,"default")),k={};i(k,{getManifestData:()=>s}),h(k,K(),r.exports);function s(d,u){try{const j=require("../manifest.json");if(!d)return j;const f=j[d];if(!f)return;if(!u)return f;const x=f.find(([b,g])=>g.package===u);return x?x[1]:void 0}catch{return}}r.exports={getManifestData:s,...K()}})(q)),q.exports}var Le=Ge();const qe=(r,e,o)=>{let n=r;if(e!=="all"&&(n=n.filter(c=>c.category===e)),o){const c=o.toLowerCase();n=n.filter(i=>i.packageName.toLowerCase().includes(c))}return n};class Ue{#e;#t=new Set;constructor(e){this.#e={applyProgress:null,checkedEntries:new Set,entries:e,error:null,filterActive:!1,filterText:"",filterType:"all",focusedPanel:"list",phase:"browsing",selectedIndex:0}}getSnapshot=()=>this.#e;subscribe=e=>(this.#t.add(e),()=>{this.#t.delete(e)});getFilteredEntries=()=>qe(this.#e.entries,this.#e.filterType,this.#e.filterText);#r(){this.#e={...this.#e};for(const e of this.#t)e()}select(e){const o=this.getFilteredEntries();this.#e.selectedIndex=o.length===0?-1:Math.max(0,Math.min(e,o.length-1)),this.#r()}toggleCheck(e){const o=new Set(this.#e.checkedEntries);o.has(e)?o.delete(e):o.add(e),this.#e.checkedEntries=o,this.#r()}toggleAll(){const e=this.getFilteredEntries(),o=new Set(this.#e.checkedEntries);if(e.every(n=>o.has(n.packageName)))for(const n of e)o.delete(n.packageName);else for(const n of e)o.add(n.packageName);this.#e.checkedEntries=o,this.#r()}setFilter(e){this.#e.filterType=e,this.#e.selectedIndex=0,this.#r()}setFilterText(e){this.#e.filterText=e,this.#e.selectedIndex=0,this.#r()}setFilterActive(e){this.#e.filterActive=e,this.#r()}setFocusedPanel(e){this.#e.focusedPanel=e,this.#r()}setPhase(e){this.#e.phase=e,this.#r()}setProgress(e,o){this.#e.applyProgress={current:e,total:o},this.#r()}setError(e){this.#e.error=e,this.#e.phase="error",this.#r()}getCheckedEntries(){return this.#e.entries.filter(e=>this.#e.checkedEntries.has(e.packageName))}}const ee={"micro-utility":"gray",native:"green",preferred:"yellow",socket:"cyan"},Be={"micro-utility":"MICRO",native:"NATIVE",preferred:"PREF",socket:"SOCKET"},ze={"micro-utility":"Trivial utility package that can be replaced with inline code.",native:"Polyfill for a native JS/Node.js API. Use the built-in instead.",preferred:"A lighter or faster alternative package exists.",socket:"Security-hardened replacement from Socket.dev's @socketregistry."},Je=({entry:r,focused:e,scrollRef:o})=>{const n=e?"white":"gray";if(!r)return t.jsx(m,{alignItems:"center",borderColor:"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,justifyContent:"center",children:t.jsx(a,{dimColor:!0,children:"No entry selected"})});const c=ee[r.category]??"gray";return t.jsxs(m,{borderColor:n,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[t.jsx(m,{flexShrink:0,paddingTop:1,paddingX:2,children:t.jsx(a,{bold:!0,color:"white",children:r.packageName})}),t.jsxs(xe,{flexGrow:1,flexShrink:1,paddingX:2,ref:o,scrollbar:!0,scrollbarColor:"gray",children:[t.jsx(a,{}),t.jsxs(m,{children:[t.jsx(m,{width:14,children:t.jsx(a,{dimColor:!0,children:"Category:"})}),t.jsx(a,{bold:!0,color:c,children:r.category})]}),t.jsxs(m,{children:[t.jsx(m,{width:14,children:t.jsx(a,{dimColor:!0,children:"Replace with:"})}),t.jsx(a,{children:r.replacement})]}),r.overrideSpec&&t.jsxs(m,{children:[t.jsx(m,{width:14,children:t.jsx(a,{dimColor:!0,children:"Override:"})}),t.jsx(a,{color:"cyan",children:r.overrideSpec})]}),t.jsxs(m,{children:[t.jsx(m,{width:14,children:t.jsx(a,{dimColor:!0,children:"Codemod:"})}),t.jsx(a,{color:r.hasCodemod?"green":"gray",children:r.hasCodemod?"available ⚙":"not available"})]}),t.jsxs(m,{flexDirection:"column",marginTop:1,children:[t.jsx(a,{dimColor:!0,children:"── "}),t.jsx(a,{bold:!0,color:"white",children:"DESCRIPTION"}),t.jsx(m,{marginTop:1,paddingLeft:2,children:t.jsx(a,{children:ze[r.category]??""})})]}),r.category==="native"&&t.jsxs(m,{flexDirection:"column",marginTop:1,children:[t.jsx(a,{dimColor:!0,children:"── "}),t.jsx(a,{bold:!0,color:"green",children:"ACTION"}),t.jsx(m,{flexDirection:"column",marginTop:1,paddingLeft:2,children:r.hasCodemod?t.jsxs(t.Fragment,{children:[t.jsxs(a,{color:"green",children:["✓"," ","Codemod will rewrite imports to use native API."]}),t.jsx(a,{dimColor:!0,children:" The package can then be removed from dependencies."})]}):t.jsxs(t.Fragment,{children:[t.jsxs(a,{color:"yellow",children:["ℹ"," ","No automated codemod available."]}),t.jsx(a,{dimColor:!0,children:" Manual migration required — replace usage with native equivalent."})]})})]}),r.category==="socket"&&t.jsxs(m,{flexDirection:"column",marginTop:1,children:[t.jsx(a,{dimColor:!0,children:"── "}),t.jsx(a,{bold:!0,color:"cyan",children:"ACTION"}),t.jsxs(m,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[t.jsxs(a,{color:"cyan",children:["✓"," ","Override will redirect resolution to the hardened package."]}),t.jsx(a,{dimColor:!0,children:" No source code changes needed — drop-in replacement."})]})]}),(r.category==="preferred"||r.category==="micro-utility")&&t.jsxs(m,{flexDirection:"column",marginTop:1,children:[t.jsx(a,{dimColor:!0,children:"── "}),t.jsx(a,{bold:!0,color:"yellow",children:"ACTION"}),t.jsx(m,{flexDirection:"column",marginTop:1,paddingLeft:2,children:r.hasCodemod?t.jsxs(t.Fragment,{children:[t.jsxs(a,{color:"green",children:["✓"," ","Codemod will rewrite imports to the recommended alternative."]}),t.jsx(a,{dimColor:!0,children:" The original package can then be removed from dependencies."})]}):t.jsxs(t.Fragment,{children:[t.jsxs(a,{color:"yellow",children:["ℹ"," ","Manual migration required."]}),r.docUrl?t.jsx(a,{dimColor:!0,children:" Open the migration guide below for the recommended alternative and steps."}):t.jsx(a,{dimColor:!0,children:" Consult the package's docs or the e18e module-replacements guide for an alternative."})]})})]}),t.jsxs(m,{flexDirection:"column",marginTop:1,children:[t.jsx(a,{dimColor:!0,children:"── "}),t.jsx(a,{bold:!0,color:"white",children:"LINKS"}),t.jsxs(m,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[t.jsxs(a,{color:"cyan",underline:!0,children:["https://npmx.dev/",r.packageName]}),r.docUrl&&t.jsx(a,{color:"cyan",underline:!0,children:r.docUrl})]})]})]})]})},He=[{key:"all",label:"All",shortcut:"1"},{key:"native",label:"Native",shortcut:"2"},{key:"preferred",label:"Preferred",shortcut:"3"},{key:"micro-utility",label:"Micro",shortcut:"4"},{key:"socket",label:"Socket",shortcut:"5"}],Xe=({checked:r,entry:e,isSelected:o})=>{const n=ee[e.category]??"white",c=Be[e.category]??e.category,i=r?"☑":"☐",l=e.hasCodemod?"⚙":" ";return t.jsxs(m,{flexShrink:0,height:1,children:[t.jsx(a,{children:o?">":" "}),t.jsxs(a,{color:r?"white":"gray",children:[" ",i," "]}),t.jsx(a,{bold:!0,color:n,children:`[${c}]`.padEnd(9)}),t.jsxs(a,{children:[" ",l," "]}),t.jsx(m,{flexGrow:1,children:t.jsx(a,{bold:o,inverse:o,wrap:"truncate",children:e.packageName})}),t.jsx(a,{dimColor:!0,children:" → "}),t.jsx(a,{wrap:"truncate",children:e.replacement})]})},Ke=({checkedEntries:r,entries:e,filterActive:o,filterText:n,filterType:c,focused:i,isDryRun:l,scrollOffset:h,selectedIndex:k,totalEntries:s,viewportHeight:d})=>{const u=i?"white":"gray";let j=0,f=0,x=0,b=0;for(const C of e)switch(C.category){case"micro-utility":{x++;break}case"native":{j++;break}case"preferred":{f++;break}case"socket":{b++;break}}const g=[];j>0&&g.push(`${j} native`),f>0&&g.push(`${f} preferred`),x>0&&g.push(`${x} micro`),b>0&&g.push(`${b} socket`);const v=g.length>0?` (${g.join(", ")})`:"",$=r.size,T=[];for(const[C,p]of e.entries())T.push(t.jsx(Xe,{checked:r.has(p.packageName),entry:p,isSelected:C===k},p.packageName));const N=e.length,P=N>d&&d>0;return t.jsxs(m,{borderColor:u,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[t.jsxs(m,{flexShrink:0,gap:1,paddingX:1,children:[t.jsx(a,{bold:!0,inverse:!0,children:" VIS OPTIMIZE "}),t.jsxs(a,{wrap:"truncate",children:[s," ","optimizations",v]}),!l&&$>0&&t.jsxs(a,{dimColor:!0,children:[" ","—",$," ","selected"]})]}),t.jsx(m,{flexShrink:0,gap:1,paddingX:1,paddingY:1,children:He.map(C=>{const p=c===C.key;return t.jsxs(m,{children:[t.jsx(a,{dimColor:!p,children:"["}),t.jsx(a,{bold:p,color:p?"cyan":"gray",children:C.shortcut}),t.jsx(a,{dimColor:!p,children:"]"}),t.jsxs(a,{color:p?"white":"gray",children:[" ",C.label]})]},C.key)})}),o&&t.jsxs(m,{flexShrink:0,paddingX:1,children:[t.jsx(a,{bold:!0,color:"white",children:"/ "}),t.jsx(a,{children:n}),t.jsx(a,{inverse:!0,children:" "})]}),t.jsxs(m,{flexDirection:"row",flexGrow:1,overflow:"hidden",children:[t.jsx(m,{flexDirection:"column",flexGrow:1,overflow:"hidden",paddingLeft:1,children:t.jsx(m,{flexDirection:"column",marginTop:-h,children:T})}),P&&t.jsx(m,{flexShrink:0,marginLeft:1,marginRight:1,children:t.jsx(ye,{contentHeight:N,placement:"inset",scrollOffset:h,style:"block",viewportHeight:d})})]})]})},Ve=100,W=10,Y={1:"all",2:"native",3:"preferred",4:"micro-utility",5:"socket"},We=({isDryRun:r,store:e})=>{const{exit:o}=je(),{columns:n,rows:c}=ke(),i=_.useSyncExternalStore(e.subscribe,e.getSnapshot),l=_.useRef(null),[h,k]=_.useState(0),[s,d]=_.useState(!1),u=e.getFilteredEntries(),j=u[i.selectedIndex]??null,f=n>=Ve,x=Math.max(0,c-5),b=_.useCallback(g=>{o(g)},[o]);return ve((g,v)=>{if(s){g==="y"||g==="Y"?b():d(!1);return}if(i.filterActive){v.escape?(e.setFilterActive(!1),e.setFilterText("")):v.return?e.setFilterActive(!1):v.backspace||v.delete?e.setFilterText(i.filterText.slice(0,-1)):g&&!v.ctrl&&!v.meta&&e.setFilterText(i.filterText+g);return}if(g==="q"){!r&&i.checkedEntries.size>0?d(!0):b();return}if(g==="/"){e.setFilterActive(!0);return}if(Y[g]){e.setFilter(Y[g]);return}if(v.tab){e.setFocusedPanel(i.focusedPanel==="list"?"detail":"list");return}if(i.focusedPanel==="list")if(v.upArrow||g==="k"){const $=Math.max(0,i.selectedIndex-1);e.select($),$<h&&k($)}else if(v.downArrow||g==="j"){const $=Math.min(u.length-1,i.selectedIndex+1);e.select($),$>=h+x&&k($-x+1)}else g===" "?j&&e.toggleCheck(j.packageName):g==="a"?e.toggleAll():v.return&&!r&&i.checkedEntries.size>0&&b(e.getCheckedEntries());else i.focusedPanel==="detail"&&(v.upArrow||g==="k"?l.current?.scrollBy(-1):(v.downArrow||g==="j")&&l.current?.scrollBy(1))},{isActive:i.phase==="browsing"}),c<W?t.jsx(m,{alignItems:"center",justifyContent:"center",children:t.jsxs(a,{color:"yellow",children:["Terminal too small. Resize to at least",W," ","rows."]})}):t.jsxs(m,{flexDirection:"column",height:c,width:n,children:[t.jsxs(m,{flexDirection:f?"row":"column",flexGrow:1,children:[t.jsx(m,{flexBasis:f?"50%":void 0,flexGrow:1,children:t.jsx(Ke,{checkedEntries:i.checkedEntries,entries:u,filterActive:i.filterActive,filterText:i.filterText,filterType:i.filterType,focused:i.focusedPanel==="list",isDryRun:r,scrollOffset:h,selectedIndex:i.selectedIndex,totalEntries:i.entries.length,viewportHeight:x})}),t.jsx(m,{flexBasis:f?"50%":void 0,flexGrow:1,children:t.jsx(Je,{entry:j,focused:i.focusedPanel==="detail",scrollRef:l})})]}),t.jsx(m,{flexShrink:0,paddingX:1,children:t.jsxs(a,{dimColor:!0,children:[r?"Preview mode":"space:toggle a:all enter:apply"," ","| tab:switch panel /: filter q:quit |","⚙","=codemod available"]})}),t.jsx(we,{autoExitSeconds:3,onCancel:()=>{d(!1)},visible:s})]})},B=(r,e)=>{const o=new Set;try{const n=Z(r),c=e?[n.dependencies,n.optionalDependencies]:[n.dependencies,n.devDependencies,n.peerDependencies,n.optionalDependencies];for(const i of c)if(i)for(const l of Object.keys(i))o.add(l)}catch{}return o},re=r=>{const e=fe(r);if(e)return J(r,e);const o=O(r,"package.json");if(!z(o))return[];try{const n=Z(o),c=Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages;return c?J(r,c):[]}catch{return[]}},Ye="https://github.com/es-tooling/module-replacements/blob/main/docs/modules",Qe=r=>`${Ye}/${r}.md`,Ze=r=>{if(r.type==="simple"&&r.replacement)return r.replacement;if(r.type==="native"){const e=r.nodeVersion?` (Node ${r.nodeVersion}+)`:"";return r.replacement?`${r.replacement}${e}`:`Native API${e}`}return r.type==="documented"&&r.docPath?"see migration guide":""},te=r=>{const e=[],o=(n,c)=>{const i=n.moduleReplacements;if(Array.isArray(i))for(const l of i)r.has(l.moduleName)&&e.push({category:c,docUrl:l.type==="documented"&&l.docPath?Qe(l.docPath):void 0,hasCodemod:!1,overrideSpec:void 0,packageName:l.moduleName,replacement:Ze(l)})};return o(ue,"native"),o(ge,"preferred"),o(he,"micro-utility"),e},oe=(r,e,o,n)=>{const c=Le.getManifestData("npm")??[],i=[];for(const[,l]of c){if(l.deprecated)continue;const h=r.has(l.package),k=e?Me(e,l.package,o.name):!1;if(!h&&!k)continue;const s=Q.coerce(l.version)?.major;if(s===void 0)continue;const d=n?`npm:${l.name}@${l.version}`:`npm:${l.name}@^${String(s)}`;i.push({category:"socket",hasCodemod:!1,overrideSpec:d,packageName:l.package,replacement:l.name})}return i};let G;const ne=async()=>{if(G)return G;try{return G=(await import("module-replacements-codemods")).codemods,G}catch{return{}}},se=async r=>{try{const e=await ne();for(const o of r)o.category!=="socket"&&e[o.packageName]&&(o.hasCodemod=!0)}catch{}},ie=async(r,e,o)=>{let n=0;try{const c=(await ne())[o];if(!c)return{filesChanged:0,packageName:o};const i=c({}),l=await er(e);for(const h of l){const k=D(h);if(k.includes(o))try{const s=await i.transform({file:{filename:h,source:k}});s!==k&&(await r.writeFile(h,s,"utf8"),n++)}catch(s){process.stderr.write(`warn: codemod transform failed for ${h}: ${s instanceof Error?s.message:String(s)}
13
- `)}}}catch{}return{filesChanged:n,packageName:o}},er=async r=>Se("**/*.{cjs,cts,js,jsx,mjs,mts,ts,tsx}",{absolute:!0,cwd:r,ignore:["**/.*/**","**/.*","**/node_modules/**","**/dist/**","**/coverage/**","**/.git/**","**/.next/**","**/.nuxt/**"]}),rr=async({fs:r,logger:e,options:o,visConfig:n,workspaceRoot:c})=>{if(!c)throw new Error("Could not determine workspace root. Run this command inside a monorepo.");const i=$e(c),l=!!o.dryRun,h=!!o.prod,k=!!o.pin;y.info(`Detected ${i.name} v${i.version}.`);const s=B(O(c,"package.json"),h),d=re(c),u=new Set(s);for(const p of d){const R=B(O(ae(c,p),"package.json"),h);for(const E of R)u.add(E)}d.length>0&&y.info(`Scanned ${String(d.length)} workspace package${d.length===1?"":"s"}.`),y.info(`Scanning dependencies...
14
- `);const j=Fe(c,i.name),f=te(u),x=oe(u,j,i,k),b=new Set(f.map(p=>p.packageName)),g=x.filter(p=>!b.has(p.packageName)),v=[...f,...g];if(await se(v),v.length===0){y.info("No optimizations found for your dependencies.");return}const $=!!process.stdout.isTTY&&!me,T=o.format==="json"||!!o.json;if($&&!l&&!T){const p=new Ue(v),R=await de(pe.createElement(We,{isDryRun:!1,store:p}),{alternateScreen:!0,exitOnCtrlC:!1,interactive:!0,patchConsole:!0}).waitUntilExit(),E=Array.isArray(R)?R:[];if(E.length===0){y.info("No optimizations selected.");return}const I=E.filter(w=>w.category!=="socket"&&w.hasCodemod),F=E.filter(w=>w.category!=="socket"&&!w.hasCodemod),L=E.filter(w=>w.category==="socket");if(I.length>0){y.info(`
15
- Running ${String(I.length)} codemod${I.length===1?"":"s"}...
16
- `);for(const w of I){const S=await ie(r,c,w.packageName);S.filesChanged>0?y.success(` ${w.packageName}: ${String(S.filesChanged)} file${S.filesChanged===1?"":"s"} updated`):y.info(` ${w.packageName}: no files changed`)}}if(F.length>0){y.warn(`
17
- ${String(F.length)} selected replacement${F.length===1?"":"s"} require manual migration (no codemod available):`);for(const w of F)y.info(` ${w.packageName} → ${w.replacement}`);y.notice(" Replace usage in your source code, then remove from dependencies.")}if(L.length>0){const w=L.filter(M=>M.overrideSpec).map(M=>({original:M.packageName,spec:M.overrideSpec})),S=Ie(c,O(c,"package.json"),w,i,n?.editorconfig??!0);S.added.length>0&&y.success(`
18
- Added ${String(S.added.length)} override${S.added.length===1?"":"s"}.`),S.updated.length>0&&y.success(`Updated ${String(S.updated.length)} override${S.updated.length===1?"":"s"}.`)}if(L.length>0&&o.install!==!1){y.info(`
19
- Running ${i.name} install to update lockfile...`);const w=Ce(i,{dev:!1,filter:[],force:!1,frozenLockfile:!1,ignoreScripts:!1,lockfileOnly:!1,noOptional:!1,offline:!1,prod:!1,recursive:!1,silent:!1,workspaceRoot:!1},c,e);w!==0&&y.warn(`${i.name} install exited with code ${String(w)}. Run it manually.`)}y.info(""),y.success("Optimization complete.");return}if(T){process.stdout.write(`${JSON.stringify({e18e:f.map(p=>({category:p.category,hasCodemod:p.hasCodemod,packageName:p.packageName,replacement:p.replacement})),packageManager:i.name,socket:g.map(p=>({overrideSpec:p.overrideSpec,packageName:p.packageName,replacement:p.replacement})),total:v.length,workspaces:d.length},void 0,2)}
20
- `);return}const N=f.filter(p=>p.category==="native"),P=f.filter(p=>p.category==="preferred"),C=f.filter(p=>p.category==="micro-utility");if(N.length>0){y.info(`Native replacements (${String(N.length)}):`);for(const p of N)y.info(` ${p.hasCodemod?"⚙":" "} ${p.packageName} → ${p.replacement}`)}if(P.length>0){y.info(`
21
- Preferred alternatives (${String(P.length)}):`);for(const p of P)y.info(` ${p.hasCodemod?"⚙":" "} ${p.packageName} → ${p.replacement}`)}if(C.length>0){y.info(`
22
- Micro-utilities (${String(C.length)}):`);for(const p of C)y.info(` ${p.hasCodemod?"⚙":" "} ${p.packageName} → ${p.replacement}`)}if(g.length>0){y.info(`
23
- Socket.dev overrides (${String(g.length)}):`);for(const p of g)y.info(` ${p.packageName} → ${p.overrideSpec}`)}y.info(`
24
- Total: ${String(v.length)} optimizations available (⚙ = codemod available).`),l&&y.notice("Run without --dry-run for interactive selection.")},jr=Object.defineProperty({__proto__:null,buildE18eEntries:te,buildSocketEntries:oe,collectDepsFromPkgJson:B,default:rr,discoverWorkspacePackages:re,markCodemodAvailability:se,runCodemod:ie},Symbol.toStringTag,{value:"Module"});export{re as A,te as F,ie as I,Fe as N,oe as T,se as U,Ie as a,jr as h,B as x};
1
+ import{createRequire as H}from"node:module";import{I as W}from"../packem_shared/index-B0EsgdzO.js";import{p as q}from"../packem_shared/prompt-DjXHVgYU.js";import{f as Y,m as X,a as J,T as U}from"../packem_shared/index-CE6MsgcV.js";import{f as D,A as Q,C as Z,r as ee,_ as te,i as A}from"../packem_shared/env-DJlbJiFh.js";import{a as se}from"../packem_shared/readJsonSync-DuMMeB3s-ihoybKvs.js";import{g as re,r as oe}from"../packem_shared/packument-CY2QDFml.js";import{q as ne,j as ie,E as $,s as k,V as C,I as x}from"../packem_shared/index.server-J83sowC4.js";import{h as ae,W as ce}from"../packem_shared/pm-runner-CQcraCcu.js";import{r as le,a as fe}from"../packem_shared/command-runtime-3FTGuUsK.js";const L=H(import.meta.url),v=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,G=e=>{if(typeof v<"u"&&v.versions&&v.versions.node){const[t,s]=v.versions.node.split(".").map(Number);if(t>22||t===22&&s>=3||t===20&&s>=16)return v.getBuiltinModule(e)}return L(e)},{renameSync:F}=G("node:fs"),{stripVTControlCharacters:P}=G("node:util"),pe=(e={})=>{const t=e.isCi??W;return(e.isTty??!!(process.stdin.isTTY&&process.stdout.isTTY))&&!t},w=X(D(),"dlx-seen.json"),V=(e,t)=>`${e}@${t}`,ue=e=>{if(typeof e!="object"||e===null)return!1;const t=e;return Array.isArray(t.alertKeys)&&t.alertKeys.every(s=>typeof s=="string")&&typeof t.seenAt=="number"},B=()=>{try{if(Y(w)){const e=se(w);if(e&&typeof e=="object"&&e.packages&&typeof e.packages=="object"&&e.version===1){const t={};for(const[s,r]of Object.entries(e.packages))ue(r)&&(t[s]=r);return{packages:t,version:1}}}}catch{}return{packages:{},version:1}},ge=e=>{try{J(D());const t=`${w}.${String(process.pid)}.tmp`;U(t,JSON.stringify(e)),F(t,w)}catch{}},me=(e,t,s)=>e.packages[V(t,s)],de=(e,t)=>{if(!e)return!0;const s=new Set(Array.isArray(e.alertKeys)?e.alertKeys:[]);return t.some(r=>!s.has(r))},E=(e,t,s,r)=>{const o=B();o.packages[V(e,t)]={alertKeys:[...s].sort(),seenAt:r},ge(o)},he=/[\u0000-\u0008\u000B-\u001F\u007F]/g,z=e=>P(e).replaceAll(" "," ").replaceAll(he,""),_=["CHANGELOG.md","CHANGELOG","changelog.md","CHANGES.md","HISTORY.md"],ye=4e3,R=async(e,t,s)=>{if(t?.aborted)return;const r=new AbortController,o=setTimeout(()=>{r.abort()},ye),a=()=>{r.abort()};t?.addEventListener("abort",a,{once:!0});try{const i=await fetch(e,{headers:s,signal:r.signal});return i.ok?await i.text():void 0}catch{return}finally{clearTimeout(o),t?.removeEventListener("abort",a)}},$e=e=>{const t=typeof e=="string"?e:e?.url;if(!t)return;const s=/github\.com[/:]([^/]+)\/([^/#]+?)(?:\.git)?(?:[/#]|$)/i.exec(t)??/^github:([^/]+)\/([^/#]+)/i.exec(t);return s?{directory:typeof e=="object"?e?.directory:void 0,owner:s[1],repo:s[2].replace(/\.git$/,"")}:void 0},I=(e,t)=>{const s=e.split(/\r?\n/),r=/^(#{1,4})\s+(.*)$/,o=t.replaceAll(/[$()*+.?[\\\]^{|}]/g,String.raw`\$&`),a=new RegExp(String.raw`(?<![\w.])${o}(?![\w.])`);let i=-1,u=0;for(const[c,l]of s.entries()){const f=r.exec(l);if(f&&a.test(f[2])){i=c,u=f[1].length;break}}if(i===-1)return;const n=[];for(let c=i+1;c<s.length;c+=1){const l=r.exec(s[c]);if(l&&l[1].length<=u)break;n.push(s[c])}return n},O=(e,t=4)=>e.map(s=>s.trim()).filter(s=>s.length>0).map(s=>z(s.replace(/^#{1,6}\s+/,"").replace(/^[*-]\s+/,"- ")).trim()).filter(s=>s.length>0&&!/^\[.*\]:/.test(s)).slice(0,t),j=(e,t)=>{if(!e)return"";const s=Date.parse(e);if(Number.isNaN(s))return"";const r=Math.floor((t-s)/(1440*60*1e3));if(r<=0)return"today";if(r===1)return"1d ago";if(r<30)return`${String(r)}d ago`;const o=Math.floor(r/30);return o<12?`${String(o)}mo ago`:`${String(Math.floor(o/12))}y ago`},N=(e,t,s)=>{const r=e.time??{},o=j(r[t],s),a=[o?`${e.name}@${t} — published ${o}`:`${e.name}@${t}`],i=Date.parse(r[t]??""),u=Object.entries(r).filter(([n])=>n!=="created"&&n!=="modified"&&n!==t).sort((n,c)=>Date.parse(c[1])-Date.parse(n[1])).filter(([,n])=>Date.parse(n)<i).slice(0,3);for(const[n,c]of u)a.push(`- ${n} (${j(c,s)})`);return{lines:a,source:"npm-diff",version:t}},ve=async e=>{const{name:t,now:s,offline:r,packument:o,signal:a,version:i}=e;if(r)return o?N(o,i,s):void 0;for(const c of _){const l=`https://cdn.jsdelivr.net/npm/${t}@${i}/${c}`,f=await R(l,a);if(f){const d=I(f,i),p=O(d??f.split(/\r?\n/));if(p.length>0)return{lines:p,source:"package-file",url:l,version:i}}}const u=o?.versions[i],n=$e(u?.repository);if(n){const c=n.directory?`${n.directory.replaceAll(/^\/+|\/+$/g,"")}/`:"";for(const l of["HEAD","main","master"])for(const f of _){const d=`https://raw.githubusercontent.com/${n.owner}/${n.repo}/${l}/${c}${f}`,p=await R(d,a);if(p){const h=I(p,i),m=O(h??p.split(/\r?\n/));if(m.length>0){const g=`https://github.com/${n.owner}/${n.repo}/blob/${l}/${c}${f}`;return{lines:m,source:"repo-file",url:g,version:i}}}}}if(o)return N(o,i,s)},ke={dynamicRequire:"dynamic require",envVars:"env access",filesystemAccess:"filesystem",networkAccess:"network",shellAccess:"shell",telemetry:"telemetry",unsafe:"eval/unsafe",usesEval:"eval/unsafe"},be=["preinstall","install","postinstall"],we=(e,t)=>({fileCount:e?.dist?.fileCount,tarballBytes:t?.size,unpackedBytes:e?.dist?.unpackedSize}),Se=(e,t)=>{const s=be.filter(i=>!!e?.scripts?.[i]),r=e?.bin,o=typeof r=="string"?["(default)"]:Object.keys(r??{}).map(i=>z(i)),a=[...new Set(t.map(i=>ke[i.type]).filter(i=>i!==void 0))];return{bins:o,capabilities:a,lifecycleScripts:s}},Te=(e,t,s)=>{const r=e.get(`${t}@${s}`);if(r)return r;for(const o of e.values())if(o.name===t&&o.version===s)return o},Ce=async e=>{const{name:t,now:s,offline:r,signal:o,socketToken:a,spec:i,workspaceRoot:u}=e;let n;try{n=await re(t,{offline:r,signal:o,workspaceRoot:u})}catch{n=void 0}const c=n?oe(n,i):void 0;if(!c)return;const l=n?.versions[c],f=async()=>{if(!(r||!a))try{const y=await Z([{name:t,version:c}],{apiToken:a});return Te(y,t,c)}catch{return}},d=ve({name:t,now:s,offline:r,packument:n,signal:o,version:c}).catch(()=>{}),[p,h]=await Promise.all([f(),d]),m=p?.alerts??[],g=[...new Set(m.filter(y=>y.severity==="critical"||y.severity==="high").map(y=>y.key))].sort(),S=p?Math.round((p.score.overall??Q(p.score))*100):void 0;return{changelog:h,name:t,permissions:Se(l,m),security:{alerts:m,available:!!p,highSeverityKeys:g,score:S},size:we(l,p),version:c}},b=e=>ee(P(e)),Ae={critical:C,high:C,low:$,medium:k},K=e=>{if(!(e===void 0||e<0))return te(e,{decimals:1,space:!0})},xe=e=>{const{fileCount:t,tarballBytes:s,unpackedBytes:r}=e.size,o=K(r),a=K(s);if(o&&a){const i=t===void 0?"":`, ${String(t)} files`;return`${o} unpacked (${a} tarball${i})`}if(o)return`${o} unpacked`;if(a)return`${a} tarball`},Ee=e=>{const{alerts:t,available:s,score:r}=e.security;if(!s)return $("unavailable — set VIS_SOCKET_TOKEN for a Socket.dev score");const o=r===void 0?$:r>=70?x:r>=40?k:C,a=r===void 0?"n/a":`${String(r)}/100`,i=new Map;for(const l of t)i.set(l.severity,(i.get(l.severity)??0)+1);const u=[],n=["critical","high","medium","low"];for(const l of n){const f=i.get(l);f&&u.push(Ae[l](`${String(f)} ${l}`))}const c=u.length>0?` ${k("!")} ${u.join(", ")}`:` ${x("no alerts")}`;return`${o(a)} ${$("(Socket.dev)")}${c}`},_e=e=>{const{bins:t,capabilities:s,lifecycleScripts:r}=e.permissions,o=[];for(const a of r)o.push(k(`${a} script`));for(const a of s)o.push(k(a));return t.length>0&&o.push($(`bins: ${t.join(", ")}`)),o.length>0?o.join($(" · ")):void 0},Re=e=>{const t=[],s=xe(e);s&&t.push({label:"size",values:[s]}),t.push({label:"score",values:[Ee(e)]});const r=_e(e);if(r&&t.push({label:"perms",values:[r]}),e.changelog){const o=e.changelog.source==="npm-diff"?"registry":e.changelog.source==="repo-file"?"repo CHANGELOG":"CHANGELOG";t.push({label:"latest",values:[...e.changelog.lines,$(`source: ${o}`)]})}return t},M=6,Ie=e=>{const t=Re(e),s=` first run: ${e.name}@${e.version} `,r=[];for(const n of t)n.values.forEach((c,l)=>{const f=l===0?ne(n.label.padEnd(M)):" ".repeat(M);r.push(`${f} ${c}`)});const o=Math.max(b(s),...r.map(n=>b(n))),a=n=>`${n}${" ".repeat(Math.max(0,o-b(n)))}`,i=`┌─${ie(s)}${"─".repeat(Math.max(0,o-b(s)))}─┐`,u=`└─${"─".repeat(o)}─┘`;return[i,...r.map(n=>`│ ${a(n)} │`),u]},Oe=e=>{if(e.startsWith("@")){const s=e.indexOf("@",1);return s===-1?{name:e}:{name:e.slice(0,s),spec:e.slice(s+1)}}const t=e.indexOf("@");return t<=0?{name:e}:{name:e.slice(0,t),spec:e.slice(t+1)}},je=e=>e===""||e.startsWith(".")||e.startsWith("/")||e.startsWith("~")?!1:!(e.startsWith("@")?e.slice(1):e).includes(":"),Ne=6e3,Ke=e=>{process.stdout.write(e)},Me=async e=>{const{forceInfo:t=!1,noInfo:s=!1,offline:r=!1,pkg:o,socketToken:a,workspaceRoot:i,yes:u=!1}=e;if(s||!je(o))return{proceed:!0};const n=e.now??Date.now(),c=u||!pe({isCi:e.isCi,isTty:e.isTty}),l=e.output??Ke;if(c&&!t)return{proceed:!0};const{name:f,spec:d}=Oe(o),p=new AbortController;let h;const m=new Promise(T=>{h=setTimeout(()=>{p.abort(),T(void 0)},Ne)}),g=await Promise.race([Ce({name:f,now:n,offline:r,signal:p.signal,socketToken:a,spec:d,workspaceRoot:i}).catch(()=>{}),m]);if(h&&clearTimeout(h),!g)return{proceed:!0};const S=me(B(),g.name,g.version);if(!t&&!de(S,g.security.highSeverityKeys))return{proceed:!0};for(const T of Ie(g))l(`${T}
2
+ `);if(c)return E(g.name,g.version,g.security.highSeverityKeys,n),{proceed:!0};const y=await q("? Ok to proceed? (y/N) ",e.readline);return y&&E(g.name,g.version,g.security.highSeverityKeys,n),{proceed:y}},Fe=async({argument:e,logger:t,options:s,visConfig:r,workspaceRoot:o})=>{const a=e;if(!a||a.length===0)throw new Error("No package specified. Usage: vis dlx <package[@version]> [args...]");const[i,...u]=a,n=o??process.cwd(),c=s.package?Array.isArray(s.package)?s.package:[s.package]:[],l=s.shellMode?c:[i,...c];for(const h of l){const m=s.info||!1,g=m?!1:s.noInfo||A(process.env.VIS_DLX_NO_INFO);if(!(await Me({forceInfo:m,noInfo:g,offline:s.offline||!1,pkg:h,socketToken:r?.security?.socket?.apiToken??process.env.VIS_SOCKET_TOKEN,workspaceRoot:n,yes:s.yes||A(process.env.VIS_DLX_YES)})).proceed){t.info("Aborted."),process.exitCode=1;return}}const f=le({logger:t,options:s,visConfig:r},n),d=ae(n,{backend:fe(f),configBackend:r?.install?.backend,configCorepack:r?.install?.corepack}),p=ce(d,{additionalPackages:c,args:u,package:i,shellMode:s.shellMode||!1,silent:s.silent||!1},n,t,{offline:s.offline||!1});p!==0&&(process.exitCode=p)};export{Fe as default};