rolldown-pnpm-config 3.0.7 → 3.2.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,623 @@
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 { WorkingDirectory } from "../cwd.js";
8
+ import { evaluatePluginConfig } from "../evaluate.js";
9
+ import { failureDoc, warningDoc } from "../render/report.js";
10
+ import { RegistryResolver } from "../resolve.js";
11
+ import { applyEdits } from "../rewrite.js";
12
+ import { renderCommitMessage } from "../sync/commit-message.js";
13
+ import { SyncConfigError, resolveEvaluatedSync } from "../sync/config.js";
14
+ import { applyFloorEdits, describeFloorEdits, planFloorEdits } from "../sync/floors.js";
15
+ import { exportDrift, exportedCatalogNames, readServedCatalogs } from "../sync/local-gate.js";
16
+ import { MEMBERSHIP_REMEDY, checkMembership, membershipMessage, pluginManifest, pluginPackageName } from "../sync/membership.js";
17
+ import { readReleasePlan } from "../sync/release-plan.js";
18
+ import { rippleEdits, rippleMismatches } from "../sync/ripples.js";
19
+ import { currentCatalogs, mergeMoves, parseChangeset, renderChangeset, staleMoves } from "../sync/running-list.js";
20
+ import { findWorkspaceRoot, makeWorkspaceResolver } from "../workspace-resolve.js";
21
+ import { CHECK_FAILED_LABEL, UpgradeError, checkJsonOutcome, readCatalogSource, resolveTargetFile, runUpgrade } from "./upgrade.js";
22
+
23
+ // src/cli/commands/sync.ts
24
+ /**
25
+ * An invalid `sync` flag combination: a usage error, so it exits 64 (mapped by
26
+ * tag in `EXIT_CODES`).
27
+ *
28
+ * @internal
29
+ */
30
+ var SyncUsageError = class extends Data.TaggedError("SyncUsageError") {
31
+ /** The failure report `CliRuntime.main` prints: the message, without the class name. */
32
+ [CliDoc]() {
33
+ return failureDoc(this.message);
34
+ }
35
+ };
36
+ /**
37
+ * Publishable workspace packages the sync catalog does not name. Raised before
38
+ * any write: a sync that upgraded versions while a member was missing would
39
+ * report "synced" for a catalog that is still incomplete. A finding, exit 1.
40
+ *
41
+ * @internal
42
+ */
43
+ var MembershipError = class extends Data.TaggedError("MembershipError") {
44
+ /** The failure report: the `membershipMessage` text. */
45
+ [CliDoc]() {
46
+ return failureDoc(this.message);
47
+ }
48
+ };
49
+ /** Read and decode the `sync` block of the config at `configFile`. */
50
+ function readSyncConfig(configFile) {
51
+ return Effect.gen(function* () {
52
+ const { source } = yield* readCatalogSource(configFile);
53
+ const evaluated = yield* Effect.try({
54
+ try: () => evaluatePluginConfig(source, configFile),
55
+ catch: (error) => new SyncConfigError({ message: `cannot evaluate ${configFile}: ${Fmt.errorText(error)}` })
56
+ });
57
+ return yield* resolveEvaluatedSync(evaluated, configFile);
58
+ });
59
+ }
60
+ /** Write `content` to `file` atomically; a failure is the run's, like upgrade's own write. */
61
+ function writeFile(file, content) {
62
+ return Effect.gen(function* () {
63
+ const fs = yield* FileSystem.FileSystem;
64
+ const path = yield* Path.Path;
65
+ yield* fs.makeDirectory(path.dirname(file), { recursive: true });
66
+ yield* AtomicFile.write(file, content);
67
+ }).pipe(Effect.mapError(() => new UpgradeError({ message: `Cannot write ${file}` })));
68
+ }
69
+ /** The running-list changeset at `file`, or none when there is none yet. */
70
+ function readRunningList(file) {
71
+ return Effect.gen(function* () {
72
+ 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}` })));
73
+ });
74
+ }
75
+ /** Write the running list and the commit message for `moves`. */
76
+ function writeListAndMessage(rootDir, sync, pluginName, moves) {
77
+ return Effect.gen(function* () {
78
+ const path = yield* Path.Path;
79
+ yield* writeFile(path.join(rootDir, sync.changesetPath), renderChangeset(pluginName, sync.bump, moves, sync.catalog));
80
+ yield* writeFile(path.join(rootDir, sync.messagePath), renderCommitMessage(sync.commitScope, moves));
81
+ });
82
+ }
83
+ /**
84
+ * Bring the sync catalog in the config at `configFile` to the next release
85
+ * versions, and record the moves in the running-list changeset.
86
+ *
87
+ * @remarks
88
+ * The order is the scripts' and each step has its reason:
89
+ *
90
+ * 1. Membership, before any write: a sync that upgrades versions while a
91
+ * member is missing would report success for an incomplete catalog.
92
+ * 2. Floors, when `sync.floors` is on, before the plan is read: a raised
93
+ * package releases at a new minor, and the catalog must name that version.
94
+ * 3. The release plan, read before the config is rewritten, so a plan that
95
+ * cannot be read fails the run with the config, the running list and the
96
+ * commit message unchanged (step 2 may already have written floors).
97
+ * 4. A snapshot of the config, which decides whether the catalog moved: the
98
+ * file cannot disagree with itself.
99
+ * 5. The upgrade (`--yes`), scoped to the sync catalog.
100
+ * 6. Ripples, read from the config the upgrade just wrote: a package bumped
101
+ * only as a dependency ripple has no changeset, so the upgrade cannot see it.
102
+ * 7. If the config did not move, the running list is rewritten only when it is
103
+ * stale (hand-edited, or carried over a merge), so a sync repairs it.
104
+ * Otherwise this run's moves are merged into it: it lists every move since
105
+ * the last release, never just the latest.
106
+ * 8. The commit message, written beside the running list.
107
+ *
108
+ * @internal
109
+ */
110
+ const runSyncWrite = Effect.fn("Sync.runSyncWrite")(function* (opts) {
111
+ const path = yield* Path.Path;
112
+ const file = opts.configFile;
113
+ const sync = yield* readSyncConfig(file);
114
+ const rootDir = findWorkspaceRoot(dirname(path.resolve(file)));
115
+ const membership = yield* checkMembership(file, rootDir, sync);
116
+ if (membership.missing.length > 0) return yield* new MembershipError({
117
+ message: membershipMessage(membership.missing, file),
118
+ missing: membership.missing
119
+ });
120
+ const pluginName = yield* pluginPackageName(file);
121
+ let floors = 0;
122
+ if (sync.floors) {
123
+ const { edits } = yield* planFloorEdits(rootDir);
124
+ yield* applyFloorEdits(rootDir, edits).pipe(Effect.mapError(() => new UpgradeError({ message: `Cannot write the breaking-floor changesets in ${rootDir}` })));
125
+ floors = edits.length;
126
+ }
127
+ const plan = yield* readReleasePlan(rootDir);
128
+ const before = (yield* readCatalogSource(file)).source;
129
+ const upgraded = yield* runUpgrade({
130
+ file,
131
+ resolver: opts.resolver,
132
+ workspaceResolver: opts.workspaceResolver,
133
+ catalog: sync.catalog
134
+ });
135
+ const { source: afterUpgrade, entries } = yield* readCatalogSource(file, sync.catalog);
136
+ const ripples = yield* rippleMismatches(entries, plan);
137
+ if (ripples.length > 0) yield* writeFile(file, applyEdits(afterUpgrade, rippleEdits(entries, ripples)));
138
+ const after = yield* readCatalogSource(file);
139
+ const current = currentCatalogs(after.entries);
140
+ const existing = yield* readRunningList(path.join(rootDir, sync.changesetPath));
141
+ const pending = Option.match(existing, {
142
+ onNone: () => [],
143
+ onSome: parseChangeset
144
+ });
145
+ if (after.source === before) {
146
+ const stale = Option.isSome(existing) && staleMoves(pending, current).length > 0;
147
+ if (stale) yield* writeListAndMessage(rootDir, sync, pluginName, mergeMoves(pending, [], current));
148
+ return {
149
+ moves: [],
150
+ ripples,
151
+ floors,
152
+ membership,
153
+ wrote: stale || floors > 0,
154
+ listWritten: stale
155
+ };
156
+ }
157
+ const fresh = [...upgraded.changed.map((row) => ({
158
+ catalog: row.catalog,
159
+ pkg: row.pkg,
160
+ from: row.from,
161
+ to: row.to ?? row.from,
162
+ peer: void 0
163
+ })), ...ripples.map((r) => ({
164
+ catalog: r.catalog,
165
+ pkg: r.pkg,
166
+ from: r.from,
167
+ to: r.to,
168
+ peer: r.peer
169
+ }))];
170
+ yield* writeListAndMessage(rootDir, sync, pluginName, mergeMoves(pending, fresh, current));
171
+ return {
172
+ moves: mergeMoves([], fresh, current),
173
+ ripples,
174
+ floors,
175
+ membership,
176
+ wrote: true,
177
+ listWritten: true
178
+ };
179
+ });
180
+ /**
181
+ * The remedy for everything a plain `sync` repairs. `displayFile` is the
182
+ * config path as the reader should type it (the command passes it relative to
183
+ * the working directory), never an absolute path that leaks the machine's
184
+ * layout into CI logs.
185
+ */
186
+ const syncRemedy = (displayFile) => `Run \`rolldown-pnpm-config sync ${displayFile}\`.`;
187
+ /** The remedy for export drift: the export writes the yaml, the rebuild serves what it wrote. */
188
+ const EXPORT_REMEDY = "Run `pnpm pnpm:export`, then rebuild the plugin.";
189
+ /** A section with nothing to report. */
190
+ const ok = (section) => ({
191
+ section,
192
+ status: "ok"
193
+ });
194
+ /** `rows` as findings, or ok when there are none. */
195
+ const findings = (section, rows, remedy) => rows.length === 0 ? ok(section) : {
196
+ section,
197
+ status: "findings",
198
+ rows,
199
+ remedy
200
+ };
201
+ /**
202
+ * Evaluate one section. A typed failure becomes its `error` status, so one
203
+ * section that cannot be read never hides the verdict of the next.
204
+ */
205
+ function evaluate(section, effect) {
206
+ return effect.pipe(Effect.catch((error) => Effect.succeed({
207
+ section,
208
+ status: "error",
209
+ kind: error._tag,
210
+ message: error.message
211
+ })));
212
+ }
213
+ /** One drift row: `catalog.pkg from -> to (source)`; a peer-only resync keeps its range. */
214
+ function driftRow(row) {
215
+ const move = row.to === void 0 ? `${row.from} (peer only)` : `${row.from} -> ${row.to}`;
216
+ return ` ${row.catalog}.${row.pkg} ${move} (${row.source})`;
217
+ }
218
+ /**
219
+ * Versions: the upgrade's own check, a dry run scoped to the sync catalog.
220
+ * Also returns the rows the upgrade would move (none when it errored), which
221
+ * the ripples section lays over the config.
222
+ */
223
+ function versionsSection(opts, sync, remedy) {
224
+ return runUpgrade({
225
+ file: opts.configFile,
226
+ resolver: opts.resolver,
227
+ workspaceResolver: opts.workspaceResolver,
228
+ catalog: sync.catalog,
229
+ dryRun: true
230
+ }).pipe(Effect.result, Effect.map((result) => {
231
+ const { failure } = checkJsonOutcome(result);
232
+ if (failure !== void 0) return {
233
+ section: {
234
+ section: "versions",
235
+ status: "error",
236
+ kind: failure.kind ?? "resolution",
237
+ message: failure.message
238
+ },
239
+ changed: []
240
+ };
241
+ const changed = Result.isSuccess(result) ? result.success.changed : [];
242
+ return {
243
+ section: findings("versions", changed.map(driftRow), remedy),
244
+ changed
245
+ };
246
+ }));
247
+ }
248
+ /** Membership: publishable workspace members the sync catalog does not name. */
249
+ function membershipSection(configFile, rootDir, sync) {
250
+ return evaluate("membership", checkMembership(configFile, rootDir, sync).pipe(Effect.map((m) => findings("membership", m.missing.map((name) => ` - ${name}`), MEMBERSHIP_REMEDY))));
251
+ }
252
+ /** Floors: the breaking-floor changesets on disk differ from the ones the plan derives. */
253
+ function floorsSection(rootDir, remedy) {
254
+ return evaluate("floors", planFloorEdits(rootDir).pipe(Effect.map(({ raised, edits }) => findings("floors", describeFloorEdits(raised, edits).split("\n").filter((line) => line !== ""), remedy))));
255
+ }
256
+ /** The running list: a pending list whose moves disagree with the config. Absent is in sync. */
257
+ function runningListSection(configFile, rootDir, sync, remedy) {
258
+ return evaluate("running-list", Effect.gen(function* () {
259
+ const existing = yield* readRunningList((yield* Path.Path).join(rootDir, sync.changesetPath));
260
+ if (Option.isNone(existing)) return ok("running-list");
261
+ const { entries } = yield* readCatalogSource(configFile);
262
+ const stale = staleMoves(parseChangeset(existing.value), currentCatalogs(entries));
263
+ return findings("running-list", stale, remedy);
264
+ }));
265
+ }
266
+ /**
267
+ * Ripples: entries behind the version the release plan would release, which
268
+ * the upgrade cannot see.
269
+ *
270
+ * @remarks
271
+ * Write mode looks for ripples after the upgrade has run, so `upgraded` (the
272
+ * versions section's drift rows) is laid over the config first: a package the
273
+ * upgrade moves is a versions row, never a ripple too. When versions errored,
274
+ * `upgraded` is empty and the list is unfiltered. With `floors: true`, the
275
+ * targets come from the plan before any floor is raised (write mode raises
276
+ * floors first), so a row can differ from what a sync would write.
277
+ */
278
+ function ripplesSection(configFile, rootDir, sync, upgraded, remedy) {
279
+ return evaluate("ripples", Effect.gen(function* () {
280
+ const plan = yield* readReleasePlan(rootDir);
281
+ const { entries } = yield* readCatalogSource(configFile, sync.catalog);
282
+ const moved = new Map(upgraded.map((row) => [`${row.catalog}\0${row.pkg}`, row.to]));
283
+ const afterUpgrade = entries.map((entry) => {
284
+ const to = moved.get(`${entry.catalog}\0${entry.pkg}`);
285
+ return to === void 0 ? entry : {
286
+ ...entry,
287
+ currentRange: to
288
+ };
289
+ });
290
+ const rows = (yield* rippleMismatches(afterUpgrade, plan)).map((r) => ` ${r.catalog}.${r.pkg} ${r.from} -> ${r.to}`);
291
+ return findings("ripples", rows, remedy);
292
+ }));
293
+ }
294
+ /**
295
+ * Export parity: the exported catalogs in `pnpm-workspace.yaml` against what
296
+ * the built pnpmfile serves. A missing build is a finding (build it), not an
297
+ * error: nothing is wrong with the tree that a build does not fix.
298
+ */
299
+ function exportSection(configFile, rootDir, sync) {
300
+ return evaluate("export", Effect.gen(function* () {
301
+ const fs = yield* FileSystem.FileSystem;
302
+ const path = yield* Path.Path;
303
+ const pnpmfile = path.resolve(path.dirname(yield* pluginManifest(configFile)), sync.pnpmfile);
304
+ const served = yield* readServedCatalogs(pnpmfile).pipe(Effect.result);
305
+ if (Result.isFailure(served)) {
306
+ if (yield* fs.exists(pnpmfile)) return yield* Effect.fail(served.failure);
307
+ return findings("export", [` ${pnpmfile}: not built`], served.failure.message);
308
+ }
309
+ const source = yield* fs.readFileString(path.join(rootDir, "pnpm-workspace.yaml"));
310
+ const workspace = yield* PnpmWorkspaceFile.parse(source);
311
+ const names = exportedCatalogNames(served.success, sync);
312
+ return findings("export", exportDrift(served.success, names, { ...workspace.value }), EXPORT_REMEDY);
313
+ }));
314
+ }
315
+ /** What both gates start from: the decoded `sync` block and the workspace root. */
316
+ function gateContext(configFile) {
317
+ return Effect.gen(function* () {
318
+ const path = yield* Path.Path;
319
+ return {
320
+ sync: yield* readSyncConfig(configFile),
321
+ rootDir: findWorkspaceRoot(dirname(path.resolve(configFile)))
322
+ };
323
+ });
324
+ }
325
+ /** The document over `sections`, `evaluated` derived from them. */
326
+ function checkDoc(mode, sections) {
327
+ return {
328
+ command: "sync",
329
+ mode,
330
+ evaluated: sections.every((s) => s.status !== "error"),
331
+ sections
332
+ };
333
+ }
334
+ /**
335
+ * Report whether a plain `sync` would change anything, and why. Never writes.
336
+ *
337
+ * @remarks
338
+ * Every section is evaluated, in the order versions, membership, floors (when
339
+ * `sync.floors` is on), running-list, ripples, and none short-circuits: the
340
+ * scripts this ports stop at the first failure, but a red check that lists
341
+ * everything saves a round trip. Only an unreadable or invalid config fails
342
+ * the run; a section that cannot be evaluated is an `error` section.
343
+ *
344
+ * @internal
345
+ */
346
+ const runSyncCheck = Effect.fn("Sync.runSyncCheck")(function* (opts) {
347
+ const file = opts.configFile;
348
+ const remedy = syncRemedy(opts.displayFile ?? file);
349
+ const { sync, rootDir } = yield* gateContext(file);
350
+ const versions = yield* versionsSection(opts, sync, remedy);
351
+ const rest = yield* Effect.all([
352
+ membershipSection(file, rootDir, sync),
353
+ ...sync.floors ? [floorsSection(rootDir, remedy)] : [],
354
+ runningListSection(file, rootDir, sync, remedy),
355
+ ripplesSection(file, rootDir, sync, versions.changed, remedy)
356
+ ]);
357
+ return checkDoc("check", [versions.section, ...rest]);
358
+ });
359
+ /**
360
+ * The offline push-time gate: membership, and that the exported catalogs in
361
+ * `pnpm-workspace.yaml` match what the built plugin serves. No registry, no
362
+ * release plan, no version drift; writes nothing.
363
+ *
364
+ * @remarks
365
+ * The sync catalog and its `:peers` sibling are not exported by default, so a
366
+ * lagging sync catalog in the yaml is not reported: that is `--check`'s
367
+ * versions question, and it needs the network.
368
+ *
369
+ * @internal
370
+ */
371
+ const runSyncLocal = Effect.fn("Sync.runSyncLocal")(function* (opts) {
372
+ const file = opts.configFile;
373
+ const { sync, rootDir } = yield* gateContext(file);
374
+ return checkDoc("local", yield* Effect.all([membershipSection(file, rootDir, sync), exportSection(file, rootDir, sync)]));
375
+ });
376
+ /**
377
+ * Fail unless the `sync` block manages breaking floors: `--floors-only` on a
378
+ * config with `floors: false` would otherwise write or pass on files this
379
+ * config never asked `sync` to own.
380
+ */
381
+ function requireFloors(sync, configFile) {
382
+ return sync.floors ? Effect.void : Effect.fail(new SyncConfigError({ message: `--floors-only needs \`sync.floors: true\` in ${configFile}; this config does not manage breaking floors` }));
383
+ }
384
+ /**
385
+ * `sync --floors-only`: raise the breaking-floor changesets and stop. No
386
+ * registry, no upgrade, no running list or commit message: the floors step
387
+ * of {@link runSyncWrite} alone, for a repository that keeps a separate
388
+ * floors script or hook.
389
+ *
390
+ * @internal
391
+ */
392
+ const runSyncFloors = Effect.fn("Sync.runSyncFloors")(function* (opts) {
393
+ const { sync, rootDir } = yield* gateContext(opts.configFile);
394
+ yield* requireFloors(sync, opts.configFile);
395
+ const { edits } = yield* planFloorEdits(rootDir);
396
+ yield* applyFloorEdits(rootDir, edits).pipe(Effect.mapError(() => new UpgradeError({ message: `Cannot write the breaking-floor changesets in ${rootDir}` })));
397
+ return { edits: edits.map((edit) => ({
398
+ path: edit.path,
399
+ deleted: edit.content === null
400
+ })) };
401
+ });
402
+ /**
403
+ * `sync --check --floors-only`: the floors section of the gate alone. Offline;
404
+ * writes nothing.
405
+ *
406
+ * @internal
407
+ */
408
+ const runSyncFloorsCheck = Effect.fn("Sync.runSyncFloorsCheck")(function* (opts) {
409
+ const { sync, rootDir } = yield* gateContext(opts.configFile);
410
+ yield* requireFloors(sync, opts.configFile);
411
+ return checkDoc("check", [yield* floorsSection(rootDir, `Run \`rolldown-pnpm-config sync --floors-only ${opts.displayFile ?? opts.configFile}\`.`)]);
412
+ });
413
+ /** The human view of a `--floors-only` write. @internal */
414
+ function syncFloorsDoc(result) {
415
+ if (result.edits.length === 0) return [Doc.line("Breaking floors are current; nothing written.")];
416
+ return [Doc.line(`Updated ${Fmt.plural(result.edits.length, "breaking-floor changeset")}:`), Doc.lines(result.edits.map((edit) => ` ${edit.path}${edit.deleted ? " (deleted)" : ""}`), { wrap: false })];
417
+ }
418
+ /** The gate's exit code: 0 when every section is ok, 1 for any finding or error. @internal */
419
+ function syncCheckExit(doc) {
420
+ return doc.sections.every((s) => s.status === "ok") ? 0 : 1;
421
+ }
422
+ /** A finding section's heading. */
423
+ function findingsHeading(section, count) {
424
+ switch (section) {
425
+ case "versions": return `Catalog drift detected in ${Fmt.plural(count, "package")}:`;
426
+ case "membership": return "Publishable packages missing from the catalog:";
427
+ case "floors": return `Breaking floors are out of date in ${Fmt.plural(count, "changeset")}:`;
428
+ case "running-list": return `The running list disagrees with the catalog config on ${Fmt.plural(count, "package")}:`;
429
+ case "ripples": return `Catalog is behind on ${Fmt.plural(count, "dependency-ripple bump")}:`;
430
+ case "export": return "pnpm-workspace.yaml does not match the catalogs the built plugin serves:";
431
+ }
432
+ }
433
+ /** The human view of a gate run: every section that is not ok, in order. @internal */
434
+ function syncCheckView(doc) {
435
+ const failing = doc.sections.filter((s) => s.status !== "ok");
436
+ if (failing.length === 0) return [Doc.line(doc.mode === "check" ? "Catalogs are in sync." : "Catalog membership and the exported catalogs are in sync.")];
437
+ return failing.map((s) => {
438
+ if (s.status === "findings") return Doc.section(void 0, [
439
+ Doc.line(findingsHeading(s.section, s.rows.length)),
440
+ Doc.lines(s.rows, { wrap: false }),
441
+ Doc.line(s.remedy)
442
+ ]);
443
+ const heading = s.section === "versions" ? CHECK_FAILED_LABEL : `The ${s.section} section could not be evaluated (${s.kind}, not a finding):`;
444
+ return Doc.section(void 0, [Doc.line(heading), Doc.lines(s.message.split("\n").map((line) => ` ${line}`), { wrap: false })]);
445
+ });
446
+ }
447
+ /** One move as a report line: `catalog.pkg from -> to`. */
448
+ function moveLine(move, note = "") {
449
+ return ` ${move.catalog}.${move.pkg} ${move.from} -> ${move.to}${note}`;
450
+ }
451
+ /** The human view of a write-mode run. @internal */
452
+ function syncWriteDoc(result) {
453
+ if (!result.wrote) return [Doc.line("The sync catalog is current; nothing written.")];
454
+ const rippled = new Set(result.ripples.map((r) => `${r.catalog}\0${r.pkg}`));
455
+ const blocks = [];
456
+ if (result.moves.length > 0) {
457
+ blocks.push(Doc.line(`Synced ${Fmt.plural(result.moves.length, "catalog entry", "catalog entries")}:`));
458
+ blocks.push(Doc.lines(result.moves.map((m) => moveLine(m, rippled.has(`${m.catalog}\0${m.pkg}`) ? " (ripple)" : "")), { wrap: false }));
459
+ } else if (result.listWritten) blocks.push(Doc.line("The catalog was current; rewrote the stale running list."));
460
+ else blocks.push(Doc.line("The catalog was current; the running list was left as it was."));
461
+ if (result.floors > 0) blocks.push(Doc.line(`Updated ${Fmt.plural(result.floors, "breaking-floor changeset")}.`));
462
+ return blocks;
463
+ }
464
+ /**
465
+ * The `--format json` document of a write-mode run.
466
+ *
467
+ * @remarks
468
+ * On failure `wrote` and `listWritten` are `false` and make no claim about
469
+ * what the run wrote before it failed: a run that failed after its floors
470
+ * step or its upgrade may already have written floor changesets or the
471
+ * config. The documents say so; tracking each write is not worth the state.
472
+ *
473
+ * @internal
474
+ */
475
+ function syncWriteJson(result) {
476
+ if (Result.isFailure(result)) {
477
+ const { _tag, message } = result.failure;
478
+ return {
479
+ command: "sync",
480
+ mode: "write",
481
+ wrote: false,
482
+ listWritten: false,
483
+ error: {
484
+ kind: _tag,
485
+ message
486
+ }
487
+ };
488
+ }
489
+ const { moves, ripples, membership, wrote, listWritten } = result.success;
490
+ return {
491
+ command: "sync",
492
+ mode: "write",
493
+ moves,
494
+ ripples,
495
+ membership,
496
+ wrote,
497
+ listWritten
498
+ };
499
+ }
500
+ const configArg = Argument.File("config").pipe(Argument.withDescription("The plugin config holding the `sync` block (autodetected in the current directory when omitted)"), Argument.optional);
501
+ const checkFlag = Flag.Boolean("check").pipe(Flag.withDescription("Report whether a sync would change anything, and why (a gate; never writes)"), Flag.withDefault(false));
502
+ const localFlag = Flag.Boolean("local").pipe(Flag.withDescription("Compare the built pnpmfile's catalogs with pnpm-workspace.yaml (offline; never writes)"), Flag.withDefault(false));
503
+ const floorsOnlyFlag = Flag.Boolean("floors-only").pipe(Flag.withDescription("Only the breaking-floor changesets: raise them, or with --check report them (offline; needs sync.floors)"), Flag.withDefault(false));
504
+ const formatFlag = CliFormat.flag(["json"], {
505
+ aliases: { text: "auto" },
506
+ default: "text",
507
+ description: "Output format: text (for whoever is reading) or json (one JSON document on stdout)"
508
+ });
509
+ /**
510
+ * `file` as the reader should type it: relative to the working directory. A
511
+ * contributor copies the remedy from a CI log or a terminal, and an absolute
512
+ * path is neither portable nor private.
513
+ */
514
+ function displayPath(file) {
515
+ return Effect.gen(function* () {
516
+ const cwd = yield* WorkingDirectory;
517
+ const path = yield* Path.Path;
518
+ const relative = path.relative(cwd, path.resolve(cwd, file));
519
+ return relative === "" ? file : relative;
520
+ });
521
+ }
522
+ /** JSON mode writes one single-line document, so a bash gate can pipe it straight into jq. */
523
+ const ONE_LINE = { indent: 0 };
524
+ /**
525
+ * The "sync" command. Plain mode brings the `sync` block's catalog to the next
526
+ * release versions and records the moves in the running-list changeset.
527
+ * `--check` and `--local` are the gates, and are mutually exclusive.
528
+ *
529
+ * @internal
530
+ */
531
+ const syncCommand = Command.make("sync", {
532
+ config: configArg,
533
+ check: checkFlag,
534
+ local: localFlag,
535
+ floorsOnly: floorsOnlyFlag,
536
+ format: formatFlag
537
+ }, ({ config, check, local, floorsOnly, format }) => Effect.gen(function* () {
538
+ if (check && local) return yield* new SyncUsageError({ message: "--check and --local cannot be combined; pass one" });
539
+ if (floorsOnly && local) return yield* new SyncUsageError({ message: "--floors-only cannot be combined with --local; pass it alone or with --check" });
540
+ if (floorsOnly && !check) {
541
+ const result = yield* resolveTargetFile(config).pipe(Effect.flatMap((file) => runSyncFloors({ configFile: file })), Effect.result);
542
+ if (format === "json") {
543
+ const json = Result.isFailure(result) ? {
544
+ command: "sync",
545
+ mode: "floors",
546
+ wrote: false,
547
+ error: {
548
+ kind: result.failure._tag,
549
+ message: result.failure.message
550
+ }
551
+ } : {
552
+ command: "sync",
553
+ mode: "floors",
554
+ wrote: result.success.edits.length > 0,
555
+ edits: result.success.edits
556
+ };
557
+ yield* CliFormat.print("json", {
558
+ doc: () => [],
559
+ json: () => json
560
+ }, ONE_LINE);
561
+ }
562
+ if (Result.isFailure(result)) return yield* Effect.fail(result.failure);
563
+ if (format === "json") return;
564
+ yield* Doc.print(syncFloorsDoc(result.success));
565
+ return;
566
+ }
567
+ if (check || local) {
568
+ const mode = check ? "check" : "local";
569
+ const result = yield* resolveTargetFile(config).pipe(Effect.flatMap((file) => floorsOnly ? Effect.flatMap(displayPath(file), (displayFile) => runSyncFloorsCheck({
570
+ configFile: file,
571
+ displayFile
572
+ })) : check ? Effect.flatMap(Effect.all([RegistryResolver, displayPath(file)]), ([resolver, displayFile]) => runSyncCheck({
573
+ configFile: file,
574
+ displayFile,
575
+ resolver,
576
+ workspaceResolver: makeWorkspaceResolver(findWorkspaceRoot(dirname(file)))
577
+ })) : runSyncLocal({ configFile: file })), Effect.result);
578
+ if (Result.isFailure(result)) {
579
+ if (format === "json") {
580
+ const { _tag, message } = result.failure;
581
+ const json = {
582
+ command: "sync",
583
+ mode,
584
+ evaluated: false,
585
+ sections: [],
586
+ error: {
587
+ kind: _tag,
588
+ message
589
+ }
590
+ };
591
+ yield* CliFormat.print("json", {
592
+ doc: () => [],
593
+ json: () => json
594
+ }, ONE_LINE);
595
+ }
596
+ return yield* Effect.fail(result.failure);
597
+ }
598
+ const doc = result.success;
599
+ yield* CliFormat.print(format === "json" ? "json" : "auto", {
600
+ doc: () => syncCheckView(doc),
601
+ json: () => doc
602
+ }, ONE_LINE);
603
+ return yield* CliExit.set(syncCheckExit(doc));
604
+ }
605
+ const resolver = yield* RegistryResolver;
606
+ const result = yield* resolveTargetFile(config).pipe(Effect.flatMap((file) => runSyncWrite({
607
+ configFile: file,
608
+ resolver,
609
+ workspaceResolver: makeWorkspaceResolver(findWorkspaceRoot(dirname(file)))
610
+ })), Effect.result);
611
+ if (format === "json") yield* CliFormat.print("json", {
612
+ doc: () => [],
613
+ json: () => syncWriteJson(result)
614
+ }, ONE_LINE);
615
+ if (Result.isFailure(result)) return yield* Effect.fail(result.failure);
616
+ const success = result.success;
617
+ for (const ripple of success.ripples) if (ripple.warning !== void 0) yield* Doc.print(warningDoc(`${ripple.catalog}.${ripple.pkg}: ${ripple.warning}`), { stream: "stderr" });
618
+ if (format === "json") return;
619
+ yield* Doc.print(syncWriteDoc(success));
620
+ if (success.wrote) yield* CliMessage.success("Sync written.");
621
+ })).pipe(Command.withDescription("Sync the plugin's own catalog to the next release versions"));
622
+
623
+ export { MembershipError, SyncUsageError, runSyncCheck, runSyncFloors, runSyncFloorsCheck, runSyncLocal, runSyncWrite, syncCheckExit, syncCheckView, syncCommand, syncFloorsDoc, syncWriteDoc, syncWriteJson };
@@ -3,7 +3,7 @@ import { CliDoc, CliExit, CliFormat, CliInteractive, CliMessage, Doc, Fmt } from
3
3
  import { CliUi } from "@effected/cli-kit/ui";
4
4
  import { AtomicFile } from "@effected/files";
5
5
  import { ReleaseAgeGate } from "@effected/pnpm";
6
- import { Clock, Data, Effect, FileSystem, Option, Result } from "effect";
6
+ import { Clock, Data, Effect, Option, Result } from "effect";
7
7
  import { Argument, Command, Flag } from "effect/cli";
8
8
  import { bareVersion } from "../../semver-util.js";
9
9
  import { WorkingDirectory } from "../cwd.js";
@@ -94,7 +94,7 @@ function writeSource(file, next) {
94
94
  */
95
95
  function readCatalogSource(file, catalog) {
96
96
  return Effect.gen(function* () {
97
- const source = yield* (yield* FileSystem.FileSystem).readFileString(file).pipe(Effect.mapError(() => new UpgradeError({ message: `Cannot read ${file}` })));
97
+ const { text: source } = yield* AtomicFile.readText(file).pipe(Effect.mapError(() => new UpgradeError({ message: `Cannot read ${file}` })));
98
98
  const { entries, skipped, skippedRefs, catalogs } = yield* Effect.try({
99
99
  try: () => discoverCatalogEntries(source, file),
100
100
  catch: (e) => new UpgradeError({ message: Fmt.describe(e) })
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];