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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/dist/bin.js +1 -1
  3. package/dist/binx.js +1 -1
  4. package/dist/packem_chunks/CONFIG_FILES.js +3 -3
  5. package/dist/packem_chunks/agent-instructions.js +11 -0
  6. package/dist/packem_chunks/bloom-status.js +1 -1
  7. package/dist/packem_chunks/bloom-sync.js +1 -1
  8. package/dist/packem_chunks/catalog.js +63 -62
  9. package/dist/packem_chunks/cli-exec.js +1 -1
  10. package/dist/packem_chunks/cli-main.js +172 -973
  11. package/dist/packem_chunks/defineReleasePlugin.js +3 -0
  12. package/dist/packem_chunks/detect.js +1 -1
  13. package/dist/packem_chunks/fix.js +1 -1
  14. package/dist/packem_chunks/group-tags.js +1 -0
  15. package/dist/packem_chunks/handler.js +1 -1
  16. package/dist/packem_chunks/handler10.js +1 -1
  17. package/dist/packem_chunks/handler11.js +1 -1
  18. package/dist/packem_chunks/handler12.js +2 -2
  19. package/dist/packem_chunks/handler13.js +1 -1
  20. package/dist/packem_chunks/handler14.js +1 -1
  21. package/dist/packem_chunks/handler15.js +1 -1
  22. package/dist/packem_chunks/handler16.js +1 -1
  23. package/dist/packem_chunks/handler17.js +1 -1
  24. package/dist/packem_chunks/handler18.js +1 -1
  25. package/dist/packem_chunks/handler19.js +1 -1
  26. package/dist/packem_chunks/handler20.js +1 -1
  27. package/dist/packem_chunks/handler21.js +1 -1
  28. package/dist/packem_chunks/handler24.js +1 -1
  29. package/dist/packem_chunks/handler26.js +1 -1
  30. package/dist/packem_chunks/handler27.js +1 -1
  31. package/dist/packem_chunks/handler28.js +1 -1
  32. package/dist/packem_chunks/handler29.js +1 -1
  33. package/dist/packem_chunks/handler3.js +1 -1
  34. package/dist/packem_chunks/handler30.js +1 -1
  35. package/dist/packem_chunks/handler32.js +1 -1
  36. package/dist/packem_chunks/handler4.js +1 -1
  37. package/dist/packem_chunks/handler40.js +19 -19
  38. package/dist/packem_chunks/handler5.js +3 -3
  39. package/dist/packem_chunks/handler50.js +4 -4
  40. package/dist/packem_chunks/handler51.js +3 -3
  41. package/dist/packem_chunks/handler54.js +1 -1
  42. package/dist/packem_chunks/handler57.js +11 -5
  43. package/dist/packem_chunks/handler58.js +5 -11
  44. package/dist/packem_chunks/handler59.js +11 -3
  45. package/dist/packem_chunks/handler6.js +6 -6
  46. package/dist/packem_chunks/handler60.js +3 -22
  47. package/dist/packem_chunks/handler61.js +21 -60
  48. package/dist/packem_chunks/handler62.js +61 -3
  49. package/dist/packem_chunks/handler63.js +3 -6
  50. package/dist/packem_chunks/handler64.js +6 -9
  51. package/dist/packem_chunks/handler65.js +9 -2
  52. package/dist/packem_chunks/handler66.js +2 -24
  53. package/dist/packem_chunks/handler67.js +24 -25
  54. package/dist/packem_chunks/handler68.js +25 -153
  55. package/dist/packem_chunks/handler69.js +153 -10
  56. package/dist/packem_chunks/handler7.js +1 -1
  57. package/dist/packem_chunks/handler70.js +10 -23
  58. package/dist/packem_chunks/handler71.js +23 -322
  59. package/dist/packem_chunks/handler72.js +273 -659
  60. package/dist/packem_chunks/handler73.js +708 -48
  61. package/dist/packem_chunks/handler74.js +48 -27
  62. package/dist/packem_chunks/handler75.js +27 -3
  63. package/dist/packem_chunks/handler76.js +3 -190
  64. package/dist/packem_chunks/handler77.js +189 -37
  65. package/dist/packem_chunks/handler78.js +38 -0
  66. package/dist/packem_chunks/handler9.js +1 -1
  67. package/dist/packem_chunks/heal-accept.js +1 -1
  68. package/dist/packem_chunks/heal.js +1 -1
  69. package/dist/packem_chunks/help-command.js +1 -1
  70. package/dist/packem_chunks/index2.js +802 -7
  71. package/dist/packem_chunks/index3.js +7 -135
  72. package/dist/packem_chunks/index4.js +134 -73
  73. package/dist/packem_chunks/index5.js +74 -0
  74. package/dist/packem_chunks/keys-refresh.js +1 -1
  75. package/dist/packem_chunks/lean.js +1 -1
  76. package/dist/packem_chunks/list.js +1 -1
  77. package/dist/packem_chunks/loader.js +1 -1
  78. package/dist/packem_chunks/orchestrator.js +26 -23
  79. package/dist/packem_chunks/print-config.js +1 -1
  80. package/dist/packem_chunks/prune.js +1 -1
  81. package/dist/packem_chunks/registry.js +2 -2
  82. package/dist/packem_chunks/shell-runner.js +1 -1
  83. package/dist/packem_chunks/state.js +3 -3
  84. package/dist/packem_chunks/status.js +1 -1
  85. package/dist/packem_chunks/sync.js +1 -1
  86. package/dist/packem_chunks/sync2.js +1 -1
  87. package/dist/packem_chunks/tripwire.js +2 -2
  88. package/dist/packem_chunks/ts-loader.js +1 -1
  89. package/dist/packem_chunks/verify-lockfile.js +1 -1
  90. package/dist/packem_chunks/version-resolver.js +2 -2
  91. package/dist/packem_shared/ReleaseClient-BY4OZNCK.js +1 -0
  92. package/dist/packem_shared/{advisories-CefYKEPe.js → advisories-B76fBVL-.js} +1 -1
  93. package/dist/packem_shared/affected-shas-CCxG4tvm.js +1 -0
  94. package/dist/packem_shared/{ai-analysis-CO6S0afy.js → ai-analysis-DF_AfeS3.js} +4 -4
  95. package/dist/packem_shared/{ai-fix-CI0Vvqld.js → ai-fix-D1bFLkfk.js} +3 -3
  96. package/dist/packem_shared/bin-BlGVEhl8.js +1 -0
  97. package/dist/packem_shared/{build-scripts-MTSK6TNr.js → build-scripts-q__dKE2y.js} +1 -1
  98. package/dist/packem_shared/{command-runtime-BE-vKsGH.js → command-runtime-3FTGuUsK.js} +1 -1
  99. package/dist/packem_shared/{cyclonedx-BeUmPgfO.js → cyclonedx-CmrYQ0vx.js} +1 -1
  100. package/dist/packem_shared/{docker-CViFYtmM.js → docker-BYqiD711.js} +1 -1
  101. package/dist/packem_shared/{env-C2ZCnfP_.js → env-DJlbJiFh.js} +2 -2
  102. package/dist/packem_shared/{failure-log-jFfZRJK9.js → failure-log-Bt7sW4p7.js} +1 -1
  103. package/dist/packem_shared/{index-D7EZ612R.js → index-C6tpgeIV.js} +2 -2
  104. package/dist/packem_shared/{index-CQjzW7m8.js → index-D6fJJDli.js} +1 -1
  105. package/dist/packem_shared/{lifecycle-Dyb47wbD.js → lifecycle-XeMei1ED.js} +1 -1
  106. package/dist/packem_shared/{manifests-WBnsV_Eb.js → manifests-DSBr3-dw.js} +1 -1
  107. package/dist/packem_shared/{native-config-sync-BFDVK9LH.js → native-config-sync-D-z2Uwqu.js} +1 -1
  108. package/dist/packem_shared/{osv-bloom-BsQ-aFiM.js → osv-bloom-DMhXP184.js} +2 -2
  109. package/dist/packem_shared/{packument-DquNPIq9.js → packument-CY2QDFml.js} +1 -1
  110. package/dist/packem_shared/plugins.d-ND23R9I3.d.ts +4 -0
  111. package/dist/packem_shared/pm-runner-CQcraCcu.js +1 -0
  112. package/dist/packem_shared/{provenance-DIq8KyBV.js → provenance-DVHiWZrW.js} +1 -1
  113. package/dist/packem_shared/{registry-keys-C8K11ets.js → registry-keys-BKEq72qX.js} +1 -1
  114. package/dist/packem_shared/{resolve-explicit-Dr4kIybR.js → resolve-explicit-UtkNrGKq.js} +1 -1
  115. package/dist/packem_shared/resolve-runtime-QRaQucfL.js +1 -0
  116. package/dist/packem_shared/{runtime-check-BXehSP06.js → runtime-check-qnrPTlma.js} +1 -1
  117. package/dist/packem_shared/{s1ngularity-CtMmtXJo.js → s1ngularity-DUZtU95L.js} +1 -1
  118. package/dist/packem_shared/scan-progress-BgtHexnt.js +2 -0
  119. package/dist/packem_shared/{signatures-CE8OAK-i.js → signatures-QoCuUv9E.js} +1 -1
  120. package/dist/packem_shared/target-merge-Dg25Izl5.js +11 -0
  121. package/dist/packem_shared/{toolchain-C44mPKPu.js → toolchain-Zb3VzZb4.js} +1 -1
  122. package/dist/packem_shared/{typosquats-CQz-1Y6K.js → typosquats-C12CP_2G.js} +1 -1
  123. package/dist/packem_shared/use-measured-height-BpKmrlkw.js +1 -0
  124. package/dist/packem_shared/{vis-update-app-Cpme_3Du.js → vis-update-app-BoCQ4ute.js} +1 -1
  125. package/dist/packem_shared/{watch-loop-JfGKIgKB.js → watch-loop-BZudYfcl.js} +1 -1
  126. package/dist/release/index.d.ts +39 -2
  127. package/dist/release/index.js +1 -1
  128. package/dist/release/plugin-sdk.d.ts +2 -1
  129. package/dist/release/plugin-sdk.js +1 -1
  130. package/dist/release/types.d.ts +117 -1
  131. package/dist/release/types.js +1 -1
  132. package/index.js +52 -52
  133. package/package.json +11 -11
  134. package/schemas/vis-config.schema.json +33 -0
  135. package/schemas/vis-release-config.schema.json +33 -0
  136. package/dist/packem_shared/ReleaseClient-YHzBIxYS.js +0 -1
  137. package/dist/packem_shared/affected-shas-CwRY5aoc.js +0 -1
  138. package/dist/packem_shared/bin-P6Q5tKrP.js +0 -1
  139. package/dist/packem_shared/pm-runner-D4jM58Oz.js +0 -1
  140. package/dist/packem_shared/resolve-runtime-Tx0bvg0h.js +0 -1
  141. package/dist/packem_shared/scan-progress-D4yywI6P.js +0 -2
  142. package/dist/packem_shared/target-merge-DOm6h6tW.js +0 -11
  143. package/dist/packem_shared/use-measured-height-XK9YSwtv.js +0 -1
  144. package/dist/packem_shared/window-ops-DDePlWLV.js +0 -2
  145. /package/dist/packem_shared/{readJsonSync-CvkZyKmL-ihoybKvs.js → readJsonSync-DuMMeB3s-ihoybKvs.js} +0 -0
