@visulima/vis 3.0.1 → 3.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/LICENSE.md +33 -22
- package/dashboard/dist/index.html +12 -12
- package/dist/bin.js +1 -1
- package/dist/binx.js +1 -1
- package/dist/packem_chunks/CONFIG_FILES.js +1 -1
- package/dist/packem_chunks/bloom-status.js +1 -1
- package/dist/packem_chunks/bloom-sync.js +1 -1
- package/dist/packem_chunks/catalog.js +2 -2
- package/dist/packem_chunks/cli-exec.js +1 -1
- package/dist/packem_chunks/cli-main.js +168 -170
- package/dist/packem_chunks/doctor-probe.js +2 -2
- package/dist/packem_chunks/fix.js +5 -5
- package/dist/packem_chunks/handler13.js +1 -1
- package/dist/packem_chunks/handler14.js +1 -1
- package/dist/packem_chunks/handler15.js +1 -1
- package/dist/packem_chunks/handler19.js +1 -1
- package/dist/packem_chunks/handler2.js +1 -1
- package/dist/packem_chunks/handler20.js +1 -1
- package/dist/packem_chunks/handler21.js +1 -1
- package/dist/packem_chunks/handler23.js +1 -1
- package/dist/packem_chunks/handler24.js +1 -1
- package/dist/packem_chunks/handler26.js +1 -1
- package/dist/packem_chunks/handler28.js +1 -1
- package/dist/packem_chunks/handler3.js +1 -1
- package/dist/packem_chunks/handler50.js +4 -4
- package/dist/packem_chunks/handler53.js +1 -1
- package/dist/packem_chunks/handler54.js +1 -1
- package/dist/packem_chunks/handler55.js +1 -1
- package/dist/packem_chunks/handler58.js +1 -1
- package/dist/packem_chunks/handler59.js +1 -1
- package/dist/packem_chunks/handler6.js +5 -5
- package/dist/packem_chunks/handler60.js +1 -1
- package/dist/packem_chunks/handler61.js +7 -7
- package/dist/packem_chunks/handler62.js +1 -1
- package/dist/packem_chunks/handler63.js +1 -1
- package/dist/packem_chunks/handler64.js +2 -2
- package/dist/packem_chunks/handler65.js +2 -2
- package/dist/packem_chunks/handler66.js +1 -1
- package/dist/packem_chunks/handler67.js +25 -24
- package/dist/packem_chunks/handler68.js +153 -25
- package/dist/packem_chunks/handler69.js +10 -153
- package/dist/packem_chunks/handler70.js +22 -10
- package/dist/packem_chunks/handler71.js +4 -4
- package/dist/packem_chunks/handler72.js +3 -3
- package/dist/packem_chunks/handler73.js +6 -6
- package/dist/packem_chunks/handler74.js +1 -1
- package/dist/packem_chunks/handler75.js +1 -1
- package/dist/packem_chunks/handler76.js +1 -1
- package/dist/packem_chunks/handler77.js +40 -40
- package/dist/packem_chunks/handler78.js +20 -20
- package/dist/packem_chunks/heal.js +4 -4
- package/dist/packem_chunks/help-command.js +5 -5
- package/dist/packem_chunks/index4.js +6 -8
- package/dist/packem_chunks/index6.js +5 -5
- package/dist/packem_chunks/list.js +1 -1
- package/dist/packem_chunks/prompts.js +1 -1
- package/dist/packem_chunks/prune.js +1 -1
- package/dist/packem_chunks/run.js +1 -1
- package/dist/packem_chunks/shell-runner.js +1 -1
- package/dist/packem_chunks/status.js +1 -1
- package/dist/packem_chunks/sync.js +1 -1
- package/dist/packem_chunks/tar.js +3 -3
- package/dist/packem_shared/{advisories-CyDqzi5j.js → advisories-0ScpWAHV.js} +1 -1
- package/dist/packem_shared/{affected-selection-DPQR-Bd3.js → affected-selection-BMoQWuHl.js} +1 -1
- package/dist/packem_shared/{ai-fix-6nXZbecQ.js → ai-fix-CKN1JGRh.js} +1 -1
- package/dist/packem_shared/{bin-wafzkjaB.js → bin-CN4heKmb.js} +1 -1
- package/dist/packem_shared/{cyclonedx-C_ezHg8b.js → cyclonedx-B1vzerwP.js} +1 -1
- package/dist/packem_shared/{docker-Br_iFmI-.js → docker-Bex05Qcn.js} +16 -16
- package/dist/packem_shared/giget-D8Kwb0kD.js +2 -0
- package/dist/packem_shared/index.server-BAjDJSEu.js +2 -0
- package/dist/packem_shared/main-BP-w-K-6.js +1 -0
- package/dist/packem_shared/{osv-bloom-5wDAoZ1e.js → osv-bloom-JYIWcH3F.js} +1 -1
- package/dist/packem_shared/{package-version-BJkg7-6H.js → package-version-CJxZ_B7G.js} +3 -3
- package/dist/packem_shared/{project-name-filter-BeREbPMI.js → project-name-filter-DsrVo0MY.js} +1 -1
- package/dist/packem_shared/{resolve-explicit-COmP7eqr.js → resolve-explicit-DYaHAVDg.js} +1 -1
- package/dist/packem_shared/{s1ngularity-RZOHbGrE.js → s1ngularity-C8sva2SO.js} +1 -1
- package/dist/packem_shared/{scan-progress-C9nMDLis.js → scan-progress-5uTRdC1G.js} +2 -2
- package/dist/packem_shared/{spinner-CbJfWYwB.js → spinner-BM_0Bj6x.js} +1 -1
- package/dist/packem_shared/{tabs-BilwonkM.js → tabs-UDYQ3tqt.js} +1 -1
- package/dist/packem_shared/target-merge-B4No-LHM.js +4 -0
- package/dist/packem_shared/{typosquats-D8ppc5kr.js → typosquats-Cdsnf6aN.js} +1 -1
- package/dist/packem_shared/{vis-update-app-ngwL2mRv.js → vis-update-app-zqSa2clT.js} +1 -1
- package/dist/packem_shared/{vis-user-error-jhNwmkZp.js → vis-user-error-Dkc97rGY.js} +1 -1
- package/index.js +26 -26
- package/package.json +14 -14
- package/dist/packem_shared/giget-CVyyR7x8.js +0 -2
- package/dist/packem_shared/index.server-CwSgbeN7.js +0 -2
- package/dist/packem_shared/main-BjJN8kWj.js +0 -1
- package/dist/packem_shared/target-merge-D1xbylFw.js +0 -4
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as
|
|
1
|
+
import{createRequire as H}from"node:module";import{J as A,q as U,j as W,F as E}from"../packem_shared/index.server-BAjDJSEu.js";import{a as P}from"../packem_shared/index-DHD8wb6Z.js";import{Z as I}from"./cli-main.js";import{d as F,f as C,r as Z,a as Q,b as X,s as Y,c as ee,e as te,g as se,h as ie,i as ne,j as re,k as ae,l as oe,m as ce,n as de,o as fe,p as le,q as ue,t as pe}from"../packem_shared/watch-loop-COWvvSbR.js";import{T as h}from"./catalog.js";let J;const D=t=>(J??=H(import.meta.url))(t),k=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,G=t=>{if(typeof k<"u"&&k.versions&&k.versions.node){const[e,s]=k.versions.node.split(".").map(Number);if(e>22||e===22&&s>=3||e===20&&s>=16)return k.getBuiltinModule(t)}return D(t)},{createHash:_}=G("node:crypto"),ge=t=>t.startsWith("/")||/^[a-z]:[\\/]/i.test(t),q=(t,e)=>ge(e)?e:`${t}/${e}`,me={argsCheck:(t,e)=>O(t,e,"check"),argsFix:(t,e)=>O(t,e,"fix"),bin:()=>["pnpm","exec","dprint"],cacheKey:(t,e)=>{const s=["dprint",t.declaredVersion??"unknown",t.configFile??"no-config",e.quiet?"q":"",...e.extraArgs??[]];return _("sha256").update(s.join("|")).digest("hex").slice(0,16)},detect:(t,e)=>{const s=F(e,h.dprint.packageNames[0]),i=C(t,h.dprint.configFiles);if(!(!s&&!i))return{adapter:"dprint",configFile:i,declared:!!s,declaredVersion:s,root:t}},extensions:["cjs","css","cts","dockerfile","html","js","json","jsonc","jsx","md","mdx","mjs","mts","toml","ts","tsx","yaml","yml"],id:"dprint",kind:"fmt",parse:(t,e)=>{if(t.exitCode===0)return[];const s=[];for(const i of t.stdout.split(/\r?\n/)){const n=i.trim();!n||n.startsWith("[")||n.startsWith("Checked ")||n.startsWith("Error:")||s.push({adapter:"dprint",file:q(e.root,n),fixable:!0,message:"Code style issues would be auto-fixed",severity:"info"})}return s}},O=(t,e,s)=>{const i=s==="fix"?["fmt"]:["check","--list-different"];return e.extraArgs?.length&&i.push(...e.extraArgs),i.push(...t),i},he={argsCheck:(t,e)=>V(t,e,"check"),argsFix:(t,e)=>V(t,e,"fix"),bin:()=>["pnpm","exec","oxfmt"],cacheKey:(t,e)=>{const s=["oxfmt",t.declaredVersion??"unknown",t.configFile??"no-config",e.quiet?"q":"",...e.extraArgs??[]];return _("sha256").update(s.join("|")).digest("hex").slice(0,16)},detect:(t,e)=>{const s=F(e,h.oxfmt.packageNames[0]),i=C(t,h.oxfmt.configFiles);if(!(!s&&!i))return{adapter:"oxfmt",configFile:i,declared:!!s,declaredVersion:s,root:t}},extensions:["cjs","cts","js","json","jsonc","jsx","mjs","mts","ts","tsx"],id:"oxfmt",kind:"fmt",parse:(t,e)=>{if(t.exitCode===0)return[];const s=[];for(const i of t.stdout.split(/\r?\n/)){const n=i.trim();!n||n.startsWith("[")||s.push({adapter:"oxfmt",file:q(e.root,n),fixable:!0,message:"Code style issues would be auto-fixed",severity:"info"})}return s}},V=(t,e,s)=>{const i=s==="fix"?["--write"]:["--list-different"];return e.extraArgs?.length&&i.push(...e.extraArgs),i.push(...t),i},xe={argsCheck:(t,e)=>N(t,e,"check"),argsFix:(t,e)=>N(t,e,"fix"),bin:()=>["pnpm","exec","prettier"],cacheKey:(t,e)=>{const s=["prettier",t.declaredVersion??"unknown",t.configFile??"no-config",e.quiet?"q":"",...e.extraArgs??[]];return _("sha256").update(s.join("|")).digest("hex").slice(0,16)},detect:(t,e)=>{const s=F(e,h.prettier.packageNames[0]),i=C(t,h.prettier.configFiles);if(!(!s&&!i))return{adapter:"prettier",configFile:i,declared:!!s,declaredVersion:s,root:t}},extensions:["cjs","css","cts","html","js","json","jsx","less","md","mdx","mjs","mts","scss","ts","tsx","vue","yaml","yml"],id:"prettier",kind:"fmt",parse:(t,e)=>{if(t.exitCode===0)return[];const s=[];for(const i of t.stdout.split(/\r?\n/)){const n=i.trim();n&&(n.startsWith("[")||s.push({adapter:"prettier",file:q(e.root,n),fixable:!0,message:"Code style issues would be auto-fixed",severity:"info"}))}return s}},N=(t,e,s)=>{const i=s==="fix"?["--write"]:["--list-different"];return e.quiet&&i.push("--log-level","warn"),e.extraArgs?.length&&i.push(...e.extraArgs),i.push(...t),i},ke=[he,se,me,xe,ie,ne],Re=async({logger:t,options:e,visConfig:s,workspaceRoot:i})=>{const n=i??process.cwd(),p=s?.fmt,w=Z(ke,p?.order),L=Q(n,w),x=X(L,w,"fmt").filter(({adapter:l})=>p?.adapters?.[l.id]?.enabled!==!1);if(x.length===0){t.warn("vis fmt: no formatter detected in this workspace (looked for: oxfmt, biome, dprint, prettier, ruff, deno-fmt).");return}const R=l=>{const a=p?.adapters?.[l]?.extraArgs;return a&&a.length>0?[...a]:void 0},v={quiet:e.quiet??!1},$=we(e),b=e.check?"check":"fix";let c;if(e.staged){if(c=Y(n),c===void 0)t.warn("vis fmt: could not resolve --staged (not a git repo or git unavailable). Falling back to a workspace-wide run.");else if(c.length===0){t.info(A("✓ fmt: no staged files"));return}}else if(typeof e.since=="string"&&e.since.length>0){if(c=ee(n,e.since),c===void 0)t.warn(`vis fmt: could not resolve --since ${e.since} (not a git repo or unknown ref). Falling back to a workspace-wide run.`);else if(c.length===0){t.info(A(`✓ fmt: no files changed since ${e.since}`));return}}const K=I(n,void 0,void 0,!0),y=e.format??"human";y==="human"&&e.output!==void 0&&t.warn("vis fmt: --output is ignored for the human format; pass --format json|minimal|sarif|junit|github to redirect findings to a file.");const M=async l=>{const a=$.length>0?$:l,g=[];if(a){const r=re(a,x,p?.extensionOverrides);for(const{adapter:o,presence:d}of x){const f=r.get(o.id);if(!f||f.length===0)continue;const B=R(o.id),T={adapter:o,files:f,presence:d};B&&(T.options={...v,extraArgs:B}),g.push(T)}}else for(const{adapter:r,presence:o}of x){const d=R(r.id),f={adapter:r,files:["."],presence:o};d&&(f.options={...v,extraArgs:d}),g.push(f)}if(g.length===0)return;const z=await ae(g,v,b,{cacheRoot:K}),j=g.map((r,o)=>{const d=z[o],f=r.adapter.parse(d,r.presence);return{adapter:r.adapter,durationMs:d.durationMs,exitCode:d.exitCode,findings:f}}),u=oe(j.map(r=>({adapter:r.adapter.id,durationMs:r.durationMs,exitCode:r.exitCode,findingCount:r.findings.length,findings:r.findings}))),m=y==="human"?void 0:ce({cwd:n,target:e.output});try{switch(y){case"github":{m.write(le({runs:j.map(r=>({findings:r.findings})),workspaceRoot:n}));break}case"json":{m.write(`${JSON.stringify({findings:u.findings,mode:b,runs:u.runs},null,2)}
|
|
2
2
|
`);break}case"junit":{m.write(fe({runs:j.map(r=>({adapter:r.adapter.id,durationMs:r.durationMs,findings:r.findings})),workspaceRoot:n}));break}case"minimal":{je(u.findings,n,m);break}case"sarif":{m.write(de({runs:j.map(r=>({adapter:r.adapter.id,findings:r.findings,presence:g.find(o=>o.adapter.id===r.adapter.id)?.presence})),workspaceRoot:n}));break}default:be(u.findings,n,b,t)}}finally{m?.close()}const S=b==="fix"?u.hadProcessFailure?1:0:ue({...u,maxSeverity:u.findings.length>0?"error":void 0});S!==0&&(process.exitCode=S)};if(e.watch){const l=[...new Set(x.flatMap(({adapter:a})=>a.extensions))];await te({extensions:l,initialFiles:c,label:"fmt",log:a=>{t.info(a)},runCycle:M,workspaceRoot:n});return}await M(c)},we=t=>{const e=t;return[...e._??e.args??[]]},be=(t,e,s,i)=>{if(t.length===0){i.info(A(s==="fix"?"✓ fmt: nothing to change":"✓ fmt: all files already formatted"));return}const n=pe(t),p=s==="fix"?U(W("Formatted:")):W("Would change:");i.info(p);for(const w of n.keys())i.info(` ${E("·")} ${P(e,w)}`);s==="check"&&(i.info(""),i.info(E(`Run \`vis fmt\` to apply changes (${String(n.size)} file${n.size===1?"":"s"}).`)))},je=(t,e,s)=>{for(const i of t)s.write(`${i.adapter} ${P(e,i.file)}
|
|
3
3
|
`)};export{Re as default};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as re}from"node:module";import{F as d,
|
|
1
|
+
import{createRequire as re}from"node:module";import{F as d,j as y,q as v}from"../packem_shared/index.server-BAjDJSEu.js";import{e as S,m as K,a as G,v as F,b as oe,U as ie}from"../packem_shared/index-DHD8wb6Z.js";import{y as _}from"../packem_shared/isAccessibleSync-DYKTrrvc-CSnBISfV.js";import{L as H}from"./catalog.js";import{d as de}from"../packem_shared/giget-D8Kwb0kD.js";import{p as f}from"./cli-main.js";import{h as J,U as me}from"../packem_shared/writeFileSync-DJoHk3Ks-CgQ-VNNT.js";let se;const ne=t=>(se??=re(import.meta.url))(t),O=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,B=t=>{if(typeof O<"u"&&O.versions&&O.versions.node){const[e,r]=O.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return O.getBuiltinModule(t)}return ne(t)},{fileURLToPath:ae}=B("node:url"),{createInterface:ce}=B("node:readline"),{mkdtempSync:le,rmSync:fe}=B("node:fs"),{tmpdir:ue}=B("node:os"),{spawnSync:pe}=B("node:child_process"),z=[".ts",".mts",".cts",".js",".mjs",".cjs"],he="template.yml",ge=[".d",".test",".spec",".config",".bench",".stories"],we=[".d.ts",".d.mts",".d.cts",".js.map",".mjs.map",".cjs.map",".ts.map"],X=t=>{for(const e of z)if(t.endsWith(e))return t.slice(0,-e.length);return t},$e=t=>{if(we.some(r=>t.endsWith(r))||!z.some(r=>t.endsWith(r)))return!1;const e=X(t);return!ge.some(r=>e.endsWith(r))},U=(t,e)=>{const r=[];if(!_(t))return r;for(const n of H(t,{includeDirs:!1,includeSymlinks:!1,maxDepth:1})){if(!$e(n.name))continue;const s=X(n.name);r.push({load:()=>ve(n.path),name:s,path:n.path,source:e})}return r},I=(t,e)=>{const r=[];if(!_(t))return r;for(const n of H(t,{includeFiles:!1,includeSymlinks:!1,maxDepth:1})){if(n.path===t)continue;const s=S(n.path,he);_(s)&&r.push({load:()=>be(n.path,n.name),name:n.name,path:n.path,source:e})}return r},ye=()=>{try{const t=ae(import.meta.url),e=S(K(t),"..","..","templates");return _(e)?e:void 0}catch{return}},R=t=>{const{extraDirectories:e=[],onWarning:r,workspaceRoot:n}=t,s=[...U(S(n,".vis","templates"),"native"),...I(S(n,".vis","templates"),"moon"),...I(S(n,".moon","templates"),"moon")];for(const c of e)s.push(...I(c,"config")),s.push(...U(c,"config"));const i=ye();i&&s.push(...I(i,"builtin"));const a=new Map;for(const c of s){const o=a.get(c.name);if(!o){a.set(c.name,c);continue}r&&r(`Template "${c.name}" exists in multiple sources — using ${o.source} (${o.path}), ignoring ${c.source} (${c.path}).`)}return[...a.values()].sort((c,o)=>c.name.localeCompare(o.name))},ve=async t=>{const{loadNativeTemplate:e}=await import("./loader2.js");return e(t)},be=async(t,e)=>{const{loadMoonTemplate:r}=await import("./index5.js");return r(t,e)},q=(t,e)=>new Promise(r=>{t.question(e,n=>{r(n.trim())})}),Te=async(t,e,r)=>{const s=await q(t,` ${e} ${d(r?"[Y/n]":"[y/N]")} `);return s===""?r:s.toLowerCase()==="y"||s.toLowerCase()==="yes"},Se=async(t,e,r,n)=>{process.stderr.write(` ${e}
|
|
2
2
|
`);for(const[s,i]of r.entries()){const a=y(v(` ${String(s+1)}.`)),c=i===n?d(" (default)"):"";process.stderr.write(`${a} ${i}${c}
|
|
3
3
|
`)}for(;;){const s=await q(t,`
|
|
4
4
|
${d(`Enter choice (1-${String(r.length)}):`)} `);if(s===""&&n!==void 0)return n;const i=Number.parseInt(s,10);if(Number.isInteger(i)&&i>=1&&i<=r.length)return r[i-1];const a=r.find(c=>c===s);if(a)return a;process.stderr.write(` ${d("Invalid choice. Try again.")}
|
|
@@ -6,17 +6,17 @@ import{createRequire as re}from"node:module";import{F as d,q as y,D as v}from"..
|
|
|
6
6
|
`);for(const[s,i]of r.entries()){const a=y(v(` ${String(s+1)}.`)),c=n.includes(i)?d(" (default)"):"";process.stderr.write(`${a} ${i}${c}
|
|
7
7
|
`)}for(;;){const s=await q(t,`
|
|
8
8
|
${d("Enter choices:")} `);if(s===""&&n.length>0)return n;const i=s.split(",").map(a=>Number.parseInt(a.trim(),10)).filter(a=>Number.isInteger(a)&&a>=1&&a<=r.length);if(i.length>0)return i.map(a=>r[a-1]);process.stderr.write(` ${d("Invalid choice. Try again.")}
|
|
9
|
-
`)}},xe=t=>` ${d(`${t}:`)} `,Ne=(t,e)=>e.prompt??t,Oe=t=>Object.entries(t).sort(([e,r],[n,s])=>{const i=r.order??0,a=s.order??0;return i!==a?i-a:e.localeCompare(n)}),V=(t,e)=>{switch(t.type){case"array":return e.split(",").map(r=>r.trim()).filter(Boolean);case"boolean":return e==="true"||e==="1"||e==="yes"||e==="y";case"enum":return t.multiple?e.split(",").map(r=>r.trim()).filter(Boolean):e;case"number":{const r=Number(e);if(Number.isNaN(r))throw new TypeError(`Expected a number, got "${e}"`);return r}default:return e}},W=(t,e,r)=>{if(e.type==="enum"){const n=Array.isArray(r)?r:[r];for(const s of n)if(typeof s!="string"||!e.values.includes(s))throw new Error(`Variable "${t}" must be one of: ${e.values.join(", ")} (got "${String(s)}")`)}},_e=async t=>{const{defaults:e,interactive:r,overrides:n,variables:s}=t,i={},a=r?ce({input:process.stdin,output:process.stderr}):null;try{for(const[c,o]of Oe(s)){if(Object.hasOwn(n,c)){const m=V(o,n[c]??"");W(c,o,m),i[c]=m;continue}if(e||!r||o.internal){if(o.default!==void 0){W(c,o,o.default),i[c]=o.default;continue}if(o.required)throw new Error(`Required variable "${c}" not provided. Pass --${c}=<value> or remove --defaults.`);continue}const l=Ne(c,o);let u;if(o.type==="boolean")u=await Te(a,l,!!(o.default??!1));else if(o.type==="enum")if(o.multiple){const m=Array.isArray(o.default)?o.default:[];u=await Ee(a,l,o.values,m)}else{const m=typeof o.default=="string"?o.default:void 0;u=await Se(a,l,o.values,m)}else{const m=o.default===void 0?"":` (${String(o.default)})`,T=await q(a,xe(`${l}${m}`));if(T===""&&o.default!==void 0)u=o.default;else if(T===""){if(o.required)throw new Error(`Variable "${c}" is required`);continue}else u=V(o,T)}W(c,o,u),i[c]=u}return i}finally{a?.close()}},Be=["git://","npm://","https://","github:","gitlab:","bitbucket:","sourcehut:"],ke=t=>Be.some(e=>t.startsWith(e)),De=async(t,e={})=>{const r=e.targetDirectory===void 0,n=e.targetDirectory??le(S(ue(),"vis-generate-")),s=()=>{if(r)try{fe(n,{force:!0,recursive:!0})}catch{}};f.info(`Downloading ${t}…`);try{const i=await de(t,{auth:e.auth||process.env.GIGET_AUTH||process.env.GITHUB_TOKEN||process.env.GH_TOKEN||void 0,dir:n,force:!0,preferOffline:e.preferOffline});return{cleanup:s,directory:i.dir}}catch(i){s();const a=i instanceof Error?i.message:String(i);throw f.warn(`Failed to download template: ${a}`),i}},Y=(t,e="")=>{const r=[];for(const[n,s]of Object.entries(t)){const i=e?`${e}/${n}`:n;typeof s=="string"||Buffer.isBuffer(s)?r.push({content:s,path:i}):s&&typeof s=="object"&&r.push(...Y(s,i))}return r},
|
|
10
|
-
`)}}else{J(e.destination);let o=0,l=0;for(const u of c){const{file:m,meta:T,target:k}=u,b=_(k),E=e.force||T.force===!0;if(b&&!E){f.warn(`Skipped existing file: ${m.path} (use --force or set frontmatter force: true to overwrite)`),l+=1;continue}
|
|
9
|
+
`)}},xe=t=>` ${d(`${t}:`)} `,Ne=(t,e)=>e.prompt??t,Oe=t=>Object.entries(t).sort(([e,r],[n,s])=>{const i=r.order??0,a=s.order??0;return i!==a?i-a:e.localeCompare(n)}),V=(t,e)=>{switch(t.type){case"array":return e.split(",").map(r=>r.trim()).filter(Boolean);case"boolean":return e==="true"||e==="1"||e==="yes"||e==="y";case"enum":return t.multiple?e.split(",").map(r=>r.trim()).filter(Boolean):e;case"number":{const r=Number(e);if(Number.isNaN(r))throw new TypeError(`Expected a number, got "${e}"`);return r}default:return e}},W=(t,e,r)=>{if(e.type==="enum"){const n=Array.isArray(r)?r:[r];for(const s of n)if(typeof s!="string"||!e.values.includes(s))throw new Error(`Variable "${t}" must be one of: ${e.values.join(", ")} (got "${String(s)}")`)}},_e=async t=>{const{defaults:e,interactive:r,overrides:n,variables:s}=t,i={},a=r?ce({input:process.stdin,output:process.stderr}):null;try{for(const[c,o]of Oe(s)){if(Object.hasOwn(n,c)){const m=V(o,n[c]??"");W(c,o,m),i[c]=m;continue}if(e||!r||o.internal){if(o.default!==void 0){W(c,o,o.default),i[c]=o.default;continue}if(o.required)throw new Error(`Required variable "${c}" not provided. Pass --${c}=<value> or remove --defaults.`);continue}const l=Ne(c,o);let u;if(o.type==="boolean")u=await Te(a,l,!!(o.default??!1));else if(o.type==="enum")if(o.multiple){const m=Array.isArray(o.default)?o.default:[];u=await Ee(a,l,o.values,m)}else{const m=typeof o.default=="string"?o.default:void 0;u=await Se(a,l,o.values,m)}else{const m=o.default===void 0?"":` (${String(o.default)})`,T=await q(a,xe(`${l}${m}`));if(T===""&&o.default!==void 0)u=o.default;else if(T===""){if(o.required)throw new Error(`Variable "${c}" is required`);continue}else u=V(o,T)}W(c,o,u),i[c]=u}return i}finally{a?.close()}},Be=["git://","npm://","https://","github:","gitlab:","bitbucket:","sourcehut:"],ke=t=>Be.some(e=>t.startsWith(e)),De=async(t,e={})=>{const r=e.targetDirectory===void 0,n=e.targetDirectory??le(S(ue(),"vis-generate-")),s=()=>{if(r)try{fe(n,{force:!0,recursive:!0})}catch{}};f.info(`Downloading ${t}…`);try{const i=await de(t,{auth:e.auth||process.env.GIGET_AUTH||process.env.GITHUB_TOKEN||process.env.GH_TOKEN||void 0,dir:n,force:!0,preferOffline:e.preferOffline});return{cleanup:s,directory:i.dir}}catch(i){s();const a=i instanceof Error?i.message:String(i);throw f.warn(`Failed to download template: ${a}`),i}},Y=(t,e="")=>{const r=[];for(const[n,s]of Object.entries(t)){const i=e?`${e}/${n}`:n;typeof s=="string"||Buffer.isBuffer(s)?r.push({content:s,path:i}):s&&typeof s=="object"&&r.push(...Y(s,i))}return r},je=t=>t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`,Ie=(t,e)=>{if(F(e))throw new Error(`Refusing to write outside destination: template produced absolute path "${e}".`);const r=S(t,e),n=G(t,r);if(n===".."||n.startsWith(`..${oe}`)||F(n))throw new Error(`Refusing to write outside destination: "${e}" resolves to "${r}" which escapes "${t}".`);return r},Re=(t,e)=>{J(K(t)),me(t,e)},qe=(t,e,r=!1)=>{const n=typeof t=="string"?[t]:t.commands,s=typeof t=="string"?r:t.silent??r;for(const i of n){s||f.info(`$ ${i}`);const a=pe(i,{cwd:e,shell:!0,stdio:s?"ignore":"inherit"});if(a.status!==0)return f.warn(`Script failed (exit ${String(a.status)}): ${i}`),!1}return!0},Le=t=>{const e=new Map;for(const r of t){const n=typeof r=="string"?0:r.phase??0,s=e.get(n);s?s.push(r):e.set(n,[r])}return[...e.entries()].sort(([r],[n])=>r-n)},We=async(t,e)=>{const n={builtins:{dest_dir:e.destination,dest_rel_dir:G(e.workspaceRoot,e.destination)||".",working_dir:e.cwd,workspace_root:e.workspaceRoot},options:e.options},s=await t.produce(n),i=s.files?Y(s.files):[],a=s.filesMeta??{},c=[];for(const o of i){const l=Ie(e.destination,o.path);c.push({file:o,meta:a[o.path]??{},target:l})}if(e.dryRun){f.info(`${y(v("Plan"))} ${d("(dry-run, no files written)")}`);for(const o of c){const l=Buffer.isBuffer(o.file.content)?o.file.content.length:Buffer.byteLength(o.file.content,"utf8");process.stderr.write(` ${d("write")} ${o.file.path} ${d(`(${je(l)})`)}
|
|
10
|
+
`)}}else{J(e.destination);let o=0,l=0;for(const u of c){const{file:m,meta:T,target:k}=u,b=_(k),E=e.force||T.force===!0;if(b&&!E){f.warn(`Skipped existing file: ${m.path} (use --force or set frontmatter force: true to overwrite)`),l+=1;continue}Re(k,m.content),o+=1}f.success(`Wrote ${String(o)} file${o===1?"":"s"}${l>0?`, skipped ${String(l)}`:""}`)}if(!e.dryRun&&!e.skipScripts&&s.scripts&&s.scripts.length>0){const o=Le(s.scripts);f.info(`Running ${String(s.scripts.length)} script${s.scripts.length===1?"":"s"} across ${String(o.length)} phase${o.length===1?"":"s"}…`);for(const[,l]of o)if((await Promise.all(l.map(m=>Promise.resolve(qe(m,e.destination))))).includes(!1))throw new Error("Script failed — aborting.")}if(s.suggestions&&s.suggestions.length>0){process.stderr.write(`
|
|
11
11
|
`),f.notice("Next steps:");for(const o of s.suggestions)process.stderr.write(` ${d("•")} ${o}
|
|
12
12
|
`)}},Fe=async t=>{let e;try{e=(await t.load()).about?.description}catch{}return{description:e,name:t.name,path:t.path,source:t.source}},Me=(t,e)=>{const r={default:e.default,name:t,order:e.order,prompt:e.prompt,required:e.required,type:e.type};return e.type==="enum"&&(r.multiple=e.multiple,r.values=e.values),r},Ae=async t=>{const e=await t.load(),r=Object.entries(e.options??{}).sort(([n,s],[i,a])=>{const c=s.order??0,o=a.order??0;return c===o?n.localeCompare(i):c-o}).map(([n,s])=>Me(n,s));return{description:e.about?.description??"",destination:e.destination,name:t.name,path:t.path,source:t.source,variables:r}},Pe=t=>{if(t.length===0){f.info("No templates found."),f.notice("Create one at .vis/templates/<name>.ts (programmatic) or .vis/templates/<name>/ (moon-format with template.yml).");return}f.info("Available templates:");for(const e of t){const r=d(`(${e.source})`);process.stderr.write(` ${y(v(e.name))} ${r}
|
|
13
13
|
`)}},Ce=(t,e)=>{const r={},n=[];for(let s=0;s<t.length;s++){const i=t[s];if(!i.startsWith("--")){n.push(i);continue}const a=i.indexOf("=");if(a===-1){const l=i.slice(2);if(l.startsWith("no-"))r[l.slice(3)]="false";else{r[l]="true";const u=t[s+1];u!==void 0&&!u.startsWith("-")&&e?.(`\`--${l} ${u}\` was read as boolean \`--${l}=true\` and \`${u}\` was ignored. For a string value use \`--${l}=${u}\`.`)}continue}const c=i.slice(2,a),o=i.slice(a+1);r[c]=o}return{overrides:r,remaining:n}},Ue=async t=>{const{createInterface:e}=await import("node:readline"),r=e({input:process.stdin,output:process.stderr});try{process.stderr.write(` ${y(v("vis generate"))} ${d("— pick a template")}
|
|
14
14
|
|
|
15
15
|
`);for(const[n,s]of t.entries()){const i=y(v(` ${String(n+1)}.`));process.stderr.write(`${i} ${s.name} ${d(`(${s.source})`)}
|
|
16
16
|
`)}return new Promise((n,s)=>{r.question(`
|
|
17
|
-
${d(`Enter choice (1-${String(t.length)}):`)} `,i=>{const a=Number.parseInt(i.trim(),10);Number.isInteger(a)&&a>=1&&a<=t.length?n(t[a-1].name):s(new Error("Invalid choice."))})})}finally{r.close()}},Qe=async({argument:t,options:e,rawUnknown:r,visConfig:n,workspaceRoot:s})=>{const i=e.cwd||s||process.cwd(),a=s??i,c=n?.generator,o=Array.isArray(t)?t:t?[t]:[];if(e.list){const p=
|
|
18
|
-
`);return}Pe(p);return}if(e.describe){const p=o[0];if(!p)throw new Error("`--describe` requires a template name. Run `vis generate --list` to see available templates.");const w=
|
|
19
|
-
`);return}if(f.info(`Template: ${y(v(g.name))} ${d(`(${g.source})`)}`),g.description&&f.info(g.description),g.destination&&f.info(`Destination: ${d(g.destination)}`),g.variables.length===0)f.info("No variables.");else{f.info("Variables:");for(const $ of g.variables){const
|
|
20
|
-
`)}}return}let l=[...r??[]];if(l.length===0){const p=process.argv.slice(2),h=p.indexOf("--");h!==-1&&(l=p.slice(h+1))}const u=o.indexOf("--"),m=u===-1?[]:o.slice(u+1),T=u===-1?o:o.slice(0,u),{overrides:k}=Ce([...m,...l],p=>{f.warn(p)});let b,E,D;const N=T[0];let L;if(N&&ke(N)){const p=await De(N,{auth:c?.auth,preferOffline:!!e.preferOffline||c?.preferOffline});L=p.cleanup;try{const w=
|
|
17
|
+
${d(`Enter choice (1-${String(t.length)}):`)} `,i=>{const a=Number.parseInt(i.trim(),10);Number.isInteger(a)&&a>=1&&a<=t.length?n(t[a-1].name):s(new Error("Invalid choice."))})})}finally{r.close()}},Qe=async({argument:t,options:e,rawUnknown:r,visConfig:n,workspaceRoot:s})=>{const i=e.cwd||s||process.cwd(),a=s??i,c=n?.generator,o=Array.isArray(t)?t:t?[t]:[];if(e.list){const p=R({extraDirectories:c?.templates??[],onWarning:h=>{f.warn(h)},workspaceRoot:a});if(e.json){const h=await Promise.all(p.map(w=>Fe(w)));process.stdout.write(`${JSON.stringify(h,null,2)}
|
|
18
|
+
`);return}Pe(p);return}if(e.describe){const p=o[0];if(!p)throw new Error("`--describe` requires a template name. Run `vis generate --list` to see available templates.");const w=R({extraDirectories:c?.templates??[],onWarning:$=>{f.warn($)},workspaceRoot:a}).find($=>$.name===p);if(!w)throw new Error(`Template "${p}" not found. Run \`vis generate --list\` to see available templates.`);const g=await Ae(w);if(e.json){process.stdout.write(`${JSON.stringify(g,null,2)}
|
|
19
|
+
`);return}if(f.info(`Template: ${y(v(g.name))} ${d(`(${g.source})`)}`),g.description&&f.info(g.description),g.destination&&f.info(`Destination: ${d(g.destination)}`),g.variables.length===0)f.info("No variables.");else{f.info("Variables:");for(const $ of g.variables){const j=[$.type];$.required&&j.push("required"),$.default!==void 0&&j.push(`default=${JSON.stringify($.default)}`),$.values&&j.push(`values=${$.values.join("|")}`),process.stderr.write(` ${y(v($.name))} ${d(`(${j.join(", ")})`)}
|
|
20
|
+
`)}}return}let l=[...r??[]];if(l.length===0){const p=process.argv.slice(2),h=p.indexOf("--");h!==-1&&(l=p.slice(h+1))}const u=o.indexOf("--"),m=u===-1?[]:o.slice(u+1),T=u===-1?o:o.slice(0,u),{overrides:k}=Ce([...m,...l],p=>{f.warn(p)});let b,E,D;const N=T[0];let L;if(N&&ke(N)){const p=await De(N,{auth:c?.auth,preferOffline:!!e.preferOffline||c?.preferOffline});L=p.cleanup;try{const w=R({extraDirectories:[p.directory],workspaceRoot:a}).find(g=>g.path.startsWith(p.directory));if(!w)throw new Error(`Downloaded template at ${p.directory} contains no template.yml or *.ts entrypoint.`);b=await w.load(),E=w.name,D=b.destination}catch(h){throw L(),h}}else{const p=R({extraDirectories:c?.templates??[],onWarning:g=>{f.warn(g)},workspaceRoot:a});if(p.length===0)throw new Error("No templates found. Create one at .vis/templates/<name>.ts or .vis/templates/<name>/template.yml.");let h;if(N)h=N;else{if(e.interactive===!1||!process.stdin.isTTY)throw new Error("No template specified. Pass a template name (see `vis generate --list`) or run interactively in a terminal.");h=await Ue(p)}const w=p.find(g=>g.name===h);if(!w)throw new Error(`Template "${h}" not found. Run 'vis generate --list' to see available templates.`);b=await w.load(),E=w.name,D=b.destination}const M=e.to,A=!!e.dryRun,Q=!!e.force,P=!!e.defaults,Z=!!e.skipScripts,ee=e.interactive!==!1&&!!process.stdin.isTTY&&!P;let x;M?x=M:D?x=D:x=".";const C=F(x)?x:ie(i,x);f.info(`Template: ${y(v(E))}`),f.info(`Target: ${d(C)}`),process.stderr.write(`
|
|
21
21
|
`);const te=await _e({defaults:P,interactive:ee,overrides:k,variables:b.options??{}});try{await We(b,{cwd:i,destination:C,dryRun:A,force:Q,options:te,skipScripts:Z,workspaceRoot:a}),A||(process.stderr.write(`
|
|
22
22
|
`),f.success(`Template '${E}' applied.`))}finally{L?.()}};export{Qe as default};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{z as A,m as G,a as I,e as b}from"../packem_shared/index-DHD8wb6Z.js";import x from"./index.js";import{d as U,x as F}from"./catalog.js";import{n as B}from"../packem_shared/manifests-BNSmpPF_.js";import{_ as E,$ as J}from"./cli-main.js";import{l as K}from"../packem_shared/glob-Cyk1H9ZL-ox19CSsT.js";import{U as R,h as q}from"../packem_shared/writeFileSync-DJoHk3Ks-CgQ-VNNT.js";import{T as M}from"../packem_shared/target-merge-
|
|
1
|
+
import{z as A,m as G,a as I,e as b}from"../packem_shared/index-DHD8wb6Z.js";import x from"./index.js";import{d as U,x as F}from"./catalog.js";import{n as B}from"../packem_shared/manifests-BNSmpPF_.js";import{_ as E,$ as J}from"./cli-main.js";import{l as K}from"../packem_shared/glob-Cyk1H9ZL-ox19CSsT.js";import{U as R,h as q}from"../packem_shared/writeFileSync-DJoHk3Ks-CgQ-VNNT.js";import{T as M}from"../packem_shared/target-merge-B4No-LHM.js";const H=(e,t)=>{const n=t.replace(/^\.?\//,"");return n===""||n==="."?`/${e}/`:e===""||e==="."?`/${n}`:`/${e}/${n}`},N=(e,t,n=[])=>{const s=[],o=new Set;for(const[c,r]of Object.entries(t?.globalPaths??{}))s.push({owners:r,path:c,source:"project-json"}),o.add(c);for(const[c,r]of Object.entries(e.projects)){const a=r.owners??[];for(const f of a){const l=H(r.root??c,f.path);s.push({channel:f.channel,owners:f.owners,path:l,projectId:c,source:"project-json"}),o.add(l)}}for(const c of n)o.has(c.path)||(s.push(c),o.add(c.path));return(t?.orderBy??"file-source")==="project-id"?s.sort((c,r)=>(c.projectId??"").localeCompare(r.projectId??"")||c.path.localeCompare(r.path)):s.sort((c,r)=>c.path.localeCompare(r.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}`,""],D=e=>{const t=[];for(const n of e){const s=n.owners.join(" "),o=n.channel?` # notify: ${n.channel}`:"";t.push(`${n.path} ${s}${o}`)}return t},Q=(e,t={})=>[...Y(t.regenerationCommand),...D(e),""].join(`
|
|
2
2
|
`),O={begin:"# BEGIN vis-codeowners",end:"# END vis-codeowners"},X=(e,t=O,n={})=>{const s=n.regenerationCommand?`# Generated by vis sync codeowners — re-run with: ${n.regenerationCommand}`:"# Generated by `vis sync codeowners` — do not edit by hand.";return[t.begin,s,...D(e),t.end].join(`
|
|
3
3
|
`)},Z=(e,t,n=O)=>{const s=e.indexOf(n.begin),o=e.indexOf(n.end);if(s!==-1&&o!==-1&&o>s){const r=e.slice(0,s),a=o+n.end.length,f=e.slice(a);return`${r}${t}${f}`}const i=e.replace(/\s+$/u,"");return`${i.length===0?"":`${i}
|
|
4
4
|
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as G}from"node:module";import{J as q,
|
|
1
|
+
import{createRequire as G}from"node:module";import{J as q,j as X,F as E,X as B,b as L,q as Z}from"../packem_shared/index.server-BAjDJSEu.js";import{a as J}from"../packem_shared/index-DHD8wb6Z.js";import{Z as Q}from"./cli-main.js";import{d as k,f as b,r as ee,a as ne,b as te,s as re,c as ie,e as se,g as ae,u as oe,v as le,w as ce,k as de,l as ue,m as fe,n as ge,o as me,p as pe,t as he,q as xe}from"../packem_shared/watch-loop-COWvvSbR.js";import{T as c}from"./catalog.js";let H;const U=e=>(H??=G(import.meta.url))(e),v=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,z=e=>{if(typeof v<"u"&&v.versions&&v.versions.node){const[n,t]=v.versions.node.split(".").map(Number);if(n>22||n===22&&t>=3||n===20&&t>=16)return v.getBuiltinModule(e)}return U(e)},{createHash:y}=z("node:crypto"),we={1:"warning",2:"error"},ve={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]),r=b(e,c.eslint.configFiles);if(!(!t&&!r))return{adapter:"eslint",configFile:r,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 r=[];for(const i of t)for(const s of i.messages)r.push({adapter:"eslint",column:s.column,endColumn:s.endColumn,endLine:s.endLine,file:i.filePath,fixable:!!s.fix,line:s.line,message:s.message,ruleId:s.ruleId??void 0,severity:s.fatal?"error":we[s.severity]??"warning"});return r}},V=(e,n,t)=>{const r=["--format","json","--no-error-on-unmatched-pattern"];return t&&r.push("--fix"),n.quiet&&r.push("--quiet"),typeof n.maxWarnings=="number"&&r.push("--max-warnings",String(n.maxWarnings)),n.extraArgs?.length&&r.push(...n.extraArgs),r.push(...e),r},ke=/^([^:]+):(\d+)(?::(\d+))?\s+([\w/-]+)\s+(.+)$/,be=e=>{const n=ke.exec(e);if(!n)return;const[,t,r,i,s,o]=n;return{column:i===void 0?void 0:Number(i),file:t,line:Number(r),message:o,ruleId:s}},ye=e=>e.startsWith("/")||/^[a-z]:[\\/]/i.test(e),Ae={argsCheck:(e,n)=>M(e,n,!1),argsFix:(e,n)=>M(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(i=>k(n,i)).find(i=>i!==void 0),r=b(e,c.markdownlint.configFiles);if(!(!t&&!r))return{adapter:"markdownlint",configFile:r,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 r=[];for(const i of t.split(/\r?\n/)){const s=be(i.trim());s&&r.push({adapter:"markdownlint",column:s.column,file:ye(s.file)?s.file:`${n.root}/${s.file}`,fixable:!0,line:s.line,message:s.message,ruleId:s.ruleId,severity:"warning"})}return r}},M=(e,n,t)=>{const r=[];return t&&r.push("--fix"),n.extraArgs?.length&&r.push(...n.extraArgs),e.length===0?r.push("**/*.md"):r.push(...e),r},$e={advice:"info",error:"error",warning:"warning"},Ce={argsCheck:(e,n)=>O(e,n,!1),argsFix:(e,n)=>O(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]),r=b(e,c.oxlint.configFiles);if(!(!t&&!r))return{adapter:"oxlint",configFile:r,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 r=[];for(const i of t.diagnostics??[]){const s=i.labels?.[0]?.span;r.push({adapter:"oxlint",column:s?.column,file:i.filename??n.root,fixable:!1,line:s?.line,message:i.message??"",ruleId:i.code,severity:$e[i.severity??""]??"warning"})}return r}},O=(e,n,t)=>{const r=["--format","json"];return t&&r.push("--fix"),n.quiet&&r.push("--quiet"),typeof n.maxWarnings=="number"&&r.push(`--max-warnings=${String(n.maxWarnings)}`),n.extraArgs?.length&&r.push(...n.extraArgs),r.push(...e),r},Fe={error:"error",info:"info",style:"info",warning:"warning"},Se=e=>e.startsWith("/")||/^[a-z]:[\\/]/i.test(e),je=(e,n)=>e?Se(e)?e:`${n}/${e}`:n,qe={argsCheck:(e,n)=>T(e,n),argsFix:(e,n)=>T(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]),r=b(e,c.shellcheck.configFiles);if(!(!t&&!r))return{adapter:"shellcheck",configFile:r,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 r=[];for(const i of t.comments??[])r.push({adapter:"shellcheck",column:i.column,endColumn:i.endColumn,endLine:i.endLine,file:je(i.file,n.root),fixable:!!i.fix,line:i.line,message:i.message??"",ruleId:i.code===void 0?void 0:`SC${String(i.code)}`,severity:Fe[i.level??""]??"warning"});return r}},T=(e,n)=>{const t=["--format=json1"];return n.extraArgs?.length&&t.push(...n.extraArgs),t.push(...e),t},Ne={error:"error",warning:"warning"},_e={argsCheck:(e,n)=>P(e,n,!1),argsFix:(e,n)=>P(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]),r=b(e,c.stylelint.configFiles);if(!(!t&&!r))return{adapter:"stylelint",configFile:r,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 r=[];for(const i of t)for(const s of i.warnings??[])r.push({adapter:"stylelint",column:s.column,endColumn:s.endColumn,endLine:s.endLine,file:i.source,fixable:!1,line:s.line,message:s.text??"",ruleId:s.rule,severity:Ne[s.severity??""]??"warning"});return r}},P=(e,n,t)=>{const r=["--formatter","json"];return t&&r.push("--fix"),n.quiet&&r.push("--quiet"),typeof n.maxWarnings=="number"&&r.push("--max-warnings",String(n.maxWarnings)),n.extraArgs?.length&&r.push(...n.extraArgs),r.push(...e),r},We=[Ce,ae,ve,_e,oe,Ae,qe,le],Ke=async({logger:e,options:n,visConfig:t,workspaceRoot:r})=>{const i=r??process.cwd(),s=t?.lint,o=ee(We,s?.order),F=ne(i,o),p=te(F,o,"lint").filter(({adapter:l})=>s?.adapters?.[l.id]?.enabled!==!1);if(p.length===0){e.warn("vis lint: no linter detected in this workspace (looked for: oxlint, biome, eslint, stylelint, ruff, markdownlint, shellcheck, deno).");return}const S=l=>{const d=s?.adapters?.[l]?.extraArgs;return d&&d.length>0?[...d]:void 0},A={extraArgs:void 0,maxWarnings:typeof n.maxWarnings=="number"?n.maxWarnings:void 0,quiet:n.quiet??!1},N=Ie(n),K=n.fix?"fix":"check";let u;if(n.staged){if(u=re(i),u===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(u.length===0){e.info(q("✓ lint: no staged files"));return}}else if(typeof n.since=="string"&&n.since.length>0){if(u=ie(i,n.since),u===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(u.length===0){e.info(q(`✓ lint: no files changed since ${n.since}`));return}}const _=N.length>0?N:void 0,Y=Q(i,void 0,void 0,!0),j=n.format??"human";j==="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 W=async l=>{const d=l!==void 0&&l.length>0&&_===void 0,h=[];for(const{adapter:a,presence:w}of p){let f;if(d){if(f=ce(l,a.extensions),f.length===0)continue}else f=_??l??["."];const C=S(a.id),R={adapter:a,files:f,presence:w};C&&(R.options={...A,extraArgs:C}),h.push(R)}if(h.length===0)return;const D=await de(h,A,K,{cacheRoot:Y}),$=h.map((a,w)=>{const f=D[w],C=a.adapter.parse(f,a.presence);return{adapter:a.adapter,durationMs:f.durationMs,exitCode:f.exitCode,findings:C}}),x=ue($.map(a=>({adapter:a.adapter.id,durationMs:a.durationMs,exitCode:a.exitCode,findingCount:a.findings.length,findings:a.findings}))),m=j==="human"?void 0:fe({cwd:i,target:n.output});try{switch(j){case"github":{m.write(pe({runs:$.map(a=>({findings:a.findings})),workspaceRoot:i}));break}case"json":{m.write(`${JSON.stringify({findings:x.findings,runs:x.runs},null,2)}
|
|
2
2
|
`);break}case"junit":{m.write(me({runs:$.map(a=>({adapter:a.adapter.id,durationMs:a.durationMs,findings:a.findings})),workspaceRoot:i}));break}case"minimal":{Ee(x.findings,i,m);break}case"sarif":{m.write(ge({runs:$.map(a=>({adapter:a.adapter.id,findings:a.findings,presence:h.find(w=>w.adapter.id===a.adapter.id)?.presence})),workspaceRoot:i}));break}default:Re(x.findings,i,e)}}finally{m?.close()}const I=xe(x);I!==0&&(process.exitCode=I)};if(n.watch){const l=[...new Set(p.flatMap(({adapter:d})=>d.extensions))];await se({extensions:l,initialFiles:u,label:"lint",log:d=>{e.info(d)},runCycle:W,workspaceRoot:i});return}await W(u)},Ie=e=>{const n=e;return[...n._??n.args??[]]},Re=(e,n,t)=>{if(e.length===0){t.info(q("✓ lint: no findings"));return}const r=he(e);for(const[o,F]of r){t.info(X(J(n,o)));for(const g of F){const p=Ve(g),S=Me(g.severity),A=g.ruleId?E(` ${g.ruleId}`):"";t.info(` ${E(p)} ${S} ${g.message}${A}`)}}const i=e.filter(o=>o.severity==="error").length,s=e.filter(o=>o.severity==="warning").length;t.info(""),t.info(`${B(`${String(i)} error${i===1?"":"s"}`)}, ${L(`${String(s)} warning${s===1?"":"s"}`)}`)},Ee=(e,n,t)=>{for(const r of e){const i=J(n,r.file),s=r.line??"",o=r.column??"";t.write(`${r.adapter} ${i} ${String(s)} ${String(o)} ${r.severity} ${r.ruleId??""} ${r.message}
|
|
3
3
|
`)}},Ve=e=>e.line===void 0?"":e.column===void 0?String(e.line):`${String(e.line)}:${String(e.column)}`,Me=e=>e==="error"?B("error"):e==="warning"?L("warn "):Z("info ");export{Ke as default};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{a as B,z as J,e as C,$ as K,U as Y}from"../packem_shared/index-DHD8wb6Z.js";import{U as q,V,W as z,T as Z,u as Q,p as E,C as ee}from"./cli-main.js";import{i as re}from"../packem_shared/index-BjdW45xX.js";import{y as t,X as f,m as a,u as R,R as te,v as se,A as ne,B as oe,C as ie,i as ce,j as A}from"./catalog.js";import le from"./index.js";import{sortPackageJsonStringWithOptions as U}from"#native";import{e as I}from"../packem_shared/utils-DQFHJn72.js";import{y as L}from"../packem_shared/isAccessibleSync-DYKTrrvc-CSnBISfV.js";const _={error:0,rewritten:1,"would-rewrite":1,unchanged:2},ae=e=>[...e].sort((r,s)=>_[r.status]-_[s.status]),de=(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:ae(r),filterType:"all",focusedPanel:"list",selectedIndex:0}}getSnapshot=()=>this.#e;subscribe=r=>(this.#r.add(r),()=>{this.#r.delete(r)});getFilteredEntries=()=>de(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 ue=({checkMode:e,entry:r,focused:s,scrollRef:c})=>{const o=s?"white":"gray";return r?t.jsxs(f,{borderColor:o,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[t.jsx(f,{flexShrink:0,paddingTop:1,paddingX:2,children:t.jsx(a,{bold:!0,color:"white",children:r.relativePath})}),t.jsxs(q,{flexGrow:1,flexShrink:1,paddingX:2,ref:c,scrollbar:!0,scrollbarColor:"gray",children:[t.jsx(a,{}),t.jsxs(f,{children:[t.jsx(f,{width:10,children:t.jsx(a,{dimColor:!0,children:"Status:"})}),r.status==="error"?t.jsx(a,{bold:!0,color:"red",children:"error"}):r.status==="unchanged"?t.jsx(a,{bold:!0,color:"green",children:"already sorted"}):r.status==="rewritten"?t.jsx(a,{bold:!0,color:"yellow",children:"rewritten"}):t.jsx(a,{bold:!0,color:"yellow",children:"would rewrite (--check)"})]}),t.jsxs(f,{children:[t.jsx(f,{width:10,children:t.jsx(a,{dimColor:!0,children:"Path:"})}),t.jsx(a,{children:r.filePath})]}),r.error?t.jsxs(t.Fragment,{children:[t.jsxs(f,{flexDirection:"column",marginTop:1,children:[t.jsx(a,{dimColor:!0,children:"── "}),t.jsx(a,{bold:!0,color:"red",children:"ERROR"}),t.jsxs(f,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[t.jsxs(f,{children:[t.jsx(f,{width:10,children:t.jsx(a,{dimColor:!0,children:"Step:"})}),t.jsx(a,{color:"yellow",children:r.error.step})]}),r.error.context&&t.jsxs(f,{children:[t.jsx(f,{width:10,children:t.jsx(a,{dimColor:!0,children:"Position:"})}),t.jsx(a,{children:`line ${String(r.error.context.line)}, column ${String(r.error.context.column)}`})]}),t.jsx(f,{marginTop:1,children:t.jsx(a,{color:"red",children:r.error.message})})]})]}),r.error.context&&r.error.context.snippet.length>0&&t.jsxs(f,{flexDirection:"column",marginTop:1,children:[t.jsx(a,{dimColor:!0,children:"── "}),t.jsx(a,{bold:!0,color:"white",children:"SNIPPET"}),t.jsxs(f,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[r.error.context.snippet.map(n=>{const i=`${n.isErrorLine?"❯":" "} ${String(n.lineNumber).padStart(4)} `;return t.jsxs(f,{children:[t.jsx(a,{color:n.isErrorLine?"red":"gray",children:i}),t.jsx(a,{color:n.isErrorLine?"white":"gray",wrap:"truncate-end",children:n.content||" "})]},n.lineNumber)}),r.error.context.column>0&&t.jsx(f,{children:t.jsx(a,{color:"red",children:`${" ".repeat(7+r.error.context.column-1)}↑`})})]})]})]}):t.jsxs(f,{flexDirection:"column",marginTop:1,children:[t.jsx(a,{dimColor:!0,children:"── "}),t.jsx(a,{bold:!0,color:"white",children:"KEY DIFF"}),t.jsx(f,{flexDirection:"column",marginTop:1,paddingLeft:2,children:r.diff.length===0?t.jsx(a,{dimColor:!0,children:"No top-level keys moved (sub-key reorder only)."}):r.diff.map(n=>{const i=n.toIndex-n.fromIndex,d=i<0?`↑ ${String(Math.abs(i))}`:`↓ ${String(i)}`,u=i<0?"green":"yellow";return t.jsxs(f,{children:[t.jsx(f,{width:28,children:t.jsx(a,{wrap:"truncate",children:n.key})}),t.jsx(f,{width:10,children:t.jsxs(a,{dimColor:!0,children:[String(n.fromIndex)," → ",String(n.toIndex)]})}),t.jsx(a,{color:u,children:d})]},n.key)})}),e&&r.status==="would-rewrite"&&t.jsx(f,{marginTop:1,paddingLeft:2,children:t.jsx(a,{dimColor:!0,children:"--check mode: no write performed."})})]})]})]}):t.jsx(f,{alignItems:"center",borderColor:"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,justifyContent:"center",children:t.jsx(a,{dimColor:!0,children:"No entry selected"})})},he={error:"red",rewritten:"yellow",unchanged:"green","would-rewrite":"yellow"},ge={error:"ERROR",rewritten:"REWROTE",unchanged:"SORTED","would-rewrite":"REWRITE"},W={error:"errors",rewritten:"rewrites",unchanged:"sorted","would-rewrite":"rewrites"},xe={errors:"Errors",rewrites:"Rewrites",sorted:"Sorted"},pe=[{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[W[s.status]]++;return r},me=({entry:e,isSelected:r})=>{const s=he[e.status],c=ge[e.status];return t.jsxs(f,{flexShrink:0,height:1,children:[t.jsx(a,{children:r?">":" "}),t.jsx(a,{children:" "}),t.jsx(a,{bold:!0,color:s,children:`[${c}]`.padEnd(10)}),t.jsx(a,{children:" "}),t.jsx(f,{flexGrow:1,children:t.jsx(a,{bold:r,inverse:r,wrap:"truncate",children:e.relativePath})}),e.status!=="error"&&e.diff.length>0&&t.jsx(a,{dimColor:!0,children:` ${String(e.diff.length)} key${e.diff.length===1?"":"s"}`})]})},je=({color:e,count:r,label:s})=>t.jsx(f,{flexShrink:0,height:1,children:t.jsx(a,{bold:!0,color:e,children:`${s} (${String(r)})`})}),Se=({counts:e,entries:r,filterType:s,focused:c,selectedIndex:o,totalEntries:n,viewportHeight:i})=>{const d=c?"white":"gray",u=X(r),x=(u.errors>0?1:0)+(u.rewrites>0?1:0)+(u.sorted>0?1:0),m=s==="all"&&x>1,h=[];let j;for(const[l,g]of r.entries()){const k=W[g.status];m&&k!==j&&(j!==void 0&&h.push({kind:"spacer"}),h.push({color:k==="errors"?"red":k==="rewrites"?"yellow":"green",count:u[k],kind:"header",label:xe[k]}),j=k),h.push({entry:g,entryIndex:l,kind:"entry"})}const p=h.findIndex(l=>l.kind==="entry"&&l.entryIndex===o),y=p!==-1,S=h.length,w=Math.max(0,S-i);let b=0;y&&i>0&&(b=Math.min(w,Math.max(0,p-i+1)));const O=S>i&&i>0;return t.jsxs(f,{borderColor:d,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[t.jsxs(f,{flexShrink:0,gap:1,paddingX:1,children:[t.jsx(a,{bold:!0,inverse:!0,children:" VIS SORT "}),t.jsxs(a,{wrap:"truncate",children:[n," ","file",n===1?"":"s"]})]}),t.jsx(f,{flexShrink:0,gap:1,paddingX:1,paddingY:1,children:pe.map(l=>{const g=s===l.key,k=l.count(e);return t.jsxs(f,{children:[t.jsx(a,{dimColor:!g,children:"["}),t.jsx(a,{bold:g,color:g?"cyan":"gray",children:l.shortcut}),t.jsx(a,{dimColor:!g,children:"]"}),t.jsxs(a,{color:g?"white":"gray",children:[" ",l.label]}),t.jsxs(a,{dimColor:!0,children:[" ","(",k,")"]})]},l.key)})}),t.jsxs(f,{flexDirection:"row",flexGrow:1,overflow:"hidden",children:[t.jsx(f,{flexDirection:"column",flexGrow:1,overflow:"hidden",paddingLeft:1,children:t.jsx(f,{flexDirection:"column",marginTop:-b,children:h.map((l,g)=>l.kind==="spacer"?t.jsx(f,{flexShrink:0,height:1},`s-${String(g)}`):l.kind==="header"?t.jsx(je,{color:l.color,count:l.count,label:l.label},`h-${l.label}`):t.jsx(me,{entry:l.entry,isSelected:l.entryIndex===o},l.entry.filePath))})}),O&&t.jsx(f,{flexShrink:0,marginLeft:1,marginRight:1,children:t.jsx(V,{contentHeight:S,placement:"inset",scrollOffset:b,style:"block",viewportHeight:i})})]})]})},we=100,D=10,ye=6,ke=1,M={1:"all",2:"rewritten",3:"errors",4:"unchanged"},Ee=({checkMode:e,store:r})=>{const{exit:s}=z(),{columns:c,rows:o}=Z(),n=R.useSyncExternalStore(r.subscribe,r.getSnapshot),i=R.useRef(null),d=r.getFilteredEntries(),u=d[n.selectedIndex]??null,x=X(n.entries),m=c>=we,h=Math.max(0,o-ke),j=m?h:Math.floor(h/2),p=Math.max(0,j-ye),y=R.useCallback(()=>{s()},[s]),S=R.useRef(0),w=R.useRef(void 0),b=R.useRef(!1),O=R.useCallback((l,g)=>{S.current+=g,w.current=l,!b.current&&(b.current=!0,queueMicrotask(()=>{b.current=!1;const k=S.current,N=w.current;S.current=0,w.current=void 0,!(k===0||N===void 0)&&(N==="list"?r.selectStep(Math.sign(k)):i.current?.scrollBy(Math.sign(k)))}))},[r]);return Q((l,g)=>{if(l==="q"||g.escape){y();return}if(M[l]){r.setFilter(M[l]);return}if(g.tab){r.setFocusedPanel(n.focusedPanel==="list"?"detail":"list");return}n.focusedPanel==="list"?g.upArrow||l==="k"?O("list",-1):(g.downArrow||l==="j")&&O("list",1):n.focusedPanel==="detail"&&(g.upArrow||l==="k"?O("detail",-1):(g.downArrow||l==="j")&&O("detail",1))}),o<D?t.jsx(f,{alignItems:"center",justifyContent:"center",children:t.jsxs(a,{color:"yellow",children:["Terminal too small. Resize to at least",D," ","rows."]})}):t.jsxs(f,{flexDirection:"column",height:o,width:c,children:[t.jsxs(f,{flexDirection:m?"row":"column",flexGrow:1,children:[t.jsx(f,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:t.jsx(Se,{counts:x,entries:d,filterType:n.filterType,focused:n.focusedPanel==="list",selectedIndex:n.selectedIndex,totalEntries:n.entries.length,viewportHeight:p})}),t.jsx(f,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:t.jsx(ue,{checkMode:e,entry:u,focused:n.focusedPanel==="detail",scrollRef:i})})]}),t.jsx(f,{flexShrink:0,paddingX:1,children:t.jsx(a,{dimColor:!0,children:"↑/↓ or j/k:navigate | tab:switch panel | 1-4:filter | q:quit"})})]})},F=["types","node-addons","node","import","require","default"],be=/^git\+https:\/\/github\.com\/([^/]+)\/([^/.]+(?:\.git)?)$/,Oe=/^git\+ssh:\/\/git@github\.com\/([^/]+)\/([^/.]+(?:\.git)?)$/,T=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$=e=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(s=>$(s));const r={};for(const[s,c]of Object.entries(e))r[s]=$(c);return r},Re=e=>{if(!T(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}},Ce=e=>e.endsWith(".git")?e.slice(0,-4):e,Ie=e=>{if(!T(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 c=be.exec(s)??Oe.exec(s);if(!c)return{changed:!1,value:e};const o=c[1],n=Ce(c[2]??"");if(!o||!n)return{changed:!1,value:e};const i=new Set(["type","url"]);for(const d of Object.keys(e))if(!i.has(d))return{changed:!1,value:e};return{changed:!0,value:`${o}/${n}`}},Te=e=>{const r=Object.keys(e),s=[],c=[];for(const d of F)Object.hasOwn(e,d)&&s.push(d);for(const d of r)F.includes(d)||c.push(d);const o=[...s,...c];if(o.length===r.length&&o.every((d,u)=>d===r[u]))return{changed:!1,value:e};const i={};for(const d of o)i[d]=e[d];return{changed:!0,value:i}},H=e=>{if(!T(e))return{changed:!1,value:e};let r=!1;const s={};for(const[o,n]of Object.entries(e)){const i=H(n);s[o]=i.value,i.changed&&(r=!0)}const c=Te(s);return{changed:r||c.changed,value:c.value}},Pe=(e,r)=>{const s=$(e);let c=!1;if(r.formatBugs!==!1&&Object.hasOwn(s,"bugs")){const o=Re(s.bugs);o.changed&&(s.bugs=o.value,c=!0)}if(r.formatRepository!==!1&&Object.hasOwn(s,"repository")){const o=Ie(s.repository);o.changed&&(s.repository=o.value,c=!0)}if(r.sortExports!==!1&&Object.hasOwn(s,"exports")&&T(s.exports)){const o=H(s.exports);o.changed&&(s.exports=o.value,c=!0)}return{changed:c,pkg:s}},$e=/at position (\d+)/,Ne=/\(?line (\d+) column (\d+)\)?/,Ae=e=>{const r=new Set,s=[],c=n=>{const i=Y(n);!r.has(i)&&L(i)&&(r.add(i),s.push(i))};c(C(e,"package.json"));const o=ce(e);if(o){const n=A(e,o);for(const i of n)c(C(e,i,"package.json"))}else{const n=C(e,"package.json");if(L(n)){const i=JSON.parse(J(n)),d=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;if(d){const u=A(e,d);for(const x of u)c(C(e,x,"package.json"))}}}return s},Le=e=>/\n([ \t]+)/.exec(e)?.[1]??" ",_e=e=>{if(!(e===void 0||e===""))return e==="tab"||e===String.raw`\t`?" ":/^\d+$/.test(e)?" ".repeat(Number.parseInt(e,10)):e},P=e=>e===void 0?[]:(Array.isArray(e)?e:[e]).flatMap(s=>s.split(",")).map(s=>s.trim()).filter(s=>s.length>0),De=e=>e.includes(`\r
|
|
1
|
+
import{a as B,z as J,e as I,$ as K,U as Y}from"../packem_shared/index-DHD8wb6Z.js";import{U as q,V,W as z,T as Z,v as Q,p as E,d as ee}from"./cli-main.js";import{i as re}from"../packem_shared/index-BjdW45xX.js";import{y as t,X as f,m as a,u as R,R as te,v as se,A as ne,B as oe,C as ie,i as ce,j as A}from"./catalog.js";import le from"./index.js";import{sortPackageJsonStringWithOptions as U}from"#native";import{e as C}from"../packem_shared/utils-DQFHJn72.js";import{y as L}from"../packem_shared/isAccessibleSync-DYKTrrvc-CSnBISfV.js";const _={error:0,rewritten:1,"would-rewrite":1,unchanged:2},ae=e=>[...e].sort((r,s)=>_[r.status]-_[s.status]),de=(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:ae(r),filterType:"all",focusedPanel:"list",selectedIndex:0}}getSnapshot=()=>this.#e;subscribe=r=>(this.#r.add(r),()=>{this.#r.delete(r)});getFilteredEntries=()=>de(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 ue=({checkMode:e,entry:r,focused:s,scrollRef:c})=>{const o=s?"white":"gray";return r?t.jsxs(f,{borderColor:o,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[t.jsx(f,{flexShrink:0,paddingTop:1,paddingX:2,children:t.jsx(a,{bold:!0,color:"white",children:r.relativePath})}),t.jsxs(q,{flexGrow:1,flexShrink:1,paddingX:2,ref:c,scrollbar:!0,scrollbarColor:"gray",children:[t.jsx(a,{}),t.jsxs(f,{children:[t.jsx(f,{width:10,children:t.jsx(a,{dimColor:!0,children:"Status:"})}),r.status==="error"?t.jsx(a,{bold:!0,color:"red",children:"error"}):r.status==="unchanged"?t.jsx(a,{bold:!0,color:"green",children:"already sorted"}):r.status==="rewritten"?t.jsx(a,{bold:!0,color:"yellow",children:"rewritten"}):t.jsx(a,{bold:!0,color:"yellow",children:"would rewrite (--check)"})]}),t.jsxs(f,{children:[t.jsx(f,{width:10,children:t.jsx(a,{dimColor:!0,children:"Path:"})}),t.jsx(a,{children:r.filePath})]}),r.error?t.jsxs(t.Fragment,{children:[t.jsxs(f,{flexDirection:"column",marginTop:1,children:[t.jsx(a,{dimColor:!0,children:"── "}),t.jsx(a,{bold:!0,color:"red",children:"ERROR"}),t.jsxs(f,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[t.jsxs(f,{children:[t.jsx(f,{width:10,children:t.jsx(a,{dimColor:!0,children:"Step:"})}),t.jsx(a,{color:"yellow",children:r.error.step})]}),r.error.context&&t.jsxs(f,{children:[t.jsx(f,{width:10,children:t.jsx(a,{dimColor:!0,children:"Position:"})}),t.jsx(a,{children:`line ${String(r.error.context.line)}, column ${String(r.error.context.column)}`})]}),t.jsx(f,{marginTop:1,children:t.jsx(a,{color:"red",children:r.error.message})})]})]}),r.error.context&&r.error.context.snippet.length>0&&t.jsxs(f,{flexDirection:"column",marginTop:1,children:[t.jsx(a,{dimColor:!0,children:"── "}),t.jsx(a,{bold:!0,color:"white",children:"SNIPPET"}),t.jsxs(f,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[r.error.context.snippet.map(n=>{const i=`${n.isErrorLine?"❯":" "} ${String(n.lineNumber).padStart(4)} `;return t.jsxs(f,{children:[t.jsx(a,{color:n.isErrorLine?"red":"gray",children:i}),t.jsx(a,{color:n.isErrorLine?"white":"gray",wrap:"truncate-end",children:n.content||" "})]},n.lineNumber)}),r.error.context.column>0&&t.jsx(f,{children:t.jsx(a,{color:"red",children:`${" ".repeat(7+r.error.context.column-1)}↑`})})]})]})]}):t.jsxs(f,{flexDirection:"column",marginTop:1,children:[t.jsx(a,{dimColor:!0,children:"── "}),t.jsx(a,{bold:!0,color:"white",children:"KEY DIFF"}),t.jsx(f,{flexDirection:"column",marginTop:1,paddingLeft:2,children:r.diff.length===0?t.jsx(a,{dimColor:!0,children:"No top-level keys moved (sub-key reorder only)."}):r.diff.map(n=>{const i=n.toIndex-n.fromIndex,d=i<0?`↑ ${String(Math.abs(i))}`:`↓ ${String(i)}`,u=i<0?"green":"yellow";return t.jsxs(f,{children:[t.jsx(f,{width:28,children:t.jsx(a,{wrap:"truncate",children:n.key})}),t.jsx(f,{width:10,children:t.jsxs(a,{dimColor:!0,children:[String(n.fromIndex)," → ",String(n.toIndex)]})}),t.jsx(a,{color:u,children:d})]},n.key)})}),e&&r.status==="would-rewrite"&&t.jsx(f,{marginTop:1,paddingLeft:2,children:t.jsx(a,{dimColor:!0,children:"--check mode: no write performed."})})]})]})]}):t.jsx(f,{alignItems:"center",borderColor:"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,justifyContent:"center",children:t.jsx(a,{dimColor:!0,children:"No entry selected"})})},he={error:"red",rewritten:"yellow",unchanged:"green","would-rewrite":"yellow"},ge={error:"ERROR",rewritten:"REWROTE",unchanged:"SORTED","would-rewrite":"REWRITE"},W={error:"errors",rewritten:"rewrites",unchanged:"sorted","would-rewrite":"rewrites"},xe={errors:"Errors",rewrites:"Rewrites",sorted:"Sorted"},pe=[{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[W[s.status]]++;return r},me=({entry:e,isSelected:r})=>{const s=he[e.status],c=ge[e.status];return t.jsxs(f,{flexShrink:0,height:1,children:[t.jsx(a,{children:r?">":" "}),t.jsx(a,{children:" "}),t.jsx(a,{bold:!0,color:s,children:`[${c}]`.padEnd(10)}),t.jsx(a,{children:" "}),t.jsx(f,{flexGrow:1,children:t.jsx(a,{bold:r,inverse:r,wrap:"truncate",children:e.relativePath})}),e.status!=="error"&&e.diff.length>0&&t.jsx(a,{dimColor:!0,children:` ${String(e.diff.length)} key${e.diff.length===1?"":"s"}`})]})},je=({color:e,count:r,label:s})=>t.jsx(f,{flexShrink:0,height:1,children:t.jsx(a,{bold:!0,color:e,children:`${s} (${String(r)})`})}),Se=({counts:e,entries:r,filterType:s,focused:c,selectedIndex:o,totalEntries:n,viewportHeight:i})=>{const d=c?"white":"gray",u=X(r),x=(u.errors>0?1:0)+(u.rewrites>0?1:0)+(u.sorted>0?1:0),m=s==="all"&&x>1,h=[];let j;for(const[l,g]of r.entries()){const k=W[g.status];m&&k!==j&&(j!==void 0&&h.push({kind:"spacer"}),h.push({color:k==="errors"?"red":k==="rewrites"?"yellow":"green",count:u[k],kind:"header",label:xe[k]}),j=k),h.push({entry:g,entryIndex:l,kind:"entry"})}const p=h.findIndex(l=>l.kind==="entry"&&l.entryIndex===o),y=p!==-1,S=h.length,w=Math.max(0,S-i);let b=0;y&&i>0&&(b=Math.min(w,Math.max(0,p-i+1)));const O=S>i&&i>0;return t.jsxs(f,{borderColor:d,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[t.jsxs(f,{flexShrink:0,gap:1,paddingX:1,children:[t.jsx(a,{bold:!0,inverse:!0,children:" VIS SORT "}),t.jsxs(a,{wrap:"truncate",children:[n," ","file",n===1?"":"s"]})]}),t.jsx(f,{flexShrink:0,gap:1,paddingX:1,paddingY:1,children:pe.map(l=>{const g=s===l.key,k=l.count(e);return t.jsxs(f,{children:[t.jsx(a,{dimColor:!g,children:"["}),t.jsx(a,{bold:g,color:g?"cyan":"gray",children:l.shortcut}),t.jsx(a,{dimColor:!g,children:"]"}),t.jsxs(a,{color:g?"white":"gray",children:[" ",l.label]}),t.jsxs(a,{dimColor:!0,children:[" ","(",k,")"]})]},l.key)})}),t.jsxs(f,{flexDirection:"row",flexGrow:1,overflow:"hidden",children:[t.jsx(f,{flexDirection:"column",flexGrow:1,overflow:"hidden",paddingLeft:1,children:t.jsx(f,{flexDirection:"column",marginTop:-b,children:h.map((l,g)=>l.kind==="spacer"?t.jsx(f,{flexShrink:0,height:1},`s-${String(g)}`):l.kind==="header"?t.jsx(je,{color:l.color,count:l.count,label:l.label},`h-${l.label}`):t.jsx(me,{entry:l.entry,isSelected:l.entryIndex===o},l.entry.filePath))})}),O&&t.jsx(f,{flexShrink:0,marginLeft:1,marginRight:1,children:t.jsx(V,{contentHeight:S,placement:"inset",scrollOffset:b,style:"block",viewportHeight:i})})]})]})},we=100,D=10,ye=6,ke=1,M={1:"all",2:"rewritten",3:"errors",4:"unchanged"},Ee=({checkMode:e,store:r})=>{const{exit:s}=z(),{columns:c,rows:o}=Z(),n=R.useSyncExternalStore(r.subscribe,r.getSnapshot),i=R.useRef(null),d=r.getFilteredEntries(),u=d[n.selectedIndex]??null,x=X(n.entries),m=c>=we,h=Math.max(0,o-ke),j=m?h:Math.floor(h/2),p=Math.max(0,j-ye),y=R.useCallback(()=>{s()},[s]),S=R.useRef(0),w=R.useRef(void 0),b=R.useRef(!1),O=R.useCallback((l,g)=>{S.current+=g,w.current=l,!b.current&&(b.current=!0,queueMicrotask(()=>{b.current=!1;const k=S.current,N=w.current;S.current=0,w.current=void 0,!(k===0||N===void 0)&&(N==="list"?r.selectStep(Math.sign(k)):i.current?.scrollBy(Math.sign(k)))}))},[r]);return Q((l,g)=>{if(l==="q"||g.escape){y();return}if(M[l]){r.setFilter(M[l]);return}if(g.tab){r.setFocusedPanel(n.focusedPanel==="list"?"detail":"list");return}n.focusedPanel==="list"?g.upArrow||l==="k"?O("list",-1):(g.downArrow||l==="j")&&O("list",1):n.focusedPanel==="detail"&&(g.upArrow||l==="k"?O("detail",-1):(g.downArrow||l==="j")&&O("detail",1))}),o<D?t.jsx(f,{alignItems:"center",justifyContent:"center",children:t.jsxs(a,{color:"yellow",children:["Terminal too small. Resize to at least",D," ","rows."]})}):t.jsxs(f,{flexDirection:"column",height:o,width:c,children:[t.jsxs(f,{flexDirection:m?"row":"column",flexGrow:1,children:[t.jsx(f,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:t.jsx(Se,{counts:x,entries:d,filterType:n.filterType,focused:n.focusedPanel==="list",selectedIndex:n.selectedIndex,totalEntries:n.entries.length,viewportHeight:p})}),t.jsx(f,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:t.jsx(ue,{checkMode:e,entry:u,focused:n.focusedPanel==="detail",scrollRef:i})})]}),t.jsx(f,{flexShrink:0,paddingX:1,children:t.jsx(a,{dimColor:!0,children:"↑/↓ or j/k:navigate | tab:switch panel | 1-4:filter | q:quit"})})]})},F=["types","node-addons","node","import","require","default"],be=/^git\+https:\/\/github\.com\/([^/]+)\/([^/.]+(?:\.git)?)$/,Oe=/^git\+ssh:\/\/git@github\.com\/([^/]+)\/([^/.]+(?:\.git)?)$/,T=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$=e=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(s=>$(s));const r={};for(const[s,c]of Object.entries(e))r[s]=$(c);return r},Re=e=>{if(!T(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}},Ie=e=>e.endsWith(".git")?e.slice(0,-4):e,Ce=e=>{if(!T(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 c=be.exec(s)??Oe.exec(s);if(!c)return{changed:!1,value:e};const o=c[1],n=Ie(c[2]??"");if(!o||!n)return{changed:!1,value:e};const i=new Set(["type","url"]);for(const d of Object.keys(e))if(!i.has(d))return{changed:!1,value:e};return{changed:!0,value:`${o}/${n}`}},Te=e=>{const r=Object.keys(e),s=[],c=[];for(const d of F)Object.hasOwn(e,d)&&s.push(d);for(const d of r)F.includes(d)||c.push(d);const o=[...s,...c];if(o.length===r.length&&o.every((d,u)=>d===r[u]))return{changed:!1,value:e};const i={};for(const d of o)i[d]=e[d];return{changed:!0,value:i}},H=e=>{if(!T(e))return{changed:!1,value:e};let r=!1;const s={};for(const[o,n]of Object.entries(e)){const i=H(n);s[o]=i.value,i.changed&&(r=!0)}const c=Te(s);return{changed:r||c.changed,value:c.value}},Pe=(e,r)=>{const s=$(e);let c=!1;if(r.formatBugs!==!1&&Object.hasOwn(s,"bugs")){const o=Re(s.bugs);o.changed&&(s.bugs=o.value,c=!0)}if(r.formatRepository!==!1&&Object.hasOwn(s,"repository")){const o=Ce(s.repository);o.changed&&(s.repository=o.value,c=!0)}if(r.sortExports!==!1&&Object.hasOwn(s,"exports")&&T(s.exports)){const o=H(s.exports);o.changed&&(s.exports=o.value,c=!0)}return{changed:c,pkg:s}},$e=/at position (\d+)/,Ne=/\(?line (\d+) column (\d+)\)?/,Ae=e=>{const r=new Set,s=[],c=n=>{const i=Y(n);!r.has(i)&&L(i)&&(r.add(i),s.push(i))};c(I(e,"package.json"));const o=ce(e);if(o){const n=A(e,o);for(const i of n)c(I(e,i,"package.json"))}else{const n=I(e,"package.json");if(L(n)){const i=JSON.parse(J(n)),d=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;if(d){const u=A(e,d);for(const x of u)c(I(e,x,"package.json"))}}}return s},Le=e=>/\n([ \t]+)/.exec(e)?.[1]??" ",_e=e=>{if(!(e===void 0||e===""))return e==="tab"||e===String.raw`\t`?" ":/^\d+$/.test(e)?" ".repeat(Number.parseInt(e,10)):e},P=e=>e===void 0?[]:(Array.isArray(e)?e:[e]).flatMap(s=>s.split(",")).map(s=>s.trim()).filter(s=>s.length>0),De=e=>e.includes(`\r
|
|
2
2
|
`)?"crlf":"lf",Me=new Set(["auto","crlf","lf"]),Fe=e=>{if(e===void 0||e==="")return"auto";if(Me.has(e))return e;throw new Error(`--line-ending must be one of: auto, lf, crlf (got "${e}")`)},Ge=(e,r,s)=>r.length===0?e:e.filter(c=>{const o=B(s,c),n=K(c);return!r.some(i=>{const d=i.includes("/")?o:n;return le(i,d)})}),ve=(e,r)=>{if(r.length===0)return e;const s={},c=new Set;for(const o of r)Object.hasOwn(e,o)&&(s[o]=e[o],c.add(o));for(const o of Object.keys(e))c.has(o)||(s[o]=e[o]);return s},Be=(e,r,s)=>{if(s.length===0)return e;const c={...e};for(const o of s)Object.hasOwn(r,o)&&(c[o]=r[o]);return c},Je=(e,r)=>{let s=1,c=1;const o=Math.min(r,e.length);for(let n=0;n<o;n++)e.codePointAt(n)===10?(s++,c=1):c++;return{column:c,line:s}},G=(e,r,s=2)=>{const c=e.split(`
|
|
3
3
|
`);if(r<1||r>c.length)return[];const o=Math.max(0,r-1-s),n=Math.min(c.length,r+s),i=[];for(let d=o;d<n;d++)i.push({content:c[d]??"",isErrorLine:d+1===r,lineNumber:d+1});return i},v=(e,r)=>{if(!(e instanceof Error))return;const s=$e.exec(e.message);if(s){const{column:o,line:n}=Je(r,Number.parseInt(s[1]??"0",10));return{column:o,line:n,snippet:G(r,n)}}const c=Ne.exec(e.message);if(c){const o=Number.parseInt(c[1]??"1",10);return{column:Number.parseInt(c[2]??"1",10),line:o,snippet:G(r,o)}}},Ue=(e,r)=>{const s=Object.keys(JSON.parse(e)),c=Object.keys(JSON.parse(r)),o=new Map(s.map((i,d)=>[i,d])),n=[];for(const[i,d]of c.entries()){const u=o.get(d);u!==void 0&&u!==i&&n.push({fromIndex:u,key:d,toIndex:i})}return n},We=(e,r,s)=>{const c=r.indent??s.indent??Le(e),o=r.lineEnding==="auto"?s.lineEnding??De(e):r.lineEnding,n=U(e,{pretty:!1,sortScripts:r.sortScripts});let i=JSON.parse(n);if(r.unsorted.length>0){const m=JSON.parse(e);i=Be(i,m,r.unsorted)}i=ve(i,r.sortOrder);const d={formatBugs:r.formatBugs,formatRepository:r.formatRepository,sortExports:r.sortExports},u=Pe(i,d);let x=JSON.stringify(u.pkg,null,c);return r.finalNewline&&(x+=`
|
|
4
4
|
`),o==="crlf"&&(x=x.replaceAll(`
|
|
5
5
|
`,`\r
|
|
6
|
-
`)),x},Xe=(e,r)=>{const s=Ae(e),c=se(e),o=ne({cwd:e,extraPatterns:oe(c)}),n=s.filter(d=>!o.ignores(d)),i=Ge(n,r,e);return{afterGitignore:n,allFiles:s,files:i}},He=async(e,{checkMode:r,cwd:s,fs:c,normalized:o})=>{const n=B(s,e)||e;let i;try{i=J(e)}catch(h){return{diff:[],error:{message:
|
|
6
|
+
`)),x},Xe=(e,r)=>{const s=Ae(e),c=se(e),o=ne({cwd:e,extraPatterns:oe(c)}),n=s.filter(d=>!o.ignores(d)),i=Ge(n,r,e);return{afterGitignore:n,allFiles:s,files:i}},He=async(e,{checkMode:r,cwd:s,fs:c,normalized:o})=>{const n=B(s,e)||e;let i;try{i=J(e)}catch(h){return{diff:[],error:{message:C(h),step:"read"},filePath:e,relativePath:n,status:"error"}}let d;try{d=U(i,{pretty:!1,sortScripts:o.sortScripts})}catch(h){const j={message:C(h),step:"native-sort"},p=v(h,i);return p&&(j.context=p),{diff:[],error:j,filePath:e,relativePath:n,status:"error"}}const u=o.editorconfig?ie(e):{};let x;try{x=We(i,o,u)}catch(h){const j={message:C(h),step:"json-parse"},p=v(h,i);return p&&(j.context=p),{diff:[],error:j,filePath:e,relativePath:n,status:"error"}}if(i===x)return{diff:[],filePath:e,relativePath:n,status:"unchanged"};let m;try{m=Ue(i,d)}catch{m=[]}if(r)return{diff:m,filePath:e,relativePath:n,status:"would-rewrite"};try{await c.writeFile(e,x,"utf8")}catch(h){return{diff:m,error:{message:C(h),step:"write"},filePath:e,relativePath:n,status:"error"}}return{diff:m,filePath:e,relativePath:n,status:"rewritten"}},Ke=e=>{if(e.error&&(E.error(`${e.filePath}: ${e.error.message}`),E.info(` step: ${e.error.step}`),e.error.context)){E.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?">":" ";E.info(` ${s} ${String(r.lineNumber).padStart(4)} | ${r.content}`)}}},tr=async({fs:e,options:r,visConfig:s,workspaceRoot:c})=>{const o=c??process.cwd(),n=s?.sortPackageJson,i=r.check||!1,u={editorconfig:r.editorconfig===!1?!1:n?.editorconfig??!0,finalNewline:r.finalNewline??n?.finalNewline??!0,formatBugs:r.formatBugs===!1?!1:n?.formatBugs??!0,formatRepository:r.formatRepository===!1?!1:n?.formatRepository??!0,ignore:[...P(r.ignore),...n?.ignore??[]],indent:_e(r.indent??n?.indent),lineEnding:Fe(r.lineEnding??n?.lineEnding),sortExports:r.sortExports===!1?!1:n?.sortExports??!0,sortOrder:[...P(r.sortOrder),...n?.sortOrder??[]],sortScripts:r.sortScripts||n?.sortScripts||!1,unsorted:[...P(r.unsorted),...n?.unsorted??[]]},x=Xe(o,u.ignore),{afterGitignore:m,allFiles:h,files:j}=x;if(j.length===0){h.length===0?E.info("No package.json files found."):m.length===0?E.info("All package.json files were excluded by .gitignore or workspace exclusions."):E.info("All package.json files were excluded by --ignore.");return}const p=[];for(const l of j)p.push(await He(l,{checkMode:i,cwd:o,fs:e,normalized:u}));let y=0,S=0,w=0;for(const l of p)l.status==="error"?w++:l.status==="rewritten"||l.status==="would-rewrite"?y++:S++;const b=y>0||w>0;if(!!process.stdout.isTTY&&!re&&b){const l=new fe(p);await ee(te.createElement(Ee,{checkMode:i,store:l}),{alternateScreen:!0,exitOnCtrlC:!1,interactive:!0,patchConsole:!0}).waitUntilExit()}else for(const l of p)switch(l.status){case"error":{Ke(l);break}case"rewritten":{E.success(`Sorted ${l.filePath}`);break}case"would-rewrite":{E.warn(`${l.filePath} is not sorted`);break}}if(i)y>0?(E.info(`${String(y)} file${y===1?"":"s"} not sorted, ${String(S)} already sorted`),process.exitCode=1):w===0&&E.info(`All ${String(S)} package.json file${S===1?" is":"s are"} sorted`);else{const l=[];y>0&&l.push(`sorted ${String(y)} file${y===1?"":"s"}`),S>0&&l.push(`${String(S)} already sorted`),w>0&&l.push(`${String(w)} error${w===1?"":"s"}`),l.length>0&&E.info(l.join(", "))}w>0&&(process.exitCode=1)};export{G as buildSnippet,Ue as computeKeyDiff,Je as computeLineColumn,tr as default,Xe as discoverPackageJsonFiles,v as extractParseErrorContext,He as processFile};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{createRequire as z}from"node:module";import{DEFAULT_CHANGES_DIR as Y}from"./DEFAULT_CLEAN_KEEP.js";import{b as Z,f as Q}from"./orchestrator.js";import{createShellRunner as ee}from"./shell-runner.js";import{r as te}from"../packem_shared/slug-OBHcH7wV.js";import{maxBump as ne}from"../release/types.js";let X;const V=r=>(X??=z(import.meta.url))(r),k=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,U=r=>{if(typeof k<"u"&&k.versions&&k.versions.node){const[e,t]=k.versions.node.split(".").map(Number);if(e>22||e===22&&t>=3||e===20&&t>=16)return k.getBuiltinModule(r)}return V(r)},{join:N,relative:J}=U("node:path"),G=/(?!.*)/;function re(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function C(r){return r.map(e=>typeof e=="string"?re(e.trim()):e.source).filter(Boolean).join("|")}function se(r,e){if(!r)return G;const t=C(r);return e?e(t):new RegExp(`^
|
|
1
|
+
import{createRequire as z}from"node:module";import{DEFAULT_CHANGES_DIR as Y}from"./DEFAULT_CLEAN_KEEP.js";import{b as Z,f as Q}from"./orchestrator.js";import{createShellRunner as ee}from"./shell-runner.js";import{r as te}from"../packem_shared/slug-OBHcH7wV.js";import{maxBump as ne}from"../release/types.js";let X;const V=r=>(X??=z(import.meta.url))(r),k=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,U=r=>{if(typeof k<"u"&&k.versions&&k.versions.node){const[e,t]=k.versions.node.split(".").map(Number);if(e>22||e===22&&t>=3||e===20&&t>=16)return k.getBuiltinModule(r)}return V(r)},{join:N,relative:J}=U("node:path"),G=/(?!.*)/;function re(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function C(r){return r.map(e=>typeof e=="string"?re(e.trim()):e.source).filter(Boolean).join("|")}function se(r,e){if(!r)return G;const t=C(r);return e?e(t):new RegExp(`^(?:\\*\\s+)?(${t}):\\s*(.*)`,"i")}function ie(r,e){if(!r)return G;const t=e?"g":"gi";return new RegExp(`(?:.*?)??\\s*([\\w-\\.\\/]*?)??(${C(r)})([\\w-]+)(?=\\s|$|[,;.)\\]])`,t)}function oe(r){if(!r)return/()(.+)/gi;const e=C(r);return new RegExp(`(${e})(?:\\s+(.*?))(?=(?:${e})|$)`,"gi")}function ce(r){const e=r?`|\\s+(?:${C(r)})`:"";return new RegExp(`^(?:BREAKING CHANGE|[\\w-]+)(?::\\s+${e}).+`,"i")}function ae(r={}){const e=se(r.noteKeywords,r.notesPattern),t=ie(r.issuePrefixes,r.issuePrefixesCaseSensitive),n=oe(r.referenceActions),s=ce(r.issuePrefixes);return{notes:e,referenceParts:t,references:n,footerToken:s,mentions:/@([\w-]+)/g,url:/\b(?:https?):\/\/(?:www\.)?([-a-zA-Z0-9@:%_+.~#?&//=])+\b/}}const le="------------------------ >8 ------------------------";function S(r){const e=r.match(/[^\r\n]/);if(typeof e?.index!="number")return"";const t=e.index;let n=r.length-1;for(;r[n]==="\r"||r[n]===`
|
|
2
2
|
`;)n--;return r.substring(t,n+1)}function $(r,e){return r?`${r}
|
|
3
|
-
${e||""}`:e||""}function fe(r){return r?e=>!e.startsWith(r):()=>!0}function he(r,e){const t=r.indexOf(`${e} ${le}`);return t===-1?r:r.slice(0,t)}function B(r){return!r.match(/^\s*gpg:/)}function I(r,e,t){const{groups:n}=e;for(let s=0,i=t.length,c;s<i;s++)c=t[s],r[c]=(n?n[c]:e[s+1])||null;return r}const ue={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 F(r={}){return{merge:null,revert:null,header:null,body:null,footer:null,notes:[],mentions:[],references:[],...r}}class de{options;regexes;lines=[];lineIndex=0;commit=F();constructor(e={}){this.options={...ue,...e},this.regexes=ae(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:n}=this;if(n.url.test(e))return null;const s=n.referenceParts.exec(e);if(!s)return null;let[i,c=null,u,d]=s,x=null;if(c){const w=c.indexOf("/");w!==-1&&(x=c.slice(0,w),c=c.slice(w+1))}return{raw:i,action:t,owner:x,repository:c,prefix:u,issue:d}}parseReferences(e){const{regexes:t}=this,n=e.match(t.references)?t.references:/()(.+)/gi,s=[];let i,c,u,d;for(;i=n.exec(e),!!i;)for(c=i[1]||null,u=i[2]||"";d=this.parseReference(u,c),!!d;)s.push(d);return s}skipEmptyLines(){let e=this.currentLine();for(;e!==void 0&&!e.trim();)this.nextLine(),e=this.currentLine()}parseMerge(){const{commit:e,options:t}=this,n=t.mergeCorrespondence||[],s=this.currentLine(),i=s&&t.mergePattern?s.match(t.mergePattern):null;return i?(this.nextLine(),e.merge=i[0]||null,I(e,i,n),!0):!1}parseHeader(e){e&&this.skipEmptyLines();const{commit:t,options:n}=this,s=n.headerCorrespondence||[],i=t.header??this.nextLine();let c=null;i&&(n.breakingHeaderPattern&&(c=i.match(n.breakingHeaderPattern)),!c&&n.headerPattern&&(c=i.match(n.headerPattern))),i&&(t.header=i),c&&I(t,c,s)}parseMeta(){const{options:e,commit:t}=this;if(!e.fieldPattern||!this.isLineAvailable())return!1;let n,s=null,i=!1;for(;this.isLineAvailable();){if(n=this.currentLine().match(e.fieldPattern),n){s=n[1]||null,this.nextLine();continue}if(s)i=!0,t[s]=$(t[s],this.currentLine()),this.nextLine();else break}return i}parseNotes(){const{regexes:e,commit:t}=this;if(!this.isLineAvailable())return!1;const n=this.currentLine().match(e.notes);let s;if(n){const i={title:n[1],text:n[2]};for(t.notes.push(i),t.footer=$(t.footer,this.currentLine()),this.nextLine();this.isLineAvailable();){if(this.parseMeta()||this.parseNotes())return!0;if(s=e.footerToken.test(this.currentLine()),t.references.push(...this.parseReferences(this.currentLine())),s||(i.text=$(i.text,this.currentLine())),t.footer=$(t.footer,this.currentLine()),this.nextLine(),s)break}return!0}return!1}parseBodyAndFooter(e){const{commit:t,regexes:n}=this;if(!this.isLineAvailable())return e;const i=!n.footerToken.test(this.currentLine())&&e;return t.references.push(...this.parseReferences(this.currentLine())),i?t.body=$(t.body,this.currentLine()):t.footer=$(t.footer,this.currentLine()),this.nextLine(),i}parseBreakingHeader(){const{commit:e,options:t}=this;if(!t.breakingHeaderPattern||e.notes.length||!e.header)return;const n=e.header.match(t.breakingHeaderPattern);n&&e.notes.push({title:"BREAKING CHANGE",text:n[3]})}parseMentions(e){const{commit:t,regexes:n}=this;let s;for(;s=n.mentions.exec(e),!!s;)t.mentions.push(s[1])}parseRevert(e){const{commit:t,options:n}=this,s=n.revertCorrespondence||[],i=n.revertPattern?e.match(n.revertPattern):null;i&&(t.revert=I({},i,s))}cleanupCommit(){const{commit:e}=this;e.body&&=S(e.body),e.footer&&=S(e.footer),e.notes.forEach(n=>{n.text=S(n.text)});const t=new Set;e.references=e.references.filter(n=>{const s=`${n.action} ${n.raw}`.toLocaleLowerCase(),i=!t.has(s);return i&&t.add(s),i})}parse(e){if(!e.trim())throw new TypeError("Expected a raw commit");const{commentChar:t}=this.options,n=fe(t),s=S(e).split(/\r?\n/),i=t?he(s,t).filter(x=>n(x)&&B(x)):s.filter(x=>B(x)),c=F();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 d=!0;for(;this.isLineAvailable();)this.parseMeta(),this.parseNotes()&&(d=!1),this.parseBodyAndFooter(d)||(d=!1);return this.parseBreakingHeader(),this.parseMentions(e),this.parseRevert(e),this.cleanupCommit(),c}}const D={build:"patch",chore:"patch",ci:"patch",docs:"patch",feat:"minor",fix:"patch",perf:"patch",refactor:"patch",style:"patch",test:"patch"},me=new de,pe=/^Revert\s+"(.+)"\s*$/,ge=/This reverts commit\s+([0-9a-f]{7,40})/i,xe=/^(?:[\p{Emoji_Presentation}\p{Extended_Pictographic}]|:\w+:)\s+/u,be=(r,e)=>{const t=r.replace(xe,""),n=me.parse(`${t}
|
|
3
|
+
${e||""}`:e||""}function fe(r){return r?e=>!e.startsWith(r):()=>!0}function he(r,e){const t=r.indexOf(`${e} ${le}`);return t===-1?r:r.slice(0,t)}function B(r){return!r.match(/^\s*gpg:/)}function I(r,e,t){const{groups:n}=e;for(let s=0,i=t.length,c;s<i;s++)c=t[s],r[c]=(n?n[c]:e[s+1])||null;return r}const ue={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:/^-(?=.*\w)(.*?)-$/};function F(r={}){return{merge:null,revert:null,header:null,body:null,footer:null,notes:[],mentions:[],references:[],...r}}class de{options;regexes;lines=[];lineIndex=0;commit=F();constructor(e={}){this.options={...ue,...e},this.regexes=ae(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:n}=this;if(n.url.test(e))return null;const s=n.referenceParts.exec(e);if(!s)return null;let[i,c=null,u,d]=s,x=null;if(c){const w=c.indexOf("/");w!==-1&&(x=c.slice(0,w),c=c.slice(w+1))}return{raw:i,action:t,owner:x,repository:c,prefix:u,issue:d}}parseReferences(e){const{regexes:t}=this,n=e.match(t.references)?t.references:/()(.+)/gi,s=[];let i,c,u,d;for(;i=n.exec(e),!!i;)for(c=i[1]||null,u=i[2]||"";d=this.parseReference(u,c),!!d;)s.push(d);return s}skipEmptyLines(){let e=this.currentLine();for(;e!==void 0&&!e.trim();)this.nextLine(),e=this.currentLine()}parseMerge(){const{commit:e,options:t}=this,n=t.mergeCorrespondence||[],s=this.currentLine(),i=s&&t.mergePattern?s.match(t.mergePattern):null;return i?(this.nextLine(),e.merge=i[0]||null,I(e,i,n),!0):!1}parseHeader(e){e&&this.skipEmptyLines();const{commit:t,options:n}=this,s=n.headerCorrespondence||[],i=t.header??this.nextLine();let c=null;i&&(n.breakingHeaderPattern&&(c=i.match(n.breakingHeaderPattern)),!c&&n.headerPattern&&(c=i.match(n.headerPattern))),i&&(t.header=i),c&&I(t,c,s)}parseMeta(){const{options:e,commit:t}=this;if(!e.fieldPattern||!this.isLineAvailable())return!1;let n,s=null,i=!1;for(;this.isLineAvailable();){if(n=this.currentLine().match(e.fieldPattern),n){s=n[1]||null,this.nextLine();continue}if(s)i=!0,t[s]=$(t[s],this.currentLine()),this.nextLine();else break}return i}parseNotes(){const{regexes:e,commit:t}=this;if(!this.isLineAvailable())return!1;const n=this.currentLine().match(e.notes);let s;if(n){const i={title:n[1],text:n[2]};for(t.notes.push(i),t.footer=$(t.footer,this.currentLine()),this.nextLine();this.isLineAvailable();){if(this.parseMeta()||this.parseNotes())return!0;if(s=e.footerToken.test(this.currentLine()),t.references.push(...this.parseReferences(this.currentLine())),s||(i.text=$(i.text,this.currentLine())),t.footer=$(t.footer,this.currentLine()),this.nextLine(),s)break}return!0}return!1}parseBodyAndFooter(e){const{commit:t,regexes:n}=this;if(!this.isLineAvailable())return e;const i=!n.footerToken.test(this.currentLine())&&e;return t.references.push(...this.parseReferences(this.currentLine())),i?t.body=$(t.body,this.currentLine()):t.footer=$(t.footer,this.currentLine()),this.nextLine(),i}parseBreakingHeader(){const{commit:e,options:t}=this;if(!t.breakingHeaderPattern||e.notes.length||!e.header)return;const n=e.header.match(t.breakingHeaderPattern);n&&e.notes.push({title:"BREAKING CHANGE",text:n[3]})}parseMentions(e){const{commit:t,regexes:n}=this;let s;for(;s=n.mentions.exec(e),!!s;)t.mentions.push(s[1])}parseRevert(e){const{commit:t,options:n}=this,s=n.revertCorrespondence||[],i=n.revertPattern?e.match(n.revertPattern):null;i&&(t.revert=I({},i,s))}cleanupCommit(){const{commit:e}=this;e.body&&=S(e.body),e.footer&&=S(e.footer),e.notes.forEach(n=>{n.text=S(n.text)});const t=new Set;e.references=e.references.filter(n=>{const s=`${n.action} ${n.raw}`.toLocaleLowerCase(),i=!t.has(s);return i&&t.add(s),i})}parse(e){if(!e.trim())throw new TypeError("Expected a raw commit");const{commentChar:t}=this.options,n=fe(t),s=S(e).split(/\r?\n/),i=t?he(s,t).filter(x=>n(x)&&B(x)):s.filter(x=>B(x)),c=F();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 d=!0;for(;this.isLineAvailable();)this.parseMeta(),this.parseNotes()&&(d=!1),this.parseBodyAndFooter(d)||(d=!1);return this.parseBreakingHeader(),this.parseMentions(e),this.parseRevert(e),this.cleanupCommit(),c}}const D={build:"patch",chore:"patch",ci:"patch",docs:"patch",feat:"minor",fix:"patch",perf:"patch",refactor:"patch",style:"patch",test:"patch"},me=new de,pe=/^Revert\s+"(.+)"\s*$/,ge=/This reverts commit\s+([0-9a-f]{7,40})/i,xe=/^(?:[\p{Emoji_Presentation}\p{Extended_Pictographic}]|:\w+:)\s+/u,be=(r,e)=>{const t=r.replace(xe,""),n=me.parse(`${t}
|
|
4
4
|
|
|
5
5
|
${e}`);return{breaking:n.notes.some(i=>/BREAKING/i.test(i.title)),scope:n.scope??void 0,type:n.type??void 0}},we=(r,e,t)=>{let n,s=!1;if(t.type==="revert"){s=!0;const u=r.indexOf(":");u!==-1&&(n=r.slice(u+1).trim())}else{const u=pe.exec(r.trim());u&&(s=!0,n=u[1]?.trim())}let i;const c=ge.exec(e);return c&&(i=c[1]?.toLowerCase()),{isRevert:s,targetSha:i,targetSubject:n}},Re=(r,e=new Set,t)=>{const n=r.map(o=>{const l=be(o.subject,o.body),{isRevert:a,targetSha:m,targetSubject:h}=we(o.subject,o.body,l);return{...o,cancelled:!1,parsed:l,revert:a,revertSubject:h,revertTargetSha:m}}),s=n.toReversed(),i=12,c=new Map;for(const o of s)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 m=o.hash.slice(0,a);if(c.has(m)){const h=c.get(m);h!==null&&h!==o&&c.set(m,null)}else c.set(m,o)}}const u=(o,l)=>{if(o.revertTargetSha){const a=o.revertTargetSha.toLowerCase();let h=c.get(a)??void 0;if(h||(h=s.find(P=>P.hash.startsWith(a))),h&&h!==o)return h}if(o.revertSubject)for(let a=l.length-1;a>=0;a-=1){const m=l[a];if(m.subject===o.revertSubject)return m}},d=64,x=o=>{let l=o;for(let a=0;a<d;a+=1){if(!l.revert)return l;const m=l.cancelledBy;let h;if(m&&(h=c.get(m)??void 0,h||(h=c.get(m.slice(0,7))??void 0)),!h||h===l)return l;l=h}},w=[],R=[];for(const o of s){if(o.revert){const l=u(o,R);if(l){if(e.has(l.hash)){R.push(o);continue}const a=x(l);if(a===void 0){w.push(`Revert chain at ${o.hash} exceeded depth limit (${d}) — skipping cancellation`),R.push(o);continue}if(e.has(a.hash)){R.push(o);continue}a.cancelled=!a.cancelled,a.cancelledBy=a.cancelled?o.hash:void 0,o.cancelled=!0,o.cancelledBy=l.hash}}R.push(o)}const v=n.filter(o=>!o.cancelled&&!o.revert&&!o.subject?.startsWith("Merge ")),_=v.filter(o=>!o.parsed.type);if(v.length>0&&_.length/v.length>.5){const o=t??"<from>..HEAD";w.push(`${_.length}/${v.length} commits in ${o} have no conventional-commits prefix. Consider enabling commit-message linting.`)}return{commits:n,warnings:w}},Ae=async({fs:r,logger:e,options:t,workspaceRoot:n})=>{const s=n??process.cwd(),i=await Z({cwd:s,skipRegistryLookup:!0}),{printConfigIfRequested:c}=await import("./print-config.js");if(c(t,i,e))return;const u=ee();let d=t.from;if(!d){const f=i.config.baseBranch??"main",g=await u.run("git",["merge-base",`origin/${f}`,"HEAD"],{cwd:s,silent:!0});if(g.exitCode===0&&g.stdout.trim())d=g.stdout.trim();else{const p=await u.run("git",["merge-base",f,"HEAD"],{cwd:s,silent:!0});d=p.exitCode===0?p.stdout.trim():"HEAD~10"}}const x=new Map;for(const f of i.packages){const p=(f.dir.startsWith(s)?f.dir.slice(s.length):f.dir).replaceAll("\\","/").replace(/^\/+/,"");x.set(p,f.name)}const w=f=>{for(const[g,p]of x)if(f.startsWith(`${g}/`)||f===`${g}/package.json`)return p},R=Math.random().toString(16).slice(2,10),v=`@@VIS_RELEASE_COMMIT_${R}@@`,_=`@@VIS_RELEASE_FILES_${R}@@`,o=await u.run("git",["log",`${d}..HEAD`,`--pretty=format:${v}%n%H%n%s%n%b%n${_}`,"--name-only"],{cwd:s,silent:!0});if(o.exitCode!==0){e.error(`git log failed: ${o.stderr}`),process.exitCode=1;return}const l=new Map,a=[],m=[],h=o.stdout.split(v).map(f=>f.trim()).filter(Boolean);for(const f of h){const[g,p=""]=f.split(_).toReversed(),A=p.split(`
|
|
6
6
|
`),E=A[0]?.trim()??"",L=A[1]?.trim()??"",b=A.slice(2).join(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as F}from"node:module";import{i as W}from"../packem_shared/index-BjdW45xX.js";import{p as Y}from"../packem_shared/prompt-DMzaQEVa.js";import{e as U}from"../packem_shared/index-DHD8wb6Z.js";import{l as B,m as X,n as J,D as Q,o as Z,$ as ee,k as _}from"../packem_shared/formatBytes-BHAzNIrn-DFIppnY0.js";import{y as te}from"../packem_shared/isAccessibleSync-DYKTrrvc-CSnBISfV.js";import{p as se}from"../packem_shared/readJsonSync-CbryXYxN-B2aSeDpC.js";import{h as re,U as oe}from"../packem_shared/writeFileSync-DJoHk3Ks-CgQ-VNNT.js";import{g as ne,r as ce}from"../packem_shared/packument-C55kVxcQ.js";import{
|
|
1
|
+
import{createRequire as F}from"node:module";import{i as W}from"../packem_shared/index-BjdW45xX.js";import{p as Y}from"../packem_shared/prompt-DMzaQEVa.js";import{e as U}from"../packem_shared/index-DHD8wb6Z.js";import{l as B,m as X,n as J,D as Q,o as Z,$ as ee,k as _}from"../packem_shared/formatBytes-BHAzNIrn-DFIppnY0.js";import{y as te}from"../packem_shared/isAccessibleSync-DYKTrrvc-CSnBISfV.js";import{p as se}from"../packem_shared/readJsonSync-CbryXYxN-B2aSeDpC.js";import{h as re,U as oe}from"../packem_shared/writeFileSync-DJoHk3Ks-CgQ-VNNT.js";import{g as ne,r as ce}from"../packem_shared/packument-C55kVxcQ.js";import{q as ie,j as ae,F as v,b as $,X as E,J as A}from"../packem_shared/index.server-BAjDJSEu.js";import{a as le,o as fe}from"../packem_shared/pm-runner-de-jCq8q.js";import{r as ue,a as pe}from"../packem_shared/command-runtime-CiLVo4ED.js";let V;const z=e=>(V??=F(import.meta.url))(e),b=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,M=e=>{if(typeof b<"u"&&b.versions&&b.versions.node){const[t,s]=b.versions.node.split(".").map(Number);if(t>22||t===22&&s>=3||t===20&&s>=16)return b.getBuiltinModule(e)}return z(e)},{renameSync:q}=M("node:fs"),{stripVTControlCharacters:G}=M("node:util"),de=(e={})=>{const t=e.isCi??W;return(e.isTty??!!(process.stdin.isTTY&&process.stdout.isTTY))&&!t},k=U(B(),"dlx-seen.json"),H=(e,t)=>`${e}@${t}`,me=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"},P=()=>{try{if(te(k)){const e=se(k);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))me(r)&&(t[s]=r);return{packages:t,version:1}}}}catch{}return{packages:{},version:1}},he=e=>{try{re(B());const t=`${k}.${String(process.pid)}.tmp`;oe(t,JSON.stringify(e)),q(t,k)}catch{}},ge=(e,t,s)=>e.packages[H(t,s)],ye=(e,t)=>{if(!e)return!0;const s=new Set(Array.isArray(e.alertKeys)?e.alertKeys:[]);return t.some(r=>!s.has(r))},R=(e,t,s,r)=>{const o=P();o.packages[H(e,t)]={alertKeys:[...s].sort(),seenAt:r},he(o)},ve=/[\u0000-\u0008\u000B-\u001F\u007F]/g,K=e=>G(e).replaceAll(" "," ").replaceAll(ve,""),x=["CHANGELOG.md","CHANGELOG","changelog.md","CHANGES.md","HISTORY.md"],be=4e3,C=async(e,t,s)=>{if(t?.aborted)return;const r=new AbortController,o=setTimeout(()=>{r.abort()},be),a=()=>{r.abort()};t?.addEventListener("abort",a,{once:!0});try{const n=await fetch(e,{headers:s,signal:r.signal});return n.ok?await n.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},O=(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 n=-1,p=0;for(const[i,l]of s.entries()){const f=r.exec(l);if(f&&a.test(f[2])){n=i,p=f[1].length;break}}if(n===-1)return;const c=[];for(let i=n+1;i<s.length;i+=1){const l=r.exec(s[i]);if(l&&l[1].length<=p)break;c.push(s[i])}return c},I=(e,t=4)=>e.map(r=>r.trim()).filter(r=>r.length>0).map(r=>K(r.replace(/^#{1,6}\s+/,"").replace(/^[*-]\s+/,"- ")).trim()).filter(r=>r.length>0&&!/^\[.*\]:/.test(r)).slice(0,t),L=(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=L(r[t],s),a=[o?`${e.name}@${t} — published ${o}`:`${e.name}@${t}`],n=Date.parse(r[t]??""),c=Object.entries(r).filter(([i])=>i!=="created"&&i!=="modified"&&i!==t).sort((i,l)=>Date.parse(l[1])-Date.parse(i[1])).filter(([,i])=>Date.parse(i)<n).slice(0,3);for(const[i,l]of c)a.push(`- ${i} (${L(l,s)})`);return{lines:a,source:"npm-diff",version:t}},Se=async e=>{const{name:t,now:s,offline:r,packument:o,signal:a,version:n}=e;if(r)return o?N(o,n,s):void 0;for(const i of x){const l=`https://cdn.jsdelivr.net/npm/${t}@${n}/${i}`,f=await C(l,a);if(f){const h=O(f,n),u=I(h??f.split(/\r?\n/));if(u.length>0)return{lines:u,source:"package-file",url:l,version:n}}}const p=o?.versions[n],c=$e(p?.repository);if(c){const i=c.directory?`${c.directory.replaceAll(/^\/+|\/+$/g,"")}/`:"";for(const l of["HEAD","main","master"])for(const f of x){const h=`https://raw.githubusercontent.com/${c.owner}/${c.repo}/${l}/${i}${f}`,u=await C(h,a);if(u){const g=O(u,n),m=I(g??u.split(/\r?\n/));if(m.length>0){const d=`https://github.com/${c.owner}/${c.repo}/blob/${l}/${i}${f}`;return{lines:m,source:"repo-file",url:d,version:n}}}}}if(o)return N(o,n,s)},we={dynamicRequire:"dynamic require",envVars:"env access",filesystemAccess:"filesystem",networkAccess:"network",shellAccess:"shell",telemetry:"telemetry",unsafe:"eval/unsafe",usesEval:"eval/unsafe"},ke=["preinstall","install","postinstall"],Te=(e,t)=>({fileCount:e?.dist?.fileCount,tarballBytes:t?.size,unpackedBytes:e?.dist?.unpackedSize}),Ee=(e,t)=>{const s=ke.filter(n=>!!e?.scripts?.[n]),r=e?.bin,o=typeof r=="string"?["(default)"]:Object.keys(r??{}).map(n=>K(n)),a=[...new Set(t.map(n=>we[n.type]).filter(n=>n!==void 0))];return{bins:o,capabilities:a,lifecycleScripts:s}},_e=(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},Ae=async e=>{const{name:t,now:s,offline:r,signal:o,socketToken:a,spec:n,workspaceRoot:p}=e;let c;try{c=await ne(t,{offline:r,signal:o,workspaceRoot:p})}catch{c=void 0}const i=c?ce(c,n):void 0;if(!i)return;const l=c?.versions[i],f=async()=>{if(!(r||!a))try{const y=await J([{name:t,version:i}],{apiToken:a,minimumScore:Q});return _e(y,t,i)}catch{return}},h=Se({name:t,now:s,offline:r,packument:c,signal:o,version:i}).catch(()=>{}),[u,g]=await Promise.all([f(),h]),m=u?.alerts??[],d=[...new Set(m.filter(y=>y.severity==="critical"||y.severity==="high").map(y=>y.key))].sort(),S=u?Math.round((u.score.overall??X(u.score))*100):void 0;return{changelog:g,name:t,permissions:Ee(l,m),security:{alerts:m,available:!!u,highSeverityKeys:d,score:S},size:Te(l,u),version:i}},w=e=>Z(G(e)),Re={critical:E,high:E,low:v,medium:$},D=e=>{if(!(e===void 0||e<0))return ee(e,{decimals:1,space:!0})},xe=e=>{const{fileCount:t,tarballBytes:s,unpackedBytes:r}=e.size,o=D(r),a=D(s);if(o&&a){const n=t===void 0?"":`, ${String(t)} files`;return`${o} unpacked (${a} tarball${n})`}if(o)return`${o} unpacked`;if(a)return`${a} tarball`},Ce=e=>{const{alerts:t,available:s,score:r}=e.security;if(!s)return v("unavailable — set VIS_SOCKET_TOKEN for a Socket.dev score");const o=r===void 0?v:r>=70?A:r>=40?$:E,a=r===void 0?"n/a":`${String(r)}/100`,n=new Map;for(const l of t)n.set(l.severity,(n.get(l.severity)??0)+1);const p=[],c=["critical","high","medium","low"];for(const l of c){const f=n.get(l);f&&p.push(Re[l](`${String(f)} ${l}`))}const i=p.length>0?` ${$("!")} ${p.join(", ")}`:` ${A("no alerts")}`;return`${o(a)} ${v("(Socket.dev)")}${i}`},Oe=e=>{const{bins:t,capabilities:s,lifecycleScripts:r}=e.permissions,o=[];for(const a of r)o.push($(`${a} script`));for(const a of s)o.push($(a));return t.length>0&&o.push(v(`bins: ${t.join(", ")}`)),o.length>0?o.join(v(" · ")):void 0},Ie=e=>{const t=[],s=xe(e);s&&t.push({label:"size",values:[s]}),t.push({label:"score",values:[Ce(e)]});const r=Oe(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,v(`source: ${o}`)]})}return t},j=6,Le=e=>{const t=Ie(e),s=` first run: ${e.name}@${e.version} `,r=[];for(const c of t)c.values.forEach((i,l)=>{const f=l===0?ie(c.label.padEnd(j)):" ".repeat(j);r.push(`${f} ${i}`)});const o=Math.max(w(s),...r.map(c=>w(c))),a=c=>`${c}${" ".repeat(Math.max(0,o-w(c)))}`,n=`┌─${ae(s)}${"─".repeat(Math.max(0,o-w(s)))}─┐`,p=`└─${"─".repeat(o)}─┘`;return[n,...r.map(c=>`│ ${a(c)} │`),p]},Ne=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)}},De=e=>e===""||e.startsWith(".")||e.startsWith("/")||e.startsWith("~")?!1:!(e.startsWith("@")?e.slice(1):e).includes(":"),je=6e3,Me=e=>{process.stdout.write(e)},Be=async e=>{const{forceInfo:t=!1,noInfo:s=!1,offline:r=!1,pkg:o,socketToken:a,workspaceRoot:n,yes:p=!1}=e;if(s||!De(o))return{proceed:!0};const c=e.now??Date.now(),i=p||!de({isCi:e.isCi,isTty:e.isTty}),l=e.output??Me;if(i&&!t)return{proceed:!0};const{name:f,spec:h}=Ne(o),u=new AbortController;let g;const m=new Promise(T=>{g=setTimeout(()=>{u.abort(),T(void 0)},je)}),d=await Promise.race([Ae({name:f,now:c,offline:r,signal:u.signal,socketToken:a,spec:h,workspaceRoot:n}).catch(()=>{}),m]);if(g&&clearTimeout(g),!d)return{proceed:!0};const S=ge(P(),d.name,d.version);if(!t&&!ye(S,d.security.highSeverityKeys))return{proceed:!0};for(const T of Le(d))l(`${T}
|
|
2
2
|
`);if(i)return R(d.name,d.version,d.security.highSeverityKeys,c),{proceed:!0};const y=await Y("? Ok to proceed? (y/N) ",e.readline);return y&&R(d.name,d.version,d.security.highSeverityKeys,c),{proceed:y}},Je=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[n,...p]=a,c=o??process.cwd(),i=s.package?Array.isArray(s.package)?s.package:[s.package]:[],l=s.shellMode?i:[n,...i];for(const g of l){const m=s.info||!1,d=m?!1:s.noInfo||_(process.env.VIS_DLX_NO_INFO);if(!(await Be({forceInfo:m,noInfo:d,offline:s.offline||!1,pkg:g,socketToken:r?.security?.socket?.apiToken??process.env.VIS_SOCKET_TOKEN,workspaceRoot:c,yes:s.yes||_(process.env.VIS_DLX_YES)})).proceed){t.info("Aborted."),process.exitCode=1;return}}const f=ue({logger:t,options:s,visConfig:r},c),h=le(c,{backend:pe(f),configBackend:r?.install?.backend,configCorepack:r?.install?.corepack}),u=fe(h,{additionalPackages:i,args:p,package:n,shellMode:s.shellMode||!1,silent:s.silent||!1},c,t,{offline:s.offline||!1});u!==0&&(process.exitCode=u)};export{Je as default};
|