storyblok 4.27.0 → 4.27.2

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.
package/dist/index.mjs CHANGED
@@ -898,10 +898,15 @@ var CommandError = class extends Error {
898
898
  var Logger = class {
899
899
  transports = [];
900
900
  context = {};
901
+ hasReportedTransportError = false;
901
902
  constructor(options) {
902
903
  if (options?.transports) this.transports = options.transports;
903
904
  if (options?.context) this.context = options.context;
904
905
  }
906
+ setTransports(transports) {
907
+ this.transports = transports;
908
+ this.hasReportedTransportError = false;
909
+ }
905
910
  log(level, message, context) {
906
911
  const timestamp = /* @__PURE__ */ new Date();
907
912
  const mergedContext = context ? {
@@ -914,7 +919,19 @@ var Logger = class {
914
919
  message,
915
920
  context: Object.keys(mergedContext).length ? mergedContext : void 0
916
921
  };
917
- for (const transport of this.transports) transport.log(record);
922
+ for (const transport of this.transports) try {
923
+ transport.log(record);
924
+ } catch (error) {
925
+ this.reportTransportError(error);
926
+ }
927
+ }
928
+ reportTransportError(error) {
929
+ if (this.hasReportedTransportError) return;
930
+ this.hasReportedTransportError = true;
931
+ try {
932
+ const reason = error instanceof Error ? error.message : String(error);
933
+ process.stderr.write(`Logging failed, some log entries may be missing: ${reason}\n`);
934
+ } catch {}
918
935
  }
919
936
  error(message, context) {
920
937
  this.log("error", message, context);
@@ -935,7 +952,7 @@ function getLogger(options) {
935
952
  return loggerInstance;
936
953
  }
937
954
  function setLoggerTransports(transports) {
938
- if (loggerInstance) loggerInstance.transports = transports;
955
+ if (loggerInstance) loggerInstance.setTransports(transports);
939
956
  }
940
957
  //#endregion
941
958
  //#region src/utils/format.ts
@@ -1615,9 +1632,8 @@ const OVERFLOW_SUFFIX = "more failure reason(s)";
1615
1632
  * Accumulates per-item failures keyed by their human-readable reason string
1616
1633
  * and produces a compact grouped summary for terminal output.
1617
1634
  *
1618
- * Mirrors the grouping convention in `assets/transfer/index.ts` so all
1619
- * asset-push/transfer/pipeline failure displays are consistent: one line per
1620
- * unique cause instead of one line per failed item.
1635
+ * Keeps failure displays consistent across commands (assets, migrations):
1636
+ * one line per unique cause instead of one line per failed item.
1621
1637
  *
1622
1638
  * Usage:
1623
1639
  * ```ts
@@ -1625,8 +1641,8 @@ const OVERFLOW_SUFFIX = "more failure reason(s)";
1625
1641
  * // …during processing:
1626
1642
  * failures.record(toError(error).message, asset.short_filename);
1627
1643
  * // …after processing, before/after stopping progress bars:
1628
- * for (const line of failures.toListLines()) {
1629
- * ui.warn(line); // or ui.list(failures.toListLines())
1644
+ * for (const line of failures.toListLines("push", ["asset", "assets"])) {
1645
+ * ui.warn(line);
1630
1646
  * }
1631
1647
  * ```
1632
1648
  */
@@ -1668,13 +1684,14 @@ var FailureReasonGroup = class {
1668
1684
  * - Multiple: `Failed to push N assets — reason (e.g. "a", "b")`
1669
1685
  * - Overflow: `… and N more failure reason(s)`
1670
1686
  *
1671
- * Pass `verb` to customise the opening word ("push", "read", "transfer", …).
1687
+ * `verb` is the opening word ("push", "transfer", "migrate", …) and the
1688
+ * nouns name what failed, singular and plural.
1672
1689
  */
1673
- toListLines(verb = "push") {
1690
+ toListLines(verb, [singular, plural]) {
1674
1691
  const all = this.entries();
1675
1692
  const lines = all.slice(0, MAX_REASONS).map(({ reason, count, examples }) => {
1676
1693
  if (count === 1 && examples.length > 0) return `Failed to ${verb} "${examples[0]}": ${reason}`;
1677
- return `Failed to ${verb} ${count} ${count === 1 ? "asset" : "assets"} — ${reason}${examples.length > 0 ? ` (e.g. ${examples.map((e) => `"${e}"`).join(", ")})` : ""}`;
1694
+ return `Failed to ${verb} ${count} ${count === 1 ? singular : plural} — ${reason}${examples.length > 0 ? ` (e.g. ${examples.map((e) => `"${e}"`).join(", ")})` : ""}`;
1678
1695
  });
1679
1696
  if (all.length > MAX_REASONS) lines.push(`… and ${all.length - MAX_REASONS} ${OVERFLOW_SUFFIX}`);
1680
1697
  return lines;
@@ -1981,25 +1998,32 @@ var Reporter = class Reporter {
1981
1998
  this.report.summary[key] = value;
1982
1999
  return this;
1983
2000
  }
1984
- finalize() {
2001
+ /**
2002
+ * Writes the report. Pass the error that stopped the command early, so the
2003
+ * report says the run failed even though its summaries look complete.
2004
+ */
2005
+ finalize(stoppedBy) {
1985
2006
  if (!this.enabled) return;
1986
2007
  const endedAt = /* @__PURE__ */ new Date();
1987
2008
  this.report.meta.endedAt = endedAt.toISOString();
1988
2009
  this.report.meta.durationMs = endedAt.getTime() - this.startedAt.getTime();
1989
- this.updateStatus();
2010
+ if (stoppedBy) {
2011
+ this.report.meta.error = stoppedBy.message;
2012
+ this.report.status = REPORT_STATUS.failure;
2013
+ } else this.updateStatus();
1990
2014
  saveToFileSync(this.filePath, JSON.stringify(this.report, null, 2));
1991
2015
  if (this.maxFiles !== void 0) pruneSiblingRunFiles(this.filePath, this.maxFiles);
1992
2016
  }
2017
+ /**
2018
+ * Each summary is a stage, and stages often count the same items (e.g. a
2019
+ * story that is processed and then fails to update), so counts are never
2020
+ * added up across stages: a stage where everything failed fails the run.
2021
+ */
1993
2022
  updateStatus() {
1994
- let succeededTotal = 0;
1995
- let failedTotal = 0;
1996
- for (const item of Object.values(this.report.summary)) {
1997
- succeededTotal += item.succeeded;
1998
- failedTotal += item.failed;
1999
- }
2000
- if (failedTotal === 0) this.report.status = REPORT_STATUS.success;
2001
- else if (succeededTotal > 0) this.report.status = REPORT_STATUS.partialSuccess;
2002
- else this.report.status = REPORT_STATUS.failure;
2023
+ const stages = Object.values(this.report.summary);
2024
+ if (stages.every((stage) => stage.failed === 0)) this.report.status = REPORT_STATUS.success;
2025
+ else if (stages.some((stage) => stage.failed > 0 && stage.succeeded + (stage.skipped ?? 0) === 0)) this.report.status = REPORT_STATUS.failure;
2026
+ else this.report.status = REPORT_STATUS.partialSuccess;
2003
2027
  }
2004
2028
  static pruneReportFiles(directory, keep) {
2005
2029
  return pruneRunFiles(directory, Reporter.FILE_EXTENSION, keep);
@@ -4844,6 +4868,33 @@ const ERROR_CODES = {
4844
4868
  MIGRATION_STORY_UPDATE_NULL: "MIGRATION_STORY_UPDATE_NULL"
4845
4869
  };
4846
4870
  //#endregion
4871
+ //#region src/commands/migrations/run/failed-stories.ts
4872
+ function toReason({ step, migration, error }) {
4873
+ if (step === "fetch") return `Fetch failed: ${error}`;
4874
+ if (step === "update") return `Update failed: ${error}`;
4875
+ return migration ? `${migration} failed: ${error}` : error;
4876
+ }
4877
+ /**
4878
+ * Lists failed stories grouped by reason, so one cause shared by hundreds of
4879
+ * stories reads as one line. The reason carries the API's own explanation
4880
+ * (e.g. a workflow stage that doesn't allow publishing) when there is one.
4881
+ */
4882
+ function listFailedStories(failed) {
4883
+ const group = new FailureReasonGroup();
4884
+ for (const story of failed) {
4885
+ const { id, name } = story;
4886
+ group.record(toReason(story), name && name !== id.toString() ? `${name} (id ${id})` : `id ${id}`);
4887
+ }
4888
+ return group.toListLines("migrate", ["story", "stories"]);
4889
+ }
4890
+ /**
4891
+ * Whether an error would fail every remaining story the same way (revoked
4892
+ * credentials), so continuing the run would only repeat it for each story.
4893
+ */
4894
+ function isSystemicError(error) {
4895
+ return error instanceof APIError && error.errorId === "unauthorized";
4896
+ }
4897
+ //#endregion
4847
4898
  //#region src/commands/migrations/run/streams/stories-stream.ts
4848
4899
  /**
4849
4900
  * Iterator that fetches stories
@@ -4886,21 +4937,27 @@ async function* storiesIterator(spaceId, params, onTotal) {
4886
4937
  /**
4887
4938
  * Given a stream of stories, fetches the content for each story and streams the full story.
4888
4939
  * This is necessary because the content is not included in the stories stream.
4940
+ * A story that can't be fetched is reported through `onError` and skipped, so
4941
+ * it doesn't stop the remaining stories from being migrated. An error that
4942
+ * would fail every remaining story too (e.g. revoked credentials) stops the run.
4889
4943
  */
4890
4944
  var StoriesStream = class extends Transform {
4891
4945
  spaceId;
4892
4946
  onProgress;
4947
+ onError;
4893
4948
  semaphore;
4894
- constructor(spaceId, onProgress) {
4949
+ constructor(spaceId, onProgress, onError) {
4895
4950
  super({ objectMode: true });
4896
4951
  this.spaceId = spaceId;
4897
4952
  this.onProgress = onProgress;
4953
+ this.onError = onError;
4898
4954
  this.semaphore = createPipelineBackpressureLock();
4899
4955
  }
4900
4956
  async _transform(chunk, _encoding, callback) {
4901
4957
  try {
4902
4958
  await this.semaphore.acquire();
4903
4959
  const story = await fetchStory(this.spaceId, chunk.id.toString());
4960
+ if (!story) throw new Error("The API returned no story");
4904
4961
  this.push(story);
4905
4962
  this.onProgress?.();
4906
4963
  getLogger().info("Fetched story", { storyId: chunk.id });
@@ -4909,10 +4966,17 @@ var StoriesStream = class extends Transform {
4909
4966
  const error = toError(maybeError);
4910
4967
  getLogger().error(error.message, {
4911
4968
  storyId: chunk.id,
4969
+ storyName: chunk.name,
4912
4970
  error,
4913
4971
  errorCode: ERROR_CODES.MIGRATION_STORY_FETCH_ERROR
4914
4972
  });
4915
- callback(error);
4973
+ this.onError?.({
4974
+ storyId: chunk.id,
4975
+ name: chunk.name,
4976
+ full_slug: chunk.full_slug,
4977
+ error
4978
+ });
4979
+ callback(isSystemicError(error) ? error : null);
4916
4980
  } finally {
4917
4981
  this.semaphore.release();
4918
4982
  }
@@ -4926,10 +4990,10 @@ var StoriesStream = class extends Transform {
4926
4990
  /**
4927
4991
  * Creates a stream of stories
4928
4992
  */
4929
- const createStoriesStream = async ({ spaceId, params, onTotal, onProgress }) => {
4993
+ const createStoriesStream = async ({ spaceId, params, onTotal, onProgress, onError }) => {
4930
4994
  const iterator = storiesIterator(spaceId, params, onTotal);
4931
4995
  const listStoriesStream = Readable.from(iterator);
4932
- return pipeline(listStoriesStream, new StoriesStream(spaceId, onProgress), (err) => {
4996
+ return pipeline(listStoriesStream, new StoriesStream(spaceId, onProgress, onError), (err) => {
4933
4997
  if (err) getLogger().error(err.message, {
4934
4998
  error: err,
4935
4999
  errorCode: ERROR_CODES.MIGRATION_CREATE_STORIES_PIPELINE_ERROR
@@ -5110,16 +5174,23 @@ var MigrationStream = class extends Transform {
5110
5174
  this.migrationFunctions.set(migrationFile.name, migrationFunction);
5111
5175
  return migrationFunction;
5112
5176
  }
5177
+ recordFailure(failed) {
5178
+ this.results.failed.push(failed);
5179
+ this.options.onError?.(failed);
5180
+ }
5113
5181
  async processStory(story) {
5114
5182
  const relevantMigrations = this.options.componentName ? this.options.migrationFiles.filter((file) => migrationTargetsComponent(file.name, this.options.componentName)) : this.options.migrationFiles;
5115
5183
  if (!story.content) {
5116
- this.results.failed.push({
5184
+ this.recordFailure({
5117
5185
  storyId: story.id,
5186
+ name: story.name,
5187
+ full_slug: story.full_slug,
5118
5188
  migrationNames: relevantMigrations.map((m) => m.name),
5119
5189
  error: /* @__PURE__ */ new Error("Story content is missing")
5120
5190
  });
5121
5191
  getLogger().error("Failed to process story: Content is missing", {
5122
5192
  storyId: story.id,
5193
+ storyName: story.name,
5123
5194
  errorCode: ERROR_CODES.MIGRATION_STORY_CONTENT_MISSING
5124
5195
  });
5125
5196
  return [];
@@ -5131,25 +5202,34 @@ var MigrationStream = class extends Transform {
5131
5202
  }
5132
5203
  async applyMigrationsToStory(story, migrationFiles) {
5133
5204
  const migrationNames = migrationFiles.map((f) => f.name);
5205
+ let migrationName;
5134
5206
  try {
5135
5207
  const storyContent = structuredClone(story.content);
5136
5208
  const originalContentHash = hash(storyContent);
5137
5209
  let processed = false;
5138
5210
  for (const migrationFile of migrationFiles) {
5211
+ migrationName = migrationFile.name;
5139
5212
  const migrationFunction = await this.getOrLoadMigrationFunction(migrationFile);
5140
5213
  if (!migrationFunction) {
5141
5214
  const error = /* @__PURE__ */ new Error(`Failed to load migration function from file "${migrationFile.name}"`);
5142
- this.results.failed.push({
5215
+ this.recordFailure({
5143
5216
  storyId: story.id,
5217
+ name: story.name,
5218
+ full_slug: story.full_slug,
5144
5219
  migrationNames,
5145
5220
  error
5146
5221
  });
5147
- getLogger().error(error.message, { errorCode: ERROR_CODES.MIGRATION_FILE_NOT_FOUND });
5222
+ getLogger().error(error.message, {
5223
+ storyId: story.id,
5224
+ storyName: story.name,
5225
+ errorCode: ERROR_CODES.MIGRATION_FILE_NOT_FOUND
5226
+ });
5148
5227
  return null;
5149
5228
  }
5150
5229
  const migrationProcessed = applyMigrationToAllBlocks(storyContent, migrationFunction, migrationFile.name);
5151
5230
  processed = processed || migrationProcessed;
5152
5231
  }
5232
+ migrationName = void 0;
5153
5233
  const contentChanged = originalContentHash !== hash(storyContent);
5154
5234
  if (processed && contentChanged) {
5155
5235
  await saveRollbackData({
@@ -5178,6 +5258,7 @@ var MigrationStream = class extends Transform {
5178
5258
  return {
5179
5259
  storyId: story.id,
5180
5260
  name: story.name,
5261
+ full_slug: story.full_slug,
5181
5262
  content: storyContent,
5182
5263
  published: story.published ?? void 0,
5183
5264
  unpublished_changes: story.unpublished_changes ?? void 0
@@ -5210,14 +5291,19 @@ var MigrationStream = class extends Transform {
5210
5291
  }
5211
5292
  } catch (maybeError) {
5212
5293
  const error = toError(maybeError);
5213
- this.results.failed.push({
5294
+ this.recordFailure({
5214
5295
  storyId: story.id,
5296
+ name: story.name,
5297
+ full_slug: story.full_slug,
5215
5298
  migrationNames,
5299
+ migrationName,
5216
5300
  error
5217
5301
  });
5218
5302
  getLogger().error(error.message, {
5219
5303
  storyId: story.id,
5304
+ storyName: story.name,
5220
5305
  migrationNames,
5306
+ migrationName,
5221
5307
  error,
5222
5308
  errorCode: ERROR_CODES.MIGRATION_APPLY_TO_STORY_ERROR
5223
5309
  });
@@ -5238,7 +5324,7 @@ var MigrationStream = class extends Transform {
5238
5324
  */
5239
5325
  getSummary() {
5240
5326
  const { successful, failed, skipped } = this.results;
5241
- let summary = `Migration Results: ${new Set(successful.map((result) => result.storyId)).size} stories updated, ${skipped.length} stories skipped`;
5327
+ let summary = `Migration Results: ${new Set(successful.map((result) => result.storyId)).size} stories migrated, ${skipped.length} stories skipped`;
5242
5328
  if (skipped.length > 0) {
5243
5329
  const skippedByReason = skipped.reduce((acc, item) => {
5244
5330
  if (!acc[item.reason]) acc[item.reason] = 0;
@@ -5328,7 +5414,20 @@ var UpdateStream = class extends Writable {
5328
5414
  async _write(chunk, _encoding, callback) {
5329
5415
  try {
5330
5416
  await this.semaphore.acquire();
5331
- this.updateStory(chunk).finally(() => {
5417
+ if (this.destroyed) {
5418
+ this.semaphore.release();
5419
+ callback();
5420
+ return;
5421
+ }
5422
+ this.updateStory(chunk).catch((maybeError) => {
5423
+ const error = toError(maybeError);
5424
+ getLogger().error(error.message, {
5425
+ storyId: chunk.storyId,
5426
+ storyName: chunk.name,
5427
+ error,
5428
+ errorCode: ERROR_CODES.MIGRATION_STORY_UPDATE_ERROR
5429
+ });
5430
+ }).finally(() => {
5332
5431
  this.semaphore.release();
5333
5432
  });
5334
5433
  callback();
@@ -5337,7 +5436,7 @@ var UpdateStream = class extends Writable {
5337
5436
  }
5338
5437
  }
5339
5438
  async updateStory(migrationResult) {
5340
- const { storyId, name, content, published, unpublished_changes } = migrationResult;
5439
+ const { storyId, name, full_slug, content, published, unpublished_changes } = migrationResult;
5341
5440
  const storyName = name || storyId.toString();
5342
5441
  try {
5343
5442
  const payload = {
@@ -5367,38 +5466,44 @@ var UpdateStream = class extends Writable {
5367
5466
  getLogger().info("Updated story", { storyId });
5368
5467
  } else {
5369
5468
  const error = /* @__PURE__ */ new Error("Update returned null");
5370
- this.results.failed.push({
5469
+ this.recordFailure({
5371
5470
  storyId,
5372
5471
  name: storyName,
5472
+ full_slug,
5373
5473
  error
5374
5474
  });
5375
- this.results.totalProcessed++;
5376
- this.options.onProgress?.(this.results.totalProcessed);
5377
5475
  getLogger().error(`Failed to update story: ${error.message}`, {
5378
5476
  storyId,
5477
+ storyName,
5379
5478
  errorCode: ERROR_CODES.MIGRATION_STORY_UPDATE_NULL
5380
5479
  });
5381
5480
  }
5382
5481
  } catch (maybeError) {
5383
5482
  const error = toError(maybeError);
5384
- this.results.failed.push({
5483
+ this.recordFailure({
5385
5484
  storyId,
5386
5485
  name: storyName,
5486
+ full_slug,
5387
5487
  error
5388
5488
  });
5389
- this.results.totalProcessed++;
5390
- this.options.onProgress?.(this.results.totalProcessed);
5391
5489
  getLogger().error(error.message, {
5392
5490
  storyId,
5491
+ storyName,
5393
5492
  error,
5394
5493
  errorCode: ERROR_CODES.MIGRATION_STORY_UPDATE_ERROR
5395
5494
  });
5495
+ if (isSystemicError(error)) this.destroy(error);
5396
5496
  }
5397
5497
  }
5498
+ recordFailure(failed) {
5499
+ this.results.failed.push(failed);
5500
+ this.results.totalProcessed++;
5501
+ this.options.onProgress?.(this.results.totalProcessed);
5502
+ this.options.onError?.(failed);
5503
+ }
5398
5504
  async _destroy(error, callback) {
5399
5505
  try {
5400
5506
  await this.semaphore.drain();
5401
- callback();
5402
5507
  } catch (batchError) {
5403
5508
  callback(batchError);
5404
5509
  return;
@@ -5472,6 +5577,10 @@ migrationsCommand.command("run [componentName]").description("Run migrations").o
5472
5577
  const storiesProgress = ui.createProgressBar({ title: "Fetching Stories...".padEnd(19) });
5473
5578
  const migrationsProgress = ui.createProgressBar({ title: "Applying Migrations".padEnd(19) });
5474
5579
  const updateProgress = ui.createProgressBar({ title: "Updating Stories...".padEnd(19) });
5580
+ const failedStories = [];
5581
+ let listedStories = 0;
5582
+ let fetchedStories = 0;
5583
+ let fetchFailedStories = 0;
5475
5584
  const storiesStream = await createStoriesStream({
5476
5585
  spaceId: space,
5477
5586
  params: {
@@ -5482,11 +5591,25 @@ migrationsCommand.command("run [componentName]").description("Run migrations").o
5482
5591
  })
5483
5592
  },
5484
5593
  onTotal: (total) => {
5594
+ listedStories = total;
5485
5595
  storiesProgress.setTotal(total);
5486
5596
  migrationsProgress.setTotal(total);
5487
5597
  },
5488
5598
  onProgress: () => {
5599
+ fetchedStories++;
5489
5600
  storiesProgress.increment();
5601
+ },
5602
+ onError: ({ storyId, name, full_slug, error }) => {
5603
+ fetchFailedStories++;
5604
+ storiesProgress.increment();
5605
+ migrationsProgress.increment();
5606
+ failedStories.push({
5607
+ id: storyId,
5608
+ name,
5609
+ full_slug,
5610
+ step: "fetch",
5611
+ error: error.message
5612
+ });
5490
5613
  }
5491
5614
  });
5492
5615
  const migrationStream = new MigrationStream({
@@ -5500,6 +5623,16 @@ migrationsCommand.command("run [componentName]").description("Run migrations").o
5500
5623
  },
5501
5624
  onProgress: () => {
5502
5625
  migrationsProgress.increment();
5626
+ },
5627
+ onError: ({ storyId, name, full_slug, error, migrationName }) => {
5628
+ failedStories.push({
5629
+ id: storyId,
5630
+ name,
5631
+ full_slug,
5632
+ step: "migrate",
5633
+ migration: migrationName,
5634
+ error: error.message
5635
+ });
5503
5636
  }
5504
5637
  });
5505
5638
  const updateStream = new UpdateStream({
@@ -5508,22 +5641,23 @@ migrationsCommand.command("run [componentName]").description("Run migrations").o
5508
5641
  dryRun,
5509
5642
  onProgress: () => {
5510
5643
  updateProgress.increment();
5644
+ },
5645
+ onError: ({ storyId, name, full_slug, error }) => {
5646
+ failedStories.push({
5647
+ id: storyId,
5648
+ name,
5649
+ full_slug,
5650
+ step: "update",
5651
+ error: error.message
5652
+ });
5511
5653
  }
5512
5654
  });
5513
- await new Promise((resolve, reject) => {
5655
+ const fatalError = await new Promise((resolve) => {
5514
5656
  pipeline(storiesStream, migrationStream, updateStream, (err) => {
5515
- if (err) {
5516
- reject(err);
5517
- return;
5518
- }
5519
- resolve();
5657
+ resolve(err ?? null);
5520
5658
  });
5521
5659
  });
5522
5660
  ui.stopAllProgressBars();
5523
- const migrationSummary = migrationStream.getSummary();
5524
- ui.info(migrationSummary);
5525
- const updateSummary = updateStream.getSummary();
5526
- ui.info(updateSummary);
5527
5661
  const migrationStreamResults = migrationStream.getResults();
5528
5662
  const migrationResults = {
5529
5663
  total: migrationStreamResults.totalProcessed,
@@ -5537,13 +5671,40 @@ migrationsCommand.command("run [componentName]").description("Run migrations").o
5537
5671
  succeeded: updateStreamResults.successful.length,
5538
5672
  failed: updateStreamResults.failed.length
5539
5673
  };
5674
+ const fetchResults = {
5675
+ total: fetchedStories + fetchFailedStories,
5676
+ succeeded: fetchedStories,
5677
+ failed: fetchFailedStories
5678
+ };
5679
+ if (fatalError && listedStories > 0) {
5680
+ const finishedStories = fetchResults.failed + migrationResults.failed + migrationResults.skipped + updateResults.total;
5681
+ ui.warn(`Run stopped after ${finishedStories} of ${listedStories} stories.`);
5682
+ }
5683
+ if (!fatalError || listedStories > 0) ui.info(migrationStream.getSummary());
5684
+ if (updateResults.total > 0 || !fatalError && failedStories.length === 0) ui.info(updateStream.getSummary());
5685
+ if (failedStories.length > 0) ui.list(listFailedStories(failedStories));
5686
+ const fullListPath = reporter.enabled ? reporter.filePath : logger.transports.find((transport) => transport instanceof FileTransport)?.filePath;
5540
5687
  logger.info("Migration finished", {
5688
+ fetchResults,
5541
5689
  migrationResults,
5542
5690
  updateResults
5543
5691
  });
5692
+ reporter.addSummary("fetchResults", fetchResults);
5544
5693
  reporter.addSummary("migrationResults", migrationResults);
5545
5694
  reporter.addSummary("updateResults", updateResults);
5546
- reporter.finalize();
5695
+ if (failedStories.length > 0) reporter.addMeta("failedStories", failedStories);
5696
+ try {
5697
+ reporter.finalize(fatalError ?? void 0);
5698
+ if (failedStories.length > 0 && fullListPath) ui.info(`All failed stories are listed in ${fullListPath}`);
5699
+ } catch (error) {
5700
+ if (!fatalError) throw error;
5701
+ handleError(error, verbose);
5702
+ }
5703
+ if (fatalError) {
5704
+ handleError(fatalError, verbose);
5705
+ return;
5706
+ }
5707
+ process.exitCode = failedStories.length > 0 ? 1 : 0;
5547
5708
  } catch (error) {
5548
5709
  handleError(error, verbose);
5549
5710
  }
@@ -9779,7 +9940,7 @@ const upsertAssetsPipeline = async ({ assetBinaryPath, assetData, directoryPath,
9779
9940
  }
9780
9941
  }));
9781
9942
  await pipeline$1(steps);
9782
- for (const line of failures.toListLines()) ui.warn(line);
9943
+ for (const line of failures.toListLines("push", ["asset", "assets"])) ui.warn(line);
9783
9944
  return [["assetResults", summary]];
9784
9945
  };
9785
9946
  const mapAssetReferencesInStoriesPipeline = async ({ logger, maps, schemas, space, transports, ui }) => {
@@ -10261,7 +10422,7 @@ assetsCommand.command("transfer [asset-id...]").option("-s, --space <space>", "s
10261
10422
  if (summary.failed > 0) {
10262
10423
  const failures = new FailureReasonGroup();
10263
10424
  for (const result of results) if (result.status === "failed") failures.record(result.reason ?? "Unknown error");
10264
- ui.list(failures.toListLines("transfer"));
10425
+ ui.list(failures.toListLines("transfer", ["asset", "assets"]));
10265
10426
  }
10266
10427
  reporter.addSummary("transferResults", summary);
10267
10428
  reporter.finalize();
@@ -14116,6 +14277,119 @@ function collectTagNames(component) {
14116
14277
  return [...names];
14117
14278
  }
14118
14279
  //#endregion
14280
+ //#region src/commands/schema/dimensions.ts
14281
+ const IDENTITY_KEYS = ["entry_value", "name"];
14282
+ function isDimensionIdentity(value) {
14283
+ return isRecord(value) && typeof value.name === "string" && typeof value.entry_value === "string";
14284
+ }
14285
+ /** The declarable dimensions of a `dimensions` value, in entry_value order. */
14286
+ function toDimensionList(value) {
14287
+ return (Array.isArray(value) ? value.filter(isDimensionIdentity) : []).sort((a, b) => compareStrings(a.entry_value, b.entry_value) || compareStrings(a.name, b.name));
14288
+ }
14289
+ function compareStrings(a, b) {
14290
+ return a < b ? -1 : a > b ? 1 : 0;
14291
+ }
14292
+ /**
14293
+ * A matched dimension keeps its remote id, and with it the values editors
14294
+ * entered for that dimension. An identical dimension is matched first, so the
14295
+ * result does not depend on order when the space holds duplicates. After that,
14296
+ * `entry_value` takes precedence over `name` because the Content Delivery API
14297
+ * `dimension` parameter filters by it.
14298
+ */
14299
+ function pairDimensions(local, remote) {
14300
+ const pairs = /* @__PURE__ */ new Map();
14301
+ const unmatchedRemote = [...remote];
14302
+ const matchers = [(rd, ld) => isUnchanged(ld, rd), ...IDENTITY_KEYS.map((key) => (rd, ld) => rd[key] === ld[key])];
14303
+ for (const matches of matchers) for (const localDimension of local) {
14304
+ if (pairs.has(localDimension)) continue;
14305
+ const index = unmatchedRemote.findIndex((rd) => matches(rd, localDimension));
14306
+ if (index !== -1) {
14307
+ pairs.set(localDimension, unmatchedRemote[index]);
14308
+ unmatchedRemote.splice(index, 1);
14309
+ }
14310
+ }
14311
+ return {
14312
+ pairs,
14313
+ unmatchedRemote
14314
+ };
14315
+ }
14316
+ function isUnchanged(declared, own) {
14317
+ return own?.name === declared.name && own.entry_value === declared.entry_value;
14318
+ }
14319
+ /**
14320
+ * The Management API checks both the `name` and the `entry_value` of every
14321
+ * dimension an update creates or changes against the stored dimensions, before
14322
+ * it applies any other change of the same update. A value another dimension
14323
+ * still holds is therefore rejected, even when that dimension is renamed or
14324
+ * removed in the same update, and even when the changed dimension keeps that
14325
+ * value.
14326
+ */
14327
+ function findDimensionConflicts(local, remote) {
14328
+ const { pairs } = pairDimensions(local, remote);
14329
+ const conflicts = [];
14330
+ for (const declared of local) {
14331
+ const own = pairs.get(declared);
14332
+ if (isUnchanged(declared, own)) continue;
14333
+ for (const key of IDENTITY_KEYS) {
14334
+ const holder = remote.find((rd) => rd !== own && rd[key] === declared[key]);
14335
+ if (holder) conflicts.push({
14336
+ declared,
14337
+ key,
14338
+ holder
14339
+ });
14340
+ }
14341
+ }
14342
+ return conflicts;
14343
+ }
14344
+ /**
14345
+ * The Management API does not check the dimensions of one request against each
14346
+ * other, so dimensions that share a value and are created or changed together
14347
+ * are stored as they are. Duplicates the space already holds, and that the
14348
+ * update leaves untouched, are not reported.
14349
+ */
14350
+ function findDuplicateDimensions(local, remote) {
14351
+ const { pairs } = pairDimensions(local, remote);
14352
+ const duplicates = /* @__PURE__ */ new Map();
14353
+ for (const declared of local) {
14354
+ if (isUnchanged(declared, pairs.get(declared))) continue;
14355
+ for (const key of IDENTITY_KEYS) {
14356
+ const value = declared[key];
14357
+ if (local.some((other) => other !== declared && other[key] === value)) duplicates.set(`${key}:${value}`, {
14358
+ key,
14359
+ value
14360
+ });
14361
+ }
14362
+ }
14363
+ return [...duplicates.values()];
14364
+ }
14365
+ function formatDuplicateDimensions(datasourceName, duplicates) {
14366
+ return `Datasource '${datasourceName}' declares more than one dimension with ${duplicates.map(({ key, value }) => `the ${key} '${value}'`).join(", ")}. Give each dimension a unique name and entry_value.`;
14367
+ }
14368
+ function describeDimension({ name, entry_value }) {
14369
+ return `'${name}' (entry_value '${entry_value}')`;
14370
+ }
14371
+ function formatDimensionConflicts(datasourceName, conflicts) {
14372
+ return `Datasource '${datasourceName}' cannot be updated in one step: ${conflicts.map(({ declared, key, holder }) => `dimension ${describeDimension(declared)} uses the ${key} '${declared[key]}' still held by the existing dimension ${describeDimension(holder)}`).join("; ")}. The Management API rejects a name or entry_value that another dimension holds before the update. Apply the change in two steps: first change that value on the existing dimension or remove it, then make this change.`;
14373
+ }
14374
+ /** Dimensions an update removes, and with them the values entered for them. */
14375
+ function removedDimensionNames(diff) {
14376
+ const { unmatchedRemote } = pairDimensions(toDimensionList(diff.after?.dimensions), toDimensionList(diff.before?.dimensions));
14377
+ return unmatchedRemote.map((dimension) => dimension.name);
14378
+ }
14379
+ /**
14380
+ * Duplicates a datasource create or update would store, or `null` when there
14381
+ * are none. Pass no `remote` for a create.
14382
+ */
14383
+ function describeDuplicateDimensions(datasourceName, local, remote) {
14384
+ const duplicates = findDuplicateDimensions(toDimensionList(local), toDimensionList(remote));
14385
+ return duplicates.length > 0 ? formatDuplicateDimensions(datasourceName, duplicates) : null;
14386
+ }
14387
+ /** Why the Management API would reject a datasource update, or `null` when it would not. */
14388
+ function describeDimensionConflicts(datasourceName, local, remote) {
14389
+ const conflicts = findDimensionConflicts(toDimensionList(local), toDimensionList(remote));
14390
+ return conflicts.length > 0 ? formatDimensionConflicts(datasourceName, conflicts) : null;
14391
+ }
14392
+ //#endregion
14119
14393
  //#region src/commands/schema/diff-schema.ts
14120
14394
  function resolveTagWith(own, other) {
14121
14395
  return (entry) => {
@@ -14199,9 +14473,9 @@ function asRecord(value) {
14199
14473
  return isRecord(value) ? value : {};
14200
14474
  }
14201
14475
  /**
14202
- * An array that is really a set keyed by `name` — datasource dimensions — as a
14203
- * name-keyed record, so a change reads as the member that moved
14204
- * rather than two dumps of the whole list, and reordering alone is not a change.
14476
+ * An array that is really a set keyed by `name` as a name-keyed record, so a
14477
+ * change reads as the member that moved rather than two dumps of the whole
14478
+ * list, and reordering alone is not a change.
14205
14479
  * Returns `null` for any other array shape, including one whose duplicate names
14206
14480
  * would make the mapping lossy.
14207
14481
  */
@@ -14218,8 +14492,7 @@ function asNameKeyed(value) {
14218
14492
  * Like {@link diffKeyed}, but recurses into nested records so a change reads as
14219
14493
  * the property that actually moved (`schema.body.maximum`) instead of two dumps
14220
14494
  * of the whole enclosing object. Name-keyed arrays are recursed into the same
14221
- * way (`dimensions.fr.entry_value`); every other non-record value is reported
14222
- * whole.
14495
+ * way; every other non-record value is reported whole.
14223
14496
  */
14224
14497
  function diffKeyedDeep(before, after, prefix) {
14225
14498
  const changes = [];
@@ -14273,6 +14546,47 @@ function componentChanges(before, after) {
14273
14546
  return [...diffKeyed(beforeProps, afterProps), ...diffKeyedDeep(asRecord(beforeSchema), asRecord(afterSchema), "schema.")];
14274
14547
  }
14275
14548
  /**
14549
+ * Dimension changes as `schema push` applies them: a dimension paired with a
14550
+ * remote one is updated in place and reads as the property that changed, keyed
14551
+ * by the name it has in the space (`dimensions.Light.name` for a rename of
14552
+ * `Light`). Only an unpaired
14553
+ * dimension is `added` or `removed`, and removing one deletes the values
14554
+ * entered for it.
14555
+ */
14556
+ function dimensionChanges(before, after) {
14557
+ const changes = [];
14558
+ const target = toDimensionList(after);
14559
+ const { pairs, unmatchedRemote } = pairDimensions(target, toDimensionList(before));
14560
+ for (const dimension of target) {
14561
+ const current = pairs.get(dimension);
14562
+ if (!current) {
14563
+ changes.push({
14564
+ field: `dimensions.${dimension.name}`,
14565
+ change: "added",
14566
+ after: dimension
14567
+ });
14568
+ continue;
14569
+ }
14570
+ for (const key of ["entry_value", "name"]) if (current[key] !== dimension[key]) changes.push({
14571
+ field: `dimensions.${current.name}.${key}`,
14572
+ change: "modified",
14573
+ before: current[key],
14574
+ after: dimension[key]
14575
+ });
14576
+ }
14577
+ for (const dimension of unmatchedRemote) changes.push({
14578
+ field: `dimensions.${dimension.name}`,
14579
+ change: "removed",
14580
+ before: dimension
14581
+ });
14582
+ return changes.sort((a, b) => a.field < b.field ? -1 : a.field > b.field ? 1 : 0);
14583
+ }
14584
+ function datasourceChanges(before, after) {
14585
+ const { dimensions: beforeDimensions, ...beforeProps } = before;
14586
+ const { dimensions: afterDimensions, ...afterProps } = after;
14587
+ return [...dimensionChanges(beforeDimensions, afterDimensions), ...diffKeyedDeep(beforeProps, afterProps, "")];
14588
+ }
14589
+ /**
14276
14590
  * `cleanComponent` marks an explicitly ungrouped block with a sentinel, because
14277
14591
  * a literal `null` would be dropped by the canonical form and become
14278
14592
  * indistinguishable from a block that does not manage its group at all. Once the
@@ -14329,7 +14643,7 @@ function buildEntityDiff(type, name, fromClean, toClean) {
14329
14643
  type,
14330
14644
  name,
14331
14645
  action: "update",
14332
- changes: (type === "component" ? componentChanges(fromClean, toClean) : diffKeyedDeep(fromClean, toClean, "")).map(resolveFolderSentinelInChange),
14646
+ changes: (type === "component" ? componentChanges(fromClean, toClean) : datasourceChanges(fromClean, toClean)).map(resolveFolderSentinelInChange),
14333
14647
  before: resolveFolderSentinel(fromClean),
14334
14648
  after: resolveFolderSentinel(toClean)
14335
14649
  };
@@ -14433,8 +14747,19 @@ function diffComponent(name, fromComp, toComp, context, compareGroupUuid, manage
14433
14747
  const byTagName = comparesTagsByName(fromComp, toComp, context.from, context.to);
14434
14748
  return buildEntityDiff("component", name, fromComp ? cleanComponent(applyDefaults(toPathSpace(toTagSpace(omitUnmanagedOptionalKeys(fromComp, toComp), fromTag, byTagName), uuidToPath, manageFolder), COMPONENT_DEFAULTS), { includeGroupUuid }) : null, toComp ? cleanComponent(applyDefaults(toPathSpace(toTagSpace(omitUnmanagedOptionalKeys(toComp, fromComp), toTag, byTagName), uuidToPath, manageFolder), COMPONENT_DEFAULTS), { includeGroupUuid }) : null);
14435
14749
  }
14750
+ /**
14751
+ * Dimension order carries no meaning: an update cannot set it, and the
14752
+ * Management API returns dimensions in no guaranteed order.
14753
+ */
14754
+ function cleanDatasourceForDiff(datasource) {
14755
+ const clean = cleanDatasource(applyDefaults(datasource, DATASOURCE_DEFAULTS));
14756
+ return {
14757
+ ...clean,
14758
+ dimensions: toDimensionList(clean.dimensions)
14759
+ };
14760
+ }
14436
14761
  function diffDatasource(name, fromDs, toDs) {
14437
- return buildEntityDiff("datasource", name, fromDs ? cleanDatasource(applyDefaults(fromDs, DATASOURCE_DEFAULTS)) : null, toDs ? cleanDatasource(applyDefaults(toDs, DATASOURCE_DEFAULTS)) : null);
14762
+ return buildEntityDiff("datasource", name, fromDs ? cleanDatasourceForDiff(fromDs) : null, toDs ? cleanDatasourceForDiff(toDs) : null);
14438
14763
  }
14439
14764
  /**
14440
14765
  * Folders (component groups) are identified by slug path. Renames are
@@ -14877,6 +15202,42 @@ function assertPushableFields(components) {
14877
15202
  }
14878
15203
  if (problems.length > 0) throw new CommandError(`Schema fields that cannot be pushed: ${problems.join(", ")}. Run \`storyblok schema validate\` for the full report.`);
14879
15204
  }
15205
+ const DIMENSION_IDENTITY_KEYS = ["name", "entry_value"];
15206
+ /**
15207
+ * Fails the load when a datasource declares dimensions the push cannot carry.
15208
+ *
15209
+ * A `dimensions` value that is not an array reads as no dimensions, so the push
15210
+ * deletes every dimension the space holds. A dimension without a string `name`
15211
+ * and `entry_value` is dropped from the update, so it never reaches the space
15212
+ * and nothing reports it. A blank one is rejected by the Management API, but
15213
+ * only once the push is underway, after other entities may already have been
15214
+ * written. `schema validate` reports the same problems as
15215
+ * `invalid_datasource_dimensions` / `invalid_dimension*`.
15216
+ */
15217
+ function assertPushableDimensions(datasources) {
15218
+ const problems = [];
15219
+ for (const datasource of datasources) {
15220
+ const datasourceLabel = `datasource "${String(datasource.slug)}"`;
15221
+ const dimensions = datasource.dimensions;
15222
+ if (dimensions === void 0) continue;
15223
+ if (!Array.isArray(dimensions)) {
15224
+ problems.push(`"dimensions" in ${datasourceLabel} is not an array`);
15225
+ continue;
15226
+ }
15227
+ dimensions.forEach((dimension, index) => {
15228
+ const dimensionLabel = `the dimension at index ${index} in ${datasourceLabel}`;
15229
+ if (!isRecord(dimension)) {
15230
+ problems.push(`${dimensionLabel} is not an object`);
15231
+ return;
15232
+ }
15233
+ for (const key of DIMENSION_IDENTITY_KEYS) {
15234
+ const value = dimension[key];
15235
+ if (typeof value !== "string" || value.trim() === "") problems.push(`${dimensionLabel} has a missing or blank "${key}"`);
15236
+ }
15237
+ });
15238
+ }
15239
+ if (problems.length > 0) throw new CommandError(`Datasource dimensions that cannot be pushed: ${problems.join(", ")}. Run \`storyblok schema validate\` for the full report.`);
15240
+ }
14880
15241
  const toArray = (value) => Array.isArray(value) ? value : [];
14881
15242
  /**
14882
15243
  * Classifies a module's exports into wire components, datasources, and folders,
@@ -14888,6 +15249,7 @@ function classifyExports(moduleExports) {
14888
15249
  const { components, datasources, folders } = collectSchemaExports(moduleExports);
14889
15250
  assertUniqueIdentities(components, datasources);
14890
15251
  assertPushableFields(components);
15252
+ assertPushableDimensions(datasources);
14891
15253
  const registered = folders.map((folder) => folder.path);
14892
15254
  const derived = [];
14893
15255
  for (const component of components) {
@@ -15953,6 +16315,12 @@ function toComponentCreate(input) {
15953
16315
  function toComponentUpdate(input) {
15954
16316
  return buildComponentPayload(input);
15955
16317
  }
16318
+ function declaredDimensions(dimensions) {
16319
+ return dimensions.filter(isDimensionIdentity).map(({ name, entry_value }) => ({
16320
+ name,
16321
+ entry_value
16322
+ }));
16323
+ }
15956
16324
  /** Converts an unknown input to a DatasourceCreate-compatible payload. */
15957
16325
  function toDatasourceCreate(input) {
15958
16326
  if (!isRecord(input)) return {
@@ -15963,32 +16331,33 @@ function toDatasourceCreate(input) {
15963
16331
  name: typeof input.name === "string" ? input.name : "",
15964
16332
  slug: typeof input.slug === "string" ? input.slug : ""
15965
16333
  };
15966
- if (Array.isArray(input.dimensions)) result.dimensions_attributes = input.dimensions.filter((d) => isRecord(d) && typeof d.name === "string" && typeof d.entry_value === "string").map((d) => ({
15967
- name: d.name,
15968
- entry_value: d.entry_value
15969
- }));
16334
+ if (Array.isArray(input.dimensions)) result.dimensions_attributes = declaredDimensions(input.dimensions);
15970
16335
  return result;
15971
16336
  }
15972
16337
  /**
15973
- * Builds a datasource update payload that handles dimension deletions.
15974
- * The Storyblok API requires `{ id, _destroy: true }` to remove dimensions;
15975
- * an empty `dimensions_attributes` array is a no-op.
16338
+ * The Management API treats a dimension without an `id` as new and rejects it
16339
+ * when its `name` or `entry_value` already exists. Removing one requires
16340
+ * `{ id, _destroy: true }`; an empty `dimensions_attributes` array is a no-op.
15976
16341
  */
15977
16342
  function toDatasourceUpdate(input, remote) {
15978
16343
  const base = toDatasourceCreate(input);
15979
- const localDims = base.dimensions_attributes ?? [];
15980
- const remoteDims = remote.dimensions ?? [];
15981
- if (remoteDims.length === 0) return base;
15982
- const localKeys = new Set(localDims.map((d) => `${d.name}::${d.entry_value}`));
15983
- const destroyEntries = remoteDims.filter((rd) => rd.id != null && !localKeys.has(`${rd.name}::${rd.entry_value}`)).map((rd) => ({
15984
- id: rd.id,
15985
- _destroy: true
15986
- }));
15987
- if (destroyEntries.length > 0) return {
16344
+ const localDimensions = isRecord(input) && Array.isArray(input.dimensions) ? declaredDimensions(input.dimensions) : [];
16345
+ const remoteDimensions = (remote.dimensions ?? []).filter((rd) => rd.id != null);
16346
+ if (remoteDimensions.length === 0) return base;
16347
+ const { pairs, unmatchedRemote } = pairDimensions(localDimensions, remoteDimensions);
16348
+ return {
15988
16349
  ...base,
15989
- dimensions_attributes: [...localDims, ...destroyEntries]
16350
+ dimensions_attributes: [...localDimensions.map((local) => {
16351
+ const match = pairs.get(local);
16352
+ return match ? {
16353
+ id: match.id,
16354
+ ...local
16355
+ } : local;
16356
+ }), ...unmatchedRemote.map((rd) => ({
16357
+ id: rd.id,
16358
+ _destroy: true
16359
+ }))]
15990
16360
  };
15991
- return base;
15992
16361
  }
15993
16362
  //#endregion
15994
16363
  //#region src/commands/schema/push/actions.ts
@@ -16754,6 +17123,12 @@ schemaCommand.command("push <entry-file>").description("Push local TypeScript sc
16754
17123
  const diffResult = diffSchema(remoteToNormalized(remote), localToNormalized(local), { compareGroupUuid: true });
16755
17124
  ui.br();
16756
17125
  ui.log(formatDiffOutput(diffResult, { delete: options.delete }));
17126
+ const datasourceWrites = diffResult.diffs.filter((d) => d.type === "datasource" && (d.action === "create" || d.action === "update"));
17127
+ const dimensionConflicts = datasourceWrites.map((d) => describeDuplicateDimensions(d.name, d.after?.dimensions, d.before?.dimensions) ?? describeDimensionConflicts(d.name, d.after?.dimensions, d.before?.dimensions)).filter((message) => message !== null);
17128
+ if (dimensionConflicts.length > 0) {
17129
+ handleError(new CommandError(dimensionConflicts.join("\n")), verbose);
17130
+ return;
17131
+ }
16757
17132
  if (options.migrations) {
16758
17133
  const breakingChanges = analyzeBreakingChanges(diffResult, local, remote);
16759
17134
  if (breakingChanges.length > 0) {
@@ -16826,6 +17201,7 @@ schemaCommand.command("push <entry-file>").description("Push local TypeScript sc
16826
17201
  }
16827
17202
  }
16828
17203
  }
17204
+ for (const datasource of datasourceWrites) for (const dimension of removedDimensionNames(datasource)) ui.warn(`Dimension '${dimension}' of datasource '${datasource.name}' will be deleted along with the values entered for it.`);
16829
17205
  if (diffResult.stale > 0 && !options.delete) ui.warn(`${diffResult.stale} stale entity(s) exist remotely but not in schema. Use --delete to remove.`);
16830
17206
  if (options.dryRun) {
16831
17207
  ui.info("Dry run — no changes applied.");
@@ -17080,6 +17456,17 @@ function remapGroupUuids(payload, uuidMap) {
17080
17456
  return result;
17081
17457
  }
17082
17458
  /**
17459
+ * Throws when a datasource the rollback restores holds dimensions the
17460
+ * Management API would reject, before any rollback op is applied.
17461
+ */
17462
+ function assertRollbackApplicable(ops, remote) {
17463
+ for (const op of ops) {
17464
+ if (op.type !== "datasource" || op.action !== "update") continue;
17465
+ const conflict = describeDimensionConflicts(op.name, op.payload.dimensions, remote.datasources.get(op.name)?.dimensions);
17466
+ if (conflict) throw new CommandError(conflict);
17467
+ }
17468
+ }
17469
+ /**
17083
17470
  * Applies rollback ops to the MAPI in dependency-safe order:
17084
17471
  * 1. Folder creates (parent-first) — recreated groups get new uuids, tracked in
17085
17472
  * an old→new map so restored components can be remapped onto them.
@@ -17103,6 +17490,7 @@ async function executeRollback(spaceId, ops, remote) {
17103
17490
  const componentOps = ops.filter((op) => op.type === "component");
17104
17491
  const datasourceOps = ops.filter((op) => op.type === "datasource");
17105
17492
  const folderOps = ops.filter((op) => op.type === "folder");
17493
+ assertRollbackApplicable(datasourceOps, remote);
17106
17494
  const groupRefByPath = buildGroupRefByPath(remote);
17107
17495
  const groupUuidMap = /* @__PURE__ */ new Map();
17108
17496
  const folderCreates = folderOps.filter((o) => o.action === "create").sort((a, b) => a.name.split("/").length - b.name.split("/").length);
@@ -17304,6 +17692,23 @@ schemaCommand.command("rollback [changeset-file]").description("Roll back a Stor
17304
17692
  }
17305
17693
  ui.br();
17306
17694
  ui.log(formatRollbackOutput(changeset.changes));
17695
+ const remoteSpinner = ui.createSpinner(`Fetching current remote state from space ${space}...`);
17696
+ let remoteResult;
17697
+ try {
17698
+ remoteResult = await fetchRemoteSchema(space);
17699
+ } catch (maybeError) {
17700
+ remoteSpinner.failed("Failed to fetch remote schema");
17701
+ handleError(toError(maybeError), verbose);
17702
+ return;
17703
+ }
17704
+ const { remote } = remoteResult;
17705
+ remoteSpinner.succeed(`Remote: ${remote.components.size} components, ${remote.componentFolders.size} component folders, ${remote.datasources.size} datasources`);
17706
+ try {
17707
+ assertRollbackApplicable(ops, remote);
17708
+ } catch (maybeError) {
17709
+ handleError(toError(maybeError), verbose);
17710
+ return;
17711
+ }
17307
17712
  if (options.dryRun) {
17308
17713
  ui.info("Dry run — no changes applied.");
17309
17714
  logger.info("Dry run completed", { ops: ops.length });
@@ -17318,17 +17723,6 @@ schemaCommand.command("rollback [changeset-file]").description("Roll back a Stor
17318
17723
  return;
17319
17724
  }
17320
17725
  }
17321
- const remoteSpinner = ui.createSpinner(`Fetching current remote state from space ${space}...`);
17322
- let remoteResult;
17323
- try {
17324
- remoteResult = await fetchRemoteSchema(space);
17325
- } catch (maybeError) {
17326
- remoteSpinner.failed("Failed to fetch remote schema");
17327
- handleError(toError(maybeError), verbose);
17328
- return;
17329
- }
17330
- const { remote } = remoteResult;
17331
- remoteSpinner.succeed(`Remote: ${remote.components.size} components, ${remote.componentFolders.size} component folders, ${remote.datasources.size} datasources`);
17332
17726
  const rollbackSpinner = ui.createSpinner("Applying rollback...");
17333
17727
  let result;
17334
17728
  try {