jiek 2.0.1 → 2.0.2-alpha.10

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 (48) hide show
  1. package/{dist/cli-only-build.cjs → cli-only-build.cjs} +19 -87
  2. package/{dist/cli-only-build.js → cli-only-build.js} +19 -87
  3. package/{dist/cli.cjs → cli.cjs} +385 -531
  4. package/cli.d.cts +14 -0
  5. package/cli.d.ts +14 -0
  6. package/{dist/cli.js → cli.js} +385 -530
  7. package/{dist/index.d.cts → index.d.cts} +0 -53
  8. package/{dist/index.d.ts → index.d.ts} +0 -53
  9. package/package.json +29 -36
  10. package/{dist/rollup → rollup}/index.cjs +2 -2
  11. package/{dist/rollup → rollup}/index.js +2 -2
  12. package/README.md +0 -78
  13. package/bin/jiek-build.js +0 -16
  14. package/bin/jiek.js +0 -13
  15. package/dist/cli.d.cts +0 -67
  16. package/dist/cli.d.ts +0 -67
  17. package/src/cli-only-build.ts +0 -7
  18. package/src/cli.ts +0 -3
  19. package/src/commands/base.ts +0 -18
  20. package/src/commands/build.ts +0 -462
  21. package/src/commands/descriptions.ts +0 -17
  22. package/src/commands/init.ts +0 -373
  23. package/src/commands/meta.ts +0 -5
  24. package/src/commands/publish.ts +0 -204
  25. package/src/index.ts +0 -8
  26. package/src/inner.ts +0 -11
  27. package/src/rollup/base.ts +0 -137
  28. package/src/rollup/index.ts +0 -565
  29. package/src/rollup/plugins/progress.ts +0 -26
  30. package/src/rollup/plugins/skip.ts +0 -21
  31. package/src/rollup/utils/commonOptions.ts +0 -9
  32. package/src/rollup/utils/externalResolver.ts +0 -35
  33. package/src/rollup/utils/globalResolver.ts +0 -13
  34. package/src/rollup/utils/withMinify.ts +0 -18
  35. package/src/utils/filterSupport.ts +0 -91
  36. package/src/utils/getExports.ts +0 -140
  37. package/src/utils/getRoot.ts +0 -16
  38. package/src/utils/getWD.ts +0 -31
  39. package/src/utils/loadConfig.ts +0 -111
  40. package/src/utils/recusiveListFiles.ts +0 -13
  41. package/src/utils/ts.ts +0 -94
  42. package/src/utils/tsRegister.ts +0 -26
  43. /package/{dist/cli-only-build.d.cts → cli-only-build.d.cts} +0 -0
  44. /package/{dist/cli-only-build.d.ts → cli-only-build.d.ts} +0 -0
  45. /package/{dist/index.cjs → index.cjs} +0 -0
  46. /package/{dist/index.js → index.js} +0 -0
  47. /package/{dist/rollup → rollup}/index.d.cts +0 -0
  48. /package/{dist/rollup → rollup}/index.d.ts +0 -0
@@ -1,20 +1,19 @@
1
1
  'use strict';
2
2
 
3
+ var childProcess = require('node:child_process');
3
4
  var fs = require('node:fs');
4
5
  var path = require('node:path');
6
+ var bumper = require('@jiek/utils/bumper');
5
7
  var commander = require('commander');
6
8
  var detectIndent = require('detect-indent');
7
- var inquirer = require('inquirer');
8
9
  var jsoncParser = require('jsonc-parser');
9
- var require$$0 = require('util');
10
- var require$$0$1 = require('path');
11
- var getWorkspaceDir = require('@jiek/utils/getWorkspaceDir');
12
10
  var node_module = require('node:module');
13
11
  var filterWorkspacePackages = require('@pnpm/filter-workspace-packages');
14
12
  var jsYaml = require('js-yaml');
15
- var childProcess = require('node:child_process');
16
- var bumper = require('@jiek/utils/bumper');
13
+ var getWorkspaceDir = require('@jiek/utils/getWorkspaceDir');
17
14
  var entrypoints = require('@jiek/pkger/entrypoints');
15
+ var require$$0 = require('util');
16
+ var require$$0$1 = require('path');
18
17
  require('jiek/cli-only-build');
19
18
 
20
19
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -38,13 +37,106 @@ function _interopNamespace(e) {
38
37
  return Object.freeze(n);
39
38
  }
40
39
 
40
+ var childProcess__namespace = /*#__PURE__*/_interopNamespace(childProcess);
41
41
  var fs__default = /*#__PURE__*/_interopDefault(fs);
42
42
  var path__default = /*#__PURE__*/_interopDefault(path);
43
43
  var detectIndent__default = /*#__PURE__*/_interopDefault(detectIndent);
44
- var inquirer__default = /*#__PURE__*/_interopDefault(inquirer);
45
44
  var require$$0__default = /*#__PURE__*/_interopDefault(require$$0);
46
45
  var require$$0__default$1 = /*#__PURE__*/_interopDefault(require$$0$1);