@@ -1,22 +1,3 @@
1
- import{createRequire as te}from"node:module";import{E as u,j as g,q as y}from"../packem_shared/index.server-J83sowC4.js";import{m as T,f as j,I as V,H as G,y as K,a as L,A as P,o as se,T as ne,B as oe}from"../packem_shared/index-CE6MsgcV.js";import{f as ue}from"../packem_shared/giget-DVTFJlbR.js";import{p as l}from"./cli-main.js";const re=te(import.meta.url),R=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,E=t=>{if(typeof R<"u"&&R.versions&&R.versions.node){const[e,r]=R.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return R.getBuiltinModule(t)}return re(t)},{fileURLToPath:ie}=E("node:url"),{createInterface:ae}=E("node:readline"),{mkdtempSync:ce,rmSync:le}=E("node:fs"),{tmpdir:fe}=E("node:os"),{spawnSync:pe}=E("node:child_process"),J=[".ts",".mts",".cts",".js",".mjs",".cjs"],de="template.yml",me=[".d",".test",".spec",".config",".bench",".stories"],he=[".d.ts",".d.mts",".d.cts",".js.map",".mjs.map",".cjs.map",".ts.map"],Y=t=>{for(const e of J)if(t.endsWith(e))return t.slice(0,-e.length);return t},$e=t=>{if(he.some(r=>t.endsWith(r))||!J.some(r=>t.endsWith(r)))return!1;const e=Y(t);return!me.some(r=>e.endsWith(r))},H=(t,e)=>{const r=[];if(!j(t))return r;for(const s of V(t,{includeDirs:!1,includeSymlinks:!1,maxDepth:1})){if(!$e(s.name))continue;const n=Y(s.name);r.push({load:()=>ge(s.path),name:n,path:s.path,source:e})}return r},x=(t,e)=>{const r=[];if(!j(t))return r;for(const s of V(t,{includeFiles:!1,includeSymlinks:!1,maxDepth:1})){if(s.path===t)continue;const n=T(s.path,de);j(n)&&r.push({load:()=>ye(s.path,s.name),name:s.name,path:s.path,source:e})}return r},we=()=>{try{const t=ie(import.meta.url),e=T(G(t),"..","..","templates");return j(e)?e:void 0}catch{return}},I=t=>{const{extraDirectories:e=[],onWarning:r,workspaceRoot:s}=t,n=[...H(T(s,".vis","templates"),"native"),...x(T(s,".vis","templates"),"moon"),...x(T(s,".moon","templates"),"moon")];for(const o of e)n.push(...x(o,"config")),n.push(...H(o,"config"));const i=we();i&&n.push(...x(i,"builtin"));const a=new Map;for(const o of n){const c=a.get(o.name);if(!c){a.set(o.name,o);continue}r&&r(`Template "${o.name}" exists in multiple sources using ${c.source} (${c.path}), ignoring ${o.source} (${o.path}).`)}return[...a.values()].sort((o,c)=>o.name.localeCompare(c.name))},ge=async t=>{const{loadNativeTemplate:e}=await import("./loader2.js");return e(t)},ye=async(t,e)=>{const{loadMoonTemplate:r}=await import("./index2.js");return r(t,e)},q=(t,e)=>new Promise(r=>{t.question(e,s=>{r(s.trim())})}),ve=async(t,e,r)=>{const s=await q(t,` ${e} ${u(r?"[Y/n]":"[y/N]")} `);return s===""?r:s.toLowerCase()==="y"||s.toLowerCase()==="yes"},be=async(t,e,r,s)=>{process.stderr.write(` ${e}
2
- `);for(const[n,i]of r.entries()){const a=g(y(` ${String(n+1)}.`)),o=i===s?u(" (default)"):"";process.stderr.write(`${a} ${i}${o}
3
- `)}for(;;){const n=await q(t,`
4
- ${u(`Enter choice (1-${String(r.length)}):`)} `);if(n===""&&s!==void 0)return s;const i=Number.parseInt(n,10);if(Number.isInteger(i)&&i>=1&&i<=r.length)return r[i-1];const a=r.find(o=>o===n);if(a)return a;process.stderr.write(` ${u("Invalid choice. Try again.")}
5
- `)}},Te=async(t,e,r,s)=>{process.stderr.write(` ${e} ${u("(comma-separated numbers)")}
6
- `);for(const[n,i]of r.entries()){const a=g(y(` ${String(n+1)}.`)),o=s.includes(i)?u(" (default)"):"";process.stderr.write(`${a} ${i}${o}
7
- `)}for(;;){const n=await q(t,`
8
- ${u("Enter choices:")} `);if(n===""&&s.length>0)return s;const i=n.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(` ${u("Invalid choice. Try again.")}
9
- `)}},Se=t=>` ${u(`${t}:`)} `,Ne=(t,e)=>e.prompt??t,Re=t=>Object.entries(t).sort(([e,r],[s,n])=>{const i=r.order??0,a=n.order??0;return i!==a?i-a:e.localeCompare(s)}),U=(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}},B=(t,e,r)=>{if(e.type==="enum"){const s=Array.isArray(r)?r:[r];for(const n of s)if(typeof n!="string"||!e.values.includes(n))throw new Error(`Variable "${t}" must be one of: ${e.values.join(", ")} (got "${String(n)}")`)}},je=async t=>{const{defaults:e,interactive:r,overrides:s,variables:n}=t,i={},a=r?ae({input:process.stdin,output:process.stderr}):null;try{for(const[o,c]of Re(n)){if(Object.hasOwn(s,o)){const w=U(c,s[o]??"");B(o,c,w),i[o]=w;continue}if(e||!r||c.internal){if(c.default!==void 0){B(o,c,c.default),i[o]=c.default;continue}if(c.required)throw new Error(`Required variable "${o}" not provided. Pass --${o}=<value> or remove --defaults.`);continue}const m=Ne(o,c);let f;if(c.type==="boolean")f=await ve(a,m,!!(c.default??!1));else if(c.type==="enum")if(c.multiple){const w=Array.isArray(c.default)?c.default:[];f=await Te(a,m,c.values,w)}else{const w=typeof c.default=="string"?c.default:void 0;f=await be(a,m,c.values,w)}else{const w=c.default===void 0?"":` (${String(c.default)})`,v=await q(a,Se(`${m}${w}`));if(v===""&&c.default!==void 0)f=c.default;else if(v===""){if(c.required)throw new Error(`Variable "${o}" is required`);continue}else f=U(c,v)}B(o,c,f),i[o]=f}return i}finally{a?.close()}},Ee=["git://","npm://","https://","github:","gitlab:","bitbucket:","sourcehut:"],ke=t=>Ee.some(e=>t.startsWith(e)),Oe=async(t,e={})=>{const r=e.targetDirectory===void 0,s=e.targetDirectory??ce(T(fe(),"vis-generate-")),n=()=>{if(r)try{le(s,{force:!0,recursive:!0})}catch{}};l.info(`Downloading ${t}…`);try{const i=await ue(t,{auth:e.auth||process.env.GIGET_AUTH||process.env.GITHUB_TOKEN||process.env.GH_TOKEN||void 0,dir:s,force:!0,preferOffline:e.preferOffline});return{cleanup:n,directory:i.dir}}catch(i){n();const a=i instanceof Error?i.message:String(i);throw l.warn(`Failed to download template: ${a}`),i}},z=(t,e="")=>{const r=[];for(const[s,n]of Object.entries(t)){const i=e?`${e}/${s}`:s;typeof n=="string"||Buffer.isBuffer(n)?r.push({content:n,path:i}):n&&typeof n=="object"&&r.push(...z(n,i))}return r},_e=t=>t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`,xe=(t,e)=>{if(P(e))throw new Error(`Refusing to write outside destination: template produced absolute path "${e}".`);const r=T(t,e),s=K(t,r);if(s===".."||s.startsWith(`..${se}`)||P(s))throw new Error(`Refusing to write outside destination: "${e}" resolves to "${r}" which escapes "${t}".`);return r},Ie=(t,e)=>{L(G(t)),ne(t,e)},qe=(t,e,r=!1)=>{const s=typeof t=="string"?[t]:t.commands,n=typeof t=="string"?r:t.silent??r;for(const i of s){n||l.info(`$ ${i}`);const a=pe(i,{cwd:e,shell:!0,stdio:n?"ignore":"inherit"});if(a.status!==0)return l.warn(`Script failed (exit ${String(a.status)}): ${i}`),!1}return!0},De=t=>{const e=new Map;for(const r of t){const s=typeof r=="string"?0:r.phase??0,n=e.get(s);n?n.push(r):e.set(s,[r])}return[...e.entries()].sort(([r],[s])=>r-s)},We=async(t,e)=>{const r={builtins:{dest_dir:e.destination,dest_rel_dir:K(e.workspaceRoot,e.destination)||".",working_dir:e.cwd,workspace_root:e.workspaceRoot},options:e.options},s=await t.produce(r),n=s.files?z(s.files):[],i=s.filesMeta??{},a=[];for(const o of n){const c=xe(e.destination,o.path);a.push({file:o,meta:i[o.path]??{},target:c})}if(e.dryRun){l.info(`${g(y("Plan"))} ${u("(dry-run, no files written)")}`);for(const o of a){const c=Buffer.isBuffer(o.file.content)?o.file.content.length:Buffer.byteLength(o.file.content,"utf8");process.stderr.write(` ${u("write")} ${o.file.path} ${u(`(${_e(c)})`)}
10
- `)}}else{L(e.destination);let o=0,c=0;for(const m of a){const{file:f,meta:w,target:v}=m,D=j(v),b=e.force||w.force===!0;if(D&&!b){l.warn(`Skipped existing file: ${f.path} (use --force or set frontmatter force: true to overwrite)`),c+=1;continue}Ie(v,f.content),o+=1}l.success(`Wrote ${String(o)} file${o===1?"":"s"}${c>0?`, skipped ${String(c)}`:""}`)}if(!e.dryRun&&!e.skipScripts&&s.scripts&&s.scripts.length>0){const o=De(s.scripts);l.info(`Running ${String(s.scripts.length)} script${s.scripts.length===1?"":"s"} across ${String(o.length)} phase${o.length===1?"":"s"}…`);for(const[,c]of o)if((await Promise.all(c.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
- `),l.notice("Next steps:");for(const o of s.suggestions)process.stderr.write(` ${u("•")} ${o}
12
- `)}},Be=async t=>{let e;try{e=(await t.load()).about?.description}catch{}return{description:e,name:t.name,path:t.path,source:t.source}},Pe=(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(([s,n],[i,a])=>{const o=n.order??0,c=a.order??0;return o===c?s.localeCompare(i):o-c}).map(([s,n])=>Pe(s,n));return{description:e.about?.description??"",destination:e.destination,name:t.name,path:t.path,source:t.source,variables:r}},Ce=t=>{if(t.length===0){l.info("No templates found."),l.notice("Create one at .vis/templates/<name>.ts (programmatic) or .vis/templates/<name>/ (moon-format with template.yml).");return}l.info("Available templates:");for(const e of t){const r=u(`(${e.source})`);process.stderr.write(` ${g(y(e.name))} ${r}
13
- `)}},Me=(t,e)=>{const r={},s=[];for(let n=0;n<t.length;n++){const i=t[n];if(!i.startsWith("--")){s.push(i);continue}const a=i.indexOf("=");if(a===-1){const m=i.slice(2);if(m.startsWith("no-"))r[m.slice(3)]="false";else{r[m]="true";const f=t[n+1];f!==void 0&&!f.startsWith("-")&&e?.(`\`--${m} ${f}\` was read as boolean \`--${m}=true\` and \`${f}\` was ignored. For a string value use \`--${m}=${f}\`.`)}continue}const o=i.slice(2,a),c=i.slice(a+1);r[o]=c}return{overrides:r,remaining:s}},Fe=async t=>{const{createInterface:e}=await import("node:readline"),r=e({input:process.stdin,output:process.stderr});try{process.stderr.write(` ${g(y("vis generate"))} ${u("— pick a template")}
14
-
15
- `);for(const[s,n]of t.entries()){const i=g(y(` ${String(s+1)}.`));process.stderr.write(`${i} ${n.name} ${u(`(${n.source})`)}
16
- `)}return new Promise((s,n)=>{r.question(`
17
- ${u(`Enter choice (1-${String(t.length)}):`)} `,i=>{const a=Number.parseInt(i.trim(),10);Number.isInteger(a)&&a>=1&&a<=t.length?s(t[a-1].name):n(new Error("Invalid choice."))})})}finally{r.close()}},Le=async({argument:t,options:e,rawUnknown:r,visConfig:s,workspaceRoot:n})=>{const i=e.cwd||n||process.cwd(),a=n??i,o=s?.generator,c=Array.isArray(t)?t:t?[t]:[];if(e.list){const p=I({extraDirectories:o?.templates??[],onWarning:d=>{l.warn(d)},workspaceRoot:a});if(e.json){const d=await Promise.all(p.map(h=>Be(h)));process.stdout.write(`${JSON.stringify(d,null,2)}
18
- `);return}Ce(p);return}if(e.describe){const p=c[0];if(!p)throw new Error("`--describe` requires a template name. Run `vis generate --list` to see available templates.");const d=I({extraDirectories:o?.templates??[],onWarning:$=>{l.warn($)},workspaceRoot:a}).find($=>$.name===p);if(!d)throw new Error(`Template "${p}" not found. Run \`vis generate --list\` to see available templates.`);const h=await Ae(d);if(e.json){process.stdout.write(`${JSON.stringify(h,null,2)}
19
- `);return}if(l.info(`Template: ${g(y(h.name))} ${u(`(${h.source})`)}`),h.description&&l.info(h.description),h.destination&&l.info(`Destination: ${u(h.destination)}`),h.variables.length===0)l.info("No variables.");else{l.info("Variables:");for(const $ of h.variables){const _=[$.type];$.required&&_.push("required"),$.default!==void 0&&_.push(`default=${JSON.stringify($.default)}`),$.values&&_.push(`values=${$.values.join("|")}`),process.stderr.write(` ${g(y($.name))} ${u(`(${_.join(", ")})`)}
20
- `)}}return}let m=[...r??[]];if(m.length===0){const p=process.argv.slice(2),d=p.indexOf("--");d!==-1&&(m=p.slice(d+1))}const f=c.indexOf("--"),w=f===-1?[]:c.slice(f+1),v=f===-1?c:c.slice(0,f),{overrides:D}=Me([...w,...m],p=>{l.warn(p)});let b,k,O;const N=v[0];let W;if(N&&ke(N)){const p=await Oe(N,{auth:o?.auth,preferOffline:!!e.preferOffline||o?.preferOffline});W=p.cleanup;try{const d=I({extraDirectories:[p.directory],workspaceRoot:a}).find(h=>h.path.startsWith(p.directory));if(!d)throw new Error(`Downloaded template at ${p.directory} contains no template.yml or *.ts entrypoint.`);b=await d.load(),k=d.name,O=b.destination}catch(d){throw W(),d}}else{const p=I({extraDirectories:o?.templates??[],onWarning:$=>{l.warn($)},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 d;if(N)d=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.");d=await Fe(p)}const h=p.find($=>$.name===d);if(!h)throw new Error(`Template "${d}" not found. Run 'vis generate --list' to see available templates.`);b=await h.load(),k=h.name,O=b.destination}const A=e.to,C=!!e.dryRun,Q=!!e.force,M=!!e.defaults,X=!!e.skipScripts,Z=e.interactive!==!1&&!!process.stdin.isTTY&&!M;let S;A?S=A:O?S=O:S=".";const F=P(S)?S:oe(i,S);l.info(`Template: ${g(y(k))}`),l.info(`Target: ${u(F)}`),process.stderr.write(`
21
- `);const ee=await je({defaults:M,interactive:Z,overrides:D,variables:b.options??{}});try{await We(b,{cwd:i,destination:F,dryRun:C,force:Q,options:ee,skipScripts:X,workspaceRoot:a}),C||(process.stderr.write(`
22
- `),l.success(`Template '${k}' applied.`))}finally{W?.()}};export{Le as default};
1
+ import{createRequire as G}from"node:module";import{I as F,q as L,j as N,E as O}from"../packem_shared/index.server-J83sowC4.js";import{y as E}from"../packem_shared/index-CE6MsgcV.js";import{X as U}from"./cli-main.js";import{d as A,f as C,r as X,a as D,b as Q,s as Y,c as Z,e as ee,g as te,h as se,i as re,j as ie,k as ne,l as oe,m as ae,n as de,o as ce,p as fe,q as pe,t as le}from"../packem_shared/watch-loop-BZudYfcl.js";import{p as h}from"./catalog.js";const H=G(import.meta.url),k=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,I=t=>{if(typeof k<"u"&&k.versions&&k.versions.node){const[e,s]=k.versions.node.split(".").map(Number);if(e>22||e===22&&s>=3||e===20&&s>=16)return k.getBuiltinModule(t)}return H(t)},{createHash:q}=I("node:crypto"),ue=t=>t.startsWith("/")||/^[a-z]:[\\/]/i.test(t),_=(t,e)=>ue(e)?e:`${t}/${e}`,ge={argsCheck:(t,e)=>T(t,e,"check"),argsFix:(t,e)=>T(t,e,"fix"),bin:()=>["pnpm","exec","dprint"],cacheKey:(t,e)=>{const s=["dprint",t.declaredVersion??"unknown",t.configFile??"no-config",e.quiet?"q":"",...e.extraArgs??[]];return q("sha256").update(s.join("|")).digest("hex").slice(0,16)},detect:(t,e)=>{const s=A(e,h.dprint.packageNames[0]),r=C(t,h.dprint.configFiles);if(!(!s&&!r))return{adapter:"dprint",configFile:r,declared:!!s,declaredVersion:s,root:t}},extensions:["cjs","css","cts","dockerfile","html","js","json","jsonc","jsx","md","mdx","mjs","mts","toml","ts","tsx","yaml","yml"],id:"dprint",kind:"fmt",parse:(t,e)=>{if(t.exitCode===0)return[];const s=[];for(const r of t.stdout.split(/\r?\n/)){const i=r.trim();!i||i.startsWith("[")||i.startsWith("Checked ")||i.startsWith("Error:")||s.push({adapter:"dprint",file:_(e.root,i),fixable:!0,message:"Code style issues would be auto-fixed",severity:"info"})}return s}},T=(t,e,s)=>{const r=s==="fix"?["fmt"]:["check","--list-different"];return e.extraArgs?.length&&r.push(...e.extraArgs),r.push(...t),r},me={argsCheck:(t,e)=>B(t,e,"check"),argsFix:(t,e)=>B(t,e,"fix"),bin:()=>["pnpm","exec","oxfmt"],cacheKey:(t,e)=>{const s=["oxfmt",t.declaredVersion??"unknown",t.configFile??"no-config",e.quiet?"q":"",...e.extraArgs??[]];return q("sha256").update(s.join("|")).digest("hex").slice(0,16)},detect:(t,e)=>{const s=A(e,h.oxfmt.packageNames[0]),r=C(t,h.oxfmt.configFiles);if(!(!s&&!r))return{adapter:"oxfmt",configFile:r,declared:!!s,declaredVersion:s,root:t}},extensions:["cjs","cts","js","json","jsonc","jsx","mjs","mts","ts","tsx"],id:"oxfmt",kind:"fmt",parse:(t,e)=>{if(t.exitCode===0)return[];const s=[];for(const r of t.stdout.split(/\r?\n/)){const i=r.trim();!i||i.startsWith("[")||s.push({adapter:"oxfmt",file:_(e.root,i),fixable:!0,message:"Code style issues would be auto-fixed",severity:"info"})}return s}},B=(t,e,s)=>{const r=s==="fix"?["--write"]:["--list-different"];return e.extraArgs?.length&&r.push(...e.extraArgs),r.push(...t),r},he={argsCheck:(t,e)=>P(t,e,"check"),argsFix:(t,e)=>P(t,e,"fix"),bin:()=>["pnpm","exec","prettier"],cacheKey:(t,e)=>{const s=["prettier",t.declaredVersion??"unknown",t.configFile??"no-config",e.quiet?"q":"",...e.extraArgs??[]];return q("sha256").update(s.join("|")).digest("hex").slice(0,16)},detect:(t,e)=>{const s=A(e,h.prettier.packageNames[0]),r=C(t,h.prettier.configFiles);if(!(!s&&!r))return{adapter:"prettier",configFile:r,declared:!!s,declaredVersion:s,root:t}},extensions:["cjs","css","cts","html","js","json","jsx","less","md","mdx","mjs","mts","scss","ts","tsx","vue","yaml","yml"],id:"prettier",kind:"fmt",parse:(t,e)=>{if(t.exitCode===0)return[];const s=[];for(const r of t.stdout.split(/\r?\n/)){const i=r.trim();i&&(i.startsWith("[")||s.push({adapter:"prettier",file:_(e.root,i),fixable:!0,message:"Code style issues would be auto-fixed",severity:"info"}))}return s}},P=(t,e,s)=>{const r=s==="fix"?["--write"]:["--list-different"];return e.quiet&&r.push("--log-level","warn"),e.extraArgs?.length&&r.push(...e.extraArgs),r.push(...t),r},xe=[me,de,ge,he,ce,fe],qe=async({logger:t,options:e,visConfig:s,workspaceRoot:r})=>{const i=r??process.cwd(),u=s?.fmt,w=X(xe,u?.order),K=D(i,w),x=Q(K,w,"fmt").filter(({adapter:p})=>u?.adapters?.[p.id]?.enabled!==!1);if(x.length===0){t.warn("vis fmt: no formatter detected in this workspace (looked for: oxfmt, biome, dprint, prettier, ruff, deno-fmt).");return}const $=p=>{const o=u?.adapters?.[p]?.extraArgs;return o&&o.length>0?[...o]:void 0},j={quiet:e.quiet??!1},R=ke(e),y=e.check?"check":"fix";let d;if(e.staged){if(d=Y(i),d===void 0)t.warn("vis fmt: could not resolve --staged (not a git repo or git unavailable). Falling back to a workspace-wide run.");else if(d.length===0){t.info(F("✓ fmt: no staged files"));return}}else if(typeof e.since=="string"&&e.since.length>0){if(d=Z(i,e.since),d===void 0)t.warn(`vis fmt: could not resolve --since ${e.since} (not a git repo or unknown ref). Falling back to a workspace-wide run.`);else if(d.length===0){t.info(F(`✓ fmt: no files changed since ${e.since}`));return}}const z=U(i,void 0,void 0,!0),v=e.format??"human";v==="human"&&e.output!==void 0&&t.warn("vis fmt: --output is ignored for the human format; pass --format json|minimal|sarif|junit|github to redirect findings to a file.");const M=async p=>{const o=R.length>0?R:p,g=[];if(o){const n=te(o,x,u?.extensionOverrides);for(const{adapter:a,presence:c}of x){const f=n.get(a.id);if(!f||f.length===0)continue;const W=$(a.id),V={adapter:a,files:f,presence:c};W&&(V.options={...j,extraArgs:W}),g.push(V)}}else for(const{adapter:n,presence:a}of x){const c=$(n.id),f={adapter:n,files:["."],presence:a};c&&(f.options={...j,extraArgs:c}),g.push(f)}if(g.length===0)return;const J=await se(g,j,y,{cacheRoot:z}),b=g.map((n,a)=>{const c=J[a],f=n.adapter.parse(c,n.presence);return{adapter:n.adapter,durationMs:c.durationMs,exitCode:c.exitCode,findings:f}}),l=re(b.map(n=>({adapter:n.adapter.id,durationMs:n.durationMs,exitCode:n.exitCode,findingCount:n.findings.length,findings:n.findings}))),m=v==="human"?void 0:ie({cwd:i,target:e.output});try{switch(v){case"github":{m.write(ae({runs:b.map(n=>({findings:n.findings})),workspaceRoot:i}));break}case"json":{m.write(`${JSON.stringify({findings:l.findings,mode:y,runs:l.runs},null,2)}
2
+ `);break}case"junit":{m.write(oe({runs:b.map(n=>({adapter:n.adapter.id,durationMs:n.durationMs,findings:n.findings})),workspaceRoot:i}));break}case"minimal":{ye(l.findings,i,m);break}case"sarif":{m.write(ne({runs:b.map(n=>({adapter:n.adapter.id,findings:n.findings,presence:g.find(a=>a.adapter.id===n.adapter.id)?.presence})),workspaceRoot:i}));break}default:we(l.findings,i,y,t)}}finally{m?.close()}const S=y==="fix"?l.hadProcessFailure?1:0:le({...l,maxSeverity:l.findings.length>0?"error":void 0});S!==0&&(process.exitCode=S)};if(e.watch){const p=[...new Set(x.flatMap(({adapter:o})=>o.extensions))];await ee({extensions:p,initialFiles:d,label:"fmt",log:o=>{t.info(o)},runCycle:M,workspaceRoot:i});return}await M(d)},ke=t=>{const e=t;return[...e._??e.args??[]]},we=(t,e,s,r)=>{if(t.length===0){r.info(F(s==="fix"?" fmt: nothing to change":"✓ fmt: all files already formatted"));return}const i=pe(t),u=s==="fix"?L(N("Formatted:")):N("Would change:");r.info(u);for(const w of i.keys())r.info(` ${O("·")} ${E(e,w)}`);s==="check"&&(r.info(""),r.info(O(`Run \`vis fmt\` to apply changes (${String(i.size)} file${i.size===1?"":"s"}).`)))},ye=(t,e,s)=>{for(const r of t)s.write(`${r.adapter} ${E(e,r.file)}
3
+ `)};export{qe as default};
@@ -1,61 +1,22 @@
1
- import{v as F,H as P,y as S,m as b,T as I,O as U,a as T}from"../packem_shared/index-CE6MsgcV.js";import _ from"./index.js";import{b as J,l as M}from"./catalog.js";import{n as q}from"../packem_shared/manifests-WBnsV_Eb.js";import{_ as C,a0 as B}from"./cli-main.js";import{s as H}from"../packem_shared/glob-fqg4KepW-1S3z30c8.js";const K=(e,t)=>{const o=t.replace(/^\.?\//,"");return o===""||o==="."?`/${e}/`:e===""||e==="."?`/${o}`:`/${e}/${o}`},v=(e,t,o=[])=>{const s=[],n=new Set;for(const[r,a]of Object.entries(t?.globalPaths??{}))s.push({owners:a,path:r,source:"project-json"}),n.add(r);for(const[r,a]of Object.entries(e.projects)){const i=a.owners??[];for(const c of i){const f=K(a.root??r,c.path);s.push({channel:c.channel,owners:c.owners,path:f,projectId:r,source:"project-json"}),n.add(f)}}for(const r of o)n.has(r.path)||(s.push(r),n.add(r.path));return(t?.orderBy??"file-source")==="project-id"?s.sort((r,a)=>(r.projectId??"").localeCompare(a.projectId??"")||r.path.localeCompare(a.path)):s.sort((r,a)=>r.path.localeCompare(a.path)),s},z="Update each project's project.json `owners` field and re-run the command.",Y=e=>["# CODEOWNERS generated by `vis sync codeowners`. Do not edit by hand.",e?`# Re-run with: ${e}`:`# ${z}`,""],W=e=>{const t=[];for(const o of e){const s=o.owners.join(" "),n=o.channel?` # notify: ${o.channel}`:"";t.push(`${o.path} ${s}${n}`)}return t},Q=(e,t={})=>[...Y(t.regenerationCommand),...W(e),""].join(`
2
- `),O={begin:"# BEGIN vis-codeowners",end:"# END vis-codeowners"},V=(e,t=O,o={})=>{const s=o.regenerationCommand?`# Generated by vis sync codeowners — re-run with: ${o.regenerationCommand}`:"# Generated by `vis sync codeowners` — do not edit by hand.";return[t.begin,s,...W(e),t.end].join(`
3
- `)},X=(e,t,o=O)=>{const s=e.indexOf(o.begin),n=e.indexOf(o.end);if(s!==-1&&n!==-1&&n>s){const a=e.slice(0,s),i=n+o.end.length,c=e.slice(i);return`${a}${t}${c}`}const r=e.replace(/\s+$/u,"");return`${r.length===0?"":`${r}
1
+ import{createRequire as te}from"node:module";import{E as u,j as g,q as y}from"../packem_shared/index.server-J83sowC4.js";import{m as T,f as j,I as V,H as G,y as K,a as L,A as P,o as se,T as ne,B as oe}from"../packem_shared/index-CE6MsgcV.js";import{f as ue}from"../packem_shared/giget-DVTFJlbR.js";import{p as l}from"./cli-main.js";const re=te(import.meta.url),R=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,E=t=>{if(typeof R<"u"&&R.versions&&R.versions.node){const[e,r]=R.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return R.getBuiltinModule(t)}return re(t)},{fileURLToPath:ie}=E("node:url"),{createInterface:ae}=E("node:readline"),{mkdtempSync:ce,rmSync:le}=E("node:fs"),{tmpdir:fe}=E("node:os"),{spawnSync:pe}=E("node:child_process"),J=[".ts",".mts",".cts",".js",".mjs",".cjs"],de="template.yml",me=[".d",".test",".spec",".config",".bench",".stories"],he=[".d.ts",".d.mts",".d.cts",".js.map",".mjs.map",".cjs.map",".ts.map"],Y=t=>{for(const e of J)if(t.endsWith(e))return t.slice(0,-e.length);return t},$e=t=>{if(he.some(r=>t.endsWith(r))||!J.some(r=>t.endsWith(r)))return!1;const e=Y(t);return!me.some(r=>e.endsWith(r))},H=(t,e)=>{const r=[];if(!j(t))return r;for(const s of V(t,{includeDirs:!1,includeSymlinks:!1,maxDepth:1})){if(!$e(s.name))continue;const n=Y(s.name);r.push({load:()=>ge(s.path),name:n,path:s.path,source:e})}return r},x=(t,e)=>{const r=[];if(!j(t))return r;for(const s of V(t,{includeFiles:!1,includeSymlinks:!1,maxDepth:1})){if(s.path===t)continue;const n=T(s.path,de);j(n)&&r.push({load:()=>ye(s.path,s.name),name:s.name,path:s.path,source:e})}return r},we=()=>{try{const t=ie(import.meta.url),e=T(G(t),"..","..","templates");return j(e)?e:void 0}catch{return}},I=t=>{const{extraDirectories:e=[],onWarning:r,workspaceRoot:s}=t,n=[...H(T(s,".vis","templates"),"native"),...x(T(s,".vis","templates"),"moon"),...x(T(s,".moon","templates"),"moon")];for(const o of e)n.push(...x(o,"config")),n.push(...H(o,"config"));const i=we();i&&n.push(...x(i,"builtin"));const a=new Map;for(const o of n){const c=a.get(o.name);if(!c){a.set(o.name,o);continue}r&&r(`Template "${o.name}" exists in multiple sources using ${c.source} (${c.path}), ignoring ${o.source} (${o.path}).`)}return[...a.values()].sort((o,c)=>o.name.localeCompare(c.name))},ge=async t=>{const{loadNativeTemplate:e}=await import("./loader2.js");return e(t)},ye=async(t,e)=>{const{loadMoonTemplate:r}=await import("./index3.js");return r(t,e)},q=(t,e)=>new Promise(r=>{t.question(e,s=>{r(s.trim())})}),ve=async(t,e,r)=>{const s=await q(t,` ${e} ${u(r?"[Y/n]":"[y/N]")} `);return s===""?r:s.toLowerCase()==="y"||s.toLowerCase()==="yes"},be=async(t,e,r,s)=>{process.stderr.write(` ${e}
2
+ `);for(const[n,i]of r.entries()){const a=g(y(` ${String(n+1)}.`)),o=i===s?u(" (default)"):"";process.stderr.write(`${a} ${i}${o}
3
+ `)}for(;;){const n=await q(t,`
4
+ ${u(`Enter choice (1-${String(r.length)}):`)} `);if(n===""&&s!==void 0)return s;const i=Number.parseInt(n,10);if(Number.isInteger(i)&&i>=1&&i<=r.length)return r[i-1];const a=r.find(o=>o===n);if(a)return a;process.stderr.write(` ${u("Invalid choice. Try again.")}
5
+ `)}},Te=async(t,e,r,s)=>{process.stderr.write(` ${e} ${u("(comma-separated numbers)")}
6
+ `);for(const[n,i]of r.entries()){const a=g(y(` ${String(n+1)}.`)),o=s.includes(i)?u(" (default)"):"";process.stderr.write(`${a} ${i}${o}
7
+ `)}for(;;){const n=await q(t,`
8
+ ${u("Enter choices:")} `);if(n===""&&s.length>0)return s;const i=n.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(` ${u("Invalid choice. Try again.")}
9
+ `)}},Se=t=>` ${u(`${t}:`)} `,Ne=(t,e)=>e.prompt??t,Re=t=>Object.entries(t).sort(([e,r],[s,n])=>{const i=r.order??0,a=n.order??0;return i!==a?i-a:e.localeCompare(s)}),U=(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}},B=(t,e,r)=>{if(e.type==="enum"){const s=Array.isArray(r)?r:[r];for(const n of s)if(typeof n!="string"||!e.values.includes(n))throw new Error(`Variable "${t}" must be one of: ${e.values.join(", ")} (got "${String(n)}")`)}},je=async t=>{const{defaults:e,interactive:r,overrides:s,variables:n}=t,i={},a=r?ae({input:process.stdin,output:process.stderr}):null;try{for(const[o,c]of Re(n)){if(Object.hasOwn(s,o)){const w=U(c,s[o]??"");B(o,c,w),i[o]=w;continue}if(e||!r||c.internal){if(c.default!==void 0){B(o,c,c.default),i[o]=c.default;continue}if(c.required)throw new Error(`Required variable "${o}" not provided. Pass --${o}=<value> or remove --defaults.`);continue}const m=Ne(o,c);let f;if(c.type==="boolean")f=await ve(a,m,!!(c.default??!1));else if(c.type==="enum")if(c.multiple){const w=Array.isArray(c.default)?c.default:[];f=await Te(a,m,c.values,w)}else{const w=typeof c.default=="string"?c.default:void 0;f=await be(a,m,c.values,w)}else{const w=c.default===void 0?"":` (${String(c.default)})`,v=await q(a,Se(`${m}${w}`));if(v===""&&c.default!==void 0)f=c.default;else if(v===""){if(c.required)throw new Error(`Variable "${o}" is required`);continue}else f=U(c,v)}B(o,c,f),i[o]=f}return i}finally{a?.close()}},Ee=["git://","npm://","https://","github:","gitlab:","bitbucket:","sourcehut:"],ke=t=>Ee.some(e=>t.startsWith(e)),Oe=async(t,e={})=>{const r=e.targetDirectory===void 0,s=e.targetDirectory??ce(T(fe(),"vis-generate-")),n=()=>{if(r)try{le(s,{force:!0,recursive:!0})}catch{}};l.info(`Downloading ${t}…`);try{const i=await ue(t,{auth:e.auth||process.env.GIGET_AUTH||process.env.GITHUB_TOKEN||process.env.GH_TOKEN||void 0,dir:s,force:!0,preferOffline:e.preferOffline});return{cleanup:n,directory:i.dir}}catch(i){n();const a=i instanceof Error?i.message:String(i);throw l.warn(`Failed to download template: ${a}`),i}},z=(t,e="")=>{const r=[];for(const[s,n]of Object.entries(t)){const i=e?`${e}/${s}`:s;typeof n=="string"||Buffer.isBuffer(n)?r.push({content:n,path:i}):n&&typeof n=="object"&&r.push(...z(n,i))}return r},_e=t=>t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`,xe=(t,e)=>{if(P(e))throw new Error(`Refusing to write outside destination: template produced absolute path "${e}".`);const r=T(t,e),s=K(t,r);if(s===".."||s.startsWith(`..${se}`)||P(s))throw new Error(`Refusing to write outside destination: "${e}" resolves to "${r}" which escapes "${t}".`);return r},Ie=(t,e)=>{L(G(t)),ne(t,e)},qe=(t,e,r=!1)=>{const s=typeof t=="string"?[t]:t.commands,n=typeof t=="string"?r:t.silent??r;for(const i of s){n||l.info(`$ ${i}`);const a=pe(i,{cwd:e,shell:!0,stdio:n?"ignore":"inherit"});if(a.status!==0)return l.warn(`Script failed (exit ${String(a.status)}): ${i}`),!1}return!0},De=t=>{const e=new Map;for(const r of t){const s=typeof r=="string"?0:r.phase??0,n=e.get(s);n?n.push(r):e.set(s,[r])}return[...e.entries()].sort(([r],[s])=>r-s)},We=async(t,e)=>{const r={builtins:{dest_dir:e.destination,dest_rel_dir:K(e.workspaceRoot,e.destination)||".",working_dir:e.cwd,workspace_root:e.workspaceRoot},options:e.options},s=await t.produce(r),n=s.files?z(s.files):[],i=s.filesMeta??{},a=[];for(const o of n){const c=xe(e.destination,o.path);a.push({file:o,meta:i[o.path]??{},target:c})}if(e.dryRun){l.info(`${g(y("Plan"))} ${u("(dry-run, no files written)")}`);for(const o of a){const c=Buffer.isBuffer(o.file.content)?o.file.content.length:Buffer.byteLength(o.file.content,"utf8");process.stderr.write(` ${u("write")} ${o.file.path} ${u(`(${_e(c)})`)}
10
+ `)}}else{L(e.destination);let o=0,c=0;for(const m of a){const{file:f,meta:w,target:v}=m,D=j(v),b=e.force||w.force===!0;if(D&&!b){l.warn(`Skipped existing file: ${f.path} (use --force or set frontmatter force: true to overwrite)`),c+=1;continue}Ie(v,f.content),o+=1}l.success(`Wrote ${String(o)} file${o===1?"":"s"}${c>0?`, skipped ${String(c)}`:""}`)}if(!e.dryRun&&!e.skipScripts&&s.scripts&&s.scripts.length>0){const o=De(s.scripts);l.info(`Running ${String(s.scripts.length)} script${s.scripts.length===1?"":"s"} across ${String(o.length)} phase${o.length===1?"":"s"}…`);for(const[,c]of o)if((await Promise.all(c.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
+ `),l.notice("Next steps:");for(const o of s.suggestions)process.stderr.write(` ${u("•")} ${o}
12
+ `)}},Be=async t=>{let e;try{e=(await t.load()).about?.description}catch{}return{description:e,name:t.name,path:t.path,source:t.source}},Pe=(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(([s,n],[i,a])=>{const o=n.order??0,c=a.order??0;return o===c?s.localeCompare(i):o-c}).map(([s,n])=>Pe(s,n));return{description:e.about?.description??"",destination:e.destination,name:t.name,path:t.path,source:t.source,variables:r}},Ce=t=>{if(t.length===0){l.info("No templates found."),l.notice("Create one at .vis/templates/<name>.ts (programmatic) or .vis/templates/<name>/ (moon-format with template.yml).");return}l.info("Available templates:");for(const e of t){const r=u(`(${e.source})`);process.stderr.write(` ${g(y(e.name))} ${r}
13
+ `)}},Me=(t,e)=>{const r={},s=[];for(let n=0;n<t.length;n++){const i=t[n];if(!i.startsWith("--")){s.push(i);continue}const a=i.indexOf("=");if(a===-1){const m=i.slice(2);if(m.startsWith("no-"))r[m.slice(3)]="false";else{r[m]="true";const f=t[n+1];f!==void 0&&!f.startsWith("-")&&e?.(`\`--${m} ${f}\` was read as boolean \`--${m}=true\` and \`${f}\` was ignored. For a string value use \`--${m}=${f}\`.`)}continue}const o=i.slice(2,a),c=i.slice(a+1);r[o]=c}return{overrides:r,remaining:s}},Fe=async t=>{const{createInterface:e}=await import("node:readline"),r=e({input:process.stdin,output:process.stderr});try{process.stderr.write(` ${g(y("vis generate"))} ${u("— pick a template")}
4
14
 
5
- `}${t}
6
- `},Z=["**/CODEOWNERS"],ee=["**/node_modules/**","**/dist/**","**/build/**","**/coverage/**","**/.git/**","**/.next/**","**/.nuxt/**"],te=e=>{const t=[];for(const o of e.split(/\r?\n/u)){const s=o.indexOf("#"),n=(s===-1?o:o.slice(0,s)).trim();if(n.length===0)continue;const r=n.split(/\s+/u);if(r.length<2)continue;const[a,...i]=r,c=i.filter(f=>f.length>0);!a||c.length===0||t.push({owners:c,path:a})}return t},oe=(e,t)=>{const o=t.replace(/^\.\/?/,"").replace(/\/$/,"");return e.startsWith("/")?o===""?e:`/${o}${e}`:o===""?`/${e}`:`/${o}/${e}`},ne=async(e,t,o)=>{const s=t&&t.length>0?[...t]:[...Z],n=[...ee];if(o){const i=o.replace(/^\.\/?/,"").replace(/^\/+/,"");i.length>0&&n.push(i)}const r=await H(s,{absolute:!0,cwd:e,ignore:n}),a=[];for(const i of r){let c;try{c=F(i)}catch{continue}const f=P(i),h=S(e,f);for(const p of te(c))a.push({owners:p.owners,path:oe(p.path,h)})}return a},re=/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/?#]+)/iu,se=e=>{if(!e)return;const t=e.match(re);if(!t?.[1])return;const o=t[1].trim();if(!(o===""||o.includes(" ")))return`@${o.replace(/^@/,"")}`},ie=(e,t)=>{const o=[];for(const[s,n]of Object.entries(e.projects)){if(n.owners&&n.owners.length>0)continue;const r=n.root??s,a=b(t,r,"package.json"),i=C(a);if(!i)continue;const c=q(i.maintainers);if(!c||c.length===0)continue;const f=[],h=new Set;for(const p of c){const $=se(p.url);$&&!h.has($)&&(h.add($),f.push($))}f.length!==0&&o.push({owners:f,path:r===""||r==="."?"/":`/${r}/`,projectId:s})}return o},ae=["author","bugs","homepage","license","repository","engines"],N=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),E=(e,t)=>{if(e===t)return!0;if(typeof e!=typeof t||e===null||t===null)return!1;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(const[o,s]of e.entries())if(!E(s,t[o]))return!1;return!0}if(typeof e=="object"&&typeof t=="object"){const o=Object.keys(e),s=Object.keys(t);if(o.length!==s.length)return!1;for(const n of o)if(!E(e[n],t[n]))return!1;return!0}return!1},R=e=>e===void 0?e:structuredClone(e),ce=(e,t,o)=>{if(e==="repository"&&N(t)&&N(o)){const s={};for(const[n,r]of Object.entries(t))n!=="directory"&&(s[n]=R(r));return typeof o.directory=="string"&&(s.directory=o.directory),s}return R(t)},de=(e,t,o)=>{const s=[];for(const n of o.fields){if(!Object.hasOwn(e,n))continue;const r=e[n],a=t[n],i=ce(n,r,a);E(i,a)||s.push({after:i,before:a,field:n,packageJsonPath:""})}return s},fe=(e,t)=>{for(const o of t)e[o.field]=o.after},x="Generated by `vis sync codeowners --write-guard`. Do not edit by hand.",le=e=>{const t=e.replace(/^\.?\/+/u,"").replace(/\/+$/u,"");return t===""||t==="."?"**":`${t}/**`},D=e=>{const t=new Set,o=[];for(const s of[...e].sort((n,r)=>n.name.localeCompare(r.name))){const n=le(s.root);t.has(n)||(t.add(n),o.push(n))}return o},pe=e=>{const t=D(e),o=t.map(n=>` - "${n}"`).join(`
7
- `),s=t.map(n=>` ${n}`).join(`
8
- `);return`# ${x}
9
- name: Write Guard
10
-
11
- on:
12
- pull_request:
13
- paths:
14
- ${o}
15
-
16
- permissions:
17
- contents: read
18
- pull-requests: read
19
-
20
- jobs:
21
- write-guard:
22
- runs-on: ubuntu-latest
23
- steps:
24
- - uses: actions/checkout@v4
25
- with:
26
- fetch-depth: 0
27
- - uses: geritol/write-guard@v1
28
- with:
29
- codeowners: CODEOWNERS
30
- paths: |
31
- ${s}
32
- `},ue=e=>{const t=D(e).map(o=>` - "${o}/*"`).join(`
33
- `);return`# ${x}
34
- #
35
- # SOFT GUARD ONLY — this job does NOT block a merge by itself.
36
- # It verifies the generated CODEOWNERS is in sync and flags that a
37
- # restricted path changed. GitLab CI cannot portably gate a merge on
38
- # code-owner *approval* from a job, so REAL ENFORCEMENT REQUIRES the
39
- # native GitLab setting:
40
- # Settings -> Repository -> Protected branches ->
41
- # "Require approval from Code Owners" (GitLab Premium / Ultimate)
42
- # https://docs.gitlab.com/ee/user/project/codeowners/
43
- # Without that setting enabled, this job is advisory only.
44
- write-guard:
45
- stage: test
46
- image: node:22-alpine
47
- rules:
48
- - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
49
- changes:
50
- ${t}
51
- script:
52
- - corepack enable
53
- - pnpm install --frozen-lockfile
54
- - pnpm vis sync codeowners --check
55
- - >-
56
- echo "SOFT GUARD: a restricted path changed. This job does NOT enforce
57
- code-owner approval. Enable 'Require approval from Code Owners' on the
58
- protected branch (GitLab Premium/Ultimate) for a real merge gate:
59
- https://docs.gitlab.com/ee/user/project/codeowners/"
60
- `},he=e=>e.length===0?[]:[{content:pe(e),path:".github/workflows/write-guard.yml"},{content:ue(e),path:".gitlab/write-guard.gitlab-ci.yml"}],L=new Set(["nested-codeowners","package-json-maintainers","project-json"]),A=(e,t,o)=>{const s=new Set,n=[];for(const r of e??[])for(const a of r.split(",")){const i=a.trim();if(i.length===0)continue;if(o&&!o(i))throw new Error(`Unknown codeowners source: "${i}". Known: ${[...L].join(", ")}.`);const c=i;s.has(c)||(s.add(c),n.push(c))}return n.length>0?n:[...t]},ge=e=>L.has(e),G=["codeowners","package-json-fields"],me=(e,t)=>t.some(o=>_(o,e)),we=async(e,t,o,s,n)=>{const r=Object.entries(s.projects).filter(([,i])=>i.restricted===!0).map(([i,c])=>({name:i,root:c.root??i})),a=he(r);if(a.length===0){t.info("No projects flagged `restricted: true` in project.json. Skipping Write Guard.");return}if(n){let i=!1;for(const c of a){const f=b(o,c.path);let h="";try{h=await e.readFile(f,"utf8")}catch(p){if(p.code!=="ENOENT")throw p}h.trim()!==c.content.trim()&&(t.error(`${c.path} is out of date. Run \`vis sync codeowners --write-guard\` to update it.`),i=!0)}i?process.exitCode=1:t.info(`Write Guard CI is up to date (${a.length} files, ${r.length} restricted projects).`);return}for(const i of a){const c=b(o,i.path);T(P(c)),I(c,i.content),t.info(`Wrote ${i.path}`)}t.info(`Write Guard CI scoped to ${r.length} restricted project${r.length===1?"":"s"}.`)},$e=async({fs:e,logger:t,options:o,visConfig:s,workspaceRoot:n})=>{const r=n,{workspace:a}=J(r,s),i=s?.codeowners;o.writeGuard===!0&&await we(e,t,r,a,o.check===!0);const c=A(o.from,i?.sources??["project-json"],ge),f=o.regenerationCommand??i?.regenerationCommand,h=o.preserveBlock===!0||i?.preserveBlock===!0,p=i?.blockMarker??O,$=o.nestedIncludes??i?.nestedIncludes,g=o.out??"CODEOWNERS",w=[];if(c.includes("nested-codeowners")){const m=await ne(r,$,g);for(const j of m)w.push({...j,source:"nested"})}if(c.includes("package-json-maintainers")){const m=ie(a,r);for(const j of m)w.push({...j,source:"maintainers"})}const l=c.includes("project-json")?v(a,i,w):v({projects:{}},i,w);if(l.length===0){t.info("No `owners` entries found in any source. Nothing to sync.");return}const y=b(r,g);let d="";try{d=await e.readFile(y,"utf8")}catch(m){if(m.code!=="ENOENT")throw m}const u={regenerationCommand:f},k=h?X(d,V(l,p,u),p):Q(l,u);if(o.check){if(d.trim()!==k.trim()){t.error(`${y} is out of date. Run \`vis sync codeowners\` to update it.`),process.exitCode=1;return}t.info(`${y} is up to date.`);return}I(y,k),t.info(`Wrote ${l.length} entries to ${y}`)},ke=({logger:e,options:t,visConfig:o,workspaceRoot:s})=>{const n=s,r=o?.editorconfig??!0,a=C(b(n,"package.json"));if(!a){e.error("Could not read root package.json. Nothing to sync."),process.exitCode=1;return}const i=A(t.fields,ae),c=t.ignorePackageName??[],f=t.check===!0,h=(t.format??"human").toLowerCase(),p=t.quiet===!0,$=B(n).filter(d=>d!=="."),g=[];let w=0;for(const d of $){const u=b(n,d,"package.json"),k=C(u);if(!k)continue;const m=typeof k.name=="string"?k.name:void 0;if(m!==void 0&&c.length>0&&me(m,c))continue;w+=1;const j=de(a,k,{fields:i});j.length!==0&&g.push({filePath:u,packageJsonPath:S(n,u),packageName:m,pkg:k,pkgChanges:j})}if(!f)for(const d of g)fe(d.pkg,d.pkgChanges),U(d.filePath,d.pkg,{indent:M(d.filePath,{useEditorconfig:r}),overwrite:!0});const l=g.flatMap(d=>d.pkgChanges.map(u=>({after:u.after,before:u.before,field:u.field,packageJsonPath:d.packageJsonPath,packageName:d.packageName}))),y={changes:l,fields:i,kind:"package-json-fields",mode:f?"check":"write",totalChanges:l.length,totalPackages:w};if(h==="json")process.stdout.write(`${JSON.stringify(y,null,4)}
61
- `);else if(l.length===0)e.info(`All ${w} package${w===1?"":"s"} in sync (fields: ${i.join(", ")}).`);else if(f){if(!p)for(const d of l)e.error(`${d.packageJsonPath}: ${d.field} drifts from root`);e.error(`Found ${l.length} field drift${l.length===1?"":"s"} across ${g.length} package${g.length===1?"":"s"}. Run \`vis sync package-json-fields\` to fix.`)}else{if(!p)for(const d of g)e.info(`${d.packageJsonPath}: synced ${d.pkgChanges.map(u=>u.field).join(", ")}`);e.info(`Synced ${l.length} field${l.length===1?"":"s"} across ${g.length} package${g.length===1?"":"s"}.`)}f&&l.length>0&&(process.exitCode=1)},ve=async e=>{const t=e.argument[0];if(!t)throw new Error(`Missing sync kind. Usage: vis sync <kind> (known kinds: ${G.join(", ")})`);if(!e.workspaceRoot)throw new Error("Could not determine workspace root. Run inside a monorepo.");if(t==="codeowners"){await $e(e);return}if(t==="package-json-fields"){ke(e);return}throw new Error(`Unknown sync kind: "${t}". Known kinds: ${G.join(", ")}.`)};export{ve as default};
15
+ `);for(const[s,n]of t.entries()){const i=g(y(` ${String(s+1)}.`));process.stderr.write(`${i} ${n.name} ${u(`(${n.source})`)}
16
+ `)}return new Promise((s,n)=>{r.question(`
17
+ ${u(`Enter choice (1-${String(t.length)}):`)} `,i=>{const a=Number.parseInt(i.trim(),10);Number.isInteger(a)&&a>=1&&a<=t.length?s(t[a-1].name):n(new Error("Invalid choice."))})})}finally{r.close()}},Le=async({argument:t,options:e,rawUnknown:r,visConfig:s,workspaceRoot:n})=>{const i=e.cwd||n||process.cwd(),a=n??i,o=s?.generator,c=Array.isArray(t)?t:t?[t]:[];if(e.list){const p=I({extraDirectories:o?.templates??[],onWarning:d=>{l.warn(d)},workspaceRoot:a});if(e.json){const d=await Promise.all(p.map(h=>Be(h)));process.stdout.write(`${JSON.stringify(d,null,2)}
18
+ `);return}Ce(p);return}if(e.describe){const p=c[0];if(!p)throw new Error("`--describe` requires a template name. Run `vis generate --list` to see available templates.");const d=I({extraDirectories:o?.templates??[],onWarning:$=>{l.warn($)},workspaceRoot:a}).find($=>$.name===p);if(!d)throw new Error(`Template "${p}" not found. Run \`vis generate --list\` to see available templates.`);const h=await Ae(d);if(e.json){process.stdout.write(`${JSON.stringify(h,null,2)}
19
+ `);return}if(l.info(`Template: ${g(y(h.name))} ${u(`(${h.source})`)}`),h.description&&l.info(h.description),h.destination&&l.info(`Destination: ${u(h.destination)}`),h.variables.length===0)l.info("No variables.");else{l.info("Variables:");for(const $ of h.variables){const _=[$.type];$.required&&_.push("required"),$.default!==void 0&&_.push(`default=${JSON.stringify($.default)}`),$.values&&_.push(`values=${$.values.join("|")}`),process.stderr.write(` ${g(y($.name))} ${u(`(${_.join(", ")})`)}
20
+ `)}}return}let m=[...r??[]];if(m.length===0){const p=process.argv.slice(2),d=p.indexOf("--");d!==-1&&(m=p.slice(d+1))}const f=c.indexOf("--"),w=f===-1?[]:c.slice(f+1),v=f===-1?c:c.slice(0,f),{overrides:D}=Me([...w,...m],p=>{l.warn(p)});let b,k,O;const N=v[0];let W;if(N&&ke(N)){const p=await Oe(N,{auth:o?.auth,preferOffline:!!e.preferOffline||o?.preferOffline});W=p.cleanup;try{const d=I({extraDirectories:[p.directory],workspaceRoot:a}).find(h=>h.path.startsWith(p.directory));if(!d)throw new Error(`Downloaded template at ${p.directory} contains no template.yml or *.ts entrypoint.`);b=await d.load(),k=d.name,O=b.destination}catch(d){throw W(),d}}else{const p=I({extraDirectories:o?.templates??[],onWarning:$=>{l.warn($)},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 d;if(N)d=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.");d=await Fe(p)}const h=p.find($=>$.name===d);if(!h)throw new Error(`Template "${d}" not found. Run 'vis generate --list' to see available templates.`);b=await h.load(),k=h.name,O=b.destination}const A=e.to,C=!!e.dryRun,Q=!!e.force,M=!!e.defaults,X=!!e.skipScripts,Z=e.interactive!==!1&&!!process.stdin.isTTY&&!M;let S;A?S=A:O?S=O:S=".";const F=P(S)?S:oe(i,S);l.info(`Template: ${g(y(k))}`),l.info(`Target: ${u(F)}`),process.stderr.write(`
21
+ `);const ee=await je({defaults:M,interactive:Z,overrides:D,variables:b.options??{}});try{await We(b,{cwd:i,destination:F,dryRun:C,force:Q,options:ee,skipScripts:X,workspaceRoot:a}),C||(process.stderr.write(`
22
+ `),l.success(`Template '${k}' applied.`))}finally{W?.()}};export{Le as default};
@@ -1,3 +1,61 @@
1
- import{createRequire as G}from"node:module";import{I as q,j as Z,E as O,V as K,s as T,q as D}from"../packem_shared/index.server-J83sowC4.js";import{y as B}from"../packem_shared/index-CE6MsgcV.js";import{Z as Q}from"./cli-main.js";import{d as k,f as v,r as X,a as Y,b as ee,s as ne,c as te,e as ie,u as re,h as se,i as oe,j as ae,k as le,l as ce,m as de,n as ue,v as fe,w as ge,q as pe,t as me}from"../packem_shared/watch-loop-JfGKIgKB.js";import{p as c}from"./catalog.js";const H=G(import.meta.url),w=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,U=e=>{if(typeof w<"u"&&w.versions&&w.versions.node){const[n,t]=w.versions.node.split(".").map(Number);if(n>22||n===22&&t>=3||n===20&&t>=16)return w.getBuiltinModule(e)}return H(e)},{createHash:y}=U("node:crypto"),he={1:"warning",2:"error"},xe={argsCheck:(e,n)=>V(e,n,!1),argsFix:(e,n)=>V(e,n,!0),bin:()=>["pnpm","exec","eslint"],cacheKey:(e,n)=>{const t=["eslint",e.declaredVersion??"unknown",e.configFile??"no-config",n.maxWarnings===void 0?"":`mw=${n.maxWarnings}`,n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=k(n,c.eslint.packageNames[0]),i=v(e,c.eslint.configFiles);if(!(!t&&!i))return{adapter:"eslint",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["cjs","cts","js","jsx","mjs","mts","ts","tsx","vue"],id:"eslint",kind:"lint",parse:(e,n)=>{if(!e.stdout.trim())return[];let t;try{t=JSON.parse(e.stdout)}catch{return[{adapter:"eslint",file:n.root,fixable:!1,message:`eslint output was not valid JSON (exit ${e.exitCode})`,severity:"error"}]}const i=[];for(const r of t)for(const s of r.messages)i.push({adapter:"eslint",column:s.column,endColumn:s.endColumn,endLine:s.endLine,file:r.filePath,fixable:!!s.fix,line:s.line,message:s.message,ruleId:s.ruleId??void 0,severity:s.fatal?"error":he[s.severity]??"warning"});return i}},V=(e,n,t)=>{const i=["--format","json","--no-error-on-unmatched-pattern"];return t&&i.push("--fix"),n.quiet&&i.push("--quiet"),typeof n.maxWarnings=="number"&&i.push("--max-warnings",String(n.maxWarnings)),n.extraArgs?.length&&i.push(...n.extraArgs),i.push(...e),i},we=/^([^:]+):(\d+)(?::(\d+))?\s+([\w/-]+)\s+(.+)$/,ke=e=>{const n=we.exec(e);if(!n)return;const[,t,i,r,s,a]=n;return{column:r===void 0?void 0:Number(r),file:t,line:Number(i),message:a,ruleId:s}},ve=e=>e.startsWith("/")||/^[a-z]:[\\/]/i.test(e),ye={argsCheck:(e,n)=>J(e,n,!1),argsFix:(e,n)=>J(e,n,!0),bin:()=>["pnpm","exec","markdownlint-cli2"],cacheKey:(e,n)=>{const t=["markdownlint",e.declaredVersion??"unknown",e.configFile??"no-config",n.maxWarnings===void 0?"":`mw=${n.maxWarnings}`,n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=c.markdownlint.packageNames.map(r=>k(n,r)).find(r=>r!==void 0),i=v(e,c.markdownlint.configFiles);if(!(!t&&!i))return{adapter:"markdownlint",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["markdown","md"],id:"markdownlint",kind:"lint",parse:(e,n)=>{const t=(e.stderr||e.stdout||"").trim();if(!t)return[];const i=[];for(const r of t.split(/\r?\n/)){const s=ke(r.trim());s&&i.push({adapter:"markdownlint",column:s.column,file:ve(s.file)?s.file:`${n.root}/${s.file}`,fixable:!0,line:s.line,message:s.message,ruleId:s.ruleId,severity:"warning"})}return i}},J=(e,n,t)=>{const i=[];return t&&i.push("--fix"),n.extraArgs?.length&&i.push(...n.extraArgs),e.length===0?i.push("**/*.md"):i.push(...e),i},$e={advice:"info",error:"error",warning:"warning"},be={argsCheck:(e,n)=>R(e,n,!1),argsFix:(e,n)=>R(e,n,!0),bin:()=>["pnpm","exec","oxlint"],cacheKey:(e,n)=>{const t=["oxlint",e.declaredVersion??"unknown",e.configFile??"no-config",n.maxWarnings===void 0?"":`mw=${n.maxWarnings}`,n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=k(n,c.oxlint.packageNames[0]),i=v(e,c.oxlint.configFiles);if(!(!t&&!i))return{adapter:"oxlint",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["astro","cjs","cts","js","jsx","mjs","mts","svelte","ts","tsx","vue"],id:"oxlint",kind:"lint",parse:(e,n)=>{if(!e.stdout.trim())return[];let t;try{t=JSON.parse(e.stdout)}catch{return[{adapter:"oxlint",file:n.root,fixable:!1,message:`oxlint output was not valid JSON (exit ${e.exitCode})`,severity:"error"}]}const i=[];for(const r of t.diagnostics??[]){const s=r.labels?.[0]?.span;i.push({adapter:"oxlint",column:s?.column,file:r.filename??n.root,fixable:!1,line:s?.line,message:r.message??"",ruleId:r.code,severity:$e[r.severity??""]??"warning"})}return i}},R=(e,n,t)=>{const i=["--format","json"];return t&&i.push("--fix"),n.quiet&&i.push("--quiet"),typeof n.maxWarnings=="number"&&i.push(`--max-warnings=${String(n.maxWarnings)}`),n.extraArgs?.length&&i.push(...n.extraArgs),i.push(...e),i},Ae={error:"error",info:"info",style:"info",warning:"warning"},Fe=e=>e.startsWith("/")||/^[a-z]:[\\/]/i.test(e),je=(e,n)=>e?Fe(e)?e:`${n}/${e}`:n,Ce={argsCheck:(e,n)=>L(e,n),argsFix:(e,n)=>L(e,n),bin:()=>["shellcheck"],cacheKey:(e,n)=>{const t=["shellcheck",e.declaredVersion??"unknown",e.configFile??"no-config",n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=k(n,c.shellcheck.packageNames[0]),i=v(e,c.shellcheck.configFiles);if(!(!t&&!i))return{adapter:"shellcheck",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["bash","ksh","sh"],id:"shellcheck",kind:"lint",parse:(e,n)=>{if(!e.stdout.trim())return[];let t;try{t=JSON.parse(e.stdout)}catch{return[{adapter:"shellcheck",file:n.root,fixable:!1,message:`shellcheck output was not valid JSON (exit ${e.exitCode})`,severity:"error"}]}const i=[];for(const r of t.comments??[])i.push({adapter:"shellcheck",column:r.column,endColumn:r.endColumn,endLine:r.endLine,file:je(r.file,n.root),fixable:!!r.fix,line:r.line,message:r.message??"",ruleId:r.code===void 0?void 0:`SC${String(r.code)}`,severity:Ae[r.level??""]??"warning"});return i}},L=(e,n)=>{const t=["--format=json1"];return n.extraArgs?.length&&t.push(...n.extraArgs),t.push(...e),t},Se={error:"error",warning:"warning"},qe={argsCheck:(e,n)=>M(e,n,!1),argsFix:(e,n)=>M(e,n,!0),bin:()=>["pnpm","exec","stylelint"],cacheKey:(e,n)=>{const t=["stylelint",e.declaredVersion??"unknown",e.configFile??"no-config",n.maxWarnings===void 0?"":`mw=${n.maxWarnings}`,n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=k(n,c.stylelint.packageNames[0]),i=v(e,c.stylelint.configFiles);if(!(!t&&!i))return{adapter:"stylelint",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["astro","css","less","sass","scss","svelte","vue"],id:"stylelint",kind:"lint",parse:(e,n)=>{if(!e.stdout.trim())return[];let t;try{t=JSON.parse(e.stdout)}catch{return[{adapter:"stylelint",file:n.root,fixable:!1,message:`stylelint output was not valid JSON (exit ${e.exitCode})`,severity:"error"}]}const i=[];for(const r of t)for(const s of r.warnings??[])i.push({adapter:"stylelint",column:s.column,endColumn:s.endColumn,endLine:s.endLine,file:r.source,fixable:!1,line:s.line,message:s.text??"",ruleId:s.rule,severity:Se[s.severity??""]??"warning"});return i}},M=(e,n,t)=>{const i=["--formatter","json"];return t&&i.push("--fix"),n.quiet&&i.push("--quiet"),typeof n.maxWarnings=="number"&&i.push("--max-warnings",String(n.maxWarnings)),n.extraArgs?.length&&i.push(...n.extraArgs),i.push(...e),i},We=[be,ue,xe,qe,fe,ye,Ce,ge],Be=async({logger:e,options:n,visConfig:t,workspaceRoot:i})=>{const r=i??process.cwd(),s=t?.lint,a=X(We,s?.order),j=Y(r,a),d=ee(j,a,"lint").filter(({adapter:l})=>s?.adapters?.[l.id]?.enabled!==!1);if(d.length===0){e.warn("vis lint: no linter detected in this workspace (looked for: oxlint, biome, eslint, stylelint, ruff, markdownlint, shellcheck, deno).");return}const C=l=>{const u=s?.adapters?.[l]?.extraArgs;return u&&u.length>0?[...u]:void 0},$={extraArgs:void 0,maxWarnings:typeof n.maxWarnings=="number"?n.maxWarnings:void 0,quiet:n.quiet??!1},b=Ne(n),P=n.fix?"fix":"check";let f;if(n.staged){if(f=ne(r),f===void 0)e.warn("vis lint: could not resolve --staged (not a git repo or git unavailable). Falling back to a workspace-wide run.");else if(f.length===0){e.info(q(" lint: no staged files"));return}}else if(typeof n.since=="string"&&n.since.length>0){if(f=te(r,n.since),f===void 0)e.warn(`vis lint: could not resolve --since ${n.since} (not a git repo or unknown ref). Falling back to a workspace-wide run.`);else if(f.length===0){e.info(q(`✓ lint: no files changed since ${n.since}`));return}}const W=b.length>0?b:void 0,E=Q(r,void 0,void 0,!0),S=n.format??"human";S==="human"&&n.output!==void 0&&e.warn("vis lint: --output is ignored for the human format; pass --format json|minimal|sarif|junit|github to redirect findings to a file.");const N=async l=>{const u=l!==void 0&&l.length>0&&W===void 0,m=[];for(const{adapter:o,presence:x}of d){let g;if(u){if(g=re(l,o.extensions),g.length===0)continue}else g=W??l??["."];const F=C(o.id),I={adapter:o,files:g,presence:x};F&&(I.options={...$,extraArgs:F}),m.push(I)}if(m.length===0)return;const z=await se(m,$,P,{cacheRoot:E}),A=m.map((o,x)=>{const g=z[x],F=o.adapter.parse(g,o.presence);return{adapter:o.adapter,durationMs:g.durationMs,exitCode:g.exitCode,findings:F}}),h=oe(A.map(o=>({adapter:o.adapter.id,durationMs:o.durationMs,exitCode:o.exitCode,findingCount:o.findings.length,findings:o.findings}))),p=S==="human"?void 0:ae({cwd:r,target:n.output});try{switch(S){case"github":{p.write(de({runs:A.map(o=>({findings:o.findings})),workspaceRoot:r}));break}case"json":{p.write(`${JSON.stringify({findings:h.findings,runs:h.runs},null,2)}
2
- `);break}case"junit":{p.write(ce({runs:A.map(o=>({adapter:o.adapter.id,durationMs:o.durationMs,findings:o.findings})),workspaceRoot:r}));break}case"minimal":{Ie(h.findings,r,p);break}case"sarif":{p.write(le({runs:A.map(o=>({adapter:o.adapter.id,findings:o.findings,presence:m.find(x=>x.adapter.id===o.adapter.id)?.presence})),workspaceRoot:r}));break}default:_e(h.findings,r,e)}}finally{p?.close()}const _=me(h);_!==0&&(process.exitCode=_)};if(n.watch){const l=[...new Set(d.flatMap(({adapter:u})=>u.extensions))];await ie({extensions:l,initialFiles:f,label:"lint",log:u=>{e.info(u)},runCycle:N,workspaceRoot:r});return}await N(f)},Ne=e=>{const n=e;return[...n._??n.args??[]]},_e=(e,n,t)=>{if(e.length===0){t.info(q("✓ lint: no findings"));return}const i=pe(e);for(const[a,j]of i){t.info(Z(B(n,a)));for(const d of j){const C=Oe(d),$=Ve(d.severity),b=d.ruleId?O(` ${d.ruleId}`):"";t.info(` ${O(C)} ${$} ${d.message}${b}`)}}const r=e.filter(a=>a.severity==="error").length,s=e.filter(a=>a.severity==="warning").length;t.info(""),t.info(`${K(`${String(r)} error${r===1?"":"s"}`)}, ${T(`${String(s)} warning${s===1?"":"s"}`)}`)},Ie=(e,n,t)=>{for(const i of e){const r=B(n,i.file),s=i.line??"",a=i.column??"";t.write(`${i.adapter} ${r} ${String(s)} ${String(a)} ${i.severity} ${i.ruleId??""} ${i.message}
3
- `)}},Oe=e=>e.line===void 0?"":e.column===void 0?String(e.line):`${String(e.line)}:${String(e.column)}`,Ve=e=>e==="error"?K("error"):e==="warning"?T("warn "):D("info ");export{Be as default};
1
+ import{v as F,H as P,y as S,m as b,T as I,O as U,a as T}from"../packem_shared/index-CE6MsgcV.js";import _ from"./index.js";import{b as J,l as M}from"./catalog.js";import{n as q}from"../packem_shared/manifests-DSBr3-dw.js";import{Z as C,a0 as B}from"./cli-main.js";import{s as H}from"../packem_shared/glob-fqg4KepW-1S3z30c8.js";const K=(e,t)=>{const o=t.replace(/^\.?\//,"");return o===""||o==="."?`/${e}/`:e===""||e==="."?`/${o}`:`/${e}/${o}`},v=(e,t,o=[])=>{const s=[],n=new Set;for(const[r,a]of Object.entries(t?.globalPaths??{}))s.push({owners:a,path:r,source:"project-json"}),n.add(r);for(const[r,a]of Object.entries(e.projects)){const i=a.owners??[];for(const c of i){const f=K(a.root??r,c.path);s.push({channel:c.channel,owners:c.owners,path:f,projectId:r,source:"project-json"}),n.add(f)}}for(const r of o)n.has(r.path)||(s.push(r),n.add(r.path));return(t?.orderBy??"file-source")==="project-id"?s.sort((r,a)=>(r.projectId??"").localeCompare(a.projectId??"")||r.path.localeCompare(a.path)):s.sort((r,a)=>r.path.localeCompare(a.path)),s},z="Update each project's project.json `owners` field and re-run the command.",Y=e=>["# CODEOWNERS generated by `vis sync codeowners`. Do not edit by hand.",e?`# Re-run with: ${e}`:`# ${z}`,""],W=e=>{const t=[];for(const o of e){const s=o.owners.join(" "),n=o.channel?` # notify: ${o.channel}`:"";t.push(`${o.path} ${s}${n}`)}return t},Q=(e,t={})=>[...Y(t.regenerationCommand),...W(e),""].join(`
2
+ `),O={begin:"# BEGIN vis-codeowners",end:"# END vis-codeowners"},V=(e,t=O,o={})=>{const s=o.regenerationCommand?`# Generated by vis sync codeowners re-run with: ${o.regenerationCommand}`:"# Generated by `vis sync codeowners` do not edit by hand.";return[t.begin,s,...W(e),t.end].join(`
3
+ `)},X=(e,t,o=O)=>{const s=e.indexOf(o.begin),n=e.indexOf(o.end);if(s!==-1&&n!==-1&&n>s){const a=e.slice(0,s),i=n+o.end.length,c=e.slice(i);return`${a}${t}${c}`}const r=e.replace(/\s+$/u,"");return`${r.length===0?"":`${r}
4
+
5
+ `}${t}
6
+ `},Z=["**/CODEOWNERS"],ee=["**/node_modules/**","**/dist/**","**/build/**","**/coverage/**","**/.git/**","**/.next/**","**/.nuxt/**"],te=e=>{const t=[];for(const o of e.split(/\r?\n/u)){const s=o.indexOf("#"),n=(s===-1?o:o.slice(0,s)).trim();if(n.length===0)continue;const r=n.split(/\s+/u);if(r.length<2)continue;const[a,...i]=r,c=i.filter(f=>f.length>0);!a||c.length===0||t.push({owners:c,path:a})}return t},oe=(e,t)=>{const o=t.replace(/^\.\/?/,"").replace(/\/$/,"");return e.startsWith("/")?o===""?e:`/${o}${e}`:o===""?`/${e}`:`/${o}/${e}`},ne=async(e,t,o)=>{const s=t&&t.length>0?[...t]:[...Z],n=[...ee];if(o){const i=o.replace(/^\.\/?/,"").replace(/^\/+/,"");i.length>0&&n.push(i)}const r=await H(s,{absolute:!0,cwd:e,ignore:n}),a=[];for(const i of r){let c;try{c=F(i)}catch{continue}const f=P(i),h=S(e,f);for(const p of te(c))a.push({owners:p.owners,path:oe(p.path,h)})}return a},re=/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/?#]+)/iu,se=e=>{if(!e)return;const t=e.match(re);if(!t?.[1])return;const o=t[1].trim();if(!(o===""||o.includes(" ")))return`@${o.replace(/^@/,"")}`},ie=(e,t)=>{const o=[];for(const[s,n]of Object.entries(e.projects)){if(n.owners&&n.owners.length>0)continue;const r=n.root??s,a=b(t,r,"package.json"),i=C(a);if(!i)continue;const c=q(i.maintainers);if(!c||c.length===0)continue;const f=[],h=new Set;for(const p of c){const $=se(p.url);$&&!h.has($)&&(h.add($),f.push($))}f.length!==0&&o.push({owners:f,path:r===""||r==="."?"/":`/${r}/`,projectId:s})}return o},ae=["author","bugs","homepage","license","repository","engines"],N=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),E=(e,t)=>{if(e===t)return!0;if(typeof e!=typeof t||e===null||t===null)return!1;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(const[o,s]of e.entries())if(!E(s,t[o]))return!1;return!0}if(typeof e=="object"&&typeof t=="object"){const o=Object.keys(e),s=Object.keys(t);if(o.length!==s.length)return!1;for(const n of o)if(!E(e[n],t[n]))return!1;return!0}return!1},R=e=>e===void 0?e:structuredClone(e),ce=(e,t,o)=>{if(e==="repository"&&N(t)&&N(o)){const s={};for(const[n,r]of Object.entries(t))n!=="directory"&&(s[n]=R(r));return typeof o.directory=="string"&&(s.directory=o.directory),s}return R(t)},de=(e,t,o)=>{const s=[];for(const n of o.fields){if(!Object.hasOwn(e,n))continue;const r=e[n],a=t[n],i=ce(n,r,a);E(i,a)||s.push({after:i,before:a,field:n,packageJsonPath:""})}return s},fe=(e,t)=>{for(const o of t)e[o.field]=o.after},x="Generated by `vis sync codeowners --write-guard`. Do not edit by hand.",le=e=>{const t=e.replace(/^\.?\/+/u,"").replace(/\/+$/u,"");return t===""||t==="."?"**":`${t}/**`},D=e=>{const t=new Set,o=[];for(const s of[...e].sort((n,r)=>n.name.localeCompare(r.name))){const n=le(s.root);t.has(n)||(t.add(n),o.push(n))}return o},pe=e=>{const t=D(e),o=t.map(n=>` - "${n}"`).join(`
7
+ `),s=t.map(n=>` ${n}`).join(`
8
+ `);return`# ${x}
9
+ name: Write Guard
10
+
11
+ on:
12
+ pull_request:
13
+ paths:
14
+ ${o}
15
+
16
+ permissions:
17
+ contents: read
18
+ pull-requests: read
19
+
20
+ jobs:
21
+ write-guard:
22
+ runs-on: ubuntu-latest
23
+ steps:
24
+ - uses: actions/checkout@v4
25
+ with:
26
+ fetch-depth: 0
27
+ - uses: geritol/write-guard@v1
28
+ with:
29
+ codeowners: CODEOWNERS
30
+ paths: |
31
+ ${s}
32
+ `},ue=e=>{const t=D(e).map(o=>` - "${o}/*"`).join(`
33
+ `);return`# ${x}
34
+ #
35
+ # SOFT GUARD ONLY — this job does NOT block a merge by itself.
36
+ # It verifies the generated CODEOWNERS is in sync and flags that a
37
+ # restricted path changed. GitLab CI cannot portably gate a merge on
38
+ # code-owner *approval* from a job, so REAL ENFORCEMENT REQUIRES the
39
+ # native GitLab setting:
40
+ # Settings -> Repository -> Protected branches ->
41
+ # "Require approval from Code Owners" (GitLab Premium / Ultimate)
42
+ # https://docs.gitlab.com/ee/user/project/codeowners/
43
+ # Without that setting enabled, this job is advisory only.
44
+ write-guard:
45
+ stage: test
46
+ image: node:22-alpine
47
+ rules:
48
+ - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
49
+ changes:
50
+ ${t}
51
+ script:
52
+ - corepack enable
53
+ - pnpm install --frozen-lockfile
54
+ - pnpm vis sync codeowners --check
55
+ - >-
56
+ echo "SOFT GUARD: a restricted path changed. This job does NOT enforce
57
+ code-owner approval. Enable 'Require approval from Code Owners' on the
58
+ protected branch (GitLab Premium/Ultimate) for a real merge gate:
59
+ https://docs.gitlab.com/ee/user/project/codeowners/"
60
+ `},he=e=>e.length===0?[]:[{content:pe(e),path:".github/workflows/write-guard.yml"},{content:ue(e),path:".gitlab/write-guard.gitlab-ci.yml"}],L=new Set(["nested-codeowners","package-json-maintainers","project-json"]),A=(e,t,o)=>{const s=new Set,n=[];for(const r of e??[])for(const a of r.split(",")){const i=a.trim();if(i.length===0)continue;if(o&&!o(i))throw new Error(`Unknown codeowners source: "${i}". Known: ${[...L].join(", ")}.`);const c=i;s.has(c)||(s.add(c),n.push(c))}return n.length>0?n:[...t]},ge=e=>L.has(e),G=["codeowners","package-json-fields"],me=(e,t)=>t.some(o=>_(o,e)),we=async(e,t,o,s,n)=>{const r=Object.entries(s.projects).filter(([,i])=>i.restricted===!0).map(([i,c])=>({name:i,root:c.root??i})),a=he(r);if(a.length===0){t.info("No projects flagged `restricted: true` in project.json. Skipping Write Guard.");return}if(n){let i=!1;for(const c of a){const f=b(o,c.path);let h="";try{h=await e.readFile(f,"utf8")}catch(p){if(p.code!=="ENOENT")throw p}h.trim()!==c.content.trim()&&(t.error(`${c.path} is out of date. Run \`vis sync codeowners --write-guard\` to update it.`),i=!0)}i?process.exitCode=1:t.info(`Write Guard CI is up to date (${a.length} files, ${r.length} restricted projects).`);return}for(const i of a){const c=b(o,i.path);T(P(c)),I(c,i.content),t.info(`Wrote ${i.path}`)}t.info(`Write Guard CI scoped to ${r.length} restricted project${r.length===1?"":"s"}.`)},$e=async({fs:e,logger:t,options:o,visConfig:s,workspaceRoot:n})=>{const r=n,{workspace:a}=J(r,s),i=s?.codeowners;o.writeGuard===!0&&await we(e,t,r,a,o.check===!0);const c=A(o.from,i?.sources??["project-json"],ge),f=o.regenerationCommand??i?.regenerationCommand,h=o.preserveBlock===!0||i?.preserveBlock===!0,p=i?.blockMarker??O,$=o.nestedIncludes??i?.nestedIncludes,g=o.out??"CODEOWNERS",w=[];if(c.includes("nested-codeowners")){const m=await ne(r,$,g);for(const j of m)w.push({...j,source:"nested"})}if(c.includes("package-json-maintainers")){const m=ie(a,r);for(const j of m)w.push({...j,source:"maintainers"})}const l=c.includes("project-json")?v(a,i,w):v({projects:{}},i,w);if(l.length===0){t.info("No `owners` entries found in any source. Nothing to sync.");return}const y=b(r,g);let d="";try{d=await e.readFile(y,"utf8")}catch(m){if(m.code!=="ENOENT")throw m}const u={regenerationCommand:f},k=h?X(d,V(l,p,u),p):Q(l,u);if(o.check){if(d.trim()!==k.trim()){t.error(`${y} is out of date. Run \`vis sync codeowners\` to update it.`),process.exitCode=1;return}t.info(`${y} is up to date.`);return}I(y,k),t.info(`Wrote ${l.length} entries to ${y}`)},ke=({logger:e,options:t,visConfig:o,workspaceRoot:s})=>{const n=s,r=o?.editorconfig??!0,a=C(b(n,"package.json"));if(!a){e.error("Could not read root package.json. Nothing to sync."),process.exitCode=1;return}const i=A(t.fields,ae),c=t.ignorePackageName??[],f=t.check===!0,h=(t.format??"human").toLowerCase(),p=t.quiet===!0,$=B(n).filter(d=>d!=="."),g=[];let w=0;for(const d of $){const u=b(n,d,"package.json"),k=C(u);if(!k)continue;const m=typeof k.name=="string"?k.name:void 0;if(m!==void 0&&c.length>0&&me(m,c))continue;w+=1;const j=de(a,k,{fields:i});j.length!==0&&g.push({filePath:u,packageJsonPath:S(n,u),packageName:m,pkg:k,pkgChanges:j})}if(!f)for(const d of g)fe(d.pkg,d.pkgChanges),U(d.filePath,d.pkg,{indent:M(d.filePath,{useEditorconfig:r}),overwrite:!0});const l=g.flatMap(d=>d.pkgChanges.map(u=>({after:u.after,before:u.before,field:u.field,packageJsonPath:d.packageJsonPath,packageName:d.packageName}))),y={changes:l,fields:i,kind:"package-json-fields",mode:f?"check":"write",totalChanges:l.length,totalPackages:w};if(h==="json")process.stdout.write(`${JSON.stringify(y,null,4)}
61
+ `);else if(l.length===0)e.info(`All ${w} package${w===1?"":"s"} in sync (fields: ${i.join(", ")}).`);else if(f){if(!p)for(const d of l)e.error(`${d.packageJsonPath}: ${d.field} drifts from root`);e.error(`Found ${l.length} field drift${l.length===1?"":"s"} across ${g.length} package${g.length===1?"":"s"}. Run \`vis sync package-json-fields\` to fix.`)}else{if(!p)for(const d of g)e.info(`${d.packageJsonPath}: synced ${d.pkgChanges.map(u=>u.field).join(", ")}`);e.info(`Synced ${l.length} field${l.length===1?"":"s"} across ${g.length} package${g.length===1?"":"s"}.`)}f&&l.length>0&&(process.exitCode=1)},ve=async e=>{const t=e.argument[0];if(!t)throw new Error(`Missing sync kind. Usage: vis sync <kind> (known kinds: ${G.join(", ")})`);if(!e.workspaceRoot)throw new Error("Could not determine workspace root. Run inside a monorepo.");if(t==="codeowners"){await $e(e);return}if(t==="package-json-fields"){ke(e);return}throw new Error(`Unknown sync kind: "${t}". Known kinds: ${G.join(", ")}.`)};export{ve as default};
@@ -1,6 +1,3 @@
1
- import{createRequire as V}from"node:module";import{y as L,v as _,m as P,f as M,J as z,B as Y}from"../packem_shared/index-CE6MsgcV.js";import{m as t,n as a,i as c,r as v,$ as K,c as U,k as Q,s as Z,t as ee,u as re,e as te,W as N}from"./catalog.js";import"../packem_shared/env-C2ZCnfP_.js";import"../packem_shared/window-ops-DDePlWLV.js";import{I as se}from"../packem_shared/index-B0EsgdzO.js";import oe from"./index.js";import{sortPackageJsonStringWithOptions as q}from"#native";import{U as ne,V as ie,W as le,T as ce,y as ae,p as k}from"./cli-main.js";import{o as O}from"../packem_shared/utils-CRueU43T.js";const Ke=V(import.meta.url),Ue=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process;const A={error:0,rewritten:1,"would-rewrite":1,unchanged:2},de=e=>[...e].sort((r,s)=>A[r.status]-A[s.status]),ue=(e,r)=>r==="all"?e:r==="errors"?e.filter(s=>s.status==="error"):r==="rewritten"?e.filter(s=>s.status==="rewritten"||s.status==="would-rewrite"):e.filter(s=>s.status==="unchanged");class fe{#e;#r=new Set;constructor(r){this.#e={entries:de(r),filterType:"all",focusedPanel:"list",selectedIndex:0}}getSnapshot=()=>this.#e;subscribe=r=>(this.#r.add(r),()=>{this.#r.delete(r)});getFilteredEntries=()=>ue(this.#e.entries,this.#e.filterType);#t(){this.#e={...this.#e};for(const r of this.#r)r()}select(r){const s=this.getFilteredEntries();this.#e.selectedIndex=s.length===0?-1:Math.max(0,Math.min(r,s.length-1)),this.#t()}selectStep(r){this.select(this.#e.selectedIndex+r)}setFilter(r){this.#e.filterType=r,this.#e.selectedIndex=0,this.#t()}setFocusedPanel(r){this.#e.focusedPanel=r,this.#t()}}const he=({checkMode:e,entry:r,focused:s,scrollRef:l})=>{const i=s?"white":"gray";return r?t.jsxs(a,{borderColor:i,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[t.jsx(a,{flexShrink:0,paddingTop:1,paddingX:2,children:t.jsx(c,{bold:!0,color:"white",children:r.relativePath})}),t.jsxs(ne,{flexGrow:1,flexShrink:1,paddingX:2,ref:l,scrollbar:!0,scrollbarColor:"gray",children:[t.jsx(c,{}),t.jsxs(a,{children:[t.jsx(a,{width:10,children:t.jsx(c,{dimColor:!0,children:"Status:"})}),r.status==="error"?t.jsx(c,{bold:!0,color:"red",children:"error"}):r.status==="unchanged"?t.jsx(c,{bold:!0,color:"green",children:"already sorted"}):r.status==="rewritten"?t.jsx(c,{bold:!0,color:"yellow",children:"rewritten"}):t.jsx(c,{bold:!0,color:"yellow",children:"would rewrite (--check)"})]}),t.jsxs(a,{children:[t.jsx(a,{width:10,children:t.jsx(c,{dimColor:!0,children:"Path:"})}),t.jsx(c,{children:r.filePath})]}),r.error?t.jsxs(t.Fragment,{children:[t.jsxs(a,{flexDirection:"column",marginTop:1,children:[t.jsx(c,{dimColor:!0,children:"── "}),t.jsx(c,{bold:!0,color:"red",children:"ERROR"}),t.jsxs(a,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[t.jsxs(a,{children:[t.jsx(a,{width:10,children:t.jsx(c,{dimColor:!0,children:"Step:"})}),t.jsx(c,{color:"yellow",children:r.error.step})]}),r.error.context&&t.jsxs(a,{children:[t.jsx(a,{width:10,children:t.jsx(c,{dimColor:!0,children:"Position:"})}),t.jsx(c,{children:`line ${String(r.error.context.line)}, column ${String(r.error.context.column)}`})]}),t.jsx(a,{marginTop:1,children:t.jsx(c,{color:"red",children:r.error.message})})]})]}),r.error.context&&r.error.context.snippet.length>0&&t.jsxs(a,{flexDirection:"column",marginTop:1,children:[t.jsx(c,{dimColor:!0,children:"── "}),t.jsx(c,{bold:!0,color:"white",children:"SNIPPET"}),t.jsxs(a,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[r.error.context.snippet.map(o=>{const n=`${o.isErrorLine?"❯":" "} ${String(o.lineNumber).padStart(4)} `;return t.jsxs(a,{children:[t.jsx(c,{color:o.isErrorLine?"red":"gray",children:n}),t.jsx(c,{color:o.isErrorLine?"white":"gray",wrap:"truncate-end",children:o.content||" "})]},o.lineNumber)}),r.error.context.column>0&&t.jsx(a,{children:t.jsx(c,{color:"red",children:`${" ".repeat(7+r.error.context.column-1)}↑`})})]})]})]}):t.jsxs(a,{flexDirection:"column",marginTop:1,children:[t.jsx(c,{dimColor:!0,children:"── "}),t.jsx(c,{bold:!0,color:"white",children:"KEY DIFF"}),t.jsx(a,{flexDirection:"column",marginTop:1,paddingLeft:2,children:r.diff.length===0?t.jsx(c,{dimColor:!0,children:"No top-level keys moved (sub-key reorder only)."}):r.diff.map(o=>{const n=o.toIndex-o.fromIndex,d=n<0?`↑ ${String(Math.abs(n))}`:`↓ ${String(n)}`,g=n<0?"green":"yellow";return t.jsxs(a,{children:[t.jsx(a,{width:28,children:t.jsx(c,{wrap:"truncate",children:o.key})}),t.jsx(a,{width:10,children:t.jsxs(c,{dimColor:!0,children:[String(o.fromIndex)," → ",String(o.toIndex)]})}),t.jsx(c,{color:g,children:d})]},o.key)})}),e&&r.status==="would-rewrite"&&t.jsx(a,{marginTop:1,paddingLeft:2,children:t.jsx(c,{dimColor:!0,children:"--check mode: no write performed."})})]})]})]}):t.jsx(a,{alignItems:"center",borderColor:"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,justifyContent:"center",children:t.jsx(c,{dimColor:!0,children:"No entry selected"})})},ge={error:"red",rewritten:"yellow",unchanged:"green","would-rewrite":"yellow"},pe={error:"ERROR",rewritten:"REWROTE",unchanged:"SORTED","would-rewrite":"REWRITE"},H={error:"errors",rewritten:"rewrites",unchanged:"sorted","would-rewrite":"rewrites"},xe={errors:"Errors",rewrites:"Rewrites",sorted:"Sorted"},me=[{count:e=>e.errors+e.rewrites+e.sorted,key:"all",label:"All",shortcut:"1"},{count:e=>e.rewrites,key:"rewritten",label:"Rewrites",shortcut:"2"},{count:e=>e.errors,key:"errors",label:"Errors",shortcut:"3"},{count:e=>e.sorted,key:"unchanged",label:"Sorted",shortcut:"4"}],W=e=>{const r={errors:0,rewrites:0,sorted:0};for(const s of e)r[H[s.status]]++;return r},we=({entry:e,isSelected:r})=>{const s=ge[e.status],l=pe[e.status];return t.jsxs(a,{flexShrink:0,height:1,children:[t.jsx(c,{children:r?">":" "}),t.jsx(c,{children:" "}),t.jsx(c,{bold:!0,color:s,children:`[${l}]`.padEnd(10)}),t.jsx(c,{children:" "}),t.jsx(a,{flexGrow:1,children:t.jsx(c,{bold:r,inverse:r,wrap:"truncate",children:e.relativePath})}),e.status!=="error"&&e.diff.length>0&&t.jsx(c,{dimColor:!0,children:` ${String(e.diff.length)} key${e.diff.length===1?"":"s"}`})]})},je=({color:e,count:r,label:s})=>t.jsx(a,{flexShrink:0,height:1,children:t.jsx(c,{bold:!0,color:e,children:`${s} (${String(r)})`})}),ye=({counts:e,entries:r,filterType:s,focused:l,selectedIndex:i,totalEntries:o,viewportHeight:n})=>{const d=l?"white":"gray",g=W(r),m=(g.errors>0?1:0)+(g.rewrites>0?1:0)+(g.sorted>0?1:0),y=s==="all"&&m>1,h=[];let w;for(const[u,x]of r.entries()){const b=H[x.status];y&&b!==w&&(w!==void 0&&h.push({kind:"spacer"}),h.push({color:b==="errors"?"red":b==="rewrites"?"yellow":"green",count:g[b],kind:"header",label:xe[b]}),w=b),h.push({entry:x,entryIndex:u,kind:"entry"})}const p=h.findIndex(u=>u.kind==="entry"&&u.entryIndex===i),S=p!==-1,j=h.length,$=Math.max(0,j-n);let f=0;S&&n>0&&(f=Math.min($,Math.max(0,p-n+1)));const E=j>n&&n>0;return t.jsxs(a,{borderColor:d,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[t.jsxs(a,{flexShrink:0,gap:1,paddingX:1,children:[t.jsx(c,{bold:!0,inverse:!0,children:" VIS SORT "}),t.jsxs(c,{wrap:"truncate",children:[o," ","file",o===1?"":"s"]})]}),t.jsx(a,{flexShrink:0,gap:1,paddingX:1,paddingY:1,children:me.map(u=>{const x=s===u.key,b=u.count(e);return t.jsxs(a,{children:[t.jsx(c,{dimColor:!x,children:"["}),t.jsx(c,{bold:x,color:x?"cyan":"gray",children:u.shortcut}),t.jsx(c,{dimColor:!x,children:"]"}),t.jsxs(c,{color:x?"white":"gray",children:[" ",u.label]}),t.jsxs(c,{dimColor:!0,children:[" ","(",b,")"]})]},u.key)})}),t.jsxs(a,{flexDirection:"row",flexGrow:1,overflow:"hidden",children:[t.jsx(a,{flexDirection:"column",flexGrow:1,overflow:"hidden",paddingLeft:1,children:t.jsx(a,{flexDirection:"column",marginTop:-f,children:h.map((u,x)=>u.kind==="spacer"?t.jsx(a,{flexShrink:0,height:1},`s-${String(x)}`):u.kind==="header"?t.jsx(je,{color:u.color,count:u.count,label:u.label},`h-${u.label}`):t.jsx(we,{entry:u.entry,isSelected:u.entryIndex===i},u.entry.filePath))})}),E&&t.jsx(a,{flexShrink:0,marginLeft:1,marginRight:1,children:t.jsx(ie,{contentHeight:j,placement:"inset",scrollOffset:f,style:"block",viewportHeight:n})})]})]})},be=100,D=10,ke=6,Se=1,F={1:"all",2:"rewritten",3:"errors",4:"unchanged"},$e=({checkMode:e,store:r})=>{const{exit:s}=le(),{columns:l,rows:i}=ce(),o=v.useSyncExternalStore(r.subscribe,r.getSnapshot),n=v.useRef(null),d=r.getFilteredEntries(),g=d[o.selectedIndex]??null,m=W(o.entries),y=l>=be,h=Math.max(0,i-Se),w=y?h:Math.floor(h/2),p=Math.max(0,w-ke),S=v.useCallback(()=>{s()},[s]),j=v.useRef(0),$=v.useRef(void 0),f=v.useRef(!1),E=v.useCallback((u,x)=>{j.current+=x,$.current=u,!f.current&&(f.current=!0,queueMicrotask(()=>{f.current=!1;const b=j.current,T=$.current;j.current=0,$.current=void 0,!(b===0||T===void 0)&&(T==="list"?r.selectStep(Math.sign(b)):n.current?.scrollBy(Math.sign(b)))}))},[r]);return ae((u,x)=>{if(u==="q"||x.escape){S();return}if(F[u]){r.setFilter(F[u]);return}if(x.tab){r.setFocusedPanel(o.focusedPanel==="list"?"detail":"list");return}o.focusedPanel==="list"?x.upArrow||u==="k"?E("list",-1):(x.downArrow||u==="j")&&E("list",1):o.focusedPanel==="detail"&&(x.upArrow||u==="k"?E("detail",-1):(x.downArrow||u==="j")&&E("detail",1))}),i<D?t.jsx(a,{alignItems:"center",justifyContent:"center",children:t.jsxs(c,{color:"yellow",children:["Terminal too small. Resize to at least",D," ","rows."]})}):t.jsxs(a,{flexDirection:"column",height:i,width:l,children:[t.jsxs(a,{flexDirection:y?"row":"column",flexGrow:1,children:[t.jsx(a,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:t.jsx(ye,{counts:m,entries:d,filterType:o.filterType,focused:o.focusedPanel==="list",selectedIndex:o.selectedIndex,totalEntries:o.entries.length,viewportHeight:p})}),t.jsx(a,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:t.jsx(he,{checkMode:e,entry:g,focused:o.focusedPanel==="detail",scrollRef:n})})]}),t.jsx(a,{flexShrink:0,paddingX:1,children:t.jsx(c,{dimColor:!0,children:"↑/↓ or j/k:navigate | tab:switch panel | 1-4:filter | q:quit"})})]})},B=["types","node-addons","node","import","require","default"],ve=/^git\+https:\/\/github\.com\/([^/]+)\/([^/.]+(?:\.git)?)$/,Ee=/^git\+ssh:\/\/git@github\.com\/([^/]+)\/([^/.]+(?:\.git)?)$/,C=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),I=e=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(s=>I(s));const r={};for(const[s,l]of Object.entries(e))r[s]=I(l);return r},Pe=e=>{if(!C(e))return{changed:!1,value:e};const r=Object.keys(e);return r.length===1&&r[0]==="url"&&typeof e.url=="string"?{changed:!0,value:e.url}:{changed:!1,value:e}},Oe=e=>e.endsWith(".git")?e.slice(0,-4):e,Ce=e=>{if(!C(e))return{changed:!1,value:e};if(typeof e.directory=="string"&&e.directory.length>0)return{changed:!1,value:e};const{type:r}=e;if(r!==void 0&&r!=="git")return{changed:!1,value:e};const{url:s}=e;if(typeof s!="string")return{changed:!1,value:e};const l=ve.exec(s)??Ee.exec(s);if(!l)return{changed:!1,value:e};const i=l[1],o=Oe(l[2]??"");if(!i||!o)return{changed:!1,value:e};const n=new Set(["type","url"]);for(const d of Object.keys(e))if(!n.has(d))return{changed:!1,value:e};return{changed:!0,value:`${i}/${o}`}},Re=e=>{const r=Object.keys(e),s=[],l=[];for(const n of B)Object.hasOwn(e,n)&&s.push(n);for(const n of r)B.includes(n)||l.push(n);const i=[...s,...l];if(i.length===r.length&&i.every((n,d)=>n===r[d]))return{changed:!1,value:e};const o={};for(const n of i)o[n]=e[n];return{changed:!0,value:o}},X=e=>{if(!C(e))return{changed:!1,value:e};let r=!1;const s={};for(const[i,o]of Object.entries(e)){const n=X(o);s[i]=n.value,n.changed&&(r=!0)}const l=Re(s);return{changed:r||l.changed,value:l.value}},Ie=(e,r)=>{const s=I(e);let l=!1;if(r.formatBugs!==!1&&Object.hasOwn(s,"bugs")){const i=Pe(s.bugs);i.changed&&(s.bugs=i.value,l=!0)}if(r.formatRepository!==!1&&Object.hasOwn(s,"repository")){const i=Ce(s.repository);i.changed&&(s.repository=i.value,l=!0)}if(r.sortExports!==!1&&Object.hasOwn(s,"exports")&&C(s.exports)){const i=X(s.exports);i.changed&&(s.exports=i.value,l=!0)}return{changed:l,pkg:s}},Te=/at position (\d+)/,Me=/\(?line (\d+) column (\d+)\)?/,Ne=e=>{const r=new Set,s=[],l=o=>{const n=Y(o);!r.has(n)&&M(n)&&(r.add(n),s.push(n))};l(P(e,"package.json"));const i=te(e);if(i){const o=N(e,i);for(const n of o)l(P(e,n,"package.json"))}else{const o=P(e,"package.json");if(M(o)){const n=JSON.parse(_(o)),d=Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages;if(d){const g=N(e,d);for(const m of g)l(P(e,m,"package.json"))}}}return s},Ae=e=>/\n([ \t]+)/.exec(e)?.[1]??" ",De=e=>{if(!(e===void 0||e===""))return e==="tab"||e===String.raw`\t`?" ":/^\d+$/.test(e)?" ".repeat(Number.parseInt(e,10)):e},R=e=>e===void 0?[]:(Array.isArray(e)?e:[e]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0),Fe=e=>e.includes(`\r
2
- `)?"crlf":"lf",Be=new Set(["auto","crlf","lf"]),Ge=e=>{if(e===void 0||e==="")return"auto";if(Be.has(e))return e;throw new Error(`--line-ending must be one of: auto, lf, crlf (got "${e}")`)},Je=(e,r,s)=>r.length===0?e:e.filter(l=>{const i=L(s,l),o=z(l);return!r.some(n=>{const d=n.includes("/")?i:o;return oe(n,d)})}),Le=(e,r)=>{if(r.length===0)return e;const s={},l=new Set;for(const i of r)Object.hasOwn(e,i)&&(s[i]=e[i],l.add(i));for(const i of Object.keys(e))l.has(i)||(s[i]=e[i]);return s},_e=(e,r,s)=>{if(s.length===0)return e;const l={...e};for(const i of s)Object.hasOwn(r,i)&&(l[i]=r[i]);return l},qe=(e,r)=>{let s=1,l=1;const i=Math.min(r,e.length);for(let o=0;o<i;o++)e.codePointAt(o)===10?(s++,l=1):l++;return{column:l,line:s}},G=(e,r,s=2)=>{const l=e.split(`
3
- `);if(r<1||r>l.length)return[];const i=Math.max(0,r-1-s),o=Math.min(l.length,r+s),n=[];for(let d=i;d<o;d++)n.push({content:l[d]??"",isErrorLine:d+1===r,lineNumber:d+1});return n},J=(e,r)=>{if(!(e instanceof Error))return;const s=Te.exec(e.message);if(s){const{column:i,line:o}=qe(r,Number.parseInt(s[1]??"0",10));return{column:i,line:o,snippet:G(r,o)}}const l=Me.exec(e.message);if(l){const i=Number.parseInt(l[1]??"1",10);return{column:Number.parseInt(l[2]??"1",10),line:i,snippet:G(r,i)}}},He=(e,r)=>{const s=Object.keys(JSON.parse(e)),l=Object.keys(JSON.parse(r)),i=new Map(s.map((n,d)=>[n,d])),o=[];for(const[n,d]of l.entries()){const g=i.get(d);g!==void 0&&g!==n&&o.push({fromIndex:g,key:d,toIndex:n})}return o},We=(e,r,s)=>{const l=r.indent??s.indent??Ae(e),i=r.lineEnding==="auto"?s.lineEnding??Fe(e):r.lineEnding,o=q(e,{pretty:!1,sortScripts:r.sortScripts});let n=JSON.parse(o);if(r.unsorted.length>0){const y=JSON.parse(e);n=_e(n,y,r.unsorted)}n=Le(n,r.sortOrder);const d={formatBugs:r.formatBugs,formatRepository:r.formatRepository,sortExports:r.sortExports},g=Ie(n,d);let m=JSON.stringify(g.pkg,null,l);return r.finalNewline&&(m+=`
4
- `),i==="crlf"&&(m=m.replaceAll(`
5
- `,`\r
6
- `)),m},Xe=(e,r)=>{const s=Ne(e),l=Q(e),i=Z({cwd:e,extraPatterns:ee(l)}),o=s.filter(d=>!i.ignores(d)),n=Je(o,r,e);return{afterGitignore:o,allFiles:s,files:n}},Ve=async(e,{checkMode:r,cwd:s,fs:l,normalized:i})=>{const o=L(s,e)||e;let n;try{n=_(e)}catch(h){return{diff:[],error:{message:O(h),step:"read"},filePath:e,relativePath:o,status:"error"}}let d;try{d=q(n,{pretty:!1,sortScripts:i.sortScripts})}catch(h){const w={message:O(h),step:"native-sort"},p=J(h,n);return p&&(w.context=p),{diff:[],error:w,filePath:e,relativePath:o,status:"error"}}const g=i.editorconfig?re(e):{};let m;try{m=We(n,i,g)}catch(h){const w={message:O(h),step:"json-parse"},p=J(h,n);return p&&(w.context=p),{diff:[],error:w,filePath:e,relativePath:o,status:"error"}}if(n===m)return{diff:[],filePath:e,relativePath:o,status:"unchanged"};let y;try{y=He(n,d)}catch{y=[]}if(r)return{diff:y,filePath:e,relativePath:o,status:"would-rewrite"};try{await l.writeFile(e,m,"utf8")}catch(h){return{diff:y,error:{message:O(h),step:"write"},filePath:e,relativePath:o,status:"error"}}return{diff:y,filePath:e,relativePath:o,status:"rewritten"}},ze=e=>{if(e.error&&(k.error(`${e.filePath}: ${e.error.message}`),k.info(` step: ${e.error.step}`),e.error.context)){k.info(` at line ${String(e.error.context.line)}, column ${String(e.error.context.column)}`);for(const r of e.error.context.snippet){const s=r.isErrorLine?">":" ";k.info(` ${s} ${String(r.lineNumber).padStart(4)} | ${r.content}`)}}},lr=async({fs:e,options:r,visConfig:s,workspaceRoot:l})=>{const i=l??process.cwd(),o=s?.sortPackageJson,n=r.check||!1,d={editorconfig:r.editorconfig===!1?!1:o?.editorconfig??!0,finalNewline:r.finalNewline??o?.finalNewline??!0,formatBugs:r.formatBugs===!1?!1:o?.formatBugs??!0,formatRepository:r.formatRepository===!1?!1:o?.formatRepository??!0,ignore:[...R(r.ignore),...o?.ignore??[]],indent:De(r.indent??o?.indent),lineEnding:Ge(r.lineEnding??o?.lineEnding),sortExports:r.sortExports===!1?!1:o?.sortExports??!0,sortOrder:[...R(r.sortOrder),...o?.sortOrder??[]],sortScripts:r.sortScripts||o?.sortScripts||!1,unsorted:[...R(r.unsorted),...o?.unsorted??[]]},g=Xe(i,d.ignore),{afterGitignore:m,allFiles:y,files:h}=g;if(h.length===0){y.length===0?k.info("No package.json files found."):m.length===0?k.info("All package.json files were excluded by .gitignore or workspace exclusions."):k.info("All package.json files were excluded by --ignore.");return}const w=[];for(const f of h)w.push(await Ve(f,{checkMode:n,cwd:i,fs:e,normalized:d}));let p=0,S=0,j=0;for(const f of w)f.status==="error"?j++:f.status==="rewritten"||f.status==="would-rewrite"?p++:S++;const $=p>0||j>0;if(process.stdout.isTTY&&!se&&$){const f=new fe(w);await K(U.createElement($e,{checkMode:n,store:f}),{alternateScreen:!0,exitOnCtrlC:!1,interactive:!0,patchConsole:!0}).waitUntilExit()}else for(const f of w)switch(f.status){case"error":{ze(f);break}case"rewritten":{k.success(`Sorted ${f.filePath}`);break}case"would-rewrite":{k.warn(`${f.filePath} is not sorted`);break}}if(n)p>0?(k.info(`${String(p)} file${p===1?"":"s"} not sorted, ${String(S)} already sorted`),process.exitCode=1):j===0&&k.info(`All ${String(S)} package.json file${S===1?" is":"s are"} sorted`);else{const f=[];p>0&&f.push(`sorted ${String(p)} file${p===1?"":"s"}`),S>0&&f.push(`${String(S)} already sorted`),j>0&&f.push(`${String(j)} error${j===1?"":"s"}`),f.length>0&&k.info(f.join(", "))}j>0&&(process.exitCode=1)};export{G as buildSnippet,He as computeKeyDiff,qe as computeLineColumn,lr as default,Xe as discoverPackageJsonFiles,J as extractParseErrorContext,Ve as processFile};
1
+ import{createRequire as G}from"node:module";import{I as q,j as X,E as O,V as K,s as T,q as D}from"../packem_shared/index.server-J83sowC4.js";import{y as B}from"../packem_shared/index-CE6MsgcV.js";import{X as Q}from"./cli-main.js";import{d as k,f as v,r as Y,a as Z,b as ee,s as ne,c as te,e as ie,u as re,h as se,i as oe,j as ae,k as le,l as ce,m as de,n as ue,v as fe,w as ge,q as pe,t as me}from"../packem_shared/watch-loop-BZudYfcl.js";import{p as c}from"./catalog.js";const H=G(import.meta.url),w=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,U=e=>{if(typeof w<"u"&&w.versions&&w.versions.node){const[n,t]=w.versions.node.split(".").map(Number);if(n>22||n===22&&t>=3||n===20&&t>=16)return w.getBuiltinModule(e)}return H(e)},{createHash:y}=U("node:crypto"),he={1:"warning",2:"error"},xe={argsCheck:(e,n)=>V(e,n,!1),argsFix:(e,n)=>V(e,n,!0),bin:()=>["pnpm","exec","eslint"],cacheKey:(e,n)=>{const t=["eslint",e.declaredVersion??"unknown",e.configFile??"no-config",n.maxWarnings===void 0?"":`mw=${n.maxWarnings}`,n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=k(n,c.eslint.packageNames[0]),i=v(e,c.eslint.configFiles);if(!(!t&&!i))return{adapter:"eslint",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["cjs","cts","js","jsx","mjs","mts","ts","tsx","vue"],id:"eslint",kind:"lint",parse:(e,n)=>{if(!e.stdout.trim())return[];let t;try{t=JSON.parse(e.stdout)}catch{return[{adapter:"eslint",file:n.root,fixable:!1,message:`eslint output was not valid JSON (exit ${e.exitCode})`,severity:"error"}]}const i=[];for(const r of t)for(const s of r.messages)i.push({adapter:"eslint",column:s.column,endColumn:s.endColumn,endLine:s.endLine,file:r.filePath,fixable:!!s.fix,line:s.line,message:s.message,ruleId:s.ruleId??void 0,severity:s.fatal?"error":he[s.severity]??"warning"});return i}},V=(e,n,t)=>{const i=["--format","json","--no-error-on-unmatched-pattern"];return t&&i.push("--fix"),n.quiet&&i.push("--quiet"),typeof n.maxWarnings=="number"&&i.push("--max-warnings",String(n.maxWarnings)),n.extraArgs?.length&&i.push(...n.extraArgs),i.push(...e),i},we=/^([^:]+):(\d+)(?::(\d+))?\s+([\w/-]+)\s+(.+)$/,ke=e=>{const n=we.exec(e);if(!n)return;const[,t,i,r,s,a]=n;return{column:r===void 0?void 0:Number(r),file:t,line:Number(i),message:a,ruleId:s}},ve=e=>e.startsWith("/")||/^[a-z]:[\\/]/i.test(e),ye={argsCheck:(e,n)=>J(e,n,!1),argsFix:(e,n)=>J(e,n,!0),bin:()=>["pnpm","exec","markdownlint-cli2"],cacheKey:(e,n)=>{const t=["markdownlint",e.declaredVersion??"unknown",e.configFile??"no-config",n.maxWarnings===void 0?"":`mw=${n.maxWarnings}`,n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=c.markdownlint.packageNames.map(r=>k(n,r)).find(r=>r!==void 0),i=v(e,c.markdownlint.configFiles);if(!(!t&&!i))return{adapter:"markdownlint",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["markdown","md"],id:"markdownlint",kind:"lint",parse:(e,n)=>{const t=(e.stderr||e.stdout||"").trim();if(!t)return[];const i=[];for(const r of t.split(/\r?\n/)){const s=ke(r.trim());s&&i.push({adapter:"markdownlint",column:s.column,file:ve(s.file)?s.file:`${n.root}/${s.file}`,fixable:!0,line:s.line,message:s.message,ruleId:s.ruleId,severity:"warning"})}return i}},J=(e,n,t)=>{const i=[];return t&&i.push("--fix"),n.extraArgs?.length&&i.push(...n.extraArgs),e.length===0?i.push("**/*.md"):i.push(...e),i},$e={advice:"info",error:"error",warning:"warning"},be={argsCheck:(e,n)=>R(e,n,!1),argsFix:(e,n)=>R(e,n,!0),bin:()=>["pnpm","exec","oxlint"],cacheKey:(e,n)=>{const t=["oxlint",e.declaredVersion??"unknown",e.configFile??"no-config",n.maxWarnings===void 0?"":`mw=${n.maxWarnings}`,n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=k(n,c.oxlint.packageNames[0]),i=v(e,c.oxlint.configFiles);if(!(!t&&!i))return{adapter:"oxlint",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["astro","cjs","cts","js","jsx","mjs","mts","svelte","ts","tsx","vue"],id:"oxlint",kind:"lint",parse:(e,n)=>{if(!e.stdout.trim())return[];let t;try{t=JSON.parse(e.stdout)}catch{return[{adapter:"oxlint",file:n.root,fixable:!1,message:`oxlint output was not valid JSON (exit ${e.exitCode})`,severity:"error"}]}const i=[];for(const r of t.diagnostics??[]){const s=r.labels?.[0]?.span;i.push({adapter:"oxlint",column:s?.column,file:r.filename??n.root,fixable:!1,line:s?.line,message:r.message??"",ruleId:r.code,severity:$e[r.severity??""]??"warning"})}return i}},R=(e,n,t)=>{const i=["--format","json"];return t&&i.push("--fix"),n.quiet&&i.push("--quiet"),typeof n.maxWarnings=="number"&&i.push(`--max-warnings=${String(n.maxWarnings)}`),n.extraArgs?.length&&i.push(...n.extraArgs),i.push(...e),i},Ae={error:"error",info:"info",style:"info",warning:"warning"},Fe=e=>e.startsWith("/")||/^[a-z]:[\\/]/i.test(e),je=(e,n)=>e?Fe(e)?e:`${n}/${e}`:n,Ce={argsCheck:(e,n)=>L(e,n),argsFix:(e,n)=>L(e,n),bin:()=>["shellcheck"],cacheKey:(e,n)=>{const t=["shellcheck",e.declaredVersion??"unknown",e.configFile??"no-config",n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=k(n,c.shellcheck.packageNames[0]),i=v(e,c.shellcheck.configFiles);if(!(!t&&!i))return{adapter:"shellcheck",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["bash","ksh","sh"],id:"shellcheck",kind:"lint",parse:(e,n)=>{if(!e.stdout.trim())return[];let t;try{t=JSON.parse(e.stdout)}catch{return[{adapter:"shellcheck",file:n.root,fixable:!1,message:`shellcheck output was not valid JSON (exit ${e.exitCode})`,severity:"error"}]}const i=[];for(const r of t.comments??[])i.push({adapter:"shellcheck",column:r.column,endColumn:r.endColumn,endLine:r.endLine,file:je(r.file,n.root),fixable:!!r.fix,line:r.line,message:r.message??"",ruleId:r.code===void 0?void 0:`SC${String(r.code)}`,severity:Ae[r.level??""]??"warning"});return i}},L=(e,n)=>{const t=["--format=json1"];return n.extraArgs?.length&&t.push(...n.extraArgs),t.push(...e),t},Se={error:"error",warning:"warning"},qe={argsCheck:(e,n)=>M(e,n,!1),argsFix:(e,n)=>M(e,n,!0),bin:()=>["pnpm","exec","stylelint"],cacheKey:(e,n)=>{const t=["stylelint",e.declaredVersion??"unknown",e.configFile??"no-config",n.maxWarnings===void 0?"":`mw=${n.maxWarnings}`,n.quiet?"q":"",...n.extraArgs??[]];return y("sha256").update(t.join("|")).digest("hex").slice(0,16)},detect:(e,n)=>{const t=k(n,c.stylelint.packageNames[0]),i=v(e,c.stylelint.configFiles);if(!(!t&&!i))return{adapter:"stylelint",configFile:i,declared:!!t,declaredVersion:t,root:e}},extensions:["astro","css","less","sass","scss","svelte","vue"],id:"stylelint",kind:"lint",parse:(e,n)=>{if(!e.stdout.trim())return[];let t;try{t=JSON.parse(e.stdout)}catch{return[{adapter:"stylelint",file:n.root,fixable:!1,message:`stylelint output was not valid JSON (exit ${e.exitCode})`,severity:"error"}]}const i=[];for(const r of t)for(const s of r.warnings??[])i.push({adapter:"stylelint",column:s.column,endColumn:s.endColumn,endLine:s.endLine,file:r.source,fixable:!1,line:s.line,message:s.text??"",ruleId:s.rule,severity:Se[s.severity??""]??"warning"});return i}},M=(e,n,t)=>{const i=["--formatter","json"];return t&&i.push("--fix"),n.quiet&&i.push("--quiet"),typeof n.maxWarnings=="number"&&i.push("--max-warnings",String(n.maxWarnings)),n.extraArgs?.length&&i.push(...n.extraArgs),i.push(...e),i},We=[be,ue,xe,qe,fe,ye,Ce,ge],Be=async({logger:e,options:n,visConfig:t,workspaceRoot:i})=>{const r=i??process.cwd(),s=t?.lint,a=Y(We,s?.order),j=Z(r,a),d=ee(j,a,"lint").filter(({adapter:l})=>s?.adapters?.[l.id]?.enabled!==!1);if(d.length===0){e.warn("vis lint: no linter detected in this workspace (looked for: oxlint, biome, eslint, stylelint, ruff, markdownlint, shellcheck, deno).");return}const C=l=>{const u=s?.adapters?.[l]?.extraArgs;return u&&u.length>0?[...u]:void 0},$={extraArgs:void 0,maxWarnings:typeof n.maxWarnings=="number"?n.maxWarnings:void 0,quiet:n.quiet??!1},b=Ne(n),P=n.fix?"fix":"check";let f;if(n.staged){if(f=ne(r),f===void 0)e.warn("vis lint: could not resolve --staged (not a git repo or git unavailable). Falling back to a workspace-wide run.");else if(f.length===0){e.info(q("✓ lint: no staged files"));return}}else if(typeof n.since=="string"&&n.since.length>0){if(f=te(r,n.since),f===void 0)e.warn(`vis lint: could not resolve --since ${n.since} (not a git repo or unknown ref). Falling back to a workspace-wide run.`);else if(f.length===0){e.info(q(`✓ lint: no files changed since ${n.since}`));return}}const W=b.length>0?b:void 0,E=Q(r,void 0,void 0,!0),S=n.format??"human";S==="human"&&n.output!==void 0&&e.warn("vis lint: --output is ignored for the human format; pass --format json|minimal|sarif|junit|github to redirect findings to a file.");const N=async l=>{const u=l!==void 0&&l.length>0&&W===void 0,m=[];for(const{adapter:o,presence:x}of d){let g;if(u){if(g=re(l,o.extensions),g.length===0)continue}else g=W??l??["."];const F=C(o.id),I={adapter:o,files:g,presence:x};F&&(I.options={...$,extraArgs:F}),m.push(I)}if(m.length===0)return;const z=await se(m,$,P,{cacheRoot:E}),A=m.map((o,x)=>{const g=z[x],F=o.adapter.parse(g,o.presence);return{adapter:o.adapter,durationMs:g.durationMs,exitCode:g.exitCode,findings:F}}),h=oe(A.map(o=>({adapter:o.adapter.id,durationMs:o.durationMs,exitCode:o.exitCode,findingCount:o.findings.length,findings:o.findings}))),p=S==="human"?void 0:ae({cwd:r,target:n.output});try{switch(S){case"github":{p.write(de({runs:A.map(o=>({findings:o.findings})),workspaceRoot:r}));break}case"json":{p.write(`${JSON.stringify({findings:h.findings,runs:h.runs},null,2)}
2
+ `);break}case"junit":{p.write(ce({runs:A.map(o=>({adapter:o.adapter.id,durationMs:o.durationMs,findings:o.findings})),workspaceRoot:r}));break}case"minimal":{Ie(h.findings,r,p);break}case"sarif":{p.write(le({runs:A.map(o=>({adapter:o.adapter.id,findings:o.findings,presence:m.find(x=>x.adapter.id===o.adapter.id)?.presence})),workspaceRoot:r}));break}default:_e(h.findings,r,e)}}finally{p?.close()}const _=me(h);_!==0&&(process.exitCode=_)};if(n.watch){const l=[...new Set(d.flatMap(({adapter:u})=>u.extensions))];await ie({extensions:l,initialFiles:f,label:"lint",log:u=>{e.info(u)},runCycle:N,workspaceRoot:r});return}await N(f)},Ne=e=>{const n=e;return[...n._??n.args??[]]},_e=(e,n,t)=>{if(e.length===0){t.info(q("✓ lint: no findings"));return}const i=pe(e);for(const[a,j]of i){t.info(X(B(n,a)));for(const d of j){const C=Oe(d),$=Ve(d.severity),b=d.ruleId?O(` ${d.ruleId}`):"";t.info(` ${O(C)} ${$} ${d.message}${b}`)}}const r=e.filter(a=>a.severity==="error").length,s=e.filter(a=>a.severity==="warning").length;t.info(""),t.info(`${K(`${String(r)} error${r===1?"":"s"}`)}, ${T(`${String(s)} warning${s===1?"":"s"}`)}`)},Ie=(e,n,t)=>{for(const i of e){const r=B(n,i.file),s=i.line??"",a=i.column??"";t.write(`${i.adapter} ${r} ${String(s)} ${String(a)} ${i.severity} ${i.ruleId??""} ${i.message}
3
+ `)}},Oe=e=>e.line===void 0?"":e.column===void 0?String(e.line):`${String(e.line)}:${String(e.column)}`,Ve=e=>e==="error"?K("error"):e==="warning"?T("warn "):D("info ");export{Be as default};
@@ -1,9 +1,6 @@
1
- import{createRequire as q}from"node:module";import{DEFAULT_CHANGES_DIR as Z}from"./DEFAULT_CLEAN_KEEP.js";import{b as J,f as Q}from"./orchestrator.js";import{createShellRunner as X}from"./shell-runner.js";import{r as ee}from"../packem_shared/slug-DoueYuLo.js";import{maxBump as te}from"../release/types.js";const V=q(import.meta.url),P=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,U=s=>{if(typeof P<"u"&&P.versions&&P.versions.node){const[e,t]=P.versions.node.split(".").map(Number);if(e>22||e===22&&t>=3||e===20&&t>=16)return P.getBuiltinModule(s)}return V(s)},{join:M,relative:Y}=U("node:path"),D=/(?!.*)/;function re(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function S(s){return s.map(e=>typeof e=="string"?re(e.trim()):e.source).filter(Boolean).join("|")}function ne(s,e){if(!s)return D;const t=S(s);return e?e(t):new RegExp(`^[\\s|*]*(${t})[:\\s]+(.*)`,"i")}function se(s,e){if(!s)return D;const t=e?"g":"gi";return new RegExp(`(?:.*?)??\\s*([\\w-\\.\\/]*?)??(${S(s)})([\\w-]+)(?=\\s|$|[,;)\\]])`,t)}function ie(s){if(!s)return/()(.+)/gi;const e=S(s);return new RegExp(`(${e})(?:\\s+(.*?))(?=(?:${e})|$)`,"gi")}function oe(s={}){const e=ne(s.noteKeywords,s.notesPattern),t=se(s.issuePrefixes,s.issuePrefixesCaseSensitive),r=ie(s.referenceActions);return{notes:e,referenceParts:t,references:r,mentions:/@([\w-]+)/g,url:/\b(?:https?):\/\/(?:www\.)?([-a-zA-Z0-9@:%_+.~#?&//=])+\b/}}const ce="------------------------ >8 ------------------------";function j(s){const e=s.match(/[^\r\n]/);if(typeof e?.index!="number")return"";const t=e.index;let r=s.length-1;for(;s[r]==="\r"||s[r]===`
2
- `;)r--;return s.substring(t,r+1)}function A(s,e){return s?`${s}
3
- ${e||""}`:e||""}function ae(s){return s?e=>!e.startsWith(s):()=>!0}function le(s,e){const t=s.indexOf(`${e} ${ce}`);return t===-1?s:s.slice(0,t)}function I(s){return!s.match(/^\s*gpg:/)}function _(s,e,t){const{groups:r}=e;for(let n=0,i=t.length,c;n<i;n++)c=t[n],s[c]=(r?r[c]:e[n+1])||null;return s}const fe={noteKeywords:["BREAKING CHANGE","BREAKING-CHANGE"],issuePrefixes:["#"],referenceActions:["close","closes","closed","fix","fixes","fixed","resolve","resolves","resolved"],headerPattern:/^(\w*)(?:\(([\w$@.\-*/ ]*)\))?: (.*)$/,headerCorrespondence:["type","scope","subject"],revertPattern:/^Revert\s"([\s\S]*)"\s*This reverts commit (\w*)\.?/,revertCorrespondence:["header","hash"],fieldPattern:/^-(.*?)-$/};function T(s={}){return{merge:null,revert:null,header:null,body:null,footer:null,notes:[],mentions:[],references:[],...s}}class he{options;regexes;lines=[];lineIndex=0;commit=T();constructor(e={}){this.options={...fe,...e},this.regexes=oe(this.options)}currentLine(){return this.lines[this.lineIndex]}nextLine(){return this.lines[this.lineIndex++]}isLineAvailable(){return this.lineIndex<this.lines.length}parseReference(e,t){const{regexes:r}=this;if(r.url.test(e))return null;const n=r.referenceParts.exec(e);if(!n)return null;let[i,c=null,u,p]=n,x=null;if(c){const b=c.indexOf("/");b!==-1&&(x=c.slice(0,b),c=c.slice(b+1))}return{raw:i,action:t,owner:x,repository:c,prefix:u,issue:p}}parseReferences(e){const{regexes:t}=this,r=e.match(t.references)?t.references:/()(.+)/gi,n=[];let i,c,u,p;for(;i=r.exec(e),!!i;)for(c=i[1]||null,u=i[2]||"";p=this.parseReference(u,c),!!p;)n.push(p);return n}skipEmptyLines(){let e=this.currentLine();for(;e!==void 0&&!e.trim();)this.nextLine(),e=this.currentLine()}parseMerge(){const{commit:e,options:t}=this,r=t.mergeCorrespondence||[],n=this.currentLine(),i=n&&t.mergePattern?n.match(t.mergePattern):null;return i?(this.nextLine(),e.merge=i[0]||null,_(e,i,r),!0):!1}parseHeader(e){e&&this.skipEmptyLines();const{commit:t,options:r}=this,n=r.headerCorrespondence||[],i=t.header??this.nextLine();let c=null;i&&(r.breakingHeaderPattern&&(c=i.match(r.breakingHeaderPattern)),!c&&r.headerPattern&&(c=i.match(r.headerPattern))),i&&(t.header=i),c&&_(t,c,n)}parseMeta(){const{options:e,commit:t}=this;if(!e.fieldPattern||!this.isLineAvailable())return!1;let r,n=null,i=!1;for(;this.isLineAvailable();){if(r=this.currentLine().match(e.fieldPattern),r){n=r[1]||null,this.nextLine();continue}if(n)i=!0,t[n]=A(t[n],this.currentLine()),this.nextLine();else break}return i}parseNotes(){const{regexes:e,commit:t}=this;if(!this.isLineAvailable())return!1;const r=this.currentLine().match(e.notes);let n=[];if(r){const i={title:r[1],text:r[2]};for(t.notes.push(i),t.footer=A(t.footer,this.currentLine()),this.nextLine();this.isLineAvailable();){if(this.parseMeta()||this.parseNotes())return!0;if(n=this.parseReferences(this.currentLine()),n.length?t.references.push(...n):i.text=A(i.text,this.currentLine()),t.footer=A(t.footer,this.currentLine()),this.nextLine(),n.length)break}return!0}return!1}parseBodyAndFooter(e){const{commit:t}=this;if(!this.isLineAvailable())return e;const r=this.parseReferences(this.currentLine()),n=!r.length&&e;return n?t.body=A(t.body,this.currentLine()):(t.references.push(...r),t.footer=A(t.footer,this.currentLine())),this.nextLine(),n}parseBreakingHeader(){const{commit:e,options:t}=this;if(!t.breakingHeaderPattern||e.notes.length||!e.header)return;const r=e.header.match(t.breakingHeaderPattern);r&&e.notes.push({title:"BREAKING CHANGE",text:r[3]})}parseMentions(e){const{commit:t,regexes:r}=this;let n;for(;n=r.mentions.exec(e),!!n;)t.mentions.push(n[1])}parseRevert(e){const{commit:t,options:r}=this,n=r.revertCorrespondence||[],i=r.revertPattern?e.match(r.revertPattern):null;i&&(t.revert=_({},i,n))}cleanupCommit(){const{commit:e}=this;e.body&&(e.body=j(e.body)),e.footer&&(e.footer=j(e.footer)),e.notes.forEach(r=>{r.text=j(r.text)});const t=new Set;e.references=e.references.filter(r=>{const n=`${r.action} ${r.raw}`.toLocaleLowerCase(),i=!t.has(n);return i&&t.add(n),i})}parse(e){if(!e.trim())throw new TypeError("Expected a raw commit");const{commentChar:t}=this.options,r=ae(t),n=j(e).split(/\r?\n/),i=t?le(n,t).filter(x=>r(x)&&I(x)):n.filter(x=>I(x)),c=T();this.lines=i,this.lineIndex=0,this.commit=c;const u=this.parseMerge();this.parseHeader(u),c.header&&(c.references=this.parseReferences(c.header));let p=!0;for(;this.isLineAvailable();)this.parseMeta(),this.parseNotes()&&(p=!1),this.parseBodyAndFooter(p)||(p=!1);return this.parseBreakingHeader(),this.parseMentions(e),this.parseRevert(e),this.cleanupCommit(),c}}const N={build:"patch",chore:"patch",ci:"patch",docs:"patch",feat:"minor",fix:"patch",perf:"patch",refactor:"patch",style:"patch",test:"patch"},ue=new he,pe=/^Revert\s+"(.+)"\s*$/,de=/This reverts commit\s+([0-9a-f]{7,40})/i,me=/^(?:[\p{Emoji_Presentation}\p{Extended_Pictographic}]|:\w+:)\s+/u,ge=(s,e)=>{const t=s.replace(me,""),r=ue.parse(`${t}
4
-
5
- ${e}`);return{breaking:r.notes.some(n=>/BREAKING/i.test(n.title)),scope:r.scope??void 0,type:r.type??void 0}},xe=(s,e,t)=>{let r,n=!1;if(t.type==="revert"){n=!0;const u=s.indexOf(":");u!==-1&&(r=s.slice(u+1).trim())}else{const u=pe.exec(s.trim());u&&(n=!0,r=u[1]?.trim())}let i;const c=de.exec(e);return c&&(i=c[1]?.toLowerCase()),{isRevert:n,targetSha:i,targetSubject:r}},ve=(s,e=new Set,t)=>{const r=s.map(o=>{const l=ge(o.subject,o.body),{isRevert:a,targetSha:f,targetSubject:d}=xe(o.subject,o.body,l);return{...o,cancelled:!1,parsed:l,revert:a,revertSubject:d,revertTargetSha:f}}),n=r.toReversed(),i=12,c=new Map;for(const o of n)if(c.set(o.hash,o),o.hash.length>=7){const l=Math.min(o.hash.length-1,i);for(let a=7;a<=l;a+=1){const f=o.hash.slice(0,a);if(c.has(f)){const d=c.get(f);d!==null&&d!==o&&c.set(f,null)}else c.set(f,o)}}const u=(o,l)=>{if(o.revertTargetSha){const a=o.revertTargetSha.toLowerCase();let f=c.get(a)??void 0;if(f||(f=n.find(d=>d.hash.startsWith(a))),f&&f!==o)return f}if(o.revertSubject)for(let a=l.length-1;a>=0;a-=1){const f=l[a];if(f.subject===o.revertSubject)return f}},p=64,x=o=>{let l=o;for(let a=0;a<p;a+=1){if(!l.revert)return l;const f=l.cancelledBy;let d;if(f&&(d=c.get(f)??void 0,d||(d=c.get(f.slice(0,7))??void 0)),!d||d===l)return l;l=d}},b=[],w=[];for(const o of n){if(o.revert){const l=u(o,w);if(l){if(e.has(l.hash)){w.push(o);continue}const a=x(l);if(a===void 0){b.push(`Revert chain at ${o.hash} exceeded depth limit (${p}) — skipping cancellation`),w.push(o);continue}if(e.has(a.hash)){w.push(o);continue}a.cancelled=!a.cancelled,a.cancelledBy=a.cancelled?o.hash:void 0,o.cancelled=!0,o.cancelledBy=l.hash}}w.push(o)}const L=r.filter(o=>!o.cancelled&&!o.revert&&!o.subject?.startsWith("Merge ")),C=L.filter(o=>!o.parsed.type);if(L.length>0&&C.length/L.length>.5){const o=t??"<from>..HEAD";b.push(`${C.length}/${L.length} commits in ${o} have no conventional-commits prefix. Consider enabling commit-message linting.`)}return{commits:r,warnings:b}},Ae=async({fs:s,logger:e,options:t,workspaceRoot:r})=>{const n=r??process.cwd(),i=await J({cwd:n,skipRegistryLookup:!0}),{printConfigIfRequested:c}=await import("./print-config.js");if(c(t,i,e))return;const u=X();let p=t.from;if(!p){const h=i.config.baseBranch??"main",m=await u.run("git",["merge-base",`origin/${h}`,"HEAD"],{cwd:n,silent:!0});if(m.exitCode===0&&m.stdout.trim())p=m.stdout.trim();else{const g=await u.run("git",["merge-base",h,"HEAD"],{cwd:n,silent:!0});p=g.exitCode===0?g.stdout.trim():"HEAD~10"}}const x=new Map;for(const h of i.packages){const m=(h.dir.startsWith(n)?h.dir.slice(n.length):h.dir).replaceAll("\\","/").replace(/^\/+/,"");x.set(m,h.name)}const b=h=>{for(const[m,g]of x)if(h.startsWith(`${m}/`)||h===`${m}/package.json`)return g},w=Math.random().toString(16).slice(2,10),L=`@@VIS_RELEASE_COMMIT_${w}@@`,C=`@@VIS_RELEASE_FILES_${w}@@`,o=await u.run("git",["log",`${p}..HEAD`,`--pretty=format:${L}%n%H%n%s%n%b%n${C}`,"--name-only"],{cwd:n,silent:!0});if(o.exitCode!==0){e.error(`git log failed: ${o.stderr}`),process.exitCode=1;return}const l=new Map,a=[],f=[],d=o.stdout.split(L).map(h=>h.trim()).filter(Boolean);for(const h of d){const[m,g=""]=h.split(C).toReversed(),E=g.split(`
6
- `),$=E[0]?.trim()??"",y=E[1]?.trim()??"",v=E.slice(2).join(`
7
- `).trim(),R=(m??"").split(`
8
- `).map(z=>z.trim()).filter(Boolean);$&&f.push({body:v,files:R,hash:$,subject:y})}const{commits:F,warnings:G}=ve(f,void 0,`${p}..HEAD`);for(const h of G)e.warn(h);for(const{cancelled:h,files:m,parsed:g,subject:E}of F){if(h)continue;let $="patch";g.breaking?$="major":g.type&&N[g.type]&&($=N[g.type]??"patch");const y=new Set;if(g.scope)for(const v of i.packages)(v.name===g.scope||v.name.endsWith(`/${g.scope}`))&&y.add(v.name);if(y.size===0)for(const v of m){const R=b(v);R&&y.add(R)}for(const v of y){const R=l.get(v);l.set(v,R?te(R,$):$)}y.size>0&&a.push(`- ${E}`)}if(l.size===0){e.info("No commits affected workspace packages — nothing to generate.");return}const O={bumps:Object.fromEntries(l)},K=a.length>0?a.join(`
9
- `):"Auto-generated change file.",k=Q(O,K);if(t.dryRun){e.info("[dry-run] would write:"),e.info(k);return}const B=i.config.changesDir??Z,W=(t.name??ee()).replaceAll(/[^a-z0-9-]/gi,"-"),H=M(n,B,`${W}.md`);await s.mkdir(M(n,B),{recursive:!0}),await s.writeFile(H,k),e.info(`Created ${Y(n,H)}`);for(const[h,m]of l)e.info(` ${h}: ${m}`)};export{Ae as default};
1
+ import{createRequire as z}from"node:module";import{y as J,v as L,m as P,f as M,J as V,B as Y}from"../packem_shared/index-CE6MsgcV.js";import{m as t,n as a,i as c,r as v,$ as K,d as Q,k as U,s as Z,t as ee,u as re,e as te,W as N}from"./catalog.js";import"../packem_shared/env-DJlbJiFh.js";import{I as se}from"../packem_shared/index-B0EsgdzO.js";import oe from"./index.js";import{sortPackageJsonStringWithOptions as q}from"#native";import{T as ne,_ as ie,U as le,Q as ce,y as ae,p as k}from"./cli-main.js";import{o as O}from"../packem_shared/utils-CRueU43T.js";const Ke=z(import.meta.url),Qe=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process;const A={error:0,rewritten:1,"would-rewrite":1,unchanged:2},de=e=>[...e].sort((r,s)=>A[r.status]-A[s.status]),ue=(e,r)=>r==="all"?e:r==="errors"?e.filter(s=>s.status==="error"):r==="rewritten"?e.filter(s=>s.status==="rewritten"||s.status==="would-rewrite"):e.filter(s=>s.status==="unchanged");class fe{#e;#r=new Set;constructor(r){this.#e={entries:de(r),filterType:"all",focusedPanel:"list",selectedIndex:0}}getSnapshot=()=>this.#e;subscribe=r=>(this.#r.add(r),()=>{this.#r.delete(r)});getFilteredEntries=()=>ue(this.#e.entries,this.#e.filterType);#t(){this.#e={...this.#e};for(const r of this.#r)r()}select(r){const s=this.getFilteredEntries();this.#e.selectedIndex=s.length===0?-1:Math.max(0,Math.min(r,s.length-1)),this.#t()}selectStep(r){this.select(this.#e.selectedIndex+r)}setFilter(r){this.#e.filterType=r,this.#e.selectedIndex=0,this.#t()}setFocusedPanel(r){this.#e.focusedPanel=r,this.#t()}}const he=({checkMode:e,entry:r,focused:s,scrollRef:l})=>{const i=s?"white":"gray";return r?t.jsxs(a,{borderColor:i,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[t.jsx(a,{flexShrink:0,paddingTop:1,paddingX:2,children:t.jsx(c,{bold:!0,color:"white",children:r.relativePath})}),t.jsxs(ne,{flexGrow:1,flexShrink:1,paddingX:2,ref:l,scrollbar:!0,scrollbarColor:"gray",children:[t.jsx(c,{}),t.jsxs(a,{children:[t.jsx(a,{width:10,children:t.jsx(c,{dimColor:!0,children:"Status:"})}),r.status==="error"?t.jsx(c,{bold:!0,color:"red",children:"error"}):r.status==="unchanged"?t.jsx(c,{bold:!0,color:"green",children:"already sorted"}):r.status==="rewritten"?t.jsx(c,{bold:!0,color:"yellow",children:"rewritten"}):t.jsx(c,{bold:!0,color:"yellow",children:"would rewrite (--check)"})]}),t.jsxs(a,{children:[t.jsx(a,{width:10,children:t.jsx(c,{dimColor:!0,children:"Path:"})}),t.jsx(c,{children:r.filePath})]}),r.error?t.jsxs(t.Fragment,{children:[t.jsxs(a,{flexDirection:"column",marginTop:1,children:[t.jsx(c,{dimColor:!0,children:"── "}),t.jsx(c,{bold:!0,color:"red",children:"ERROR"}),t.jsxs(a,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[t.jsxs(a,{children:[t.jsx(a,{width:10,children:t.jsx(c,{dimColor:!0,children:"Step:"})}),t.jsx(c,{color:"yellow",children:r.error.step})]}),r.error.context&&t.jsxs(a,{children:[t.jsx(a,{width:10,children:t.jsx(c,{dimColor:!0,children:"Position:"})}),t.jsx(c,{children:`line ${String(r.error.context.line)}, column ${String(r.error.context.column)}`})]}),t.jsx(a,{marginTop:1,children:t.jsx(c,{color:"red",children:r.error.message})})]})]}),r.error.context&&r.error.context.snippet.length>0&&t.jsxs(a,{flexDirection:"column",marginTop:1,children:[t.jsx(c,{dimColor:!0,children:"── "}),t.jsx(c,{bold:!0,color:"white",children:"SNIPPET"}),t.jsxs(a,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[r.error.context.snippet.map(o=>{const n=`${o.isErrorLine?"❯":" "} ${String(o.lineNumber).padStart(4)} `;return t.jsxs(a,{children:[t.jsx(c,{color:o.isErrorLine?"red":"gray",children:n}),t.jsx(c,{color:o.isErrorLine?"white":"gray",wrap:"truncate-end",children:o.content||" "})]},o.lineNumber)}),r.error.context.column>0&&t.jsx(a,{children:t.jsx(c,{color:"red",children:`${" ".repeat(7+r.error.context.column-1)}↑`})})]})]})]}):t.jsxs(a,{flexDirection:"column",marginTop:1,children:[t.jsx(c,{dimColor:!0,children:"── "}),t.jsx(c,{bold:!0,color:"white",children:"KEY DIFF"}),t.jsx(a,{flexDirection:"column",marginTop:1,paddingLeft:2,children:r.diff.length===0?t.jsx(c,{dimColor:!0,children:"No top-level keys moved (sub-key reorder only)."}):r.diff.map(o=>{const n=o.toIndex-o.fromIndex,d=n<0?`↑ ${String(Math.abs(n))}`:`↓ ${String(n)}`,g=n<0?"green":"yellow";return t.jsxs(a,{children:[t.jsx(a,{width:28,children:t.jsx(c,{wrap:"truncate",children:o.key})}),t.jsx(a,{width:10,children:t.jsxs(c,{dimColor:!0,children:[String(o.fromIndex)," → ",String(o.toIndex)]})}),t.jsx(c,{color:g,children:d})]},o.key)})}),e&&r.status==="would-rewrite"&&t.jsx(a,{marginTop:1,paddingLeft:2,children:t.jsx(c,{dimColor:!0,children:"--check mode: no write performed."})})]})]})]}):t.jsx(a,{alignItems:"center",borderColor:"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,justifyContent:"center",children:t.jsx(c,{dimColor:!0,children:"No entry selected"})})},ge={error:"red",rewritten:"yellow",unchanged:"green","would-rewrite":"yellow"},pe={error:"ERROR",rewritten:"REWROTE",unchanged:"SORTED","would-rewrite":"REWRITE"},H={error:"errors",rewritten:"rewrites",unchanged:"sorted","would-rewrite":"rewrites"},xe={errors:"Errors",rewrites:"Rewrites",sorted:"Sorted"},me=[{count:e=>e.errors+e.rewrites+e.sorted,key:"all",label:"All",shortcut:"1"},{count:e=>e.rewrites,key:"rewritten",label:"Rewrites",shortcut:"2"},{count:e=>e.errors,key:"errors",label:"Errors",shortcut:"3"},{count:e=>e.sorted,key:"unchanged",label:"Sorted",shortcut:"4"}],X=e=>{const r={errors:0,rewrites:0,sorted:0};for(const s of e)r[H[s.status]]++;return r},we=({entry:e,isSelected:r})=>{const s=ge[e.status],l=pe[e.status];return t.jsxs(a,{flexShrink:0,height:1,children:[t.jsx(c,{children:r?">":" "}),t.jsx(c,{children:" "}),t.jsx(c,{bold:!0,color:s,children:`[${l}]`.padEnd(10)}),t.jsx(c,{children:" "}),t.jsx(a,{flexGrow:1,children:t.jsx(c,{bold:r,inverse:r,wrap:"truncate",children:e.relativePath})}),e.status!=="error"&&e.diff.length>0&&t.jsx(c,{dimColor:!0,children:` ${String(e.diff.length)} key${e.diff.length===1?"":"s"}`})]})},je=({color:e,count:r,label:s})=>t.jsx(a,{flexShrink:0,height:1,children:t.jsx(c,{bold:!0,color:e,children:`${s} (${String(r)})`})}),ye=({counts:e,entries:r,filterType:s,focused:l,selectedIndex:i,totalEntries:o,viewportHeight:n})=>{const d=l?"white":"gray",g=X(r),m=(g.errors>0?1:0)+(g.rewrites>0?1:0)+(g.sorted>0?1:0),y=s==="all"&&m>1,h=[];let w;for(const[u,x]of r.entries()){const b=H[x.status];y&&b!==w&&(w!==void 0&&h.push({kind:"spacer"}),h.push({color:b==="errors"?"red":b==="rewrites"?"yellow":"green",count:g[b],kind:"header",label:xe[b]}),w=b),h.push({entry:x,entryIndex:u,kind:"entry"})}const p=h.findIndex(u=>u.kind==="entry"&&u.entryIndex===i),S=p!==-1,j=h.length,$=Math.max(0,j-n);let f=0;S&&n>0&&(f=Math.min($,Math.max(0,p-n+1)));const E=j>n&&n>0;return t.jsxs(a,{borderColor:d,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[t.jsxs(a,{flexShrink:0,gap:1,paddingX:1,children:[t.jsx(c,{bold:!0,inverse:!0,children:" VIS SORT "}),t.jsxs(c,{wrap:"truncate",children:[o," ","file",o===1?"":"s"]})]}),t.jsx(a,{flexShrink:0,gap:1,paddingX:1,paddingY:1,children:me.map(u=>{const x=s===u.key,b=u.count(e);return t.jsxs(a,{children:[t.jsx(c,{dimColor:!x,children:"["}),t.jsx(c,{bold:x,color:x?"cyan":"gray",children:u.shortcut}),t.jsx(c,{dimColor:!x,children:"]"}),t.jsxs(c,{color:x?"white":"gray",children:[" ",u.label]}),t.jsxs(c,{dimColor:!0,children:[" ","(",b,")"]})]},u.key)})}),t.jsxs(a,{flexDirection:"row",flexGrow:1,overflow:"hidden",children:[t.jsx(a,{flexDirection:"column",flexGrow:1,overflow:"hidden",paddingLeft:1,children:t.jsx(a,{flexDirection:"column",marginTop:-f,children:h.map((u,x)=>u.kind==="spacer"?t.jsx(a,{flexShrink:0,height:1},`s-${String(x)}`):u.kind==="header"?t.jsx(je,{color:u.color,count:u.count,label:u.label},`h-${u.label}`):t.jsx(we,{entry:u.entry,isSelected:u.entryIndex===i},u.entry.filePath))})}),E&&t.jsx(a,{flexShrink:0,marginLeft:1,marginRight:1,children:t.jsx(ie,{contentHeight:j,placement:"inset",scrollOffset:f,style:"block",viewportHeight:n})})]})]})},be=100,D=10,ke=6,Se=1,F={1:"all",2:"rewritten",3:"errors",4:"unchanged"},$e=({checkMode:e,store:r})=>{const{exit:s}=le(),{columns:l,rows:i}=ce(),o=v.useSyncExternalStore(r.subscribe,r.getSnapshot),n=v.useRef(null),d=r.getFilteredEntries(),g=d[o.selectedIndex]??null,m=X(o.entries),y=l>=be,h=Math.max(0,i-Se),w=y?h:Math.floor(h/2),p=Math.max(0,w-ke),S=v.useCallback(()=>{s()},[s]),j=v.useRef(0),$=v.useRef(void 0),f=v.useRef(!1),E=v.useCallback((u,x)=>{j.current+=x,$.current=u,!f.current&&(f.current=!0,queueMicrotask(()=>{f.current=!1;const b=j.current,T=$.current;j.current=0,$.current=void 0,!(b===0||T===void 0)&&(T==="list"?r.selectStep(Math.sign(b)):n.current?.scrollBy(Math.sign(b)))}))},[r]);return ae((u,x)=>{if(u==="q"||x.escape){S();return}if(F[u]){r.setFilter(F[u]);return}if(x.tab){r.setFocusedPanel(o.focusedPanel==="list"?"detail":"list");return}o.focusedPanel==="list"?x.upArrow||u==="k"?E("list",-1):(x.downArrow||u==="j")&&E("list",1):o.focusedPanel==="detail"&&(x.upArrow||u==="k"?E("detail",-1):(x.downArrow||u==="j")&&E("detail",1))}),i<D?t.jsx(a,{alignItems:"center",justifyContent:"center",children:t.jsxs(c,{color:"yellow",children:["Terminal too small. Resize to at least",D," ","rows."]})}):t.jsxs(a,{flexDirection:"column",height:i,width:l,children:[t.jsxs(a,{flexDirection:y?"row":"column",flexGrow:1,children:[t.jsx(a,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:t.jsx(ye,{counts:m,entries:d,filterType:o.filterType,focused:o.focusedPanel==="list",selectedIndex:o.selectedIndex,totalEntries:o.entries.length,viewportHeight:p})}),t.jsx(a,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:t.jsx(he,{checkMode:e,entry:g,focused:o.focusedPanel==="detail",scrollRef:n})})]}),t.jsx(a,{flexShrink:0,paddingX:1,children:t.jsx(c,{dimColor:!0,children:"↑/↓ or j/k:navigate | tab:switch panel | 1-4:filter | q:quit"})})]})},B=["types","node-addons","node","import","require","default"],ve=/^git\+https:\/\/github\.com\/([^/]+)\/([^/.]+(?:\.git)?)$/,Ee=/^git\+ssh:\/\/git@github\.com\/([^/]+)\/([^/.]+(?:\.git)?)$/,C=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),I=e=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(s=>I(s));const r={};for(const[s,l]of Object.entries(e))r[s]=I(l);return r},Pe=e=>{if(!C(e))return{changed:!1,value:e};const r=Object.keys(e);return r.length===1&&r[0]==="url"&&typeof e.url=="string"?{changed:!0,value:e.url}:{changed:!1,value:e}},Oe=e=>e.endsWith(".git")?e.slice(0,-4):e,Ce=e=>{if(!C(e))return{changed:!1,value:e};if(typeof e.directory=="string"&&e.directory.length>0)return{changed:!1,value:e};const{type:r}=e;if(r!==void 0&&r!=="git")return{changed:!1,value:e};const{url:s}=e;if(typeof s!="string")return{changed:!1,value:e};const l=ve.exec(s)??Ee.exec(s);if(!l)return{changed:!1,value:e};const i=l[1],o=Oe(l[2]??"");if(!i||!o)return{changed:!1,value:e};const n=new Set(["type","url"]);for(const d of Object.keys(e))if(!n.has(d))return{changed:!1,value:e};return{changed:!0,value:`${i}/${o}`}},Re=e=>{const r=Object.keys(e),s=[],l=[];for(const n of B)Object.hasOwn(e,n)&&s.push(n);for(const n of r)B.includes(n)||l.push(n);const i=[...s,...l];if(i.length===r.length&&i.every((n,d)=>n===r[d]))return{changed:!1,value:e};const o={};for(const n of i)o[n]=e[n];return{changed:!0,value:o}},W=e=>{if(!C(e))return{changed:!1,value:e};let r=!1;const s={};for(const[i,o]of Object.entries(e)){const n=W(o);s[i]=n.value,n.changed&&(r=!0)}const l=Re(s);return{changed:r||l.changed,value:l.value}},Ie=(e,r)=>{const s=I(e);let l=!1;if(r.formatBugs!==!1&&Object.hasOwn(s,"bugs")){const i=Pe(s.bugs);i.changed&&(s.bugs=i.value,l=!0)}if(r.formatRepository!==!1&&Object.hasOwn(s,"repository")){const i=Ce(s.repository);i.changed&&(s.repository=i.value,l=!0)}if(r.sortExports!==!1&&Object.hasOwn(s,"exports")&&C(s.exports)){const i=W(s.exports);i.changed&&(s.exports=i.value,l=!0)}return{changed:l,pkg:s}},Te=/at position (\d+)/,Me=/\(?line (\d+) column (\d+)\)?/,Ne=e=>{const r=new Set,s=[],l=o=>{const n=Y(o);!r.has(n)&&M(n)&&(r.add(n),s.push(n))};l(P(e,"package.json"));const i=te(e);if(i){const o=N(e,i);for(const n of o)l(P(e,n,"package.json"))}else{const o=P(e,"package.json");if(M(o)){const n=JSON.parse(L(o)),d=Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages;if(d){const g=N(e,d);for(const m of g)l(P(e,m,"package.json"))}}}return s},Ae=e=>/\n([ \t]+)/.exec(e)?.[1]??" ",De=e=>{if(!(e===void 0||e===""))return e==="tab"||e===String.raw`\t`?" ":/^\d+$/.test(e)?" ".repeat(Number.parseInt(e,10)):e},R=e=>e===void 0?[]:(Array.isArray(e)?e:[e]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0),Fe=e=>e.includes(`\r
2
+ `)?"crlf":"lf",Be=new Set(["auto","crlf","lf"]),Ge=e=>{if(e===void 0||e==="")return"auto";if(Be.has(e))return e;throw new Error(`--line-ending must be one of: auto, lf, crlf (got "${e}")`)},_e=(e,r,s)=>r.length===0?e:e.filter(l=>{const i=J(s,l),o=V(l);return!r.some(n=>{const d=n.includes("/")?i:o;return oe(n,d)})}),Je=(e,r)=>{if(r.length===0)return e;const s={},l=new Set;for(const i of r)Object.hasOwn(e,i)&&(s[i]=e[i],l.add(i));for(const i of Object.keys(e))l.has(i)||(s[i]=e[i]);return s},Le=(e,r,s)=>{if(s.length===0)return e;const l={...e};for(const i of s)Object.hasOwn(r,i)&&(l[i]=r[i]);return l},qe=(e,r)=>{let s=1,l=1;const i=Math.min(r,e.length);for(let o=0;o<i;o++)e.codePointAt(o)===10?(s++,l=1):l++;return{column:l,line:s}},G=(e,r,s=2)=>{const l=e.split(`
3
+ `);if(r<1||r>l.length)return[];const i=Math.max(0,r-1-s),o=Math.min(l.length,r+s),n=[];for(let d=i;d<o;d++)n.push({content:l[d]??"",isErrorLine:d+1===r,lineNumber:d+1});return n},_=(e,r)=>{if(!(e instanceof Error))return;const s=Te.exec(e.message);if(s){const{column:i,line:o}=qe(r,Number.parseInt(s[1]??"0",10));return{column:i,line:o,snippet:G(r,o)}}const l=Me.exec(e.message);if(l){const i=Number.parseInt(l[1]??"1",10);return{column:Number.parseInt(l[2]??"1",10),line:i,snippet:G(r,i)}}},He=(e,r)=>{const s=Object.keys(JSON.parse(e)),l=Object.keys(JSON.parse(r)),i=new Map(s.map((n,d)=>[n,d])),o=[];for(const[n,d]of l.entries()){const g=i.get(d);g!==void 0&&g!==n&&o.push({fromIndex:g,key:d,toIndex:n})}return o},Xe=(e,r,s)=>{const l=r.indent??s.indent??Ae(e),i=r.lineEnding==="auto"?s.lineEnding??Fe(e):r.lineEnding,o=q(e,{pretty:!1,sortScripts:r.sortScripts});let n=JSON.parse(o);if(r.unsorted.length>0){const y=JSON.parse(e);n=Le(n,y,r.unsorted)}n=Je(n,r.sortOrder);const d={formatBugs:r.formatBugs,formatRepository:r.formatRepository,sortExports:r.sortExports},g=Ie(n,d);let m=JSON.stringify(g.pkg,null,l);return r.finalNewline&&(m+=`
4
+ `),i==="crlf"&&(m=m.replaceAll(`
5
+ `,`\r
6
+ `)),m},We=(e,r)=>{const s=Ne(e),l=U(e),i=Z({cwd:e,extraPatterns:ee(l)}),o=s.filter(d=>!i.ignores(d)),n=_e(o,r,e);return{afterGitignore:o,allFiles:s,files:n}},ze=async(e,{checkMode:r,cwd:s,fs:l,normalized:i})=>{const o=J(s,e)||e;let n;try{n=L(e)}catch(h){return{diff:[],error:{message:O(h),step:"read"},filePath:e,relativePath:o,status:"error"}}let d;try{d=q(n,{pretty:!1,sortScripts:i.sortScripts})}catch(h){const w={message:O(h),step:"native-sort"},p=_(h,n);return p&&(w.context=p),{diff:[],error:w,filePath:e,relativePath:o,status:"error"}}const g=i.editorconfig?re(e):{};let m;try{m=Xe(n,i,g)}catch(h){const w={message:O(h),step:"json-parse"},p=_(h,n);return p&&(w.context=p),{diff:[],error:w,filePath:e,relativePath:o,status:"error"}}if(n===m)return{diff:[],filePath:e,relativePath:o,status:"unchanged"};let y;try{y=He(n,d)}catch{y=[]}if(r)return{diff:y,filePath:e,relativePath:o,status:"would-rewrite"};try{await l.writeFile(e,m,"utf8")}catch(h){return{diff:y,error:{message:O(h),step:"write"},filePath:e,relativePath:o,status:"error"}}return{diff:y,filePath:e,relativePath:o,status:"rewritten"}},Ve=e=>{if(e.error&&(k.error(`${e.filePath}: ${e.error.message}`),k.info(` step: ${e.error.step}`),e.error.context)){k.info(` at line ${String(e.error.context.line)}, column ${String(e.error.context.column)}`);for(const r of e.error.context.snippet){const s=r.isErrorLine?">":" ";k.info(` ${s} ${String(r.lineNumber).padStart(4)} | ${r.content}`)}}},ir=async({fs:e,options:r,visConfig:s,workspaceRoot:l})=>{const i=l??process.cwd(),o=s?.sortPackageJson,n=r.check||!1,d={editorconfig:r.editorconfig===!1?!1:o?.editorconfig??!0,finalNewline:r.finalNewline??o?.finalNewline??!0,formatBugs:r.formatBugs===!1?!1:o?.formatBugs??!0,formatRepository:r.formatRepository===!1?!1:o?.formatRepository??!0,ignore:[...R(r.ignore),...o?.ignore??[]],indent:De(r.indent??o?.indent),lineEnding:Ge(r.lineEnding??o?.lineEnding),sortExports:r.sortExports===!1?!1:o?.sortExports??!0,sortOrder:[...R(r.sortOrder),...o?.sortOrder??[]],sortScripts:r.sortScripts||o?.sortScripts||!1,unsorted:[...R(r.unsorted),...o?.unsorted??[]]},g=We(i,d.ignore),{afterGitignore:m,allFiles:y,files:h}=g;if(h.length===0){y.length===0?k.info("No package.json files found."):m.length===0?k.info("All package.json files were excluded by .gitignore or workspace exclusions."):k.info("All package.json files were excluded by --ignore.");return}const w=[];for(const f of h)w.push(await ze(f,{checkMode:n,cwd:i,fs:e,normalized:d}));let p=0,S=0,j=0;for(const f of w)f.status==="error"?j++:f.status==="rewritten"||f.status==="would-rewrite"?p++:S++;const $=p>0||j>0;if(process.stdout.isTTY&&!se&&$){const f=new fe(w);await K(Q.createElement($e,{checkMode:n,store:f}),{alternateScreen:!0,exitOnCtrlC:!1,interactive:!0,patchConsole:!0}).waitUntilExit()}else for(const f of w)switch(f.status){case"error":{Ve(f);break}case"rewritten":{k.success(`Sorted ${f.filePath}`);break}case"would-rewrite":{k.warn(`${f.filePath} is not sorted`);break}}if(n)p>0?(k.info(`${String(p)} file${p===1?"":"s"} not sorted, ${String(S)} already sorted`),process.exitCode=1):j===0&&k.info(`All ${String(S)} package.json file${S===1?" is":"s are"} sorted`);else{const f=[];p>0&&f.push(`sorted ${String(p)} file${p===1?"":"s"}`),S>0&&f.push(`${String(S)} already sorted`),j>0&&f.push(`${String(j)} error${j===1?"":"s"}`),f.length>0&&k.info(f.join(", "))}j>0&&(process.exitCode=1)};export{G as buildSnippet,He as computeKeyDiff,qe as computeLineColumn,ir as default,We as discoverPackageJsonFiles,_ as extractParseErrorContext,ze as processFile};