rolldown-pnpm-config 3.0.6 → 3.1.0

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.
@@ -71,7 +71,7 @@ function runExport(opts) {
71
71
  });
72
72
  const merged = overlayWorkspace(effective, parsed);
73
73
  const rendered = yield* Effect.fromResult(file.writeResult(merged)).pipe(Effect.mapError((e) => new ExportError({ message: e.message })));
74
- const localKeys = new Set(Object.keys(localCfg ?? {}));
74
+ const localKeys = new Set(Object.keys(localCfg ?? {}).filter((k) => WORKSPACE_FIELDS.has(k)));
75
75
  const tree = buildDiff(PnpmWorkspaceFile.canonicalize(parsed), PnpmWorkspaceFile.canonicalize(merged), {
76
76
  localKeys,
77
77
  managedKeys: WORKSPACE_FIELDS
@@ -0,0 +1,527 @@
1
+ import { dirname } from "node:path";
2
+ import { CliDoc, CliExit, CliFormat, CliMessage, Doc, Fmt } from "@effected/cli-kit";
3
+ import { AtomicFile } from "@effected/files";
4
+ import { PnpmWorkspaceFile } from "@effected/pnpm";
5
+ import { Data, Effect, FileSystem, Option, Path, Result } from "effect";
6
+ import { Argument, Command, Flag } from "effect/cli";
7
+ import { evaluatePluginConfig } from "../evaluate.js";
8
+ import { failureDoc, warningDoc } from "../render/report.js";
9
+ import { RegistryResolver } from "../resolve.js";
10
+ import { applyEdits } from "../rewrite.js";
11
+ import { renderCommitMessage } from "../sync/commit-message.js";
12
+ import { SyncConfigError, resolveEvaluatedSync } from "../sync/config.js";
13
+ import { applyFloorEdits, describeFloorEdits, planFloorEdits } from "../sync/floors.js";
14
+ import { exportDrift, exportedCatalogNames, readServedCatalogs } from "../sync/local-gate.js";
15
+ import { MEMBERSHIP_REMEDY, checkMembership, membershipMessage, pluginManifest, pluginPackageName } from "../sync/membership.js";
16
+ import { readReleasePlan } from "../sync/release-plan.js";
17
+ import { rippleEdits, rippleMismatches } from "../sync/ripples.js";
18
+ import { currentCatalogs, mergeMoves, parseChangeset, renderChangeset, staleMoves } from "../sync/running-list.js";
19
+ import { findWorkspaceRoot, makeWorkspaceResolver } from "../workspace-resolve.js";
20
+ import { CHECK_FAILED_LABEL, UpgradeError, checkJsonOutcome, readCatalogSource, resolveTargetFile, runUpgrade } from "./upgrade.js";
21
+
22
+ // src/cli/commands/sync.ts
23
+ /**
24
+ * An invalid `sync` flag combination: a usage error, so it exits 64 (mapped by
25
+ * tag in `EXIT_CODES`).
26
+ *
27
+ * @internal
28
+ */
29
+ var SyncUsageError = class extends Data.TaggedError("SyncUsageError") {
30
+ /** The failure report `CliRuntime.main` prints: the message, without the class name. */
31
+ [CliDoc]() {
32
+ return failureDoc(this.message);
33
+ }
34
+ };
35
+ /**
36
+ * Publishable workspace packages the sync catalog does not name. Raised before
37
+ * any write: a sync that upgraded versions while a member was missing would
38
+ * report "synced" for a catalog that is still incomplete. A finding, exit 1.
39
+ *
40
+ * @internal
41
+ */
42
+ var MembershipError = class extends Data.TaggedError("MembershipError") {
43
+ /** The failure report: the `membershipMessage` text. */
44
+ [CliDoc]() {
45
+ return failureDoc(this.message);
46
+ }
47
+ };
48
+ /** Read and decode the `sync` block of the config at `configFile`. */
49
+ function readSyncConfig(configFile) {
50
+ return Effect.gen(function* () {
51
+ const { source } = yield* readCatalogSource(configFile);
52
+ const evaluated = yield* Effect.try({
53
+ try: () => evaluatePluginConfig(source, configFile),
54
+ catch: (error) => new SyncConfigError({ message: `cannot evaluate ${configFile}: ${Fmt.errorText(error)}` })
55
+ });
56
+ return yield* resolveEvaluatedSync(evaluated, configFile);
57
+ });
58
+ }
59
+ /** Write `content` to `file` atomically; a failure is the run's, like upgrade's own write. */
60
+ function writeFile(file, content) {
61
+ return Effect.gen(function* () {
62
+ const fs = yield* FileSystem.FileSystem;
63
+ const path = yield* Path.Path;
64
+ yield* fs.makeDirectory(path.dirname(file), { recursive: true });
65
+ yield* AtomicFile.write(file, content);
66
+ }).pipe(Effect.mapError(() => new UpgradeError({ message: `Cannot write ${file}` })));
67
+ }
68
+ /** The running-list changeset at `file`, or none when there is none yet. */
69
+ function readRunningList(file) {
70
+ return Effect.gen(function* () {
71
+ return yield* (yield* FileSystem.FileSystem).readFileString(file).pipe(Effect.map(Option.some), Effect.catchTag("PlatformError", (error) => error.reason._tag === "NotFound" ? Effect.succeed(Option.none()) : Effect.fail(error)), Effect.mapError(() => new UpgradeError({ message: `Cannot read ${file}` })));
72
+ });
73
+ }
74
+ /** Write the running list and the commit message for `moves`. */
75
+ function writeListAndMessage(rootDir, sync, pluginName, moves) {
76
+ return Effect.gen(function* () {
77
+ const path = yield* Path.Path;
78
+ yield* writeFile(path.join(rootDir, sync.changesetPath), renderChangeset(pluginName, sync.bump, moves, sync.catalog));
79
+ yield* writeFile(path.join(rootDir, sync.messagePath), renderCommitMessage(sync.commitScope, moves));
80
+ });
81
+ }
82
+ /**
83
+ * Bring the sync catalog in the config at `configFile` to the next release
84
+ * versions, and record the moves in the running-list changeset.
85
+ *
86
+ * @remarks
87
+ * The order is the scripts' and each step has its reason:
88
+ *
89
+ * 1. Membership, before any write: a sync that upgrades versions while a
90
+ * member is missing would report success for an incomplete catalog.
91
+ * 2. Floors, when `sync.floors` is on, before the plan is read: a raised
92
+ * package releases at a new minor, and the catalog must name that version.
93
+ * 3. The release plan, read before the config is rewritten, so a plan that
94
+ * cannot be read fails the run with the config, the running list and the
95
+ * commit message unchanged (step 2 may already have written floors).
96
+ * 4. A snapshot of the config, which decides whether the catalog moved: the
97
+ * file cannot disagree with itself.
98
+ * 5. The upgrade (`--yes`), scoped to the sync catalog.
99
+ * 6. Ripples, read from the config the upgrade just wrote: a package bumped
100
+ * only as a dependency ripple has no changeset, so the upgrade cannot see it.
101
+ * 7. If the config did not move, the running list is rewritten only when it is
102
+ * stale (hand-edited, or carried over a merge), so a sync repairs it.
103
+ * Otherwise this run's moves are merged into it: it lists every move since
104
+ * the last release, never just the latest.
105
+ * 8. The commit message, written beside the running list.
106
+ *
107
+ * @internal
108
+ */
109
+ const runSyncWrite = Effect.fn("Sync.runSyncWrite")(function* (opts) {
110
+ const path = yield* Path.Path;
111
+ const file = opts.configFile;
112
+ const sync = yield* readSyncConfig(file);
113
+ const rootDir = findWorkspaceRoot(dirname(path.resolve(file)));
114
+ const membership = yield* checkMembership(file, rootDir, sync);
115
+ if (membership.missing.length > 0) return yield* new MembershipError({
116
+ message: membershipMessage(membership.missing, file),
117
+ missing: membership.missing
118
+ });
119
+ const pluginName = yield* pluginPackageName(file);
120
+ let floors = 0;
121
+ if (sync.floors) {
122
+ const { edits } = yield* planFloorEdits(rootDir);
123
+ yield* applyFloorEdits(rootDir, edits).pipe(Effect.mapError(() => new UpgradeError({ message: `Cannot write the breaking-floor changesets in ${rootDir}` })));
124
+ floors = edits.length;
125
+ }
126
+ const plan = yield* readReleasePlan(rootDir);
127
+ const before = (yield* readCatalogSource(file)).source;
128
+ const upgraded = yield* runUpgrade({
129
+ file,
130
+ resolver: opts.resolver,
131
+ workspaceResolver: opts.workspaceResolver,
132
+ catalog: sync.catalog
133
+ });
134
+ const { source: afterUpgrade, entries } = yield* readCatalogSource(file, sync.catalog);
135
+ const ripples = yield* rippleMismatches(entries, plan);
136
+ if (ripples.length > 0) yield* writeFile(file, applyEdits(afterUpgrade, rippleEdits(entries, ripples)));
137
+ const after = yield* readCatalogSource(file);
138
+ const current = currentCatalogs(after.entries);
139
+ const existing = yield* readRunningList(path.join(rootDir, sync.changesetPath));
140
+ const pending = Option.match(existing, {
141
+ onNone: () => [],
142
+ onSome: parseChangeset
143
+ });
144
+ if (after.source === before) {
145
+ const stale = Option.isSome(existing) && staleMoves(pending, current).length > 0;
146
+ if (stale) yield* writeListAndMessage(rootDir, sync, pluginName, mergeMoves(pending, [], current));
147
+ return {
148
+ moves: [],
149
+ ripples,
150
+ floors,
151
+ membership,
152
+ wrote: stale || floors > 0,
153
+ listWritten: stale
154
+ };
155
+ }
156
+ const fresh = [...upgraded.changed.map((row) => ({
157
+ catalog: row.catalog,
158
+ pkg: row.pkg,
159
+ from: row.from,
160
+ to: row.to ?? row.from,
161
+ peer: void 0
162
+ })), ...ripples.map((r) => ({
163
+ catalog: r.catalog,
164
+ pkg: r.pkg,
165
+ from: r.from,
166
+ to: r.to,
167
+ peer: r.peer
168
+ }))];
169
+ yield* writeListAndMessage(rootDir, sync, pluginName, mergeMoves(pending, fresh, current));
170
+ return {
171
+ moves: mergeMoves([], fresh, current),
172
+ ripples,
173
+ floors,
174
+ membership,
175
+ wrote: true,
176
+ listWritten: true
177
+ };
178
+ });
179
+ /** The remedy for everything a plain `sync` repairs. */
180
+ const syncRemedy = (configFile) => `Run \`rolldown-pnpm-config sync ${configFile}\`.`;
181
+ /** The remedy for export drift: the export writes the yaml, the rebuild serves what it wrote. */
182
+ const EXPORT_REMEDY = "Run `pnpm pnpm:export`, then rebuild the plugin.";
183
+ /** A section with nothing to report. */
184
+ const ok = (section) => ({
185
+ section,
186
+ status: "ok"
187
+ });
188
+ /** `rows` as findings, or ok when there are none. */
189
+ const findings = (section, rows, remedy) => rows.length === 0 ? ok(section) : {
190
+ section,
191
+ status: "findings",
192
+ rows,
193
+ remedy
194
+ };
195
+ /**
196
+ * Evaluate one section. A typed failure becomes its `error` status, so one
197
+ * section that cannot be read never hides the verdict of the next.
198
+ */
199
+ function evaluate(section, effect) {
200
+ return effect.pipe(Effect.catch((error) => Effect.succeed({
201
+ section,
202
+ status: "error",
203
+ kind: error._tag,
204
+ message: error.message
205
+ })));
206
+ }
207
+ /** One drift row: `catalog.pkg from -> to (source)`; a peer-only resync keeps its range. */
208
+ function driftRow(row) {
209
+ const move = row.to === void 0 ? `${row.from} (peer only)` : `${row.from} -> ${row.to}`;
210
+ return ` ${row.catalog}.${row.pkg} ${move} (${row.source})`;
211
+ }
212
+ /**
213
+ * Versions: the upgrade's own check, a dry run scoped to the sync catalog.
214
+ * Also returns the rows the upgrade would move (none when it errored), which
215
+ * the ripples section lays over the config.
216
+ */
217
+ function versionsSection(opts, sync) {
218
+ return runUpgrade({
219
+ file: opts.configFile,
220
+ resolver: opts.resolver,
221
+ workspaceResolver: opts.workspaceResolver,
222
+ catalog: sync.catalog,
223
+ dryRun: true
224
+ }).pipe(Effect.result, Effect.map((result) => {
225
+ const { failure } = checkJsonOutcome(result);
226
+ if (failure !== void 0) return {
227
+ section: {
228
+ section: "versions",
229
+ status: "error",
230
+ kind: failure.kind ?? "resolution",
231
+ message: failure.message
232
+ },
233
+ changed: []
234
+ };
235
+ const changed = Result.isSuccess(result) ? result.success.changed : [];
236
+ return {
237
+ section: findings("versions", changed.map(driftRow), syncRemedy(opts.configFile)),
238
+ changed
239
+ };
240
+ }));
241
+ }
242
+ /** Membership: publishable workspace members the sync catalog does not name. */
243
+ function membershipSection(configFile, rootDir, sync) {
244
+ return evaluate("membership", checkMembership(configFile, rootDir, sync).pipe(Effect.map((m) => findings("membership", m.missing.map((name) => ` - ${name}`), MEMBERSHIP_REMEDY))));
245
+ }
246
+ /** Floors: the breaking-floor changesets on disk differ from the ones the plan derives. */
247
+ function floorsSection(configFile, rootDir) {
248
+ return evaluate("floors", planFloorEdits(rootDir).pipe(Effect.map(({ raised, edits }) => findings("floors", describeFloorEdits(raised, edits).split("\n").filter((line) => line !== ""), syncRemedy(configFile)))));
249
+ }
250
+ /** The running list: a pending list whose moves disagree with the config. Absent is in sync. */
251
+ function runningListSection(configFile, rootDir, sync) {
252
+ return evaluate("running-list", Effect.gen(function* () {
253
+ const existing = yield* readRunningList((yield* Path.Path).join(rootDir, sync.changesetPath));
254
+ if (Option.isNone(existing)) return ok("running-list");
255
+ const { entries } = yield* readCatalogSource(configFile);
256
+ const stale = staleMoves(parseChangeset(existing.value), currentCatalogs(entries));
257
+ return findings("running-list", stale, syncRemedy(configFile));
258
+ }));
259
+ }
260
+ /**
261
+ * Ripples: entries behind the version the release plan would release, which
262
+ * the upgrade cannot see.
263
+ *
264
+ * @remarks
265
+ * Write mode looks for ripples after the upgrade has run, so `upgraded` (the
266
+ * versions section's drift rows) is laid over the config first: a package the
267
+ * upgrade moves is a versions row, never a ripple too. When versions errored,
268
+ * `upgraded` is empty and the list is unfiltered. With `floors: true`, the
269
+ * targets come from the plan before any floor is raised (write mode raises
270
+ * floors first), so a row can differ from what a sync would write.
271
+ */
272
+ function ripplesSection(configFile, rootDir, sync, upgraded) {
273
+ return evaluate("ripples", Effect.gen(function* () {
274
+ const plan = yield* readReleasePlan(rootDir);
275
+ const { entries } = yield* readCatalogSource(configFile, sync.catalog);
276
+ const moved = new Map(upgraded.map((row) => [`${row.catalog}\0${row.pkg}`, row.to]));
277
+ const afterUpgrade = entries.map((entry) => {
278
+ const to = moved.get(`${entry.catalog}\0${entry.pkg}`);
279
+ return to === void 0 ? entry : {
280
+ ...entry,
281
+ currentRange: to
282
+ };
283
+ });
284
+ const rows = (yield* rippleMismatches(afterUpgrade, plan)).map((r) => ` ${r.catalog}.${r.pkg} ${r.from} -> ${r.to}`);
285
+ return findings("ripples", rows, syncRemedy(configFile));
286
+ }));
287
+ }
288
+ /**
289
+ * Export parity: the exported catalogs in `pnpm-workspace.yaml` against what
290
+ * the built pnpmfile serves. A missing build is a finding (build it), not an
291
+ * error: nothing is wrong with the tree that a build does not fix.
292
+ */
293
+ function exportSection(configFile, rootDir, sync) {
294
+ return evaluate("export", Effect.gen(function* () {
295
+ const fs = yield* FileSystem.FileSystem;
296
+ const path = yield* Path.Path;
297
+ const pnpmfile = path.resolve(path.dirname(yield* pluginManifest(configFile)), sync.pnpmfile);
298
+ const served = yield* readServedCatalogs(pnpmfile).pipe(Effect.result);
299
+ if (Result.isFailure(served)) {
300
+ if (yield* fs.exists(pnpmfile)) return yield* Effect.fail(served.failure);
301
+ return findings("export", [` ${pnpmfile}: not built`], served.failure.message);
302
+ }
303
+ const source = yield* fs.readFileString(path.join(rootDir, "pnpm-workspace.yaml"));
304
+ const workspace = yield* PnpmWorkspaceFile.parse(source);
305
+ const names = exportedCatalogNames(served.success, sync);
306
+ return findings("export", exportDrift(served.success, names, { ...workspace.value }), EXPORT_REMEDY);
307
+ }));
308
+ }
309
+ /** What both gates start from: the decoded `sync` block and the workspace root. */
310
+ function gateContext(configFile) {
311
+ return Effect.gen(function* () {
312
+ const path = yield* Path.Path;
313
+ return {
314
+ sync: yield* readSyncConfig(configFile),
315
+ rootDir: findWorkspaceRoot(dirname(path.resolve(configFile)))
316
+ };
317
+ });
318
+ }
319
+ /** The document over `sections`, `evaluated` derived from them. */
320
+ function checkDoc(mode, sections) {
321
+ return {
322
+ command: "sync",
323
+ mode,
324
+ evaluated: sections.every((s) => s.status !== "error"),
325
+ sections
326
+ };
327
+ }
328
+ /**
329
+ * Report whether a plain `sync` would change anything, and why. Never writes.
330
+ *
331
+ * @remarks
332
+ * Every section is evaluated, in the order versions, membership, floors (when
333
+ * `sync.floors` is on), running-list, ripples, and none short-circuits: the
334
+ * scripts this ports stop at the first failure, but a red check that lists
335
+ * everything saves a round trip. Only an unreadable or invalid config fails
336
+ * the run; a section that cannot be evaluated is an `error` section.
337
+ *
338
+ * @internal
339
+ */
340
+ const runSyncCheck = Effect.fn("Sync.runSyncCheck")(function* (opts) {
341
+ const file = opts.configFile;
342
+ const { sync, rootDir } = yield* gateContext(file);
343
+ const versions = yield* versionsSection(opts, sync);
344
+ const rest = yield* Effect.all([
345
+ membershipSection(file, rootDir, sync),
346
+ ...sync.floors ? [floorsSection(file, rootDir)] : [],
347
+ runningListSection(file, rootDir, sync),
348
+ ripplesSection(file, rootDir, sync, versions.changed)
349
+ ]);
350
+ return checkDoc("check", [versions.section, ...rest]);
351
+ });
352
+ /**
353
+ * The offline push-time gate: membership, and that the exported catalogs in
354
+ * `pnpm-workspace.yaml` match what the built plugin serves. No registry, no
355
+ * release plan, no version drift; writes nothing.
356
+ *
357
+ * @remarks
358
+ * The sync catalog and its `:peers` sibling are not exported by default, so a
359
+ * lagging sync catalog in the yaml is not reported: that is `--check`'s
360
+ * versions question, and it needs the network.
361
+ *
362
+ * @internal
363
+ */
364
+ const runSyncLocal = Effect.fn("Sync.runSyncLocal")(function* (opts) {
365
+ const file = opts.configFile;
366
+ const { sync, rootDir } = yield* gateContext(file);
367
+ return checkDoc("local", yield* Effect.all([membershipSection(file, rootDir, sync), exportSection(file, rootDir, sync)]));
368
+ });
369
+ /** The gate's exit code: 0 when every section is ok, 1 for any finding or error. @internal */
370
+ function syncCheckExit(doc) {
371
+ return doc.sections.every((s) => s.status === "ok") ? 0 : 1;
372
+ }
373
+ /** A finding section's heading. */
374
+ function findingsHeading(section, count) {
375
+ switch (section) {
376
+ case "versions": return `Catalog drift detected in ${Fmt.plural(count, "package")}:`;
377
+ case "membership": return "Publishable packages missing from the catalog:";
378
+ case "floors": return `Breaking floors are out of date in ${Fmt.plural(count, "changeset")}:`;
379
+ case "running-list": return `The running list disagrees with the catalog config on ${Fmt.plural(count, "package")}:`;
380
+ case "ripples": return `Catalog is behind on ${Fmt.plural(count, "dependency-ripple bump")}:`;
381
+ case "export": return "pnpm-workspace.yaml does not match the catalogs the built plugin serves:";
382
+ }
383
+ }
384
+ /** The human view of a gate run: every section that is not ok, in order. @internal */
385
+ function syncCheckView(doc) {
386
+ const failing = doc.sections.filter((s) => s.status !== "ok");
387
+ if (failing.length === 0) return [Doc.line(doc.mode === "check" ? "Catalogs are in sync." : "Catalog membership and the exported catalogs are in sync.")];
388
+ return failing.map((s) => {
389
+ if (s.status === "findings") return Doc.section(void 0, [
390
+ Doc.line(findingsHeading(s.section, s.rows.length)),
391
+ Doc.lines(s.rows, { wrap: false }),
392
+ Doc.line(s.remedy)
393
+ ]);
394
+ const heading = s.section === "versions" ? CHECK_FAILED_LABEL : `The ${s.section} section could not be evaluated (${s.kind}, not a finding):`;
395
+ return Doc.section(void 0, [Doc.line(heading), Doc.lines(s.message.split("\n").map((line) => ` ${line}`), { wrap: false })]);
396
+ });
397
+ }
398
+ /** One move as a report line: `catalog.pkg from -> to`. */
399
+ function moveLine(move, note = "") {
400
+ return ` ${move.catalog}.${move.pkg} ${move.from} -> ${move.to}${note}`;
401
+ }
402
+ /** The human view of a write-mode run. @internal */
403
+ function syncWriteDoc(result) {
404
+ if (!result.wrote) return [Doc.line("The sync catalog is current; nothing written.")];
405
+ const rippled = new Set(result.ripples.map((r) => `${r.catalog}\0${r.pkg}`));
406
+ const blocks = [];
407
+ if (result.moves.length > 0) {
408
+ blocks.push(Doc.line(`Synced ${Fmt.plural(result.moves.length, "catalog entry", "catalog entries")}:`));
409
+ blocks.push(Doc.lines(result.moves.map((m) => moveLine(m, rippled.has(`${m.catalog}\0${m.pkg}`) ? " (ripple)" : "")), { wrap: false }));
410
+ } else if (result.listWritten) blocks.push(Doc.line("The catalog was current; rewrote the stale running list."));
411
+ else blocks.push(Doc.line("The catalog was current; the running list was left as it was."));
412
+ if (result.floors > 0) blocks.push(Doc.line(`Updated ${Fmt.plural(result.floors, "breaking-floor changeset")}.`));
413
+ return blocks;
414
+ }
415
+ /**
416
+ * The `--format json` document of a write-mode run.
417
+ *
418
+ * @remarks
419
+ * On failure `wrote` and `listWritten` are `false` and make no claim about
420
+ * what the run wrote before it failed: a run that failed after its floors
421
+ * step or its upgrade may already have written floor changesets or the
422
+ * config. The documents say so; tracking each write is not worth the state.
423
+ *
424
+ * @internal
425
+ */
426
+ function syncWriteJson(result) {
427
+ if (Result.isFailure(result)) {
428
+ const { _tag, message } = result.failure;
429
+ return {
430
+ command: "sync",
431
+ mode: "write",
432
+ wrote: false,
433
+ listWritten: false,
434
+ error: {
435
+ kind: _tag,
436
+ message
437
+ }
438
+ };
439
+ }
440
+ const { moves, ripples, membership, wrote, listWritten } = result.success;
441
+ return {
442
+ command: "sync",
443
+ mode: "write",
444
+ moves,
445
+ ripples,
446
+ membership,
447
+ wrote,
448
+ listWritten
449
+ };
450
+ }
451
+ const configArg = Argument.File("config").pipe(Argument.withDescription("The plugin config holding the `sync` block (autodetected in the current directory when omitted)"), Argument.optional);
452
+ const checkFlag = Flag.Boolean("check").pipe(Flag.withDescription("Report whether a sync would change anything, and why (a gate; never writes)"), Flag.withDefault(false));
453
+ const localFlag = Flag.Boolean("local").pipe(Flag.withDescription("Compare the built pnpmfile's catalogs with pnpm-workspace.yaml (offline; never writes)"), Flag.withDefault(false));
454
+ const formatFlag = CliFormat.flag(["json"], {
455
+ aliases: { text: "auto" },
456
+ default: "text",
457
+ description: "Output format: text (for whoever is reading) or json (one JSON document on stdout)"
458
+ });
459
+ /** JSON mode writes one single-line document, so a bash gate can pipe it straight into jq. */
460
+ const ONE_LINE = { indent: 0 };
461
+ /**
462
+ * The "sync" command. Plain mode brings the `sync` block's catalog to the next
463
+ * release versions and records the moves in the running-list changeset.
464
+ * `--check` and `--local` are the gates, and are mutually exclusive.
465
+ *
466
+ * @internal
467
+ */
468
+ const syncCommand = Command.make("sync", {
469
+ config: configArg,
470
+ check: checkFlag,
471
+ local: localFlag,
472
+ format: formatFlag
473
+ }, ({ config, check, local, format }) => Effect.gen(function* () {
474
+ if (check && local) return yield* new SyncUsageError({ message: "--check and --local cannot be combined; pass one" });
475
+ if (check || local) {
476
+ const mode = check ? "check" : "local";
477
+ const result = yield* resolveTargetFile(config).pipe(Effect.flatMap((file) => check ? Effect.flatMap(RegistryResolver, (resolver) => runSyncCheck({
478
+ configFile: file,
479
+ resolver,
480
+ workspaceResolver: makeWorkspaceResolver(findWorkspaceRoot(dirname(file)))
481
+ })) : runSyncLocal({ configFile: file })), Effect.result);
482
+ if (Result.isFailure(result)) {
483
+ if (format === "json") {
484
+ const { _tag, message } = result.failure;
485
+ const json = {
486
+ command: "sync",
487
+ mode,
488
+ evaluated: false,
489
+ sections: [],
490
+ error: {
491
+ kind: _tag,
492
+ message
493
+ }
494
+ };
495
+ yield* CliFormat.print("json", {
496
+ doc: () => [],
497
+ json: () => json
498
+ }, ONE_LINE);
499
+ }
500
+ return yield* Effect.fail(result.failure);
501
+ }
502
+ const doc = result.success;
503
+ yield* CliFormat.print(format === "json" ? "json" : "auto", {
504
+ doc: () => syncCheckView(doc),
505
+ json: () => doc
506
+ }, ONE_LINE);
507
+ return yield* CliExit.set(syncCheckExit(doc));
508
+ }
509
+ const resolver = yield* RegistryResolver;
510
+ const result = yield* resolveTargetFile(config).pipe(Effect.flatMap((file) => runSyncWrite({
511
+ configFile: file,
512
+ resolver,
513
+ workspaceResolver: makeWorkspaceResolver(findWorkspaceRoot(dirname(file)))
514
+ })), Effect.result);
515
+ if (format === "json") yield* CliFormat.print("json", {
516
+ doc: () => [],
517
+ json: () => syncWriteJson(result)
518
+ }, ONE_LINE);
519
+ if (Result.isFailure(result)) return yield* Effect.fail(result.failure);
520
+ const success = result.success;
521
+ for (const ripple of success.ripples) if (ripple.warning !== void 0) yield* Doc.print(warningDoc(`${ripple.catalog}.${ripple.pkg}: ${ripple.warning}`), { stream: "stderr" });
522
+ if (format === "json") return;
523
+ yield* Doc.print(syncWriteDoc(success));
524
+ if (success.wrote) yield* CliMessage.success("Sync written.");
525
+ })).pipe(Command.withDescription("Sync the plugin's own catalog to the next release versions"));
526
+
527
+ export { MembershipError, SyncUsageError, runSyncCheck, runSyncLocal, runSyncWrite, syncCheckExit, syncCheckView, syncCommand, syncWriteDoc, syncWriteJson };
package/cli/effective.js CHANGED
@@ -1,5 +1,6 @@
1
+ import { WORKSPACE_FIELDS } from "../registry.js";
1
2
  import { excludeByRepo } from "../runtime/ctx.js";
2
- import { applyLocalDirective } from "./local-merge.js";
3
+ import { MAP_EXPORT_FIELDS, UNION_EXPORT_FIELDS, applyLocalDirective } from "./local-merge.js";
3
4
 
4
5
  // src/cli/effective.ts
5
6
  /** Apply the manifest's excludeByRepo refine to publicHoistPattern, if present. */
@@ -12,13 +13,22 @@ function applyExcludeByRepo(out, manifest, rootName) {
12
13
  * Compute the effective workspace fields for THIS repo: managed base, then
13
14
  * excludeByRepo on publicHoistPattern, then per-field local directives.
14
15
  * `overrides` always runs (default file-protocol preserve), even with no local.
16
+ * Union- and map-strategy fields also keep the existing file's entries unless `rewrite`.
17
+ * Only `local` keys that are managed workspace settings apply: a plugin-only
18
+ * key (`localPatchesDir`) or any other non-setting never reaches the yaml.
15
19
  *
16
20
  * @internal
17
21
  */
18
22
  function effectiveManaged(managed, local, parsed, manifest, rootName) {
19
23
  const out = { ...managed };
20
24
  applyExcludeByRepo(out, manifest, rootName);
21
- const fields = /* @__PURE__ */ new Set(["overrides", ...Object.keys(local ?? {})]);
25
+ const keepFileFields = [...UNION_EXPORT_FIELDS, ...MAP_EXPORT_FIELDS].filter((f) => f in out || f in parsed);
26
+ const localFields = Object.keys(local ?? {}).filter((f) => WORKSPACE_FIELDS.has(f));
27
+ const fields = /* @__PURE__ */ new Set([
28
+ "overrides",
29
+ ...keepFileFields,
30
+ ...localFields
31
+ ]);
22
32
  for (const field of fields) {
23
33
  const next = applyLocalDirective(out[field], local?.[field], parsed[field], field);
24
34
  if (next === void 0) delete out[field];
package/cli/exit-codes.js CHANGED
@@ -7,10 +7,17 @@
7
7
  *
8
8
  * `UpgradeUsageError` is the command's own invalid flag combination (`--format
9
9
  * json` outside `--check`/`--yes`/`--dry-run`), so it shares the parser's 64
10
- * (BSD `EX_USAGE`) rather than a resolution failure's 1.
10
+ * (BSD `EX_USAGE`) rather than a resolution failure's 1. `SyncUsageError`
11
+ * (`sync --check --local`) and `SyncConfigError` (an absent or malformed
12
+ * `sync` block) are usage errors too. Every other sync failure — membership,
13
+ * workspace discovery, the release plan, the upgrade — stays at 1.
11
14
  *
12
15
  * @internal
13
16
  */
14
- const EXIT_CODES = { UpgradeUsageError: 64 };
17
+ const EXIT_CODES = {
18
+ UpgradeUsageError: 64,
19
+ SyncUsageError: 64,
20
+ SyncConfigError: 64
21
+ };
15
22
 
16
23
  export { EXIT_CODES };
@@ -1,4 +1,7 @@
1
1
  import { Array as Array$1, Predicate } from "effect";
2
+ import { FIELD_REGISTRY } from "../registry.js";
3
+ import { sectionMerge, unionRecord } from "../runtime/strategies/arrays.js";
4
+ import { mapChildWins } from "../runtime/strategies/maps.js";
2
5
 
3
6
  // src/cli/local-merge.ts
4
7
  /** Default protocols whose existing-file override entries are preserved. @internal */
@@ -8,6 +11,53 @@ const DEFAULT_PRESERVE = [
8
11
  "workspace",
9
12
  "portal"
10
13
  ];
14
+ /**
15
+ * Fields whose runtime strategy unions the file with the managed value, derived
16
+ * from `FIELD_REGISTRY` so `export` keeps hand-added entries as install does.
17
+ * `local: { strategy: "rewrite" }` opts a field back into overwrite.
18
+ *
19
+ * @internal
20
+ */
21
+ const UNION_EXPORT_FIELDS = new Set(Object.entries(FIELD_REGISTRY).filter(([, p]) => p.strategy === "arrayUnion" || p.strategy === "arrayRecordUnion").map(([name]) => name));
22
+ /** The runtime map strategies `export` replays, the file as base and the managed value on top. */
23
+ const MAP_STRATEGIES = {
24
+ mapChildWins,
25
+ sectionMerge
26
+ };
27
+ /**
28
+ * Map fields' runtime strategy functions, keyed by field: every
29
+ * `FIELD_REGISTRY` entry whose strategy is `mapChildWins` or `sectionMerge`.
30
+ * `export` merges through the same function with the arguments the other way
31
+ * round: the file is the base and the managed value is laid on top, so a
32
+ * managed change to a key the file holds is exported (install, where the
33
+ * consumer's value wins, freezes such a key after the first export).
34
+ */
35
+ const MAP_EXPORT_STRATEGIES = new Map(Object.entries(FIELD_REGISTRY).flatMap(([name, p]) => {
36
+ const strategy = MAP_STRATEGIES[p.strategy];
37
+ return strategy === void 0 ? [] : [[name, strategy]];
38
+ }));
39
+ /**
40
+ * Map fields (`mapChildWins` and `sectionMerge` in `FIELD_REGISTRY`) whose
41
+ * file-only keys `export` keeps; on a key both hold the managed value wins.
42
+ * A deliberate consumer value goes in `local`; `local: { strategy: "rewrite" }`
43
+ * opts a field back into overwrite.
44
+ *
45
+ * @internal
46
+ */
47
+ const MAP_EXPORT_FIELDS = new Set(MAP_EXPORT_STRATEGIES.keys());
48
+ const isMap = (v) => Predicate.isObject(v) && !Array.isArray(v);
49
+ /**
50
+ * `map` without the keys `names` lists: an array of key names, or a map whose
51
+ * keys are removed. A non-map input (nothing managed, nothing in the file)
52
+ * stays absent rather than becoming an empty map.
53
+ */
54
+ function withoutKeys(map, names) {
55
+ if (!isMap(map)) return void 0;
56
+ const out = { ...map };
57
+ const keys = Array.isArray(names) ? names.map(String) : isMap(names) ? Object.keys(names) : [];
58
+ for (const k of keys) delete out[k];
59
+ return out;
60
+ }
11
61
  const DIRECTIVE_KEYS = /* @__PURE__ */ new Set([
12
62
  "preserve",
13
63
  "value",
@@ -42,6 +92,11 @@ function combine(managed, value, strategy) {
42
92
  for (const k of Object.keys(v)) delete out[k];
43
93
  return out;
44
94
  }
95
+ /** Union the file's value into `value`; records of string arrays union per key, as the runtime does. */
96
+ function unionFile(value, parsed) {
97
+ if (isMap(parsed) && (value === void 0 || isMap(value))) return unionRecord(value ?? {}, parsed);
98
+ return combine(value, parsed, "union");
99
+ }
45
100
  /**
46
101
  * Compute the effective value of one field from the managed value, the
47
102
  * `config.local[field]` directive (or bare value / undefined), and the parsed
@@ -57,6 +112,16 @@ function applyLocalDirective(managed, raw, parsed, field) {
57
112
  if (strat && strat !== "rewrite" && directive.value !== void 0) result = combine(managed, directive.value, strat);
58
113
  else if (directive.value !== void 0 && directive.strategy !== "rewrite") result = directive.value;
59
114
  else result = managed;
115
+ if (UNION_EXPORT_FIELDS.has(field) && directive.strategy !== "rewrite" && parsed !== void 0) {
116
+ if (directive.strategy === "difference" && directive.value !== void 0) result = combine(unionFile(managed, parsed), directive.value, "difference");
117
+ else result = unionFile(result, parsed);
118
+ }
119
+ const mapStrategy = MAP_EXPORT_STRATEGIES.get(field);
120
+ if (mapStrategy !== void 0 && directive.strategy !== "rewrite") {
121
+ const mergeFile = (value) => isMap(parsed) && (value === void 0 || isMap(value)) ? mapStrategy(parsed, value, { rootName: void 0 }).merged : value;
122
+ if (directive.strategy === "difference" && directive.value !== void 0) result = withoutKeys(mergeFile(managed), directive.value);
123
+ else result = mergeFile(result);
124
+ }
60
125
  if (field === "overrides") {
61
126
  const protocols = directive.preserve ?? DEFAULT_PRESERVE;
62
127
  const base = Predicate.isObject(result) ? { ...result } : {};
@@ -69,4 +134,4 @@ function applyLocalDirective(managed, raw, parsed, field) {
69
134
  return result;
70
135
  }
71
136
 
72
- export { DEFAULT_PRESERVE, applyLocalDirective, isLocalDirective };
137
+ export { DEFAULT_PRESERVE, MAP_EXPORT_FIELDS, UNION_EXPORT_FIELDS, applyLocalDirective, isLocalDirective };