jiek 0.4.1 → 0.4.3

Sign up to get free protection for your applications and to get access to all the features.
package/dist/cli.cjs CHANGED
@@ -1,2 +1,688 @@
1
- "use strict";var e=require("node:fs"),t=require("node:path"),r=require("@pnpm/filter-workspace-packages"),n=require("commander"),o=require("js-yaml"),a=require("@jiek/utils/getWorkspaceDir"),i=require("node:child_process"),s=require("@jiek/pkger"),l=require("detect-indent"),c=require("inquirer"),p=require("jsonc-parser"),u=require("micromatch"),f=require("@jiek/utils/bumper");function d(e){return e&&e.__esModule?e:{default:e}}function m(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var g=d(e),y=d(t),w=m(i),k=d(l),h=d(c);let b,j;function v(){if(b)return b;const e=n.program.getOptionValue("root");return b=e?y.default.isAbsolute(e)?e:y.default.resolve(process.cwd(),e):void 0,b}let S=!1;function $(){if(j)return{wd:j,notWorkspace:S};const e=v();if(void 0!==e){const t=a.isWorkspaceDir(e,E);return S=!t,j=e,{wd:j,notWorkspace:S}}try{j=a.getWorkspaceDir(E)}catch(t){if(!("message"in t)||"workspace root not found"!==t.message)throw t;j=e,S=!0}return{wd:j,notWorkspace:S}}let E="";try{require.resolve("@pnpm/filter-workspace-packages"),E="pnpm"}catch{}async function O(){let e=n.program.getOptionValue("filter");const t=v(),{wd:a,notWorkspace:i}=$();if(!i&&"pnpm"===E){const n=y.default.resolve(a,"pnpm-workspace.yaml"),i=g.default.readFileSync(n,"utf-8"),s=o.load(i);if(t===a&&!e)throw new Error("root path is workspace root, please provide a filter");if(t!==a&&!e){if(!g.default.existsSync(y.default.resolve(t,"package.json")))throw new Error("root path is not workspace root, please provide a filter");const r=JSON.parse(g.default.readFileSync(y.default.resolve(t,"package.json"),"utf-8"));if(!r.name)throw new Error("root path is not workspace root, please provide a filter");e=r.name}const{selectedProjectsGraph:l}=await r.filterPackagesFromDir(a,[{filter:e??"",followProdDepsOnly:!0}],{prefix:t,workspaceDir:a,patterns:s.packages});return{wd:a,root:t,value:Object.entries(l).reduce(((e,[t,r])=>(e[t]=r.package.manifest,e)),{})}}return{wd:a,root:t,value:{[a]:JSON.parse(g.default.readFileSync(y.default.resolve(a,"package.json"),"utf-8"))}}}""!==E&&n.program.option("-f, --filter <filter>","filter packages");var q=require("../package.json");let x,F;function _(){x()}function A(){new Promise((e=>x=e))}function D(e,t,r={}){const{excludeDistInExports:n=!1}=r,{jiek:{cwd:o,...a}={}}=e,{outdir:i="dist"}=a;let{exports:l}=e,c=!1;"string"==typeof l&&(c=!0,l={".":l}),void 0===l&&(l={".":"./src/index.ts"}),"object"==typeof l&&(c=!!(Array.isArray(l)&&l.length>0)||!!l["."]);let p=Array.isArray(l)?l:Object.entries(l).reduce(((e,[t,r])=>{if("string"==typeof r)return"."===t?[r,...e]:e.concat(r);if(Array.isArray(r))return e.concat(r);throw new TypeError(`Unexpected value type for key "${t}" in exports, expected string, got ${typeof r}`)}),[]);if(n&&(p=p.filter((e=>!e.startsWith(`./${i}`)&&!e.startsWith(i)))),0===p.length)throw new Error("No inputs found");const u=p.map((e=>y.default.isAbsolute(e)?e:y.default.resolve(t,e)));let f=y.default.dirname(u[0]);u.length>1&&(f=function(e,t=process.cwd()){const r=e.map((e=>y.default.isAbsolute(e)?e:y.default.resolve(t,e))),[n=""]=r,o=n.split("/");let a="";for(let e=0;e<o.length;e++){const t=o[e];if(!r.every((e=>e.startsWith(a+t))))break;a+=t+"/"}return a}(u,t));const d=u.map((e=>y.default.relative(f,e)));return{...e,...s.pkger({cwd:t,noIndex:!c,source:y.default.relative(t,f),inputs:d,...a})}}function J(e){try{return require.resolve(e),!0}catch(e){return!1}}n.program.version(q.version).description(q.description).option("--root <root>","root path").option("-c, --config-path <configPath>","config path");const N=[process.env.JIEK_TS_REGISTER,"esbuild-register","@swc-node/register","ts-node/register"].filter(Boolean);for(const e of N)if(J(e)){F=e;break}const W=e=>`\nconst pkg = ${JSON.stringify(e,null,2)}\nconst { jiek = {} } = pkg\nconst templateArg = jiek.templateArgFilePath\n ? require.resolve(jiek.templateArgFilePath)\n : {\n styled: jiek.styled\n }\nmodule.exports = require('jiek/rollup').template(templateArg, pkg)\n`.trimStart();n.program.command("build").action((async()=>{A();const{wd:e,value:t={}}=await O()??{};if(0===Object.keys(t).length)throw new Error("no package found");const r=(...t)=>y.default.resolve(e,"node_modules/.jiek",...t);g.default.existsSync(r())||g.default.mkdirSync(r());const n=require.resolve("rollup").replace(/dist\/rollup.js$/,"dist/bin/rollup");let o=0;for(const[e,a]of Object.entries(t)){const t=D(a,e,{excludeDistInExports:!0}),i=a.name?.replace(/^@/g,"").replace(/\//g,"+"),s=r(`${i??"anonymous-"+o++}.rollup.config.js`);g.default.writeFileSync(s,W(t));let l="";F&&(l=`node -r ${F} `),w.execSync(`${l}${n} --silent -c ${s}`,{cwd:e,stdio:"inherit"})}_()}));let P="jiek.config";function I(){const{wd:e,notWorkspace:t}=$();if(t)throw new Error("not in workspace");let r=n.program.getOptionValue("configPath");if(r){if(!g.default.existsSync(r))throw new Error(`config file not found: ${r}`);y.default.isAbsolute(r)||(r=y.default.resolve(e,r))}else r=function(e){const t=!!F;function r(t){const r=[y.default.resolve(e,`${P}.${t}`),y.default.resolve(e,`.${P}.${t}`)];for(const e of r)if(g.default.existsSync(e)&&g.default.lstatSync(e).isFile())return e}return P=r("js")??P,P=r("json")??P,P=r("yaml")??P,t&&(P=r("ts")??P),y.default.resolve(e,P)}(e);const a=y.default.extname(r);let i;switch(a){case".js":i=require(r);break;case".json":return require(r);case".yaml":return o.load(g.default.readFileSync(r,"utf-8"));case".ts":if(F){require(F),i=require(r);break}throw new Error("ts config file is not supported without ts register, please install esbuild-register or set JIEK_TS_REGISTER env for custom ts register");case".config":i={};break;default:throw new Error(`unsupported config file type: ${a}`)}if(!i)throw new Error("config file is empty");return i.default??i}const M='{\n "name": "",\n "version": "0.0.1",\n "description": "",\n "license": "",\n "author": "",\n "files": ["dist"],\n "exports": {\n ".": "./src/index.ts"\n },\n "scripts": {\n },\n "homepage": "",\n "repository": "",\n "bugs": ""\n}'.trimStart(),R="# $name\n\n## Installation\n\n```bash\nnpm install $name\n# or\npnpm install $name\n# or\nyarn add $name\n```\n\n## Usage\n\n\n## License\n\n$license\n".trimStart();const T=new Map;function z(e,t){if(T.has(e))return T.get(e)[t];const r=y.default.resolve(e,"package.json"),n=JSON.parse(g.default.readFileSync(r,"utf-8"));return T.set(e,n),n[t]}n.program.command("init [name]").option("-t, --template <template>","the package.json template file path or file content").action((async()=>{const[,e]=n.program.args,t=process.cwd(),{init:r={}}=I()??{},{wd:o}=$(),a=y.default.basename(o),{named:i,template:s,bug:l={},readme:c=R,readmeTemplate:f}=r,d={template:"bug_report.yml",labels:["bug"],...l};let m=c;if(f){const e=y.default.resolve(o,f);m=g.default.readFileSync(e,"utf-8")}const w=function(e,t){let r=t??M,n=!1;try{t&&JSON.parse(t)}catch(e){n=!0}if(n){const n=y.default.resolve(e,t);r=g.default.readFileSync(n,"utf-8")}return r}(o,s),{indent:b=" "}=k.default(w),j={tabSize:b.length,insertSpaces:!0},v=["license","author"];let S=w;for(const e of v)S=p.applyEdits(S,p.modify(S,[e],z(o,e),{formattingOptions:j}));let[E,O]=await async function(e,t,{wd:r,cwd:n,workspaceName:o}){const a=n.replace(`${r}/`,"");let i=y.default.basename(n);if("function"==typeof e)return e(t,{full:r,relative:n});let s,l,c=!1;if("object"==typeof e)if(n===r){const{rule:t}=await h.default.prompt({type:"list",name:"rule",message:"choose a rule",default:"default",choices:["default"].concat(Object.keys(e))});"default"!==t&&(s=t,l=e[t])}else for(const[t,r]of Object.entries(e)){if(u.isMatch(a,t)){s=t,l=r;break}if(u.isMatch(`${a}/jiek_ignore_dont_use_same_file_name`,t)){c=!0,s=t,l=r;break}}if(l||(s="packages/*",l=`@${o}/$basename`),!l)throw new Error("no matched rule");if(!t&&c&&(i=await h.default.prompt({type:"input",name:"name",message:`the matched rule is \`${String(l)}\`, please input the basename\n`}).then((({name:e})=>e))),"function"==typeof l)return l(t,{full:r,relative:n,basename:i});if("string"==typeof l){const e=t??i;return[l.replace(/\$basename/g,e),s?.replace(/\/\*$/g,`/${e}`)]}throw new Error("no matched rule")}(i,e,{wd:o,cwd:t,workspaceName:a});if(!O){const{dir:t}=await h.default.prompt({type:"input",name:"dir",message:"package directory",default:e});O=t}if(!E){const{name:t}=await h.default.prompt({type:"input",name:"name",message:"package name",default:e});E=t}S=p.applyEdits(S,p.modify(S,["name"],E,{formattingOptions:j}));let q=z(o,"repository");"string"==typeof q&&(q={type:"git",url:q,directory:O}),S=p.applyEdits(S,p.modify(S,["repository"],q,{formattingOptions:j}));const x=`${q?.url}/blob/master/${O}/README.md`;S=p.applyEdits(S,p.modify(S,["homepage"],x,{formattingOptions:j}));let F=d.labels;"function"==typeof F&&(F=F({name:E,dir:O})),F.push(`scope:${E}`);const _=`${q?.url}/issues/new?template=${d.template}&labels=${F.join(",")}`;function A(e){if(!O)throw new Error("pkgDir is not defined");return y.default.resolve(O,e)}S=p.applyEdits(S,p.modify(S,["bugs"],_,{formattingOptions:j})),g.default.existsSync(O)||g.default.mkdirSync(O);const D=A("package.json");if(g.default.existsSync(D))throw new Error("package.json already exists");g.default.writeFileSync(D,S),console.log(S,"written to",D);const J=z(o,"license"),N=A("README.md");"function"==typeof m&&(m=m({dir:O,packageJson:JSON.parse(S)}));const W=m.replace(/\$name/g,E).replace(/\$license/g,J);g.default.writeFileSync(N,W)})),n.program.command("publish").aliases(["pub","p"]).option("-b, --bumper <bumper>","bump version","patch").option("-p, --preview","preview publish").action((async({preview:e,bumper:t,...r})=>{A();const{value:n={}}=await O()??{},o=Object.entries(n);if(0===o.length)throw new Error("no packages selected");const a=o.map((([e,t])=>[e,D(t,e)])),i=Object.entries(r).reduce(((e,[t,r])=>(r&&e.push(`--${t}`,r),e)),[]);for(const[r,n]of a){const o=g.default.readFileSync(y.default.join(r,"package.json"),"utf-8"),a=JSON.parse(o)??"0.0.0",s=f.bump(a.version,t),{indent:l=" "}=k.default(o),c={tabSize:l.length,insertSpaces:!0};let u=o;u=p.applyEdits(u,p.modify(u,["version"],s,{formattingOptions:c}));for(const[e,t]of Object.entries(n))JSON.stringify(t)!==JSON.stringify(a[e])&&(u=p.applyEdits(u,p.modify(u,["publishConfig",e],t,{formattingOptions:c})));try{if(g.default.renameSync(y.default.join(r,"package.json"),y.default.join(r,"package.json.bak")),g.default.writeFileSync(y.default.join(r,"package.json"),u),console.log(u),e){console.warn("preview mode");continue}w.execSync(["pnpm","publish","--access","public","--no-git-checks",...i].join(" "),{cwd:r,stdio:"inherit"});const t=p.applyEdits(o,p.modify(o,["version"],s,{}));g.default.writeFileSync(y.default.join(r,"package.json.bak"),t)}finally{g.default.unlinkSync(y.default.join(r,"package.json")),g.default.renameSync(y.default.join(r,"package.json.bak"),y.default.join(r,"package.json"))}}_()})),n.program.parse(process.argv);
1
+ 'use strict';
2
+
3
+ var fs = require('node:fs');
4
+ var path = require('node:path');
5
+ var filterWorkspacePackages = require('@pnpm/filter-workspace-packages');
6
+ var commander = require('commander');
7
+ var jsYaml = require('js-yaml');
8
+ var getWorkspaceDir = require('@jiek/utils/getWorkspaceDir');
9
+ var childProcess = require('node:child_process');
10
+ var pkger = require('@jiek/pkger');
11
+ var detectIndent = require('detect-indent');
12
+ var inquirer = require('inquirer');
13
+ var jsoncParser = require('jsonc-parser');
14
+ var micromatch = require('micromatch');
15
+ var bumper = require('@jiek/utils/bumper');
16
+
17
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
18
+
19
+ function _interopNamespace(e) {
20
+ if (e && e.__esModule) return e;
21
+ var n = Object.create(null);
22
+ if (e) {
23
+ Object.keys(e).forEach(function (k) {
24
+ if (k !== 'default') {
25
+ var d = Object.getOwnPropertyDescriptor(e, k);
26
+ Object.defineProperty(n, k, d.get ? d : {
27
+ enumerable: true,
28
+ get: function () { return e[k]; }
29
+ });
30
+ }
31
+ });
32
+ }
33
+ n.default = e;
34
+ return Object.freeze(n);
35
+ }
36
+
37
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
38
+ var path__default = /*#__PURE__*/_interopDefault(path);
39
+ var childProcess__namespace = /*#__PURE__*/_interopNamespace(childProcess);
40
+ var detectIndent__default = /*#__PURE__*/_interopDefault(detectIndent);
41
+ var inquirer__default = /*#__PURE__*/_interopDefault(inquirer);
42
+
43
+ let root;
44
+ function getRoot() {
45
+ if (root)
46
+ return root;
47
+ const rootOption = commander.program.getOptionValue("root");
48
+ root = rootOption ? path__default.default.isAbsolute(rootOption) ? rootOption : path__default.default.resolve(process.cwd(), rootOption) : void 0;
49
+ return root;
50
+ }
51
+
52
+ let wd;
53
+ let notWorkspace = false;
54
+ function getWD() {
55
+ if (wd)
56
+ return { wd, notWorkspace };
57
+ const root = getRoot();
58
+ if (root !== void 0) {
59
+ const isWorkspace = getWorkspaceDir.isWorkspaceDir(root, type);
60
+ notWorkspace = !isWorkspace;
61
+ wd = root;
62
+ return { wd, notWorkspace };
63
+ }
64
+ try {
65
+ wd = getWorkspaceDir.getWorkspaceDir(type);
66
+ } catch (e) {
67
+ if ("message" in e && e.message === "workspace root not found") {
68
+ wd = root;
69
+ notWorkspace = true;
70
+ } else {
71
+ throw e;
72
+ }
73
+ }
74
+ return { wd, notWorkspace };
75
+ }
76
+
77
+ let type = "";
78
+ try {
79
+ require.resolve("@pnpm/filter-workspace-packages");
80
+ type = "pnpm";
81
+ } catch {
82
+ }
83
+ if (type !== "") {
84
+ commander.program.option("-f, --filter <filter>", "filter packages");
85
+ }
86
+ async function getSelectedProjectsGraph() {
87
+ let filter = commander.program.getOptionValue("filter");
88
+ const root = getRoot();
89
+ const { wd, notWorkspace } = getWD();
90
+ if (!notWorkspace && type === "pnpm") {
91
+ const pnpmWorkspaceFilePath = path__default.default.resolve(wd, "pnpm-workspace.yaml");
92
+ const pnpmWorkspaceFileContent = fs__default.default.readFileSync(pnpmWorkspaceFilePath, "utf-8");
93
+ const pnpmWorkspace = jsYaml.load(pnpmWorkspaceFileContent);
94
+ if (root === wd && !filter) {
95
+ throw new Error("root path is workspace root, please provide a filter");
96
+ }
97
+ if (root !== wd && !filter) {
98
+ const packageJSONIsExist = fs__default.default.existsSync(path__default.default.resolve(root, "package.json"));
99
+ if (!packageJSONIsExist) {
100
+ throw new Error("root path is not workspace root, please provide a filter");
101
+ }
102
+ const packageJSON = JSON.parse(fs__default.default.readFileSync(path__default.default.resolve(root, "package.json"), "utf-8"));
103
+ if (!packageJSON.name) {
104
+ throw new Error("root path is not workspace root, please provide a filter");
105
+ }
106
+ filter = packageJSON.name;
107
+ }
108
+ const { selectedProjectsGraph } = await filterWorkspacePackages.filterPackagesFromDir(wd, [{
109
+ filter: filter ?? "",
110
+ followProdDepsOnly: true
111
+ }], {
112
+ prefix: root,
113
+ workspaceDir: wd,
114
+ patterns: pnpmWorkspace.packages
115
+ });
116
+ return {
117
+ wd,
118
+ root,
119
+ value: Object.entries(selectedProjectsGraph).reduce((acc, [key, value]) => {
120
+ acc[key] = value.package.manifest;
121
+ return acc;
122
+ }, {})
123
+ };
124
+ }
125
+ return {
126
+ wd,
127
+ root,
128
+ value: {
129
+ [wd]: JSON.parse(fs__default.default.readFileSync(path__default.default.resolve(wd, "package.json"), "utf-8"))
130
+ }
131
+ };
132
+ }
133
+
134
+ var pkg = require("../package.json");
135
+
136
+ commander.program.version(pkg.version).description(pkg.description).option("--root <root>", "root path").option("-c, --config-path <configPath>", "config path");
137
+
138
+ let resolve;
139
+ function actionDone() {
140
+ resolve();
141
+ }
142
+ function actionRestore() {
143
+ new Promise((r) => resolve = r);
144
+ }
145
+
146
+ function commondir(files, cwd = process.cwd()) {
147
+ const resolvedFiles = files.map((file) => {
148
+ if (path__default.default.isAbsolute(file))
149
+ return file;
150
+ return path__default.default.resolve(cwd, file);
151
+ });
152
+ const sep = "/";
153
+ const [first = ""] = resolvedFiles;
154
+ const parts = first.split(sep);
155
+ let common = "";
156
+ for (let i = 0; i < parts.length; i++) {
157
+ const segment = parts[i];
158
+ if (resolvedFiles.every((file) => file.startsWith(common + segment))) {
159
+ common += segment + sep;
160
+ } else {
161
+ break;
162
+ }
163
+ }
164
+ return common;
165
+ }
166
+
167
+ function mergePackageJson(manifest, cwd, options = {}) {
168
+ const {
169
+ excludeDistInExports = false
170
+ } = options;
171
+ const {
172
+ jiek: { cwd: _, ...jiek } = {}
173
+ } = manifest;
174
+ const { outdir = "dist" } = jiek;
175
+ let { exports } = manifest;
176
+ let includeIndex = false;
177
+ if (typeof exports === "string") {
178
+ includeIndex = true;
179
+ exports = { ".": exports };
180
+ }
181
+ if (exports === void 0) {
182
+ exports = { ".": "./src/index.ts" };
183
+ }
184
+ if (typeof exports === "object") {
185
+ if (Array.isArray(exports) && exports.length > 0) {
186
+ includeIndex = true;
187
+ } else {
188
+ includeIndex = !!exports["."];
189
+ }
190
+ }
191
+ let inputs = Array.isArray(exports) ? exports : Object.entries(exports).reduce((acc, [key, value]) => {
192
+ if (typeof value === "string")
193
+ return key === "." ? [value, ...acc] : acc.concat(value);
194
+ if (Array.isArray(value))
195
+ return acc.concat(value);
196
+ throw new TypeError(`Unexpected value type for key "${key}" in exports, expected string, got ${typeof value}`);
197
+ }, []);
198
+ if (excludeDistInExports) {
199
+ inputs = inputs.filter((input) => !input.startsWith(`./${outdir}`) && !input.startsWith(outdir));
200
+ }
201
+ if (inputs.length === 0)
202
+ throw new Error("No inputs found");
203
+ const absoluteInputs = inputs.map(
204
+ (input) => path__default.default.isAbsolute(input) ? input : path__default.default.resolve(cwd, input)
205
+ );
206
+ let cDir = path__default.default.dirname(absoluteInputs[0]);
207
+ if (absoluteInputs.length > 1) {
208
+ cDir = commondir(absoluteInputs, cwd);
209
+ }
210
+ const resolvedInputs = absoluteInputs.map((input) => {
211
+ return path__default.default.relative(cDir, input);
212
+ });
213
+ return {
214
+ ...manifest,
215
+ ...pkger.pkger({
216
+ cwd,
217
+ noIndex: !includeIndex,
218
+ source: path__default.default.relative(cwd, cDir),
219
+ inputs: resolvedInputs,
220
+ ...jiek
221
+ })
222
+ };
223
+ }
224
+
225
+ function packageIsExist(name) {
226
+ try {
227
+ require.resolve(name);
228
+ return true;
229
+ } catch (e) {
230
+ return false;
231
+ }
232
+ }
233
+ let tsRegisterName;
234
+ const registers = [
235
+ process.env.JIEK_TS_REGISTER,
236
+ "esbuild-register",
237
+ "@swc-node/register",
238
+ "ts-node/register"
239
+ ].filter(Boolean);
240
+ for (const register of registers) {
241
+ if (packageIsExist(register)) {
242
+ tsRegisterName = register;
243
+ break;
244
+ }
245
+ }
246
+
247
+ const FILE_TEMPLATE = (manifest) => `
248
+ const pkg = ${JSON.stringify(manifest, null, 2)}
249
+ const { jiek = {} } = pkg
250
+ const templateArg = jiek.templateArgFilePath
251
+ ? require.resolve(jiek.templateArgFilePath)
252
+ : {
253
+ styled: jiek.styled
254
+ }
255
+ module.exports = require('jiek/rollup').template(templateArg, pkg)
256
+ `.trimStart();
257
+ commander.program.command("build").option("-t, --target <type>", "target flow: esm|umd|dts, default esm,umd,dts").option("-s, --silent", "silent mode").action(async ({ target, silent }) => {
258
+ actionRestore();
259
+ const {
260
+ wd,
261
+ value = {}
262
+ } = await getSelectedProjectsGraph() ?? {};
263
+ if (Object.keys(value).length === 0) {
264
+ throw new Error("no package found");
265
+ }
266
+ const jiekTempDir = (...paths) => path__default.default.resolve(wd, "node_modules/.jiek", ...paths);
267
+ if (!fs__default.default.existsSync(jiekTempDir()))
268
+ fs__default.default.mkdirSync(jiekTempDir());
269
+ const rollupBinaryPath = require.resolve("rollup").replace(/dist\/rollup.js$/, "dist/bin/rollup");
270
+ let i = 0;
271
+ for (const [dir, manifest] of Object.entries(value)) {
272
+ const newManifest = mergePackageJson(manifest, dir, { excludeDistInExports: true });
273
+ const escapeManifestName = manifest.name?.replace(/^@/g, "").replace(/\//g, "+");
274
+ const configFile = jiekTempDir(
275
+ `${escapeManifestName ?? `anonymous-${i++}`}.rollup.config.js`
276
+ );
277
+ fs__default.default.writeFileSync(configFile, FILE_TEMPLATE(newManifest));
278
+ let prefix = "";
279
+ if (tsRegisterName) {
280
+ prefix = `node -r ${tsRegisterName} `;
281
+ }
282
+ childProcess__namespace.execSync(`${prefix}${rollupBinaryPath} --silent -c ${configFile}`, {
283
+ cwd: dir,
284
+ stdio: "inherit",
285
+ env: {
286
+ JIEK_TARGET: target ?? process.env.JIEK_TARGET ?? "esm,umd,dts",
287
+ JIEK_SILENT: `${silent}` ?? process.env.JIEK_SILENT,
288
+ JIEK_ROOT: wd
289
+ }
290
+ });
291
+ }
292
+ actionDone();
293
+ });
294
+
295
+ let configName = "jiek.config";
296
+ function getConfigPath(root) {
297
+ const isSupportTsLoader = !!tsRegisterName;
298
+ function configWithExtIsExist(ext) {
299
+ const filenames = [
300
+ path__default.default.resolve(root, `${configName}.${ext}`),
301
+ path__default.default.resolve(root, `.${configName}.${ext}`)
302
+ ];
303
+ for (const filename of filenames) {
304
+ if (fs__default.default.existsSync(filename) && fs__default.default.lstatSync(filename).isFile()) {
305
+ return filename;
306
+ }
307
+ }
308
+ return;
309
+ }
310
+ configName = configWithExtIsExist("js") ?? configName;
311
+ configName = configWithExtIsExist("json") ?? configName;
312
+ configName = configWithExtIsExist("yaml") ?? configName;
313
+ if (isSupportTsLoader) {
314
+ configName = configWithExtIsExist("ts") ?? configName;
315
+ }
316
+ return path__default.default.resolve(root, configName);
317
+ }
318
+ function loadConfig() {
319
+ const { wd: root, notWorkspace } = getWD();
320
+ if (notWorkspace)
321
+ throw new Error("not in workspace");
322
+ let configPath = commander.program.getOptionValue("configPath");
323
+ if (!configPath) {
324
+ configPath = getConfigPath(root);
325
+ } else {
326
+ if (!fs__default.default.existsSync(configPath))
327
+ throw new Error(`config file not found: ${configPath}`);
328
+ if (!path__default.default.isAbsolute(configPath))
329
+ configPath = path__default.default.resolve(root, configPath);
330
+ }
331
+ const ext = path__default.default.extname(configPath);
332
+ let module;
333
+ switch (ext) {
334
+ case ".js":
335
+ module = require(configPath);
336
+ break;
337
+ case ".json":
338
+ return require(configPath);
339
+ case ".yaml":
340
+ return jsYaml.load(fs__default.default.readFileSync(configPath, "utf-8"));
341
+ case ".ts":
342
+ if (tsRegisterName) {
343
+ require(tsRegisterName);
344
+ module = require(configPath);
345
+ break;
346
+ }
347
+ throw new Error(
348
+ "ts config file is not supported without ts register, please install esbuild-register or set JIEK_TS_REGISTER env for custom ts register"
349
+ );
350
+ case ".config":
351
+ module = {};
352
+ break;
353
+ default:
354
+ throw new Error(`unsupported config file type: ${ext}`);
355
+ }
356
+ if (!module)
357
+ throw new Error("config file is empty");
358
+ return module.default ?? module;
359
+ }
360
+
361
+ const PACKAGE_JSON_TEMPLATE = `{
362
+ "name": "",
363
+ "version": "0.0.1",
364
+ "description": "",
365
+ "license": "",
366
+ "author": "",
367
+ "files": ["dist"],
368
+ "exports": {
369
+ ".": "./src/index.ts"
370
+ },
371
+ "scripts": {
372
+ },
373
+ "homepage": "",
374
+ "repository": "",
375
+ "bugs": ""
376
+ }`.trimStart();
377
+ const README_TEMPLATE = `# $name
378
+
379
+ ## Installation
380
+
381
+ \`\`\`bash
382
+ npm install $name
383
+ # or
384
+ pnpm install $name
385
+ # or
386
+ yarn add $name
387
+ \`\`\`
388
+
389
+ ## Usage
390
+
391
+
392
+ ## License
393
+
394
+ $license
395
+ `.trimStart();
396
+ function getTemplateStr(wd, template) {
397
+ let templateString = template ?? PACKAGE_JSON_TEMPLATE;
398
+ let isTemplateFile = false;
399
+ try {
400
+ if (template)
401
+ JSON.parse(template);
402
+ } catch (e) {
403
+ isTemplateFile = true;
404
+ }
405
+ if (isTemplateFile) {
406
+ const templatePath = path__default.default.resolve(wd, template);
407
+ templateString = fs__default.default.readFileSync(templatePath, "utf-8");
408
+ }
409
+ return templateString;
410
+ }
411
+ const wdCache = /* @__PURE__ */ new Map();
412
+ function getWDPackageJSONFiled(wd, field) {
413
+ if (wdCache.has(wd)) {
414
+ return wdCache.get(wd)[field];
415
+ }
416
+ const packageJSONPath = path__default.default.resolve(wd, "package.json");
417
+ const packageJSON = JSON.parse(fs__default.default.readFileSync(packageJSONPath, "utf-8"));
418
+ wdCache.set(wd, packageJSON);
419
+ return packageJSON[field];
420
+ }
421
+ async function getName(named, name, {
422
+ wd,
423
+ cwd,
424
+ workspaceName
425
+ }) {
426
+ const relativePath = cwd.replace(`${wd}/`, "");
427
+ let basename = path__default.default.basename(cwd);
428
+ if (typeof named === "function") {
429
+ return named(name, {
430
+ full: wd,
431
+ relative: cwd
432
+ });
433
+ }
434
+ let isParentMatched = false;
435
+ let matchedKey;
436
+ let matchedRule;
437
+ if (typeof named === "object") {
438
+ const isWD = cwd === wd;
439
+ if (isWD) {
440
+ const { rule } = await inquirer__default.default.prompt({
441
+ type: "list",
442
+ name: "rule",
443
+ message: "choose a rule",
444
+ default: "default",
445
+ choices: ["default"].concat(Object.keys(named))
446
+ });
447
+ if (rule !== "default") {
448
+ matchedKey = rule;
449
+ matchedRule = named[rule];
450
+ }
451
+ } else
452
+ for (const [key, value] of Object.entries(named)) {
453
+ if (micromatch.isMatch(relativePath, key)) {
454
+ matchedKey = key;
455
+ matchedRule = value;
456
+ break;
457
+ }
458
+ if (micromatch.isMatch(`${relativePath}/jiek_ignore_dont_use_same_file_name`, key)) {
459
+ isParentMatched = true;
460
+ matchedKey = key;
461
+ matchedRule = value;
462
+ break;
463
+ }
464
+ }
465
+ }
466
+ if (!matchedRule) {
467
+ matchedKey = "packages/*";
468
+ matchedRule = `@${workspaceName}/$basename`;
469
+ }
470
+ if (!matchedRule)
471
+ throw new Error("no matched rule");
472
+ if (!name && isParentMatched) {
473
+ basename = await inquirer__default.default.prompt({
474
+ type: "input",
475
+ name: "name",
476
+ message: `the matched rule is \`${String(matchedRule)}\`, please input the basename
477
+ `
478
+ }).then(({ name: name2 }) => name2);
479
+ }
480
+ if (typeof matchedRule === "function") {
481
+ return matchedRule(name, {
482
+ full: wd,
483
+ relative: cwd,
484
+ basename
485
+ });
486
+ }
487
+ if (typeof matchedRule === "string") {
488
+ const dirName = name ?? basename;
489
+ return [
490
+ matchedRule.replace(/\$basename/g, dirName),
491
+ matchedKey?.replace(/\/\*$/g, `/${dirName}`)
492
+ ];
493
+ }
494
+ throw new Error("no matched rule");
495
+ }
496
+ commander.program.command("init [name]").option("-t, --template <template>", "the package.json template file path or file content").action(async () => {
497
+ const [, name] = commander.program.args;
498
+ const cwd = process.cwd();
499
+ const { init = {} } = loadConfig() ?? {};
500
+ const { wd } = getWD();
501
+ const workspaceName = path__default.default.basename(wd);
502
+ const {
503
+ named,
504
+ template,
505
+ bug = {},
506
+ readme: _readme = README_TEMPLATE,
507
+ readmeTemplate
508
+ } = init;
509
+ const resolvedBug = {
510
+ template: "bug_report.yml",
511
+ labels: ["bug"],
512
+ ...bug
513
+ };
514
+ let readme = _readme;
515
+ if (readmeTemplate) {
516
+ const readmeTemplatePath = path__default.default.resolve(wd, readmeTemplate);
517
+ readme = fs__default.default.readFileSync(readmeTemplatePath, "utf-8");
518
+ }
519
+ const templateString = getTemplateStr(wd, template);
520
+ const { indent = " " } = detectIndent__default.default(templateString);
521
+ const formattingOptions = {
522
+ tabSize: indent.length,
523
+ insertSpaces: true
524
+ };
525
+ const passFields = [
526
+ "license",
527
+ "author"
528
+ ];
529
+ let newJSONString = templateString;
530
+ for (const field of passFields) {
531
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
532
+ newJSONString,
533
+ [field],
534
+ getWDPackageJSONFiled(wd, field),
535
+ { formattingOptions }
536
+ ));
537
+ }
538
+ let [pkgName, pkgDir] = await getName(named, name, {
539
+ wd,
540
+ cwd,
541
+ workspaceName
542
+ });
543
+ if (!pkgDir) {
544
+ const { dir } = await inquirer__default.default.prompt({
545
+ type: "input",
546
+ name: "dir",
547
+ message: "package directory",
548
+ default: name
549
+ });
550
+ pkgDir = dir;
551
+ }
552
+ if (!pkgName) {
553
+ const { name: inputName } = await inquirer__default.default.prompt({
554
+ type: "input",
555
+ name: "name",
556
+ message: "package name",
557
+ default: name
558
+ });
559
+ pkgName = inputName;
560
+ }
561
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(newJSONString, ["name"], pkgName, { formattingOptions }));
562
+ let pkgRepo = getWDPackageJSONFiled(wd, "repository");
563
+ if (typeof pkgRepo === "string") {
564
+ pkgRepo = {
565
+ type: "git",
566
+ url: pkgRepo,
567
+ directory: pkgDir
568
+ };
569
+ }
570
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
571
+ newJSONString,
572
+ ["repository"],
573
+ pkgRepo,
574
+ { formattingOptions }
575
+ ));
576
+ const homepage = `${pkgRepo?.url}/blob/master/${pkgDir}/README.md`;
577
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
578
+ newJSONString,
579
+ ["homepage"],
580
+ homepage,
581
+ { formattingOptions }
582
+ ));
583
+ let labels = resolvedBug.labels;
584
+ if (typeof labels === "function")
585
+ labels = labels({
586
+ name: pkgName,
587
+ dir: pkgDir
588
+ });
589
+ labels.push(`scope:${pkgName}`);
590
+ const bugs = `${pkgRepo?.url}/issues/new?template=${resolvedBug.template}&labels=${labels.join(",")}`;
591
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
592
+ newJSONString,
593
+ ["bugs"],
594
+ bugs,
595
+ { formattingOptions }
596
+ ));
597
+ function pkgDirTo(to) {
598
+ if (!pkgDir)
599
+ throw new Error("pkgDir is not defined");
600
+ return path__default.default.resolve(pkgDir, to);
601
+ }
602
+ if (!fs__default.default.existsSync(pkgDir))
603
+ fs__default.default.mkdirSync(pkgDir);
604
+ const pkgJSONFilePath = pkgDirTo("package.json");
605
+ if (fs__default.default.existsSync(pkgJSONFilePath)) {
606
+ throw new Error("package.json already exists");
607
+ }
608
+ fs__default.default.writeFileSync(pkgJSONFilePath, newJSONString);
609
+ console.log(newJSONString, "written to", pkgJSONFilePath);
610
+ const license = getWDPackageJSONFiled(wd, "license");
611
+ const readmeFilePath = pkgDirTo("README.md");
612
+ if (typeof readme === "function") {
613
+ readme = readme({
614
+ dir: pkgDir,
615
+ packageJson: JSON.parse(newJSONString)
616
+ });
617
+ }
618
+ const readmeContent = readme.replace(/\$name/g, pkgName).replace(/\$license/g, license);
619
+ fs__default.default.writeFileSync(readmeFilePath, readmeContent);
620
+ });
621
+
622
+ commander.program.command("publish").aliases(["pub", "p"]).option("-b, --bumper <bumper>", "bump version", "patch").option("-p, --preview", "preview publish").action(async ({ preview, bumper: bumper$1, ...options }) => {
623
+ actionRestore();
624
+ const { value = {} } = await getSelectedProjectsGraph() ?? {};
625
+ const selectedProjectsGraphEntries = Object.entries(value);
626
+ if (selectedProjectsGraphEntries.length === 0) {
627
+ throw new Error("no packages selected");
628
+ }
629
+ const mainfests = selectedProjectsGraphEntries.map(([dir, manifest]) => [
630
+ dir,
631
+ mergePackageJson(manifest, dir)
632
+ ]);
633
+ const passArgs = Object.entries(options).reduce((acc, [key, value2]) => {
634
+ if (value2) {
635
+ acc.push(`--${key}`, value2);
636
+ }
637
+ return acc;
638
+ }, []);
639
+ for (const [dir, manifest] of mainfests) {
640
+ const oldJSONString = fs__default.default.readFileSync(path__default.default.join(dir, "package.json"), "utf-8");
641
+ const oldJSON = JSON.parse(oldJSONString) ?? "0.0.0";
642
+ const newVersion = bumper.bump(oldJSON.version, bumper$1);
643
+ const { indent = " " } = detectIndent__default.default(oldJSONString);
644
+ const formattingOptions = {
645
+ tabSize: indent.length,
646
+ insertSpaces: true
647
+ };
648
+ let newJSONString = oldJSONString;
649
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
650
+ newJSONString,
651
+ ["version"],
652
+ newVersion,
653
+ { formattingOptions }
654
+ ));
655
+ for (const [key, value2] of Object.entries(manifest)) {
656
+ if (JSON.stringify(value2) === JSON.stringify(oldJSON[key]))
657
+ continue;
658
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
659
+ newJSONString,
660
+ ["publishConfig", key],
661
+ value2,
662
+ { formattingOptions }
663
+ ));
664
+ }
665
+ try {
666
+ fs__default.default.renameSync(path__default.default.join(dir, "package.json"), path__default.default.join(dir, "package.json.bak"));
667
+ fs__default.default.writeFileSync(path__default.default.join(dir, "package.json"), newJSONString);
668
+ console.log(newJSONString);
669
+ if (preview) {
670
+ console.warn("preview mode");
671
+ continue;
672
+ }
673
+ childProcess__namespace.execSync(["pnpm", "publish", "--access", "public", "--no-git-checks", ...passArgs].join(" "), {
674
+ cwd: dir,
675
+ stdio: "inherit"
676
+ });
677
+ const modifyVersionPackageJSON = jsoncParser.applyEdits(oldJSONString, jsoncParser.modify(oldJSONString, ["version"], newVersion, {}));
678
+ fs__default.default.writeFileSync(path__default.default.join(dir, "package.json.bak"), modifyVersionPackageJSON);
679
+ } finally {
680
+ fs__default.default.unlinkSync(path__default.default.join(dir, "package.json"));
681
+ fs__default.default.renameSync(path__default.default.join(dir, "package.json.bak"), path__default.default.join(dir, "package.json"));
682
+ }
683
+ }
684
+ actionDone();
685
+ });
686
+
687
+ commander.program.parse(process.argv);
2
688
  //# sourceMappingURL=cli.cjs.map