jiek 0.4.5 → 0.4.7-alpha.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (164) hide show
  1. package/README.md +22 -1
  2. package/bin/jiek.js +2 -1
  3. package/dist/cli.d.mts +97 -0
  4. package/dist/cli.d.mts.map +1 -0
  5. package/dist/cli.d.ts +96 -1
  6. package/dist/cli.d.ts.map +1 -0
  7. package/dist/{cli.cjs → cli.js} +361 -226
  8. package/dist/cli.js.map +1 -0
  9. package/dist/cli.min.js +1 -0
  10. package/dist/cli.min.js.map +1 -0
  11. package/dist/cli.min.mjs +1 -0
  12. package/dist/cli.min.mjs.map +1 -0
  13. package/dist/cli.mjs +803 -0
  14. package/dist/cli.mjs.map +1 -0
  15. package/dist/index.d.mts +58 -0
  16. package/dist/index.d.mts.map +1 -0
  17. package/dist/index.d.ts +47 -46
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/{index.cjs → index.js} +0 -1
  20. package/dist/index.js.map +1 -0
  21. package/dist/{index.min.cjs → index.min.js} +0 -1
  22. package/dist/index.min.js.map +1 -0
  23. package/dist/index.min.mjs +1 -0
  24. package/dist/index.min.mjs.map +1 -0
  25. package/dist/{index.esm.js → index.mjs} +0 -1
  26. package/dist/index.mjs.map +1 -0
  27. package/dist/rollup/index.d.mts +53 -0
  28. package/dist/rollup/index.d.mts.map +1 -0
  29. package/dist/rollup/index.d.ts +53 -0
  30. package/dist/rollup/index.d.ts.map +1 -0
  31. package/dist/rollup/index.js +553 -0
  32. package/dist/rollup/index.js.map +1 -0
  33. package/dist/rollup/index.min.js +1 -0
  34. package/dist/rollup/index.min.js.map +1 -0
  35. package/dist/rollup/index.min.mjs +1 -0
  36. package/dist/rollup/index.min.mjs.map +1 -0
  37. package/dist/rollup/index.mjs +551 -0
  38. package/dist/rollup/index.mjs.map +1 -0
  39. package/package.json +52 -35
  40. package/src/cli.ts +9 -0
  41. package/src/commands/base.ts +9 -0
  42. package/src/commands/build.ts +156 -0
  43. package/src/commands/init.ts +373 -0
  44. package/src/commands/publish.ts +156 -0
  45. package/src/index.ts +8 -0
  46. package/src/inner.ts +11 -0
  47. package/src/merge-package-json.ts +75 -0
  48. package/src/pkg.ts +1 -0
  49. package/src/rollup/base.ts +72 -0
  50. package/src/rollup/index.ts +420 -0
  51. package/src/rollup/plugins/globals.ts +34 -0
  52. package/src/rollup/plugins/progress.ts +26 -0
  53. package/src/rollup/plugins/skip.ts +23 -0
  54. package/src/rollup/utils/commonOptions.ts +9 -0
  55. package/src/rollup/utils/externalResolver.ts +21 -0
  56. package/src/rollup/utils/globalResolver.ts +13 -0
  57. package/src/rollup/utils/withMinify.ts +18 -0
  58. package/src/utils/filterSupport.ts +82 -0
  59. package/src/utils/getExports.ts +100 -0
  60. package/src/utils/getRoot.ts +16 -0
  61. package/src/utils/getWD.ts +31 -0
  62. package/src/utils/loadConfig.ts +93 -0
  63. package/src/utils/tsRegister.ts +22 -0
  64. package/dist/base.esm.d.ts +0 -55
  65. package/dist/cli.cjs.map +0 -1
  66. package/dist/cli.esm.d.ts +0 -2
  67. package/dist/cli.esm.js +0 -9
  68. package/dist/cli.esm.js.map +0 -1
  69. package/dist/cli.esm.min.js +0 -2
  70. package/dist/cli.esm.min.js.map +0 -1
  71. package/dist/cli.min.cjs +0 -2
  72. package/dist/cli.min.cjs.map +0 -1
  73. package/dist/commands/base.esm.js +0 -5
  74. package/dist/commands/base.esm.js.map +0 -1
  75. package/dist/commands/base.esm.min.js +0 -2
  76. package/dist/commands/base.esm.min.js.map +0 -1
  77. package/dist/commands/build.esm.js +0 -58
  78. package/dist/commands/build.esm.js.map +0 -1
  79. package/dist/commands/build.esm.min.js +0 -2
  80. package/dist/commands/build.esm.min.js.map +0 -1
  81. package/dist/commands/init.esm.js +0 -271
  82. package/dist/commands/init.esm.js.map +0 -1
  83. package/dist/commands/init.esm.min.js +0 -2
  84. package/dist/commands/init.esm.min.js.map +0 -1
  85. package/dist/commands/publish.esm.js +0 -76
  86. package/dist/commands/publish.esm.js.map +0 -1
  87. package/dist/commands/publish.esm.min.js +0 -2
  88. package/dist/commands/publish.esm.min.js.map +0 -1
  89. package/dist/index.cjs.map +0 -1
  90. package/dist/index.esm.d.ts +0 -6
  91. package/dist/index.esm.js.map +0 -1
  92. package/dist/index.esm.min.js +0 -2
  93. package/dist/index.esm.min.js.map +0 -1
  94. package/dist/index.min.cjs.map +0 -1
  95. package/dist/inner.esm.js +0 -10
  96. package/dist/inner.esm.js.map +0 -1
  97. package/dist/inner.esm.min.js +0 -2
  98. package/dist/inner.esm.min.js.map +0 -1
  99. package/dist/merge-package-json.esm.js +0 -64
  100. package/dist/merge-package-json.esm.js.map +0 -1
  101. package/dist/merge-package-json.esm.min.js +0 -2
  102. package/dist/merge-package-json.esm.min.js.map +0 -1
  103. package/dist/pkg.esm.js +0 -4
  104. package/dist/pkg.esm.js.map +0 -1
  105. package/dist/pkg.esm.min.js +0 -2
  106. package/dist/pkg.esm.min.js.map +0 -1
  107. package/dist/rollup/plugins/globals.esm.js +0 -31
  108. package/dist/rollup/plugins/globals.esm.js.map +0 -1
  109. package/dist/rollup/plugins/globals.esm.min.js +0 -2
  110. package/dist/rollup/plugins/globals.esm.min.js.map +0 -1
  111. package/dist/rollup/plugins/skip.esm.js +0 -16
  112. package/dist/rollup/plugins/skip.esm.js.map +0 -1
  113. package/dist/rollup/plugins/skip.esm.min.js +0 -2
  114. package/dist/rollup/plugins/skip.esm.min.js.map +0 -1
  115. package/dist/rollup/utils/commonOptions.esm.js +0 -9
  116. package/dist/rollup/utils/commonOptions.esm.js.map +0 -1
  117. package/dist/rollup/utils/commonOptions.esm.min.js +0 -2
  118. package/dist/rollup/utils/commonOptions.esm.min.js.map +0 -1
  119. package/dist/rollup/utils/externalResolver.esm.js +0 -12
  120. package/dist/rollup/utils/externalResolver.esm.js.map +0 -1
  121. package/dist/rollup/utils/externalResolver.esm.min.js +0 -2
  122. package/dist/rollup/utils/externalResolver.esm.min.js.map +0 -1
  123. package/dist/rollup/utils/globalResolver.esm.js +0 -9
  124. package/dist/rollup/utils/globalResolver.esm.js.map +0 -1
  125. package/dist/rollup/utils/globalResolver.esm.min.js +0 -2
  126. package/dist/rollup/utils/globalResolver.esm.min.js.map +0 -1
  127. package/dist/rollup/utils/withMinify.esm.js +0 -15
  128. package/dist/rollup/utils/withMinify.esm.js.map +0 -1
  129. package/dist/rollup/utils/withMinify.esm.min.js +0 -2
  130. package/dist/rollup/utils/withMinify.esm.min.js.map +0 -1
  131. package/dist/rollup.cjs +0 -330
  132. package/dist/rollup.cjs.map +0 -1
  133. package/dist/rollup.d.ts +0 -23
  134. package/dist/rollup.esm.d.ts +0 -23
  135. package/dist/rollup.esm.js +0 -248
  136. package/dist/rollup.esm.js.map +0 -1
  137. package/dist/rollup.esm.min.js +0 -2
  138. package/dist/rollup.esm.min.js.map +0 -1
  139. package/dist/rollup.min.cjs +0 -2
  140. package/dist/rollup.min.cjs.map +0 -1
  141. package/dist/utils/commondir.esm.js +0 -25
  142. package/dist/utils/commondir.esm.js.map +0 -1
  143. package/dist/utils/commondir.esm.min.js +0 -2
  144. package/dist/utils/commondir.esm.min.js.map +0 -1
  145. package/dist/utils/filterSupport.esm.js +0 -67
  146. package/dist/utils/filterSupport.esm.js.map +0 -1
  147. package/dist/utils/filterSupport.esm.min.js +0 -2
  148. package/dist/utils/filterSupport.esm.min.js.map +0 -1
  149. package/dist/utils/getRoot.esm.js +0 -14
  150. package/dist/utils/getRoot.esm.js.map +0 -1
  151. package/dist/utils/getRoot.esm.min.js +0 -2
  152. package/dist/utils/getRoot.esm.min.js.map +0 -1
  153. package/dist/utils/getWD.esm.js +0 -31
  154. package/dist/utils/getWD.esm.js.map +0 -1
  155. package/dist/utils/getWD.esm.min.js +0 -2
  156. package/dist/utils/getWD.esm.min.js.map +0 -1
  157. package/dist/utils/loadConfig.esm.js +0 -75
  158. package/dist/utils/loadConfig.esm.js.map +0 -1
  159. package/dist/utils/loadConfig.esm.min.js +0 -2
  160. package/dist/utils/loadConfig.esm.min.js.map +0 -1
  161. package/dist/utils/tsRegister.esm.js +0 -24
  162. package/dist/utils/tsRegister.esm.js.map +0 -1
  163. package/dist/utils/tsRegister.esm.min.js +0 -2
  164. package/dist/utils/tsRegister.esm.min.js.map +0 -1
