@tryghost/mg-context 0.1.27 → 0.3.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.
package/README.md CHANGED
@@ -1,272 +1,690 @@
1
1
  # Migrate Context
2
2
 
3
- This package makes it easier to create post objects that can be used in the Ghost migration tools. It aims to provide a consistent, typed interface for posts, pages, tags, and authors. It also validates input data to ensure that the resulting object is valid for importing into Ghost.
3
+ A SQLite-backed data store for building Ghost import files. Provides a validated, typed interface for posts, tags, and authors with batched iteration for large migrations.
4
4
 
5
- It can also be used for custom migrations, and can output a JSON file that can be imported in Ghost.
6
-
7
- This package exports a few different classes: `MigrateContext`, `PostContext`, `TagContext`, and `AuthorContext`.
8
- Most of the time, you'll want the `MigrateContext` class, which is the top-level class that manages all the other classes.
5
+ Data is persisted to SQLite (in-memory by default), so migrations with tens of thousands of posts don't require excessive memory. Content is validated against Ghost's schema on write, and HTML is converted to Lexical or Mobiledoc during an explicit preparation step before export.
9
6
 
10
7
  ## Install
11
8
 
12
- `npm install @tryghost/mg-context --save`
9
+ ```bash
10
+ npm install @tryghost/mg-context --save
11
+ # or
12
+ yarn add @tryghost/mg-context
13
+ ```
13
14
 
14
- or
15
+ ## Quick start
15
16
 
16
- `yarn add @tryghost/mg-context`
17
+ ```js
18
+ import {MigrateContext} from '@tryghost/mg-context';
17
19
 
20
+ const context = new MigrateContext();
21
+ await context.init();
22
+
23
+ // Add a few posts
24
+ for (let i = 1; i <= 3; i++) {
25
+ const post = await context.addPost();
26
+ post.set('title', `Post ${i}`);
27
+ post.set('slug', `post-${i}`);
28
+ post.set('status', 'published');
29
+ post.set('created_at', new Date(`2025-01-${10 + i}T10:00:00Z`));
30
+ post.set('html', '<p>Hello world</p>');
31
+ post.addTag({name: 'News', slug: 'news'});
32
+ post.addAuthor({name: 'Alice', slug: 'alice', email: 'alice@example.com'});
33
+ await post.save(context.db);
34
+ }
35
+
36
+ // Update every post — find-replace content and add a tag
37
+ await context.forEachPost(async (post) => {
38
+ const html = post.get('html');
39
+ post.set('html', html.replace('Hello world', 'Lorem ipsum'));
40
+ post.addTag({name: 'Updated', slug: 'updated'});
41
+ });
18
42
 
19
- # Usage
43
+ // Prepare for export (deduplicate slugs, convert HTML to Lexical)
44
+ await context.prepareForExport();
20
45
 
21
- Let's walk through adding a post to a context, and then outputting the final JSON that can be imported into Ghost.
46
+ await context.writeGhostJson('./output/');
47
+ await context.close();
48
+ ```
22
49
 
23
- ### Create a context
50
+ See the [examples/](examples/) directory for complete runnable scripts, including bulk generation and iteration patterns.
51
+
52
+ ## Architecture
24
53
 
25
- ```js
26
- import {MigrateContext} from '@tryghost/mg-context';
27
- const context = new MigrateContext();
28
54
  ```
55
+ MigrateContext
56
+ └─ PostContext
57
+ ├─ TagContext
58
+ └─ AuthorContext
59
+ ```
60
+
61
+ `MigrateContext` manages the database and provides methods for adding, finding, iterating, and exporting posts. Each post holds references to its tags and authors. All data is stored in SQLite with JSON columns for flexible schema storage and indexed columns for fast lookups.
62
+
63
+ ---
64
+
65
+ # API Reference
66
+
67
+ ## MigrateContext
68
+
69
+ The top-level class that manages the database and all entity operations.
29
70
 
30
- You can optionally set the content format to `lexical` or `mobiledoc` on the context. By default, only `html` is exported. All posts added to the context will use this format.
71
+ ### Constructor
31
72
 
32
73
  ```js
33
- const context = new MigrateContext({contentFormat: 'lexical'});
74
+ new MigrateContext(options?)
34
75
  ```
35
76
 
36
- ### Create a post
77
+ | Option | Type | Default | Description |
78
+ |----------------------------|--------------------------------------|---------------------|----------------------------------------------|
79
+ | `contentFormat` | `'lexical' \| 'mobiledoc' \| 'html'` | `'lexical'` | Target format for HTML conversion on export |
80
+ | `dbPath` | `string` | — | Path to a SQLite file for persistent storage |
81
+ | `ephemeral` | `boolean` | `true` if no dbPath | Use in-memory database |
82
+ | `emitEvents` | `boolean` | `true` | Emit progress events (see [Events](#events)) |
83
+ | `warnOnLookupKeyDuplicate` | `boolean` | `false` | Log when a duplicate lookupKey is skipped |
37
84
 
38
85
  ```js
