@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.
Files changed (73) hide show
  1. package/README.md +73 -832
  2. package/build/index.d.ts +10 -4
  3. package/build/index.js +5 -2
  4. package/build/index.js.map +1 -1
  5. package/build/lib/AuthorContext.d.ts +3 -3
  6. package/build/lib/AuthorContext.js +32 -34
  7. package/build/lib/AuthorContext.js.map +1 -1
  8. package/build/lib/MigrateBase.js +2 -2
  9. package/build/lib/MigrateBase.js.map +1 -1
  10. package/build/lib/MigrateContext.d.ts +139 -36
  11. package/build/lib/MigrateContext.js +606 -324
  12. package/build/lib/MigrateContext.js.map +1 -1
  13. package/build/lib/PostContext.d.ts +72 -16
  14. package/build/lib/PostContext.js +191 -123
  15. package/build/lib/PostContext.js.map +1 -1
  16. package/build/lib/SourceRecords.d.ts +80 -0
  17. package/build/lib/SourceRecords.js +385 -0
  18. package/build/lib/SourceRecords.js.map +1 -0
  19. package/build/lib/TagContext.d.ts +1 -1
  20. package/build/lib/TagContext.js +35 -37
  21. package/build/lib/TagContext.js.map +1 -1
  22. package/build/lib/database.d.ts +47 -11
  23. package/build/lib/database.js +189 -24
  24. package/build/lib/database.js.map +1 -1
  25. package/build/lib/db-helpers.d.ts +1 -5
  26. package/build/lib/db-helpers.js +7 -37
  27. package/build/lib/db-helpers.js.map +1 -1
  28. package/build/lib/export-filename.d.ts +1 -0
  29. package/build/lib/export-filename.js +11 -0
  30. package/build/lib/export-filename.js.map +1 -0
  31. package/build/lib/ghost-csv.d.ts +10 -0
  32. package/build/lib/ghost-csv.js +55 -0
  33. package/build/lib/ghost-csv.js.map +1 -0
  34. package/build/lib/ghost-json.d.ts +4 -0
  35. package/build/lib/ghost-json.js +108 -0
  36. package/build/lib/ghost-json.js.map +1 -0
  37. package/build/lib/ghost-schema.d.ts +58 -0
  38. package/build/lib/ghost-schema.js +61 -0
  39. package/build/lib/ghost-schema.js.map +1 -0
  40. package/build/lib/json.d.ts +8 -0
  41. package/build/lib/json.js +40 -0
  42. package/build/lib/json.js.map +1 -0
  43. package/build/lib/migration-report.d.ts +3 -0
  44. package/build/lib/migration-report.js +41 -0
  45. package/build/lib/migration-report.js.map +1 -0
  46. package/build/lib/source-schema.d.ts +1 -0
  47. package/build/lib/source-schema.js +44 -0
  48. package/build/lib/source-schema.js.map +1 -0
  49. package/build/test/fixtures/mg-context-v2.d.ts +5 -0
  50. package/build/test/fixtures/mg-context-v2.js +58 -0
  51. package/build/test/fixtures/mg-context-v2.js.map +1 -0
  52. package/build/test/ghost-csv.test.d.ts +1 -0
  53. package/build/test/ghost-csv.test.js +333 -0
  54. package/build/test/ghost-csv.test.js.map +1 -0
  55. package/build/test/ghost-schema.test.d.ts +1 -0
  56. package/build/test/ghost-schema.test.js +38 -0
  57. package/build/test/ghost-schema.test.js.map +1 -0
  58. package/build/test/migrate-base.test.js +0 -6
  59. package/build/test/migrate-base.test.js.map +1 -1
  60. package/build/test/migrate-context.test.js +1094 -250
  61. package/build/test/migrate-context.test.js.map +1 -1
  62. package/build/test/package-exports.test.d.ts +1 -0
  63. package/build/test/package-exports.test.js +50 -0
  64. package/build/test/package-exports.test.js.map +1 -0
  65. package/build/test/post-context.test.js +36 -151
  66. package/build/test/post-context.test.js.map +1 -1
  67. package/build/test/source-records.test.d.ts +1 -0
  68. package/build/test/source-records.test.js +625 -0
  69. package/build/test/source-records.test.js.map +1 -0
  70. package/build/test/stream-export.test.d.ts +1 -0
  71. package/build/test/stream-export.test.js +401 -0
  72. package/build/test/stream-export.test.js.map +1 -0
  73. package/package.json +13 -10
@@ -1,36 +1,101 @@
1
- import { stat, mkdir, open, writeFile } from 'node:fs/promises';
2
- import { join, resolve } from 'node:path';
1
+ import { stat, mkdir, mkdtemp, rename, rm, writeFile } from 'node:fs/promises';
2
+ import { createWriteStream } from 'node:fs';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { tmpdir } from 'node:os';
5
+ import { dirname, join, resolve } from 'node:path';
3
6
  import { EventEmitter } from 'node:events';
7
+ import { Readable } from 'node:stream';
8
+ import { pipeline } from 'node:stream/promises';
4
9
  import errors from '@tryghost/errors';
5
- import { htmlToLexical } from '@tryghost/mg-html-lexical';
6
10
  import MigrateBase from './MigrateBase.js';
7
- import PostContext, { normalizeContentFormat } from './PostContext.js';
11
+ import SourceRecords from './SourceRecords.js';
12
+ import { writeGhostJson } from './ghost-json.js';
13
+ import { writeMigrationReport } from './migration-report.js';
14
+ import { exportBaseFilename } from './export-filename.js';
15
+ import { serializeMetadata } from './json.js';
16
+ import PostContext, { normalizeTitle } from './PostContext.js';
8
17
  import TagContext from './TagContext.js';
9
18
  import AuthorContext from './AuthorContext.js';
