@bernierllc/contentful-migration-service 1.6.2 → 1.6.5

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/README.md CHANGED
@@ -345,19 +345,18 @@ for (const id of pending) {
345
345
  Uses `@bernierllc/logger` for structured logging throughout the service.
346
346
 
347
347
  **NeverHub Integration**: ✅ Implemented
348
- Automatically detects and integrates with NeverHub if available.
348
+ Registers with NeverHub on construction; works unchanged when NeverHub is unreachable.
349
349
 
350
350
  ## NeverHub Integration
351
351
 
352
- The service automatically detects and integrates with NeverHub if available:
352
+ The constructor registers the service with NeverHub (type `service`, the package's own name and version). Registration never throws. When NeverHub is unreachable it does nothing. A failed or rejected registration is logged as a `NeverHub registration failed` warning, and migrations keep running.
353
353
 
354
354
  ```typescript
355
- // Events emitted:
356
- // - migration.completed: When migration succeeds
357
- // - migration.failed: When migration fails
355
+ // Events emitted in the background once registration settles; runMigration() never waits on NeverHub (no-ops when unavailable):
356
+ // - migration.completed: { migrationId, name, duration, dryRun }
357
+ // - migration.failed: { migrationId, name, error, duration }
358
358
 
359
359
  const service = new ContentfulMigrationService(config);
360
- // NeverHub automatically initialized if available
361
360
  ```
362
361
 
363
362
  ## Best Practices
@@ -430,19 +429,32 @@ Break large changes into smaller, atomic migrations:
430
429
 
431
430
  ## Error Handling
432
431
 
433
- The service handles errors gracefully and tracks them in storage:
432
+ Errors use `ContentfulMigrationServiceError` (exported from the package root). Each one carries a `code`, optional `context`, and the original error as `cause` (ES2022 `Error.cause`).
433
+
434
+ | Code | When |
435
+ |------|------|
436
+ | `INVALID_INPUT` | `InMemoryMigrationStorage.updateMigrationStatus()` is called with an unknown migration id (`context.migrationId`) |
437
+ | `OPERATION_FAILED` | `validateMigration()` hit a storage failure. The wrapper is logged with the cause chain; `errors` holds the original storage error's message |
438
+ | `CONTENTFUL_MIGRATION_SERVICE_ERROR` | Default code |
439
+
440
+ - `runMigration()` does not throw when a migration fails. It records `status: 'failed'` with the error message in storage, logs the error, publishes `migration.failed`, and returns `{ success: false, error }`.
441
+ - Storage errors from `hasMigration()` and the initial `saveMigration()` reject `runMigration()` unchanged.
442
+ - Once the migration starts, a failing `updateMigrationStatus()` is handled like a migration failure. If recording the `failed` status also throws, that error rejects `runMigration()`.
443
+ - Errors are logged to the console with an `errorChain` metadata array (each entry carries `name`, `message`, `depth` and `code`), because the logger does not serialize `Error.cause`.
434
444
 
435
445
  ```typescript
446
+ import { ContentfulMigrationServiceError } from '@bernierllc/contentful-migration-service';
447
+
436
448
  try {
437
449
  const result = await service.runMigration(migrationFn, options);
438
-
439
450
  if (!result.success) {
440
- // Migration failed but error was caught
441
- console.error(result.error);
451
+ console.error('Migration failed:', result.error);
442
452
  }
443
453
  } catch (error) {
444
- // Unexpected error (storage failure, etc.)
445
- console.error('Unexpected error:', error);
454
+ if (error instanceof ContentfulMigrationServiceError) {
455
+ console.error(error.code, error.context, error.cause);
456
+ }
457
+ throw error;
446
458
  }
447
459
  ```
448
460
 
@@ -8,12 +8,20 @@ export declare class ContentfulMigrationService {
8
8
  private logger;
9
9
  private cmaClient;
10
10
  private config;
11
- private neverhub?;
11
+ private readonly neverhub;
12
+ /** Settles when NeverHub registration finishes; never rejects. */
13
+ private readonly registration;
12
14
  constructor(config: MigrationServiceConfig);
13
15
  /**
14
- * Initialize NeverHub integration if available
16
+ * Register with NeverHub. register() no-ops when NeverHub is unreachable,
17
+ * so no detect() guard is needed.
15
18
  */
16
- private initializeNeverHub;
19
+ private registerWithNeverHub;
20
+ /**
21
+ * Publish once registration has settled, without blocking the caller: registration can retry
22
+ * for tens of seconds, and NeverHub is optional. publishEvent() no-ops when NeverHub is unavailable.
23
+ */
24
+ private publish;
17
25
  /**
18
26
  * Run a migration function
19
27
  */
@@ -12,6 +12,9 @@ const contentful_migration_1 = require("contentful-migration");
12
12
  const contentful_cma_client_1 = require("@bernierllc/contentful-cma-client");
13
13
  const logger_1 = require("@bernierllc/logger");
14
14
  const neverhub_adapter_1 = require("@bernierllc/neverhub-adapter");
15
+ const errors_1 = require("./errors");
16
+ // Read at runtime: Lerna bumps package.json, so a literal version drifts.
17
+ const pkg = require('../package.json');
15
18
  /**
16
19
  * ContentfulMigrationService manages content model migrations with version control,
17
20
  * rollback support, and migration history tracking.
@@ -20,7 +23,9 @@ class ContentfulMigrationService {
20
23
  logger;
21
24
  cmaClient;
22
25
  config;
23
- neverhub;
26
+ neverhub = new neverhub_adapter_1.NeverHubAdapter();
27
+ /** Settles when NeverHub registration finishes; never rejects. */
28
+ registration;
24
29
  constructor(config) {
25
30
  this.config = {
26
31
  ...config,
@@ -28,10 +33,10 @@ class ContentfulMigrationService {
28
33
  };
29
34
  this.logger = new logger_1.Logger({
30
35
  level: 2, // INFO level
31
- transports: [],
36
+ transports: [new logger_1.ConsoleTransport()],
32
37
  context: {
33
38
  service: 'ContentfulMigrationService',
34
- version: '1.0.0',
39
+ version: pkg.version,
35
40
  environment: process.env.NODE_ENV || 'development',
36
41
  },
37
42
  });
@@ -40,38 +45,53 @@ class ContentfulMigrationService {
40
45
  spaceId: config.spaceId,
41
46
  environmentId: this.config.environmentId,
42
47
  });
43
- this.initializeNeverHub();
48
+ this.registration = this.registerWithNeverHub();
44
49
  }
45
50
  /**
46
- * Initialize NeverHub integration if available
51
+ * Register with NeverHub. register() no-ops when NeverHub is unreachable,
52
+ * so no detect() guard is needed.
47
53
  */
48
- async initializeNeverHub() {
54
+ async registerWithNeverHub() {
49
55
  try {
50
- if (await neverhub_adapter_1.NeverHubAdapter.detect()) {
51
- this.neverhub = new neverhub_adapter_1.NeverHubAdapter();
52
- await this.neverhub.register({
53
- type: 'contentful-migration-service',
54
- name: '@bernierllc/contentful-migration-service',
55
- version: '1.0.0',
56
- dependencies: [
57
- '@bernierllc/contentful-cma-client',
58
- '@bernierllc/contentful-types',
59
- ],
60
- capabilities: [
61
- {
62
- type: 'migration',
63
- name: 'contentful-migrations',
64
- version: '1.0.0',
65
- },
66
- ],
67
- });
68
- this.logger.info('NeverHub integration initialized');
56
+ await this.neverhub.register({
57
+ type: 'service',
58
+ name: pkg.name,
59
+ version: pkg.version,
60
+ dependencies: Object.keys(pkg.dependencies ?? {}),
61
+ capabilities: [
62
+ {
63
+ type: 'migration',
64
+ name: 'contentful-migrations',
65
+ version: pkg.version,
66
+ },
67
+ ],
68
+ });
69
+ // register() resolves on timeouts and non-2xx responses, so check the outcome.
70
+ if (this.neverhub.isAvailable() && !this.neverhub.isRegistered()) {
71
+ this.logger.warn('NeverHub registration failed', { error: 'registration not accepted' });
69
72
  }
70
73
  }
71
74
  catch (error) {
72
- this.logger.warn('NeverHub integration not available', { error });
75
+ // NeverHub is optional: migrations keep running without it.
76
+ this.logger.warn('NeverHub registration failed', {
77
+ error: error instanceof Error ? error.message : String(error),
78
+ });
73
79
  }
74
80
  }
81
+ /**
82
+ * Publish once registration has settled, without blocking the caller: registration can retry
83
+ * for tens of seconds, and NeverHub is optional. publishEvent() no-ops when NeverHub is unavailable.
84
+ */
85
+ publish(event) {
86
+ this.registration
87
+ .then(() => this.neverhub.publishEvent(event))
88
+ .catch((error) => {
89
+ this.logger.warn('NeverHub event publish failed', {
90
+ event: event.type,
91
+ error: error instanceof Error ? error.message : String(error),
92
+ });
93
+ });
94
+ }
75
95
  /**
76
96
  * Run a migration function
77
97
  */
@@ -117,17 +137,15 @@ class ContentfulMigrationService {
117
137
  // Update status
118
138
  await this.config.storage.updateMigrationStatus(id, 'completed', undefined, duration);
119
139
  this.logger.info(`Migration completed: ${name}`, { id, duration, dryRun });
120
- if (this.neverhub) {
121
- await this.neverhub.publishEvent({
122
- type: 'migration.completed',
123
- data: {
124
- migrationId: id,
125
- name,
126
- duration,
127
- dryRun,
128
- },
129
- });
130
- }
140
+ this.publish({
141
+ type: 'migration.completed',
142
+ data: {
143
+ migrationId: id,
144
+ name,
145
+ duration,
146
+ dryRun,
147
+ },
148
+ });
131
149
  return {
132
150
  success: true,
133
151
  migrationId: id,
@@ -140,18 +158,19 @@ class ContentfulMigrationService {
140
158
  const errorMessage = error instanceof Error ? error.message : String(error);
141
159
  const errorObj = error instanceof Error ? error : new Error(String(error));
142
160
  await this.config.storage.updateMigrationStatus(id, 'failed', errorMessage, duration);
143
- this.logger.error(`Migration failed: ${name}`, errorObj, { migrationId: id });
144
- if (this.neverhub) {
145
- await this.neverhub.publishEvent({
146
- type: 'migration.failed',
147
- data: {
148
- migrationId: id,
149
- name,
150
- error: errorMessage,
151
- duration,
152
- },
153
- });
154
- }
161
+ this.logger.error(`Migration failed: ${name}`, errorObj, {
162
+ migrationId: id,
163
+ errorChain: (0, logger_1.getErrorChainEntries)(errorObj),
164
+ });
165
+ this.publish({
166
+ type: 'migration.failed',
167
+ data: {
168
+ migrationId: id,
169
+ name,
170
+ error: errorMessage,
171
+ duration,
172
+ },
173
+ });
155
174
  return {
156
175
  success: false,
157
176
  migrationId: id,
@@ -205,6 +224,17 @@ class ContentfulMigrationService {
205
224
  };
206
225
  }
207
226
  catch (error) {
227
+ // runMigration() reports migration failures in its result; a throw here is a storage failure.
228
+ const failure = new errors_1.ContentfulMigrationServiceError('Migration validation failed', {
229
+ code: 'OPERATION_FAILED',
230
+ cause: error instanceof Error ? error : new Error(String(error)),
231
+ context: { migrationId: options.id },
232
+ });
233
+ // The logger drops Error.cause, so pass the chain explicitly.
234
+ this.logger.error(failure.message, failure, {
235
+ migrationId: options.id,
236
+ errorChain: (0, logger_1.getErrorChainEntries)(failure),
237
+ });
208
238
  const errorMessage = error instanceof Error ? error.message : String(error);
209
239
  return {
210
240
  valid: false,
@@ -8,6 +8,7 @@ Redistribution or use in other products or commercial offerings is not permitted
8
8
  */
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
10
  exports.InMemoryMigrationStorage = void 0;
11
+ const errors_1 = require("../errors");
11
12
  /**
12
13
  * In-memory implementation of MigrationStorage for testing and development
13
14
  */
@@ -34,7 +35,10 @@ class InMemoryMigrationStorage {
34
35
  async updateMigrationStatus(id, status, error, duration) {
35
36
  const migration = this.migrations.get(id);
36
37
  if (!migration) {
37
- throw new Error(`Migration ${id} not found`);
38
+ throw new errors_1.ContentfulMigrationServiceError(`Migration ${id} not found`, {
39
+ code: 'INVALID_INPUT',
40
+ context: { migrationId: id },
41
+ });
38
42
  }
39
43
  migration.status = status;
40
44
  if (error !== undefined) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bernierllc/contentful-migration-service",
3
- "version": "1.6.2",
3
+ "version": "1.6.5",
4
4
  "description": "Content model migration management with version control, rollback support, and migration history tracking",
5
5
  "keywords": [
6
6
  "contentful",
@@ -21,9 +21,9 @@
21
21
  ],
22
22
  "dependencies": {
23
23
  "contentful-migration": "^4.0.0",
24
- "@bernierllc/contentful-cma-client": "^1.3.1",
24
+ "@bernierllc/contentful-cma-client": "^1.3.3",
25
25
  "@bernierllc/contentful-types": "^1.5.0",
26
- "@bernierllc/logger": "^1.7.1",
26
+ "@bernierllc/logger": "^2.0.1",
27
27
  "@bernierllc/neverhub-adapter": "^0.4.1"
28
28
  },
29
29
  "devDependencies": {
@@ -1,5 +0,0 @@
1
- export declare class NeverHubAdapter {
2
- static detect(): Promise<boolean>;
3
- register(): Promise<void>;
4
- publishEvent(): Promise<void>;
5
- }
@@ -1,15 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.NeverHubAdapter = void 0;
4
- class NeverHubAdapter {
5
- static async detect() {
6
- return false;
7
- }
8
- async register() {
9
- return;
10
- }
11
- async publishEvent() {
12
- return;
13
- }
14
- }
15
- exports.NeverHubAdapter = NeverHubAdapter;