@tryghost/mg-substack 1.14.0-0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -31,7 +31,7 @@ migrate substack --pathToZip /path/to/my-export.zip --url https://example.com
31
31
  A more complex command for a Substack migration looks like this:
32
32
 
33
33
  ```sh
34
- migrate substack --pathToZip /path/to/my-export.zip --url https://example.com --email 'person@example.com' --drafts false
34
+ migrate substack --pathToZip /path/to/my-export.zip --url https://example.com --email 'person@example.com' --useMetaAuthor false --drafts false
35
35
  ```
36
36
 
37
37
  ```sh
@@ -52,6 +52,9 @@ It's possible to pass more options, in order to achieve a better migration file
52
52
  - **`--zip`**
53
53
  - Create a zip file
54
54
  - bool - default: `true`
55
+ - **`--report`**
56
+ - Write a `.report.json` migration report beside the import, or a `.failed-report.json` if the run fails
57
+ - bool - default: `false`
55
58
  - **`-s` `--scrape`**
56
59
  - Configure scraping tasks
57
60
  - string - default: `all`
@@ -61,8 +64,8 @@ It's possible to pass more options, in order to achieve a better migration file
61
64
  - `assets`: Only download assets (images, media, files)
62
65
  - `none`: Skip all scraping tasks
63
66
  - **`-e` `--email`**
64
- - Provide an email domain for users e.g. `person@example.com` (Is ignored if `--useMetaAuthor` is provided)
65
- - bool/string - default: `false`
67
+ - Provide an email for users e.g. `person@example.com` to create a general user with slug `person` (Is ignored unless `--useMetaAuthor false` is provided)
68
+ - string - default: `null`
66
69
  - **`--addTag`**
67
70
  - string - default: `null`
68
71
  - Provide a tag name which should be added to every post in this migration (Wrap in single quotes if tag name has spaces `'Like This'`)
@@ -117,16 +120,87 @@ It's possible to pass more options, in order to achieve a better migration file
117
120
  - **`--postsAfter`**
118
121
  - Only migrate posts after and including a given date e.g. 'August 16 2023'
119
122
  - string - default: `null`
120
- - **`--fallBackHTMLCard`**
121
- - Fall back to convert to HTMLCard, if standard Mobiledoc convert fails
122
- - bool - default: `true`
123
+ - **`--wait_after_scrape`**
124
+ - Time in ms to wait after a URL is scraped
125
+ - number - default: `2000`
126
+ - **`--rereadSource`**
127
+ - Read the export zip again, replacing the stored source while preserving downloaded assets
128
+ - bool - default: `false`
129
+ - **`--postsPerFile`**
130
+ - Maximum posts written per Ghost import JSON file
131
+ - number - default: `2000`
123
132
  - **`--cache`**
124
133
  - Persist local cache after migration is complete (Only if `--zip` is `true`)
125
134
  - bool - default: `true`
135
+ - **`--tmpPath`**
136
+ - Specify the full path where the temporary files will be stored (Defaults a hidden tmp dir)
137
+ - string - default: `null`
138
+ - **`--outputPath`**
139
+ - Specify the full path where the final zip file will be saved to (Defaults to CWD)
140
+ - string - default: `null`
141
+ - **`--cacheName`**
142
+ - Provide a unique name for the cache directory
143
+ - string - default: one based on the export's full path
144
+ - **`--ghostApiUrl`**, **`--ghostAdminKey`**
145
+ - Match the `--email` author to an existing Ghost user by email
146
+ - string - default: `null`
126
147
 
127
148
  **Note**: You can combine `--postsBefore` and `--postsAfter` to migrate posts between 2 dates.
128
149
 
129
150
 
151
+ ## Output
152
+
153
+ The import contains HTML; Ghost's importer converts it. `--fallBackHTMLCard` has been removed. A small migration writes `ghost-import.json`, and larger ones write `ghost-import-1.json`, `ghost-import-2.json` and so on, `--postsPerFile` posts each. With `--report`, a `.report.json` beside the ZIP (or in the workspace when `--zip false`) lists imported and skipped counts with diagnostics for duplicate rows, skipped posts, field changes, slug changes and optional scraping failures. Posts with an invalid date, or without an HTML file in the export, are skipped and reported. When every selected post is invalid, or the run fails, `--report` writes a `.failed-report.json` instead. An intentionally empty selection succeeds.
154
+
155
+
156
+ ## Source storage
157
+
158
+ The first run stores the export in an `mg-context` SQLite database in the workspace; later runs map the stored export again without reading the zip, even if it has moved. Use `--rereadSource` to read it again. Without `--cacheName`, the workspace is keyed by the export's full path, so exports that share a file name do not share stored data.
159
+
160
+ Each row of `posts.csv` is stored as a `post` record keyed by its `post_id` (such as `123401.plain-text`), and each `posts/*.html` file as an `html` record keyed by its file name. The zip is read one entry at a time, and may hold its files inside a single top-level directory. A `post_id` or file name that appears twice keeps its first record and reports a `source:conflict`.
161
+
162
+ Every option applies when the stored records are mapped, so changing a filter, tag, author or content option needs no new read. Mapping joins each row to its HTML file and follows the order of `posts.csv`. Ghost IDs derive from `--url` and the `post_id`, tag slug or author, so they stay the same across runs. Posts that were never given a date are dated when the export was read, so their dates also stay the same across runs.
163
+
164
+ Web scraping happens after mapping. For each published post, the scraped metadata, the section and post tags (placed before the other tags) and, with `--useMetaAuthor`, the ld+json authors are applied to the mapped post, and its HTML is converted again from the stored export with the scraped `og:image` and podcast audio. Scraped pages are cached in the workspace.
165
+
166
+
167
+ ## Programmatic API
168
+
169
+ The package exports `parse`, `ingest`, `map` and `applyScrapedData` for use with `@tryghost/mg-context`. The caller owns the context, scraping, export and closure:
170
+
171
+ ```js
172
+ import {MigrateContext} from '@tryghost/mg-context';
173
+ import {ingest, map} from '@tryghost/mg-substack';
174
+
175
+ const context = new MigrateContext({dbPath: './migration.sqlite'});
176
+ const rereadSource = process.argv.includes('--rereadSource');
177
+ await context.init();
178
+ try {
179
+ if (!context.sources.hasCompletedIngestion || rereadSource) {
180
+ await ingest('/path/to/export.zip', context, {replace: rereadSource});
181
+ }
182
+ const summary = await map({url: 'https://example.substack.com', drafts: false}, context);
183
+ for await (const file of context.writeGhostJsonStream('./output', {filename: 'ghost-import'})) {
184
+ // Consume one file descriptor at a time.
185
+ }
186
+ await context.writeMigrationReport('./migration.report.json', summary);
187
+ } finally {
188
+ await context.close();
189
+ }
190
+ ```
191
+
192
+ - `ingest(pathToZip, context, {replace})` reads the export into `context.sources` inside `context.sources.ingest()`. Explicit `replace: true` is required when completed source data exists; a failed read keeps the previous data. An export without `posts.csv` is rejected.
193
+ - `parse(pathToZip)` yields the same records as `SourceRecordInput` values, one at a time, without storing them.
194
+ - `map(options, context, {ghostUsers?})` rebuilds mapped content and returns `{selected, imported, skipped}`. `options.url` is required; the other options are the CLI's, with the CLI's defaults. `ghostUsers` may be an iterable or async iterable of existing Ghost users; an `email` author whose email matches keeps that user's Ghost ID.
195
+ - `applyScrapedData(post, scraped, context, options)` applies post-processed scrape results to a mapped post, as the CLI's scrape step does. The caller saves the post.
196
+ - `postUrl(row, url)` returns a `posts.csv` row's public URL, and `contentStats(pathToZip)` counts the export's post HTML files.
197
+ - `processContent`, `getImageDimensions` and `largeImageUrl` convert Substack HTML and image URLs.
198
+
199
+ The previous default export (`ingest(ctx)` and `process(input, ctx)`, which built arrays of posts in memory) has been removed.
200
+
201
+ The CLI's programmatic `outputStorage.upload({body, fileName, size})` receives a Node readable stream as `body`, for the ZIP and, with `--report`, the report, and must consume it before resolving to the remote path. The uploaded ZIP is named like the local one, such as `gh-substack-my-export-1700000000000.zip`.
202
+
203
+
130
204
  ## Develop
131
205
 
132
206
  This is a mono repository, managed with [Nx](https://nx.dev/) and pnpm workspaces.
@@ -147,7 +221,7 @@ pnpm dev substack <pathToZip>
147
221
 
148
222
  ## Test
149
223
 
150
- - `pnpm test` runs the package tests
224
+ - `pnpm test:local` builds the package and runs its tests with 100% coverage
151
225
  - Linting and formatting are run from the repo root (`pnpm lint`, `pnpm format`)
152
226
 
153
227
 
@@ -0,0 +1,5 @@
1
+ export { contentStats, ingest, parse } from './lib/ingest.js';
2
+ export { applyScrapedData, ghostId, map, postUrl } from './lib/map.js';
3
+ export { processContent, getImageDimensions, largeImageUrl } from './lib/process.js';
4
+ export type { MappingServices, MappingSummary } from './lib/map.js';
5
+ export type { ContentOptions, ContentPost, ScrapedData, ScrapedRelation, SubstackOptions, SubstackRow } from './lib/types.js';
package/build/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { contentStats, ingest, parse } from './lib/ingest.js';
2
+ export { applyScrapedData, ghostId, map, postUrl } from './lib/map.js';
3
+ export { processContent, getImageDimensions, largeImageUrl } from './lib/process.js';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,YAAY,EAAE,MAAM,EAAE,KAAK,EAAC,MAAM,iBAAiB,CAAC;AAC5D,OAAO,EAAC,gBAAgB,EAAE,OAAO,EAAE,GAAG,EAAE,OAAO,EAAC,MAAM,cAAc,CAAC;AACrE,OAAO,EAAC,cAAc,EAAE,kBAAkB,EAAE,aAAa,EAAC,MAAM,kBAAkB,CAAC"}
@@ -0,0 +1,18 @@
1
+ import type { MigrateContext, SourceRecordInput } from '@tryghost/mg-context';
2
+ /** Count the post HTML files in a Substack export without reading them. */
3
+ export declare function contentStats(pathToZip: string): Promise<{
4
+ posts: number;
5
+ }>;
6
+ /**
7
+ * Yield the export's originals one at a time without storing them: each `posts.csv` row as a `post` record keyed
8
+ * by its `post_id`, and each `posts/*.html` file as an `html` record keyed by its file name.
9
+ */
10
+ export declare function parse(pathToZip: string): AsyncGenerator<SourceRecordInput>;
11
+ /**
12
+ * Read a Substack export zip into `context.sources`. A `post_id` or file name that appears twice keeps its first
13
+ * record, and a differing duplicate is reported as a `source:conflict`. Explicit `replace: true` is required when
14
+ * completed source data exists; a failed read keeps the previous data.
15
+ */
16
+ export declare function ingest(pathToZip: string, context: MigrateContext, { replace }?: {
17
+ replace?: boolean;
18
+ }): Promise<void>;
@@ -0,0 +1,62 @@
1
+ import { basename } from 'node:path';
2
+ import fsUtils from '@tryghost/mg-fs-utils';
3
+ // A Substack export holds `posts.csv` and `posts/<id>.<slug>.html`, optionally inside one top-level directory.
4
+ const isPostsCsv = (name) => name === 'posts.csv' || name.endsWith('/posts.csv');
5
+ const isPostHtml = (name) => /^posts\/.*\.html$/.test(name) || /\/posts\/.*\.html$/.test(name);
6
+ const isContent = (entry) => !entry.isDirectory && (isPostsCsv(entry.name) || isPostHtml(entry.name));
7
+ /** Count the post HTML files in a Substack export without reading them. */
8
+ export async function contentStats(pathToZip) {
9
+ let posts = 0;
10
+ for await (const entry of fsUtils.zip.entries(pathToZip, { filter: isContent })) {
11
+ posts += Number(isPostHtml(entry.name));
12
+ }
13
+ return { posts };
14
+ }
15
+ /**
16
+ * Yield the export's originals one at a time without storing them: each `posts.csv` row as a `post` record keyed
17
+ * by its `post_id`, and each `posts/*.html` file as an `html` record keyed by its file name.
18
+ */
19
+ export async function* parse(pathToZip) {
20
+ let csvFiles = 0;
21
+ for await (const entry of fsUtils.zip.entries(pathToZip, { filter: isContent })) {
22
+ if (isPostsCsv(entry.name)) {
23
+ csvFiles += 1;
24
+ let row = 0;
25
+ for await (const data of fsUtils.csv.streamRows(await entry.stream())) {
26
+ row += 1;
27
+ yield {
28
+ kind: 'post',
29
+ key: data.post_id || undefined,
30
+ content: JSON.stringify(data),
31
+ format: 'json',
32
+ metadata: { file: entry.path, row }
33
+ };
34
+ }
35
+ }
36
+ else {
37
+ yield {
38
+ kind: 'html',
39
+ key: basename(entry.name),
40
+ content: (await entry.read()).toString('utf8'),
41
+ format: 'html',
42
+ metadata: { file: entry.path }
43
+ };
44
+ }
45
+ }
46
+ if (!csvFiles) {
47
+ throw new Error(`${pathToZip}: No posts.csv found in the Substack export`);
48
+ }
49
+ }
50
+ /**
51
+ * Read a Substack export zip into `context.sources`. A `post_id` or file name that appears twice keeps its first
52
+ * record, and a differing duplicate is reported as a `source:conflict`. Explicit `replace: true` is required when
53
+ * completed source data exists; a failed read keeps the previous data.
54
+ */
55
+ export async function ingest(pathToZip, context, { replace = false } = {}) {
56
+ await context.sources.ingest({ replace, metadata: { adapter: 'substack', file: basename(pathToZip) } }, async (stage) => {
57
+ for await (const record of parse(pathToZip)) {
58
+ stage.reconcile(record);
59
+ }
60
+ });
61
+ }
62
+ //# sourceMappingURL=ingest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ingest.js","sourceRoot":"","sources":["../../src/lib/ingest.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,QAAQ,EAAC,MAAM,WAAW,CAAC;AACnC,OAAO,OAAO,MAAM,uBAAuB,CAAC;AAG5C,+GAA+G;AAC/G,MAAM,UAAU,GAAG,CAAC,IAAY,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,SAAS,CAAC,MAAM,CAAC,CAAC;QAC5B,CAAC;IACL,CAAC,CAAC,CAAC;AACP,CAAC"}
@@ -0,0 +1,24 @@
1
+ import { MigrateContext, PostContext } from '@tryghost/mg-context';
2
+ import type { MappingSummary } from '@tryghost/mg-context';
3
+ import type { GhostUser } from '@tryghost/mg-ghost-authors';
4
+ import type { ScrapedData, SubstackOptions, SubstackRow } from './types.js';
5
+ export type { MappingSummary };
6
+ export interface MappingServices {
7
+ /** Existing Ghost users; an `--email` author with a matching email keeps that user's ID. */
8
+ ghostUsers?: Iterable<GhostUser> | AsyncIterable<GhostUser>;
9
+ }
10
+ export declare function ghostId(site: string, kind: string, key: string): string;
11
+ /** The URL a `posts.csv` row's post was published at, such as `https://example.substack.com/p/my-post`. */
12
+ export declare function postUrl(row: SubstackRow, url: string): string;
13
+ /**
14
+ * Rebuild posts, pages, tags and authors from the stored `posts.csv` rows and their HTML files. Every filter and
15
+ * content option applies here, so changing one needs no new read of the export. Records with an invalid date or
16
+ * no HTML file are skipped with a `record:skipped` diagnostic.
17
+ */
18
+ export declare function map(options: SubstackOptions, context: MigrateContext, services?: MappingServices): Promise<MappingSummary>;
19
+ /**
20
+ * Apply a scraped post page to a mapped post: schema fields such as `meta_title` and `og_image`, the section and
21
+ * post tags (placed before the mapped tags), the ld+json authors, and the HTML again with the scraped `og_image`
22
+ * and podcast audio, re-converted from the stored export HTML. The caller saves the post.
23
+ */
24
+ export declare function applyScrapedData(post: PostContext, scraped: ScrapedData, context: MigrateContext, options: SubstackOptions): void;
@@ -0,0 +1,302 @@
1
+ import { PostContext, TagContext, AuthorContext, MappingState, RecordDataError, ghostId as coreGhostId } from '@tryghost/mg-context';
2
+ import { mergeUsersWithGhost } from '@tryghost/mg-ghost-authors';
3
+ import { slugify } from '@tryghost/string';
4
+ import { dateUtils, stringUtils, urlUtils } from '@tryghost/mg-utils';
5
+ import { decode } from 'he';
6
+ import { processContent } from './process.js';
7
+ const ROLES = ['Contributor', 'Author', 'Editor', 'Administrator'];
8
+ /** The CLI's defaults, used for options the caller leaves undefined. */
9
+ const DEFAULTS = {
10
+ posts: true,
11
+ drafts: true,
12
+ pages: true,
13
+ podcasts: true,
14
+ threads: false,
15
+ useMetaImage: true,
16
+ useFirstImage: true,
17
+ useMetaAuthor: true,
18
+ addPlatformTag: true,
19
+ addTypeTag: true,
20
+ addAccessTag: true,
21
+ comments: true,
22
+ noSubscribeButtons: false,
23
+ subscribeLink: '#/portal/signup',
24
+ commentLink: '#ghost-comments-root'
25
+ };
26
+ /** The site URL without trailing slashes. */
27
+ function siteUrl(value) {
28
+ if (!urlUtils.httpUrl(value)) {
29
+ throw new Error('Substack migrations need the site URL (--url) as an HTTP or HTTPS URL.');
30
+ }
31
+ return urlUtils.trimTrailingSlashes(value.trim());
32
+ }
33
+ function resolveOptions(options) {
34
+ const resolved = { ...DEFAULTS };
35
+ for (const [key, value] of Object.entries(options)) {
36
+ if (value !== undefined) {
37
+ resolved[key] = value;
38
+ }
39
+ }
40
+ resolved.url = siteUrl(options.url);
41
+ return resolved;
42
+ }
43
+ export function ghostId(site, kind, key) {
44
+ return coreGhostId('mg-substack:1', site, kind, key);
45
+ }
46
+ function postSlug(postId) {
47
+ return postId.replace(/^(?:\d{1,10}\.)(\S*)/gm, '$1');
48
+ }
49
+ /** The URL a `posts.csv` row's post was published at, such as `https://example.substack.com/p/my-post`. */
50
+ export function postUrl(row, url) {
51
+ return `${siteUrl(url)}/p/${postSlug(row.post_id)}`;
52
+ }
53
+ /** Substack writes ISO dates in UTC; a zoneless timestamp is read as UTC too. */
54
+ function rowDate(row) {
55
+ if (!row.post_date?.trim()) {
56
+ return undefined;
57
+ }
58
+ const date = dateUtils.parseDate(row.post_date);
59
+ if (!date) {
60
+ throw new RecordDataError('Invalid Substack post date');
61
+ }
62
+ return date;
63
+ }
64
+ function selected(row, options) {
65
+ const type = (row.type ?? '').toLowerCase();
66
+ return !((type === 'newsletter' && !options.posts) ||
67
+ (type === 'page' && !options.pages) ||
68
+ (type === 'thread' && !options.threads) ||
69
+ (type === 'podcast' && !options.podcasts) ||
70
+ ((row.is_published ?? '').toLowerCase() !== 'true' && !options.drafts));
71
+ }
72
+ /** Posts without a date are left out of date-bounded migrations. */
73
+ function inDateRange(date, options) {
74
+ if (options.postsAfter && !(date && date > new Date(options.postsAfter))) {
75
+ return false;
76
+ }
77
+ if (options.postsBefore) {
78
+ const end = new Date(options.postsBefore);
79
+ end.setDate(end.getDate() + 1);
80
+ return Boolean(date && date < end);
81
+ }
82
+ return true;
83
+ }
84
+ /** Convert a post's export HTML, using scraped values when the runner has them. */
85
+ function renderContent(row, html, options, scraped = {}) {
86
+ const slug = postSlug(row.post_id);
87
+ const post = {
88
+ substackPodcastURL: row.podcast_url || false,
89
+ data: {
90
+ html,
91
+ title: row.title || slug,
92
+ slug,
93
+ og_image: scraped.og_image,
94
+ podcast_audio_src: scraped.podcast_audio_src
95
+ }
96
+ };
97
+ processContent(post, options.url, options);
98
+ return {
99
+ html: post.data.html,
100
+ feature_image: post.data.feature_image ?? null,
101
+ feature_image_caption: post.data.feature_image_caption ?? null
102
+ };
103
+ }
104
+ /** Substack tags are identified by slug, so tags that share a slug are one Ghost tag. */
105
+ function tagEntity(name, slug, site) {
106
+ if (name.startsWith('#') && !slug.startsWith('hash-')) {
107
+ slug = `hash-${slug}`;
108
+ }
109
+ const tag = new TagContext({ name, slug });
110
+ tag.ghostId = ghostId(site, 'tag', slug);
111
+ return tag;
112
+ }
113
+ /** The type, `--addTag`, platform, type and access tags for a row. */
114
+ function rowTags(row, options) {
115
+ const type = slugify(row.type ?? '');
116
+ const access = slugify(row.audience ?? '');
117
+ const tags = [{ name: stringUtils.startCase(type), slug: type }];
118
+ if (options.addTag?.trim()) {
119
+ tags.push({ name: options.addTag.trim(), slug: slugify(options.addTag.trim()) });
120
+ }
121
+ if (options.addPlatformTag) {
122
+ tags.push({ name: '#substack', slug: 'hash-substack' });
123
+ }
124
+ if (options.addTypeTag) {
125
+ tags.push({ name: `#substack-type-${type}`, slug: `hash-substack-type-${type}` });
126
+ }
127
+ if (options.addAccessTag) {
128
+ tags.push({ name: `#substack-access-${access}`, slug: `hash-substack-access-${access}` });
129
+ }
130
+ return tags.filter(tag => tag.name);
131
+ }
132
+ function emailAuthor(state, email, site) {
133
+ const context = state.context;
134
+ const key = `email:${email.toLowerCase()}`;
135
+ const binding = state.getBinding('author', key);
136
+ if (binding) {
137
+ return AuthorContext.fromRow(context.db.stmts.findAuthorById.get(binding));
138
+ }
139
+ const slug = slugify(email.replace(/(^[\w_-]*)(@[\w_-]*\.\w*(?:\.\w{0,2})?)/, '$1'));
140
+ let data = { name: stringUtils.startCase(slug), slug, email, roles: ['Contributor'] };
141
+ const match = state.get('ghost-user', email.toLowerCase());
142
+ if (match) {
143
+ data = { ...mergeUsersWithGhost([{ url: '', data: data }], [match])[0].data };
144
+ }
145
+ const id = data.id || ghostId(site, 'author', key);
146
+ delete data.id;
147
+ if (data.roles.some((role) => !ROLES.includes(role))) {
148
+ context.recordDiagnostic('operation:warning', {
149
+ author: key,
150
+ reason: 'Unsupported author roles replaced by supported Ghost roles'
151
+ });
152
+ data.roles = data.roles.filter((role) => ROLES.includes(role));
153
+ if (!data.roles.length) {
154
+ data.roles = ['Contributor'];
155
+ }
156
+ }
157
+ data.slug = state.uniqueSlug('author', data.slug, id);
158
+ const entity = new AuthorContext();
159
+ for (const [field, value] of Object.entries(data)) {
160
+ if (value !== undefined) {
161
+ entity.set(field, value);
162
+ }
163
+ }
164
+ entity.ghostId = id;
165
+ entity.save(context.db);
166
+ state.bind('author', key, entity.dbId);
167
+ return entity;
168
+ }
169
+ /**
170
+ * Rebuild posts, pages, tags and authors from the stored `posts.csv` rows and their HTML files. Every filter and
171
+ * content option applies here, so changing one needs no new read of the export. Records with an invalid date or
172
+ * no HTML file are skipped with a `record:skipped` diagnostic.
173
+ */
174
+ export async function map(options, context, services = {}) {
175
+ if (!context.sources.hasCompletedIngestion) {
176
+ throw new Error('Ingest a complete Substack export before mapping.');
177
+ }
178
+ const resolved = resolveOptions(options);
179
+ for (const name of ['postsBefore', 'postsAfter']) {
180
+ if (resolved[name] && !Number.isFinite(Date.parse(resolved[name]))) {
181
+ throw new Error(`Invalid ${name} date: ${resolved[name]}`);
182
+ }
183
+ }
184
+ const site = urlUtils.canonicalSite(resolved.url);
185
+ // Posts never given a date are dated when the export was read, so remapping keeps their dates.
186
+ const readAt = new Date(context.sources.currentIngestion.completedAt);
187
+ const state = new MappingState(context, 'mg-substack');
188
+ return context.rebuildMappedContent(async () => {
189
+ for await (const user of services.ghostUsers ?? []) {
190
+ state.reserveSlug('author', user.slug, user.id);
191
+ if (user.email) {
192
+ state.set('ghost-user', user.email.toLowerCase(), user);
193
+ }
194
+ }
195
+ return context.mapRecords(context.sources.records({ kind: 'post' }), async (record) => {
196
+ const row = JSON.parse(record.content);
197
+ if (!selected(row, resolved)) {
198
+ return false;
199
+ }
200
+ const date = rowDate(row);
201
+ if (!inDateRange(date, resolved)) {
202
+ return false;
203
+ }
204
+ if (!record.key) {
205
+ throw new RecordDataError('Row has no post_id');
206
+ }
207
+ const source = context.sources.get('html', `${record.key}.html`);
208
+ if (!source) {
209
+ throw new RecordDataError('No HTML file in the export for this post');
210
+ }
211
+ const slug = postSlug(record.key);
212
+ const post = new PostContext({ lookupKey: record.key });
213
+ post.ghostId = ghostId(site, 'post', record.key);
214
+ post.set('title', row.title || slug);
215
+ post.set('slug', slug);
216
+ post.set('comment_id', record.key.replace(/\..*$/, ''));
217
+ post.set('created_at', date ?? readAt);
218
+ post.set('updated_at', date ?? readAt);
219
+ post.set('published_at', date ?? readAt);
220
+ post.set('custom_excerpt', row.subtitle ? decode(row.subtitle) : null);
221
+ post.set('type', slugify(row.type ?? '') === 'page' ? 'page' : 'post');
222
+ post.set('status', (row.is_published ?? '').toLowerCase() === 'true' ? 'published' : 'draft');
223
+ post.set('visibility', row.audience === 'only_paid' ? 'paid' : row.audience === 'only_free' ? 'members' : 'public');
224
+ for (const [field, value] of Object.entries(renderContent(row, source.content, resolved))) {
225
+ post.set(field, value);
226
+ }
227
+ if (resolved.email && !resolved.useMetaAuthor) {
228
+ const author = emailAuthor(state, resolved.email, site);
229
+ post.addAuthor(author);
230
+ context.sources.link(record.id, { type: 'author', id: author.dbId });
231
+ }
232
+ for (const { name, slug: tagSlug } of rowTags(row, resolved).sort((a, b) => Number(a.name.startsWith('#')) - Number(b.name.startsWith('#')))) {
233
+ const tag = tagEntity(name, tagSlug, site);
234
+ tag.save(context.db);
235
+ post.addTag(tag);
236
+ context.sources.link(record.id, { type: 'tag', id: tag.dbId });
237
+ }
238
+ post.save(context.db);
239
+ context.sources.link(record.id, { type: 'post', id: post.dbId });
240
+ context.sources.link(source.id, { type: 'post', id: post.dbId });
241
+ context.addLink(stringUtils.cleanURL(postUrl(row, resolved.url)), `/${post.get('slug')}/`);
242
+ });
243
+ });
244
+ }
245
+ function scrapedAuthor({ data }, site) {
246
+ const author = new AuthorContext({
247
+ name: data.name,
248
+ slug: data.slug,
249
+ email: data.email || `${data.slug}@example.com`,
250
+ profile_image: data.profile_image ?? null,
251
+ roles: ['Contributor']
252
+ });
253
+ author.ghostId = ghostId(site, 'author', `slug:${data.slug}`);
254
+ return author;
255
+ }
256
+ /**
257
+ * Apply a scraped post page to a mapped post: schema fields such as `meta_title` and `og_image`, the section and
258
+ * post tags (placed before the mapped tags), the ld+json authors, and the HTML again with the scraped `og_image`
259
+ * and podcast audio, re-converted from the stored export HTML. The caller saves the post.
260
+ */
261
+ export function applyScrapedData(post, scraped, context, options) {
262
+ const resolved = resolveOptions(options);
263
+ const site = urlUtils.canonicalSite(resolved.url);
264
+ for (const [field, value] of Object.entries(scraped)) {
265
+ if (field !== 'tags' &&
266
+ field !== 'authors' &&
267
+ field in post.schema.shape &&
268
+ value !== null &&
269
+ value !== undefined &&
270
+ value !== '') {
271
+ post.set(field, value);
272
+ }
273
+ }
274
+ if (scraped.og_image || scraped.podcast_audio_src) {
275
+ const row = JSON.parse(context.sources.get('post', post.lookupKey).content);
276
+ const html = context.sources.get('html', `${post.lookupKey}.html`).content;
277
+ for (const [field, value] of Object.entries(renderContent(row, html, resolved, scraped))) {
278
+ post.set(field, value);
279
+ }
280
+ }
281
+ const order = new Map();
282
+ for (const { data } of scraped.tags ?? []) {
283
+ if (!data.name?.trim()) {
284
+ continue;
285
+ }
286
+ const tag = tagEntity(data.name, data.slug, site);
287
+ if (!order.has(tag.data.slug)) {
288
+ order.set(tag.data.slug, order.size);
289
+ }
290
+ post.addTag(tag);
291
+ }
292
+ if (order.size) {
293
+ post.setTagOrder(tags => {
294
+ const rank = (tag) => Number(tag.data.name.startsWith('#')) * 2 * tags.length + (order.get(tag.data.slug) ?? order.size);
295
+ return [...tags].sort((a, b) => rank(a) - rank(b));
296
+ });
297
+ }
298
+ for (const author of scraped.authors ?? []) {
299
+ post.addAuthor(scrapedAuthor(author, site));
300
+ }
301
+ }
302
+ //# sourceMappingURL=map.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"map.js","sourceRoot":"","sources":["../../src/lib/map.ts"],"names":[],"mappings":"AAAA,OAAO,EAEH,WAAW,EACX,UAAU,EACV,aAAa,EACb,YAAY,EACZ,eAAe,EACf,OAAO,IAAI,WAAW,EACzB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAC,mBAAmB,EAAC,MAAM,4BAA4B,CAAC;AAE/D,OAAO,EAAC,OAAO,EAAC,MAAM,kBAAkB,CAAC;AACzC,OAAO,EAAC,SAAS,EAAE,WAAW,EAAE,QAAQ,EAAC,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAC,MAAM,EAAC,MAAM,IAAI,CAAC;AAC1B,OAAO,EAAC,cAAc,EAAC,MAAM,cAAc,CAAC;AAU5C,MAAM,KAAK,GAAG,CAAC,aAAa,EAAE,QAAQ,EAAE,QAAQ,EAAE,eAAe,CAAC,CAAC;AAEnE,wEAAwE;AACxE,MAAM,QAAQ,GAAG;IACb,KAAK,EAAE,IAAI;IACX,MAA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,EAAE,EAAE,CAAC;YACrB,SAAS;QACb,CAAC;QACD,MAAM,GAAG,GAAG,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QAClD,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YAC5B,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;QACzC,CAAC;QACD,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IACrB,CAAC;IACD,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC;QACb,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE;YACpB,MAAM,IAAI,GAAG,CAAC,GAAe,EAAE,EAAE,CAC7B,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC;YACvG,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACvD,CAAC,CAAC,CAAC;IACP,CAAC;IACD,KAAK,MAAM,MAAM,IAAI,OAAO,CAAC,OAAO,IAAI,EAAE,EAAE,CAAC;QACzC,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;IAChD,CAAC;AACL,CAAC"}
@@ -0,0 +1,15 @@
1
+ import type { ContentOptions, ContentPost } from './types.js';
2
+ declare const largeImageUrl: (path: string) => string;
3
+ declare const getImageDimensions: (str: string) => {
4
+ width: number;
5
+ height: number;
6
+ } | false;
7
+ /**
8
+ * Convert Substack's export HTML into Ghost-compatible HTML, in place on `post.data`.
9
+ *
10
+ * Reads `post.data.html`, the optional scraped `og_image` and `podcast_audio_src`, and `post.substackPodcastURL`
11
+ * (from `posts.csv`). Writes `post.data.html`, and `feature_image`/`feature_image_caption` when the first image
12
+ * becomes the feature image.
13
+ */
14
+ declare const processContent: (post: ContentPost, siteUrl: string, options: ContentOptions) => ContentPost;
15
+ export { processContent, getImageDimensions, largeImageUrl };