10
- import { createDatabase } from './database.js';
11
- import { withTransaction, findByIds, findByColumn, buildDateWhere, buildFullWhere, countWhere, findPostsWhere, findPostIdColumnsWhere, findAllPostIdsWhere, findPostsByIds } from './db-helpers.js';
19
+ import { GHOST_CSV_COLUMNS, csvLine, csvPostLine } from './ghost-csv.js';
20
+ import { createDatabase, assertMappedWrite, flushDatabaseEvents, recordSanitizedFields } from './database.js';
21
+ import { withTransaction, buildDateWhere, countWhere, findPostsWhere } from './db-helpers.js';
22
+ function hasPostFilter(filter) {
23
+ return Boolean(filter?.tag || filter?.author || filter?.createdAt || filter?.publishedAt);
24
+ }
25
+ export function buildPostWhere(filter) {
26
+ const dateWhere = buildDateWhere(filter);
27
+ const conditions = dateWhere.sql ? [dateWhere.sql] : [];
28
+ const params = [...dateWhere.params];
29
+ if (filter?.tag) {
30
+ const column = filter.tag.slug ? 'slug' : filter.tag.name ? 'name' : null;
31
+ if (column) {
32
+ conditions.push(`EXISTS (SELECT 1 FROM PostTags pt JOIN Tags t ON t.id = pt.tag_id WHERE pt.post_id = Posts.id AND t.${column} = ?)`);
33
+ params.push(filter.tag[column]);
34
+ }
35
+ else {
36
+ conditions.push('1 = 0');
37
+ }
38
+ }
39
+ if (filter?.author) {
40
+ const column = filter.author.slug ? 'slug' : filter.author.name ? 'name' : filter.author.email ? 'email' : null;
41
+ if (column) {
42
+ conditions.push(`EXISTS (SELECT 1 FROM PostAuthors pa JOIN Authors a ON a.id = pa.author_id WHERE pa.post_id = Posts.id AND a.${column} = ?)`);
43
+ params.push(filter.author[column]);
44
+ }
45
+ else {
46
+ conditions.push('1 = 0');
47
+ }
48
+ }
49
+ return { sql: conditions.length ? `WHERE ${conditions.join(' AND ')}` : '', params };
50
+ }
12
51
  export default class MigrateContext extends MigrateBase {
13
- #contentFormat;
14
52
  #dbPath;
15
- #ephemeral;
53
+ #storage;
54
+ #temporaryDirectory = null;
55
+ #sources = null;
56
+ #resetContent;
16
57
  #emitEvents;
17
58
  #warnOnLookupKeyDuplicate;
59
+ #onDuplicate;
18
60
  #db = null;
19
- #slugsDeduped = false;
20
- #duplicateSlugs = [];
21
61
  #emitter = new EventEmitter();
22
- constructor({ contentFormat = 'lexical', dbPath, ephemeral, emitEvents = true, warnOnLookupKeyDuplicate = false } = {}) {
62
+ constructor({ dbPath, storage, resetContent = false, ephemeral, emitEvents = true, warnOnLookupKeyDuplicate = false, onDuplicate, ...unsupportedOptions } = {}) {
23
63
  super();
24
- this.#contentFormat = normalizeContentFormat(contentFormat);
25
64
  this.#emitEvents = emitEvents;
26
65
  this.#warnOnLookupKeyDuplicate = warnOnLookupKeyDuplicate;
66
+ this.#onDuplicate = onDuplicate;
67
+ this.#resetContent = resetContent;
68
+ if (Object.hasOwn(unsupportedOptions, 'contentIdentity')) {
69
+ throw new errors.BadRequestError({
70
+ message: 'contentIdentity was removed; callers own ingestion and reuse policy.'
71
+ });
72
+ }
73
+ if (Object.hasOwn(unsupportedOptions, 'mode')) {
74
+ throw new errors.BadRequestError({ message: 'Use resetContent: true instead of the removed mode option.' });
75
+ }
76
+ if (Object.hasOwn(unsupportedOptions, 'rereadSource')) {
77
+ throw new errors.BadRequestError({ message: 'Use resetContent instead of rereadSource.' });
78
+ }
79
+ if (dbPath !== undefined && (typeof dbPath !== 'string' || !dbPath.trim())) {
80
+ throw new errors.BadRequestError({ message: 'dbPath must be a non-empty path.' });
81
+ }
82
+ if (typeof resetContent !== 'boolean') {
83
+ throw new errors.BadRequestError({ message: 'resetContent must be a boolean.' });
84
+ }
85
+ if (dbPath && storage) {
86
+ throw new errors.BadRequestError({ message: 'Pass either dbPath or storage, not both.' });
87
+ }
27
88
  if (dbPath) {
28
89
  this.#dbPath = dbPath;
29
- this.#ephemeral = ephemeral ?? false;
90
+ this.#storage = 'persistent';
91
+ }
92
+ else if (storage === 'memory' || ephemeral === true) {
93
+ this.#dbPath = null;
94
+ this.#storage = 'memory';
30
95
  }
31
96
  else {
32
- this.#dbPath = ':memory:';
33
- this.#ephemeral = ephemeral ?? true;
97
+ this.#dbPath = null;
98
+ this.#storage = 'temporary';
34
99
  }
35
100
  }
36
101
  get db() {
@@ -45,52 +110,257 @@ export default class MigrateContext extends MigrateBase {
45
110
  message: 'MigrateContext is already initialized. Call close() before reinitializing.'
46
111
  });
47
112
  }
48
- const storage = this.#ephemeral ? ':memory:' : this.#dbPath;
49
- this.#db = createDatabase(storage);
113
+ let databasePath;
114
+ if (this.#storage === 'memory') {
115
+ databasePath = ':memory:';
116
+ }
117
+ else if (this.#storage === 'persistent') {
118
+ databasePath = this.#dbPath;
119
+ await mkdir(dirname(databasePath), { recursive: true });
120
+ }
121
+ else {
122
+ this.#temporaryDirectory = await mkdtemp(join(tmpdir(), 'mg-context-'));
123
+ databasePath = join(this.#temporaryDirectory, 'mg-context.sqlite');
124
+ this.#dbPath = databasePath;
125
+ }
126
+ try {
127
+ this.#db = createDatabase(databasePath);
128
+ }
129
+ catch (error) {
130
+ /* c8 ignore next 4 -- defensive cleanup when SQLite initialization fails */
131
+ if (this.#temporaryDirectory) {
132
+ await rm(this.#temporaryDirectory, { recursive: true, force: true });
133
+ this.#temporaryDirectory = null;
134
+ }
135
+ throw error;
136
+ }
137
+ this.#sources = new SourceRecords(() => this.db, () => this.#clearMapped());
138
+ this.#db.hasListeners = type => this.#emitEvents && this.#emitter.listenerCount(type) > 0;
139
+ this.#db.emitEvent = (event) => {
140
+ if (this.#emitEvents) {
141
+ this.#emitter.emit(event.type, event.payload);
142
+ }
143
+ };
144
+ if (this.#resetContent) {
145
+ this.reset();
146
+ }
50
147
  }
51
148
  async close() {
52
- if (this.#db) {
53
- this.#db.db.close();
54
- this.#db = null;
149
+ try {
150
+ if (this.#db) {
151
+ try {
152
+ this.#sources.close();
153
+ }
154
+ finally {
155
+ this.#sources = null;
156
+ try {
157
+ this.#db.db.close();
158
+ }
159
+ finally {
160
+ this.#db = null;
161
+ }
162
+ }
163
+ }
55
164
  }
165
+ finally {
166
+ if (this.#temporaryDirectory) {
167
+ const directory = this.#temporaryDirectory;
168
+ this.#temporaryDirectory = null;
169
+ await rm(directory, { recursive: true, force: true });
170
+ }
171
+ }
172
+ }
173
+ /** The SQLite path in use, or :memory: for explicit memory storage. */
174
+ get databasePath() {
175
+ return this.#storage === 'memory' ? ':memory:' : this.#dbPath;
176
+ }
177
+ /** The version of the mg-context schema stored in the open SQLite database. */
178
+ get schemaVersion() {
179
+ return this.db.schemaVersion;
180
+ }
181
+ /** Return content counts when populated, or false when the database is empty. */
182
+ hasContent() {
183
+ const row = this.db.stmts.contentStats.get();
184
+ const stats = {
185
+ posts: row.posts,
186
+ pages: row.pages,
187
+ users: row.users,
188
+ tags: row.tags,
189
+ userAssociations: row.post_user_associations,
190
+ tagAssociations: row.post_tag_associations,
191
+ links: row.links
192
+ };
193
+ return Object.values(stats).some(count => count > 0) ? stats : false;
194
+ }
195
+ get sources() {
196
+ if (!this.#sources) {
197
+ throw new errors.InternalServerError({ message: 'Database not initialized. Call init() first.' });
198
+ }
199
+ return this.#sources;
200
+ }
201
+ #clearMapped() {
202
+ const db = this.db;
203
+ withTransaction(db, () => {
204
+ db.db.exec(`DELETE FROM PostTags; DELETE FROM PostAuthors; DELETE FROM Posts;
205
+ DELETE FROM Tags; DELETE FROM Authors; DELETE FROM Links; DELETE FROM SourceEntityLinks;
206
+ DELETE FROM MigrationEvents WHERE phase = 'mapping';
207
+ DELETE FROM Fingerprints; DELETE FROM PendingEvents;`);
208
+ });
209
+ }
210
+ resetMappedContent() {
211
+ this.sources.assertIdle();
212
+ this.#clearMapped();
213
+ }
214
+ async rebuildMappedContent(callback) {
215
+ this.sources.assertIdle();
216
+ return this.savepoint(async () => {
217
+ this.#clearMapped();
218
+ return await callback();
219
+ });
220
+ }
221
+ reset() {
222
+ if (arguments.length > 0) {
223
+ throw new errors.BadRequestError({ message: 'reset() no longer accepts options.' });
224
+ }
225
+ this.sources.assertIdle();
226
+ withTransaction(this.db, () => {
227
+ this.#clearMapped();
228
+ this.db.db.exec(`DELETE FROM SourceRecords; DELETE FROM SourceIngestions; DELETE FROM MigrationEvents;
229
+ DELETE FROM sqlite_sequence WHERE name IN ('Posts', 'Tags', 'Authors', 'PostTags', 'PostAuthors', 'Links', 'MigrationEvents', 'SourceRecords', 'SourceIngestions', 'PendingEvents');`);
230
+ });
231
+ }
232
+ async savepoint(callback) {
233
+ if (!this.db.inTransaction) {
234
+ return this.transaction(callback);
235
+ }
236
+ const name = `record_${randomUUID().replaceAll('-', '')}`;
237
+ this.db.db.exec(`SAVEPOINT ${name}`);
238
+ try {
239
+ const result = await callback();
240
+ this.db.db.exec(`RELEASE ${name}`);
241
+ return result;
242
+ }
243
+ catch (error) {
244
+ this.db.db.exec(`ROLLBACK TO ${name}; RELEASE ${name}`);
245
+ throw error;
246
+ }
247
+ }
248
+ recordDiagnostic(type, details = {}, sourceRecordId) {
249
+ assertMappedWrite(this.db);
250
+ if (!type.trim() || (sourceRecordId !== undefined && !this.sources.getById(sourceRecordId))) {
251
+ throw new errors.BadRequestError({ message: 'Diagnostic requires a type and a completed source record.' });
252
+ }
253
+ this.db.db
254
+ .prepare("INSERT INTO MigrationEvents(type, details, created_at, phase, source_record_id) VALUES (?, ?, ?, 'mapping', ?)")
255
+ .run(type, serializeMetadata(details), new Date().toISOString(), sourceRecordId ?? null);
256
+ }
257
+ async *streamDiagnostics({ phase, ingestionId, batchSize = 25 } = {}) {
258
+ if (!Number.isSafeInteger(batchSize) || batchSize < 1) {
259
+ throw new RangeError('batchSize must be a positive safe integer.');
260
+ }
261
+ const conditions = ['id > ?'];
262
+ const params = [];
263
+ if (phase !== undefined) {
264
+ conditions.push('phase = ?');
265
+ params.push(phase);
266
+ }
267
+ if (ingestionId !== undefined) {
268
+ conditions.push('ingestion_id = ?');
269
+ params.push(ingestionId);
270
+ }
271
+ const query = this.db.db.prepare(`SELECT * FROM MigrationEvents WHERE ${conditions.join(' AND ')} ORDER BY id LIMIT ?`);
272
+ let after = 0;
273
+ while (true) {
274
+ const rows = query.all(after, ...params, batchSize);
275
+ if (!rows.length) {
276
+ break;
277
+ }
278
+ for (const row of rows) {
279
+ after = row.id;
280
+ yield {
281
+ id: row.id,
282
+ type: row.type,
283
+ postId: row.post_id,
284
+ lookupKey: row.lookup_key,
285
+ details: JSON.parse(row.details),
286
+ createdAt: row.created_at,
287
+ phase: row.phase,
288
+ ingestionId: row.ingestion_id,
289
+ sourceRecordId: row.source_record_id
290
+ };
291
+ }
292
+ }
293
+ }
294
+ writeGhostJsonStream(outputDir, options = {}) {
295
+ return writeGhostJson(this, outputDir, {
296
+ ...options,
297
+ onWrite: file => {
298
+ options.onWrite?.(file);
299
+ if (this.#emitEvents) {
300
+ this.#emitter.emit('export:file-written', structuredClone(file));
301
+ }
302
+ }
303
+ });
304
+ }
305
+ writeMigrationReport(path, summary = {}) {
306
+ return writeMigrationReport(this, path, summary);
56
307
  }
57
- // eslint-disable-next-line no-unused-vars
58
308
  on(event, listener) {
59
309
  this.#emitter.on(event, listener);
60
310
  return this;
61
311
  }
62
- // eslint-disable-next-line no-unused-vars
63
312
  off(event, listener) {
64
313
  this.#emitter.off(event, listener);
65
314
  return this;
66
315
  }
316
+ getMigrationReport() {
317
+ const summary = {
318
+ 'post:inserted': 0,
319
+ 'post:skipped': 0,
320
+ 'post:replaced': 0,
321
+ 'field:sanitized': 0,
322
+ 'slug:renamed': 0
323
+ };
324
+ for (const row of this.db.stmts.countMigrationEventsByType.all()) {
325
+ summary[row.type] = row.count;
326
+ }
327
+ const events = this.db.stmts.findMigrationEvents.all().map(row => ({
328
+ id: row.id,
329
+ type: row.type,
330
+ postId: row.post_id ?? null,
331
+ lookupKey: row.lookup_key ?? null,
332
+ details: JSON.parse(row.details),
333
+ createdAt: row.created_at,
334
+ phase: row.phase,
335
+ ingestionId: row.ingestion_id,
336
+ sourceRecordId: row.source_record_id
337
+ }));
338
+ return { summary, events };
339
+ }
67
340
  get duplicateSlugs() {
68
- return this.#duplicateSlugs;
341
+ return this.#collectDuplicateSlugs();
69
342
  }
70
343
  /**
71
- * Every value changed to satisfy Ghost's schema during this run — see
72
- * MigrateBase.sanitize(). Collected as posts, tags and authors are saved.
344
+ * Materialize persisted sanitization diagnostics for the current mapped result.
345
+ * Use streamDiagnostics() when the full array would be too large.
73
346
  */
74
347
  get sanitizedFields() {
75
348
  return this.db.sanitizedFields;
76
349
  }
77
350
  #postUrl(row) {
78
- const source = JSON.parse(row.source);
79
351
  const data = JSON.parse(row.data);
80
- return source.url || data.canonical_url || '';
352
+ return data.canonical_url || '';
81
353
  }
