@visulima/vis 4.0.1 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/LICENSE.md +403 -921
  3. package/README.md +2 -2
  4. package/dashboard/dist/index.html +12 -12
  5. package/dist/bin.js +1 -1
  6. package/dist/binx.js +1 -1
  7. package/dist/packem_chunks/bloom-status.js +1 -1
  8. package/dist/packem_chunks/bloom-sync.js +1 -1
  9. package/dist/packem_chunks/catalog.js +34 -34
  10. package/dist/packem_chunks/cli-exec.js +1 -1
  11. package/dist/packem_chunks/cli-main.js +157 -157
  12. package/dist/packem_chunks/doctor-probe.js +1 -1
  13. package/dist/packem_chunks/fix.js +1 -1
  14. package/dist/packem_chunks/git.js +4 -3
  15. package/dist/packem_chunks/handler13.js +1 -1
  16. package/dist/packem_chunks/handler14.js +1 -1
  17. package/dist/packem_chunks/handler15.js +1 -1
  18. package/dist/packem_chunks/handler2.js +1 -1
  19. package/dist/packem_chunks/handler20.js +1 -1
  20. package/dist/packem_chunks/handler23.js +1 -1
  21. package/dist/packem_chunks/handler24.js +1 -1
  22. package/dist/packem_chunks/handler26.js +1 -1
  23. package/dist/packem_chunks/handler28.js +1 -1
  24. package/dist/packem_chunks/handler3.js +1 -1
  25. package/dist/packem_chunks/handler39.js +6 -6
  26. package/dist/packem_chunks/handler40.js +1 -75
  27. package/dist/packem_chunks/handler50.js +1 -1
  28. package/dist/packem_chunks/handler53.js +1 -1
  29. package/dist/packem_chunks/handler54.js +1 -1
  30. package/dist/packem_chunks/handler56.js +6 -6
  31. package/dist/packem_chunks/handler59.js +73 -9
  32. package/dist/packem_chunks/handler6.js +1 -1
  33. package/dist/packem_chunks/handler60.js +11 -3
  34. package/dist/packem_chunks/handler61.js +3 -22
  35. package/dist/packem_chunks/handler62.js +21 -60
  36. package/dist/packem_chunks/handler63.js +61 -3
  37. package/dist/packem_chunks/handler64.js +3 -6
  38. package/dist/packem_chunks/handler65.js +6 -9
  39. package/dist/packem_chunks/handler66.js +1 -1
  40. package/dist/packem_chunks/handler67.js +1 -1
  41. package/dist/packem_chunks/handler68.js +1 -1
  42. package/dist/packem_chunks/handler69.js +1 -1
  43. package/dist/packem_chunks/handler70.js +1 -1
  44. package/dist/packem_chunks/handler72.js +1 -1
  45. package/dist/packem_chunks/handler73.js +1 -1
  46. package/dist/packem_chunks/handler74.js +1 -1
  47. package/dist/packem_chunks/handler75.js +1 -1
  48. package/dist/packem_chunks/handler76.js +1 -1
  49. package/dist/packem_chunks/handler78.js +1 -1
  50. package/dist/packem_chunks/heal.js +1 -1
  51. package/dist/packem_chunks/help-command.js +5 -5
  52. package/dist/packem_chunks/index6.js +7 -21
  53. package/dist/packem_chunks/index7.js +47 -47
  54. package/dist/packem_chunks/prompts.js +1 -1
  55. package/dist/packem_chunks/resolveFormatter.js +7 -5
  56. package/dist/packem_chunks/root-handler.js +1 -0
  57. package/dist/packem_chunks/shell-runner.js +1 -1
  58. package/dist/packem_chunks/status.js +1 -1
  59. package/dist/packem_chunks/sync.js +1 -1
  60. package/dist/packem_chunks/version-resolver.js +3 -2
  61. package/dist/packem_shared/DEFAULT_BREAKING_SECTION-DUAcKVLD.js +1 -0
  62. package/dist/packem_shared/DEFAULT_CONVENTIONAL_HEADING-D7oNGUcP.js +1 -0
  63. package/dist/packem_shared/{affected-selection-DLrq50Mz.js → affected-selection-DP4GM66N.js} +1 -1
  64. package/dist/packem_shared/{api.d-BPftyU9r.d.ts → api.d-C10vHKJZ.d.ts} +1 -1
  65. package/dist/packem_shared/{bin-As0Wq5ZN.js → bin-BO1M68aW.js} +1 -1
  66. package/dist/packem_shared/buildCompareUrl-BLaukjgu.js +1 -0
  67. package/dist/packem_shared/conventional-CGiOOEq1.js +4 -0
  68. package/dist/packem_shared/{cyclonedx-B1vzerwP.js → cyclonedx-CX2fFvDi.js} +1 -1
  69. package/dist/packem_shared/docker-Dy-X_BuM.js +59 -0
  70. package/dist/packem_shared/hasBulletMarker-BX2KwzI5.js +1 -0
  71. package/dist/packem_shared/{index-CcVv0V1y.js → index-rcfHhvVo.js} +1 -1
  72. package/dist/packem_shared/index.server-sXNQYpsl.js +2 -0
  73. package/dist/packem_shared/main-CgDAlZkm.js +1 -0
  74. package/dist/packem_shared/{package-version-BFsJ8iyZ.js → package-version-BO37_qsn.js} +1 -1
  75. package/dist/packem_shared/{project-name-filter-DdXd3P3a.js → project-name-filter-C_mppI1h.js} +1 -1
  76. package/dist/packem_shared/release-heading-DRpkhETz.js +1 -0
  77. package/dist/packem_shared/{resolve-explicit-ZZEPWdpP.js → resolve-explicit-CsTmALmE.js} +1 -1
  78. package/dist/packem_shared/run-D-uVGHQ4.js +10 -0
  79. package/dist/packem_shared/{s1ngularity-R-zLjQjp.js → s1ngularity-BRk_GMUj.js} +1 -1
  80. package/dist/packem_shared/{scan-progress-5uTRdC1G.js → scan-progress-DRIGQRMr.js} +1 -1
  81. package/dist/packem_shared/{typosquats-Cdsnf6aN.js → typosquats-CSkIFgF5.js} +1 -1
  82. package/dist/packem_shared/{vis-user-error-DJvfOpBX.js → vis-user-error-YIyfYNBK.js} +1 -1
  83. package/dist/release/core/changelog/index.d.ts +274 -31
  84. package/dist/release/core/changelog/index.js +1 -1
  85. package/dist/release/plugin-sdk.d.ts +2 -2
  86. package/dist/release/types.d.ts +44 -2
  87. package/index.js +52 -52
  88. package/package.json +11 -11
  89. package/schemas/vis-config.schema.json +19 -1
  90. package/schemas/vis-release-config.schema.json +19 -1
  91. package/dist/packem_shared/docker-Bex05Qcn.js +0 -59
  92. package/dist/packem_shared/index.server-BAjDJSEu.js +0 -2
  93. package/dist/packem_shared/main-BP-w-K-6.js +0 -1
