jiek 2.0.1 → 2.0.2-alpha.10

Sign up to get free protection for your applications and to get access to all the features.
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,113 @@
1
+ import * as childProcess from 'node:child_process';
1
2
  import fs from 'node:fs';
2
- import path, { isAbsolute, relative, resolve as resolve$1 } from 'node:path';
3
+ import path, { isAbsolute, relative, resolve } from 'node:path';
4
+ import { TAGS, bump } from '@jiek/utils/bumper';
3
5
  import { program } from 'commander';
4
6
  import detectIndent from 'detect-indent';
5
- import inquirer from 'inquirer';
6
7
  import { applyEdits, modify } from 'jsonc-parser';
7
- import require$$0 from 'util';
8
- import require$$0$1 from 'path';
9
- import { isWorkspaceDir, getWorkspaceDir } from '@jiek/utils/getWorkspaceDir';
10
8
  import { createRequire } from 'node:module';
11
9
  import { filterPackagesFromDir } from '@pnpm/filter-workspace-packages';
12
10
  import { load } from 'js-yaml';
13
- import * as childProcess from 'node:child_process';
14
- import { bump, TAGS } from '@jiek/utils/bumper';
11
+ import { isWorkspaceDir, getWorkspaceDir } from '@jiek/utils/getWorkspaceDir';
15
12
  import { resolveEntrypoints, filterLeafs, DEFAULT_SKIP_VALUES, entrypoints2Exports } from '@jiek/pkger/entrypoints';
13
+ import require$$0 from 'util';
14
+ import require$$0$1 from 'path';
16
15
  import 'jiek/cli-only-build';
17
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
+ const require = createRequire(import.meta.url);
54
+ require.resolve("@pnpm/filter-workspace-packages");
55
+ type = "pnpm";
56
+ } catch {
57
+ }
58
+ async function getSelectedProjectsGraph(filter = program.getOptionValue("filter")) {
59
+ let root = getRoot();
60
+ const { wd, notWorkspace } = getWD();
61
+ if (notWorkspace) {
62
+ return {
63
+ wd,
64
+ root,
65
+ value: {
66
+ [wd]: JSON.parse(fs.readFileSync(path.resolve(wd, "package.json"), "utf-8"))
67
+ }
68
+ };
69
+ }
70
+ if (type === "pnpm") {
71
+ const pnpmWorkspaceFilePath = path.resolve(wd, "pnpm-workspace.yaml");
72
+ const pnpmWorkspaceFileContent = fs.readFileSync(pnpmWorkspaceFilePath, "utf-8");
73
+ const pnpmWorkspace = load(pnpmWorkspaceFileContent);
74
+ if (root === wd && !filter) {
75
+ throw new Error("root path is workspace root, please provide a filter");
76
+ }
77
+ if (root === void 0) {
78
+ root = process.cwd();
79
+ }
80
+ if (root !== wd && !filter) {
81
+ const packageJSONIsExist = fs.existsSync(path.resolve(root, "package.json"));
82
+ if (!packageJSONIsExist) {
83
+ throw new Error("root path is not workspace root, please provide a filter");
84
+ }
85
+ const packageJSON = JSON.parse(fs.readFileSync(path.resolve(root, "package.json"), "utf-8"));
86
+ if (!packageJSON.name) {
87
+ throw new Error("root path is not workspace root, please provide a filter");
88
+ }
89
+ filter = packageJSON.name;
90
+ }
91
+ const { selectedProjectsGraph } = await filterPackagesFromDir(wd, [{
92
+ filter: filter ?? "",
93
+ followProdDepsOnly: true
94
+ }], {
95
+ prefix: root,
96
+ workspaceDir: wd,
97
+ patterns: pnpmWorkspace.packages
98
+ });
99
+ return {
100
+ wd,
101
+ root,
102
+ value: Object.entries(selectedProjectsGraph).reduce((acc, [key, value]) => {
103
+ acc[key] = value.package.manifest;
104
+ return acc;
105
+ }, {})
106
+ };
107
+ }
108
+ throw new Error(`not supported package manager ${type}`);
109
+ }
110
+
18
111
  var utils$1 = {};
19
112
 
20
113
  var hasRequiredUtils$1;