82
354
  async deduplicateSlugs() {
83
- if (this.#slugsDeduped) {
84
- return this.#duplicateSlugs;
85
- }
86
- this.#slugsDeduped = true;
355
+ return this.#collectDuplicateSlugs();
356
+ }
357
+ #collectDuplicateSlugs() {
87
358
  // Slug deduplication happens at insert time in PostContext.save(), which records the
88
359
  // pre-deduplication slug in original_slug. The groups are rebuilt from the database
89
360
  // rather than from the in-memory renames, so the result is still complete when
90
361
  // resuming against an existing dbPath, where the renames happened on an earlier run.
91
362
  const renamedRows = this.db.stmts.findRenamedPosts.all();
92
363
  if (renamedRows.length === 0) {
93
- this.#duplicateSlugs = [];
94
364
  return [];
95
365
  }
96
366
  // Group the renamed posts by the slug they originally wanted. Map preserves
@@ -128,55 +398,51 @@ export default class MigrateContext extends MigrateBase {
128
398
  });
129
399
  }
130
400
  }
131
- this.#duplicateSlugs = result;
132
401
  return result;
133
402
  }
134
403
  async prepareForExport({ batchSize = 200 } = {}) {
135
- await this.deduplicateSlugs();
404
+ assertMappedWrite(this.db);
405
+ if (!Number.isSafeInteger(batchSize) || batchSize < 1) {
406
+ throw new RangeError('batchSize must be a positive safe integer.');
407
+ }
136
408
  const total = this.db.stmts.countPosts.get().count;
137
409
  let processed = 0;
138
- for (let offset = 0; offset < total; offset += batchSize) {
139
- const rows = this.db.stmts.findPostsForConversion.all(batchSize, offset);
140
- this.db.db.exec('BEGIN');
141
- try {
410
+ let after = 0;
411
+ const query = this.db.db.prepare('SELECT id, data FROM Posts WHERE id > ? ORDER BY id LIMIT ?');
412
+ while (true) {
413
+ const rows = query.all(after, batchSize);
414
+ if (!rows.length) {
415
+ break;
416
+ }
417
+ withTransaction(this.db, () => {
142
418
  for (const row of rows) {
143
- const cf = normalizeContentFormat(row.content_format);
144
- if (cf === 'html') {
145
- continue;
146
- }
147
419
  const data = JSON.parse(row.data);
148
- let changed = false;
149
- if (!data.lexical && data.html) {
150
- data.lexical = JSON.stringify(htmlToLexical(data.html));
151
- changed = true;
152
- }
153
- if (data.mobiledoc !== null) {
154
- data.mobiledoc = null;
155
- changed = true;
156
- }
157
- if (changed) {
420
+ const title = normalizeTitle(data.title);
421
+ if (data.title !== title) {
422
+ recordSanitizedFields(this.db, [
423
+ {
424
+ context: 'PostContext',
425
+ slug: data.slug ?? '',
426
+ field: 'title',
427
+ reason: 'replaced',
428
+ oldValue: data.title,
429
+ newValue: title
430
+ }
431
+ ]);
432
+ data.title = title;
158
433
  this.db.stmts.updatePostData.run(JSON.stringify(data), row.id);
159
434
  }
435
+ after = row.id;
160
436
  }
161
- this.db.db.exec('COMMIT');
162
- /* c8 ignore next 4 */
163
- }
164
- catch (err) {
165
- this.db.db.exec('ROLLBACK');
166
- throw err;
167
- }
437
+ });
168
438
  processed += rows.length;
169
439
  if (this.#emitEvents) {
170
- this.#emitter.emit('progress', 'prepareForExport', processed, total);
440
+ this.#emitter.emit('progress', { operation: 'prepareForExport', processed, total });
171
441
  }
172
- // Yield to the event loop between batches so V8 can garbage-collect
173
- // the intermediate DOM/lexical trees created by the converter
174
- await new Promise(r => {
175
- setImmediate(r);
176
- });
177
442
  }
178
443
  }
179
444
  async transaction(callback) {
445
+ this.sources.assertIdle();
180
446
  if (this.db.inTransaction) {
181
447
  return await callback();
182
448
  }
@@ -185,10 +451,14 @@ export default class MigrateContext extends MigrateBase {
185
451
  try {
186
452
  const result = await callback();
187
453
  this.db.db.exec('COMMIT');
454
+ this.db.inTransaction = false;
455
+ flushDatabaseEvents(this.db);
188
456
  return result;
189
457
  }
190
458
  catch (err) {
191
- this.db.db.exec('ROLLBACK');
459
+ if (this.db.inTransaction) {
460
+ this.db.db.exec('ROLLBACK');
461
+ }
192
462
  throw err;
193
463
  /* c8 ignore next */
194
464
  }
@@ -196,130 +466,140 @@ export default class MigrateContext extends MigrateBase {
196
466
  this.db.inTransaction = false;
197
467
  }
198
468
  }
199
- #resolveFilterPostIds(filter) {
200
- if (!filter || (!filter.tag && !filter.author)) {
201
- return null;
469
+ #buildFilterWhere(filter) {
470
+ return buildPostWhere(filter);
471
+ }
472
+ async *#filteredRows(filter, batchSize, operation) {
473
+ if (!Number.isSafeInteger(batchSize) || batchSize < 1) {
474
+ throw new RangeError('batchSize must be a positive safe integer.');
202
475
  }
203
- let tagPostIds = null;
204
- let authorPostIds = null;
205
- if (filter.tag) {
206
- let tags = [];
207
- if (filter.tag.slug) {
208
- tags = this.db.stmts.findTagsBySlug.all(filter.tag.slug);
209
- }
210
- else if (filter.tag.name) {
211
- tags = this.db.stmts.findTagsByName.all(filter.tag.name);
212
- }
213
- tagPostIds = new Set();
214
- for (const tag of tags) {
215
- const postTags = this.db.stmts.findPostTagsByTagId.all(tag.id);
216
- for (const pt of postTags) {
217
- tagPostIds.add(pt.post_id);
476
+ const where = this.#buildFilterWhere(filter);
477
+ const iteration = randomUUID();
478
+ this.db.db
479
+ .prepare(`INSERT INTO IterationPosts SELECT ?, id FROM Posts ${where.sql}`)
480
+ .run(iteration, ...where.params);
481
+ try {
482
+ const total = this.db.db
483
+ .prepare('SELECT COUNT(*) AS count FROM IterationPosts WHERE iteration_id = ?')
484
+ .get(iteration).count;
485
+ const query = this.db.db.prepare('SELECT p.* FROM IterationPosts i JOIN Posts p ON p.id = i.post_id WHERE i.iteration_id = ? AND i.post_id > ? ORDER BY i.post_id LIMIT ?');
486
+ let after = 0;
487
+ let processed = 0;
488
+ while (true) {
489
+ const rows = query.all(iteration, after, batchSize);
490
+ if (!rows.length) {
491
+ break;
218
492
  }
219
- }
220
- }
221
- if (filter.author) {
222
- let authors = [];
223
- if (filter.author.slug) {
224
- authors = this.db.stmts.findAuthorsBySlug.all(filter.author.slug);
225
- }
226
- else if (filter.author.name) {
227
- authors = this.db.stmts.findAuthorsByName.all(filter.author.name);
228
- }
229
- else if (filter.author.email) {
230
- authors = this.db.stmts.findAuthorsByEmail.all(filter.author.email);
231
- }
232
- authorPostIds = new Set();
233
- for (const author of authors) {
234
- const postAuthors = this.db.stmts.findPostAuthorsByAuthorId.all(author.id);
235
- for (const pa of postAuthors) {
236
- authorPostIds.add(pa.post_id);
493
+ for (const row of rows) {
494
+ after = row.id;
495
+ yield row;
496
+ processed += 1;
497
+ }
498
+ if (this.#emitEvents) {
499
+ this.#emitter.emit('progress', { operation, processed, total });
237
500
  }
238
501
  }
239
502
  }
240
- let ids;
241
- if (tagPostIds && authorPostIds) {
242
- ids = [...tagPostIds].filter(id => authorPostIds.has(id));
243
- }
244
- else if (tagPostIds) {
245
- ids = [...tagPostIds];
246
- }
247
- else {
248
- ids = [...authorPostIds];
503
+ finally {
504
+ this.db.db.prepare('DELETE FROM IterationPosts WHERE iteration_id = ?').run(iteration);
249
505
  }
250
- return ids.sort((a, b) => a - b);
251
- }
252
- #buildFilterWhere(filter) {
253
- const postIds = this.#resolveFilterPostIds(filter);
254
- const dateWhere = buildDateWhere(filter);
255
- return buildFullWhere(dateWhere, postIds);
256
506
  }
257
507
  // eslint-disable-next-line no-unused-vars
258
508
  async forEachPost(callback, { batchSize = 100, filter } = {}) {
259
- const where = this.#buildFilterWhere(filter);
260
- // Snapshot matching IDs up front so mutations during iteration
261
- // cannot shift pagination (e.g. changing a date or tag used in the filter).
262
- const allIds = findAllPostIdsWhere(this.db, where);
263
- const total = allIds.length;
264
- let processed = 0;
265
- for (let offset = 0; offset < total; offset += batchSize) {
266
- const batchIds = allIds.slice(offset, offset + batchSize);
267
- const rows = findPostsByIds(this.db, batchIds);
268
- for (const row of rows) {
269
- const post = PostContext.fromRow(row, this.db);
270
- await callback(post);
509
+ if (!hasPostFilter(filter)) {
510
+ const total = this.db.stmts.countPosts.get().count;
511
+ const maxId = this.db.stmts.findMaxPostId.get().max_id;
512
+ await this.#forEachByKeyset(total, maxId, batchSize, 'forEachPost', (afterId, upperId, limit) => this.db.stmts.findPostsAfterId.all(afterId, upperId, limit), row => PostContext.fromRow(row, this.db), callback, post => {
271
513
  withTransaction(this.db, () => {
272
514
  post.save(this.db);
273
515
  });
274
- processed += 1;
275
- }
276
- if (this.#emitEvents) {
277
- this.#emitter.emit('progress', 'forEachPost', processed, total);
278
- }
516
+ });
517
+ return;
518
+ }
519
+ for await (const row of this.#filteredRows(filter, batchSize, 'forEachPost')) {
520
+ const post = PostContext.fromRow(row, this.db);
521
+ await callback(post);
522
+ post.save(this.db);
279
523
  }
280
524
  }
281
525
  async *streamPosts({ batchSize = 100, filter } = {}) {
282
- const where = this.#buildFilterWhere(filter);
283
- const allIds = findAllPostIdsWhere(this.db, where);
284
- yield* this.#streamByIds(allIds, batchSize, 'streamPosts', ids => findPostsByIds(this.db, ids), row => PostContext.fromRow(row, this.db));
526
+ if (!hasPostFilter(filter)) {
527
+ const total = this.db.stmts.countPosts.get().count;
528
+ const maxId = this.db.stmts.findMaxPostId.get().max_id;
529
+ yield* this.#streamByKeyset(total, maxId, batchSize, 'streamPosts', (afterId, upperId, limit) => this.db.stmts.findPostsAfterId.all(afterId, upperId, limit), row => PostContext.fromRow(row, this.db));
530
+ return;
531
+ }
532
+ for await (const row of this.#filteredRows(filter, batchSize, 'streamPosts')) {
533
+ yield PostContext.fromRow(row, this.db);
534
+ }
285
535
  }
286
- async *streamTags({ batchSize = 100 } = {}) {
287
- const allIds = this.db.stmts.findUsedTagIds.all().map((r) => r.id);
288
- yield* this.#streamByIds(allIds, batchSize, 'streamTags', ids => findByIds(this.db, 'Tags', ids), row => TagContext.fromRow(row));
536
+ async *streamTags({ batchSize = 100, scope = 'referenced' } = {}) {
537
+ const total = (scope === 'all' ? this.db.stmts.countAllTags : this.db.stmts.countUsedTags).get().count;
538
+ const maxId = (scope === 'all' ? this.db.stmts.findMaxTagId : this.db.stmts.findMaxUsedTagId).get().max_id;
539
+ yield* this.#streamByKeyset(total, maxId, batchSize, 'streamTags', (afterId, upperId, limit) => (scope === 'all' ? this.db.stmts.findTagsAfterId : this.db.stmts.findUsedTagsAfterId).all(afterId, upperId, limit), row => TagContext.fromRow(row));
289
540
  }
290
- async *streamAuthors({ batchSize = 100 } = {}) {
291
- const allIds = this.db.stmts.findUsedAuthorIds.all().map((r) => r.id);
292
- yield* this.#streamByIds(allIds, batchSize, 'streamAuthors', ids => findByIds(this.db, 'Authors', ids), row => AuthorContext.fromRow(row));
541
+ async *streamAuthors({ batchSize = 100, scope = 'referenced' } = {}) {
542
+ const total = (scope === 'all' ? this.db.stmts.countAllAuthors : this.db.stmts.countUsedAuthors).get().count;
543
+ const maxId = (scope === 'all' ? this.db.stmts.findMaxAuthorId : this.db.stmts.findMaxUsedAuthorId).get().max_id;
544
+ yield* this.#streamByKeyset(total, maxId, batchSize, 'streamAuthors', (afterId, upperId, limit) => (scope === 'all' ? this.db.stmts.findAuthorsAfterId : this.db.stmts.findUsedAuthorsAfterId).all(afterId, upperId, limit), row => AuthorContext.fromRow(row));
293
545
  }
294
- // eslint-disable-next-line no-unused-vars
295
- async *#streamByIds(allIds, batchSize, eventName, fetchBatch, toEntity) {
296
- const total = allIds.length;
546
+ async #forEachByKeyset(total, maxId, batchSize, eventName, fetchBatch, toEntity, callback, save) {
547
+ if (maxId === null) {
548
+ return;
549
+ }
297
550
  let processed = 0;
298
- for (let offset = 0; offset < total; offset += batchSize) {
299
- const batchIds = allIds.slice(offset, offset + batchSize);
300
- const rows = fetchBatch(batchIds);
551
+ let lastId = 0;
552
+ let rows;
553
+ do {
554
+ rows = fetchBatch(lastId, maxId, batchSize);
301
555
  for (const row of rows) {
302
- yield toEntity(row);
556
+ lastId = row.id;
557
+ const entity = toEntity(row);
558
+ await callback(entity);
559
+ save(entity);
303
560
  processed += 1;
304
561
  }
305
562
  if (this.#emitEvents) {
306
- this.#emitter.emit('progress', eventName, processed, total);
563
+ this.#emitter.emit('progress', { operation: eventName, processed, total });
307
564
  }
565
+ } while (rows.length === batchSize && lastId < maxId);
566
+ }
567
+ async *#streamByKeyset(total, maxId, batchSize, eventName, fetchBatch, toEntity) {
568
+ if (maxId === null) {
569
+ return;
308
570
  }
571
+ let processed = 0;
572
+ let lastId = 0;
573
+ let rows;
574
+ do {
575
+ rows = fetchBatch(lastId, maxId, batchSize);
576
+ for (const row of rows) {
577
+ lastId = row.id;
578
+ yield toEntity(row);
579
+ processed += 1;
580
+ }
581
+ if (this.#emitEvents) {
582
+ this.#emitter.emit('progress', { operation: eventName, processed, total });
583
+ }
584
+ } while (rows.length === batchSize && lastId < maxId);
309
585
  }
310
586
  async addPost(post) {
311
587
  let newPost;
312
588
  if (post && post instanceof PostContext) {
313
589
  newPost = post;
590
+ newPost.onDuplicate = this.#onDuplicate ?? newPost.onDuplicate;
314
591
  newPost.warnOnLookupKeyDuplicate = this.#warnOnLookupKeyDuplicate;
315
592
  newPost.save(this.db);
316
593
  }
317
594
  else if (post && typeof post === 'object') {
318
- newPost = new PostContext({ ...post, contentFormat: this.#contentFormat });
595
+ newPost = new PostContext({
596
+ ...post,
597
+ onDuplicate: post.onDuplicate ?? this.#onDuplicate
598
+ });
319
599
  newPost.warnOnLookupKeyDuplicate = this.#warnOnLookupKeyDuplicate;
320
600
  }
321
601
  else {
322
- newPost = new PostContext({ contentFormat: this.#contentFormat });
602
+ newPost = new PostContext({ onDuplicate: this.#onDuplicate });
323
603
  newPost.warnOnLookupKeyDuplicate = this.#warnOnLookupKeyDuplicate;
324
604
  }
325
605
  return newPost;
@@ -328,7 +608,46 @@ export default class MigrateContext extends MigrateBase {
328
608
  const rows = this.db.stmts.findAllPostsOrdered.all();
329
609
  return rows.map((row) => PostContext.fromRow(row, this.db));
330
610
  }
331
- async findPosts({ slug, title, sourceAttr, tagSlug, tagName, authorSlug, authorName, authorEmail } = {}) {
611
+ /**
612
+ * Patch scalar post data without hydrating or replacing tag/author relationships.
613
+ * Slugs stay on the full PostContext save path because they require deduplication
614
+ * and redirect tracking.
615
+ */
616
+ updatePostData(dbId, patch, options = {}) {
617
+ assertMappedWrite(this.db);
618
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {
619
+ throw new errors.BadRequestError({ message: 'Post data patch must be an object.' });
620
+ }
621
+ const forbiddenField = ['slug', 'tags', 'authors'].find(field => Object.hasOwn(patch, field));
622
+ if (forbiddenField) {
623
+ throw new errors.BadRequestError({
624
+ message: `Post data patch cannot update "${forbiddenField}". Use PostContext.save() instead.`
625
+ });
626
+ }
627
+ const row = this.db.stmts.findPostById.get(dbId);
628
+ if (!row) {
629
+ throw new errors.NotFoundError({ message: `Post with database ID ${dbId} was not found.` });
630
+ }
631
+ const post = PostContext.fromRow(row, this.db, { hydrateRelationships: false });
632
+ for (const [key, value] of Object.entries(patch)) {
633
+ post.set(key, value);
634
+ }
635
+ const sanitized = [];
636
+ post.sanitize(sanitized);
637
+ post.checkRequired(post.data);
638
+ const postData = { ...post.data };
639
+ delete postData.tags;
640
+ delete postData.authors;
641
+ const toISOString = (value) => value?.toISOString() ?? null;
642
+ withTransaction(this.db, () => {
643
+ this.db.stmts.patchPostData.run(JSON.stringify(postData), toISOString(post.data.created_at), toISOString(post.data.updated_at), toISOString(post.data.published_at), dbId);
644
+ if (Object.hasOwn(options, 'webscrapeData')) {
645
+ this.db.stmts.updatePostWebscrapeData.run(JSON.stringify(options.webscrapeData) ?? null, dbId);
646
+ }
647
+ recordSanitizedFields(this.db, sanitized);
648
+ });
649
+ }
650
+ async findPosts({ slug, title, tagSlug, tagName, authorSlug, authorName, authorEmail } = {}) {
332
651
  if (slug) {
333
652
  const rows = this.db.stmts.findPostsBySlug.all(slug);
334
653
  return rows.map((row) => PostContext.fromRow(row, this.db));
@@ -344,17 +663,6 @@ export default class MigrateContext extends MigrateBase {
344
663
  }
345
664
  return results;
346
665
  }
347
- else if (sourceAttr && sourceAttr.key && sourceAttr.value) {
348
- const rows = this.db.stmts.findAllPostsOrdered.all();
349
- const results = [];
350
- for (const row of rows) {
351
- const source = JSON.parse(row.source);
352
- if (source[sourceAttr.key] === sourceAttr.value) {
353
- results.push(PostContext.fromRow(row, this.db));
354
- }
355
- }
356
- return results;
357
- }
358
666
  else if (tagSlug) {
359
667
  const tag = this.db.stmts.findTagBySlug.get(tagSlug);
360
668
  if (!tag) {
@@ -441,79 +749,59 @@ export default class MigrateContext extends MigrateBase {
441
749
  }
442
750
  }
443
751
  addLink(oldUrl, newUrl) {
752
+ assertMappedWrite(this.db);
444
753
  this.db.stmts.insertLink.run(oldUrl, newUrl);
445
754
  }
446
755
  findLink(oldUrl) {
447
756
  const row = this.db.stmts.findLink.get(oldUrl);
448
757
  return row ? row.new_url : null;
449
758
  }
450
- async findTags({ slug, name } = {}) {
759
+ async findTags({ slug, name, scope = 'referenced' } = {}) {
760
+ let rows;
451
761
  if (slug) {
452
- const rows = this.db.stmts.findTagsBySlug.all(slug);
453
- return rows.map((row) => TagContext.fromRow(row));
762
+ rows = this.db.stmts.findTagsBySlug.all(slug);
454
763
  }
455
764
  else if (name) {
456
- const rows = this.db.stmts.findTagsByName.all(name);
457
- return rows.map((row) => TagContext.fromRow(row));
765
+ rows = this.db.stmts.findTagsByName.all(name);
458
766
  }
459
767
  else {
460
768
  return null;
461
769
  }
770
+ if (scope === 'referenced') {
771
+ rows = rows.filter(row => this.db.stmts.tagIsUsed.get(row.id));
772
+ }
773
+ return rows.map((row) => TagContext.fromRow(row));
462
774
  }
463
775
  // eslint-disable-next-line no-unused-vars
464
- async forEachTag(callback, { batchSize = 100 } = {}) {
465
- const allIds = this.db.stmts.findUsedTagIds.all().map((r) => r.id);
466
- const total = allIds.length;
467
- let processed = 0;
468
- for (let offset = 0; offset < total; offset += batchSize) {
469
- const batchIds = allIds.slice(offset, offset + batchSize);
470
- const rows = findByIds(this.db, 'Tags', batchIds);
471
- for (const row of rows) {
472
- const tag = TagContext.fromRow(row);
473
- await callback(tag);
474
- tag.save(this.db);
475
- processed += 1;
476
- }
477
- if (this.#emitEvents) {
478
- this.#emitter.emit('progress', 'forEachTag', processed, total);
479
- }
480
- }
776
+ async forEachTag(callback, { batchSize = 100, scope = 'referenced' } = {}) {
777
+ const total = (scope === 'all' ? this.db.stmts.countAllTags : this.db.stmts.countUsedTags).get().count;
778
+ const maxId = (scope === 'all' ? this.db.stmts.findMaxTagId : this.db.stmts.findMaxUsedTagId).get().max_id;
779
+ await this.#forEachByKeyset(total, maxId, batchSize, 'forEachTag', (afterId, upperId, limit) => (scope === 'all' ? this.db.stmts.findTagsAfterId : this.db.stmts.findUsedTagsAfterId).all(afterId, upperId, limit), row => TagContext.fromRow(row), callback, tag => tag.save(this.db));
481
780
  }
482
781
  // eslint-disable-next-line no-unused-vars
483
- async forEachAuthor(callback, { batchSize = 100 } = {}) {
484
- const allIds = this.db.stmts.findUsedAuthorIds.all().map((r) => r.id);
485
- const total = allIds.length;
486
- let processed = 0;
487
- for (let offset = 0; offset < total; offset += batchSize) {
488
- const batchIds = allIds.slice(offset, offset + batchSize);
489
- const rows = findByIds(this.db, 'Authors', batchIds);
490
- for (const row of rows) {
491
- const author = AuthorContext.fromRow(row);
492
- await callback(author);
493
- author.save(this.db);
494
- processed += 1;
495
- }
496
- if (this.#emitEvents) {
497
- this.#emitter.emit('progress', 'forEachAuthor', processed, total);
498
- }
499
- }
782
+ async forEachAuthor(callback, { batchSize = 100, scope = 'referenced' } = {}) {
783
+ const total = (scope === 'all' ? this.db.stmts.countAllAuthors : this.db.stmts.countUsedAuthors).get().count;
784
+ const maxId = (scope === 'all' ? this.db.stmts.findMaxAuthorId : this.db.stmts.findMaxUsedAuthorId).get().max_id;
785
+ await this.#forEachByKeyset(total, maxId, batchSize, 'forEachAuthor', (afterId, upperId, limit) => (scope === 'all' ? this.db.stmts.findAuthorsAfterId : this.db.stmts.findUsedAuthorsAfterId).all(afterId, upperId, limit), row => AuthorContext.fromRow(row), callback, author => author.save(this.db));
500
786
  }
501
- async findAuthors({ slug, name, email } = {}) {
787
+ async findAuthors({ slug, name, email, scope = 'referenced' } = {}) {
788
+ let rows;
502
789
  if (slug) {
503
- const rows = this.db.stmts.findAuthorsBySlug.all(slug);
504
- return rows.map((row) => AuthorContext.fromRow(row));
790
+ rows = this.db.stmts.findAuthorsBySlug.all(slug);
505
791
  }
506
792
  else if (name) {
507
- const rows = this.db.stmts.findAuthorsByName.all(name);
508
- return rows.map((row) => AuthorContext.fromRow(row));
793
+ rows = this.db.stmts.findAuthorsByName.all(name);
509
794
  }
510
795
  else if (email) {
511
- const rows = this.db.stmts.findAuthorsByEmail.all(email);
512
- return rows.map((row) => AuthorContext.fromRow(row));
796
+ rows = this.db.stmts.findAuthorsByEmail.all(email);
513
797
  }
514
798
  else {
515
799
  return null;
516
800
  }
801
+ if (scope === 'referenced') {
802
+ rows = rows.filter(row => this.db.stmts.authorIsUsed.get(row.id));
803
+ }
804
+ return rows.map((row) => AuthorContext.fromRow(row));
517
805
  }
518
806
  // eslint-disable-next-line no-unused-vars
519
807
  async forEachGhostPost(callback, { batchSize = 100, filter } = {}) {
@@ -532,139 +820,133 @@ export default class MigrateContext extends MigrateBase {
532
820
  processed += 1;
533
821
  }
534
822
  if (this.#emitEvents) {
535
- this.#emitter.emit('progress', 'forEachGhostPost', processed, total);
823
+ this.#emitter.emit('progress', { operation: 'forEachGhostPost', processed, total });
536
824
  }
537
825
  }
538
826
  }
539
- // eslint-disable-next-line no-unused-vars
540
- async writeGhostJson(outputDir, { batchSize = 5000, filename: rawFilename = 'posts', filter, onWrite } = {}) {
541
- const filename = rawFilename.replace(/\.json$/i, '');
827
+ async writeGhostJson(outputDir, options = {}) {
828
+ const files = [];
829
+ for await (const file of this.writeGhostJsonStream(outputDir, options)) {
830
+ files.push(file);
831
+ }
832
+ return files;
833
+ }
834
+ async writeGhostCSV(outputDir, { filename: rawFilename = 'posts', filter } = {}) {
835
+ const name = `${exportBaseFilename(rawFilename, 'csv')}.csv`;
836
+ await this.prepareForExport();
542
837
  await mkdir(outputDir, { recursive: true });
543
- const where = this.#buildFilterWhere(filter);
544
- const count = countWhere(this.db, where);
545
- const totalBatches = Math.max(1, Math.ceil(count / batchSize));
546
- const writtenFiles = [];
547
- const subBatchSize = 200;
548
- for (let batch = 0; batch < totalBatches; batch++) {
549
- const batchOffset = batch * batchSize;
550
- const batchLimit = Math.min(batchSize, count - batchOffset);
551
- // Query post IDs and ghost IDs for this file batch
552
- const postIdRows = findPostIdColumnsWhere(this.db, where, batchLimit, batchOffset);
553
- const postIds = postIdRows.map((r) => r.id);
554
- const ghostIdMap = new Map(postIdRows.map((r) => [r.id, r.ghost_id]));
555
- // Load junction + entity data from DB (small — tags/authors are few)
556
- const postTagRows = findByColumn(this.db, 'PostTags', 'post_id', postIds, 'post_id ASC, sort_order ASC');
557
- const postAuthorRows = findByColumn(this.db, 'PostAuthors', 'post_id', postIds, 'post_id ASC, sort_order ASC');
558
- const tagDbIds = [...new Set(postTagRows.map((r) => r.tag_id))];
559
- const authorDbIds = [...new Set(postAuthorRows.map((r) => r.author_id))];
560
- const tagRows = findByIds(this.db, 'Tags', tagDbIds);
561
- const authorRows = findByIds(this.db, 'Authors', authorDbIds);
562
- // Build small Ghost JSON arrays
563
- const tagGhostIds = new Map();
564
- const tags = tagRows.map((r) => {
565
- const data = JSON.parse(r.data);
566
- tagGhostIds.set(r.id, r.ghost_id);
567
- return { id: r.ghost_id, ...data };
568
- });
569
- const authorGhostIds = new Map();
570
- const users = authorRows.map((r) => {
571
- const data = JSON.parse(r.data);
572
- authorGhostIds.set(r.id, r.ghost_id);
573
- return { id: r.ghost_id, ...data };
574
- });
575
- const postsTags = postTagRows.map((r) => ({
576
- post_id: ghostIdMap.get(r.post_id),
577
- tag_id: tagGhostIds.get(r.tag_id),
578
- sort_order: r.sort_order
579
- }));
580
- const postsAuthors = postAuthorRows.map((r) => ({
581
- post_id: ghostIdMap.get(r.post_id),
582
- author_id: authorGhostIds.get(r.author_id),
583
- sort_order: r.sort_order
584
- }));
585
- // Stream file: posts are loaded and written in sub-batches
586
- const fileName = totalBatches === 1 ? `${filename}.json` : `${filename}-${batch + 1}.json`;
587
- const outputPath = join(outputDir, fileName);
588
- const fh = await open(outputPath, 'w');
589
- const postsMeta = [];
590
- let postCount = 0;
591
- // Indent a JSON.stringify block so all lines after the first are at the given depth
592
- const pretty = (obj, depth) => {
593
- const pad = ' '.repeat(depth);
594
- return JSON.stringify(obj, null, 2).replace(/\n/g, `\n${pad}`);
595
- };
596
- try {
597
- await fh.write('{\n');
598
- await fh.write(` "meta": ${pretty({ exported_on: Date.now(), version: '2.0.0' }, 2)},\n`);
599
- await fh.write(' "data": {\n');
600
- await fh.write(' "posts": [\n');
601
- // Stream posts in sub-batches
602
- for (let sub = 0; sub < batchLimit; sub += subBatchSize) {
603
- const rows = findPostsWhere(this.db, where, Math.min(subBatchSize, batchLimit - sub), batchOffset + sub);
604
- for (const row of rows) {
605
- const { post, meta } = PostContext.toGhostPost(row);
606
- if (postCount > 0) {
607
- await fh.write(',\n');
608
- }
609
- await fh.write(` ${pretty(post, 6)}`);
610
- if (meta) {
611
- postsMeta.push(meta);
612
- }
613
- postCount += 1;
614
- }
838
+ const where = buildPostWhere(filter);
839
+ const total = countWhere(this.db, where);
840
+ const { max_id: maxId } = this.db.db
841
+ .prepare(`SELECT MAX(id) AS max_id FROM Posts ${where.sql}`)
842
+ .get(...where.params);
843
+ const keysetWhere = where.sql
844
+ ? `${where.sql} AND Posts.id > ? AND Posts.id <= ?`
845
+ : 'WHERE Posts.id > ? AND Posts.id <= ?';
846
+ const findBatch = this.db.db.prepare(`SELECT * FROM Posts ${keysetWhere} ORDER BY Posts.id ASC LIMIT ?`);
847
+ const outputPath = join(outputDir, name);
848
+ const temporaryPath = `${outputPath}.${randomUUID()}.tmp`;
849
+ let postCount = 0;
850
+ async function* lines(context) {
851
+ yield csvLine(GHOST_CSV_COLUMNS);
852
+ let afterId = 0;
853
+ while (maxId !== null) {
854
+ const rows = findBatch.all(...where.params, afterId, maxId, 200);
855
+ if (rows.length === 0) {
856
+ break;
857
+ }
858
+ const postIds = rows.map(row => row.id);
859
+ const placeholders = postIds.map(() => '?').join(',');
860
+ const tagRows = context.db.db
861
+ .prepare(`SELECT pt.post_id, t.data FROM PostTags pt JOIN Tags t ON t.id = pt.tag_id WHERE pt.post_id IN (${placeholders}) ORDER BY pt.post_id ASC, pt.sort_order ASC`)
862
+ .all(...postIds);
863
+ const authorRows = context.db.db
864
+ .prepare(`SELECT pa.post_id, a.data FROM PostAuthors pa JOIN Authors a ON a.id = pa.author_id WHERE pa.post_id IN (${placeholders}) ORDER BY pa.post_id ASC, pa.sort_order ASC`)
865
+ .all(...postIds);
866
+ const relations = new Map(postIds.map(id => [id, { authors: [], tags: [] }]));
867
+ for (const row of tagRows) {
868
+ const tag = JSON.parse(row.data);
869
+ relations.get(row.post_id).tags.push(tag.name);
870
+ }
871
+ for (const row of authorRows) {
872
+ const author = JSON.parse(row.data);
873
+ relations.get(row.post_id).authors.push({ name: author.name, email: author.email });
615
874
  }
616
- await fh.write('\n ],\n');
617
- await fh.write(` "users": ${pretty(users, 4)},\n`);
618
- await fh.write(` "tags": ${pretty(tags, 4)},\n`);
619
- await fh.write(` "posts_authors": ${pretty(postsAuthors, 4)},\n`);
620
- await fh.write(` "posts_tags": ${pretty(postsTags, 4)},\n`);
621
- await fh.write(` "posts_meta": ${pretty(postsMeta, 4)}\n`);
622
- await fh.write(' }\n}\n');
623
- }
624
- finally {
625
- await fh.close();
626
- }
627
- const fileStats = await stat(outputPath);
628
- const written = {
629
- path: resolve(outputPath),
630
- name: fileName,
631
- size: fileStats.size,
632
- posts: postCount
633
- };
634
- writtenFiles.push(written);
635
- if (onWrite) {
636
- onWrite(written);
637
- }
638
- }
639
- return writtenFiles;
640
- }
641
- async writeGhostTagsJson(outputDir, { filename = 'tags' } = {}) {
642
- const name = filename.replace(/\.json$/i, '') + '.json';
875
+ for (const row of rows) {
876
+ yield csvPostLine(JSON.parse(row.data), relations.get(row.id));
877
+ postCount += 1;
878
+ }
879
+ afterId = rows[rows.length - 1].id;
880
+ if (context.#emitEvents) {
881
+ context.#emitter.emit('progress', { operation: 'writeGhostCSV', processed: postCount, total });
882
+ }
883
+ }
884
+ }
885
+ try {
886
+ await pipeline(Readable.from(lines(this)), createWriteStream(temporaryPath, { encoding: 'utf8' }));
887
+ const fileStats = await stat(temporaryPath);
888
+ const written = { path: resolve(outputPath), name, size: fileStats.size, posts: postCount };
889
+ await rename(temporaryPath, outputPath);
890
+ if (this.#emitEvents) {
891
+ this.#emitter.emit('export:file-written', structuredClone(written));
892
+ }
893
+ return written;
894
+ }
895
+ finally {
896
+ await rm(temporaryPath, { force: true });
897
+ }
898
+ }
899
+ async writeGhostTagsJson(outputDir, { filename = 'tags', scope = 'referenced' } = {}) {
900
+ const name = exportBaseFilename(filename) + '.json';
901
+ await this.prepareForExport();
643
902
  await mkdir(outputDir, { recursive: true });
644
- const rows = this.db.stmts.findUsedTags.all();
903
+ const rows = (scope === 'all' ? this.db.stmts.findAllTags : this.db.stmts.findUsedTags).all();
645
904
  const tags = rows.map((r) => ({ id: r.ghost_id, ...JSON.parse(r.data) }));
646
905
  const outputPath = join(outputDir, name);
906
+ const temporaryPath = `${outputPath}.${randomUUID()}.tmp`;
647
907
  const content = JSON.stringify({
648
908
  meta: { exported_on: Date.now(), version: '2.0.0' },
649
909
  data: { tags }
650
910
  }, null, 2);
651
- await writeFile(outputPath, content);
652
- const fileStats = await stat(outputPath);
653
- return { path: resolve(outputPath), name, size: fileStats.size, posts: 0 };
911
+ try {
912
+ await writeFile(temporaryPath, content);
913
+ const fileStats = await stat(temporaryPath);
914
+ const written = { path: resolve(outputPath), name, size: fileStats.size, posts: 0 };
915
+ await rename(temporaryPath, outputPath);
916
+ if (this.#emitEvents) {
917
+ this.#emitter.emit('export:file-written', structuredClone(written));
918
+ }
919
+ return written;
920
+ }
921
+ finally {
922
+ await rm(temporaryPath, { force: true });
923
+ }
654
924
  }
655
- async writeGhostUsersJson(outputDir, { filename = 'users' } = {}) {
656
- const name = filename.replace(/\.json$/i, '') + '.json';
925
+ async writeGhostUsersJson(outputDir, { filename = 'users', scope = 'referenced' } = {}) {
926
+ const name = exportBaseFilename(filename) + '.json';
927
+ await this.prepareForExport();
657
928
  await mkdir(outputDir, { recursive: true });
658
- const rows = this.db.stmts.findUsedAuthors.all();
929
+ const rows = (scope === 'all' ? this.db.stmts.findAllAuthors : this.db.stmts.findUsedAuthors).all();
659
930
  const users = rows.map((r) => ({ id: r.ghost_id, ...JSON.parse(r.data) }));
660
931
  const outputPath = join(outputDir, name);
932
+ const temporaryPath = `${outputPath}.${randomUUID()}.tmp`;
661
933
  const content = JSON.stringify({
662
934
  meta: { exported_on: Date.now(), version: '2.0.0' },
663
935
  data: { users }
664
936
  }, null, 2);
665
- await writeFile(outputPath, content);
666
- const fileStats = await stat(outputPath);
667
- return { path: resolve(outputPath), name, size: fileStats.size, posts: 0 };
937
+ try {
938
+ await writeFile(temporaryPath, content);
939
+ const fileStats = await stat(temporaryPath);
940
+ const written = { path: resolve(outputPath), name, size: fileStats.size, posts: 0 };
941
+ await rename(temporaryPath, outputPath);
942
+ if (this.#emitEvents) {
943
+ this.#emitter.emit('export:file-written', structuredClone(written));
944
+ }
945
+ return written;
946
+ }
947
+ finally {
948
+ await rm(temporaryPath, { force: true });
949
+ }
668
950
  }
669
951
  }
670
952
  //# sourceMappingURL=MigrateContext.js.map