39
- const post = context.addPost();
40
- post.set('title', 'My Post');
41
- post.set('slug', 'my-post');
42
- post.set('status', 'published');
43
- post.set('published_at', new Date('2023-12-08T13:34:22.000Z'));
44
- post.set('created_at', new Date('2023-12-08T13:23:03.000Z'));
45
- post.set('updated_at', new Date('2023-12-08T13:36:42.000Z'));
46
- post.set('html', '<p>My post content</p>');
86
+ // In-memory (default)
87
+ const ctx = new MigrateContext();
88
+
89
+ // Persistent file-based
90
+ const ctx = new MigrateContext({dbPath: './migration.sqlite'});
91
+
92
+ // Mobiledoc output instead of Lexical
93
+ const ctx = new MigrateContext({contentFormat: 'mobiledoc'});
94
+
95
+ // Server mode — disable events for zero overhead
96
+ const ctx = new MigrateContext({emitEvents: false});
47
97
  ```
48
98
 
49
- When you call `post.set('html', '<p>...</p>')`, the content is automatically converted based on the `contentFormat`:
99
+ ### Lifecycle
100
+
101
+ #### `init(): Promise<void>`
102
+
103
+ Initialize the database. Must be called before any other operations. Throws if called twice without `close()` in between.
50
104
 
51
- - **`html`** (default): Only `html` is populated in the export. `mobiledoc` and `lexical` will be `null`.
52
- - **`lexical`**: Both `html` and `lexical` are populated. The HTML is automatically converted to Lexical format. `mobiledoc` will be `null`.
53
- - **`mobiledoc`**: Both `html` and `mobiledoc` are populated. The HTML is automatically converted to Mobiledoc format. `lexical` will be `null`.
105
+ #### `close(): Promise<void>`
54
106
 
55
- ### Add a tag
107
+ Close the database connection. Always call this when done, ideally in a `finally` block.
56
108
 
57
109
  ```js
58
- post.addTag({
59
- name: 'My Tag',
60
- slug: 'my-tag'
61
- });
110
+ const ctx = new MigrateContext();
111
+ await ctx.init();
112
+ try {
113
+ // ... work
114
+ } finally {
115
+ await ctx.close();
116
+ }
62
117
  ```
63
118
 
64
- ### Add an author
119
+ #### `db: DatabaseModels`
120
+
121
+ Access the underlying database models. Needed for `post.save(ctx.db)`.
122
+
123
+ ### Adding posts
124
+
125
+ #### `addPost(options?): Promise<PostContext>`
126
+
127
+ Create a new post. Returns an unsaved `PostContext` — call `post.save(ctx.db)` to persist.
65
128
 
66
129
  ```js
67
- post.addAuthor({
68
- name: 'Author Name',
69
- slug: 'author-name',
70
- email: 'name@example.com'
71
- });
130
+ // Empty post
131
+ const post = await ctx.addPost();
132
+
133
+ // With a lookup key for deduplication
134
+ const post = await ctx.addPost({lookupKey: 'https://example.com/original-url'});
135
+
136
+ // With source metadata (preserved but not exported)
137
+ const post = await ctx.addPost({source: {originalId: 123}});
72
138
  ```
73
139
 
74
- ## Adding posts from another source
140
+ When called with a `PostContext` instance, saves it immediately instead.
75
141
 
76
- If you have post data in another format, get it in to some sort of array or object that can be iterated over. Then, for each row, create a new post and set the data with the same methods as above.
142
+ #### `addPost(postContext): Promise<PostContext>`
77
143
 
78
144
  ```js
79
- const arrayOfPostData = [...];
145
+ const post = new PostContext({contentFormat: 'html'});
146
+ post.set('title', 'Pre-built');
147
+ post.set('slug', 'pre-built');
148
+ post.set('created_at', new Date());
149
+ await ctx.addPost(post); // saves immediately
150
+ ```
151
+
152
+ ### Transactions
153
+
154
+ #### `transaction(callback): Promise<T>`
80
155
 
81
- arrayOfPostData.forEach((row) => {
82
- const post = context.addPost();
83
- // post.set('title', row.title);
84
- // ...
156
+ Wrap operations in a database transaction. Significantly improves write performance for bulk inserts.
157
+
158
+ ```js
159
+ await ctx.transaction(async () => {
160
+ for (const row of data) {
161
+ const post = await ctx.addPost();
162
+ post.set('title', row.title);
163
+ // ...
164
+ await post.save(ctx.db);
165
+ }
85
166
  });