47
- var childProcess__namespace = /*#__PURE__*/_interopNamespace(childProcess);
46
+
47
+ let root;
48
+ function getRoot() {
49
+ if (root)
50
+ return root;
51
+ const rootOption = commander.program.getOptionValue("root");
52
+ root = rootOption ? path__default.default.isAbsolute(rootOption) ? rootOption : path__default.default.resolve(process.cwd(), rootOption) : void 0;
53
+ return root;
54
+ }
55
+
56
+ let wd;
57
+ let notWorkspace = false;
58
+ function getWD() {
59
+ if (wd)
60
+ return { wd, notWorkspace };
61
+ const root = getRoot();
62
+ if (root !== void 0) {
63
+ const isWorkspace = getWorkspaceDir.isWorkspaceDir(root, type);
64
+ notWorkspace = !isWorkspace;
65
+ wd = root;
66
+ return { wd, notWorkspace };
67
+ }
68
+ try {
69
+ wd = getWorkspaceDir.getWorkspaceDir(type);
70
+ } catch (e) {
71
+ if ("message" in e && e.message === "workspace root not found") {
72
+ wd = root;
73
+ notWorkspace = true;
74
+ } else {
75
+ throw e;
76
+ }
77
+ }
78
+ return { wd, notWorkspace };
79
+ }
80
+
81
+ let type = "";
82
+ try {
83
+ const require$1 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href)));
84
+ require$1.resolve("@pnpm/filter-workspace-packages");
85
+ type = "pnpm";
86
+ } catch {
87
+ }
88
+ async function getSelectedProjectsGraph(filter = commander.program.getOptionValue("filter")) {
89
+ let root = getRoot();
90
+ const { wd, notWorkspace } = getWD();
91
+ if (notWorkspace) {
92
+ return {
93
+ wd,
94
+ root,
95
+ value: {
96
+ [wd]: JSON.parse(fs__default.default.readFileSync(path__default.default.resolve(wd, "package.json"), "utf-8"))
97
+ }
98
+ };
99
+ }
100
+ if (type === "pnpm") {
101
+ const pnpmWorkspaceFilePath = path__default.default.resolve(wd, "pnpm-workspace.yaml");
102
+ const pnpmWorkspaceFileContent = fs__default.default.readFileSync(pnpmWorkspaceFilePath, "utf-8");
103
+ const pnpmWorkspace = jsYaml.load(pnpmWorkspaceFileContent);
104
+ if (root === wd && !filter) {
105
+ throw new Error("root path is workspace root, please provide a filter");
106
+ }
107
+ if (root === void 0) {
108
+ root = process.cwd();
109
+ }
110
+ if (root !== wd && !filter) {
111
+ const packageJSONIsExist = fs__default.default.existsSync(path__default.default.resolve(root, "package.json"));
112
+ if (!packageJSONIsExist) {
113
+ throw new Error("root path is not workspace root, please provide a filter");
114
+ }
115
+ const packageJSON = JSON.parse(fs__default.default.readFileSync(path__default.default.resolve(root, "package.json"), "utf-8"));
116
+ if (!packageJSON.name) {
117
+ throw new Error("root path is not workspace root, please provide a filter");
118
+ }
119
+ filter = packageJSON.name;
120
+ }
121
+ const { selectedProjectsGraph } = await filterWorkspacePackages.filterPackagesFromDir(wd, [{
122
+ filter: filter ?? "",
123
+ followProdDepsOnly: true
124
+ }], {
125
+ prefix: root,
126
+ workspaceDir: wd,
127
+ patterns: pnpmWorkspace.packages
128
+ });
129
+ return {
130
+ wd,
131
+ root,
132
+ value: Object.entries(selectedProjectsGraph).reduce((acc, [key, value]) => {
133
+ acc[key] = value.package.manifest;
134
+ return acc;
135
+ }, {})
136
+ };
137
+ }
138
+ throw new Error(`not supported package manager ${type}`);
139
+ }
48
140
 
49
141
  var utils$1 = {};
50
142
 
