"use strict";const f=require("node:process"),c=require("picocolors"),helpers=require("yargs/helpers"),p$1=require("yargs"),o=require("@clack/prompts"),results=require("@vyke/results"),p=require("node:fs"),a$1=require("node:path"),node_child_process=require("node:child_process"),zod=require("zod"),sola=require("@vyke/sola");function _interopDefaultCompat(e){return e&&typeof e=="object"&&"default"in e?e.default:e}function _interopNamespaceCompat(e){if(e&&typeof e=="object"&&"default"in e)return e;const n=Object.create(null);if(e)for(const r in e)n[r]=e[r];return n.default=e,n}const f__default=_interopDefaultCompat(f),c__default=_interopDefaultCompat(c),p__default$1=_interopDefaultCompat(p$1),o__namespace=_interopNamespaceCompat(o),p__default=_interopDefaultCompat(p),a__default=_interopDefaultCompat(a$1),name="@vyke/jsr-sync",type="module",version="0.0.2",description="Small cli tool to keep jsr config on sync with your package.json",author="Jose Albizures (https://albizures.com/)",license="MIT",keywords=["helpers","typescript","jsr","package"],exports$1={".":{import:"./dist/index.mjs",require:"./dist/index.cjs"}},main="./dist/index.cjs",types="./dist/index.d.ts",bin={"jsr-sync":"./bin/cli.js"},files=["dist"],scripts={build:"run-s build:*","build:dist":"unbuild",test:"run-s test:unit test:types test:lint","test:use":"knip","test:lint":"eslint .","test:unit":"vitest run","test:unit:dev":"pnpm test:stub && vitest","test:types":"tsc --noEmit","test:stub":"unbuild --stub","release:bump":"standard-version -t v","release:jsr-sync":"node ./bin/cli.js --section=exports","release:publish":"pnpm publish --access public","release:push-tags":"git push --follow-tags origin main",release:"run-s build test release:jsr-sync release:bump release:publish release:push-tags"},dependencies={"@clack/prompts":"^0.7.0","@vyke/results":"npm:@jsr/vyke__results@^0.3.4","@vyke/sola":"^0.0.6",picocolors:"^1.0.1","type-fest":"^4.18.2",yargs:"^17.7.2",zod:"^3.23.8"},devDependencies={"@antfu/eslint-config":"^2.18.1","@types/fs-extra":"^11.0.4","@types/yargs":"^17.0.32","@vyke/tsdocs":"^0.0.8",eslint:"^9.3.0",execa:"^9.1.0","fs-extra":"^11.2.0",knip:"^5.16.0","npm-run-all":"^4.1.5","standard-version":"^9.5.0",typescript:"^5.4.5",unbuild:"^2.0.0",vitest:"^1.6.0"},t={name,type,version,description,author,license,keywords,exports:exports$1,main,types,bin,files,scripts,dependencies,devDependencies,"standard-version":{skip:{changelog:!0}}};function getIsGitInitialized(){return results.capture(()=>p__default.existsSync(a__default.join(f__default.cwd(),".git")))}function getIsGitClean(){return results.capture(()=>node_child_process.execSync("git status").toString().includes("working tree clean"))}function getCurrentBranch(){let e=results.capture(()=>node_child_process.execSync("git branch --show-current").toString().trim());return results.IsOk(e)&&e.value.length!==0||(e=results.capture(()=>node_child_process.execSync("git rev-parse --abbrev-ref HEAD").toString().trim()),results.IsOk(e)&&e.value!=="HEAD")?e:results.Err("Invalid branch")}function gitCommit(e){return results.capture(()=>{node_child_process.execSync("git add .").toString().trim(),node_child_process.execSync(`git commit -m '${e}'`).toString().trim()})}const y$1=zod.z.object({name:zod.z.string(),version:zod.z.string(),exports:zod.z.record(zod.z.string(),zod.z.union([zod.z.string(),zod.z.object({import:zod.z.string().optional(),require:zod.z.string().optional()})])).optional()}),x$1=zod.z.object({name:zod.z.string().optional(),version:zod.z.string().optional(),exports:zod.z.union([zod.z.record(zod.z.string(),zod.z.string()),zod.z.string()]).optional()}).passthrough();function j$1(){const e=a__default.resolve(f__default.cwd(),"package.json");try{const n=p__default.readFileSync(e,"utf8");return results.Ok(y$1.parse(JSON.parse(n)))}catch(n){return console.error(n),results.Err(n)}}function v(){const e=a__default.resolve(f__default.cwd(),"jsr.json");try{const n=p__default.readFileSync(e,"utf8");return results.Ok(x$1.parse(JSON.parse(n)))}catch{return results.Ok({})}}function S(e){if(!e.exports)return results.Empty();const n={};Object.entries(e.exports);for(const[r,s]of Object.entries(e.exports))typeof s=="string"?n[r]=u(s):s.import?n[r]=u(s.import):s.require&&(n[r]=u(s.require));return results.Ok(n)}function u(e){const{name:n,dir:r}=a__default.parse(e);return`${r.replace("dist","src")}/${n}.ts`}function formatJrsConfig(e){return JSON.stringify(e,null," ")}function writeJsrConfigFile(e){return results.capture(()=>p__default.writeFileSync(a__default.resolve(f__default.cwd(),"jsr.json"),`${e} `))}function getSyncedJsrConfig(e){const n=j$1();if(!results.IsOk(n))return results.Err("Unable to read package.json");const r=v();if(!results.IsOk(r))return results.Err("Unable to read jsr.json");const{value:s}=n,l=S(s);if(!results.IsOk(l))return results.Err("Invalid exports in package.json");const i={...r.value};return e.has("version")&&(i.version=s.version),e.has("name")&&(i.name=i.name||s.name),e.has("exports")&&(i.exports=l.value),results.Ok(i)}const rootSola=new sola.Sola({tag:"@vyke/jsr-sync"}),k=rootSola.withTag("run"),E=new Set(["version","exports","name"]);async function run(e={sections:E}){const{sections:n,name:r,dryRun:s=!1}=e,l=getSyncedJsrConfig(n);if(!results.IsOk(l))return o__namespace.log.error(c__default.red(`\u2718 ${results.IsErr(l)?l.value:"Failed to get sync update"}`)),results.intoErr(l,"Failed to get sync update");const{value:i}=l,g=await U(i.name,r);if(!results.IsOk(g))return results.intoErr(g,"Failed to sync name");if(i.name=g.value,s)return o__namespace.log.info(c__default.green("Result of dry run:")),o__namespace.log.info(formatJrsConfig(i)),o__namespace.log.info(c__default.yellow("\u26A0 Dry run enabled, no changes will be made")),results.Ok("Dry run completed");const m=j(i);if(!results.IsOk(m))return results.intoErr(m,"Failed to sync files");const b=await x(e);return results.IsOk(b)?results.Ok("jsr.json file in sync :)"):results.intoErr(b,"Failed to commit changes")}function O(e){const{dryRun:n=!1,gitEnable:r=!n}=e;if(!r)return{gitEnable:r,isGitClean:!0};let s=!1;const l=getIsGitInitialized();if(!results.IsOk(l)||!l.value)return o__namespace.log.warn(c__default.yellow("\u26A0 Unable to check for uncommitted changes, disabling git features")),{gitEnable:!1,isGitClean:!1};const i=getIsGitClean();return s=results.IsOk(i),{gitEnable:r,isGitClean:s}}async function U(e,n){if(R(n))return results.Ok(n);if(R(e))return results.Ok(e);const r=await results.to(o__namespace.text({placeholder:`@example/${e}`,message:"Enter the name of the package"}));return results.IsOk(r)?results.Ok(String(r.value)):(k.log(r),results.Err("Unable to get a valid name"))}function R(e){return!!(e&&e.startsWith("@"))}function j(e){const n=writeJsrConfigFile(formatJrsConfig(e));return results.IsOk(n)?results.Ok("files synced"):(o__namespace.log.error(c__default.red("\u2718 Unable to write to jsr.json")),results.intoErr(n,"Unknown error"))}async function x(e){const{gitEnable:n,isGitClean:r}=O(e);if(!n)return results.Ok("Git features disabled");const s=r?e.force??!1:await I(e);if(!r&&!s)return results.Ok("Uncommitted changes");const l=getCurrentBranch();if(!s&&results.IsErr(l))return o__namespace.log.error(c__default.red("\u2718 Git commit aborted due to invalid branch detected")),l;const i=getIsGitClean();if(results.IsOk(i)&&i.value)return results.Ok("No changes to commit");const g=gitCommit("chore: sync jsr config");return results.IsOk(g)?results.Ok("Git synced"):(o__namespace.log.error(c__default.red("\u2718 Unable to commit changes")),results.intoErr(g,"Unknown error"))}async function I(e){const{force:n}=e;if(n===void 0){const r=await results.to(o__namespace.confirm({initialValue:!1,message:"There are uncommitted changes in the current repository, are you sure to continue?"}));return results.IsOk(r)&&typeof r.value=="boolean"?r.value:!1}return n}function y(){console.log(` `),o__namespace.intro(`${c__default.green("@vyke/jsr-sync ")}${c__default.dim(`v${t.version}`)}`)}const a=p__default$1(helpers.hideBin(f__default.argv)).scriptName("@vyke/jsr-sync").usage("").option("section",{alias:"s",description:"The sections to sync",type:"array",default:["version","exports","name"]}).option("name",{alias:"n",description:"Use a different name for the project",type:"string"}).option("dry-run",{alias:"d",description:"Run a dry run of the sync",type:"boolean"}).option("git-enable",{description:"Commit changes",type:"boolean"}).showHelpOnFail(!1).alias("h","help").version("version",t.version).alias("v","version");a.parse();async function d(){y();const e=await a.parse(),n=await run({...e,sections:new Set(e.section.map(r=>String(r)).filter(r=>{switch(r){case"version":case"exports":case"name":return!0;default:return!1}}))});results.IsOk(n)?o__namespace.log.success(c__default.green("\u2714 Synced jsr config")):(o__namespace.log.error(c__default.inverse(c__default.red(" Failed to sync jsr config "))),o__namespace.log.error(c__default.red(`\u2718 ${results.intoErr(n,"Failed to sync jsr config").value}`)),f__default.exit(1))}d();