yarn-version 1.0.0-pre

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.
@@ -0,0 +1,1059 @@
1
+ import fs$2 from 'node:fs';
2
+ import { program, Option } from 'commander';
3
+ import childProcess, { spawnSync } from 'node:child_process';
4
+ import path from 'node:path';
5
+ import { ConventionalGitClient } from '@conventional-changelog/git-client';
6
+ import { addConfig, Level, Logger } from 'nightingale';
7
+ import { ConsoleHandler } from 'nightingale-console';
8
+ import semver, { satisfies } from 'semver';
9
+ import { text } from 'node:stream/consumers';
10
+ import conventionalChangelogCore from 'conventional-changelog-core';
11
+ import { loadPreset } from 'conventional-changelog-preset-loader';
12
+ import { Octokit } from '@octokit/rest';
13
+ import fs from 'node:fs/promises';
14
+ import mapWorkspaces from '@npmcli/map-workspaces';
15
+ import prettyPkg from '@pob/pretty-pkg';
16
+ import fs$1 from 'fs/promises';
17
+
18
+ const UsageError = Error;
19
+
20
+ function getMapArrayItemForKey(map, key) {
21
+ let value = map.get(key);
22
+ if (value === void 0) {
23
+ map.set(key, value = []);
24
+ }
25
+ return value;
26
+ }
27
+
28
+ const PackageDescriptorNameUtils = {
29
+ parse: (value) => {
30
+ if (value.startsWith("@")) {
31
+ const [scope, name] = value.split("/", 2);
32
+ return { scope, name };
33
+ }
34
+ return { name: value };
35
+ },
36
+ stringify: (descriptor) => {
37
+ return descriptor.scope === void 0 ? descriptor.name : `@${descriptor.scope}/${descriptor.name}`;
38
+ }
39
+ };
40
+ const PackageDependencyDescriptorUtils = {
41
+ parse: (dependencyKey, dependencyValue) => {
42
+ const [name, selector] = dependencyValue.startsWith("npm:") ? dependencyValue.slice("npm:".length).split("@", 2) : [dependencyKey, dependencyValue];
43
+ return {
44
+ key: dependencyKey,
45
+ name: PackageDescriptorNameUtils.parse(name),
46
+ selector
47
+ };
48
+ },
49
+ stringify: (descriptor) => {
50
+ return [descriptor.key, descriptor.selector];
51
+ }
52
+ };
53
+
54
+ const allDependenciesTypes = [
55
+ "dependencies",
56
+ "devDependencies",
57
+ "peerDependencies"
58
+ ];
59
+ const getWorkspaceName = (workspace) => {
60
+ return workspace.pkg.name ?? (path.basename(workspace.cwd) || "unnamed-workspace");
61
+ };
62
+ const buildDependenciesMaps = (project) => {
63
+ const dependenciesMap = /* @__PURE__ */ new Map();
64
+ for (const dependent of project.children.values()) {
65
+ for (const set of allDependenciesTypes) {
66
+ for (const [dependencyKey, dependencyValue] of Object.entries(
67
+ dependent.pkg[set] || {}
68
+ )) {
69
+ if (!dependencyValue) continue;
70
+ const descriptor = PackageDependencyDescriptorUtils.parse(
71
+ dependencyKey,
72
+ dependencyValue
73
+ );
74
+ const workspace = project.children.get(
75
+ PackageDescriptorNameUtils.stringify(descriptor.name)
76
+ );
77
+ if (!workspace) continue;
78
+ const dependencies = getMapArrayItemForKey(dependenciesMap, dependent);
79
+ dependencies.push([workspace, set, descriptor]);
80
+ }
81
+ }
82
+ }
83
+ return dependenciesMap;
84
+ };
85
+ const buildTopologicalOrderBatches = (project, dependenciesMap) => {
86
+ const batches = [];
87
+ const added = /* @__PURE__ */ new Set();
88
+ const toAdd = /* @__PURE__ */ new Set([
89
+ project.root,
90
+ ...project.children.values()
91
+ ]);
92
+ while (toAdd.size > 0) {
93
+ const batch = /* @__PURE__ */ new Set();
94
+ for (const workspace of toAdd) {
95
+ if (workspace === project.root && toAdd.size > 1) {
96
+ continue;
97
+ }
98
+ const dependencies = dependenciesMap.get(workspace);
99
+ if (!dependencies || dependencies.every((w) => added.has(w[0]))) {
100
+ batch.add(workspace);
101
+ }
102
+ }
103
+ for (const workspace of batch) {
104
+ added.add(workspace);
105
+ toAdd.delete(workspace);
106
+ }
107
+ if (batch.size === 0) {
108
+ throw new Error("Circular dependency detected");
109
+ }
110
+ batches.push([...batch]);
111
+ }
112
+ return batches;
113
+ };
114
+
115
+ const SUPPORTED_UPGRADE_REGEXP = (
116
+ // eslint-disable-next-line unicorn/better-regex -- note that autofix cause issues https://github.com/sindresorhus/eslint-plugin-unicorn/issues/1626
117
+ /^(>=|[~^]|)(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$/
118
+ );
119
+ const yarnWorkspaceProtocol = "workspace:";
120
+ const calcBumpRange = (workspace, range, newVersion) => {
121
+ if (range === "*") {
122
+ return range;
123
+ }
124
+ let useWorkspaceProtocol = false;
125
+ if (range.startsWith(yarnWorkspaceProtocol)) {
126
+ const slicedRange = range.slice(yarnWorkspaceProtocol.length);
127
+ if (slicedRange === workspace.relativeCwd) {
128
+ return range;
129
+ }
130
+ if (slicedRange === "*") {
131
+ return range;
132
+ }
133
+ range = slicedRange;
134
+ useWorkspaceProtocol = true;
135
+ }
136
+ const parsed = SUPPORTED_UPGRADE_REGEXP.exec(range);
137
+ if (!parsed) {
138
+ const workspaceName = getWorkspaceName(workspace);
139
+ throw new Error(`Couldn't bump range ${range} in ${workspaceName}`);
140
+ }
141
+ return `${useWorkspaceProtocol ? yarnWorkspaceProtocol : ""}${parsed[1]}${newVersion}`;
142
+ };
143
+ const getHighestBumpType = (bumpTypes) => {
144
+ if (bumpTypes.includes("major")) {
145
+ return "major";
146
+ }
147
+ if (bumpTypes.includes("minor")) {
148
+ return "minor";
149
+ }
150
+ return "patch";
151
+ };
152
+ const calcBumpType = (bumpType, maxBumpType) => {
153
+ if (maxBumpType === "major") {
154
+ return bumpType;
155
+ }
156
+ if (maxBumpType === "minor") {
157
+ return bumpType === "major" || bumpType === "minor" ? "minor" : "patch";
158
+ }
159
+ return "patch";
160
+ };
161
+ const incVersion = (version, bumpType) => {
162
+ if (bumpType === "major" && semver.major(version) === 0) {
163
+ bumpType = "minor";
164
+ }
165
+ return semver.inc(version, bumpType);
166
+ };
167
+ const incrementVersion = (workspace, currentVersion, bumpType) => {
168
+ const newVersion = incVersion(currentVersion, bumpType);
169
+ if (!newVersion) {
170
+ throw new UsageError(
171
+ `Could not determine next version for "${getWorkspaceName(
172
+ workspace
173
+ )}" (currentVersion: ${currentVersion}, bumpType: ${bumpType}})`
174
+ );
175
+ }
176
+ return newVersion;
177
+ };
178
+
179
+ const versions = [
180
+ "major",
181
+ "minor",
182
+ "patch"
183
+ ];
184
+ const recommendBump = async (commits, config) => {
185
+ const whatBump = config.whatBump;
186
+ if (!whatBump) {
187
+ throw new Error("whatBump method is missing in config");
188
+ }
189
+ let result = { ...await whatBump(commits) };
190
+ if (result.level != null) {
191
+ result.releaseType = versions[result.level];
192
+ } else if (result == null) {
193
+ result = {};
194
+ }
195
+ return result;
196
+ };
197
+ const generateChangelog = (workspace, pkg, config, newTag, {
198
+ previousTag = "",
199
+ verbose = false,
200
+ tagPrefix = "v",
201
+ path = "",
202
+ lernaPackage
203
+ } = {}) => {
204
+ if (!newTag) throw new Error("Missing new tag");
205
+ const stream = conventionalChangelogCore(
206
+ {
207
+ cwd: workspace.cwd,
208
+ config,
209
+ pkg,
210
+ path,
211
+ append: !!previousTag,
212
+ releaseCount: !previousTag ? 0 : 1,
213
+ skipUnstable: true,
214
+ lernaPackage,
215
+ tagPrefix,
216
+ verbose,
217
+ previousTag,
218
+ currentTag: newTag
219
+ },
220
+ {
221
+ version: pkg.version,
222
+ currentTag: newTag,
223
+ previousTag
224
+ }
225
+ );
226
+ return text(stream);
227
+ };
228
+
229
+ const loadConventionalCommitConfig = async (rootWorkspace, preset) => {
230
+ try {
231
+ return loadPreset(preset);
232
+ } catch (error) {
233
+ throw new UsageError(
234
+ `Failed to require preset "${preset}": ${error.message}`
235
+ );
236
+ }
237
+ };
238
+
239
+ async function asyncIterableToArray(asyncIterable) {
240
+ const result = [];
241
+ for await (const value of asyncIterable) {
242
+ result.push(value);
243
+ }
244
+ return result;
245
+ }
246
+
247
+ async function execvp(command, args, {
248
+ cwd = process.cwd(),
249
+ env = process.env,
250
+ encoding,
251
+ strict
252
+ }) {
253
+ const stdoutChunks = [];
254
+ const stderrChunks = [];
255
+ if (env.PWD !== void 0) {
256
+ env = { ...env, PWD: cwd };
257
+ }
258
+ const subprocess = childProcess.spawn(command, args, {
259
+ cwd,
260
+ env,
261
+ stdio: ["ignore", "pipe", "pipe"]
262
+ });
263
+ subprocess.stdout.on("data", (chunk) => {
264
+ stdoutChunks.push(chunk);
265
+ });
266
+ subprocess.stderr.on("data", (chunk) => {
267
+ stderrChunks.push(chunk);
268
+ });
269
+ return new Promise((resolve, reject) => {
270
+ subprocess.on("error", (err) => {
271
+ reject(new Error(`Process ${command} failed to spawn`));
272
+ });
273
+ subprocess.on("close", (code, signal) => {
274
+ const stdout = Buffer.concat(stdoutChunks).toString(encoding ?? "utf8");
275
+ const stderr = Buffer.concat(stderrChunks).toString(encoding ?? "utf8");
276
+ if (code === 0 || !strict) {
277
+ resolve({
278
+ code,
279
+ signal,
280
+ stdout,
281
+ stderr
282
+ });
283
+ } else {
284
+ reject(
285
+ new Error(
286
+ `Process ${[command, ...args].join(" ")} exited ${code !== null ? `with code ${code}` : `with signal ${signal || ""}`}:
287
+ stdout: ${stdout.toString()}
288
+ stderr: ${stderr.toString()}`
289
+ )
290
+ );
291
+ }
292
+ });
293
+ });
294
+ }
295
+ const execCommand = (workspace, commandAndArgs = []) => {
296
+ const [command, ...args] = commandAndArgs;
297
+ return execvp(command, args, {
298
+ cwd: workspace.cwd,
299
+ strict: true
300
+ });
301
+ };
302
+
303
+ const getGitCurrentBranch = async (workspace) => {
304
+ const { stdout } = await execCommand(workspace, [
305
+ "git",
306
+ "rev-parse",
307
+ "--abbrev-ref",
308
+ "HEAD"
309
+ ]);
310
+ const currentBranch = stdout.trim();
311
+ if (currentBranch === "HEAD") {
312
+ throw new UsageError("HEAD is detached. Please checkout a branch.");
313
+ }
314
+ return currentBranch;
315
+ };
316
+ const createGitCommit = async (workspace, commitMessage) => {
317
+ await execCommand(workspace, ["git", "add", "-A"]);
318
+ await execCommand(workspace, [
319
+ "git",
320
+ "commit",
321
+ "--no-verify",
322
+ "-m",
323
+ commitMessage
324
+ ]);
325
+ };
326
+ const createGitTag = async (workspace, newTag) => {
327
+ await execCommand(workspace, ["git", "tag", newTag, "-m", newTag]);
328
+ };
329
+ const pushCommitsAndTags = async (workspace, gitRemote, currentBranch) => {
330
+ await execCommand(workspace, [
331
+ "git",
332
+ "push",
333
+ "--follow-tags",
334
+ "--no-verify",
335
+ "--atomic",
336
+ gitRemote,
337
+ currentBranch
338
+ ]);
339
+ };
340
+ const isBehindRemote = async (workspace, gitRemote, currentBranch) => {
341
+ await execCommand(workspace, ["git", "remote", "update", gitRemote]);
342
+ const { stdout } = await execCommand(workspace, [
343
+ "git",
344
+ "rev-list",
345
+ "--left-right",
346
+ "--count",
347
+ `${gitRemote}/${currentBranch}..${currentBranch}`
348
+ ]);
349
+ const [behind] = stdout.split(" ").map((val) => parseInt(val, 10));
350
+ return behind > 0;
351
+ };
352
+ const getDirtyFiles = async (workspace) => {
353
+ const { stdout: dirtyFiles } = await execCommand(workspace, [
354
+ "git",
355
+ "status",
356
+ "--porcelain"
357
+ ]);
358
+ return dirtyFiles;
359
+ };
360
+
361
+ async function createGitHubClient() {
362
+ const { GH_TOKEN, GHE_API_URL, GHE_VERSION } = process.env;
363
+ if (!GH_TOKEN) {
364
+ throw new UsageError(
365
+ '"GH_TOKEN" environment variable required when "createRelease" is set to "github"'
366
+ );
367
+ }
368
+ if (GHE_VERSION) {
369
+ Octokit.plugin(
370
+ await import(`@octokit/plugin-enterprise-rest/ghe-${GHE_VERSION}`)
371
+ );
372
+ }
373
+ const options = {
374
+ auth: `token ${GH_TOKEN}`
375
+ };
376
+ if (GHE_API_URL) {
377
+ options.baseUrl = GHE_API_URL;
378
+ }
379
+ return new Octokit(options);
380
+ }
381
+ const githubRegex = /^https?:\/\/github.com\/([^#/]+)\/([^#/]+?)(?:\.git)?$/;
382
+ const parseGithubRepoUrl = (workspace) => {
383
+ const repository = workspace.pkg.repository;
384
+ const url = typeof repository === "string" ? repository : repository?.url;
385
+ if (!url) {
386
+ throw new Error(
387
+ "No repository URL found in manifest. Please add one and try again. https://docs.npmjs.com/cli/v9/configuring-npm/package-json#repository"
388
+ );
389
+ }
390
+ const match = githubRegex.exec(url);
391
+ if (!match) {
392
+ throw new Error(`Invalid GitHub repository URL: "${url}"`);
393
+ }
394
+ const [, username, reponame] = match;
395
+ return { username, reponame };
396
+ };
397
+ const createGitRelease = async (githubClient, parsedRepoUrl, tag, body, prerelease) => {
398
+ await githubClient.repos.createRelease({
399
+ owner: parsedRepoUrl.username,
400
+ repo: parsedRepoUrl.reponame,
401
+ // eslint-disable-next-line camelcase
402
+ tag_name: tag,
403
+ name: tag,
404
+ body,
405
+ draft: false,
406
+ prerelease
407
+ });
408
+ };
409
+
410
+ const createProjectWorkspace = async (root) => {
411
+ const map = root.pkg.workspaces ? await mapWorkspaces({ cwd: root.cwd, pkg: root.pkg }) : /* @__PURE__ */ new Map();
412
+ const children = new Map(
413
+ await Promise.all(
414
+ [...map.entries()].map(
415
+ async ([packageName, packagePath]) => [
416
+ packageName,
417
+ {
418
+ ...await createWorkspace(packagePath),
419
+ relativeCwd: path.relative(root.cwd, packagePath)
420
+ }
421
+ ]
422
+ )
423
+ )
424
+ );
425
+ return { root, children };
426
+ };
427
+ const isAccessible = (path2) => fs.access(path2).then(
428
+ () => true,
429
+ () => false
430
+ );
431
+ const findRootWorkspace = async (cwd) => {
432
+ let currentPath = cwd;
433
+ do {
434
+ const isRootIfOneOfThesePathsExists = await Promise.all([
435
+ isAccessible(path.join(currentPath, ".yarnrc.yml")),
436
+ isAccessible(path.join(currentPath, "yarn.lock"))
437
+ ]);
438
+ if (isRootIfOneOfThesePathsExists.some(Boolean)) {
439
+ return createWorkspace(currentPath);
440
+ }
441
+ currentPath = path.dirname(currentPath);
442
+ } while (currentPath && currentPath !== "/");
443
+ return null;
444
+ };
445
+ const getPackageJsonPath = (cwd) => path.join(cwd, "package.json");
446
+ const createWorkspace = async (path2) => {
447
+ const pkg = await readPkg(path2);
448
+ return { cwd: path2, pkg };
449
+ };
450
+ async function writePkg(workspace, prettierOptions = void 0) {
451
+ const string = await prettyPkg(workspace.pkg, prettierOptions);
452
+ await fs.writeFile(getPackageJsonPath(workspace.cwd), string, "utf8");
453
+ }
454
+ async function readPkg(cwd) {
455
+ const packagePath = getPackageJsonPath(cwd);
456
+ const pkg = await fs.readFile(packagePath, "utf8").catch((error) => {
457
+ throw new Error(
458
+ `Failed to read package.json in "${cwd}": ${error instanceof Error ? error.message : String(error)}`
459
+ );
460
+ });
461
+ try {
462
+ return JSON.parse(pkg);
463
+ } catch (error) {
464
+ throw new Error(
465
+ `Failed to parse package.json in "${cwd}": ${error instanceof Error ? error.message : String(error)}`
466
+ );
467
+ }
468
+ }
469
+
470
+ const COMMIT_GUIDELINE = "See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.";
471
+ const CHANGELOG_HEADER = [
472
+ "# Changelog",
473
+ "",
474
+ "All notable changes to this project will be documented in this file.",
475
+ COMMIT_GUIDELINE,
476
+ ""
477
+ ].join("\n");
478
+ const updateChangelogFile = async (versionChangelogContent, tagPrefix, file = "CHANGELOG.md") => {
479
+ const START_OF_LAST_RELEASE_PATTERN = new RegExp(
480
+ `(^#+ \\[?(?:${tagPrefix})?\\d+\\.\\d+\\.\\d+|<a name=)`,
481
+ "m"
482
+ );
483
+ let oldContent = "";
484
+ try {
485
+ oldContent = await fs$1.readFile(file, "utf8");
486
+ const oldContentStart = oldContent.search(START_OF_LAST_RELEASE_PATTERN);
487
+ if (oldContentStart !== -1) {
488
+ oldContent = oldContent.slice(Math.max(0, oldContentStart));
489
+ }
490
+ } catch {
491
+ }
492
+ await fs$1.writeFile(
493
+ file,
494
+ `${CHANGELOG_HEADER}
495
+ ${versionChangelogContent}
496
+ ${oldContent}`
497
+ );
498
+ };
499
+
500
+ program.command("version").usage("Bump package version using conventional commit").addOption(
501
+ new Option("--includes-root", "Release root workspace [untested]").default(
502
+ false
503
+ )
504
+ ).addOption(new Option("--cwd", "working directory").default(process.cwd())).addOption(
505
+ new Option(
506
+ "--dry-run",
507
+ "Print the versions without actually generating the package archive"
508
+ ).default(false)
509
+ ).addOption(new Option("-v,--verbose").default(false)).addOption(
510
+ new Option("--force <type>", "Specify the release type").choices([
511
+ "major",
512
+ "minor",
513
+ "patch"
514
+ ])
515
+ ).addOption(
516
+ new Option(
517
+ "--prerelease [releaseType]",
518
+ "Add a prerelease identifier to new versions"
519
+ )
520
+ ).addOption(
521
+ new Option(
522
+ "--preset <presetName>",
523
+ "Conventional Changelog preset to require. Defaults to conventional-changelog-conventionalcommits."
524
+ ).default("conventional-changelog-conventionalcommits")
525
+ ).addOption(
526
+ new Option("--tag-version-prefix <prefix>", "Tag version prefix").default(
527
+ "v"
528
+ )
529
+ ).addOption(
530
+ new Option(
531
+ "--changelog <path>",
532
+ "Changelog path. Default to CHANGELOG.md."
533
+ ).default("CHANGELOG.md")
534
+ ).addOption(
535
+ new Option(
536
+ "-m,--commit-message <message>",
537
+ 'Commit message. Default to "chore: release %a". You can use %v for the version, %s for the version with prefix, %t to list tags, %a for auto best display.'
538
+ ).default("chore: release %a")
539
+ ).addOption(
540
+ new Option("--create-release <type>", "Create a release").choices([
541
+ "github"
542
+ ])
543
+ ).addOption(
544
+ new Option(
545
+ "--bump-dependents-highest-as <type>",
546
+ "Bump dependents highest version as major, minor or patch"
547
+ ).choices(["major", "minor", "patch"]).default("major")
548
+ ).addOption(
549
+ new Option(
550
+ "--always-bump-peer-dependencies",
551
+ "Always bump peer dependencies. Default to bumping only if the version doesn't satisfies the peer dependency range."
552
+ ).default(false)
553
+ ).addOption(
554
+ new Option(
555
+ "--git-remote <remote-name>",
556
+ "Git remote to push commits and tags to"
557
+ ).default("origin")
558
+ ).addOption(
559
+ new Option(
560
+ "--ignore-changes <glob>",
561
+ 'Ignore changes in files matching the glob. Example: "**/*.test.js"'
562
+ )
563
+ ).action(async (options) => {
564
+ if (options.json) {
565
+ process.env.NIGHTINGALE_CONSOLE_FORMATTER = "json";
566
+ }
567
+ addConfig({
568
+ pattern: /^yarn-version/,
569
+ handler: new ConsoleHandler(Level.INFO)
570
+ });
571
+ const logger = new Logger("yarn-version");
572
+ const rootWorkspace = await findRootWorkspace(options.cwd);
573
+ if (!rootWorkspace) {
574
+ throw new UsageError("Could not find root workspace from this path.");
575
+ }
576
+ const project = await createProjectWorkspace(rootWorkspace);
577
+ if (!options.dryRun) {
578
+ const dirtyFiles = await getDirtyFiles(project.root);
579
+ if (dirtyFiles) {
580
+ throw new Error(
581
+ `Dirty Files:
582
+ ${dirtyFiles}
583
+
584
+ There are uncommitted changes in the git repository. Please commit or stash them first.`
585
+ );
586
+ }
587
+ }
588
+ const rootWorkspaceChildren = [...project.children.values()];
589
+ let rootNewVersion = "";
590
+ let rootNewTag = "";
591
+ const isMonorepo = rootWorkspaceChildren.length > 0;
592
+ const isMonorepoVersionIndependent = isMonorepo && !rootWorkspace.pkg.version;
593
+ const workspaces = !isMonorepo || options.includesRoot ? [rootWorkspace, ...rootWorkspaceChildren] : rootWorkspaceChildren;
594
+ if (options.prerelease) {
595
+ throw new UsageError("--prerelease is not supported yet.");
596
+ }
597
+ if (options.ignoreChanges) {
598
+ throw new UsageError("--ignore-changes is not supported yet.");
599
+ }
600
+ const conventionalGitClient = new ConventionalGitClient(rootWorkspace.cwd);
601
+ const rootPreviousVersionTagPromise = options.force ? null : conventionalGitClient.getLastSemverTag({
602
+ prefix: options.tagVersionPrefix,
603
+ skipUnstable: true
604
+ });
605
+ const [
606
+ conventionalCommitConfig,
607
+ githubClient,
608
+ parsedRepoUrl,
609
+ gitCurrentBranch
610
+ ] = await Promise.all([
611
+ loadConventionalCommitConfig(rootWorkspace, options.preset),
612
+ // create client early to fail fast if necessary
613
+ options.createRelease ? createGitHubClient() : void 0,
614
+ options.createRelease ? parseGithubRepoUrl(rootWorkspace) : void 0,
615
+ getGitCurrentBranch(rootWorkspace)
616
+ ]);
617
+ const buildTagName = (workspace, version) => `${isMonorepo && workspace !== rootWorkspace ? `${getWorkspaceName(workspace)}@` : options.tagVersionPrefix}${version}`;
618
+ const changedWorkspaces = /* @__PURE__ */ new Map();
619
+ const dependenciesMap = isMonorepo ? buildDependenciesMaps(project) : null;
620
+ logger.info("Finding changed workspaces");
621
+ const bumpableWorkspaces = [];
622
+ for (const workspace of workspaces) {
623
+ const workspaceName = getWorkspaceName(workspace);
624
+ const isRoot = workspace === rootWorkspace;
625
+ if (isRoot && isMonorepo) continue;
626
+ const version = workspace.pkg.version;
627
+ if (!version || version === "0.0.0") {
628
+ if ((isRoot || isMonorepoVersionIndependent) && (!isMonorepo || !isMonorepoVersionIndependent)) {
629
+ throw new UsageError(
630
+ 'package.json has no version in its manifest. For the first release, set to "1.0.0-pre" or "0.1.0-pre".'
631
+ );
632
+ }
633
+ logger.info(`${workspaceName}: skipped (no version)`);
634
+ continue;
635
+ }
636
+ bumpableWorkspaces.push({
637
+ workspace,
638
+ workspaceName,
639
+ isRoot,
640
+ version
641
+ });
642
+ }
643
+ const previousTagByWorkspace = new Map(
644
+ await Promise.all(
645
+ bumpableWorkspaces.map(async ({ workspace, workspaceName, isRoot }) => {
646
+ const packageOption = isMonorepo && isMonorepoVersionIndependent ? workspaceName : void 0;
647
+ const previousVersionTagPrefix = packageOption ? `${packageOption}@` : options.tagVersionPrefix;
648
+ const previousTag = await (isRoot || !isMonorepoVersionIndependent ? rootPreviousVersionTagPromise : conventionalGitClient.getLastSemverTag({
649
+ prefix: previousVersionTagPrefix,
650
+ skipUnstable: true
651
+ }));
652
+ return [workspace, previousTag || void 0];
653
+ })
654
+ )
655
+ );
656
+ const commitsByWorkspace = options.force ? void 0 : new Map(
657
+ await Promise.all(
658
+ bumpableWorkspaces.map(async ({ workspace }) => {
659
+ const previousTag = previousTagByWorkspace.get(workspace);
660
+ const workspaceRelativePath = path.relative(
661
+ rootWorkspace.cwd,
662
+ workspace.cwd
663
+ );
664
+ return [
665
+ workspace,
666
+ await asyncIterableToArray(
667
+ conventionalGitClient.getCommits(
668
+ { path: workspaceRelativePath, from: previousTag },
669
+ conventionalCommitConfig.parser
670
+ )
671
+ )
672
+ ];
673
+ })
674
+ )
675
+ );
676
+ for (const { workspace, workspaceName } of bumpableWorkspaces) {
677
+ if (workspaceName !== "pob") continue;
678
+ let bumpType = null;
679
+ let bumpReason;
680
+ if (options.force) {
681
+ bumpType = options.force;
682
+ bumpReason = "forced by --force flag";
683
+ } else {
684
+ const commits = commitsByWorkspace?.get(workspace);
685
+ if (!commits || commits.length === 0) {
686
+ logger.info(`${workspaceName}: skipped (no changes)`);
687
+ continue;
688
+ }
689
+ const { releaseType, reason } = await recommendBump(
690
+ commits,
691
+ conventionalCommitConfig
692
+ );
693
+ bumpReason = reason;
694
+ if (releaseType) {
695
+ bumpType = releaseType;
696
+ }
697
+ }
698
+ if (bumpType) {
699
+ if (isMonorepo && !workspace.pkg.name) {
700
+ throw new Error("Workspace name is required");
701
+ }
702
+ const currentVersion = workspace.pkg.version;
703
+ if (!currentVersion) {
704
+ throw new UsageError(
705
+ `Invalid "${getWorkspaceName(workspace)}" version`
706
+ );
707
+ }
708
+ changedWorkspaces.set(workspace, {
709
+ bumpType,
710
+ bumpReason
711
+ });
712
+ }
713
+ }
714
+ if (changedWorkspaces.size === 0) {
715
+ logger.info("No changed workspaces");
716
+ return;
717
+ }
718
+ logger.info("Preparing bumping");
719
+ const bumpedWorkspaces = /* @__PURE__ */ new Map();
720
+ const noVersionToUpdateWorkspaces = /* @__PURE__ */ new Map();
721
+ const batches = dependenciesMap ? buildTopologicalOrderBatches(project, dependenciesMap) : [[rootWorkspace]];
722
+ for (const batch of batches) {
723
+ for (const workspace of batch) {
724
+ const currentVersion = workspace.pkg.version;
725
+ if (!currentVersion && !workspace.pkg.private) {
726
+ throw new UsageError(
727
+ `Invalid "${getWorkspaceName(workspace)}" version`
728
+ );
729
+ }
730
+ const changedWorkspace = changedWorkspaces.get(workspace);
731
+ let bumpType = null;
732
+ const bumpReasons = [];
733
+ const dependenciesToBump = [];
734
+ if (changedWorkspace) {
735
+ bumpType = changedWorkspace.bumpType;
736
+ bumpReasons.push(changedWorkspace.bumpReason || "by commits");
737
+ }
738
+ const dependencies = dependenciesMap?.get(workspace);
739
+ if (dependencies) {
740
+ for (const [
741
+ dependencyWorkspace,
742
+ dependencyType,
743
+ dependencyDescriptor
744
+ ] of dependencies) {
745
+ const dependencyBumpedWorkspace = bumpedWorkspaces.get(dependencyWorkspace);
746
+ if (!dependencyBumpedWorkspace) {
747
+ continue;
748
+ }
749
+ if (dependencyType === "peerDependencies" && !options.alwaysBumpPeerDependencies && // skip when peerdependency with a new version satisfied by the existing range.
750
+ satisfies(
751
+ dependencyBumpedWorkspace.newVersion,
752
+ dependencyDescriptor.selector,
753
+ { includePrerelease: true }
754
+ )) {
755
+ continue;
756
+ }
757
+ const newRange = calcBumpRange(
758
+ workspace,
759
+ dependencyDescriptor.selector,
760
+ dependencyBumpedWorkspace.newVersion
761
+ );
762
+ if (dependencyDescriptor.selector === newRange) {
763
+ continue;
764
+ }
765
+ dependenciesToBump.push([
766
+ dependencyType,
767
+ dependencyDescriptor,
768
+ newRange
769
+ ]);
770
+ bumpType = getHighestBumpType([
771
+ bumpType ?? "patch",
772
+ calcBumpType(
773
+ dependencyBumpedWorkspace.bumpType,
774
+ options.bumpDependentsHighestAs
775
+ )
776
+ ]);
777
+ bumpReasons.push(
778
+ `Version bump for dependency: ${PackageDescriptorNameUtils.stringify(dependencyDescriptor.name)}`
779
+ );
780
+ }
781
+ }
782
+ const workspaceName = getWorkspaceName(workspace);
783
+ if (!currentVersion) {
784
+ logger.info(`${workspaceName}: skipped (no version)`);
785
+ if (workspace !== rootWorkspace) {
786
+ noVersionToUpdateWorkspaces.set(workspace, {
787
+ dependenciesToBump
788
+ });
789
+ }
790
+ } else if (!bumpType) {
791
+ logger.info(
792
+ `${workspaceName}: skipped (${changedWorkspace ? `no bump recommended by ${options.preset}` : "no changes"})`
793
+ );
794
+ } else {
795
+ const newVersion = incrementVersion(
796
+ workspace,
797
+ currentVersion,
798
+ bumpType
799
+ );
800
+ const tagName = buildTagName(workspace, newVersion);
801
+ if (workspace === rootWorkspace) {
802
+ rootNewVersion = newVersion;
803
+ rootNewTag = tagName;
804
+ }
805
+ if (workspace !== rootWorkspace || !isMonorepo) {
806
+ const bumpReason = bumpReasons.join("\n");
807
+ bumpedWorkspaces.set(workspace, {
808
+ currentVersion,
809
+ bumpType,
810
+ bumpReason,
811
+ bumpForDependenciesReasons: bumpReasons.slice(1),
812
+ newVersion,
813
+ newTag: tagName,
814
+ hasChanged: changedWorkspace !== void 0,
815
+ dependenciesToBump
816
+ });
817
+ logger.info(
818
+ `${workspaceName}: ${currentVersion} -> ${!isMonorepo || isMonorepoVersionIndependent ? newVersion : "bump"} (${bumpReason.replace("\n", " ; ")})`
819
+ );
820
+ }
821
+ }
822
+ }
823
+ }
824
+ if (isMonorepo && !isMonorepoVersionIndependent) {
825
+ const currentVersion = rootWorkspace.pkg.version;
826
+ const highestBumpType = getHighestBumpType(
827
+ [...bumpedWorkspaces.values()].map(({ bumpType }) => bumpType)
828
+ );
829
+ const newVersion = incrementVersion(
830
+ rootWorkspace,
831
+ currentVersion,
832
+ highestBumpType
833
+ );
834
+ rootNewVersion = newVersion;
835
+ rootNewTag = buildTagName(rootWorkspace, newVersion);
836
+ [...bumpedWorkspaces.entries()].forEach(
837
+ ([workspace, bumpedWorkspace]) => {
838
+ const isRoot = workspace === rootWorkspace;
839
+ if (isRoot) {
840
+ throw new Error("Unexpected root found in bumped workspaces");
841
+ }
842
+ bumpedWorkspace.bumpType = highestBumpType;
843
+ bumpedWorkspace.newVersion = newVersion;
844
+ bumpedWorkspace.newTag = null;
845
+ }
846
+ );
847
+ [
848
+ ...bumpedWorkspaces.entries(),
849
+ ...noVersionToUpdateWorkspaces.entries()
850
+ ].forEach(([workspace, { dependenciesToBump }]) => {
851
+ dependenciesToBump.forEach((dependencyToBump) => {
852
+ dependencyToBump[2] = calcBumpRange(
853
+ workspace,
854
+ dependencyToBump[1].selector,
855
+ newVersion
856
+ );
857
+ });
858
+ });
859
+ bumpedWorkspaces.set(rootWorkspace, {
860
+ currentVersion,
861
+ bumpType: highestBumpType,
862
+ hasChanged: true,
863
+ newVersion: rootNewVersion,
864
+ newTag: rootNewTag,
865
+ dependenciesToBump: []
866
+ });
867
+ logger.info(
868
+ `${currentVersion} -> ${newVersion}`
869
+ // TODO Json only:
870
+ // {
871
+ // oldVersion: currentVersion,
872
+ // newVersion, },
873
+ );
874
+ }
875
+ logger.info(`${getWorkspaceName(rootWorkspace)}: Running install`);
876
+ spawnSync("yarn install", { cwd: options.cwd, stdio: "inherit" });
877
+ logger.info("Lifecycle script: preversion");
878
+ if (isMonorepoVersionIndependent && rootWorkspace.pkg.scripts?.preversion) {
879
+ spawnSync("yarn run preversion", {
880
+ cwd: rootWorkspace.cwd,
881
+ stdio: "inherit"
882
+ });
883
+ }
884
+ if (!options.dryRun) {
885
+ await Promise.all(
886
+ [...bumpedWorkspaces.entries()].map(async ([workspace]) => {
887
+ if (workspace.pkg.scripts?.preversion) {
888
+ spawnSync("yarn run preversion", {
889
+ cwd: workspace.cwd,
890
+ stdio: "inherit"
891
+ });
892
+ }
893
+ })
894
+ );
895
+ logger.info("Modifying versions in package.json");
896
+ await Promise.all(
897
+ [...bumpedWorkspaces.entries()].map(
898
+ ([workspace, { newVersion, dependenciesToBump }]) => {
899
+ workspace.pkg.version = newVersion;
900
+ for (const [
901
+ dependencyType,
902
+ dependencyDescriptor,
903
+ dependencyNewRange
904
+ ] of dependenciesToBump) {
905
+ const newDescriptor = PackageDependencyDescriptorUtils.make(
906
+ dependencyDescriptor,
907
+ dependencyNewRange
908
+ );
909
+ const [key, newValue] = PackageDependencyDescriptorUtils.stringify(newDescriptor);
910
+ workspace.pkg[dependencyType][key] = newValue;
911
+ }
912
+ return writePkg(workspace);
913
+ }
914
+ )
915
+ );
916
+ logger.info(`${getWorkspaceName(rootWorkspace)}: Running install`);
917
+ spawnSync("yarn install", {
918
+ cwd: options.cwd,
919
+ stdio: "inherit"
920
+ });
921
+ logger.info("Lifecycle script: version");
922
+ await Promise.all(
923
+ [...bumpedWorkspaces.entries()].map(async ([workspace]) => {
924
+ if (workspace.pkg.scripts?.version) {
925
+ spawnSync("yarn run version", {
926
+ cwd: workspace.cwd,
927
+ stdio: "inherit"
928
+ });
929
+ }
930
+ })
931
+ );
932
+ }
933
+ if (isMonorepoVersionIndependent && rootWorkspace.pkg.scripts?.version) {
934
+ spawnSync("yarn run version", {
935
+ cwd: rootWorkspace.cwd,
936
+ stdio: "inherit"
937
+ });
938
+ }
939
+ const changelogs = /* @__PURE__ */ new Map();
940
+ await Promise.all(
941
+ [...bumpedWorkspaces.entries()].map(
942
+ async ([
943
+ workspace,
944
+ { newTag, hasChanged, bumpReason, bumpForDependenciesReasons }
945
+ ]) => {
946
+ const workspaceRelativePath = rootWorkspace === workspace ? void 0 : path.relative(rootWorkspace.cwd, workspace.cwd);
947
+ let changelog = await generateChangelog(
948
+ rootWorkspace,
949
+ workspace.pkg,
950
+ conventionalCommitConfig,
951
+ newTag,
952
+ {
953
+ path: workspaceRelativePath,
954
+ previousTag: previousTagByWorkspace.get(workspace),
955
+ verbose: options.verbose,
956
+ tagPrefix: options.tagVersionPrefix,
957
+ lernaPackage: rootWorkspace === workspace || !isMonorepoVersionIndependent ? void 0 : getWorkspaceName(workspace)
958
+ }
959
+ );
960
+ if (changelog.slice(changelog.indexOf("\n")).trim().length === 0) {
961
+ changelog += "Note: no notable changes\n\n";
962
+ }
963
+ if (bumpForDependenciesReasons && workspace !== rootWorkspace) {
964
+ changelog += `${bumpForDependenciesReasons.join("\n")}
965
+
966
+ `;
967
+ }
968
+ changelogs.set(workspace, changelog);
969
+ if (options.changelog) {
970
+ if (options.dryRun) {
971
+ logger.info(
972
+ `${getWorkspaceName(workspace)}: ${options.changelog}
973
+ ${changelog}`
974
+ );
975
+ } else {
976
+ await updateChangelogFile(
977
+ changelog,
978
+ options.tagVersionPrefix,
979
+ `${workspace.cwd}/${options.changelog}`
980
+ );
981
+ }
982
+ }
983
+ }
984
+ )
985
+ );
986
+ if (!options.dryRun) {
987
+ console.log();
988
+ logger.info(`${getWorkspaceName(rootWorkspace)}: Running install`);
989
+ spawnSync("yarn install", {
990
+ cwd: options.cwd,
991
+ stdio: "inherit"
992
+ });
993
+ console.log();
994
+ logger.info("Commit, tag and push");
995
+ const tagsSet = new Set(
996
+ [...bumpedWorkspaces.values()].map(({ newTag }) => newTag).filter((newTag) => newTag !== null)
997
+ );
998
+ const tagsInCommitMessage = [...tagsSet].map((tag) => `- ${tag}`).join("\n");
999
+ const message = options.commitMessage.replace(/\\n/g, "\n").replace(
1000
+ /%a/g,
1001
+ isMonorepoVersionIndependent ? `
1002
+
1003
+ ${tagsInCommitMessage}` : rootNewVersion
1004
+ ).replace(/%s/g, rootNewTag).replace(/%v/g, rootNewVersion).replace(/%t/g, tagsInCommitMessage);
1005
+ await createGitCommit(rootWorkspace, message);
1006
+ for (const [workspace, { newTag }] of bumpedWorkspaces.entries()) {
1007
+ if (newTag === null) continue;
1008
+ await createGitTag(workspace, newTag);
1009
+ }
1010
+ if (await isBehindRemote(rootWorkspace, options.gitRemote, gitCurrentBranch)) {
1011
+ logger.error("Remote is ahead, aborting");
1012
+ process.exit(1);
1013
+ }
1014
+ if (rootWorkspace.pkg.scripts?.postversion) {
1015
+ spawnSync("yarn run postversion", {
1016
+ cwd: rootWorkspace.cwd,
1017
+ stdio: "inherit"
1018
+ });
1019
+ }
1020
+ await pushCommitsAndTags(
1021
+ rootWorkspace,
1022
+ options.gitRemote,
1023
+ gitCurrentBranch
1024
+ );
1025
+ if (options.createRelease && githubClient && parsedRepoUrl) {
1026
+ logger.info("Create git release");
1027
+ await Promise.all(
1028
+ [...bumpedWorkspaces.entries()].map(([workspace, { newTag }]) => {
1029
+ if (newTag === null) return void 0;
1030
+ const changelog = changelogs.get(workspace);
1031
+ if (!changelog) {
1032
+ logger.warn(
1033
+ `No changelog found for workspace: ${getWorkspaceName(
1034
+ workspace
1035
+ )}`
1036
+ );
1037
+ return void 0;
1038
+ }
1039
+ return createGitRelease(
1040
+ githubClient,
1041
+ parsedRepoUrl,
1042
+ newTag,
1043
+ changelog,
1044
+ !!options.prerelease
1045
+ );
1046
+ })
1047
+ );
1048
+ }
1049
+ }
1050
+ logger.success("Done");
1051
+ });
1052
+
1053
+ const pkg = JSON.parse(
1054
+ // eslint-disable-next-line unicorn/prefer-json-parse-buffer
1055
+ fs$2.readFileSync(new URL("../package.json", import.meta.url), "utf8")
1056
+ );
1057
+ program.name(pkg.name).description(pkg.description).version(pkg.version);
1058
+ program.parse();
1059
+ //# sourceMappingURL=index-node18.mjs.map