86
167
  ```
87
168
 
169
+ ### Finding entities
170
+
171
+ #### `findPosts(options): Promise<PostContext[] | null>`
88
172
 
89
- ### Get a Ghost JSON string
173
+ Find posts by various criteria. Only one criterion is used at a time (first match wins).
174
+
175
+ | Option | Type | Description |
176
+ |---------------|----------------|--------------------------------------------------|
177
+ | `slug` | `string` | Match post slug |
178
+ | `title` | `string` | Match post title |
179
+ | `sourceAttr` | `{key, value}` | Match a key/value pair in the post's source data |
180
+ | `tagSlug` | `string` | Find posts with this tag slug |
181
+ | `tagName` | `string` | Find posts with this tag name |
182
+ | `authorSlug` | `string` | Find posts by this author slug |
183
+ | `authorName` | `string` | Find posts by this author name |
184
+ | `authorEmail` | `string` | Find posts by this author email |
90
185
 
91
186
  ```js
92
- const json = context.ghostJson;
93
- // `json` is a JSON string. Save it to a `.json` file and import it into Ghost
187
+ const posts = await ctx.findPosts({tagSlug: 'news'});
188
+ const posts = await ctx.findPosts({authorEmail: 'alice@example.com'});
189
+ const posts = await ctx.findPosts({sourceAttr: {key: 'url', value: 'https://example.com/post'}});
94
190
  ```
95
191
 
192
+ #### `findTags(options): Promise<TagContext[] | null>`
193
+
194
+ Find tags by `slug` or `name`.
96
195
 
196
+ #### `findAuthors(options): Promise<AuthorContext[] | null>`
97
197
 
198
+ Find authors by `slug`, `name`, or `email`.
98
199
 
200
+ #### `getAllPosts(): Promise<PostContext[]>`
99
201
 
100
- # Classes & Methods
202
+ Load all posts. Use `forEachPost` for large datasets to avoid loading everything into memory.
101
203
 
102
- There's 4 main classes: `MigrateContext`, `PostContext`, `TagContext`, and `AuthorContext`. Most of the time, `MigrateContext` is what you'll use, but more advanced usage may require the usage of the other classes.
204
+ ### Iterating posts
103
205
 
206
+ #### `forEachPost(callback, options?): Promise<void>`
104
207
 
105
- ### `MigrateContext`
208
+ Iterate all posts in batches. Each post is automatically saved after the callback.
106
209
 
107
- This is the main class that manages all the other classes. It has methods for adding posts, tags, and authors, and also has methods for finding posts, tags, and authors.
210
+ ```js
211
+ await ctx.forEachPost(async (post) => {
212
+ post.set('status', 'published');
213
+ // post is saved automatically after callback
214
+ }, {batchSize: 200});
215
+ ```
216
+
217
+ #### `forEachGhostPost(callback, options?): Promise<void>`
218
+
219
+ Iterate posts as processed Ghost JSON with tags and authors inlined. Read-only — mutations are not saved.
220
+
221
+ ```js
222
+ await ctx.forEachGhostPost(async (json, post) => {
223
+ // json: { id, title, slug, tags: [...], authors: [...], ... }
224
+ await ghostApi.posts.add(json);
225
+ }, {batchSize: 50});
226
+ ```
108
227
 
109
- - `context.addPost(post`
110
- - `context.findPosts({slug, title, sourceAttr, tagSlug, tagName, authorSlug, authorName, authorEmail})`
111
- - `context.findTags({slug, name})`
112
- - `context.findAuthors({slug, name, email})`
113
- - `await context.forEachPost(callback)`
114
- - `context.forEachPostSync(callback)`
115
- - `context.allPosts`
116
- - `context.ghostJson`
228
+ #### Iteration options
117
229
 
118
- ### `PostContext`
230
+ | Option | Type | Default | Description |
231
+ |-------------|--------------|---------|-----------------------------------------------|
232
+ | `batchSize` | `number` | `100` | Posts loaded per batch |
233
+ | `filter` | `PostFilter` | — | Filter criteria (see [Filtering](#filtering)) |
119
234
 
120
- This class is only for posts and related data. You can also set tags and authors.
235
+ Progress is reported via the `progress` event (see [Events](#events)).
121
236
 
122
- - `post.get(prop)`
123
- - `post.set(prop)`
124
- - `post.remove(prop)`
125
- - `post.setMeta(value)`
126
- - `post.getMetaValue(key)`
127
- - `post.getSourceValue(key)`
128
- - `post.hasTagSlug(tagSlug)`
129
- - `post.hasTagName(tagName)`
130
- - `post.addTag(value)`
131
- - `post.removeTag(tagSlug)`
132
- - `post.setTagOrder(callback)`
133
- - `post.setPrimaryTag(value)`
134
- - `post.hasAuthorSlug(authorSlug)`
135
- - `post.hasAuthorName(authorName)`
136
- - `post.hasAuthorEmail(authorEmail)`
137
- - `post.addAuthor(value)`
138
- - `post.removeAuthor(authorSlug)`
139
- - `post.setAuthorOrder(callback)`
140
- - `post.setPrimaryAuthor(value)`
141
- - `post.meta`
142
- - `post.source`
237
+ ### Exporting
143
238
 
144
- ### `TagContext`
239
+ #### `prepareForExport(options?): Promise<void>`
145
240
 
146
- This class is used to create and manage individual tags.
241
+ Prepare all posts for export. Must be called before `writeGhostJson()` or `forEachGhostPost()`. This:
147
242
 
148
- - `tag.set(prop)`
149
- - `tag.remove(prop)`
150
- - `tag.get(prop)`
151
- - `tag.meta`
243
+ 1. Deduplicates slugs (calls `deduplicateSlugs()` internally)
244
+ 2. Converts HTML to Lexical or Mobiledoc for all posts that need it
152
245
 
153
- ### `AuthorContext`
246
+ The method is idempotent — posts that already have converted content are skipped. Call it again after modifying posts via `forEachPost()` to re-convert changed content.
154
247
 
155
- This class is used to create and manage individual authors.
248
+ | Option | Type | Default | Description |
249
+ |-------------|----------|---------|---------------------------|
250
+ | `batchSize` | `number` | `200` | Posts processed per batch |
156
251
 
157
- - `author.set(prop)`
158
- - `author.remove(prop)`
159
- - `author.get(prop)`
160
- - `author.meta`
252
+ ```js
253
+ await ctx.prepareForExport();
254
+ ```
161
255
 
162
- # Tips & tricks
256
+ #### `writeGhostJson(outputDir, options?): Promise<WrittenFile[]>`
163
257
 
164
- Knowing the methods is not that useful in itself. Here's some tips and tricks that are the heart of this package.
258
+ Write posts, tags, authors, and junction tables to Ghost JSON files.
165
259
 
166
- ## Finding Posts
260
+ | Option | Type | Default | Description |
261
+ |-------------|-------------------------------|-----------|-------------------------------------|
262
+ | `batchSize` | `number` | `5000` | Posts per output file |
263
+ | `filename` | `string` | `'posts'` | Base filename (without `.json`) |
264
+ | `filter` | `PostFilter` | — | Filter criteria |
265
+ | `onWrite` | `(file: WrittenFile) => void` | — | Callback after each file is written |
167
266
 
168
- If you need to find posts that have a specific tag or author, use the `findPosts` method. You can supply an object with any of the following keys:
267
+ Returns an array of `WrittenFile` objects:
169
268
 
170
- - `tagSlug`
171
- - `tagName`
172
- - `authorSlug`
173
- - `authorName`
174
- - `authorEmail`
269
+ | Field | Type | Description |
270
+ |---------|----------|--------------------------------|
271
+ | `path` | `string` | Absolute path to the file |
272
+ | `name` | `string` | Filename (e.g. `posts-1.json`) |
273
+ | `size` | `number` | File size in bytes |
274
+ | `posts` | `number` | Number of posts in this file |
175
275
 
176
276
  ```js
177
- const context = new MigrateContext();
277
+ const files = await ctx.writeGhostJson('./output/', {
278
+ filename: 'export',
279
+ batchSize: 2000,
280
+ onWrite(f) {
281
+ console.log(`Wrote ${f.name} (${f.posts} posts)`);
282
+ }
283
+ });
284
+ ```
178
285
 
179
- const posts = context.findPosts({tagSlug: 'my-tag'});
180
- const posts = context.findPosts({tagName: 'My Tag'});
286
+ #### `writeGhostTagsJson(outputDir, options?): Promise<WrittenFile>`
181
287
 
182
- const posts = context.findPosts({authorSlug: 'author-name'});
183
- const posts = context.findPosts({authorName: 'Author Name'});
184
- const posts = context.findPosts({authorEmail: 'author@example.com'});
288
+ Export tags as a standalone JSON file. Only tags referenced by at least one post are included.
185
289
 
186
- const posts = context.findPosts({slug: 'my-post'});
187
- const posts = context.findPosts({title: 'My Post'});
188
- const posts = context.findPosts({sourceAttr: {
189
- key: 'url',
190
- value: 'https://example.com/blog/2023/11/26/original-slug/'
191
- }});
290
+ #### `writeGhostUsersJson(outputDir, options?): Promise<WrittenFile>`
291
+
292
+ Export authors/users as a standalone JSON file. Only authors referenced by at least one post are included.
293
+
294
+ ```js
295
+ await ctx.writeGhostTagsJson('./output/', {filename: 'my-tags'});
296
+ await ctx.writeGhostUsersJson('./output/', {filename: 'my-users'});
192
297
  ```
193
298
 
194
- ### Updating found posts
299
+ ### Filtering
195
300
 
196
- Add a new tag to all posts with a specific tag
301
+ All iteration and export methods accept a `filter` option. Criteria combine with AND logic.
197
302
 
198
303
  ```js
199
- const posts = context.findPosts({tagSlug: 'my-tag'});
304
+ await ctx.forEachPost(async (post) => { /* ... */ }, {
305
+ filter: {
306
+ tag: {slug: 'news'},
307
+ createdAt: {onOrAfter: new Date('2025-01-01')}
308
+ }
309
+ });
310
+ ```
200
311
 
201
- posts.forEach((post) => {
202
- post.addTag({
203
- name: 'My New Tag',
204
- slug: 'my-new-tag'
205
- });
312
+ | Filter | Type | Description |
313
+ |-------------------------------------------------------------|----------|----------------------------|
314
+ | `tag.slug` | `string` | Posts with this tag slug |
315
+ | `tag.name` | `string` | Posts with this tag name |
316
+ | `author.slug` | `string` | Posts by this author slug |
317
+ | `author.name` | `string` | Posts by this author name |
318
+ | `author.email` | `string` | Posts by this author email |
319
+ | `createdAt.before` / `after` / `onOrBefore` / `onOrAfter` | `Date` | Filter by `created_at` |
320
+ | `publishedAt.before` / `after` / `onOrBefore` / `onOrAfter` | `Date` | Filter by `published_at` |
321
+
322
+ Posts with `null` `published_at` (drafts) are excluded by a `publishedAt` filter.
323
+
324
+ ### Events
325
+
326
+ MigrateContext emits events via `on`/`off`, powered by `node:events`. This lets you set up a single listener for progress across all operations instead of passing callbacks to each method.
327
+
328
+ #### `on(event, listener): this`
329
+
330
+ Register an event listener. Returns `this` for chaining.
331
+
332
+ #### `off(event, listener): this`
333
+
334
+ Remove an event listener.
335
+
336
+ #### `progress` event
337
+
338
+ Emitted after each batch during `prepareForExport()`, `forEachPost()`, and `forEachGhostPost()`.
339
+
340
+ ```js
341
+ ctx.on('progress', (event, processed, total) => {
342
+ console.log(`[${event}] ${processed}/${total}`);
206
343
  });
207
344
  ```
208
345
 
209
- ## Updating found authors
346
+ | Argument | Type | Description |
347
+ |-------------|----------|--------------------------------------------------------------|
348
+ | `event` | `string` | Operation name: `prepareForExport`, `forEachPost`, or `forEachGhostPost` |
349
+ | `processed` | `number` | Posts processed so far |
350
+ | `total` | `number` | Total posts to process |
351
+
352
+ Events can be disabled entirely at construction with `emitEvents: false` for server environments where the overhead is unwanted:
353
+
354
+ ```js
355
+ const ctx = new MigrateContext({emitEvents: false});
356
+ ```
357
+
358
+ ---
359
+
360
+ ## PostContext
361
+
362
+ Represents a single post with validated properties, tag/author relationships, and source metadata.
363
+
364
+ ### Properties
365
+
366
+ #### `post.get(prop): any`
367
+
368
+ Get a property value.
369
+
370
+ #### `post.set(prop, value): PostContext`
371
+
372
+ Set a property value. Validates against the schema (type, max length, allowed values). Returns `this` for chaining.
373
+
374
+ Setting `html` invalidates cached `lexical`/`mobiledoc` — call `prepareForExport()` again to re-convert.
375
+
376
+ #### `post.remove(prop): PostContext`
377
+
378
+ Reset a property to its default value (or `null`).
379
+
380
+ #### `post.save(db): void`
381
+
382
+ Persist the post and its tag/author relationships to the database.
383
+
384
+ ### Post fields
385
+
386
+ | Field | Type | Max | Default | Notes |
387
+ |-------------------------|-----------|-------|------------|-------------------------------------------|
388
+ | `title` | `string` | 255 | — | **Required** |
389
+ | `slug` | `string` | 191 | — | **Required** |
390
+ | `html` | `string?` | — | `null` | Source HTML content |
391
+ | `lexical` | `string?` | — | `null` | Auto-generated on export |
392
+ | `mobiledoc` | `string?` | — | `null` | Auto-generated on export |
393
+ | `status` | `enum` | — | `'draft'` | `published`, `draft`, `scheduled`, `sent` |
394
+ | `type` | `enum` | — | `'post'` | `post`, `page` |
395
+ | `visibility` | `enum` | — | `'public'` | `public`, `members`, `paid` |
396
+ | `featured` | `boolean` | — | `false` | |
397
+ | `created_at` | `Date` | — | — | **Required** |
398
+ | `updated_at` | `Date?` | — | `null` | |
399
+ | `published_at` | `Date?` | — | `null` | |
400
+ | `feature_image` | `string?` | 2000 | `null` | |
401
+ | `feature_image_alt` | `string?` | 125 | `null` | |
402
+ | `feature_image_caption` | `string?` | 65535 | `null` | |
403
+ | `custom_excerpt` | `string?` | 300 | `null` | |
404
+ | `canonical_url` | `string?` | 2000 | `null` | |
405
+ | `meta_title` | `string?` | 300 | `null` | |
406
+ | `meta_description` | `string?` | 500 | `null` | |
407
+ | `og_title` | `string?` | 300 | `null` | |
408
+ | `og_description` | `string?` | 500 | `null` | |
409
+ | `og_image` | `string?` | 2000 | `null` | |
410
+ | `twitter_title` | `string?` | 300 | `null` | |
411
+ | `twitter_description` | `string?` | 500 | `null` | |
412
+ | `twitter_image` | `string?` | 2000 | `null` | |
413
+ | `codeinjection_head` | `string?` | 65535 | `null` | |
414
+ | `codeinjection_foot` | `string?` | 65535 | `null` | |
415
+ | `custom_template` | `string?` | 100 | `null` | |
416
+ | `comment_id` | `string?` | 50 | `null` | |
417
+ | `plaintext` | `string?` | — | `null` | |
418
+
419
+ ### Tags
420
+
421
+ Tags have a `sort_order` that is tracked automatically. When tags are added, their position in the list becomes their sort order. The sort order is persisted to the database and included in the exported Ghost JSON as a 1-based integer (`sort_order: 1, 2, 3, ...`).
422
+
423
+ #### `post.addTag(tag, options?): TagContext | false`
210
424
 
211
- Change the email for found authors
425
+ Add a tag by object or `TagContext`. Returns `false` if the slug already exists on this post.
212
426
 
213
427
  ```js
214
- const authors = context.findAuthors({slug: 'author-name'});
428
+ post.addTag({name: 'News', slug: 'news'});
215
429
 
216
- authors.forEach((author) => {
217
- author.set('email', 'real-email@exmapl.com');
430
+ // Insert at a specific position (0-based index)
431
+ post.addTag({name: 'Breaking', slug: 'breaking', sortOrder: 0});
432
+ ```
433
+
434
+ | Option | Type | Required | Description |
435
+ |-------------|----------|----------|--------------------------------------------------|
436
+ | `name` | `string` | Yes | Tag name |
437
+ | `slug` | `string` | Yes | Tag slug |
438
+ | `sortOrder` | `number` | No | Position to insert at. Appends if out of bounds. |
439
+
440
+ #### `post.removeTag(slug): void`
441
+
442
+ Remove a tag by slug.
443
+
444
+ #### `post.hasTagSlug(slug): boolean` / `post.hasTagName(name): boolean`
445
+
446
+ Check if the post has a specific tag.
447
+
448
+ #### `post.setPrimaryTag({name, slug}): void`
449
+
450
+ Set a tag as primary (moves it to sort order 1). Adds the tag if it doesn't exist.
451
+
452
+ #### `post.setTagOrder(callback): void`
453
+
454
+ Reorder tags. The callback receives an array of `TagContext` instances and must return the same instances in the desired order. Access tag properties via `tag.data.slug`, `tag.data.name`, etc.
455
+
456
+ ```js
457
+ // Move internal tags to the end
458
+ post.setTagOrder((tags) => {
459
+ const regular = tags.filter(t => !t.data.slug.startsWith('hash-'));
460
+ const internal = tags.filter(t => t.data.slug.startsWith('hash-'));
461
+ return [...regular, ...internal];
218
462
  });
219
463
  ```
220
464
 
221
- ## Updating found tags
465
+ ### Authors
466
+
467
+ Authors follow the same ordering model as tags — `sort_order` is tracked automatically, persisted, and exported as a 1-based integer.
468
+
469
+ #### `post.addAuthor(author, options?): AuthorContext | false`
222
470
 
223
- Change the name of found tags
471
+ Add an author by object or `AuthorContext`. Returns `false` if the slug already exists on this post.
224
472
 
225
473
  ```js
226
- const tags = context.findTags({slug: 'my-tag'});
474
+ post.addAuthor({name: 'Alice', slug: 'alice', email: 'alice@example.com'});
227
475
 
228
- tags.forEach((tag) => {
229
- tag.set('name', 'My New Tag');
230
- });
476
+ // Insert at a specific position
477
+ post.addAuthor({name: 'Bob', slug: 'bob', email: 'bob@example.com', sortOrder: 0});
231
478
  ```
232
479
 
480
+ | Option | Type | Required | Description |
481
+ |-------------|----------|----------|--------------------------------------------------|
482
+ | `name` | `string` | Yes | Author name |
483
+ | `slug` | `string` | Yes | Author slug |
484
+ | `email` | `string` | Yes | Author email |
485
+ | `sortOrder` | `number` | No | Position to insert at. Appends if out of bounds. |
486
+
487
+ #### `post.removeAuthor(slug): void`
488
+
489
+ Remove an author by slug.
490
+
491
+ #### `post.hasAuthorSlug(slug): boolean` / `post.hasAuthorName(name): boolean` / `post.hasAuthorEmail(email): boolean`
492
+
493
+ Check if the post has a specific author.
494
+
495
+ #### `post.setPrimaryAuthor({name, slug, email}): void`
496
+
497
+ Set an author as primary (moves them to sort order 1). Adds the author if they don't exist.
498
+
499
+ #### `post.setAuthorOrder(callback): void`
233
500
 
234
- ### Class Flow
501
+ Reorder authors. The callback receives an array of `AuthorContext` instances and must return the same instances in the desired order. Access author properties via `author.data.slug`, `author.data.name`, etc.
235
502
 
503
+ ```js
504
+ // Reverse the author order
505
+ post.setAuthorOrder((authors) => [...authors].reverse());
236
506
  ```
237
- ┌────────────────┐
238
- │ MigrateContext │
239
- └───┬────────────┘
240
- ┌▼─────────────────────────────┐
241
- │ PostContext │
242
- └┬─────────────────────────────┘
243
- └─────┬───────────────┐
244
- ┌──────▼─────┐ ┌───────▼───────┐
245
- │ TagContext │ │ AuthorContext │
246
- └────────────┘ └───────────────┘
507
+
508
+ ### Source & metadata
509
+
510
+ #### `post.source`
511
+
512
+ Access the source data object (set at construction). Not exported to Ghost JSON — use this to store original platform data for reference during migration.
513
+
514
+ #### `post.getSourceValue(key): any`
515
+
516
+ Get a single value from the source data.
517
+
518
+ #### `post.meta`
519
+
520
+ Access the metadata object.
521
+
522
+ #### `post.setMeta(value): void`
523
+
524
+ Replace the metadata object.
525
+
526
+ #### `post.getMetaValue(key): any`
527
+
528
+ Get a single metadata value.
529
+
530
+ ### Deduplication
531
+
532
+ #### `post.lookupKey: string | null`
533
+
534
+ Get or set the lookup key. When a post with a matching lookup key already exists in the database, `save()` silently skips the insert.
535
+
536
+ ```js
537
+ const post = await ctx.addPost({lookupKey: 'https://example.com/post-url'});
538
+ // ... set fields ...
539
+ await post.save(ctx.db);
540
+
541
+ // Second save with same key is a no-op
542
+ const dupe = await ctx.addPost({lookupKey: 'https://example.com/post-url'});
543
+ await dupe.save(ctx.db); // skipped
247
544
  ```
248
545
 
546
+ ### Slug deduplication
249
547
 
250
- ## Develop
548
+ #### `deduplicateSlugs(): Promise<DuplicateSlugEntry[]>`
251
549
 
252
- This is a mono repository, managed with [lerna](https://lernajs.io/).
550
+ Ghost requires unique slugs. When a migration source contains multiple posts with the same slug, this method renames newer duplicates by appending `-2`, `-3`, etc., while the oldest post keeps the original slug.
253
551
 
254
- Follow the instructions for the top-level repo.
255
- 1. `git clone` this repo & `cd` into it as usual
256
- 2. Run `yarn` to install top-level dependencies.
552
+ Called automatically by `prepareForExport()`, so you typically don't need to call it directly. It only runs once — subsequent calls reuse the cached result.
257
553
 
554
+ After preparing, access the results via the `duplicateSlugs` getter to log renamed slugs for redirect handling:
258
555
 
259
- ## Run
556
+ ```js
557
+ await ctx.prepareForExport();
558
+
559
+ for (const entry of ctx.duplicateSlugs) {
560
+ const label = entry.oldSlug === entry.newSlug ? 'kept' : 'renamed';
561
+ console.log(`[${label}] ${entry.newSlug} ${entry.url}`);
562
+ }
563
+ ```
564
+
565
+ #### `duplicateSlugs: DuplicateSlugEntry[]`
566
+
567
+ Getter that returns the results of the most recent deduplication. Results are grouped by original slug. The first entry in each group is the retained post (`oldSlug === newSlug`), followed by the renamed ones.
568
+
569
+ | Field | Type | Description |
570
+ |-----------|----------|-------------------------------------------------------------------|
571
+ | `oldSlug` | `string` | The original (duplicate) slug |
572
+ | `newSlug` | `string` | The final slug — same as `oldSlug` for the retained post |
573
+ | `url` | `string` | Original URL from `source.url` or `canonical_url` (empty if none) |
574
+
575
+ Ordering is determined by `published_at` (falling back to `created_at`), so the earliest post keeps the original slug. If a suffix like `-2` already belongs to a real post, it skips to `-3`, etc.
576
+
577
+ See [examples/deduplicate-slugs.ts](examples/deduplicate-slugs.ts) for a complete example.
578
+
579
+ ---
580
+
581
+ ## TagContext
582
+
583
+ Represents a tag with validated properties.
260
584
 
261
- - `yarn dev`
585
+ ### Constructor
262
586
 
587
+ ```js
588
+ new TagContext({name: 'News', slug: 'news'})
589
+ // or
590
+ new TagContext({initialData: {name: 'News', slug: 'news'}})
591
+ ```
592
+
593
+ ### Methods
594
+
595
+ - `tag.get(prop): any`
596
+ - `tag.set(prop, value): TagContext`
597
+ - `tag.remove(prop): TagContext`
598
+ - `tag.save(db): void`
599
+
600
+ ### Tag fields
601
+
602
+ | Field | Type | Max | Notes |
603
+ |-----------------------|-----------|-------|--------------|
604
+ | `name` | `string` | 255 | **Required** |
605
+ | `slug` | `string` | 191 | **Required** |
606
+ | `description` | `string?` | 500 | |
607
+ | `feature_image` | `string?` | 2000 | |
608
+ | `og_image` | `string?` | 2000 | |
609
+ | `og_title` | `string?` | 300 | |
610
+ | `og_description` | `string?` | 500 | |
611
+ | `twitter_image` | `string?` | 2000 | |
612
+ | `twitter_title` | `string?` | 300 | |
613
+ | `twitter_description` | `string?` | 500 | |
614
+ | `meta_title` | `string?` | 300 | |
615
+ | `meta_description` | `string?` | 500 | |
616
+ | `codeinjection_head` | `string?` | 65535 | |
617
+ | `codeinjection_foot` | `string?` | 65535 | |
618
+ | `canonical_url` | `string?` | 2000 | |
619
+
620
+ ---
621
+
622
+ ## AuthorContext
623
+
624
+ Represents an author with validated properties.
625
+
626
+ ### Constructor
627
+
628
+ ```js
629
+ new AuthorContext({name: 'Alice', slug: 'alice', email: 'alice@example.com'})
630
+ ```
631
+
632
+ ### Methods
633
+
634
+ - `author.get(prop): any`
635
+ - `author.set(prop, value): AuthorContext`
636
+ - `author.remove(prop): AuthorContext`
637
+ - `author.save(db): void`
638
+
639
+ ### Author fields
640
+
641
+ | Field | Type | Max | Notes |
642
+ |--------------------|-----------|------|--------------------------------------------------------------|
643
+ | `name` | `string` | 191 | **Required** |
644
+ | `slug` | `string` | 191 | **Required** |
645
+ | `email` | `string` | 191 | **Required**, validated |
646
+ | `profile_image` | `string?` | 2000 | |
647
+ | `cover_image` | `string?` | 2000 | |
648
+ | `bio` | `string?` | 250 | |
649
+ | `website` | `string?` | 2000 | |
650
+ | `location` | `string?` | 150 | |
651
+ | `facebook` | `string?` | 2000 | |
652
+ | `twitter` | `string?` | 2000 | |
653
+ | `meta_title` | `string?` | 300 | |
654
+ | `meta_description` | `string?` | 500 | |
655
+ | `role` | `enum` | — | `Contributor` (default), `Author`, `Editor`, `Administrator` |
656
+
657
+ ---
658
+
659
+ ## Examples
660
+
661
+ The [examples/](examples/) directory contains runnable scripts demonstrating common patterns:
662
+
663
+ - **generate-and-export.ts** — Create 500 posts in-memory and export to Ghost JSON
664
+ - **reorder-tags-authors.ts** — Reorder tags and authors using `setTagOrder`, `setPrimaryTag`, and `addTag` with `sortOrder`
665
+ - **generate-large-export.ts** — Stress-test with 500k posts, benchmarking memory and performance
666
+ - **foreach-ghost-post.ts** — Iterate an existing database and log each post as Ghost JSON
667
+ - **deduplicate-slugs.ts** — Detect and rename duplicate slugs, then log the changes for manual redirect handling
668
+
669
+ Run any example from the package directory:
670
+
671
+ ```bash
672
+ npx tsx examples/generate-and-export.ts
673
+ ```
674
+
675
+ ## Develop
676
+
677
+ This is a mono repository, managed with [Nx](https://nx.dev/) and yarn workspaces.
678
+
679
+ Follow the instructions for the top-level repo.
680
+ 1. `git clone` this repo & `cd` into it as usual
681
+ 2. Run `yarn` to install top-level dependencies.
263
682
 
264
683
  ## Test
265
684
 
266
685
  - `yarn lint` run just eslint
267
686
  - `yarn test` run lint and tests
268
687
 
269
-
270
688
  # Copyright & License
271
689
 
272
690
  Copyright (c) 2013-2026 Ghost Foundation - Released under the [MIT license](LICENSE).