@tryghost/mg-context 0.11.8 → 0.11.10-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 +73 -832
- package/build/index.d.ts +10 -4
- package/build/index.js +5 -2
- package/build/index.js.map +1 -1
- package/build/lib/AuthorContext.d.ts +3 -3
- package/build/lib/AuthorContext.js +32 -34
- package/build/lib/AuthorContext.js.map +1 -1
- package/build/lib/MigrateBase.js +2 -2
- package/build/lib/MigrateBase.js.map +1 -1
- package/build/lib/MigrateContext.d.ts +139 -36
- package/build/lib/MigrateContext.js +606 -324
- package/build/lib/MigrateContext.js.map +1 -1
- package/build/lib/PostContext.d.ts +72 -16
- package/build/lib/PostContext.js +191 -123
- package/build/lib/PostContext.js.map +1 -1
- package/build/lib/SourceRecords.d.ts +80 -0
- package/build/lib/SourceRecords.js +385 -0
- package/build/lib/SourceRecords.js.map +1 -0
- package/build/lib/TagContext.d.ts +1 -1
- package/build/lib/TagContext.js +35 -37
- package/build/lib/TagContext.js.map +1 -1
- package/build/lib/database.d.ts +47 -11
- package/build/lib/database.js +189 -24
- package/build/lib/database.js.map +1 -1
- package/build/lib/db-helpers.d.ts +1 -5
- package/build/lib/db-helpers.js +7 -37
- package/build/lib/db-helpers.js.map +1 -1
- package/build/lib/export-filename.d.ts +1 -0
- package/build/lib/export-filename.js +11 -0
- package/build/lib/export-filename.js.map +1 -0
- package/build/lib/ghost-csv.d.ts +10 -0
- package/build/lib/ghost-csv.js +55 -0
- package/build/lib/ghost-csv.js.map +1 -0
- package/build/lib/ghost-json.d.ts +4 -0
- package/build/lib/ghost-json.js +108 -0
- package/build/lib/ghost-json.js.map +1 -0
- package/build/lib/ghost-schema.d.ts +58 -0
- package/build/lib/ghost-schema.js +61 -0
- package/build/lib/ghost-schema.js.map +1 -0
- package/build/lib/json.d.ts +8 -0
- package/build/lib/json.js +40 -0
- package/build/lib/json.js.map +1 -0
- package/build/lib/migration-report.d.ts +3 -0
- package/build/lib/migration-report.js +41 -0
- package/build/lib/migration-report.js.map +1 -0
- package/build/lib/source-schema.d.ts +1 -0
- package/build/lib/source-schema.js +44 -0
- package/build/lib/source-schema.js.map +1 -0
- package/build/test/fixtures/mg-context-v2.d.ts +5 -0
- package/build/test/fixtures/mg-context-v2.js +58 -0
- package/build/test/fixtures/mg-context-v2.js.map +1 -0
- package/build/test/ghost-csv.test.d.ts +1 -0
- package/build/test/ghost-csv.test.js +333 -0
- package/build/test/ghost-csv.test.js.map +1 -0
- package/build/test/ghost-schema.test.d.ts +1 -0
- package/build/test/ghost-schema.test.js +38 -0
- package/build/test/ghost-schema.test.js.map +1 -0
- package/build/test/migrate-base.test.js +0 -6
- package/build/test/migrate-base.test.js.map +1 -1
- package/build/test/migrate-context.test.js +1094 -250
- package/build/test/migrate-context.test.js.map +1 -1
- package/build/test/package-exports.test.d.ts +1 -0
- package/build/test/package-exports.test.js +50 -0
- package/build/test/package-exports.test.js.map +1 -0
- package/build/test/post-context.test.js +36 -151
- package/build/test/post-context.test.js.map +1 -1
- package/build/test/source-records.test.d.ts +1 -0
- package/build/test/source-records.test.js +625 -0
- package/build/test/source-records.test.js.map +1 -0
- package/build/test/stream-export.test.d.ts +1 -0
- package/build/test/stream-export.test.js +401 -0
- package/build/test/stream-export.test.js.map +1 -0
- package/package.json +13 -10
package/README.md
CHANGED
|
@@ -1,875 +1,116 @@
|
|
|
1
1
|
# Migrate Context
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
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 during an explicit preparation step before export.
|
|
3
|
+
`@tryghost/mg-context` stores original source records and mapped Ghost content in SQLite. It supports bounded ingestion, rebuilding, processing, JSON/CSV export, and diagnostic reports.
|
|
6
4
|
|
|
7
5
|
## Install
|
|
8
6
|
|
|
9
7
|
```bash
|
|
10
|
-
npm install @tryghost/mg-context --save
|
|
11
|
-
# or
|
|
12
8
|
pnpm add @tryghost/mg-context
|
|
13
9
|
```
|
|
14
10
|
|
|
15
|
-
##
|
|
16
|
-
|
|
17
|
-
```js
|
|
18
|
-
import {MigrateContext} from '@tryghost/mg-context';
|
|
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
|
-
});
|
|
42
|
-
|
|
43
|
-
// Prepare for export (deduplicate slugs, convert HTML to Lexical)
|
|
44
|
-
await context.prepareForExport();
|
|
45
|
-
|
|
46
|
-
await context.writeGhostJson('./output/');
|
|
47
|
-
await context.close();
|
|
48
|
-
```
|
|
49
|
-
|
|
50
|
-
See the [examples/](examples/) directory for complete runnable scripts, including bulk generation and iteration patterns.
|
|
51
|
-
|
|
52
|
-
## Architecture
|
|
53
|
-
|
|
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.
|
|
11
|
+
## Storage model and terminology
|
|
62
12
|
|
|
63
|
-
|
|
13
|
+
Original input lives in one shared `SourceRecords` table, separate from mapped posts, tags, and authors. Input may include attachments, author definitions, or other records that do not map directly to a post. Keeping originals separate avoids duplicating them across mapped entities and allows mapping changes to rebuild Ghost content from the same input.
|
|
64
14
|
|
|
65
|
-
|
|
15
|
+
Each context holds one current logical source dataset. Callers choose record boundaries and decide when to ingest again; core tracks completion and safely replaces the stored data. Internal staging supports replacement, without exposing a public snapshot model or retaining historical source payloads.
|
|
66
16
|
|
|
67
|
-
|
|
17
|
+
| Term | Meaning |
|
|
18
|
+
| --- | --- |
|
|
19
|
+
| Source record | One caller-defined logical item of original input, before migration transformations. |
|
|
20
|
+
| Completed source data | The current collection of originals whose ingestion finished successfully, including an intentionally empty collection. |
|
|
21
|
+
| Ingestion attempt | One effort to collect initial or replacement input. A failed attempt preserves any previously completed data. |
|
|
22
|
+
| Mapped entity | A derived Ghost post, tag, or author, produced from source records or created directly by a caller. |
|
|
23
|
+
| Mapped lookup key | An optional caller-defined key for finding or reusing a mapped output, independent of its contributing source records' keys. |
|
|
68
24
|
|
|
69
|
-
|
|
25
|
+
## Ingest once, map on every run
|
|
70
26
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
```js
|
|
74
|
-
new MigrateContext(options?)
|
|
75
|
-
```
|
|
27
|
+
The caller decides when to ingest. Core does not hash files, compare revisions, inspect command options, or fetch input. Use `sources.hasCompletedIngestion`, including when a completed ingestion contains zero records; mapped post counts are not an ingestion marker.
|
|
76
28
|
|
|
77
|
-
|
|
78
|
-
|----------------------------|--------------------------------------|---------------------|----------------------------------------------|
|
|
79
|
-
| `contentFormat` | `'lexical' \| '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 |
|
|
29
|
+
This runnable example uses synthetic input. A real runner supplies records from an adapter's streaming parser. The adapter's mapper then interprets the records read from the database.
|
|
84
30
|
|
|
85
31
|
```js
|
|
86
|
-
|
|
87
|
-
const ctx = new MigrateContext();
|
|
88
|
-
|
|
89
|
-
// Persistent file-based
|
|
90
|
-
const ctx = new MigrateContext({dbPath: './migration.sqlite'});
|
|
91
|
-
|
|
92
|
-
// Server mode — disable events for zero overhead
|
|
93
|
-
const ctx = new MigrateContext({emitEvents: false});
|
|
94
|
-
```
|
|
95
|
-
|
|
96
|
-
### Lifecycle
|
|
97
|
-
|
|
98
|
-
#### `init(): Promise<void>`
|
|
99
|
-
|
|
100
|
-
Initialize the database. Must be called before any other operations. Throws if called twice without `close()` in between.
|
|
101
|
-
|
|
102
|
-
#### `close(): Promise<void>`
|
|
32
|
+
import {MigrateContext} from '@tryghost/mg-context';
|
|
103
33
|
|
|
104
|
-
|
|
34
|
+
const context = new MigrateContext({dbPath: './migration.sqlite'});
|
|
35
|
+
const rereadSource = process.argv.includes('--rereadSource');
|
|
36
|
+
await context.init();
|
|
105
37
|
|
|
106
|
-
```js
|
|
107
|
-
const ctx = new MigrateContext();
|
|
108
|
-
await ctx.init();
|
|
109
38
|
try {
|
|
110
|
-
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
#### `addPost(options?): Promise<PostContext>`
|
|
123
|
-
|
|
124
|
-
Create a new post. Returns an unsaved `PostContext` — call `post.save(ctx.db)` to persist.
|
|
125
|
-
|
|
126
|
-
```js
|
|
127
|
-
// Empty post
|
|
128
|
-
const post = await ctx.addPost();
|
|
129
|
-
|
|
130
|
-
// With a lookup key for deduplication
|
|
131
|
-
const post = await ctx.addPost({lookupKey: 'https://example.com/original-url'});
|
|
132
|
-
|
|
133
|
-
// With source metadata (preserved but not exported)
|
|
134
|
-
const post = await ctx.addPost({source: {originalId: 123}});
|
|
135
|
-
```
|
|
136
|
-
|
|
137
|
-
When called with a `PostContext` instance, saves it immediately instead.
|
|
138
|
-
|
|
139
|
-
#### `addPost(postContext): Promise<PostContext>`
|
|
140
|
-
|
|
141
|
-
```js
|
|
142
|
-
const post = new PostContext({contentFormat: 'html'});
|
|
143
|
-
post.set('title', 'Pre-built');
|
|
144
|
-
post.set('slug', 'pre-built');
|
|
145
|
-
post.set('created_at', new Date());
|
|
146
|
-
await ctx.addPost(post); // saves immediately
|
|
147
|
-
```
|
|
148
|
-
|
|
149
|
-
### Transactions
|
|
150
|
-
|
|
151
|
-
#### `transaction(callback): Promise<T>`
|
|
152
|
-
|
|
153
|
-
Wrap operations in a database transaction. Significantly improves write performance for bulk inserts.
|
|
154
|
-
|
|
155
|
-
```js
|
|
156
|
-
await ctx.transaction(async () => {
|
|
157
|
-
for (const row of data) {
|
|
158
|
-
const post = await ctx.addPost();
|
|
159
|
-
post.set('title', row.title);
|
|
160
|
-
// ...
|
|
161
|
-
await post.save(ctx.db);
|
|
162
|
-
}
|
|
163
|
-
});
|
|
164
|
-
```
|
|
165
|
-
|
|
166
|
-
### Links
|
|
167
|
-
|
|
168
|
-
MigrateContext stores URL mappings for link fixing — old URLs that should be rewritten to new relative Ghost paths. Links are stored in a dedicated `Links` table with an indexed lookup column.
|
|
169
|
-
|
|
170
|
-
#### `addLink(oldUrl, newUrl): void`
|
|
171
|
-
|
|
172
|
-
Store a URL mapping. Keys should be cleaned URLs (`host/path`, no protocol or query params) to match how LinkFixer normalizes hrefs. Duplicate `oldUrl` entries are silently ignored (first write wins).
|
|
173
|
-
|
|
174
|
-
```js
|
|
175
|
-
ctx.addLink('example.com/my-post/', '/my-post/');
|
|
176
|
-
ctx.addLink('example.com/tag/news/', '/tag/news/');
|
|
177
|
-
ctx.addLink('example.com/author/alice/', '/author/alice/');
|
|
178
|
-
```
|
|
179
|
-
|
|
180
|
-
For multi-domain support, store an entry for each domain:
|
|
181
|
-
|
|
182
|
-
```js
|
|
183
|
-
const hosts = ['example.com', 'olddomain.com'];
|
|
184
|
-
for (const host of hosts) {
|
|
185
|
-
ctx.addLink(`${host}/my-post/`, '/my-post/');
|
|
186
|
-
}
|
|
187
|
-
```
|
|
188
|
-
|
|
189
|
-
#### `findLink(oldUrl): string | null`
|
|
190
|
-
|
|
191
|
-
Look up a single URL mapping. Returns the new URL or `null` if no match. This is an indexed lookup — fast enough to call per-link within a single post's content.
|
|
192
|
-
|
|
193
|
-
```js
|
|
194
|
-
ctx.findLink('example.com/my-post/'); // '/my-post/'
|
|
195
|
-
ctx.findLink('example.com/unknown/'); // null
|
|
196
|
-
```
|
|
197
|
-
|
|
198
|
-
Designed to be used as a lookup function with [mg-linkfixer](../mg-linkfixer)'s `fixPost`:
|
|
199
|
-
|
|
200
|
-
```js
|
|
201
|
-
import LinkFixer from '@tryghost/mg-linkfixer';
|
|
202
|
-
|
|
203
|
-
const linkFixer = new LinkFixer();
|
|
204
|
-
const lookup = (url) => ctx.findLink(url);
|
|
205
|
-
|
|
206
|
-
await ctx.forEachPost(async (post) => {
|
|
207
|
-
await linkFixer.fixPost(post, lookup);
|
|
208
|
-
});
|
|
209
|
-
```
|
|
210
|
-
|
|
211
|
-
### Finding entities
|
|
212
|
-
|
|
213
|
-
#### `findPosts(options): Promise<PostContext[] | null>`
|
|
214
|
-
|
|
215
|
-
Find posts by various criteria. Only one criterion is used at a time (first match wins).
|
|
216
|
-
|
|
217
|
-
| Option | Type | Description |
|
|
218
|
-
|---------------|----------------|--------------------------------------------------|
|
|
219
|
-
| `slug` | `string` | Match post slug |
|
|
220
|
-
| `title` | `string` | Match post title |
|
|
221
|
-
| `sourceAttr` | `{key, value}` | Match a key/value pair in the post's source data |
|
|
222
|
-
| `tagSlug` | `string` | Find posts with this tag slug |
|
|
223
|
-
| `tagName` | `string` | Find posts with this tag name |
|
|
224
|
-
| `authorSlug` | `string` | Find posts by this author slug |
|
|
225
|
-
| `authorName` | `string` | Find posts by this author name |
|
|
226
|
-
| `authorEmail` | `string` | Find posts by this author email |
|
|
227
|
-
|
|
228
|
-
```js
|
|
229
|
-
const posts = await ctx.findPosts({tagSlug: 'news'});
|
|
230
|
-
const posts = await ctx.findPosts({authorEmail: 'alice@example.com'});
|
|
231
|
-
const posts = await ctx.findPosts({sourceAttr: {key: 'url', value: 'https://example.com/post'}});
|
|
232
|
-
```
|
|
233
|
-
|
|
234
|
-
#### `findTags(options): Promise<TagContext[] | null>`
|
|
235
|
-
|
|
236
|
-
Find tags by `slug` or `name`.
|
|
237
|
-
|
|
238
|
-
#### `findAuthors(options): Promise<AuthorContext[] | null>`
|
|
239
|
-
|
|
240
|
-
Find authors by `slug`, `name`, or `email`.
|
|
241
|
-
|
|
242
|
-
#### `getAllPosts(): Promise<PostContext[]>`
|
|
243
|
-
|
|
244
|
-
Load all posts. Use `forEachPost` for large datasets to avoid loading everything into memory.
|
|
245
|
-
|
|
246
|
-
### Iterating
|
|
247
|
-
|
|
248
|
-
#### `forEachPost(callback, options?): Promise<void>`
|
|
249
|
-
|
|
250
|
-
Iterate all posts in batches. Each post is automatically saved after the callback.
|
|
251
|
-
|
|
252
|
-
```js
|
|
253
|
-
await ctx.forEachPost(async (post) => {
|
|
254
|
-
post.set('status', 'published');
|
|
255
|
-
// post is saved automatically after callback
|
|
256
|
-
}, {batchSize: 200});
|
|
257
|
-
```
|
|
258
|
-
|
|
259
|
-
#### `forEachTag(callback, options?): Promise<void>`
|
|
260
|
-
|
|
261
|
-
Iterate all tags that are referenced by at least one post, in batches. Each tag is automatically saved after the callback.
|
|
262
|
-
|
|
263
|
-
```js
|
|
264
|
-
await ctx.forEachTag(async (tag) => {
|
|
265
|
-
tag.set('description', `Articles about ${tag.data.name}`);
|
|
266
|
-
});
|
|
267
|
-
```
|
|
268
|
-
|
|
269
|
-
| Option | Type | Default | Description |
|
|
270
|
-
|-------------|----------|---------|------------------------|
|
|
271
|
-
| `batchSize` | `number` | `100` | Tags loaded per batch |
|
|
272
|
-
|
|
273
|
-
#### `forEachAuthor(callback, options?): Promise<void>`
|
|
274
|
-
|
|
275
|
-
Iterate all authors that are referenced by at least one post, in batches. Each author is automatically saved after the callback.
|
|
276
|
-
|
|
277
|
-
```js
|
|
278
|
-
await ctx.forEachAuthor(async (author) => {
|
|
279
|
-
author.set('bio', 'Updated bio');
|
|
280
|
-
});
|
|
281
|
-
```
|
|
282
|
-
|
|
283
|
-
| Option | Type | Default | Description |
|
|
284
|
-
|-------------|----------|---------|--------------------------|
|
|
285
|
-
| `batchSize` | `number` | `100` | Authors loaded per batch |
|
|
286
|
-
|
|
287
|
-
#### `forEachGhostPost(callback, options?): Promise<void>`
|
|
288
|
-
|
|
289
|
-
Iterate posts as processed Ghost JSON with tags and authors inlined. Read-only — mutations are not saved.
|
|
290
|
-
|
|
291
|
-
```js
|
|
292
|
-
await ctx.forEachGhostPost(async (json, post) => {
|
|
293
|
-
// json: { id, title, slug, tags: [...], authors: [...], ... }
|
|
294
|
-
await ghostApi.posts.add(json);
|
|
295
|
-
}, {batchSize: 50});
|
|
296
|
-
```
|
|
297
|
-
|
|
298
|
-
#### `streamPosts(options?): AsyncGenerator<PostContext>`
|
|
299
|
-
|
|
300
|
-
Async generator that yields posts one at a time. Unlike `forEachPost`, posts are not auto-saved — you control when to persist changes. Ideal for feeding posts into a concurrent task queue.
|
|
301
|
-
|
|
302
|
-
```js
|
|
303
|
-
for await (const post of ctx.streamPosts({batchSize: 200})) {
|
|
304
|
-
const html = post.get('html');
|
|
305
|
-
post.set('html', html.toUpperCase());
|
|
306
|
-
post.save(ctx.db);
|
|
307
|
-
}
|
|
308
|
-
```
|
|
309
|
-
|
|
310
|
-
Or with a task queue:
|
|
311
|
-
|
|
312
|
-
```js
|
|
313
|
-
async function* postTasks() {
|
|
314
|
-
for await (const post of ctx.streamPosts()) {
|
|
315
|
-
yield {
|
|
316
|
-
title: post.get('slug'),
|
|
317
|
-
task: async () => {
|
|
318
|
-
// process post concurrently
|
|
319
|
-
post.set('html', transform(post.get('html')));
|
|
320
|
-
post.save(ctx.db);
|
|
321
|
-
}
|
|
322
|
-
};
|
|
39
|
+
if (!context.sources.hasCompletedIngestion || rereadSource) {
|
|
40
|
+
await context.sources.ingest({replace: rereadSource}, async (stage) => {
|
|
41
|
+
await stage.write([
|
|
42
|
+
{
|
|
43
|
+
kind: 'post',
|
|
44
|
+
key: 'original-1',
|
|
45
|
+
format: 'json',
|
|
46
|
+
content: JSON.stringify({title: 'Hello', slug: 'hello', html: '<p>Original HTML</p>'}),
|
|
47
|
+
metadata: {file: 'example.json'}
|
|
48
|
+
}
|
|
49
|
+
]);
|
|
50
|
+
});
|
|
323
51
|
}
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
await queue.run(postTasks());
|
|
327
|
-
```
|
|
328
|
-
|
|
329
|
-
#### `streamTags(options?): AsyncGenerator<TagContext>`
|
|
330
|
-
|
|
331
|
-
Async generator that yields tags referenced by at least one post. Tags are not auto-saved.
|
|
332
|
-
|
|
333
|
-
```js
|
|
334
|
-
for await (const tag of ctx.streamTags()) {
|
|
335
|
-
console.log(tag.data.slug, tag.data.name);
|
|
336
|
-
}
|
|
337
|
-
```
|
|
338
|
-
|
|
339
|
-
#### `streamAuthors(options?): AsyncGenerator<AuthorContext>`
|
|
340
|
-
|
|
341
|
-
Async generator that yields authors referenced by at least one post. Authors are not auto-saved.
|
|
342
|
-
|
|
343
|
-
```js
|
|
344
|
-
for await (const author of ctx.streamAuthors()) {
|
|
345
|
-
console.log(author.data.slug, author.data.name);
|
|
346
|
-
}
|
|
347
|
-
```
|
|
348
|
-
|
|
349
|
-
#### Iteration options
|
|
350
52
|
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
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.
|
|
368
|
-
|
|
369
|
-
| Option | Type | Default | Description |
|
|
370
|
-
|-------------|----------|---------|---------------------------|
|
|
371
|
-
| `batchSize` | `number` | `200` | Posts processed per batch |
|
|
372
|
-
|
|
373
|
-
```js
|
|
374
|
-
await ctx.prepareForExport();
|
|
375
|
-
```
|
|
376
|
-
|
|
377
|
-
#### `writeGhostJson(outputDir, options?): Promise<WrittenFile[]>`
|
|
378
|
-
|
|
379
|
-
Write posts, tags, authors, and junction tables to Ghost JSON files.
|
|
380
|
-
|
|
381
|
-
| Option | Type | Default | Description |
|
|
382
|
-
|-------------|-------------------------------|-----------|-------------------------------------|
|
|
383
|
-
| `batchSize` | `number` | `5000` | Posts per output file |
|
|
384
|
-
| `filename` | `string` | `'posts'` | Base filename (without `.json`) |
|
|
385
|
-
| `filter` | `PostFilter` | — | Filter criteria |
|
|
386
|
-
| `onWrite` | `(file: WrittenFile) => void` | — | Callback after each file is written |
|
|
387
|
-
|
|
388
|
-
Returns an array of `WrittenFile` objects:
|
|
389
|
-
|
|
390
|
-
| Field | Type | Description |
|
|
391
|
-
|---------|----------|--------------------------------|
|
|
392
|
-
| `path` | `string` | Absolute path to the file |
|
|
393
|
-
| `name` | `string` | Filename (e.g. `posts-1.json`) |
|
|
394
|
-
| `size` | `number` | File size in bytes |
|
|
395
|
-
| `posts` | `number` | Number of posts in this file |
|
|
396
|
-
|
|
397
|
-
```js
|
|
398
|
-
const files = await ctx.writeGhostJson('./output/', {
|
|
399
|
-
filename: 'export',
|
|
400
|
-
batchSize: 2000,
|
|
401
|
-
onWrite(f) {
|
|
402
|
-
console.log(`Wrote ${f.name} (${f.posts} posts)`);
|
|
53
|
+
await context.rebuildMappedContent(async () => {
|
|
54
|
+
for await (const record of context.sources.records({kind: 'post'})) {
|
|
55
|
+
const original = JSON.parse(record.content);
|
|
56
|
+
const post = await context.addPost({lookupKey: record.key ?? undefined});
|
|
57
|
+
post.set('title', original.title);
|
|
58
|
+
post.set('slug', original.slug);
|
|
59
|
+
post.set('html', original.html);
|
|
60
|
+
post.set('created_at', new Date('2026-01-01T00:00:00Z'));
|
|
61
|
+
post.save(context.db);
|
|
62
|
+
context.sources.link(record.id, {type: 'post', id: post.dbId});
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
for await (const file of context.writeGhostJsonStream('./output')) {
|
|
67
|
+
console.log(file.path);
|
|
403
68
|
}
|
|
404
|
-
});
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
#### `writeGhostTagsJson(outputDir, options?): Promise<WrittenFile>`
|
|
408
|
-
|
|
409
|
-
Export tags as a standalone JSON file. Only tags referenced by at least one post are included.
|
|
410
|
-
|
|
411
|
-
#### `writeGhostUsersJson(outputDir, options?): Promise<WrittenFile>`
|
|
412
|
-
|
|
413
|
-
Export authors/users as a standalone JSON file. Only authors referenced by at least one post are included.
|
|
414
|
-
|
|
415
|
-
```js
|
|
416
|
-
await ctx.writeGhostTagsJson('./output/', {filename: 'my-tags'});
|
|
417
|
-
await ctx.writeGhostUsersJson('./output/', {filename: 'my-users'});
|
|
418
|
-
```
|
|
419
|
-
|
|
420
|
-
### Filtering
|
|
421
|
-
|
|
422
|
-
All iteration and export methods accept a `filter` option. Criteria combine with AND logic.
|
|
423
|
-
|
|
424
|
-
```js
|
|
425
|
-
await ctx.forEachPost(async (post) => { /* ... */ }, {
|
|
426
|
-
filter: {
|
|
427
|
-
tag: {slug: 'news'},
|
|
428
|
-
createdAt: {onOrAfter: new Date('2025-01-01')}
|
|
429
|
-
}
|
|
430
|
-
});
|
|
431
|
-
```
|
|
432
|
-
|
|
433
|
-
| Filter | Type | Description |
|
|
434
|
-
|-------------------------------------------------------------|----------|----------------------------|
|
|
435
|
-
| `tag.slug` | `string` | Posts with this tag slug |
|
|
436
|
-
| `tag.name` | `string` | Posts with this tag name |
|
|
437
|
-
| `author.slug` | `string` | Posts by this author slug |
|
|
438
|
-
| `author.name` | `string` | Posts by this author name |
|
|
439
|
-
| `author.email` | `string` | Posts by this author email |
|
|
440
|
-
| `createdAt.before` / `after` / `onOrBefore` / `onOrAfter` | `Date` | Filter by `created_at` |
|
|
441
|
-
| `publishedAt.before` / `after` / `onOrBefore` / `onOrAfter` | `Date` | Filter by `published_at` |
|
|
442
|
-
|
|
443
|
-
Posts with `null` `published_at` (drafts) are excluded by a `publishedAt` filter.
|
|
444
|
-
|
|
445
|
-
### Events
|
|
446
|
-
|
|
447
|
-
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.
|
|
448
|
-
|
|
449
|
-
#### `on(event, listener): this`
|
|
450
|
-
|
|
451
|
-
Register an event listener. Returns `this` for chaining.
|
|
452
|
-
|
|
453
|
-
#### `off(event, listener): this`
|
|
454
|
-
|
|
455
|
-
Remove an event listener.
|
|
456
|
-
|
|
457
|
-
#### `progress` event
|
|
458
|
-
|
|
459
|
-
Emitted after each batch during `prepareForExport()`, `forEachPost()`, `forEachGhostPost()`, `streamPosts()`, `streamTags()`, and `streamAuthors()`.
|
|
460
|
-
|
|
461
|
-
```js
|
|
462
|
-
ctx.on('progress', (event, processed, total) => {
|
|
463
|
-
console.log(`[${event}] ${processed}/${total}`);
|
|
464
|
-
});
|
|
465
|
-
```
|
|
466
|
-
|
|
467
|
-
| Argument | Type | Description |
|
|
468
|
-
|-------------|----------|--------------------------------------------------------------|
|
|
469
|
-
| `event` | `string` | Operation name: `prepareForExport`, `forEachPost`, `forEachGhostPost`, `streamPosts`, `streamTags`, or `streamAuthors` |
|
|
470
|
-
| `processed` | `number` | Posts processed so far |
|
|
471
|
-
| `total` | `number` | Total posts to process |
|
|
472
|
-
|
|
473
|
-
Events can be disabled entirely at construction with `emitEvents: false` for server environments where the overhead is unwanted:
|
|
474
|
-
|
|
475
|
-
```js
|
|
476
|
-
const ctx = new MigrateContext({emitEvents: false});
|
|
477
|
-
```
|
|
478
|
-
|
|
479
|
-
---
|
|
480
|
-
|
|
481
|
-
## PostContext
|
|
482
|
-
|
|
483
|
-
Represents a single post with validated properties, tag/author relationships, and source metadata.
|
|
484
|
-
|
|
485
|
-
### Properties
|
|
486
|
-
|
|
487
|
-
#### `post.get(prop): any`
|
|
488
|
-
|
|
489
|
-
Get a property value.
|
|
490
|
-
|
|
491
|
-
#### `post.set(prop, value): PostContext`
|
|
492
|
-
|
|
493
|
-
Set a property value. Validates against the schema (type, max length, allowed values). Returns `this` for chaining.
|
|
494
|
-
|
|
495
|
-
Setting `html` invalidates cached `lexical` — call `prepareForExport()` again to re-convert.
|
|
496
|
-
|
|
497
|
-
#### `post.remove(prop): PostContext`
|
|
498
|
-
|
|
499
|
-
Reset a property to its default value (or `null`).
|
|
500
|
-
|
|
501
|
-
#### `post.save(db): void`
|
|
502
|
-
|
|
503
|
-
Persist the post and its tag/author relationships to the database.
|
|
504
|
-
|
|
505
|
-
### Post fields
|
|
506
|
-
|
|
507
|
-
| Field | Type | Max | Default | Notes |
|
|
508
|
-
|-------------------------|-----------|-------|------------|-------------------------------------------|
|
|
509
|
-
| `title` | `string` | 255 | — | **Required** |
|
|
510
|
-
| `slug` | `string` | 191 | — | **Required** |
|
|
511
|
-
| `html` | `string?` | — | `null` | Source HTML content |
|
|
512
|
-
| `lexical` | `string?` | — | `null` | Auto-generated on export |
|
|
513
|
-
| `mobiledoc` | `string?` | — | `null` | Legacy Ghost field, always exported null |
|
|
514
|
-
| `status` | `enum` | — | `'draft'` | `published`, `draft`, `scheduled`, `sent` |
|
|
515
|
-
| `type` | `enum` | — | `'post'` | `post`, `page` |
|
|
516
|
-
| `visibility` | `enum` | — | `'public'` | `public`, `members`, `paid` |
|
|
517
|
-
| `featured` | `boolean` | — | `false` | |
|
|
518
|
-
| `created_at` | `Date` | — | — | **Required** |
|
|
519
|
-
| `updated_at` | `Date?` | — | `null` | |
|
|
520
|
-
| `published_at` | `Date?` | — | `null` | |
|
|
521
|
-
| `feature_image` | `string?` | 2000 | `null` | |
|
|
522
|
-
| `feature_image_alt` | `string?` | 125 | `null` | |
|
|
523
|
-
| `feature_image_caption` | `string?` | 65535 | `null` | |
|
|
524
|
-
| `custom_excerpt` | `string?` | 300 | `null` | |
|
|
525
|
-
| `canonical_url` | `string?` | 2000 | `null` | |
|
|
526
|
-
| `meta_title` | `string?` | 300 | `null` | |
|
|
527
|
-
| `meta_description` | `string?` | 500 | `null` | |
|
|
528
|
-
| `og_title` | `string?` | 300 | `null` | |
|
|
529
|
-
| `og_description` | `string?` | 500 | `null` | |
|
|
530
|
-
| `og_image` | `string?` | 2000 | `null` | |
|
|
531
|
-
| `twitter_title` | `string?` | 300 | `null` | |
|
|
532
|
-
| `twitter_description` | `string?` | 500 | `null` | |
|
|
533
|
-
| `twitter_image` | `string?` | 2000 | `null` | |
|
|
534
|
-
| `codeinjection_head` | `string?` | 65535 | `null` | |
|
|
535
|
-
| `codeinjection_foot` | `string?` | 65535 | `null` | |
|
|
536
|
-
| `custom_template` | `string?` | 100 | `null` | |
|
|
537
|
-
| `comment_id` | `string?` | 50 | `null` | |
|
|
538
|
-
| `plaintext` | `string?` | — | `null` | |
|
|
539
|
-
|
|
540
|
-
### Tags
|
|
541
|
-
|
|
542
|
-
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, ...`).
|
|
543
|
-
|
|
544
|
-
#### `post.addTag(tag, options?): TagContext | false`
|
|
545
|
-
|
|
546
|
-
Add a tag by object or `TagContext`. Returns `false` if the slug already exists on this post.
|
|
547
|
-
|
|
548
|
-
```js
|
|
549
|
-
post.addTag({name: 'News', slug: 'news'});
|
|
550
|
-
|
|
551
|
-
// Insert at a specific position (0-based index)
|
|
552
|
-
post.addTag({name: 'Breaking', slug: 'breaking', sortOrder: 0});
|
|
553
|
-
```
|
|
554
|
-
|
|
555
|
-
| Option | Type | Required | Description |
|
|
556
|
-
|-------------|----------|----------|--------------------------------------------------|
|
|
557
|
-
| `name` | `string` | Yes | Tag name |
|
|
558
|
-
| `slug` | `string` | Yes | Tag slug |
|
|
559
|
-
| `sortOrder` | `number` | No | Position to insert at. Appends if out of bounds. |
|
|
560
|
-
|
|
561
|
-
#### `post.removeTag(slug): void`
|
|
562
|
-
|
|
563
|
-
Remove a tag by slug.
|
|
564
|
-
|
|
565
|
-
#### `post.hasTagSlug(slug): boolean` / `post.hasTagName(name): boolean`
|
|
566
|
-
|
|
567
|
-
Check if the post has a specific tag.
|
|
568
|
-
|
|
569
|
-
#### `post.setPrimaryTag({name, slug}): void`
|
|
570
|
-
|
|
571
|
-
Set a tag as primary (moves it to sort order 1). Adds the tag if it doesn't exist.
|
|
572
|
-
|
|
573
|
-
#### `post.setTagOrder(callback): void`
|
|
574
|
-
|
|
575
|
-
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.
|
|
576
|
-
|
|
577
|
-
```js
|
|
578
|
-
// Move internal tags to the end
|
|
579
|
-
post.setTagOrder((tags) => {
|
|
580
|
-
const regular = tags.filter(t => !t.data.slug.startsWith('hash-'));
|
|
581
|
-
const internal = tags.filter(t => t.data.slug.startsWith('hash-'));
|
|
582
|
-
return [...regular, ...internal];
|
|
583
|
-
});
|
|
584
|
-
```
|
|
585
|
-
|
|
586
|
-
### Authors
|
|
587
|
-
|
|
588
|
-
Authors follow the same ordering model as tags — `sort_order` is tracked automatically, persisted, and exported as a 1-based integer.
|
|
589
|
-
|
|
590
|
-
#### `post.addAuthor(author, options?): AuthorContext | false`
|
|
591
|
-
|
|
592
|
-
Add an author by object or `AuthorContext`. Returns `false` if the slug already exists on this post.
|
|
593
|
-
|
|
594
|
-
```js
|
|
595
|
-
post.addAuthor({name: 'Alice', slug: 'alice', email: 'alice@example.com'});
|
|
596
|
-
|
|
597
|
-
// Insert at a specific position
|
|
598
|
-
post.addAuthor({name: 'Bob', slug: 'bob', email: 'bob@example.com', sortOrder: 0});
|
|
599
|
-
```
|
|
600
|
-
|
|
601
|
-
| Option | Type | Required | Description |
|
|
602
|
-
|-------------|----------|----------|--------------------------------------------------|
|
|
603
|
-
| `name` | `string` | Yes | Author name |
|
|
604
|
-
| `slug` | `string` | Yes | Author slug |
|
|
605
|
-
| `email` | `string` | Yes | Author email |
|
|
606
|
-
| `sortOrder` | `number` | No | Position to insert at. Appends if out of bounds. |
|
|
607
|
-
|
|
608
|
-
#### `post.removeAuthor(slug): void`
|
|
609
|
-
|
|
610
|
-
Remove an author by slug.
|
|
611
|
-
|
|
612
|
-
#### `post.hasAuthorSlug(slug): boolean` / `post.hasAuthorName(name): boolean` / `post.hasAuthorEmail(email): boolean`
|
|
613
|
-
|
|
614
|
-
Check if the post has a specific author.
|
|
615
|
-
|
|
616
|
-
#### `post.setPrimaryAuthor({name, slug, email}): void`
|
|
617
|
-
|
|
618
|
-
Set an author as primary (moves them to sort order 1). Adds the author if they don't exist.
|
|
619
|
-
|
|
620
|
-
#### `post.setAuthorOrder(callback): void`
|
|
621
|
-
|
|
622
|
-
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.
|
|
623
|
-
|
|
624
|
-
```js
|
|
625
|
-
// Reverse the author order
|
|
626
|
-
post.setAuthorOrder((authors) => [...authors].reverse());
|
|
627
|
-
```
|
|
628
|
-
|
|
629
|
-
### Source & metadata
|
|
630
|
-
|
|
631
|
-
#### `post.source`
|
|
632
|
-
|
|
633
|
-
Access the source data object (set at construction). Not exported to Ghost JSON — use this to store original platform data for reference during migration.
|
|
634
|
-
|
|
635
|
-
#### `post.getSourceValue(key): any`
|
|
636
|
-
|
|
637
|
-
Get a single value from the source data.
|
|
638
|
-
|
|
639
|
-
#### `post.meta`
|
|
640
|
-
|
|
641
|
-
Access the metadata object.
|
|
642
|
-
|
|
643
|
-
#### `post.setMeta(value): void`
|
|
644
|
-
|
|
645
|
-
Replace the metadata object.
|
|
646
|
-
|
|
647
|
-
#### `post.getMetaValue(key): any`
|
|
648
|
-
|
|
649
|
-
Get a single metadata value.
|
|
650
|
-
|
|
651
|
-
### Web scrape data
|
|
652
|
-
|
|
653
|
-
#### `post.webscrapeData: any`
|
|
654
|
-
|
|
655
|
-
Get or set the raw web scrape response for this post. Stored as a JSON blob in a dedicated `webscrape_data` column on the Posts table. Defaults to `null`.
|
|
656
|
-
|
|
657
|
-
This is set automatically by [mg-webscraper](../mg-webscraper)'s `scrapePost` method, preserving the raw scraped response before any post-processing. Use it to access or reprocess scraped metadata in later pipeline steps without re-scraping.
|
|
658
|
-
|
|
659
|
-
```js
|
|
660
|
-
// Set during scraping (done automatically by scrapePost)
|
|
661
|
-
post.webscrapeData = {meta_title: 'Page Title', og_image: 'https://example.com/img.jpg'};
|
|
662
|
-
|
|
663
|
-
// Read later in the pipeline
|
|
664
|
-
const scraped = post.webscrapeData;
|
|
665
|
-
if (scraped?.og_image) {
|
|
666
|
-
post.set('feature_image', scraped.og_image);
|
|
667
|
-
}
|
|
668
|
-
```
|
|
669
|
-
|
|
670
|
-
### Deduplication
|
|
671
|
-
|
|
672
|
-
#### `post.lookupKey: string | null`
|
|
673
|
-
|
|
674
|
-
Get or set the lookup key. When a post with a matching lookup key already exists in the database, `save()` silently skips the insert.
|
|
675
|
-
|
|
676
|
-
```js
|
|
677
|
-
const post = await ctx.addPost({lookupKey: 'https://example.com/post-url'});
|
|
678
|
-
// ... set fields ...
|
|
679
|
-
await post.save(ctx.db);
|
|
680
|
-
|
|
681
|
-
// Second save with same key is a no-op
|
|
682
|
-
const dupe = await ctx.addPost({lookupKey: 'https://example.com/post-url'});
|
|
683
|
-
await dupe.save(ctx.db); // skipped
|
|
684
|
-
```
|
|
685
|
-
|
|
686
|
-
### Field sanitization
|
|
687
|
-
|
|
688
|
-
Source data routinely carries values Ghost will not accept — a title over 255 characters, a tag name over 191, an email that is not an address. Rather than failing the migration, each context normalizes its own data against [Ghost's schema](https://github.com/TryGhost/Ghost/blob/main/ghost/core/core/server/data/schema/schema.js) before anything is written.
|
|
689
|
-
|
|
690
|
-
Enforcement lives in one place per context: `save()` calls `sanitize()`, which applies every rule and records what changed. That covers values set with `set()` as well as values handed to a constructor or loaded from a row, which bypass `set()` entirely.
|
|
691
|
-
|
|
692
|
-
The rules:
|
|
693
|
-
|
|
694
|
-
| Applies to | Rule |
|
|
695
|
-
|------------|------|
|
|
696
|
-
| Every string field | Surrounding whitespace is stripped |
|
|
697
|
-
| Every string field | Values over the field's maximum are truncated; a slug left with a dangling `-` has it removed |
|
|
698
|
-
| URL fields | An over-long URL is dropped to `null` rather than truncated — a cut URL is a broken link, not a shorter one. Covers `feature_image`, `og_image`, `twitter_image` and `canonical_url` on posts and tags, and `website`, `profile_image` and `cover_image` on authors |
|
|
699
|
-
| Post slugs | A deduplicating suffix (`-2`, `-3`) trims the base rather than overflowing the 191 character limit |
|
|
700
|
-
| Tag `name` | A leading comma is stripped — Ghost validates names with `matches: /^([^,]\|$)/` |
|
|
701
|
-
| Author `email` | An address Ghost would reject is replaced with a derived placeholder at `example.com` (see below) |
|
|
702
|
-
| Author `website` | Anything that is not a URL is dropped to `null`, on top of the length rule above |
|
|
703
|
-
|
|
704
|
-
An invalid email cannot be trimmed into shape, so it is replaced with a recognisable stand-in: the address is slugified, minus the bogus tail after its last dot, and given the reserved `example.com` domain. `hello@world.com123` becomes `hello-world@example.com`. When there is nothing usable to slugify, it falls back to the author's slug, then their name, then `author`. The local part is capped at 50 characters, which is Ghost's limit.
|
|
705
|
-
|
|
706
|
-
#### `sanitizedFields: SanitizedField[]`
|
|
707
|
-
|
|
708
|
-
Getter listing every value changed during this run, so nothing is lost silently:
|
|
709
|
-
|
|
710
|
-
```js
|
|
711
|
-
for (const entry of ctx.sanitizedFields) {
|
|
712
|
-
console.log(`[${entry.reason}] ${entry.context} ${entry.slug} — ${entry.field}: ${entry.newValue}`);
|
|
713
|
-
}
|
|
714
|
-
```
|
|
715
|
-
|
|
716
|
-
| Field | Type | Description |
|
|
717
|
-
|------------|----------|-----------------------------------------------------------------------------------|
|
|
718
|
-
| `context` | `string` | `PostContext`, `TagContext` or `AuthorContext` |
|
|
719
|
-
| `slug` | `string` | Slug of the post, tag or author, for locating it afterwards |
|
|
720
|
-
| `field` | `string` | The field that changed |
|
|
721
|
-
| `reason` | `string` | `truncated`, `trimmed` or `replaced` |
|
|
722
|
-
| `oldValue` | `string` | The value before sanitization |
|
|
723
|
-
| `newValue` | `string \| null` | The value that was stored |
|
|
724
|
-
|
|
725
|
-
This is collected in memory as posts are saved, so it covers the current run only — resuming an existing `dbPath` starts empty, since the stored data was already sanitized when it was first written.
|
|
726
|
-
|
|
727
|
-
### Slug deduplication
|
|
728
|
-
|
|
729
|
-
#### `deduplicateSlugs(): Promise<DuplicateSlugEntry[]>`
|
|
730
|
-
|
|
731
|
-
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.
|
|
732
|
-
|
|
733
|
-
Called automatically by `prepareForExport()`, so you typically don't need to call it directly. It only runs once — subsequent calls reuse the cached result.
|
|
734
|
-
|
|
735
|
-
Renaming happens at insert time, and the slug a post originally wanted is stored alongside it. The results are rebuilt from the database, so resuming against an existing `dbPath` still reports every rename, including those made on an earlier run. A slug changed after its post was inserted is not a duplicate and is not reported.
|
|
736
|
-
|
|
737
|
-
After preparing, access the results via the `duplicateSlugs` getter to log renamed slugs for redirect handling:
|
|
738
|
-
|
|
739
|
-
```js
|
|
740
|
-
await ctx.prepareForExport();
|
|
741
|
-
|
|
742
|
-
for (const entry of ctx.duplicateSlugs) {
|
|
743
|
-
const label = entry.oldSlug === entry.newSlug ? 'kept' : 'renamed';
|
|
744
|
-
console.log(`[${label}] ${entry.newSlug} ${entry.url}`);
|
|
69
|
+
await context.writeMigrationReport('./report.json', {status: 'success'});
|
|
70
|
+
} finally {
|
|
71
|
+
await context.close();
|
|
745
72
|
}
|
|
746
73
|
```
|
|
747
74
|
|
|
748
|
-
|
|
75
|
+
On the first run, mapping reads the newly stored originals. Subsequent runs reuse those originals and rebuild all mapped entities and relationships. Mapping-option changes therefore do not require fresh ingestion. Stable Ghost IDs are the adapter's responsibility; internal source-record IDs are not stable external identities.
|
|
749
76
|
|
|
750
|
-
|
|
77
|
+
`replace: true` stages fresh input in committed batches while completed data remains readable. Successful ingestion atomically replaces the originals and clears mapped content. Failure preserves the previous originals and mapped content. Interrupted staging restarts from the beginning; failed-attempt diagnostics survive. Core exposes no snapshot or source-identity API.
|
|
751
78
|
|
|
752
|
-
|
|
753
|
-
|-----------|----------|-------------------------------------------------------------------|
|
|
754
|
-
| `oldSlug` | `string` | The original (duplicate) slug |
|
|
755
|
-
| `newSlug` | `string` | The final slug — same as `oldSlug` for the retained post |
|
|
756
|
-
| `url` | `string` | Original URL from `source.url` or `canonical_url` (empty if none) |
|
|
79
|
+
## Source records and provenance
|
|
757
80
|
|
|
758
|
-
|
|
81
|
+
A caller chooses each record's boundary: a post, an attachment, an author definition, a Markdown file, or another logical item. Content is opaque text with a caller-defined format label. Parsed XML/API records may be serialized as JSON; core does not require exact document bytes or validate the payload against its format.
|
|
759
82
|
|
|
760
|
-
|
|
83
|
+
Completed source content and ingestion metadata cannot be changed through the public API. Keyed records are unique by kind/key within an ingestion. Duplicate keys throw unless the caller explicitly selects `keep` or `replace`; timestamp interpretation belongs to adapters. Unkeyed records remain available for diagnostics.
|
|
761
84
|
|
|
762
|
-
|
|
85
|
+
One source record may contribute to several mapped entities, and each entity may have several source records. Use `sources.link()`, `recordsFor()`, and `entitiesFor()` to record and traverse these relationships. Core provides canonical lookups, not aliases. Direct construction of mapped entities without source records remains supported.
|
|
763
86
|
|
|
764
|
-
##
|
|
765
|
-
|
|
766
|
-
Represents a tag with validated properties.
|
|
767
|
-
|
|
768
|
-
### Constructor
|
|
769
|
-
|
|
770
|
-
```js
|
|
771
|
-
new TagContext({name: 'News', slug: 'news'})
|
|
772
|
-
// or
|
|
773
|
-
new TagContext({initialData: {name: 'News', slug: 'news'}})
|
|
774
|
-
```
|
|
87
|
+
## Processing and output
|
|
775
88
|
|
|
776
|
-
|
|
89
|
+
- The default context uses a temporary file-backed database, removed on `close()`. Use `dbPath` for persistence or `storage: 'memory'` for small jobs.
|
|
90
|
+
- `resetMappedContent()` preserves originals and ingestion diagnostics. `rebuildMappedContent()` performs an atomic reset and rebuild. `savepoint()` isolates a record's writes when the caller handles a known data error.
|
|
91
|
+
- `reset()` clears all managed database state. `resetContent: true` does the same during initialization; use staged replacement for a safe reread.
|
|
92
|
+
- Authors and tags reuse indexed database rows without application-level entity caches. Streaming APIs bound buffers; explicit array-returning APIs materialize their results.
|
|
93
|
+
- `writeGhostJson()` and `writeGhostJsonStream()` share one batched JSON exporter. The first collects completed file descriptors into an array; the second yields them with bounded file tracking. Both default to 5,000 posts per file and the base name `posts`. HTML remains HTML.
|
|
94
|
+
- `writeGhostCSV()` writes one Ghost post CSV; destination authors and tags must already exist. See the [CSV reference](docs/api-reference.md#writeghostcsvoutputdir-options-promisewrittenfile).
|
|
95
|
+
- `streamDiagnostics()` and `writeMigrationReport()` avoid collecting report history in memory. The latter writes exactly the path supplied by the caller.
|
|
96
|
+
- Consumers own output staging, publication, recovery, and cleanup. Export into a fresh staging directory and publish it only after the whole call or iteration succeeds. Core completes each file through a temporary write and rename, then yields its descriptor and emits its callback/event. A later failure leaves earlier completed files in place. There are no export manifests, backups, journals, or automatic recovery of previous runs.
|
|
777
97
|
|
|
778
|
-
|
|
779
|
-
- `tag.set(prop, value): TagContext`
|
|
780
|
-
- `tag.remove(prop): TagContext`
|
|
781
|
-
- `tag.save(db): void`
|
|
98
|
+
Scraping responses remain in `post.webscrapeData`; asset files and caches remain outside primary source storage. Source runners own scraping and delivery. Future scraper integrations must pass the original URL explicitly rather than requesting removed post-source fields.
|
|
782
99
|
|
|
783
|
-
|
|
100
|
+
## Breaking changes and rollout
|
|
784
101
|
|
|
785
|
-
|
|
786
|
-
|-----------------------|-----------|-------|--------------|
|
|
787
|
-
| `name` | `string` | 255 | **Required** |
|
|
788
|
-
| `slug` | `string` | 191 | **Required** |
|
|
789
|
-
| `description` | `string?` | 500 | |
|
|
790
|
-
| `feature_image` | `string?` | 2000 | |
|
|
791
|
-
| `og_image` | `string?` | 2000 | |
|
|
792
|
-
| `og_title` | `string?` | 300 | |
|
|
793
|
-
| `og_description` | `string?` | 500 | |
|
|
794
|
-
| `twitter_image` | `string?` | 2000 | |
|
|
795
|
-
| `twitter_title` | `string?` | 300 | |
|
|
796
|
-
| `twitter_description` | `string?` | 500 | |
|
|
797
|
-
| `meta_title` | `string?` | 300 | |
|
|
798
|
-
| `meta_description` | `string?` | 500 | |
|
|
799
|
-
| `codeinjection_head` | `string?` | 65535 | |
|
|
800
|
-
| `codeinjection_foot` | `string?` | 65535 | |
|
|
801
|
-
| `canonical_url` | `string?` | 2000 | |
|
|
102
|
+
Schema version 5 requires rebuilding older or incompatible experimental databases. Core rejects them without migrating or deleting data; even `resetContent: true` does not bypass layout validation.
|
|
802
103
|
|
|
803
|
-
|
|
104
|
+
Post source/content/meta fields and helpers, `addSourcePost()`, source-attribute filtering, `ContentIdentity`, and constructor identity validation have been removed. Automatic cleanup of previous exports, ownership manifests, whole-export recovery, and the `replaceExisting` option have also been removed; consumers manage that lifecycle. Author/tag caches have been removed in favor of indexed database reuse. See the [migration guide](docs/source-records.md) and [API reference](docs/api-reference.md).
|
|
804
105
|
|
|
805
|
-
|
|
106
|
+
The WordPress XML and Ghost API runners use this source-record lifecycle. The web scraper accepts an explicit URL chosen by its caller. Source adapters remain independently published npm packages; parsing input, mapping originals, and orchestrating runs are separate responsibilities.
|
|
806
107
|
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
### Constructor
|
|
810
|
-
|
|
811
|
-
```js
|
|
812
|
-
new AuthorContext({name: 'Alice', slug: 'alice', email: 'alice@example.com'})
|
|
813
|
-
```
|
|
814
|
-
|
|
815
|
-
### Methods
|
|
816
|
-
|
|
817
|
-
- `author.get(prop): any`
|
|
818
|
-
- `author.set(prop, value): AuthorContext`
|
|
819
|
-
- `author.remove(prop): AuthorContext`
|
|
820
|
-
- `author.save(db): void`
|
|
821
|
-
|
|
822
|
-
### Author fields
|
|
823
|
-
|
|
824
|
-
| Field | Type | Max | Notes |
|
|
825
|
-
|--------------------|-----------|------|--------------------------------------------------------------|
|
|
826
|
-
| `name` | `string` | 191 | **Required** |
|
|
827
|
-
| `slug` | `string` | 191 | **Required** |
|
|
828
|
-
| `email` | `string` | 191 | **Required**, validated |
|
|
829
|
-
| `profile_image` | `string?` | 2000 | |
|
|
830
|
-
| `cover_image` | `string?` | 2000 | |
|
|
831
|
-
| `bio` | `string?` | 250 | |
|
|
832
|
-
| `website` | `string?` | 2000 | |
|
|
833
|
-
| `location` | `string?` | 150 | |
|
|
834
|
-
| `facebook` | `string?` | 2000 | |
|
|
835
|
-
| `twitter` | `string?` | 2000 | |
|
|
836
|
-
| `meta_title` | `string?` | 300 | |
|
|
837
|
-
| `meta_description` | `string?` | 500 | |
|
|
838
|
-
| `roles` | `enum[]` | — | Defaults to `['Contributor']`. Each entry one of `Contributor`, `Author`, `Editor`, `Administrator` |
|
|
839
|
-
|
|
840
|
-
---
|
|
841
|
-
|
|
842
|
-
## Examples
|
|
843
|
-
|
|
844
|
-
The [examples/](examples/) directory contains runnable scripts demonstrating common patterns:
|
|
845
|
-
|
|
846
|
-
- **generate-and-export.ts** — Create 500 posts in-memory and export to Ghost JSON
|
|
847
|
-
- **reorder-tags-authors.ts** — Reorder tags and authors using `setTagOrder`, `setPrimaryTag`, and `addTag` with `sortOrder`
|
|
848
|
-
- **generate-large-export.ts** — Stress-test with 500k posts, benchmarking memory and performance
|
|
849
|
-
- **foreach-ghost-post.ts** — Iterate an existing database and log each post as Ghost JSON
|
|
850
|
-
- **deduplicate-slugs.ts** — Detect and rename duplicate slugs, then log the changes for manual redirect handling
|
|
851
|
-
- **stream-posts.ts** — Iterate 50k posts with `streamPosts()`, tracking peak memory usage
|
|
852
|
-
|
|
853
|
-
Run any example from the package directory:
|
|
108
|
+
## Development
|
|
854
109
|
|
|
855
110
|
```bash
|
|
856
|
-
|
|
111
|
+
pnpm --dir packages/mg-context run build
|
|
112
|
+
pnpm --dir packages/mg-context run test
|
|
113
|
+
pnpm --dir packages/mg-context run test:stress
|
|
857
114
|
```
|
|
858
115
|
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
This is a mono repository, managed with [Nx](https://nx.dev/) and pnpm workspaces.
|
|
862
|
-
|
|
863
|
-
Follow the instructions for the top-level repo.
|
|
864
|
-
1. `git clone` this repo & `cd` into it as usual
|
|
865
|
-
2. Run `pnpm install` to install top-level dependencies.
|
|
866
|
-
|
|
867
|
-
## Test
|
|
868
|
-
|
|
869
|
-
- `pnpm test` runs the package tests
|
|
870
|
-
- Linting and formatting are run from the repo root (`pnpm lint`, `pnpm format`)
|
|
871
|
-
- `pnpm test:local` build and run tests (for single-package development)
|
|
872
|
-
|
|
873
|
-
# Copyright & License
|
|
874
|
-
|
|
875
|
-
Copyright (c) 2013-2026 Ghost Foundation - Released under the [MIT license](LICENSE).
|
|
116
|
+
Tests require 100% coverage. The stress test ingests, rebuilds, and exports 100,000 records with 10 KiB bodies under a 256 MiB JavaScript heap and requires RSS below 512 MiB. `MG_CONTEXT_STRESS_RECORDS` can select a smaller local pilot.
|