package/dist/cli.mjs ADDED
@@ -0,0 +1,803 @@
1
+ import fs from 'node:fs';
2
+ import path, { resolve as resolve$1, relative } from 'node:path';
3
+ import { filterPackagesFromDir } from '@pnpm/filter-workspace-packages';
4
+ import { program } from 'commander';
5
+ import { load } from 'js-yaml';
6
+ import { isWorkspaceDir, getWorkspaceDir } from '@jiek/utils/getWorkspaceDir';
7
+ import { MultiBar, Presets } from 'cli-progress';
8
+ import { execaCommand } from 'execa';
9
+ import detectIndent from 'detect-indent';
10
+ import inquirer from 'inquirer';
11
+ import { applyEdits, modify } from 'jsonc-parser';
12
+ import { isMatch } from 'micromatch';
13
+ import * as childProcess from 'node:child_process';
14
+ import { bump } from '@jiek/utils/bumper';
15
+ import { resolveEntrypoints, filterLeafs, DEFAULT_SKIP_VALUES, entrypoints2Exports } from '@jiek/pkger/entrypoints';
16
+
17
+ let root;
18
+ function getRoot() {
19
+ if (root)
20
+ return root;
21
+ const rootOption = program.getOptionValue("root");
22
+ root = rootOption ? path.isAbsolute(rootOption) ? rootOption : path.resolve(process.cwd(), rootOption) : void 0;
23
+ return root;
24
+ }
25
+
26
+ let wd;
27
+ let notWorkspace = false;
28
+ function getWD() {
29
+ if (wd)
30
+ return { wd, notWorkspace };
31
+ const root = getRoot();
32
+ if (root !== void 0) {
33
+ const isWorkspace = isWorkspaceDir(root, type);
34
+ notWorkspace = !isWorkspace;
35
+ wd = root;
36
+ return { wd, notWorkspace };
37
+ }
38
+ try {
39
+ wd = getWorkspaceDir(type);
40
+ } catch (e) {
41
+ if ("message" in e && e.message === "workspace root not found") {
42
+ wd = root;
43
+ notWorkspace = true;
44
+ } else {
45
+ throw e;
46
+ }
47
+ }
48
+ return { wd, notWorkspace };
49
+ }
50
+
51
+ let type = "";
52
+ try {
53
+ require.resolve("@pnpm/filter-workspace-packages");
54
+ type = "pnpm";
55
+ } catch {
56
+ }
57
+ if (type !== "") {
58
+ program.option("-f, --filter <filter>", "filter packages");
59
+ }
60
+ async function getSelectedProjectsGraph() {
61
+ let filter = program.getOptionValue("filter");
62
+ const root = getRoot();
63
+ const { wd, notWorkspace } = getWD();
64
+ if (!notWorkspace && type === "pnpm") {
65
+ const pnpmWorkspaceFilePath = path.resolve(wd, "pnpm-workspace.yaml");
66
+ const pnpmWorkspaceFileContent = fs.readFileSync(pnpmWorkspaceFilePath, "utf-8");
67
+ const pnpmWorkspace = load(pnpmWorkspaceFileContent);
68
+ if (root === wd && !filter) {
69
+ throw new Error("root path is workspace root, please provide a filter");
70
+ }
71
+ if (root !== wd && !filter) {
72
+ const packageJSONIsExist = fs.existsSync(path.resolve(root, "package.json"));
73
+ if (!packageJSONIsExist) {
74
+ throw new Error("root path is not workspace root, please provide a filter");
75
+ }
76
+ const packageJSON = JSON.parse(fs.readFileSync(path.resolve(root, "package.json"), "utf-8"));
77
+ if (!packageJSON.name) {
78
+ throw new Error("root path is not workspace root, please provide a filter");
79
+ }
80
+ filter = packageJSON.name;
81
+ }
82
+ const { selectedProjectsGraph } = await filterPackagesFromDir(wd, [{
83
+ filter: filter ?? "",
84
+ followProdDepsOnly: true
85
+ }], {
86
+ prefix: root,
87
+ workspaceDir: wd,
88
+ patterns: pnpmWorkspace.packages
89
+ });
90
+ return {
91
+ wd,
92
+ root,
93
+ value: Object.entries(selectedProjectsGraph).reduce((acc, [key, value]) => {
94
+ acc[key] = value.package.manifest;
95
+ return acc;
96
+ }, {})
97
+ };
98
+ }
99
+ return {
100
+ wd,
101
+ root,
102
+ value: {
103
+ [wd]: JSON.parse(fs.readFileSync(path.resolve(wd, "package.json"), "utf-8"))
104
+ }
105
+ };
106
+ }
107
+
108
+ var pkg = require("../package.json");
109
+
110
+ program.version(pkg.version).description(pkg.description).option("--root <root>", "root path").option("-c, --config-path <configPath>", "config path");
111
+
112
+ let resolve;
113
+ function actionDone() {
114
+ resolve();
115
+ }
116
+ function actionRestore() {
117
+ new Promise((r) => resolve = r);
118
+ }
119
+
120
+ function packageIsExist(name) {
121
+ try {
122
+ require.resolve(name);
123
+ return true;
124
+ } catch (e) {
125
+ return false;
126
+ }
127
+ }
128
+ let tsRegisterName;
129
+ const registers = [
130
+ process.env.JIEK_TS_REGISTER,
131
+ "esbuild-register",
132
+ "@swc-node/register",
133
+ "ts-node/register"
134
+ ].filter(Boolean);
135
+ for (const register of registers) {
136
+ if (packageIsExist(register)) {
137
+ tsRegisterName = register;
138
+ break;
139
+ }
140
+ }
141
+
142
+ let configName = "jiek.config";
143
+ function getConfigPath(root, dir) {
144
+ const isSupportTsLoader = !!tsRegisterName;
145
+ function configWithExtIsExist(ext) {
146
+ const filenames = [
147
+ path.resolve(process.cwd(), `${configName}.${ext}`),
148
+ path.resolve(process.cwd(), `.${configName}.${ext}`),
149
+ path.resolve(root, `${configName}.${ext}`),
150
+ path.resolve(root, `.${configName}.${ext}`)
151
+ ];
152
+ if (dir) {
153
+ filenames.unshift(...[
154
+ path.resolve(dir, `${configName}.${ext}`),
155
+ path.resolve(dir, `.${configName}.${ext}`)
156
+ ]);
157
+ }
158
+ for (const filename of filenames) {
159
+ if (fs.existsSync(filename) && fs.lstatSync(filename).isFile()) {
160
+ return filename;
161
+ }
162
+ }
163
+ return;
164
+ }
165
+ configName = configWithExtIsExist("js") ?? configName;
166
+ configName = configWithExtIsExist("json") ?? configName;
167
+ configName = configWithExtIsExist("yaml") ?? configName;
168
+ if (isSupportTsLoader) {
169
+ configName = configWithExtIsExist("ts") ?? configName;
170
+ }
171
+ return path.resolve(root, configName);
172
+ }
173
+ function loadConfig(dir) {
174
+ const { wd: root } = getWD();
175
+ let configPath = program.getOptionValue("configPath");
176
+ if (!configPath) {
177
+ configPath = getConfigPath(root, dir);
178
+ } else {
179
+ if (!fs.existsSync(configPath)) {
180
+ throw new Error(`config file not found: ${configPath}`);
181
+ }
182
+ if (!path.isAbsolute(configPath)) {
183
+ configPath = path.resolve(root, configPath);
184
+ }
185
+ }
186
+ const ext = path.extname(configPath);
187
+ let module;
188
+ switch (ext) {
189
+ case ".js":
190
+ module = require(configPath);
191
+ break;
192
+ case ".json":
193
+ return require(configPath);
194
+ case ".yaml":
195
+ return load(fs.readFileSync(configPath, "utf-8"));
196
+ case ".ts":
197
+ if (tsRegisterName) {
198
+ require(tsRegisterName);
199
+ module = require(configPath);
200
+ break;
201
+ }
202
+ throw new Error(
203
+ "ts config file is not supported without ts register, please install esbuild-register or set JIEK_TS_REGISTER env for custom ts register"
204
+ );
205
+ case ".config":
206
+ module = {};
207
+ break;
208
+ default:
209
+ throw new Error(`unsupported config file type: ${ext}`);
210
+ }
211
+ if (!module)
212
+ throw new Error("config file is empty");
213
+ return module.default ?? module;
214
+ }
215
+
216
+ const FILE_TEMPLATE = (manifest) => `
217
+ const manifest = ${JSON.stringify(manifest, null, 2)}
218
+ module.exports = require('jiek/rollup').template(manifest)
219
+ `.trimStart();
220
+ program.command("build").option("-s, --silent", "Don't display logs.").option("-e, --entries <ENTRIES>", "Specify the entries of the package.json's 'exports' field.(support glob)").action(async ({
221
+ silent,
222
+ entries
223
+ }) => {
224
+ actionRestore();
225
+ const { build } = loadConfig();
226
+ silent = silent ?? build?.silent ?? false;
227
+ const {
228
+ wd,
229
+ value = {}
230
+ } = await getSelectedProjectsGraph() ?? {};
231
+ if (Object.keys(value).length === 0) {
232
+ throw new Error("no package found");
233
+ }
234
+ const wdNodeModules = path.resolve(wd, "node_modules");
235
+ if (!fs.existsSync(wdNodeModules)) {
236
+ fs.mkdirSync(wdNodeModules);
237
+ }
238
+ const jiekTempDir = (...paths) => path.resolve(wdNodeModules, ".jiek", ...paths);
239
+ if (!fs.existsSync(jiekTempDir())) {
240
+ fs.mkdirSync(jiekTempDir());
241
+ }
242
+ const rollupBinaryPath = require.resolve("rollup").replace(/dist\/rollup.js$/, "dist/bin/rollup");
243
+ const multiBars = new MultiBar({
244
+ clearOnComplete: false,
245
+ hideCursor: true,
246
+ format: "- {bar} | {status} | {input} | {message}"
247
+ }, Presets.shades_classic);
248
+ let i = 0;
249
+ await Promise.all(
250
+ Object.entries(value).map(async ([dir, manifest]) => {
251
+ const escapeManifestName = manifest.name?.replace(/^@/g, "").replace(/\//g, "+");
252
+ const configFile = jiekTempDir(
253
+ `${escapeManifestName ?? `anonymous-${i++}`}.rollup.config.js`
254
+ );
255
+ fs.writeFileSync(configFile, FILE_TEMPLATE(manifest));
256
+ let prefix = "";
257
+ if (tsRegisterName) {
258
+ prefix = `node -r ${tsRegisterName} `;
259
+ }
260
+ const command = `${prefix}${rollupBinaryPath} --silent -c ${configFile}`;
261
+ const child = execaCommand(command, {
262
+ ipc: true,
263
+ cwd: dir,
264
+ env: {
265
+ ...process.env,
266
+ JIEK_ROOT: wd,
267
+ JIEK_ENTRIES: entries
268
+ }
269
+ });
270
+ const bars = {};
271
+ let inputMaxLen = 10;
272
+ child.on("message", (e) => {
273
+ if (e.type === "debug")
274
+ console.log(...Array.isArray(e.data) ? e.data : [e.data]);
275
+ });
276
+ !silent && child.on("message", (e) => {
277
+ if (e.type === "init") {
278
+ const { leafMap, targetsLength } = e.data;
279
+ const leafs = Array.from(leafMap.entries()).flatMap(
280
+ ([input, pathAndCondiions]) => pathAndCondiions.map(([path2, ...conditions]) => ({
281
+ input,
282
+ path: path2,
283
+ conditions
284
+ }))
285
+ );
286
+ console.log(`Package '${manifest.name}' has ${targetsLength} targets to build`);
287
+ leafs.forEach(({ input }) => {
288
+ inputMaxLen = Math.max(inputMaxLen, input.length);
289
+ });
290
+ leafs.forEach(({ input, path: path2 }) => {
291
+ const key = `${input}:${path2}`;
292
+ if (bars[key])
293
+ return;
294
+ bars[key] = multiBars.create(50, 0, {
295
+ input: input.padEnd(inputMaxLen),
296
+ status: "waiting".padEnd(10)
297
+ }, {
298
+ barsize: 20,
299
+ linewrap: true
300
+ });
301
+ });
302
+ }
303
+ if (e.type === "progress") {
304
+ const {
305
+ path: path2,
306
+ tags,
307
+ input,
308
+ event,
309
+ message
310
+ } = e.data;
311
+ const bar = bars[`${input}:${path2}`];
312
+ if (!bar)
313
+ return;
314
+ bar.update(
315
+ {
316
+ start: 0,
317
+ resolve: 20,
318
+ end: 50
319
+ }[event ?? "start"] ?? 0,
320
+ {
321
+ input: input.padEnd(inputMaxLen),
322
+ status: event?.padEnd(10),
323
+ message: `${tags?.join(", ")}: ${message}`
324
+ }
325
+ );
326
+ }
327
+ });
328
+ await new Promise((resolve, reject) => {
329
+ let errorStr = "";
330
+ child.stderr?.on("data", (data) => {
331
+ errorStr += data;
332
+ });
333
+ child.once("exit", (code) => code === 0 ? resolve() : reject(new Error(`rollup build failed:
334
+ ${errorStr}`)));
335
+ });
336
+ })
337
+ ).finally(() => {
338
+ multiBars.stop();
339
+ });
340
+ actionDone();
341
+ });
342
+
343
+ const PACKAGE_JSON_TEMPLATE = `{
344
+ "name": "",
345
+ "version": "0.0.1",
346
+ "description": "",
347
+ "license": "",
348
+ "author": "",
349
+ "files": ["dist"],
350
+ "exports": {
351
+ ".": "./src/index.ts"
352
+ },
353
+ "scripts": {
354
+ },
355
+ "homepage": "",
356
+ "repository": "",
357
+ "bugs": ""
358
+ }`.trimStart();
359
+ const README_TEMPLATE = `# $name
360
+
361
+ ## Installation
362
+
363
+ \`\`\`bash
364
+ npm install $name
365
+ # or
366
+ pnpm install $name
367
+ # or
368
+ yarn add $name
369
+ \`\`\`
370
+
371
+ ## Usage
372
+
373
+
374
+ ## License
375
+
376
+ $license
377
+ `.trimStart();
378
+ function getTemplateStr(wd, template) {
379
+ let templateString = template ?? PACKAGE_JSON_TEMPLATE;
380
+ let isTemplateFile = false;
381
+ try {
382
+ if (template)
383
+ JSON.parse(template);
384
+ } catch (e) {
385
+ isTemplateFile = true;
386
+ }
387
+ if (isTemplateFile) {
388
+ const templatePath = path.resolve(wd, template);
389
+ templateString = fs.readFileSync(templatePath, "utf-8");
390
+ }
391
+ return templateString;
392
+ }
393
+ const wdCache = /* @__PURE__ */ new Map();
394
+ function getWDPackageJSONFiled(wd, field) {
395
+ if (wdCache.has(wd)) {
396
+ return wdCache.get(wd)[field];
397
+ }
398
+ const packageJSONPath = path.resolve(wd, "package.json");
399
+ const packageJSON = JSON.parse(fs.readFileSync(packageJSONPath, "utf-8"));
400
+ wdCache.set(wd, packageJSON);
401
+ return packageJSON[field];
402
+ }
403
+ async function getName(named, name, {
404
+ wd,
405
+ cwd,
406
+ workspaceName
407
+ }) {
408
+ const relativePath = cwd.replace(`${wd}/`, "");
409
+ let basename = path.basename(cwd);
410
+ if (typeof named === "function") {
411
+ return named(name, {
412
+ full: wd,
413
+ relative: cwd
414
+ });
415
+ }
416
+ let isParentMatched = false;
417
+ let matchedKey;
418
+ let matchedRule;
419
+ if (typeof named === "object") {
420
+ const isWD = cwd === wd;
421
+ if (isWD) {
422
+ const { rule } = await inquirer.prompt({
423
+ type: "list",
424
+ name: "rule",
425
+ message: "choose a rule",
426
+ default: "default",
427
+ choices: ["default"].concat(Object.keys(named))
428
+ });
429
+ if (rule !== "default") {
430
+ matchedKey = rule;
431
+ matchedRule = named[rule];
432
+ }
433
+ } else {
434
+ for (const [key, value] of Object.entries(named)) {
435
+ if (isMatch(relativePath, key)) {
436
+ matchedKey = key;
437
+ matchedRule = value;
438
+ break;
439
+ }
440
+ if (isMatch(`${relativePath}/jiek_ignore_dont_use_same_file_name`, key)) {
441
+ isParentMatched = true;
442
+ matchedKey = key;
443
+ matchedRule = value;
444
+ break;
445
+ }
446
+ }
447
+ }
448
+ }
449
+ if (!matchedRule) {
450
+ matchedKey = "packages/*";
451
+ matchedRule = `@${workspaceName}/$basename`;
452
+ }
453
+ if (!matchedRule) {
454
+ throw new Error("no matched rule");
455
+ }
456
+ if (!name && isParentMatched) {
457
+ basename = await inquirer.prompt({
458
+ type: "input",
459
+ name: "name",
460
+ message: `the matched rule is \`${String(matchedRule)}\`, please input the basename
461
+ `
462
+ }).then(({ name: name2 }) => name2);
463
+ }
464
+ if (typeof matchedRule === "function") {
465
+ return matchedRule(name, {
466
+ full: wd,
467
+ relative: cwd,
468
+ basename
469
+ });
470
+ }
471
+ if (typeof matchedRule === "string") {
472
+ const dirName = name ?? basename;
473
+ return [
474
+ matchedRule.replace(/\$basename/g, dirName),
475
+ matchedKey?.replace(/\/\*$/g, `/${dirName}`)
476
+ ];
477
+ }
478
+ throw new Error("no matched rule");
479
+ }
480
+ program.command("init [name]").option("-t, --template <template>", "the package.json template file path or file content").action(async () => {
481
+ const [, name] = program.args;
482
+ const cwd = process.cwd();
483
+ const { init = {} } = loadConfig() ?? {};
484
+ const { wd } = getWD();
485
+ const workspaceName = path.basename(wd);
486
+ const {
487
+ named,
488
+ template,
489
+ bug = {},
490
+ readme: _readme = README_TEMPLATE,
491
+ readmeTemplate
492
+ } = init;
493
+ const resolvedBug = {
494
+ template: "bug_report.yml",
495
+ labels: ["bug"],
496
+ ...bug
497
+ };
498
+ let readme = _readme;
499
+ if (readmeTemplate) {
500
+ const readmeTemplatePath = path.resolve(wd, readmeTemplate);
501
+ readme = fs.readFileSync(readmeTemplatePath, "utf-8");
502
+ }
503
+ const templateString = getTemplateStr(wd, template);
504
+ const { indent = " " } = detectIndent(templateString);
505
+ const formattingOptions = {
506
+ tabSize: indent.length,
507
+ insertSpaces: true
508
+ };
509
+ const passFields = [
510
+ "license",
511
+ "author"
512
+ ];
513
+ let newJSONString = templateString;
514
+ for (const field of passFields) {
515
+ newJSONString = applyEdits(
516
+ newJSONString,
517
+ modify(
518
+ newJSONString,
519
+ [field],
520
+ getWDPackageJSONFiled(wd, field),
521
+ { formattingOptions }
522
+ )
523
+ );
524
+ }
525
+ let [pkgName, pkgDir] = await getName(named, name, {
526
+ wd,
527
+ cwd,
528
+ workspaceName
529
+ });
530
+ if (!pkgDir) {
531
+ const { dir } = await inquirer.prompt({
532
+ type: "input",
533
+ name: "dir",
534
+ message: "package directory",
535
+ default: name
536
+ });
537
+ pkgDir = dir;
538
+ }
539
+ if (!pkgName) {
540
+ const { name: inputName } = await inquirer.prompt({
541
+ type: "input",
542
+ name: "name",
543
+ message: "package name",
544
+ default: name
545
+ });
546
+ pkgName = inputName;
547
+ }
548
+ newJSONString = applyEdits(newJSONString, modify(newJSONString, ["name"], pkgName, { formattingOptions }));
549
+ let pkgRepo = getWDPackageJSONFiled(wd, "repository");
550
+ if (typeof pkgRepo === "string") {
551
+ pkgRepo = {
552
+ type: "git",
553
+ url: pkgRepo,
554
+ directory: pkgDir
555
+ };
556
+ }
557
+ newJSONString = applyEdits(
558
+ newJSONString,
559
+ modify(
560
+ newJSONString,
561
+ ["repository"],
562
+ pkgRepo,
563
+ { formattingOptions }
564
+ )
565
+ );
566
+ const homepage = `${pkgRepo?.url}/blob/master/${pkgDir}/README.md`;
567
+ newJSONString = applyEdits(
568
+ newJSONString,
569
+ modify(
570
+ newJSONString,
571
+ ["homepage"],
572
+ homepage,
573
+ { formattingOptions }
574
+ )
575
+ );
576
+ let labels = resolvedBug.labels;
577
+ if (typeof labels === "function") {
578
+ labels = labels({
579
+ name: pkgName,
580
+ dir: pkgDir
581
+ });
582
+ }
583
+ labels.push(`scope:${pkgName}`);
584
+ const bugs = `${pkgRepo?.url}/issues/new?template=${resolvedBug.template}&labels=${labels.join(",")}`;
585
+ newJSONString = applyEdits(
586
+ newJSONString,
587
+ modify(
588
+ newJSONString,
589
+ ["bugs"],
590
+ bugs,
591
+ { formattingOptions }
592
+ )
593
+ );
594
+ function pkgDirTo(to) {
595
+ if (!pkgDir)
596
+ throw new Error("pkgDir is not defined");
597
+ return path.resolve(pkgDir, to);
598
+ }
599
+ if (!fs.existsSync(pkgDir))
600
+ fs.mkdirSync(pkgDir);
601
+ const pkgJSONFilePath = pkgDirTo("package.json");
602
+ if (fs.existsSync(pkgJSONFilePath)) {
603
+ throw new Error("package.json already exists");
604
+ }
605
+ fs.writeFileSync(pkgJSONFilePath, newJSONString);
606
+ console.log(newJSONString, "written to", pkgJSONFilePath);
607
+ const license = getWDPackageJSONFiled(wd, "license");
608
+ const readmeFilePath = pkgDirTo("README.md");
609
+ if (typeof readme === "function") {
610
+ readme = readme({
611
+ dir: pkgDir,
612
+ packageJson: JSON.parse(newJSONString)
613
+ });
614
+ }
615
+ const readmeContent = readme.replace(/\$name/g, pkgName).replace(/\$license/g, license);
616
+ fs.writeFileSync(readmeFilePath, readmeContent);
617
+ });
618
+
619
+ const intersection = (a, b) => new Set([...a].filter((i) => b.has(i)));
620
+ function getExports({
621
+ entrypoints,
622
+ pkgIsModule,
623
+ entries,
624
+ config,
625
+ dir,
626
+ noFilter
627
+ }) {
628
+ const dirResolve = (...paths) => resolve$1(dir ?? process.cwd(), ...paths);
629
+ const dirRelative = (path) => relative(dir ?? process.cwd(), path);
630
+ const { build = {} } = config ?? {};
631
+ const {
632
+ crossModuleConvertor = true
633
+ } = build;
634
+ const jsOutdir = `./${dirRelative(dirResolve(
635
+ (typeof build?.output?.dir === "object" ? build.output.dir.js : build?.output?.dir) ?? "dist"
636
+ ))}`;
637
+ const [, resolvedEntrypoints] = resolveEntrypoints(entrypoints);
638
+ if (entries) {
639
+ Object.entries(resolvedEntrypoints).forEach(([key]) => {
640
+ if (!entries.some((e) => isMatch(key, e, { matchBase: true }))) {
641
+ delete resolvedEntrypoints[key];
642
+ }
643
+ });
644
+ }
645
+ const filteredResolvedEntrypoints = noFilter ? resolvedEntrypoints : filterLeafs(
646
+ resolvedEntrypoints,
647
+ {
648
+ skipValue: [
649
+ // ignore values that filename starts with `.jk-noentry`
650
+ /(^|\/)\.jk-noentry/,
651
+ ...DEFAULT_SKIP_VALUES
652
+ ]
653
+ }
654
+ );
655
+ const crossModuleWithConditional = crossModuleConvertor ? {
656
+ import: (opts) => !pkgIsModule && intersection(
657
+ new Set(opts.conditionals),
658
+ /* @__PURE__ */ new Set(["import", "module"])
659
+ ).size === 0 ? opts.dist.replace(/\.js$/, ".mjs") : false,
660
+ require: (opts) => pkgIsModule && intersection(
661
+ new Set(opts.conditionals),
662
+ /* @__PURE__ */ new Set(["require", "node"])
663
+ ).size === 0 ? opts.dist.replace(/\.js$/, ".cjs") : false
664
+ } : {};
665
+ return [
666
+ filteredResolvedEntrypoints,
667
+ entrypoints2Exports(filteredResolvedEntrypoints, {
668
+ outdir: jsOutdir,
669
+ withConditional: {
670
+ ...crossModuleWithConditional
671
+ }
672
+ })
673
+ ];
674
+ }
675
+
676
+ program.command("publish").aliases(["pub", "p"]).option("-b, --bumper <bumper>", "bump version", "patch").option("-p, --preview", "preview publish").action(async ({ preview, bumper, ...options }) => {
677
+ actionRestore();
678
+ const { value = {} } = await getSelectedProjectsGraph() ?? {};
679
+ const selectedProjectsGraphEntries = Object.entries(value);
680
+ if (selectedProjectsGraphEntries.length === 0) {
681
+ throw new Error("no packages selected");
682
+ }
683
+ const manifests = selectedProjectsGraphEntries.map(([dir, manifest]) => {
684
+ const { type, exports: entrypoints = {} } = manifest;
685
+ const pkgIsModule = type === "module";
686
+ const newManifest = { ...manifest };
687
+ const [resolvedEntrypoints, exports] = getExports({
688
+ entrypoints,
689
+ pkgIsModule,
690
+ config: loadConfig(dir),
691
+ dir,
692
+ noFilter: true
693
+ });
694
+ newManifest.exports = {
695
+ ...resolvedEntrypoints,
696
+ ...exports
697
+ };
698
+ return [dir, newManifest];
699
+ });
700
+ const passArgs = Object.entries(options).reduce((acc, [key, value2]) => {
701
+ if (value2) {
702
+ acc.push(`--${key}`, value2);
703
+ }
704
+ return acc;
705
+ }, []);
706
+ for (const [dir, manifest] of manifests) {
707
+ const oldJSONString = fs.readFileSync(path.join(dir, "package.json"), "utf-8");
708
+ const oldJSON = JSON.parse(oldJSONString) ?? "0.0.0";
709
+ const newVersion = bump(oldJSON.version, bumper);
710
+ const { indent = " " } = detectIndent(oldJSONString);
711
+ const formattingOptions = {
712
+ tabSize: indent.length,
713
+ insertSpaces: true
714
+ };
715
+ let newJSONString = oldJSONString;
716
+ newJSONString = applyEdits(
717
+ newJSONString,
718
+ modify(
719
+ newJSONString,
720
+ ["version"],
721
+ newVersion,
722
+ { formattingOptions }
723
+ )
724
+ );
725
+ for (const [key, value2] of Object.entries(manifest)) {
726
+ if (JSON.stringify(value2) === JSON.stringify(oldJSON[key]))
727
+ continue;
728
+ if (key !== "exports") {
729
+ newJSONString = applyEdits(
730
+ newJSONString,
731
+ modify(
732
+ newJSONString,
733
+ ["publishConfig", key],
734
+ value2,
735
+ { formattingOptions }
736
+ )
737
+ );
738
+ } else {
739
+ const exports = value2;
740
+ for (const [k, v] of Object.entries(exports)) {
741
+ newJSONString = applyEdits(
742
+ newJSONString,
743
+ modify(
744
+ newJSONString,
745
+ ["publishConfig", "exports", k],
746
+ v,
747
+ { formattingOptions }
748
+ )
749
+ );
750
+ }
751
+ const index = exports?.["."];
752
+ const indexPublishConfig = {};
753
+ if (index) {
754
+ switch (typeof index) {
755
+ case "string":
756
+ indexPublishConfig[manifest?.type === "module" ? "module" : "main"] = index;
757
+ break;
758
+ case "object": {
759
+ const indexExports = index;
760
+ indexPublishConfig.main = indexExports["require"] ?? indexExports["default"];
761
+ indexPublishConfig.module = indexExports["import"] ?? indexExports["module"] ?? indexExports["default"];
762
+ break;
763
+ }
764
+ }
765
+ for (const [k, v] of Object.entries(indexPublishConfig)) {
766
+ if (v === void 0)
767
+ continue;
768
+ newJSONString = applyEdits(
769
+ newJSONString,
770
+ modify(
771
+ newJSONString,
772
+ ["publishConfig", k],
773
+ v,
774
+ { formattingOptions }
775
+ )
776
+ );
777
+ }
778
+ }
779
+ }
780
+ }
781
+ try {
782
+ fs.renameSync(path.join(dir, "package.json"), path.join(dir, "package.json.bak"));
783
+ fs.writeFileSync(path.join(dir, "package.json"), newJSONString);
784
+ console.log(newJSONString);
785
+ if (preview) {
786
+ console.warn("preview mode");
787
+ continue;
788
+ }
789
+ childProcess.execSync(["pnpm", "publish", "--access", "public", "--no-git-checks", ...passArgs].join(" "), {
790
+ cwd: dir,
791
+ stdio: "inherit"
792
+ });
793
+ const modifyVersionPackageJSON = applyEdits(oldJSONString, modify(oldJSONString, ["version"], newVersion, {}));
794
+ fs.writeFileSync(path.join(dir, "package.json.bak"), modifyVersionPackageJSON);
795
+ } finally {
796
+ fs.unlinkSync(path.join(dir, "package.json"));
797
+ fs.renameSync(path.join(dir, "package.json.bak"), path.join(dir, "package.json"));
798
+ }
799
+ }
800
+ actionDone();
801
+ });
802
+
803
+ program.parse(process.argv);