@@ -4152,98 +4244,94 @@ function requireMicromatch () {
4152
4244
 
4153
4245
  var micromatchExports = requireMicromatch();
4154
4246
 
4155
- let root;
4156
- function getRoot() {
4157
- if (root)
4158
- return root;
4159
- const rootOption = commander.program.getOptionValue("root");
4160
- root = rootOption ? path__default.default.isAbsolute(rootOption) ? rootOption : path__default.default.resolve(process.cwd(), rootOption) : void 0;
4161
- return root;
4162
- }
4163
-
4164
- let type = "";
4165
- try {
4166
- const require$1 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href)));
4167
- require$1.resolve("@pnpm/filter-workspace-packages");
4168
- type = "pnpm";
4169
- } catch {
4170
- }
4171
- async function getSelectedProjectsGraph(filter = commander.program.getOptionValue("filter")) {
4172
- let root = getRoot();
4173
- const { wd, notWorkspace } = getWD();
4174
- if (notWorkspace) {
4175
- return {
4176
- wd,
4177
- root,
4178
- value: {
4179
- [wd]: JSON.parse(fs__default.default.readFileSync(path__default.default.resolve(wd, "package.json"), "utf-8"))
4180
- }
4181
- };
4247
+ const intersection = (a, b) => new Set([...a].filter((i) => b.has(i)));
4248
+ const {
4249
+ JIEK_OUT_DIR
4250
+ } = process.env;
4251
+ const OUTDIR = JIEK_OUT_DIR ?? "dist";
4252
+ function getOutDirs({
4253
+ cwd = process.cwd(),
4254
+ defaultOutdir = OUTDIR,
4255
+ config,
4256
+ pkgName
4257
+ }) {
4258
+ const { build = {} } = config ?? {};
4259
+ const outdir = build?.output?.dir;
4260
+ function resolveOutdir(type) {
4261
+ const dir = (typeof outdir === "object" ? outdir[type] ?? outdir[{
4262
+ js: "dts",
4263
+ dts: "js"
4264
+ }[type]] : outdir) ?? defaultOutdir;
4265
+ return (path.isAbsolute(dir) ? dir : `./${path.relative(cwd, path.resolve(cwd, dir))}`).replace("{{PKG_NAME}}", pkgName);
4182
4266
  }
4183
- if (type === "pnpm") {
4184
- const pnpmWorkspaceFilePath = path__default.default.resolve(wd, "pnpm-workspace.yaml");
4185
- const pnpmWorkspaceFileContent = fs__default.default.readFileSync(pnpmWorkspaceFilePath, "utf-8");
4186
- const pnpmWorkspace = jsYaml.load(pnpmWorkspaceFileContent);
4187
- if (root === wd && !filter) {
4188
- throw new Error("root path is workspace root, please provide a filter");
4189
- }
4190
- if (root === void 0) {
4191
- root = process.cwd();
4192
- }
4193
- if (root !== wd && !filter) {
4194
- const packageJSONIsExist = fs__default.default.existsSync(path__default.default.resolve(root, "package.json"));
4195
- if (!packageJSONIsExist) {
4196
- throw new Error("root path is not workspace root, please provide a filter");
4197
- }
4198
- const packageJSON = JSON.parse(fs__default.default.readFileSync(path__default.default.resolve(root, "package.json"), "utf-8"));
4199
- if (!packageJSON.name) {
4200
- throw new Error("root path is not workspace root, please provide a filter");
4267
+ return {
4268
+ js: resolveOutdir("js"),
4269
+ dts: resolveOutdir("dts")
4270
+ };
4271
+ }
4272
+ function getExports({
4273
+ entrypoints: entrypoints$1,
4274
+ pkgName,
4275
+ pkgIsModule,
4276
+ entries,
4277
+ config,
4278
+ dir,
4279
+ defaultOutdir = OUTDIR,
4280
+ // FIXME dts support
4281
+ outdir = getOutDirs({ pkgName, defaultOutdir, config, cwd: dir }).js,
4282
+ noFilter,
4283
+ isPublish
4284
+ }) {
4285
+ const {
4286
+ build = {},
4287
+ publish: {
4288
+ withSuffix = false,
4289
+ withSource = true
4290
+ } = {}
4291
+ } = config ?? {};
4292
+ const {
4293
+ crossModuleConvertor = true
4294
+ } = build;
4295
+ const [, resolvedEntrypoints] = entrypoints.resolveEntrypoints(entrypoints$1);
4296
+ if (entries) {
4297
+ Object.entries(resolvedEntrypoints).forEach(([key]) => {
4298
+ if (!entries.some((e) => micromatchExports.isMatch(key, e, { matchBase: true }))) {
4299
+ delete resolvedEntrypoints[key];
4201
4300
  }
4202
- filter = packageJSON.name;
4203
- }
4204
- const { selectedProjectsGraph } = await filterWorkspacePackages.filterPackagesFromDir(wd, [{
4205
- filter: filter ?? "",
4206
- followProdDepsOnly: true
4207
- }], {
4208
- prefix: root,
4209
- workspaceDir: wd,
4210
- patterns: pnpmWorkspace.packages
4211
4301
  });
4212
- return {
4213
- wd,
4214
- root,
4215
- value: Object.entries(selectedProjectsGraph).reduce((acc, [key, value]) => {
4216
- acc[key] = value.package.manifest;
4217
- return acc;
4218
- }, {})
4219
- };
4220
- }
4221
- throw new Error(`not supported package manager ${type}`);
4222
- }
4223
-
4224
- let wd;
4225
- let notWorkspace = false;
4226
- function getWD() {
4227
- if (wd)
4228
- return { wd, notWorkspace };
4229
- const root = getRoot();
4230
- if (root !== void 0) {
4231
- const isWorkspace = getWorkspaceDir.isWorkspaceDir(root, type);
4232
- notWorkspace = !isWorkspace;
4233
- wd = root;
4234
- return { wd, notWorkspace };
4235
4302
  }
4236
- try {
4237
- wd = getWorkspaceDir.getWorkspaceDir(type);
4238
- } catch (e) {
4239
- if ("message" in e && e.message === "workspace root not found") {
4240
- wd = root;
4241
- notWorkspace = true;
4242
- } else {
4243
- throw e;
4303
+ const filteredResolvedEntrypoints = noFilter ? resolvedEntrypoints : entrypoints.filterLeafs(
4304
+ resolvedEntrypoints,
4305
+ {
4306
+ skipValue: [
4307
+ // ignore values that filename starts with `.jk-noentry`
4308
+ /(^|\/)\.jk-noentry/,
4309
+ ...entrypoints.DEFAULT_SKIP_VALUES
4310
+ ]
4244
4311
  }
4245
- }
4246
- return { wd, notWorkspace };
4312
+ );
4313
+ const crossModuleWithConditional = crossModuleConvertor ? {
4314
+ import: (opts) => !pkgIsModule && intersection(
4315
+ new Set(opts.conditionals),
4316
+ /* @__PURE__ */ new Set(["import", "module"])
4317
+ ).size === 0 ? opts.dist.replace(/\.js$/, ".mjs") : false,
4318
+ require: (opts) => pkgIsModule && intersection(
4319
+ new Set(opts.conditionals),
4320
+ /* @__PURE__ */ new Set(["require", "node"])
4321
+ ).size === 0 ? opts.dist.replace(/\.js$/, ".cjs") : false
4322
+ } : {};
4323
+ return [
4324
+ filteredResolvedEntrypoints,
4325
+ entrypoints.entrypoints2Exports(filteredResolvedEntrypoints, {
4326
+ outdir,
4327
+ withSuffix: isPublish ? withSuffix : void 0,
4328
+ withSource: isPublish ? withSource : void 0,
4329
+ withConditional: {
4330
+ ...crossModuleWithConditional
4331
+ }
4332
+ }),
4333
+ outdir
4334
+ ];
4247
4335
  }
4248
4336
 
4249
4337
  const require$2 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href)));
@@ -4352,394 +4440,65 @@ function loadConfig(dirOrOptions) {
4352
4440
  return module.default ?? module;
4353
4441
  }
4354
4442
 
4355
- const PACKAGE_JSON_TEMPLATE = `{
4356
- "name": "",
4357
- "version": "0.0.1",
4358
- "description": "",
4359
- "license": "",
4360
- "author": "",
4361
- "files": ["dist"],
4362
- "exports": {
4363
- ".": "./src/index.ts"
4364
- },
4365
- "scripts": {
4366
- },
4367
- "homepage": "",
4368
- "repository": "",
4369
- "bugs": ""
4370
- }`.trimStart();
4371
- const README_TEMPLATE = `# $name
4372
-
4373
- ## Installation
4374
-
4375
- \`\`\`bash
4376
- npm install $name
4377
- # or
4378
- pnpm install $name
4379
- # or
4380
- yarn add $name
4381
- \`\`\`
4382
-
4383
- ## Usage
4384
-
4385
-
4386
- ## License
4387
-
4388
- $license
4389
- `.trimStart();
4390
- function getTemplateStr(wd, template) {
4391
- let templateString = template ?? PACKAGE_JSON_TEMPLATE;
4392
- let isTemplateFile = false;
4393
- try {
4394
- if (template)
4395
- JSON.parse(template);
4396
- } catch (e) {
4397
- isTemplateFile = true;
4398
- }
4399
- if (isTemplateFile) {
4400
- const templatePath = path__default.default.resolve(wd, template);
4401
- templateString = fs__default.default.readFileSync(templatePath, "utf-8");
4402
- }
4403
- return templateString;
4404
- }
4405
- const wdCache = /* @__PURE__ */ new Map();
4406
- function getWDPackageJSONFiled(wd, field) {
4407
- if (wdCache.has(wd)) {
4408
- return wdCache.get(wd)[field];
4409
- }
4410
- const packageJSONPath = path__default.default.resolve(wd, "package.json");
4411
- const packageJSON = JSON.parse(fs__default.default.readFileSync(packageJSONPath, "utf-8"));
4412
- wdCache.set(wd, packageJSON);
4413
- return packageJSON[field];
4414
- }
4415
- async function getName(named, name, {
4416
- wd,
4417
- cwd,
4418
- workspaceName
4419
- }) {
4420
- const relativePath = cwd.replace(`${wd}/`, "");
4421
- let basename = path__default.default.basename(cwd);
4422
- if (typeof named === "function") {
4423
- return named(name, {
4424
- full: wd,
4425
- relative: cwd
4426
- });
4427
- }
4428
- let isParentMatched = false;
4429
- let matchedKey;
4430
- let matchedRule;
4431
- if (typeof named === "object") {
4432
- const isWD = cwd === wd;
4433
- if (isWD) {
4434
- const { rule } = await inquirer__default.default.prompt({
4435
- type: "list",
4436
- name: "rule",
4437
- message: "choose a rule",
4438
- default: "default",
4439
- choices: ["default"].concat(Object.keys(named))
4440
- });
4441
- if (rule !== "default") {
4442
- matchedKey = rule;
4443
- matchedRule = named[rule];
4444
- }
4445
- } else {
4446
- for (const [key, value] of Object.entries(named)) {
4447
- if (micromatchExports.isMatch(relativePath, key)) {
4448
- matchedKey = key;
4449
- matchedRule = value;
4450
- break;
4451
- }
4452
- if (micromatchExports.isMatch(`${relativePath}/jiek_ignore_dont_use_same_file_name`, key)) {
4453
- isParentMatched = true;
4454
- matchedKey = key;
4455
- matchedRule = value;
4456
- break;
4457
- }
4458
- }
4459
- }
4460
- }
4461
- if (!matchedRule) {
4462
- matchedKey = "packages/*";
4463
- matchedRule = `@${workspaceName}/$basename`;
4464
- }
4465
- if (!matchedRule) {
4466
- throw new Error("no matched rule");
4467
- }
4468
- if (!name && isParentMatched) {
4469
- basename = await inquirer__default.default.prompt({
4470
- type: "input",
4471
- name: "name",
4472
- message: `the matched rule is \`${String(matchedRule)}\`, please input the basename
4473
- `
4474
- }).then(({ name: name2 }) => name2);
4475
- }
4476
- if (typeof matchedRule === "function") {
4477
- return matchedRule(name, {
4478
- full: wd,
4479
- relative: cwd,
4480
- basename
4481
- });
4482
- }
4483
- if (typeof matchedRule === "string") {
4484
- const dirName = name ?? basename;
4485
- return [
4486
- matchedRule.replace(/\$basename/g, dirName),
4487
- matchedKey?.replace(/\/\*$/g, `/${dirName}`)
4488
- ];
4489
- }
4490
- throw new Error("no matched rule");
4491
- }
4492
- commander.program.command("init [name]").option("-t, --template <template>", "the package.json template file path or file content").action(async () => {
4493
- const [, name] = commander.program.args;
4494
- const cwd = process.cwd();
4495
- const { init = {} } = loadConfig() ?? {};
4496
- const { wd } = getWD();
4497
- const workspaceName = path__default.default.basename(wd);
4498
- const {
4499
- named,
4500
- template,
4501
- bug = {},
4502
- readme: _readme = README_TEMPLATE,
4503
- readmeTemplate
4504
- } = init;
4505
- const resolvedBug = {
4506
- template: "bug_report.yml",
4507
- labels: ["bug"],
4508
- ...bug
4509
- };
4510
- let readme = _readme;
4511
- if (readmeTemplate) {
4512
- const readmeTemplatePath = path__default.default.resolve(wd, readmeTemplate);
4513
- readme = fs__default.default.readFileSync(readmeTemplatePath, "utf-8");
4514
- }
4515
- const templateString = getTemplateStr(wd, template);
4516
- const { indent = " " } = detectIndent__default.default(templateString);
4517
- const formattingOptions = {
4518
- tabSize: indent.length,
4519
- insertSpaces: true
4520
- };
4521
- const passFields = [
4522
- "license",
4523
- "author"
4524
- ];
4525
- let newJSONString = templateString;
4526
- for (const field of passFields) {
4527
- newJSONString = jsoncParser.applyEdits(
4528
- newJSONString,
4529
- jsoncParser.modify(
4530
- newJSONString,
4531
- [field],
4532
- getWDPackageJSONFiled(wd, field),
4533
- { formattingOptions }
4534
- )
4535
- );
4536
- }
4537
- let [pkgName, pkgDir] = await getName(named, name, {
4538
- wd,
4539
- cwd,
4540
- workspaceName
4541
- });
4542
- if (!pkgDir) {
4543
- const { dir } = await inquirer__default.default.prompt({
4544
- type: "input",
4545
- name: "dir",
4546
- message: "package directory",
4547
- default: name
4548
- });
4549
- pkgDir = dir;
4550
- }
4551
- if (!pkgName) {
4552
- const { name: inputName } = await inquirer__default.default.prompt({
4553
- type: "input",
4554
- name: "name",
4555
- message: "package name",
4556
- default: name
4557
- });
4558
- pkgName = inputName;
4559
- }
4560
- newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(newJSONString, ["name"], pkgName, { formattingOptions }));
4561
- let pkgRepo = getWDPackageJSONFiled(wd, "repository");
4562
- if (typeof pkgRepo === "string") {
4563
- pkgRepo = {
4564
- type: "git",
4565
- url: pkgRepo,
4566
- directory: pkgDir
4567
- };
4568
- }
4569
- newJSONString = jsoncParser.applyEdits(
4570
- newJSONString,
4571
- jsoncParser.modify(
4572
- newJSONString,
4573
- ["repository"],
4574
- pkgRepo,
4575
- { formattingOptions }
4576
- )
4577
- );
4578
- const homepage = `${pkgRepo?.url}/blob/master/${pkgDir}/README.md`;
4579
- newJSONString = jsoncParser.applyEdits(
4580
- newJSONString,
4581
- jsoncParser.modify(
4582
- newJSONString,
4583
- ["homepage"],
4584
- homepage,
4585
- { formattingOptions }
4586
- )
4587
- );
4588
- let labels = resolvedBug.labels;
4589
- if (typeof labels === "function") {
4590
- labels = labels({
4591
- name: pkgName,
4592
- dir: pkgDir
4593
- });
4594
- }
4595
- labels.push(`scope:${pkgName}`);
4596
- const bugs = `${pkgRepo?.url}/issues/new?template=${resolvedBug.template}&labels=${labels.join(",")}`;
4597
- newJSONString = jsoncParser.applyEdits(
4598
- newJSONString,
4599
- jsoncParser.modify(
4600
- newJSONString,
4601
- ["bugs"],
4602
- bugs,
4603
- { formattingOptions }
4604
- )
4605
- );
4606
- function pkgDirTo(to) {
4607
- if (!pkgDir)
4608
- throw new Error("pkgDir is not defined");
4609
- return path__default.default.resolve(pkgDir, to);
4610
- }
4611
- if (!fs__default.default.existsSync(pkgDir))
4612
- fs__default.default.mkdirSync(pkgDir);
4613
- const pkgJSONFilePath = pkgDirTo("package.json");
4614
- if (fs__default.default.existsSync(pkgJSONFilePath)) {
4615
- throw new Error("package.json already exists");
4616
- }
4617
- fs__default.default.writeFileSync(pkgJSONFilePath, newJSONString);
4618
- console.log(newJSONString, "written to", pkgJSONFilePath);
4619
- const license = getWDPackageJSONFiled(wd, "license");
4620
- const readmeFilePath = pkgDirTo("README.md");
4621
- if (typeof readme === "function") {
4622
- readme = readme({
4623
- dir: pkgDir,
4624
- packageJson: JSON.parse(newJSONString)
4625
- });
4626
- }
4627
- const readmeContent = readme.replace(/\$name/g, pkgName).replace(/\$license/g, license);
4628
- fs__default.default.writeFileSync(readmeFilePath, readmeContent);
4629
- });
4630
-
4631
- let resolve;
4632
- function actionDone() {
4633
- resolve();
4634
- }
4635
- function actionRestore() {
4636
- new Promise((r) => resolve = r);
4637
- }
4638
-
4639
- const intersection = (a, b) => new Set([...a].filter((i) => b.has(i)));
4640
- const {
4641
- JIEK_OUT_DIR
4642
- } = process.env;
4643
- const OUTDIR = JIEK_OUT_DIR ?? "dist";
4644
- function getOutDirs({
4645
- cwd = process.cwd(),
4646
- defaultOutdir = OUTDIR,
4647
- config,
4648
- pkgName
4649
- }) {
4650
- const { build = {} } = config ?? {};
4651
- const outdir = build?.output?.dir;
4652
- function resolveOutdir(type) {
4653
- const dir = (typeof outdir === "object" ? outdir[type] ?? outdir[{
4654
- js: "dts",
4655
- dts: "js"
4656
- }[type]] : outdir) ?? defaultOutdir;
4657
- return (path.isAbsolute(dir) ? dir : `./${path.relative(cwd, path.resolve(cwd, dir))}`).replace("{{PKG_NAME}}", pkgName);
4658
- }
4659
- return {
4660
- js: resolveOutdir("js"),
4661
- dts: resolveOutdir("dts")
4662
- };
4663
- }
4664
- function getExports({
4665
- entrypoints: entrypoints$1,
4666
- pkgName,
4667
- pkgIsModule,
4668
- entries,
4669
- config,
4670
- dir,
4671
- defaultOutdir = OUTDIR,
4672
- // FIXME dts support
4673
- outdir = getOutDirs({ pkgName, defaultOutdir, config, cwd: dir }).js,
4674
- noFilter,
4675
- isPublish
4676
- }) {
4677
- const {
4678
- build = {},
4679
- publish: {
4680
- withSuffix = false,
4681
- withSource = true
4682
- } = {}
4683
- } = config ?? {};
4684
- const {
4685
- crossModuleConvertor = true
4686
- } = build;
4687
- const [, resolvedEntrypoints] = entrypoints.resolveEntrypoints(entrypoints$1);
4688
- if (entries) {
4689
- Object.entries(resolvedEntrypoints).forEach(([key]) => {
4690
- if (!entries.some((e) => micromatchExports.isMatch(key, e, { matchBase: true }))) {
4691
- delete resolvedEntrypoints[key];
4692
- }
4693
- });
4694
- }
4695
- const filteredResolvedEntrypoints = noFilter ? resolvedEntrypoints : entrypoints.filterLeafs(
4696
- resolvedEntrypoints,
4697
- {
4698
- skipValue: [
4699
- // ignore values that filename starts with `.jk-noentry`
4700
- /(^|\/)\.jk-noentry/,
4701
- ...entrypoints.DEFAULT_SKIP_VALUES
4702
- ]
4703
- }
4704
- );
4705
- const crossModuleWithConditional = crossModuleConvertor ? {
4706
- import: (opts) => !pkgIsModule && intersection(
4707
- new Set(opts.conditionals),
4708
- /* @__PURE__ */ new Set(["import", "module"])
4709
- ).size === 0 ? opts.dist.replace(/\.js$/, ".mjs") : false,
4710
- require: (opts) => pkgIsModule && intersection(
4711
- new Set(opts.conditionals),
4712
- /* @__PURE__ */ new Set(["require", "node"])
4713
- ).size === 0 ? opts.dist.replace(/\.js$/, ".cjs") : false
4714
- } : {};
4715
- return [
4716
- filteredResolvedEntrypoints,
4717
- entrypoints.entrypoints2Exports(filteredResolvedEntrypoints, {
4718
- outdir,
4719
- withSuffix: isPublish ? withSuffix : void 0,
4720
- withSource: isPublish ? withSource : void 0,
4721
- withConditional: {
4722
- ...crossModuleWithConditional
4723
- }
4724
- }),
4725
- outdir
4726
- ];
4727
- }
4728
-
4729
4443
  const outdirDescription = `
4730
4444
  The output directory of the build, which relative to the target subpackage root directory.
4731
4445
  Support with variables: 'PKG_NAME',
4732
4446
  .e.g. 'dist/{{PKG_NAME}}'.
4733
4447
  `.trim();
4734
4448
 
4735
- commander.program.command("publish").aliases(["pub", "p"]).option("-b, --bumper <bumper>", "bump version", "patch").option("-no-b, --no-bumper", "no bump version").option("-o, --outdir <OUTDIR>", outdirDescription, String, "dist").option("-s, --silent", "no output").option("-p, --preview", "preview publish").action(async ({ outdir, preview, silent, bumper: bumper$1, ...options }) => {
4736
- actionRestore();
4449
+ const description = `
4450
+ Publish package to npm registry, and auto generate exports field and other fields in published package.json.
4451
+ If you want to through the options to the \`pnpm publish\` command, you can pass the options after '--'.
4452
+ `.trim();
4453
+ async function forEachSelectedProjectsGraphEntries(callback) {
4737
4454
  const { value = {} } = await getSelectedProjectsGraph() ?? {};
4738
4455
  const selectedProjectsGraphEntries = Object.entries(value);
4739
4456
  if (selectedProjectsGraphEntries.length === 0) {
4740
4457
  throw new Error("no packages selected");
4741
4458
  }
4742
- const manifests = selectedProjectsGraphEntries.map(([dir, manifest]) => {
4459
+ for (const [dir, manifest] of selectedProjectsGraphEntries) {
4460
+ callback(dir, manifest);
4461
+ }
4462
+ }
4463
+ commander.program.command("publish").description(description).aliases(["pub", "p"]).option("-b, --bumper <bumper>", "bump version", "patch").option("-no-b, --no-bumper", "no bump version").option("-o, --outdir <OUTDIR>", outdirDescription, String, "dist").action(async ({ outdir, bumper: bumper$1 }) => {
4464
+ let shouldPassThrough = false;
4465
+ const passThroughOptions = process.argv.reduce(
4466
+ (acc, value) => {
4467
+ if (shouldPassThrough) {
4468
+ acc.push(value);
4469
+ }
4470
+ if (value === "--") {
4471
+ shouldPassThrough = true;
4472
+ }
4473
+ return acc;
4474
+ },
4475
+ []
4476
+ );
4477
+ await forEachSelectedProjectsGraphEntries((dir) => {
4478
+ const args = ["pnpm", "publish", "--access", "public", "--no-git-checks"];
4479
+ if (bumper$1 && bumper.TAGS.includes(bumper$1)) {
4480
+ args.push("--tag", bumper$1);
4481
+ }
4482
+ args.push(...passThroughOptions);
4483
+ childProcess__namespace.execSync(args.join(" "), {
4484
+ cwd: dir,
4485
+ stdio: "inherit",
4486
+ env: {
4487
+ ...process.env,
4488
+ JIEK_PUBLISH_OUTDIR: JSON.stringify(outdir),
4489
+ JIEK_PUBLISH_BUMPER: JSON.stringify(bumper$1)
4490
+ }
4491
+ });
4492
+ });
4493
+ });
4494
+ async function prepublish() {
4495
+ const {
4496
+ JIEK_PUBLISH_OUTDIR: outdirEnv,
4497
+ JIEK_PUBLISH_BUMPER: bumperEnv
4498
+ } = process.env;
4499
+ const outdir = outdirEnv ? JSON.parse(outdirEnv) : "dist";
4500
+ const bumper$1 = bumperEnv ? JSON.parse(bumperEnv) : false;
4501
+ const generateNewManifest = (dir, manifest) => {
4743
4502
  const { name, type, exports: entrypoints = {} } = manifest;
4744
4503
  if (!name) {
4745
4504
  throw new Error(`package.json in ${dir} must have a name field`);
@@ -4760,35 +4519,38 @@ commander.program.command("publish").aliases(["pub", "p"]).option("-b, --bumper
4760
4519
  ...resolvedEntrypoints,
4761
4520
  ...exports
4762
4521
  };
4763
- return [dir, newManifest, resolvedOutdir];
4764
- });
4765
- const passArgs = Object.entries(options).reduce((acc, [key, value2]) => {
4766
- if (value2) {
4767
- acc.push(`--${key}`, value2);
4768
- }
4769
- return acc;
4770
- }, []);
4771
- for (const [dir, manifest, resolvedOutdir] of manifests) {
4772
- const oldJSONString = fs__default.default.readFileSync(path__default.default.join(dir, "package.json"), "utf-8");
4773
- const oldJSON = JSON.parse(oldJSONString) ?? "0.0.0";
4774
- const newVersion = bumper$1 ? bumper.bump(oldJSON.version, bumper$1) : oldJSON.version;
4775
- const { indent = " " } = detectIndent__default.default(oldJSONString);
4776
- const formattingOptions = {
4777
- tabSize: indent.length,
4778
- insertSpaces: true
4779
- };
4522
+ return [newManifest, resolvedOutdir];
4523
+ };
4524
+ const generateNewPackageJSONString = ({
4525
+ oldJSONString,
4526
+ oldJSON,
4527
+ manifest,
4528
+ formattingOptions
4529
+ }) => {
4780
4530
  let newJSONString = oldJSONString;
4781
4531
  newJSONString = jsoncParser.applyEdits(
4782
4532
  newJSONString,
4783
4533
  jsoncParser.modify(
4784
4534
  newJSONString,
4785
- ["version"],
4786
- newVersion,
4535
+ ["publishConfig", "typesVersions"],
4536
+ {
4537
+ "<5.0": {
4538
+ "*": [
4539
+ "*",
4540
+ `./*`,
4541
+ `./*/index.d.ts`,
4542
+ `./*/index.d.mts`,
4543
+ `./*/index.d.cts`
4544
+ ]
4545
+ }
4546
+ },
4787
4547
  { formattingOptions }
4788
4548
  )
4789
4549
  );
4790
- for (const [key, value2] of Object.entries(manifest)) {
4791
- if (JSON.stringify(value2) === JSON.stringify(oldJSON[key]))
4550
+ for (const [key, value] of Object.entries(manifest)) {
4551
+ if (key === "version")
4552
+ continue;
4553
+ if (JSON.stringify(value) === JSON.stringify(oldJSON[key]))
4792
4554
  continue;
4793
4555
  if (key !== "exports") {
4794
4556
  newJSONString = jsoncParser.applyEdits(
@@ -4796,12 +4558,12 @@ commander.program.command("publish").aliases(["pub", "p"]).option("-b, --bumper
4796
4558
  jsoncParser.modify(
4797
4559
  newJSONString,
4798
4560
  ["publishConfig", key],
4799
- value2,
4561
+ value,
4800
4562
  { formattingOptions }
4801
4563
  )
4802
4564
  );
4803
4565
  } else {
4804
- const exports = value2;
4566
+ const exports = value;
4805
4567
  for (const [k, v] of Object.entries(exports)) {
4806
4568
  newJSONString = jsoncParser.applyEdits(
4807
4569
  newJSONString,
@@ -4843,46 +4605,138 @@ commander.program.command("publish").aliases(["pub", "p"]).option("-b, --bumper
4843
4605
  }
4844
4606
  }
4845
4607
  }
4846
- newJSONString = jsoncParser.applyEdits(
4847
- newJSONString,
4848
- jsoncParser.modify(
4849
- newJSONString,
4850
- ["publishConfig", "typesVersions"],
4851
- {
4852
- "<5.0": {
4853
- "*": [
4854
- "*",
4855
- `${resolvedOutdir}/*`,
4856
- `${resolvedOutdir}/*/index.d.ts`,
4857
- `${resolvedOutdir}/*/index.d.mts`,
4858
- `${resolvedOutdir}/*/index.d.cts`
4859
- ]
4860
- }
4608
+ if (oldJSON["peerDependencies"]) {
4609
+ const peerDependenciesMeta = Object.keys(oldJSON["peerDependencies"]).reduce(
4610
+ (acc, key) => {
4611
+ acc[key] = { optional: true };
4612
+ return acc;
4861
4613
  },
4862
- { formattingOptions }
4863
- )
4614
+ {}
4615
+ );
4616
+ newJSONString = jsoncParser.applyEdits(
4617
+ newJSONString,
4618
+ jsoncParser.modify(
4619
+ newJSONString,
4620
+ ["peerDependenciesMeta"],
4621
+ peerDependenciesMeta,
4622
+ { formattingOptions }
4623
+ )
4624
+ );
4625
+ }
4626
+ if (oldJSON["files"]) {
4627
+ newJSONString = jsoncParser.applyEdits(
4628
+ newJSONString,
4629
+ jsoncParser.modify(
4630
+ newJSONString,
4631
+ ["files"],
4632
+ void 0,
4633
+ { formattingOptions }
4634
+ )
4635
+ );
4636
+ }
4637
+ return newJSONString;
4638
+ };
4639
+ await forEachSelectedProjectsGraphEntries((dir, originalManifest) => {
4640
+ const [manifest, resolvedOutdir] = generateNewManifest(dir, originalManifest);
4641
+ const resolveByDir = (...paths) => path__default.default.resolve(dir, ...paths);
4642
+ const oldJSONString = fs__default.default.readFileSync(resolveByDir("package.json"), "utf-8");
4643
+ const oldJSON = JSON.parse(oldJSONString) ?? "0.0.0";
4644
+ if (typeof oldJSON.version !== "string") {
4645
+ throw new Error(`${dir}/package.json must have a version field with a string value`);
4646
+ }
4647
+ const { indent = " " } = detectIndent__default.default(oldJSONString);
4648
+ const formattingOptions = {
4649
+ tabSize: indent.length,
4650
+ insertSpaces: true
4651
+ };
4652
+ const newVersion = bumper$1 ? bumper.bump(oldJSON.version, bumper$1) : oldJSON.version;
4653
+ const modifyVersionPackageJSON = jsoncParser.applyEdits(
4654
+ oldJSONString,
4655
+ jsoncParser.modify(oldJSONString, ["version"], newVersion, { formattingOptions })
4864
4656
  );
4865
- try {
4866
- fs__default.default.renameSync(path__default.default.join(dir, "package.json"), path__default.default.join(dir, "package.json.bak"));
4867
- fs__default.default.writeFileSync(path__default.default.join(dir, "package.json"), newJSONString);
4868
- !silent && console.log(newJSONString);
4869
- if (preview) {
4870
- continue;
4657
+ const newJSONString = generateNewPackageJSONString({
4658
+ oldJSONString: modifyVersionPackageJSON,
4659
+ oldJSON: {
4660
+ ...oldJSON,
4661
+ version: newVersion
4662
+ },
4663
+ manifest,
4664
+ formattingOptions
4665
+ });
4666
+ const withPublishConfigDirectoryOldJSONString = jsoncParser.applyEdits(
4667
+ modifyVersionPackageJSON,
4668
+ jsoncParser.modify(modifyVersionPackageJSON, ["publishConfig", "directory"], resolvedOutdir, { formattingOptions })
4669
+ );
4670
+ if (oldJSON.files) {
4671
+ if (!Array.isArray(oldJSON.files)) {
4672
+ throw new Error(`${dir}/package.json files field must be an array`);
4673
+ }
4674
+ if (Array.isArray(oldJSON.files) && oldJSON.files.every((file) => typeof file !== "string")) {
4675
+ throw new Error(`${dir}/package.json files field must be an array of string`);
4871
4676
  }
4872
- const args = ["pnpm", "publish", "--access", "public", "--no-git-checks", ...passArgs];
4873
- if (bumper$1 && bumper.TAGS.includes(bumper$1)) {
4874
- args.push("--tag", bumper$1);
4677
+ }
4678
+ const resolvedOutdirAbs = resolveByDir(resolvedOutdir);
4679
+ const files = oldJSON.files ?? fs__default.default.readdirSync(resolveByDir(".")).filter((file) => file !== "node_modules" && resolveByDir(file) !== resolvedOutdirAbs);
4680
+ for (const file of files) {
4681
+ const path2 = resolveByDir(file);
4682
+ try {
4683
+ const stat = fs__default.default.statSync(path2);
4684
+ if (stat.isDirectory()) {
4685
+ fs__default.default.symlinkSync(path2, resolveByDir(resolvedOutdir, file), "dir");
4686
+ continue;
4687
+ }
4688
+ if (stat.isFile()) {
4689
+ fs__default.default.symlinkSync(path2, resolveByDir(resolvedOutdir, file), "file");
4690
+ continue;
4691
+ }
4692
+ } catch (e) {
4693
+ console.warn(String(e));
4694
+ continue;
4875
4695
  }
4876
- childProcess__namespace.execSync(args.join(" "), {
4877
- cwd: dir,
4878
- stdio: "inherit"
4879
- });
4880
- const modifyVersionPackageJSON = jsoncParser.applyEdits(oldJSONString, jsoncParser.modify(oldJSONString, ["version"], newVersion, {}));
4881
- fs__default.default.writeFileSync(path__default.default.join(dir, "package.json.bak"), modifyVersionPackageJSON);
4882
- } finally {
4883
- fs__default.default.unlinkSync(path__default.default.join(dir, "package.json"));
4884
- fs__default.default.renameSync(path__default.default.join(dir, "package.json.bak"), path__default.default.join(dir, "package.json"));
4696
+ throw new Error(`file type of ${path2} is not supported`);
4697
+ }
4698
+ if (!fs__default.default.existsSync(resolveByDir(resolvedOutdir))) {
4699
+ fs__default.default.mkdirSync(resolveByDir(resolvedOutdir));
4700
+ }
4701
+ const jiekTempDir = resolveByDir("node_modules/.jiek/.tmp");
4702
+ if (!fs__default.default.existsSync(resolveByDir(jiekTempDir))) {
4703
+ fs__default.default.mkdirSync(resolveByDir(jiekTempDir), { recursive: true });
4704
+ }
4705
+ fs__default.default.writeFileSync(resolveByDir(resolvedOutdir, "package.json"), newJSONString);
4706
+ fs__default.default.writeFileSync(resolveByDir(jiekTempDir, "package.json"), modifyVersionPackageJSON);
4707
+ fs__default.default.writeFileSync(resolveByDir("package.json"), withPublishConfigDirectoryOldJSONString);
4708
+ });
4709
+ }
4710
+ async function postpublish() {
4711
+ await forEachSelectedProjectsGraphEntries((dir) => {
4712
+ const jiekTempDir = path__default.default.resolve(dir, "node_modules/.jiek/.tmp");
4713
+ const packageJSON = path__default.default.resolve(dir, "package.json");
4714
+ const jiekTempPackageJSON = path__default.default.resolve(jiekTempDir, "package.json");
4715
+ if (fs__default.default.existsSync(jiekTempPackageJSON)) {
4716
+ fs__default.default.copyFileSync(jiekTempPackageJSON, packageJSON);
4717
+ fs__default.default.rmSync(jiekTempPackageJSON);
4718
+ console.log(`${dir}/package.json has been restored`);
4719
+ } else {
4720
+ throw new Error(
4721
+ `jiek temp \`${dir}/package.json\` not found, please confirm the jiek pre-publish command has been executed`
4722
+ );
4885
4723
  }
4724
+ });
4725
+ }
4726
+ commander.program.action(async () => {
4727
+ const {
4728
+ npm_lifecycle_event: NPM_LIFECYCLE_EVENT
4729
+ } = process.env;
4730
+ switch (NPM_LIFECYCLE_EVENT) {
4731
+ case "prepublish":
4732
+ await prepublish();
4733
+ break;
4734
+ case "postpublish":
4735
+ await postpublish();
4736
+ break;
4737
+ default:
4738
+ commander.program.help();
4886
4739
  }
4887
- actionDone();
4888
4740
  });
4741
+ commander.program.command("prepublish").action(prepublish);
4742
+ commander.program.command("postpublish").action(postpublish);