@@ -1,61 +1,22 @@
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 M}from"../packem_shared/writeFileSync-DJoHk3Ks-CgQ-VNNT.js";import{T as q}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
- `),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
- `)},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}
1
+ import{createRequire as re}from"node:module";import{F as d,j as y,q as v}from"../packem_shared/index.server-sXNQYpsl.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
+ `);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
+ `)}for(;;){const s=await q(t,`
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.")}
5
+ `)}},Ee=async(t,e,r,n)=>{process.stderr.write(` ${e} ${d("(comma-separated numbers)")}
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
+ `)}for(;;){const s=await q(t,`
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},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
+ `),f.notice("Next steps:");for(const o of s.suggestions)process.stderr.write(` ${d("•")} ${o}
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
+ `)}},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")}
4
14
 
5
- `}${t}
6
- `},V=["**/CODEOWNERS"],ee=["**/node_modules/**","**/dist/**","**/build/**","**/coverage/**","**/.git/**","**/.next/**","**/.nuxt/**"],te=e=>{const t=[];for(const n of e.split(/\r?\n/u)){const s=n.indexOf("#"),o=(s===-1?n:n.slice(0,s)).trim();if(o.length===0)continue;const i=o.split(/\s+/u);if(i.length<2)continue;const[c,...r]=i,a=r.filter(f=>f.length>0);!c||a.length===0||t.push({owners:a,path:c})}return t},ne=(e,t)=>{const n=t.replace(/^\.\/?/,"").replace(/\/$/,"");return e.startsWith("/")?n===""?e:`/${n}${e}`:n===""?`/${e}`:`/${n}/${e}`},oe=async(e,t,n)=>{const s=t&&t.length>0?[...t]:[...V],o=[...ee];if(n){const r=n.replace(/^\.\/?/,"").replace(/^\/+/,"");r.length>0&&o.push(r)}const i=await K(s,{absolute:!0,cwd:e,ignore:o}),c=[];for(const r of i){let a;try{a=A(r)}catch{continue}const f=G(r),l=I(e,f);for(const p of te(a))c.push({owners:p.owners,path:ne(p.path,l)})}return c},re=/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/?#]+)/iu,se=e=>{if(!e)return;const t=e.match(re);if(!t?.[1])return;const n=t[1].trim();if(!(n===""||n.includes(" ")))return`@${n.replace(/^@/,"")}`},ce=(e,t)=>{const n=[];for(const[s,o]of Object.entries(e.projects)){if(o.owners&&o.owners.length>0)continue;const i=o.root??s,c=b(t,i,"package.json"),r=E(c);if(!r)continue;const a=B(r.maintainers);if(!a||a.length===0)continue;const f=[],l=new Set;for(const p of a){const y=se(p.url);y&&!l.has(y)&&(l.add(y),f.push(y))}f.length!==0&&n.push({owners:f,path:i===""||i==="."?"/":`/${i}/`,projectId:s})}return n},ie=["author","bugs","homepage","license","repository","engines"],v=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),C=(e,t)=>{if(e===t)return!0;if(typeof e!=typeof t||e===null||t===null)return!1;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(const[n,s]of e.entries())if(!C(s,t[n]))return!1;return!0}if(typeof e=="object"&&typeof t=="object"){const n=Object.keys(e),s=Object.keys(t);if(n.length!==s.length)return!1;for(const o of n)if(!C(e[o],t[o]))return!1;return!0}return!1},P=e=>e===void 0?e:structuredClone(e),ae=(e,t,n)=>{if(e==="repository"&&v(t)&&v(n)){const s={};for(const[o,i]of Object.entries(t))o!=="directory"&&(s[o]=P(i));return typeof n.directory=="string"&&(s.directory=n.directory),s}return P(t)},de=(e,t,n)=>{const s=[];for(const o of n.fields){if(!Object.hasOwn(e,o))continue;const i=e[o],c=t[o],r=ae(o,i,c);C(r,c)||s.push({after:r,before:c,field:o,packageJsonPath:""})}return s},fe=(e,t)=>{for(const n of t)e[n.field]=n.after},L="Generated by `vis sync codeowners --write-guard`. Do not edit by hand.",le=e=>{const t=e.replace(/^\.?\/+/u,"").replace(/\/+$/u,"");return t===""||t==="."?"**":`${t}/**`},T=e=>{const t=new Set,n=[];for(const s of[...e].sort((o,i)=>o.name.localeCompare(i.name))){const o=le(s.root);t.has(o)||(t.add(o),n.push(o))}return n},ue=e=>{const t=T(e),n=t.map(o=>` - "${o}"`).join(`
7
- `),s=t.map(o=>` ${o}`).join(`
8
- `);return`# ${L}
9
- name: Write Guard
10
-
11
- on:
12
- pull_request:
13
- paths:
14
- ${n}
15
-
16
- permissions:
17
- contents: read
18
- pull-requests: read
19
-
20
- jobs:
21
- write-guard:
22
- runs-on: ubuntu-latest
23
- steps:
24
- - uses: actions/checkout@v4
25
- with:
26
- fetch-depth: 0
27
- - uses: geritol/write-guard@v1
28
- with:
29
- codeowners: CODEOWNERS
30
- paths: |
31
- ${s}
32
- `},pe=e=>{const n=T(e).map(s=>` - "${s}/*"`).join(`
33
- `);return`# ${L}
34
- #
35
- # SOFT GUARD ONLY — this job does NOT block a merge by itself.
36
- # It verifies the generated CODEOWNERS is in sync and flags that a
37
- # restricted path changed. GitLab CI cannot portably gate a merge on
38
- # code-owner *approval* from a job, so REAL ENFORCEMENT REQUIRES the
39
- # native GitLab setting:
40
- # Settings -> Repository -> Protected branches ->
41
- # "Require approval from Code Owners" (GitLab Premium / Ultimate)
42
- # https://docs.gitlab.com/ee/user/project/codeowners/
43
- # Without that setting enabled, this job is advisory only.
44
- write-guard:
45
- stage: test
46
- image: node:22-alpine
47
- rules:
48
- - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
49
- changes:
50
- ${n}
51
- script:
52
- - corepack enable
53
- - pnpm install --frozen-lockfile
54
- - pnpm vis sync codeowners --check
55
- - >-
56
- echo "SOFT GUARD: a restricted path changed. This job does NOT enforce
57
- code-owner approval. Enable 'Require approval from Code Owners' on the
58
- protected branch (GitLab Premium/Ultimate) for a real merge gate:
59
- https://docs.gitlab.com/ee/user/project/codeowners/"
60
- `},he=e=>e.length===0?[]:[{content:ue(e),path:".github/workflows/write-guard.yml"},{content:pe(e),path:".gitlab/write-guard.gitlab-ci.yml"}],W=new Set(["nested-codeowners","package-json-maintainers","project-json"]),_=(e,t,n)=>{const s=new Set,o=[];for(const i of e??[])for(const c of i.split(",")){const r=c.trim();if(r.length===0)continue;if(n&&!n(r))throw new Error(`Unknown codeowners source: "${r}". Known: ${[...W].join(", ")}.`);const a=r;s.has(a)||(s.add(a),o.push(a))}return o.length>0?o:[...t]},ge=e=>W.has(e),S=["codeowners","package-json-fields"],me=(e,t)=>t.some(n=>x(n,e)),we=async(e,t,n,s,o)=>{const i=Object.entries(s.projects).filter(([,r])=>r.restricted===!0).map(([r,a])=>({name:r,root:a.root??r})),c=he(i);if(c.length===0){t.info("No projects flagged `restricted: true` in project.json. Skipping Write Guard.");return}if(o){let r=!1;for(const a of c){const f=b(n,a.path);let l="";try{l=await e.readFile(f,"utf8")}catch(p){if(p.code!=="ENOENT")throw p}l.trim()!==a.content.trim()&&(t.error(`${a.path} is out of date. Run \`vis sync codeowners --write-guard\` to update it.`),r=!0)}r?process.exitCode=1:t.info(`Write Guard CI is up to date (${c.length} files, ${i.length} restricted projects).`);return}for(const r of c){const a=b(n,r.path);M(G(a)),R(a,r.content),t.info(`Wrote ${r.path}`)}t.info(`Write Guard CI scoped to ${i.length} restricted project${i.length===1?"":"s"}.`)},ye=async({fs:e,logger:t,options:n,visConfig:s,workspaceRoot:o})=>{const i=o,{workspace:c}=U(i,s),r=s?.codeowners;n.writeGuard&&await we(e,t,i,c,n.check);const a=_(n.from,r?.sources??["project-json"],ge),f=n.regenerationCommand??r?.regenerationCommand,l=n.preserveBlock||r?.preserveBlock===!0,p=r?.blockMarker??O,y=n.nestedIncludes??r?.nestedIncludes,g=n.out??"CODEOWNERS",w=[];if(a.includes("nested-codeowners")){const m=await oe(i,y,g);for(const j of m)w.push({...j,source:"nested"})}if(a.includes("package-json-maintainers")){const m=ce(c,i);for(const j of m)w.push({...j,source:"maintainers"})}const u=a.includes("project-json")?N(c,r,w):N({projects:{}},r,w);if(u.length===0){t.info("No `owners` entries found in any source. Nothing to sync.");return}const $=b(i,g);let d="";try{d=await e.readFile($,"utf8")}catch(m){if(m.code!=="ENOENT")throw m}const h={regenerationCommand:f},k=l?Z(d,X(u,p,h),p):Q(u,h);if(n.check){if(d.trim()!==k.trim()){t.error(`${$} is out of date. Run \`vis sync codeowners\` to update it.`),process.exitCode=1;return}t.info(`${$} is up to date.`);return}R($,k),t.info(`Wrote ${u.length} entries to ${$}`)},ke=({logger:e,options:t,visConfig:n,workspaceRoot:s})=>{const o=s,i=n?.editorconfig??!0,c=E(b(o,"package.json"));if(!c){e.error("Could not read root package.json. Nothing to sync."),process.exitCode=1;return}const r=_(t.fields,ie),a=t.ignorePackageName??[],f=t.check,l=(t.format??"human").toLowerCase(),{quiet:p}=t,y=J(o).filter(d=>d!=="."),g=[];let w=0;for(const d of y){const h=b(o,d,"package.json"),k=E(h);if(!k)continue;const m=typeof k.name=="string"?k.name:void 0;if(m!==void 0&&a.length>0&&me(m,a))continue;w+=1;const j=de(c,k,{fields:r});j.length!==0&&g.push({filePath:h,packageJsonPath:I(o,h),packageName:m,pkg:k,pkgChanges:j})}if(!f)for(const d of g)fe(d.pkg,d.pkgChanges),q(d.filePath,d.pkg,{indent:F(d.filePath,{useEditorconfig:i}),overwrite:!0});const u=g.flatMap(d=>d.pkgChanges.map(h=>({after:h.after,before:h.before,field:h.field,packageJsonPath:d.packageJsonPath,packageName:d.packageName}))),$={changes:u,fields:r,kind:"package-json-fields",mode:f?"check":"write",totalChanges:u.length,totalPackages:w};if(l==="json")process.stdout.write(`${JSON.stringify($,null,4)}
61
- `);else if(u.length===0)e.info(`All ${w} package${w===1?"":"s"} in sync (fields: ${r.join(", ")}).`);else if(f){if(!p)for(const d of u)e.error(`${d.packageJsonPath}: ${d.field} drifts from root`);e.error(`Found ${u.length} field drift${u.length===1?"":"s"} across ${g.length} package${g.length===1?"":"s"}. Run \`vis sync package-json-fields\` to fix.`)}else{if(!p)for(const d of g)e.info(`${d.packageJsonPath}: synced ${d.pkgChanges.map(h=>h.field).join(", ")}`);e.info(`Synced ${u.length} field${u.length===1?"":"s"} across ${g.length} package${g.length===1?"":"s"}.`)}f&&u.length>0&&(process.exitCode=1)},Pe=async e=>{const t=e.argument[0];if(!t)throw new Error(`Missing sync kind. Usage: vis sync <kind> (known kinds: ${S.join(", ")})`);if(!e.workspaceRoot)throw new Error("Could not determine workspace root. Run inside a monorepo.");if(t==="codeowners"){await ye(e);return}if(t==="package-json-fields"){ke(e);return}throw new Error(`Unknown sync kind: "${t}". Known kinds: ${S.join(", ")}.`)};export{Pe as default};
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
+ `)}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=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
+ `);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
+ `),f.success(`Template '${E}' applied.`))}finally{L?.()}};export{Qe as default};
@@ -1,3 +1,61 @@
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
- `);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
- `)}},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
+ 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 M}from"../packem_shared/writeFileSync-DJoHk3Ks-CgQ-VNNT.js";import{T as q}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
+ `),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
+ `)},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
+
5
+ `}${t}
6
+ `},V=["**/CODEOWNERS"],ee=["**/node_modules/**","**/dist/**","**/build/**","**/coverage/**","**/.git/**","**/.next/**","**/.nuxt/**"],te=e=>{const t=[];for(const n of e.split(/\r?\n/u)){const s=n.indexOf("#"),o=(s===-1?n:n.slice(0,s)).trim();if(o.length===0)continue;const i=o.split(/\s+/u);if(i.length<2)continue;const[c,...r]=i,a=r.filter(f=>f.length>0);!c||a.length===0||t.push({owners:a,path:c})}return t},ne=(e,t)=>{const n=t.replace(/^\.\/?/,"").replace(/\/$/,"");return e.startsWith("/")?n===""?e:`/${n}${e}`:n===""?`/${e}`:`/${n}/${e}`},oe=async(e,t,n)=>{const s=t&&t.length>0?[...t]:[...V],o=[...ee];if(n){const r=n.replace(/^\.\/?/,"").replace(/^\/+/,"");r.length>0&&o.push(r)}const i=await K(s,{absolute:!0,cwd:e,ignore:o}),c=[];for(const r of i){let a;try{a=A(r)}catch{continue}const f=G(r),l=I(e,f);for(const p of te(a))c.push({owners:p.owners,path:ne(p.path,l)})}return c},re=/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/?#]+)/iu,se=e=>{if(!e)return;const t=e.match(re);if(!t?.[1])return;const n=t[1].trim();if(!(n===""||n.includes(" ")))return`@${n.replace(/^@/,"")}`},ce=(e,t)=>{const n=[];for(const[s,o]of Object.entries(e.projects)){if(o.owners&&o.owners.length>0)continue;const i=o.root??s,c=b(t,i,"package.json"),r=E(c);if(!r)continue;const a=B(r.maintainers);if(!a||a.length===0)continue;const f=[],l=new Set;for(const p of a){const y=se(p.url);y&&!l.has(y)&&(l.add(y),f.push(y))}f.length!==0&&n.push({owners:f,path:i===""||i==="."?"/":`/${i}/`,projectId:s})}return n},ie=["author","bugs","homepage","license","repository","engines"],v=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),C=(e,t)=>{if(e===t)return!0;if(typeof e!=typeof t||e===null||t===null)return!1;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(const[n,s]of e.entries())if(!C(s,t[n]))return!1;return!0}if(typeof e=="object"&&typeof t=="object"){const n=Object.keys(e),s=Object.keys(t);if(n.length!==s.length)return!1;for(const o of n)if(!C(e[o],t[o]))return!1;return!0}return!1},P=e=>e===void 0?e:structuredClone(e),ae=(e,t,n)=>{if(e==="repository"&&v(t)&&v(n)){const s={};for(const[o,i]of Object.entries(t))o!=="directory"&&(s[o]=P(i));return typeof n.directory=="string"&&(s.directory=n.directory),s}return P(t)},de=(e,t,n)=>{const s=[];for(const o of n.fields){if(!Object.hasOwn(e,o))continue;const i=e[o],c=t[o],r=ae(o,i,c);C(r,c)||s.push({after:r,before:c,field:o,packageJsonPath:""})}return s},fe=(e,t)=>{for(const n of t)e[n.field]=n.after},L="Generated by `vis sync codeowners --write-guard`. Do not edit by hand.",le=e=>{const t=e.replace(/^\.?\/+/u,"").replace(/\/+$/u,"");return t===""||t==="."?"**":`${t}/**`},T=e=>{const t=new Set,n=[];for(const s of[...e].sort((o,i)=>o.name.localeCompare(i.name))){const o=le(s.root);t.has(o)||(t.add(o),n.push(o))}return n},ue=e=>{const t=T(e),n=t.map(o=>` - "${o}"`).join(`
7
+ `),s=t.map(o=>` ${o}`).join(`
8
+ `);return`# ${L}
9
+ name: Write Guard
10
+
11
+ on:
12
+ pull_request:
13
+ paths:
14
+ ${n}
15
+
16
+ permissions:
17
+ contents: read
18
+ pull-requests: read
19
+
20
+ jobs:
21
+ write-guard:
22
+ runs-on: ubuntu-latest
23
+ steps:
24
+ - uses: actions/checkout@v4
25
+ with:
26
+ fetch-depth: 0
27
+ - uses: geritol/write-guard@v1
28
+ with:
29
+ codeowners: CODEOWNERS
30
+ paths: |
31
+ ${s}
32
+ `},pe=e=>{const n=T(e).map(s=>` - "${s}/*"`).join(`
33
+ `);return`# ${L}
34
+ #
35
+ # SOFT GUARD ONLY — this job does NOT block a merge by itself.
36
+ # It verifies the generated CODEOWNERS is in sync and flags that a
37
+ # restricted path changed. GitLab CI cannot portably gate a merge on
38
+ # code-owner *approval* from a job, so REAL ENFORCEMENT REQUIRES the
39
+ # native GitLab setting:
40
+ # Settings -> Repository -> Protected branches ->
41
+ # "Require approval from Code Owners" (GitLab Premium / Ultimate)
42
+ # https://docs.gitlab.com/ee/user/project/codeowners/
43
+ # Without that setting enabled, this job is advisory only.
44
+ write-guard:
45
+ stage: test
46
+ image: node:22-alpine
47
+ rules:
48
+ - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
49
+ changes:
50
+ ${n}
51
+ script:
52
+ - corepack enable
53
+ - pnpm install --frozen-lockfile
54
+ - pnpm vis sync codeowners --check
55
+ - >-
56
+ echo "SOFT GUARD: a restricted path changed. This job does NOT enforce
57
+ code-owner approval. Enable 'Require approval from Code Owners' on the
58
+ protected branch (GitLab Premium/Ultimate) for a real merge gate:
59
+ https://docs.gitlab.com/ee/user/project/codeowners/"
60
+ `},he=e=>e.length===0?[]:[{content:ue(e),path:".github/workflows/write-guard.yml"},{content:pe(e),path:".gitlab/write-guard.gitlab-ci.yml"}],W=new Set(["nested-codeowners","package-json-maintainers","project-json"]),_=(e,t,n)=>{const s=new Set,o=[];for(const i of e??[])for(const c of i.split(",")){const r=c.trim();if(r.length===0)continue;if(n&&!n(r))throw new Error(`Unknown codeowners source: "${r}". Known: ${[...W].join(", ")}.`);const a=r;s.has(a)||(s.add(a),o.push(a))}return o.length>0?o:[...t]},ge=e=>W.has(e),S=["codeowners","package-json-fields"],me=(e,t)=>t.some(n=>x(n,e)),we=async(e,t,n,s,o)=>{const i=Object.entries(s.projects).filter(([,r])=>r.restricted===!0).map(([r,a])=>({name:r,root:a.root??r})),c=he(i);if(c.length===0){t.info("No projects flagged `restricted: true` in project.json. Skipping Write Guard.");return}if(o){let r=!1;for(const a of c){const f=b(n,a.path);let l="";try{l=await e.readFile(f,"utf8")}catch(p){if(p.code!=="ENOENT")throw p}l.trim()!==a.content.trim()&&(t.error(`${a.path} is out of date. Run \`vis sync codeowners --write-guard\` to update it.`),r=!0)}r?process.exitCode=1:t.info(`Write Guard CI is up to date (${c.length} files, ${i.length} restricted projects).`);return}for(const r of c){const a=b(n,r.path);M(G(a)),R(a,r.content),t.info(`Wrote ${r.path}`)}t.info(`Write Guard CI scoped to ${i.length} restricted project${i.length===1?"":"s"}.`)},ye=async({fs:e,logger:t,options:n,visConfig:s,workspaceRoot:o})=>{const i=o,{workspace:c}=U(i,s),r=s?.codeowners;n.writeGuard&&await we(e,t,i,c,n.check);const a=_(n.from,r?.sources??["project-json"],ge),f=n.regenerationCommand??r?.regenerationCommand,l=n.preserveBlock||r?.preserveBlock===!0,p=r?.blockMarker??O,y=n.nestedIncludes??r?.nestedIncludes,g=n.out??"CODEOWNERS",w=[];if(a.includes("nested-codeowners")){const m=await oe(i,y,g);for(const j of m)w.push({...j,source:"nested"})}if(a.includes("package-json-maintainers")){const m=ce(c,i);for(const j of m)w.push({...j,source:"maintainers"})}const u=a.includes("project-json")?N(c,r,w):N({projects:{}},r,w);if(u.length===0){t.info("No `owners` entries found in any source. Nothing to sync.");return}const $=b(i,g);let d="";try{d=await e.readFile($,"utf8")}catch(m){if(m.code!=="ENOENT")throw m}const h={regenerationCommand:f},k=l?Z(d,X(u,p,h),p):Q(u,h);if(n.check){if(d.trim()!==k.trim()){t.error(`${$} is out of date. Run \`vis sync codeowners\` to update it.`),process.exitCode=1;return}t.info(`${$} is up to date.`);return}R($,k),t.info(`Wrote ${u.length} entries to ${$}`)},ke=({logger:e,options:t,visConfig:n,workspaceRoot:s})=>{const o=s,i=n?.editorconfig??!0,c=E(b(o,"package.json"));if(!c){e.error("Could not read root package.json. Nothing to sync."),process.exitCode=1;return}const r=_(t.fields,ie),a=t.ignorePackageName??[],f=t.check,l=(t.format??"human").toLowerCase(),{quiet:p}=t,y=J(o).filter(d=>d!=="."),g=[];let w=0;for(const d of y){const h=b(o,d,"package.json"),k=E(h);if(!k)continue;const m=typeof k.name=="string"?k.name:void 0;if(m!==void 0&&a.length>0&&me(m,a))continue;w+=1;const j=de(c,k,{fields:r});j.length!==0&&g.push({filePath:h,packageJsonPath:I(o,h),packageName:m,pkg:k,pkgChanges:j})}if(!f)for(const d of g)fe(d.pkg,d.pkgChanges),q(d.filePath,d.pkg,{indent:F(d.filePath,{useEditorconfig:i}),overwrite:!0});const u=g.flatMap(d=>d.pkgChanges.map(h=>({after:h.after,before:h.before,field:h.field,packageJsonPath:d.packageJsonPath,packageName:d.packageName}))),$={changes:u,fields:r,kind:"package-json-fields",mode:f?"check":"write",totalChanges:u.length,totalPackages:w};if(l==="json")process.stdout.write(`${JSON.stringify($,null,4)}
61
+ `);else if(u.length===0)e.info(`All ${w} package${w===1?"":"s"} in sync (fields: ${r.join(", ")}).`);else if(f){if(!p)for(const d of u)e.error(`${d.packageJsonPath}: ${d.field} drifts from root`);e.error(`Found ${u.length} field drift${u.length===1?"":"s"} across ${g.length} package${g.length===1?"":"s"}. Run \`vis sync package-json-fields\` to fix.`)}else{if(!p)for(const d of g)e.info(`${d.packageJsonPath}: synced ${d.pkgChanges.map(h=>h.field).join(", ")}`);e.info(`Synced ${u.length} field${u.length===1?"":"s"} across ${g.length} package${g.length===1?"":"s"}.`)}f&&u.length>0&&(process.exitCode=1)},Pe=async e=>{const t=e.argument[0];if(!t)throw new Error(`Missing sync kind. Usage: vis sync <kind> (known kinds: ${S.join(", ")})`);if(!e.workspaceRoot)throw new Error("Could not determine workspace root. Run inside a monorepo.");if(t==="codeowners"){await ye(e);return}if(t==="package-json-fields"){ke(e);return}throw new Error(`Unknown sync kind: "${t}". Known kinds: ${S.join(", ")}.`)};export{Pe as default};
@@ -1,6 +1,3 @@
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 u,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 ue{#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 fe=({checkMode:e,entry:r,focused:s,scrollRef:c})=>{const o=s?"white":"gray";return r?t.jsxs(u,{borderColor:o,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[t.jsx(u,{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(u,{children:[t.jsx(u,{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(u,{children:[t.jsx(u,{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(u,{flexDirection:"column",marginTop:1,children:[t.jsx(a,{dimColor:!0,children:"── "}),t.jsx(a,{bold:!0,color:"red",children:"ERROR"}),t.jsxs(u,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[t.jsxs(u,{children:[t.jsx(u,{width:10,children:t.jsx(a,{dimColor:!0,children:"Step:"})}),t.jsx(a,{color:"yellow",children:r.error.step})]}),r.error.context&&t.jsxs(u,{children:[t.jsx(u,{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(u,{marginTop:1,children:t.jsx(a,{color:"red",children:r.error.message})})]})]}),r.error.context&&r.error.context.snippet.length>0&&t.jsxs(u,{flexDirection:"column",marginTop:1,children:[t.jsx(a,{dimColor:!0,children:"── "}),t.jsx(a,{bold:!0,color:"white",children:"SNIPPET"}),t.jsxs(u,{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(u,{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(u,{children:t.jsx(a,{color:"red",children:`${" ".repeat(7+r.error.context.column-1)}↑`})})]})]})]}):t.jsxs(u,{flexDirection:"column",marginTop:1,children:[t.jsx(a,{dimColor:!0,children:"── "}),t.jsx(a,{bold:!0,color:"white",children:"KEY DIFF"}),t.jsx(u,{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)}`,f=i<0?"green":"yellow";return t.jsxs(u,{children:[t.jsx(u,{width:28,children:t.jsx(a,{wrap:"truncate",children:n.key})}),t.jsx(u,{width:10,children:t.jsxs(a,{dimColor:!0,children:[String(n.fromIndex)," → ",String(n.toIndex)]})}),t.jsx(a,{color:f,children:d})]},n.key)})}),e&&r.status==="would-rewrite"&&t.jsx(u,{marginTop:1,paddingLeft:2,children:t.jsx(a,{dimColor:!0,children:"--check mode: no write performed."})})]})]})]}):t.jsx(u,{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(u,{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(u,{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(u,{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",f=X(r),x=(f.errors>0?1:0)+(f.rewrites>0?1:0)+(f.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:f[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(u,{borderColor:d,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[t.jsxs(u,{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(u,{flexShrink:0,gap:1,paddingX:1,paddingY:1,children:pe.map(l=>{const g=s===l.key,k=l.count(e);return t.jsxs(u,{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(u,{flexDirection:"row",flexGrow:1,overflow:"hidden",children:[t.jsx(u,{flexDirection:"column",flexGrow:1,overflow:"hidden",paddingLeft:1,children:t.jsx(u,{flexDirection:"column",marginTop:-b,children:h.map((l,g)=>l.kind==="spacer"?t.jsx(u,{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(u,{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(),f=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(u,{alignItems:"center",justifyContent:"center",children:t.jsxs(a,{color:"yellow",children:["Terminal too small. Resize to at least",D," ","rows."]})}):t.jsxs(u,{flexDirection:"column",height:o,width:c,children:[t.jsxs(u,{flexDirection:m?"row":"column",flexGrow:1,children:[t.jsx(u,{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(u,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:t.jsx(fe,{checkMode:e,entry:f,focused:n.focusedPanel==="detail",scrollRef:i})})]}),t.jsx(u,{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,f)=>d===r[f]))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 f=A(e,d);for(const x of f)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
- `)?"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
- `);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 f=o.get(d);f!==void 0&&f!==i&&n.push({fromIndex:f,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},f=Pe(i,d);let x=JSON.stringify(f.pkg,null,c);return r.finalNewline&&(x+=`
4
- `),o==="crlf"&&(x=x.replaceAll(`
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: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 f=o.editorconfig?ie(e):{};let x;try{x=We(i,o,f)}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,f={editorconfig:r.editorconfig?n?.editorconfig??!0:!1,finalNewline:r.finalNewline??n?.finalNewline??!0,formatBugs:r.formatBugs?n?.formatBugs??!0:!1,formatRepository:r.formatRepository?n?.formatRepository??!0:!1,ignore:[...P(r.ignore),...n?.ignore??[]],indent:_e(r.indent??n?.indent),lineEnding:Fe(r.lineEnding??n?.lineEnding),sortExports:r.sortExports?n?.sortExports??!0:!1,sortOrder:[...P(r.sortOrder),...n?.sortOrder??[]],sortScripts:r.sortScripts||n?.sortScripts||!1,unsorted:[...P(r.unsorted),...n?.unsorted??[]]},x=Xe(o,f.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:f}));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 ue(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
+ 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-sXNQYpsl.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
+ `);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
+ `)}},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,9 +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(`^(?:\\*\\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
- `;)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:/^-(?=.*\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
-
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
- `),E=A[0]?.trim()??"",L=A[1]?.trim()??"",b=A.slice(2).join(`
7
- `).trim(),y=(g??"").split(`
8
- `).map(q=>q.trim()).filter(Boolean);E&&m.push({body:b,files:y,hash:E,subject:L})}const{commits:P,warnings:T}=Re(m,void 0,`${d}..HEAD`);for(const f of T)e.warn(f);for(const{cancelled:f,files:g,parsed:p,subject:A}of P){if(f)continue;let E="patch";p.breaking?E="major":p.type&&D[p.type]&&(E=D[p.type]??"patch");const L=new Set;if(p.scope)for(const b of i.packages)(b.name===p.scope||b.name.endsWith(`/${p.scope}`))&&L.add(b.name);if(L.size===0)for(const b of g){const y=w(b);y&&L.add(y)}for(const b of L){const y=l.get(b);l.set(b,y?ne(y,E):E)}L.size>0&&a.push(`- ${A}`)}if(l.size===0){e.info("No commits affected workspace packages — nothing to generate.");return}const O={bumps:Object.fromEntries(l)},K=a.length>0?a.join(`
9
- `):"Auto-generated change file.",j=Q(O,K);if(t.dryRun){e.info("[dry-run] would write:"),e.info(j);return}const M=i.config.changesDir??Y,W=(t.name??te()).replaceAll(/[^a-z0-9-]/gi,"-"),H=N(s,M,`${W}.md`);await r.mkdir(N(s,M),{recursive:!0}),await r.writeFile(H,j),e.info(`Created ${J(s,H)}`);for(const[f,g]of l)e.info(` ${f}: ${g}`)};export{Ae as default};
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 u,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 ue{#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 fe=({checkMode:e,entry:r,focused:s,scrollRef:c})=>{const o=s?"white":"gray";return r?t.jsxs(u,{borderColor:o,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[t.jsx(u,{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(u,{children:[t.jsx(u,{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(u,{children:[t.jsx(u,{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(u,{flexDirection:"column",marginTop:1,children:[t.jsx(a,{dimColor:!0,children:"── "}),t.jsx(a,{bold:!0,color:"red",children:"ERROR"}),t.jsxs(u,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[t.jsxs(u,{children:[t.jsx(u,{width:10,children:t.jsx(a,{dimColor:!0,children:"Step:"})}),t.jsx(a,{color:"yellow",children:r.error.step})]}),r.error.context&&t.jsxs(u,{children:[t.jsx(u,{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(u,{marginTop:1,children:t.jsx(a,{color:"red",children:r.error.message})})]})]}),r.error.context&&r.error.context.snippet.length>0&&t.jsxs(u,{flexDirection:"column",marginTop:1,children:[t.jsx(a,{dimColor:!0,children:"── "}),t.jsx(a,{bold:!0,color:"white",children:"SNIPPET"}),t.jsxs(u,{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(u,{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(u,{children:t.jsx(a,{color:"red",children:`${" ".repeat(7+r.error.context.column-1)}↑`})})]})]})]}):t.jsxs(u,{flexDirection:"column",marginTop:1,children:[t.jsx(a,{dimColor:!0,children:"── "}),t.jsx(a,{bold:!0,color:"white",children:"KEY DIFF"}),t.jsx(u,{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)}`,f=i<0?"green":"yellow";return t.jsxs(u,{children:[t.jsx(u,{width:28,children:t.jsx(a,{wrap:"truncate",children:n.key})}),t.jsx(u,{width:10,children:t.jsxs(a,{dimColor:!0,children:[String(n.fromIndex)," → ",String(n.toIndex)]})}),t.jsx(a,{color:f,children:d})]},n.key)})}),e&&r.status==="would-rewrite"&&t.jsx(u,{marginTop:1,paddingLeft:2,children:t.jsx(a,{dimColor:!0,children:"--check mode: no write performed."})})]})]})]}):t.jsx(u,{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(u,{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(u,{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(u,{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",f=X(r),x=(f.errors>0?1:0)+(f.rewrites>0?1:0)+(f.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:f[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(u,{borderColor:d,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[t.jsxs(u,{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(u,{flexShrink:0,gap:1,paddingX:1,paddingY:1,children:pe.map(l=>{const g=s===l.key,k=l.count(e);return t.jsxs(u,{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(u,{flexDirection:"row",flexGrow:1,overflow:"hidden",children:[t.jsx(u,{flexDirection:"column",flexGrow:1,overflow:"hidden",paddingLeft:1,children:t.jsx(u,{flexDirection:"column",marginTop:-b,children:h.map((l,g)=>l.kind==="spacer"?t.jsx(u,{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(u,{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(),f=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(u,{alignItems:"center",justifyContent:"center",children:t.jsxs(a,{color:"yellow",children:["Terminal too small. Resize to at least",D," ","rows."]})}):t.jsxs(u,{flexDirection:"column",height:o,width:c,children:[t.jsxs(u,{flexDirection:m?"row":"column",flexGrow:1,children:[t.jsx(u,{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(u,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:t.jsx(fe,{checkMode:e,entry:f,focused:n.focusedPanel==="detail",scrollRef:i})})]}),t.jsx(u,{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,f)=>d===r[f]))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 f=A(e,d);for(const x of f)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
+ `)?"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
+ `);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 f=o.get(d);f!==void 0&&f!==i&&n.push({fromIndex:f,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},f=Pe(i,d);let x=JSON.stringify(f.pkg,null,c);return r.finalNewline&&(x+=`
4
+ `),o==="crlf"&&(x=x.replaceAll(`
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: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 f=o.editorconfig?ie(e):{};let x;try{x=We(i,o,f)}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,f={editorconfig:r.editorconfig?n?.editorconfig??!0:!1,finalNewline:r.finalNewline??n?.finalNewline??!0,formatBugs:r.formatBugs?n?.formatBugs??!0:!1,formatRepository:r.formatRepository?n?.formatRepository??!0:!1,ignore:[...P(r.ignore),...n?.ignore??[]],indent:_e(r.indent??n?.indent),lineEnding:Fe(r.lineEnding??n?.lineEnding),sortExports:r.sortExports?n?.sortExports??!0:!1,sortOrder:[...P(r.sortOrder),...n?.sortOrder??[]],sortScripts:r.sortScripts||n?.sortScripts||!1,unsorted:[...P(r.unsorted),...n?.unsorted??[]]},x=Xe(o,f.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:f}));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 ue(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,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-Bkk_uRS-.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-CHdDsn0O.js";import{q as ie,j as ae,F as v,b as S,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-d93_73O6.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),$=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,M=e=>{if(typeof $<"u"&&$.versions&&$.versions.node){const[t,s]=$.versions.node.split(".").map(Number);if(t>22||t===22&&s>=3||t===20&&s>=16)return $.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,u=0;for(const[c,l]of s.entries()){const f=r.exec(l);if(f&&a.test(f[2])){n=c,u=f[1].length;break}}if(n===-1)return;const i=[];for(let c=n+1;c<s.length;c+=1){const l=r.exec(s[c]);if(l&&l[1].length<=u)break;i.push(s[c])}return i},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]??""),i=Object.entries(r).filter(([c])=>c!=="created"&&c!=="modified"&&c!==t).sort((c,l)=>Date.parse(l[1])-Date.parse(c[1])).filter(([,c])=>Date.parse(c)<n).slice(0,3);for(const[c,l]of i)a.push(`- ${c} (${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 c of x){const l=`https://cdn.jsdelivr.net/npm/${t}@${n}/${c}`,f=await C(l,a);if(f){const y=O(f,n),p=I(y??f.split(/\r?\n/));if(p.length>0)return{lines:p,source:"package-file",url:l,version:n}}}const u=o?.versions[n],i=$e(u?.repository);if(i){const c=i.directory?`${i.directory.replaceAll(/^\/+|\/+$/g,"")}/`:"";for(const l of["HEAD","main","master"])for(const f of x){const y=`https://raw.githubusercontent.com/${i.owner}/${i.repo}/${l}/${c}${f}`,p=await C(y,a);if(p){const m=O(p,n),h=I(m??p.split(/\r?\n/));if(h.length>0){const d=`https://github.com/${i.owner}/${i.repo}/blob/${l}/${c}${f}`;return{lines:h,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:u}=e;let i;try{i=await ne(t,{offline:r,signal:o,workspaceRoot:u})}catch{i=void 0}const c=i?ce(i,n):void 0;if(!c)return;const l=i?.versions[c],f=async()=>{if(!(r||!a))try{const g=await J([{name:t,version:c}],{apiToken:a,minimumScore:Q});return _e(g,t,c)}catch{return}},y=Se({name:t,now:s,offline:r,packument:i,signal:o,version:c}).catch(()=>{}),[p,m]=await Promise.all([f(),y]),h=p?.alerts??[],d=[...new Set(h.filter(g=>g.severity==="critical"||g.severity==="high").map(g=>g.key))].sort(),b=p?Math.round((p.score.overall??X(p.score))*100):void 0;return{changelog:m,name:t,permissions:Ee(l,h),security:{alerts:h,available:!!p,highSeverityKeys:d,score:b},size:Te(l,p),version:c}},w=e=>Z(G(e)),Re={critical:E,high:E,low:v,medium:S},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?S: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 u=[],i=["critical","high","medium","low"];for(const l of i){const f=n.get(l);f&&u.push(Re[l](`${String(f)} ${l}`))}const c=u.length>0?` ${S("!")} ${u.join(", ")}`:` ${A("no alerts")}`;return`${o(a)} ${v("(Socket.dev)")}${c}`},Oe=e=>{const{bins:t,capabilities:s,lifecycleScripts:r}=e.permissions,o=[];for(const a of r)o.push(S(`${a} script`));for(const a of s)o.push(S(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 i of t)i.values.forEach((c,l)=>{const f=l===0?ie(i.label.padEnd(j)):" ".repeat(j);r.push(`${f} ${c}`)});const o=Math.max(w(s),...r.map(i=>w(i))),a=i=>`${i}${" ".repeat(Math.max(0,o-w(i)))}`,n=`┌─${ae(s)}${"─".repeat(Math.max(0,o-w(s)))}─┐`,u=`└─${"─".repeat(o)}─┘`;return[n,...r.map(i=>`│ ${a(i)} │`),u]},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:u=!1}=e;if(s||!De(o))return{proceed:!0};const i=e.now??Date.now(),c=u||!de({isCi:e.isCi,isTty:e.isTty}),l=e.output??Me;if(c&&!t)return{proceed:!0};const{name:f,spec:y}=Ne(o),p=new AbortController;let m;const h=new Promise(T=>{m=setTimeout(()=>{p.abort(),T(void 0)},je)}),d=await Promise.race([Ae({name:f,now:i,offline:r,signal:p.signal,socketToken:a,spec:y,workspaceRoot:n}).catch(()=>{}),h]);if(m&&clearTimeout(m),!d)return{proceed:!0};const b=ge(P(),d.name,d.version);if(!t&&!ye(b,d.security.highSeverityKeys))return{proceed:!0};for(const T of Le(d))l(`${T}
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-Bkk_uRS-.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-CHdDsn0O.js";import{q as ie,j as ae,F as v,b as S,X as E,J as A}from"../packem_shared/index.server-sXNQYpsl.js";import{a as le,o as fe}from"../packem_shared/pm-runner-d93_73O6.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),$=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,M=e=>{if(typeof $<"u"&&$.versions&&$.versions.node){const[t,s]=$.versions.node.split(".").map(Number);if(t>22||t===22&&s>=3||t===20&&s>=16)return $.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,u=0;for(const[c,l]of s.entries()){const f=r.exec(l);if(f&&a.test(f[2])){n=c,u=f[1].length;break}}if(n===-1)return;const i=[];for(let c=n+1;c<s.length;c+=1){const l=r.exec(s[c]);if(l&&l[1].length<=u)break;i.push(s[c])}return i},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]??""),i=Object.entries(r).filter(([c])=>c!=="created"&&c!=="modified"&&c!==t).sort((c,l)=>Date.parse(l[1])-Date.parse(c[1])).filter(([,c])=>Date.parse(c)<n).slice(0,3);for(const[c,l]of i)a.push(`- ${c} (${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 c of x){const l=`https://cdn.jsdelivr.net/npm/${t}@${n}/${c}`,f=await C(l,a);if(f){const y=O(f,n),p=I(y??f.split(/\r?\n/));if(p.length>0)return{lines:p,source:"package-file",url:l,version:n}}}const u=o?.versions[n],i=$e(u?.repository);if(i){const c=i.directory?`${i.directory.replaceAll(/^\/+|\/+$/g,"")}/`:"";for(const l of["HEAD","main","master"])for(const f of x){const y=`https://raw.githubusercontent.com/${i.owner}/${i.repo}/${l}/${c}${f}`,p=await C(y,a);if(p){const m=O(p,n),h=I(m??p.split(/\r?\n/));if(h.length>0){const d=`https://github.com/${i.owner}/${i.repo}/blob/${l}/${c}${f}`;return{lines:h,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:u}=e;let i;try{i=await ne(t,{offline:r,signal:o,workspaceRoot:u})}catch{i=void 0}const c=i?ce(i,n):void 0;if(!c)return;const l=i?.versions[c],f=async()=>{if(!(r||!a))try{const g=await J([{name:t,version:c}],{apiToken:a,minimumScore:Q});return _e(g,t,c)}catch{return}},y=Se({name:t,now:s,offline:r,packument:i,signal:o,version:c}).catch(()=>{}),[p,m]=await Promise.all([f(),y]),h=p?.alerts??[],d=[...new Set(h.filter(g=>g.severity==="critical"||g.severity==="high").map(g=>g.key))].sort(),b=p?Math.round((p.score.overall??X(p.score))*100):void 0;return{changelog:m,name:t,permissions:Ee(l,h),security:{alerts:h,available:!!p,highSeverityKeys:d,score:b},size:Te(l,p),version:c}},w=e=>Z(G(e)),Re={critical:E,high:E,low:v,medium:S},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?S: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 u=[],i=["critical","high","medium","low"];for(const l of i){const f=n.get(l);f&&u.push(Re[l](`${String(f)} ${l}`))}const c=u.length>0?` ${S("!")} ${u.join(", ")}`:` ${A("no alerts")}`;return`${o(a)} ${v("(Socket.dev)")}${c}`},Oe=e=>{const{bins:t,capabilities:s,lifecycleScripts:r}=e.permissions,o=[];for(const a of r)o.push(S(`${a} script`));for(const a of s)o.push(S(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 i of t)i.values.forEach((c,l)=>{const f=l===0?ie(i.label.padEnd(j)):" ".repeat(j);r.push(`${f} ${c}`)});const o=Math.max(w(s),...r.map(i=>w(i))),a=i=>`${i}${" ".repeat(Math.max(0,o-w(i)))}`,n=`┌─${ae(s)}${"─".repeat(Math.max(0,o-w(s)))}─┐`,u=`└─${"─".repeat(o)}─┘`;return[n,...r.map(i=>`│ ${a(i)} │`),u]},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:u=!1}=e;if(s||!De(o))return{proceed:!0};const i=e.now??Date.now(),c=u||!de({isCi:e.isCi,isTty:e.isTty}),l=e.output??Me;if(c&&!t)return{proceed:!0};const{name:f,spec:y}=Ne(o),p=new AbortController;let m;const h=new Promise(T=>{m=setTimeout(()=>{p.abort(),T(void 0)},je)}),d=await Promise.race([Ae({name:f,now:i,offline:r,signal:p.signal,socketToken:a,spec:y,workspaceRoot:n}).catch(()=>{}),h]);if(m&&clearTimeout(m),!d)return{proceed:!0};const b=ge(P(),d.name,d.version);if(!t&&!ye(b,d.security.highSeverityKeys))return{proceed:!0};for(const T of Le(d))l(`${T}
2
2
  `);if(c)return R(d.name,d.version,d.security.highSeverityKeys,i),{proceed:!0};const g=await Y("? Ok to proceed? (y/N) ",e.readline);return g&&R(d.name,d.version,d.security.highSeverityKeys,i),{proceed:g}},Je=async({argument:e,logger:t,options:s,process:r,visConfig:o,workspaceRoot:a})=>{const n=e;if(!n||n.length===0)throw new Error("No package specified. Usage: vis dlx <package[@version]> [args...]");const[u,...i]=n,c=a??r.cwd,l=s.package?Array.isArray(s.package)?s.package:[s.package]:[],f=s.shellMode?l:[u,...l];for(const h of f){const d=!s.info||_(r.env.VIS_DLX_NO_INFO),b=!d&&s.info;if(!(await Be({forceInfo:b,noInfo:d,offline:s.offline||!1,pkg:h,socketToken:o?.security?.socket?.apiToken??r.env.VIS_SOCKET_TOKEN,workspaceRoot:c,yes:s.yes||_(r.env.VIS_DLX_YES)})).proceed){t.info("Aborted."),process.exitCode=1;return}}const y=ue({logger:t,options:s,visConfig:o},c),p=le(c,{backend:pe(y),configBackend:o?.install?.backend,configCorepack:o?.install?.corepack}),m=fe(p,{additionalPackages:l,args:i,package:u,shellMode:s.shellMode||!1,silent:s.silent||!1},c,t,{offline:s.offline||!1});m!==0&&(process.exitCode=m)};export{Je as default};