@@ -4121,98 +4214,94 @@ function requireMicromatch () {
4121
4214
 
4122
4215
  var micromatchExports = requireMicromatch();
4123
4216
 
4124
- let root;
4125
- function getRoot() {
4126
- if (root)
4127
- return root;
4128
- const rootOption = program.getOptionValue("root");
4129
- root = rootOption ? path.isAbsolute(rootOption) ? rootOption : path.resolve(process.cwd(), rootOption) : void 0;
4130
- return root;
4131
- }
4132
-
4133
- let type = "";
4134
- try {
4135
- const require = createRequire(import.meta.url);
4136
- require.resolve("@pnpm/filter-workspace-packages");
4137
- type = "pnpm";
4138
- } catch {
4139
- }
4140
- async function getSelectedProjectsGraph(filter = program.getOptionValue("filter")) {
4141
- let root = getRoot();
4142
- const { wd, notWorkspace } = getWD();
4143
- if (notWorkspace) {
4144
- return {
4145
- wd,
4146
- root,
4147
- value: {
4148
- [wd]: JSON.parse(fs.readFileSync(path.resolve(wd, "package.json"), "utf-8"))
4149
- }
4150
- };
4217
+ const intersection = (a, b) => new Set([...a].filter((i) => b.has(i)));
4218
+ const {
4219
+ JIEK_OUT_DIR
4220
+ } = process.env;
4221
+ const OUTDIR = JIEK_OUT_DIR ?? "dist";
4222
+ function getOutDirs({
4223
+ cwd = process.cwd(),
4224
+ defaultOutdir = OUTDIR,
4225
+ config,
4226
+ pkgName
4227
+ }) {
4228
+ const { build = {} } = config ?? {};
4229
+ const outdir = build?.output?.dir;
4230
+ function resolveOutdir(type) {
4231
+ const dir = (typeof outdir === "object" ? outdir[type] ?? outdir[{
4232
+ js: "dts",
4233
+ dts: "js"
4234
+ }[type]] : outdir) ?? defaultOutdir;
4235
+ return (isAbsolute(dir) ? dir : `./${relative(cwd, resolve(cwd, dir))}`).replace("{{PKG_NAME}}", pkgName);
4151
4236
  }
4152
- if (type === "pnpm") {
4153
- const pnpmWorkspaceFilePath = path.resolve(wd, "pnpm-workspace.yaml");
4154
- const pnpmWorkspaceFileContent = fs.readFileSync(pnpmWorkspaceFilePath, "utf-8");
4155
- const pnpmWorkspace = load(pnpmWorkspaceFileContent);
4156
- if (root === wd && !filter) {
4157
- throw new Error("root path is workspace root, please provide a filter");
4158
- }
4159
- if (root === void 0) {
4160
- root = process.cwd();
4161
- }
4162
- if (root !== wd && !filter) {
4163
- const packageJSONIsExist = fs.existsSync(path.resolve(root, "package.json"));
4164
- if (!packageJSONIsExist) {
4165
- throw new Error("root path is not workspace root, please provide a filter");
4166
- }
4167
- const packageJSON = JSON.parse(fs.readFileSync(path.resolve(root, "package.json"), "utf-8"));
4168
- if (!packageJSON.name) {
4169
- throw new Error("root path is not workspace root, please provide a filter");
4237
+ return {
4238
+ js: resolveOutdir("js"),
4239
+ dts: resolveOutdir("dts")
4240
+ };
4241
+ }
4242
+ function getExports({
4243
+ entrypoints,
4244
+ pkgName,
4245
+ pkgIsModule,
4246
+ entries,
4247
+ config,
4248
+ dir,
4249
+ defaultOutdir = OUTDIR,
4250
+ // FIXME dts support
4251
+ outdir = getOutDirs({ pkgName, defaultOutdir, config, cwd: dir }).js,
4252
+ noFilter,
4253
+ isPublish
4254
+ }) {
4255
+ const {
4256
+ build = {},
4257
+ publish: {
4258
+ withSuffix = false,
4259
+ withSource = true
4260
+ } = {}
4261
+ } = config ?? {};
4262
+ const {
4263
+ crossModuleConvertor = true
4264
+ } = build;
4265
+ const [, resolvedEntrypoints] = resolveEntrypoints(entrypoints);
4266
+ if (entries) {
4267
+ Object.entries(resolvedEntrypoints).forEach(([key]) => {
4268
+ if (!entries.some((e) => micromatchExports.isMatch(key, e, { matchBase: true }))) {
4269
+ delete resolvedEntrypoints[key];
4170
4270
  }
4171
- filter = packageJSON.name;
4172
- }
4173
- const { selectedProjectsGraph } = await filterPackagesFromDir(wd, [{
4174
- filter: filter ?? "",
4175
- followProdDepsOnly: true
4176
- }], {
4177
- prefix: root,
4178
- workspaceDir: wd,
4179
- patterns: pnpmWorkspace.packages
4180
4271
  });
4181
- return {
4182
- wd,
4183
- root,
4184
- value: Object.entries(selectedProjectsGraph).reduce((acc, [key, value]) => {
4185
- acc[key] = value.package.manifest;
4186
- return acc;
4187
- }, {})
4188
- };
4189
4272
  }
4190
- throw new Error(`not supported package manager ${type}`);
4191
- }
4192
-
4193
- let wd;
4194
- let notWorkspace = false;
4195
- function getWD() {
4196
- if (wd)
4197
- return { wd, notWorkspace };
4198
- const root = getRoot();
4199
- if (root !== void 0) {
4200
- const isWorkspace = isWorkspaceDir(root, type);
4201
- notWorkspace = !isWorkspace;
4202
- wd = root;
4203
- return { wd, notWorkspace };
4204
- }
4205
- try {
4206
- wd = getWorkspaceDir(type);
4207
- } catch (e) {
4208
- if ("message" in e && e.message === "workspace root not found") {
4209
- wd = root;
4210
- notWorkspace = true;
4211
- } else {
4212
- throw e;
4273
+ const filteredResolvedEntrypoints = noFilter ? resolvedEntrypoints : filterLeafs(
4274
+ resolvedEntrypoints,
4275
+ {
4276
+ skipValue: [
4277
+ // ignore values that filename starts with `.jk-noentry`
4278
+ /(^|\/)\.jk-noentry/,
4279
+ ...DEFAULT_SKIP_VALUES
4280
+ ]
4213
4281
  }
4214
- }
4215
- return { wd, notWorkspace };
4282
+ );
4283
+ const crossModuleWithConditional = crossModuleConvertor ? {
4284
+ import: (opts) => !pkgIsModule && intersection(
4285
+ new Set(opts.conditionals),
4286
+ /* @__PURE__ */ new Set(["import", "module"])
4287
+ ).size === 0 ? opts.dist.replace(/\.js$/, ".mjs") : false,
4288
+ require: (opts) => pkgIsModule && intersection(
4289
+ new Set(opts.conditionals),
4290
+ /* @__PURE__ */ new Set(["require", "node"])
4291
+ ).size === 0 ? opts.dist.replace(/\.js$/, ".cjs") : false
4292
+ } : {};
4293
+ return [
4294
+ filteredResolvedEntrypoints,
4295
+ entrypoints2Exports(filteredResolvedEntrypoints, {
4296
+ outdir,
4297
+ withSuffix: isPublish ? withSuffix : void 0,
4298
+ withSource: isPublish ? withSource : void 0,
4299
+ withConditional: {
4300
+ ...crossModuleWithConditional
4301
+ }
4302
+ }),
4303
+ outdir
4304
+ ];
4216
4305
  }
4217
4306
 
4218
4307
  const require$1 = createRequire(import.meta.url);
@@ -4321,394 +4410,65 @@ function loadConfig(dirOrOptions) {
4321
4410
  return module.default ?? module;
4322
4411
  }
4323
4412
 
4324
- const PACKAGE_JSON_TEMPLATE = `{
4325
- "name": "",
4326
- "version": "0.0.1",
4327
- "description": "",
4328
- "license": "",
4329
- "author": "",
4330
- "files": ["dist"],
4331
- "exports": {
4332
- ".": "./src/index.ts"
4333
- },
4334
- "scripts": {
4335
- },
4336
- "homepage": "",
4337
- "repository": "",
4338
- "bugs": ""
4339
- }`.trimStart();
4340
- const README_TEMPLATE = `# $name
4341
-
4342
- ## Installation
4343
-
4344
- \`\`\`bash
4345
- npm install $name
4346
- # or
4347
- pnpm install $name
4348
- # or
4349
- yarn add $name
4350
- \`\`\`
4351
-
4352
- ## Usage
4353
-
4354
-
4355
- ## License
4356
-
4357
- $license
4358
- `.trimStart();
4359
- function getTemplateStr(wd, template) {
4360
- let templateString = template ?? PACKAGE_JSON_TEMPLATE;
4361
- let isTemplateFile = false;
4362
- try {
4363
- if (template)
4364
- JSON.parse(template);
4365
- } catch (e) {
4366
- isTemplateFile = true;
4367
- }
4368
- if (isTemplateFile) {
4369
- const templatePath = path.resolve(wd, template);
4370
- templateString = fs.readFileSync(templatePath, "utf-8");
4371
- }
4372
- return templateString;
4373
- }
4374
- const wdCache = /* @__PURE__ */ new Map();
4375
- function getWDPackageJSONFiled(wd, field) {
4376
- if (wdCache.has(wd)) {
4377
- return wdCache.get(wd)[field];
4378
- }
4379
- const packageJSONPath = path.resolve(wd, "package.json");
4380
- const packageJSON = JSON.parse(fs.readFileSync(packageJSONPath, "utf-8"));
4381
- wdCache.set(wd, packageJSON);
4382
- return packageJSON[field];
4383
- }
4384
- async function getName(named, name, {
4385
- wd,
4386
- cwd,
4387
- workspaceName
4388
- }) {
4389
- const relativePath = cwd.replace(`${wd}/`, "");
4390
- let basename = path.basename(cwd);
4391
- if (typeof named === "function") {
4392
- return named(name, {
4393
- full: wd,
4394
- relative: cwd
4395
- });
4396
- }
4397
- let isParentMatched = false;
4398
- let matchedKey;
4399
- let matchedRule;
4400
- if (typeof named === "object") {
4401
- const isWD = cwd === wd;
4402
- if (isWD) {
4403
- const { rule } = await inquirer.prompt({
4404
- type: "list",
4405
- name: "rule",
4406
- message: "choose a rule",
4407
- default: "default",
4408
- choices: ["default"].concat(Object.keys(named))
4409
- });
4410
- if (rule !== "default") {
4411
- matchedKey = rule;
4412
- matchedRule = named[rule];
4413
- }
4414
- } else {
4415
- for (const [key, value] of Object.entries(named)) {
4416
- if (micromatchExports.isMatch(relativePath, key)) {
4417
- matchedKey = key;
4418
- matchedRule = value;
4419
- break;
4420
- }
4421
- if (micromatchExports.isMatch(`${relativePath}/jiek_ignore_dont_use_same_file_name`, key)) {
4422
- isParentMatched = true;
4423
- matchedKey = key;
4424
- matchedRule = value;
4425
- break;
4426
- }
4427
- }
4428
- }
4429
- }
4430
- if (!matchedRule) {
4431
- matchedKey = "packages/*";
4432
- matchedRule = `@${workspaceName}/$basename`;
4433
- }
4434
- if (!matchedRule) {
4435
- throw new Error("no matched rule");
4436
- }
4437
- if (!name && isParentMatched) {
4438
- basename = await inquirer.prompt({
4439
- type: "input",
4440
- name: "name",
4441
- message: `the matched rule is \`${String(matchedRule)}\`, please input the basename
4442
- `
4443
- }).then(({ name: name2 }) => name2);
4444
- }
4445
- if (typeof matchedRule === "function") {
4446
- return matchedRule(name, {
4447
- full: wd,
4448
- relative: cwd,
4449
- basename
4450
- });
4451
- }
4452
- if (typeof matchedRule === "string") {
4453
- const dirName = name ?? basename;
4454
- return [
4455
- matchedRule.replace(/\$basename/g, dirName),
4456
- matchedKey?.replace(/\/\*$/g, `/${dirName}`)
4457
- ];
4458
- }
4459
- throw new Error("no matched rule");
4460
- }
4461
- program.command("init [name]").option("-t, --template <template>", "the package.json template file path or file content").action(async () => {
4462
- const [, name] = program.args;
4463
- const cwd = process.cwd();
4464
- const { init = {} } = loadConfig() ?? {};
4465
- const { wd } = getWD();
4466
- const workspaceName = path.basename(wd);
4467
- const {
4468
- named,
4469
- template,
4470
- bug = {},
4471
- readme: _readme = README_TEMPLATE,
4472
- readmeTemplate
4473
- } = init;
4474
- const resolvedBug = {
4475
- template: "bug_report.yml",
4476
- labels: ["bug"],
4477
- ...bug
4478
- };
4479
- let readme = _readme;
4480
- if (readmeTemplate) {
4481
- const readmeTemplatePath = path.resolve(wd, readmeTemplate);
4482
- readme = fs.readFileSync(readmeTemplatePath, "utf-8");
4483
- }
4484
- const templateString = getTemplateStr(wd, template);
4485
- const { indent = " " } = detectIndent(templateString);
4486
- const formattingOptions = {
4487
- tabSize: indent.length,
4488
- insertSpaces: true
4489
- };
4490
- const passFields = [
4491
- "license",
4492
- "author"
4493
- ];
4494
- let newJSONString = templateString;
4495
- for (const field of passFields) {
4496
- newJSONString = applyEdits(
4497
- newJSONString,
4498
- modify(
4499
- newJSONString,
4500
- [field],
4501
- getWDPackageJSONFiled(wd, field),
4502
- { formattingOptions }
4503
- )
4504
- );
4505
- }
4506
- let [pkgName, pkgDir] = await getName(named, name, {
4507
- wd,
4508
- cwd,
4509
- workspaceName
4510
- });
4511
- if (!pkgDir) {
4512
- const { dir } = await inquirer.prompt({
4513
- type: "input",
4514
- name: "dir",
4515
- message: "package directory",
4516
- default: name
4517
- });
4518
- pkgDir = dir;
4519
- }
4520
- if (!pkgName) {
4521
- const { name: inputName } = await inquirer.prompt({
4522
- type: "input",
4523
- name: "name",
4524
- message: "package name",
4525
- default: name
4526
- });
4527
- pkgName = inputName;
4528
- }
4529
- newJSONString = applyEdits(newJSONString, modify(newJSONString, ["name"], pkgName, { formattingOptions }));
4530
- let pkgRepo = getWDPackageJSONFiled(wd, "repository");
4531
- if (typeof pkgRepo === "string") {
4532
- pkgRepo = {
4533
- type: "git",
4534
- url: pkgRepo,
4535
- directory: pkgDir
4536
- };
4537
- }
4538
- newJSONString = applyEdits(
4539
- newJSONString,
4540
- modify(
4541
- newJSONString,
4542
- ["repository"],
4543
- pkgRepo,
4544
- { formattingOptions }
4545
- )
4546
- );
4547
- const homepage = `${pkgRepo?.url}/blob/master/${pkgDir}/README.md`;
4548
- newJSONString = applyEdits(
4549
- newJSONString,
4550
- modify(
4551
- newJSONString,
4552
- ["homepage"],
4553
- homepage,
4554
- { formattingOptions }
4555
- )
4556
- );
4557
- let labels = resolvedBug.labels;
4558
- if (typeof labels === "function") {
4559
- labels = labels({
4560
- name: pkgName,
4561
- dir: pkgDir
4562
- });
4563
- }
4564
- labels.push(`scope:${pkgName}`);
4565
- const bugs = `${pkgRepo?.url}/issues/new?template=${resolvedBug.template}&labels=${labels.join(",")}`;
4566
- newJSONString = applyEdits(
4567
- newJSONString,
4568
- modify(
4569
- newJSONString,
4570
- ["bugs"],
4571
- bugs,
4572
- { formattingOptions }
4573
- )
4574
- );
4575
- function pkgDirTo(to) {
4576
- if (!pkgDir)
4577
- throw new Error("pkgDir is not defined");
4578
- return path.resolve(pkgDir, to);
4579
- }
4580
- if (!fs.existsSync(pkgDir))
4581
- fs.mkdirSync(pkgDir);
4582
- const pkgJSONFilePath = pkgDirTo("package.json");
4583
- if (fs.existsSync(pkgJSONFilePath)) {
4584
- throw new Error("package.json already exists");
4585
- }
4586
- fs.writeFileSync(pkgJSONFilePath, newJSONString);
4587
- console.log(newJSONString, "written to", pkgJSONFilePath);
4588
- const license = getWDPackageJSONFiled(wd, "license");
4589
- const readmeFilePath = pkgDirTo("README.md");
4590
- if (typeof readme === "function") {
4591
- readme = readme({
4592
- dir: pkgDir,
4593
- packageJson: JSON.parse(newJSONString)
4594
- });
4595
- }
4596
- const readmeContent = readme.replace(/\$name/g, pkgName).replace(/\$license/g, license);
4597
- fs.writeFileSync(readmeFilePath, readmeContent);
4598
- });
4599
-
4600
- let resolve;
4601
- function actionDone() {
4602
- resolve();
4603
- }
4604
- function actionRestore() {
4605
- new Promise((r) => resolve = r);
4606
- }
4607
-
4608
- const intersection = (a, b) => new Set([...a].filter((i) => b.has(i)));
4609
- const {
4610
- JIEK_OUT_DIR
4611
- } = process.env;
4612
- const OUTDIR = JIEK_OUT_DIR ?? "dist";
4613
- function getOutDirs({
4614
- cwd = process.cwd(),
4615
- defaultOutdir = OUTDIR,
4616
- config,
4617
- pkgName
4618
- }) {
4619
- const { build = {} } = config ?? {};
4620
- const outdir = build?.output?.dir;
4621
- function resolveOutdir(type) {
4622
- const dir = (typeof outdir === "object" ? outdir[type] ?? outdir[{
4623
- js: "dts",
4624
- dts: "js"
4625
- }[type]] : outdir) ?? defaultOutdir;
4626
- return (isAbsolute(dir) ? dir : `./${relative(cwd, resolve$1(cwd, dir))}`).replace("{{PKG_NAME}}", pkgName);
4627
- }
4628
- return {
4629
- js: resolveOutdir("js"),
4630
- dts: resolveOutdir("dts")
4631
- };
4632
- }
4633
- function getExports({
4634
- entrypoints,
4635
- pkgName,
4636
- pkgIsModule,
4637
- entries,
4638
- config,
4639
- dir,
4640
- defaultOutdir = OUTDIR,
4641
- // FIXME dts support
4642
- outdir = getOutDirs({ pkgName, defaultOutdir, config, cwd: dir }).js,
4643
- noFilter,
4644
- isPublish
4645
- }) {
4646
- const {
4647
- build = {},
4648
- publish: {
4649
- withSuffix = false,
4650
- withSource = true
4651
- } = {}
4652
- } = config ?? {};
4653
- const {
4654
- crossModuleConvertor = true
4655
- } = build;
4656
- const [, resolvedEntrypoints] = resolveEntrypoints(entrypoints);
4657
- if (entries) {
4658
- Object.entries(resolvedEntrypoints).forEach(([key]) => {
4659
- if (!entries.some((e) => micromatchExports.isMatch(key, e, { matchBase: true }))) {
4660
- delete resolvedEntrypoints[key];
4661
- }
4662
- });
4663
- }
4664
- const filteredResolvedEntrypoints = noFilter ? resolvedEntrypoints : filterLeafs(
4665
- resolvedEntrypoints,
4666
- {
4667
- skipValue: [
4668
- // ignore values that filename starts with `.jk-noentry`
4669
- /(^|\/)\.jk-noentry/,
4670
- ...DEFAULT_SKIP_VALUES
4671
- ]
4672
- }
4673
- );
4674
- const crossModuleWithConditional = crossModuleConvertor ? {
4675
- import: (opts) => !pkgIsModule && intersection(
4676
- new Set(opts.conditionals),
4677
- /* @__PURE__ */ new Set(["import", "module"])
4678
- ).size === 0 ? opts.dist.replace(/\.js$/, ".mjs") : false,
4679
- require: (opts) => pkgIsModule && intersection(
4680
- new Set(opts.conditionals),
4681
- /* @__PURE__ */ new Set(["require", "node"])
4682
- ).size === 0 ? opts.dist.replace(/\.js$/, ".cjs") : false
4683
- } : {};
4684
- return [
4685
- filteredResolvedEntrypoints,
4686
- entrypoints2Exports(filteredResolvedEntrypoints, {
4687
- outdir,
4688
- withSuffix: isPublish ? withSuffix : void 0,
4689
- withSource: isPublish ? withSource : void 0,
4690
- withConditional: {
4691
- ...crossModuleWithConditional
4692
- }
4693
- }),
4694
- outdir
4695
- ];
4696
- }
4697
-
4698
4413
  const outdirDescription = `
4699
4414
  The output directory of the build, which relative to the target subpackage root directory.
4700
4415
  Support with variables: 'PKG_NAME',
4701
4416
  .e.g. 'dist/{{PKG_NAME}}'.
4702
4417
  `.trim();
4703
4418
 
4704
- 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, ...options }) => {
4705
- actionRestore();
4419
+ const description = `
4420
+ Publish package to npm registry, and auto generate exports field and other fields in published package.json.
4421
+ If you want to through the options to the \`pnpm publish\` command, you can pass the options after '--'.
4422
+ `.trim();
4423
+ async function forEachSelectedProjectsGraphEntries(callback) {
4706
4424
  const { value = {} } = await getSelectedProjectsGraph() ?? {};
4707
4425
  const selectedProjectsGraphEntries = Object.entries(value);
4708
4426
  if (selectedProjectsGraphEntries.length === 0) {
4709
4427
  throw new Error("no packages selected");
4710
4428
  }
4711
- const manifests = selectedProjectsGraphEntries.map(([dir, manifest]) => {
4429
+ for (const [dir, manifest] of selectedProjectsGraphEntries) {
4430
+ callback(dir, manifest);
4431
+ }
4432
+ }
4433
+ 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 }) => {
4434
+ let shouldPassThrough = false;
4435
+ const passThroughOptions = process.argv.reduce(
4436
+ (acc, value) => {
4437
+ if (shouldPassThrough) {
4438
+ acc.push(value);
4439
+ }
4440
+ if (value === "--") {
4441
+ shouldPassThrough = true;
4442
+ }
4443
+ return acc;
4444
+ },
4445
+ []
4446
+ );
4447
+ await forEachSelectedProjectsGraphEntries((dir) => {
4448
+ const args = ["pnpm", "publish", "--access", "public", "--no-git-checks"];
4449
+ if (bumper && TAGS.includes(bumper)) {
4450
+ args.push("--tag", bumper);
4451
+ }
4452
+ args.push(...passThroughOptions);
4453
+ childProcess.execSync(args.join(" "), {
4454
+ cwd: dir,
4455
+ stdio: "inherit",
4456
+ env: {
4457
+ ...process.env,
4458
+ JIEK_PUBLISH_OUTDIR: JSON.stringify(outdir),
4459
+ JIEK_PUBLISH_BUMPER: JSON.stringify(bumper)
4460
+ }
4461
+ });
4462
+ });
4463
+ });
4464
+ async function prepublish() {
4465
+ const {
4466
+ JIEK_PUBLISH_OUTDIR: outdirEnv,
4467
+ JIEK_PUBLISH_BUMPER: bumperEnv
4468
+ } = process.env;
4469
+ const outdir = outdirEnv ? JSON.parse(outdirEnv) : "dist";
4470
+ const bumper = bumperEnv ? JSON.parse(bumperEnv) : false;
4471
+ const generateNewManifest = (dir, manifest) => {
4712
4472
  const { name, type, exports: entrypoints = {} } = manifest;
4713
4473
  if (!name) {
4714
4474
  throw new Error(`package.json in ${dir} must have a name field`);
@@ -4729,35 +4489,38 @@ program.command("publish").aliases(["pub", "p"]).option("-b, --bumper <bumper>",
4729
4489
  ...resolvedEntrypoints,
4730
4490
  ...exports
4731
4491
  };
4732
- return [dir, newManifest, resolvedOutdir];
4733
- });
4734
- const passArgs = Object.entries(options).reduce((acc, [key, value2]) => {
4735
- if (value2) {
4736
- acc.push(`--${key}`, value2);
4737
- }
4738
- return acc;
4739
- }, []);
4740
- for (const [dir, manifest, resolvedOutdir] of manifests) {
4741
- const oldJSONString = fs.readFileSync(path.join(dir, "package.json"), "utf-8");
4742
- const oldJSON = JSON.parse(oldJSONString) ?? "0.0.0";
4743
- const newVersion = bumper ? bump(oldJSON.version, bumper) : oldJSON.version;
4744
- const { indent = " " } = detectIndent(oldJSONString);
4745
- const formattingOptions = {
4746
- tabSize: indent.length,
4747
- insertSpaces: true
4748
- };
4492
+ return [newManifest, resolvedOutdir];
4493
+ };
4494
+ const generateNewPackageJSONString = ({
4495
+ oldJSONString,
4496
+ oldJSON,
4497
+ manifest,
4498
+ formattingOptions
4499
+ }) => {
4749
4500
  let newJSONString = oldJSONString;
4750
4501
  newJSONString = applyEdits(
4751
4502
  newJSONString,
4752
4503
  modify(
4753
4504
  newJSONString,
4754
- ["version"],
4755
- newVersion,
4505
+ ["publishConfig", "typesVersions"],
4506
+ {
4507
+ "<5.0": {
4508
+ "*": [
4509
+ "*",
4510
+ `./*`,
4511
+ `./*/index.d.ts`,
4512
+ `./*/index.d.mts`,
4513
+ `./*/index.d.cts`
4514
+ ]
4515
+ }
4516
+ },
4756
4517
  { formattingOptions }
4757
4518
  )
4758
4519
  );
4759
- for (const [key, value2] of Object.entries(manifest)) {
4760
- if (JSON.stringify(value2) === JSON.stringify(oldJSON[key]))
4520
+ for (const [key, value] of Object.entries(manifest)) {
4521
+ if (key === "version")
4522
+ continue;
4523
+ if (JSON.stringify(value) === JSON.stringify(oldJSON[key]))
4761
4524
  continue;
4762
4525
  if (key !== "exports") {
4763
4526
  newJSONString = applyEdits(
@@ -4765,12 +4528,12 @@ program.command("publish").aliases(["pub", "p"]).option("-b, --bumper <bumper>",
4765
4528
  modify(
4766
4529
  newJSONString,
4767
4530
  ["publishConfig", key],
4768
- value2,
4531
+ value,
4769
4532
  { formattingOptions }
4770
4533
  )
4771
4534
  );
4772
4535
  } else {
4773
- const exports = value2;
4536
+ const exports = value;
4774
4537
  for (const [k, v] of Object.entries(exports)) {
4775
4538
  newJSONString = applyEdits(
4776
4539
  newJSONString,
@@ -4812,46 +4575,138 @@ program.command("publish").aliases(["pub", "p"]).option("-b, --bumper <bumper>",
4812
4575
  }
4813
4576
  }
4814
4577
  }
4815
- newJSONString = applyEdits(
4816
- newJSONString,
4817
- modify(
4818
- newJSONString,
4819
- ["publishConfig", "typesVersions"],
4820
- {
4821
- "<5.0": {
4822
- "*": [
4823
- "*",
4824
- `${resolvedOutdir}/*`,
4825
- `${resolvedOutdir}/*/index.d.ts`,
4826
- `${resolvedOutdir}/*/index.d.mts`,
4827
- `${resolvedOutdir}/*/index.d.cts`
4828
- ]
4829
- }
4578
+ if (oldJSON["peerDependencies"]) {
4579
+ const peerDependenciesMeta = Object.keys(oldJSON["peerDependencies"]).reduce(
4580
+ (acc, key) => {
4581
+ acc[key] = { optional: true };
4582
+ return acc;
4830
4583
  },
4831
- { formattingOptions }
4832
- )
4584
+ {}
4585
+ );
4586
+ newJSONString = applyEdits(
4587
+ newJSONString,
4588
+ modify(
4589
+ newJSONString,
4590
+ ["peerDependenciesMeta"],
4591
+ peerDependenciesMeta,
4592
+ { formattingOptions }
4593
+ )
4594
+ );
4595
+ }
4596
+ if (oldJSON["files"]) {
4597
+ newJSONString = applyEdits(
4598
+ newJSONString,
4599
+ modify(
4600
+ newJSONString,
4601
+ ["files"],
4602
+ void 0,
4603
+ { formattingOptions }
4604
+ )
4605
+ );
4606
+ }
4607
+ return newJSONString;
4608
+ };
4609
+ await forEachSelectedProjectsGraphEntries((dir, originalManifest) => {
4610
+ const [manifest, resolvedOutdir] = generateNewManifest(dir, originalManifest);
4611
+ const resolveByDir = (...paths) => path.resolve(dir, ...paths);
4612
+ const oldJSONString = fs.readFileSync(resolveByDir("package.json"), "utf-8");
4613
+ const oldJSON = JSON.parse(oldJSONString) ?? "0.0.0";
4614
+ if (typeof oldJSON.version !== "string") {
4615
+ throw new Error(`${dir}/package.json must have a version field with a string value`);
4616
+ }
4617
+ const { indent = " " } = detectIndent(oldJSONString);
4618
+ const formattingOptions = {
4619
+ tabSize: indent.length,
4620
+ insertSpaces: true
4621
+ };
4622
+ const newVersion = bumper ? bump(oldJSON.version, bumper) : oldJSON.version;
4623
+ const modifyVersionPackageJSON = applyEdits(
4624
+ oldJSONString,
4625
+ modify(oldJSONString, ["version"], newVersion, { formattingOptions })
4833
4626
  );
4834
- try {
4835
- fs.renameSync(path.join(dir, "package.json"), path.join(dir, "package.json.bak"));
4836
- fs.writeFileSync(path.join(dir, "package.json"), newJSONString);
4837
- !silent && console.log(newJSONString);
4838
- if (preview) {
4839
- continue;
4627
+ const newJSONString = generateNewPackageJSONString({
4628
+ oldJSONString: modifyVersionPackageJSON,
4629
+ oldJSON: {
4630
+ ...oldJSON,
4631
+ version: newVersion
4632
+ },
4633
+ manifest,
4634
+ formattingOptions
4635
+ });
4636
+ const withPublishConfigDirectoryOldJSONString = applyEdits(
4637
+ modifyVersionPackageJSON,
4638
+ modify(modifyVersionPackageJSON, ["publishConfig", "directory"], resolvedOutdir, { formattingOptions })
4639
+ );
4640
+ if (oldJSON.files) {
4641
+ if (!Array.isArray(oldJSON.files)) {
4642
+ throw new Error(`${dir}/package.json files field must be an array`);
4840
4643
  }
4841
- const args = ["pnpm", "publish", "--access", "public", "--no-git-checks", ...passArgs];
4842
- if (bumper && TAGS.includes(bumper)) {
4843
- args.push("--tag", bumper);
4644
+ if (Array.isArray(oldJSON.files) && oldJSON.files.every((file) => typeof file !== "string")) {
4645
+ throw new Error(`${dir}/package.json files field must be an array of string`);
4844
4646
  }
4845
- childProcess.execSync(args.join(" "), {
4846
- cwd: dir,
4847
- stdio: "inherit"
4848
- });
4849
- const modifyVersionPackageJSON = applyEdits(oldJSONString, modify(oldJSONString, ["version"], newVersion, {}));
4850
- fs.writeFileSync(path.join(dir, "package.json.bak"), modifyVersionPackageJSON);
4851
- } finally {
4852
- fs.unlinkSync(path.join(dir, "package.json"));
4853
- fs.renameSync(path.join(dir, "package.json.bak"), path.join(dir, "package.json"));
4854
4647
  }
4648
+ const resolvedOutdirAbs = resolveByDir(resolvedOutdir);
4649
+ const files = oldJSON.files ?? fs.readdirSync(resolveByDir(".")).filter((file) => file !== "node_modules" && resolveByDir(file) !== resolvedOutdirAbs);
4650
+ for (const file of files) {
4651
+ const path2 = resolveByDir(file);
4652
+ try {
4653
+ const stat = fs.statSync(path2);
4654
+ if (stat.isDirectory()) {
4655
+ fs.symlinkSync(path2, resolveByDir(resolvedOutdir, file), "dir");
4656
+ continue;
4657
+ }
4658
+ if (stat.isFile()) {
4659
+ fs.symlinkSync(path2, resolveByDir(resolvedOutdir, file), "file");
4660
+ continue;
4661
+ }
4662
+ } catch (e) {
4663
+ console.warn(String(e));
4664
+ continue;
4665
+ }
4666
+ throw new Error(`file type of ${path2} is not supported`);
4667
+ }
4668
+ if (!fs.existsSync(resolveByDir(resolvedOutdir))) {
4669
+ fs.mkdirSync(resolveByDir(resolvedOutdir));
4670
+ }
4671
+ const jiekTempDir = resolveByDir("node_modules/.jiek/.tmp");
4672
+ if (!fs.existsSync(resolveByDir(jiekTempDir))) {
4673
+ fs.mkdirSync(resolveByDir(jiekTempDir), { recursive: true });
4674
+ }
4675
+ fs.writeFileSync(resolveByDir(resolvedOutdir, "package.json"), newJSONString);
4676
+ fs.writeFileSync(resolveByDir(jiekTempDir, "package.json"), modifyVersionPackageJSON);
4677
+ fs.writeFileSync(resolveByDir("package.json"), withPublishConfigDirectoryOldJSONString);
4678
+ });
4679
+ }
4680
+ async function postpublish() {
4681
+ await forEachSelectedProjectsGraphEntries((dir) => {
4682
+ const jiekTempDir = path.resolve(dir, "node_modules/.jiek/.tmp");
4683
+ const packageJSON = path.resolve(dir, "package.json");
4684
+ const jiekTempPackageJSON = path.resolve(jiekTempDir, "package.json");
4685
+ if (fs.existsSync(jiekTempPackageJSON)) {
4686
+ fs.copyFileSync(jiekTempPackageJSON, packageJSON);
4687
+ fs.rmSync(jiekTempPackageJSON);
4688
+ console.log(`${dir}/package.json has been restored`);
4689
+ } else {
4690
+ throw new Error(
4691
+ `jiek temp \`${dir}/package.json\` not found, please confirm the jiek pre-publish command has been executed`
4692
+ );
4693
+ }
4694
+ });
4695
+ }
4696
+ program.action(async () => {
4697
+ const {
4698
+ npm_lifecycle_event: NPM_LIFECYCLE_EVENT
4699
+ } = process.env;
4700
+ switch (NPM_LIFECYCLE_EVENT) {
4701
+ case "prepublish":
4702
+ await prepublish();
4703
+ break;
4704
+ case "postpublish":
4705
+ await postpublish();
4706
+ break;
4707
+ default:
4708
+ program.help();
4855
4709
  }
4856
- actionDone();
4857
4710
  });
4711
+ program.command("prepublish").action(prepublish);
4712
+ program.command("postpublish").action(postpublish);