@tryghost/mg-linkfixer 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,4 +1,6 @@
1
- # Migrate Linkfixer
1
+ # Migrate LinkFixer
2
+
3
+ Finds and replaces internal links in migrated content. During a migration, post URLs change from their original form (e.g. `https://example.com/2020/06/27/my-post/`) to relative Ghost paths (e.g. `/my-post/`). LinkFixer scans HTML and Lexical content for links that point to known posts, pages, tags, and authors, and rewrites them to the correct relative URLs.
2
4
 
3
5
  ## Install
4
6
 
@@ -8,9 +10,176 @@ or
8
10
 
9
11
  `pnpm add @tryghost/mg-linkfixer`
10
12
 
11
-
12
13
  ## Usage
13
14
 
15
+ LinkFixer operates on a migration context object (`ctx`) that is shared across all steps of a migration pipeline. It works in two steps:
16
+
17
+ 1. **Build a link map** from `ctx` — scans all posts, pages, tags, and authors to create a mapping of original URLs to relative Ghost paths
18
+ 2. **Fix links** — scans HTML and Lexical fields in the Ghost JSON output and replaces any matched URLs
19
+
20
+ ### The `ctx` object
21
+
22
+ `ctx` is the shared migration context passed through every step of a migration pipeline. LinkFixer reads from two parts of it:
23
+
24
+ **`ctx.options`** — configuration for the migration:
25
+
26
+ | Property | Type | Description |
27
+ |-------------------|------------------------|--------------------------------------------------------------------------------------------------------------------------|
28
+ | `url` | `string` or `string[]` | The source site URL(s). When an array is provided, links to any of the domains are recognized as internal and rewritten. |
29
+ | `datedPermalinks` | `string` (optional) | The dated permalink format used by the source site. See [Dated permalinks](#dated-permalinks). |
30
+
31
+ **`ctx.result`** (or `ctx.data`) — the migration data. LinkFixer reads from `ctx.result.posts` (falling back to `ctx.data.posts`), where each post has:
32
+
33
+ | Property | Type | Description |
34
+ |----------------|----------------------|-------------------------------------------------------------------------|
35
+ | `url` | `string` | The original full URL of the post (e.g. `https://example.com/my-post/`) |
36
+ | `data.slug` | `string` | The post slug, used as the target path when rewriting |
37
+ | `data.html` | `string` | HTML content — scanned for `<a>` links to rewrite |
38
+ | `data.lexical` | `string` (optional) | Lexical JSON content — scanned for `url` properties to rewrite |
39
+ | `data.tags` | `array` (optional) | Tags with `url` and `data.slug` — mapped to `/tag/{slug}/` |
40
+ | `data.author` | `object` (optional) | Author with `url` and `data.slug` — mapped to `/author/{slug}/` |
41
+ | `data.authors` | `array` (optional) | Authors array, same shape as `data.author` |
42
+
43
+ After `fix()` runs, the rewritten content is written back to `ctx.result.data.posts` (the Ghost JSON output).
44
+
45
+ ### Basic example
46
+
47
+ ```javascript
48
+ import LinkFixer from '@tryghost/mg-linkfixer';
49
+
50
+ const linkFixer = new LinkFixer();
51
+
52
+ linkFixer.buildMap(ctx);
53
+
54
+ // After converting to Ghost JSON format, fix links in the output.
55
+ // `task` is a Listr task reference (used for skip messaging when the link map is empty).
56
+ const tasks = linkFixer.fix(ctx, task);
57
+ ```
58
+
59
+ ### Integration with a migration pipeline
60
+
61
+ LinkFixer is typically used as part of a Listr task chain in a source adapter:
62
+
63
+ ```javascript
64
+ import LinkFixer from '@tryghost/mg-linkfixer';
65
+ import {makeTaskRunner} from '@tryghost/listr-smart-renderer';
66
+
67
+ const tasks = [
68
+ {
69
+ title: 'Initialise',
70
+ task: (ctx) => {
71
+ ctx.linkFixer = new LinkFixer();
72
+ }
73
+ },
74
+ // ... ingest and format data ...
75
+ {
76
+ title: 'Build Link Map',
77
+ task: (ctx) => {
78
+ ctx.linkFixer.buildMap(ctx);
79
+ }
80
+ },
81
+ // ... convert to Ghost JSON, scrape assets, etc. ...
82
+ {
83
+ title: 'Update links in content via LinkFixer',
84
+ task: (ctx, task) => {
85
+ let subtasks = ctx.linkFixer.fix(ctx, task);
86
+ return makeTaskRunner(subtasks, options);
87
+ }
88
+ }
89
+ ];
90
+ ```
91
+
92
+ ### Per-post usage with MigrateContext
93
+
94
+ When using [mg-context](../mg-context)'s `MigrateContext`, use `fixPost` instead of `buildMap`/`fix`. This avoids loading the entire link map into memory — each post's links are looked up individually against the database.
95
+
96
+ `fixPost` takes a post object (anything with `get(field)` and `set(field, value)` methods) and a lookup function. It extracts all URLs from the post's `html` and `lexical` fields, cleans each one (stripping protocol and query params), and calls the lookup function. Matches are replaced; non-matches are left unchanged.
97
+
98
+ ```javascript
99
+ import LinkFixer from '@tryghost/mg-linkfixer';
100
+ import {MigrateContext} from '@tryghost/mg-context';
101
+
102
+ const context = new MigrateContext();
103
+ await context.init();
104
+
105
+ // ... ingest posts, calling context.addLink() for each known URL ...
106
+
107
+ const linkFixer = new LinkFixer();
108
+ const lookup = (url) => context.findLink(url);
109
+
110
+ await context.forEachPost(async (post) => {
111
+ await linkFixer.fixPost(post, lookup);
112
+ });
113
+ ```
114
+
115
+ ### Multiple domains
116
+
117
+ If the source site used multiple domains over its lifetime (e.g. it moved from `olddomain.com` to `newdomain.com`), links to any of those domains should be treated as internal and fixed.
118
+
119
+ **Legacy pipeline (`buildMap`/`fix`):** Call `expandForDomains` after `buildMap` to cross-populate the link map so every known path is reachable via every domain:
120
+
121
+ ```javascript
122
+ linkFixer.buildMap(ctx);
123
+ linkFixer.expandForDomains(['https://newdomain.com', 'https://olddomain.com']);
124
+ ```
125
+
126
+ A link to `https://olddomain.com/my-post/` will be rewritten the same way as `https://newdomain.com/my-post/`.
127
+
128
+ **MigrateContext pipeline (`fixPost`):** Domain expansion is handled at ingest time by calling `context.addLink()` for each domain. `fixPost` doesn't need to know about domains — it just looks up whatever URLs it finds.
129
+
130
+ ### Dated permalinks
131
+
132
+ If the source site used dated permalink structures, set `ctx.options.datedPermalinks` so that dates are preserved in the rewritten URLs:
133
+
134
+ ```javascript
135
+ // Supported formats:
136
+ ctx.options.datedPermalinks = '/yyyy/mm/dd/'; // e.g. /2020/06/27/my-post/
137
+ ctx.options.datedPermalinks = '/yyyy/mm/'; // e.g. /2020/06/my-post/
138
+ ctx.options.datedPermalinks = '/*/yyyy/mm/dd/'; // e.g. /articles/2020/06/27/my-post/ -> /2020/06/27/my-post/
139
+ ctx.options.datedPermalinks = '/*/yyyy/mm/'; // e.g. /articles/2020/06/my-post/ -> /2020/06/my-post/
140
+ ```
141
+
142
+ When no `datedPermalinks` option is set, all URLs are rewritten to slug-only paths (e.g. `/my-post/`).
143
+
144
+ ## How it works
145
+
146
+ There are two API paths depending on how your pipeline is structured:
147
+
148
+ ### Legacy pipeline (`buildMap` + `fix`)
149
+
150
+ 1. **`buildMap(ctx)`** iterates over all posts in `ctx.result.posts` (or `ctx.data.posts`) and builds an in-memory mapping of original URLs to their new relative paths. Each post's own URL domain is used for dated permalink detection. Tags are mapped to `/tag/{slug}/` and authors to `/author/{slug}/`. Both `http` and `https` variants of each URL are handled.
151
+ 2. **`expandForDomains(urls)`** cross-populates the link map so every known path is reachable via every provided domain. Call after `buildMap` when the source site used multiple domains.
152
+ 3. **`fix(ctx, task)`** returns an array of Listr-compatible task objects. Each task processes one content field (HTML or Lexical) from one post, scanning for links that match the map and replacing them with the relative path.
153
+ 4. **`processHTML(html)`** parses the HTML, finds all `<a>` elements, cleans each `href` (stripping protocol and query parameters), and replaces it if found in the link map.
154
+ 5. **`processLexical(lexical)`** parses the Lexical JSON and recursively replaces any `url` property values that match the link map.
155
+
156
+ ### MigrateContext pipeline (`fixPost`)
157
+
158
+ 6. **`fixPost(post, lookupFn)`** processes a single post's `html` and `lexical` fields. For each URL found in the content, it cleans it with `cleanURL()` (stripping protocol and query params to `host/path`) and calls `lookupFn(cleanedUrl)`. If the function returns a string, the URL is replaced; if it returns `null`/`undefined`, the original URL is kept. The post object is duck-typed — it only needs `get(field)` and `set(field, value)` methods.
159
+
160
+ ### `cleanURL`
161
+
162
+ Both `fixPost` and `processHTML` normalize URLs before looking them up — stripping the protocol and query parameters to produce a `host/path` key (e.g. `https://example.com/my-post/?ref=home` becomes `example.com/my-post/`). If the link map keys don't use the same format, lookups silently fail.
163
+
164
+ `cleanURL` lives in [mg-utils](../mg-utils) as `stringUtils.cleanURL` and is re-exported here for convenience:
165
+
166
+ ```javascript
167
+ import {stringUtils} from '@tryghost/mg-utils';
168
+ const {cleanURL} = stringUtils;
169
+
170
+ // or via mg-linkfixer
171
+ import {cleanURL} from '@tryghost/mg-linkfixer';
172
+
173
+ cleanURL('https://example.com/my-post/?ref=home');
174
+ // => 'example.com/my-post/'
175
+
176
+ // Use it when populating the link map during ingest
177
+ context.addLink(cleanURL(postUrl), `/${slug}/`);
178
+ context.addLink(cleanURL(tagUrl), `/tag/${tagSlug}/`);
179
+ context.addLink(cleanURL(authorUrl), `/author/${authorSlug}/`);
180
+ ```
181
+
182
+ Also available as `LinkFixer.cleanURL(url)` and `instance.cleanURL(url)` for backward compatibility.
14
183
 
15
184
  ## Develop
16
185
 
@@ -20,20 +189,11 @@ Follow the instructions for the top-level repo.
20
189
  1. `git clone` this repo & `cd` into it as usual
21
190
  2. Run `pnpm install` to install top-level dependencies.
22
191
 
23
-
24
- ## Run
25
-
26
- - `pnpm dev`
27
-
28
-
29
192
  ## Test
30
193
 
31
194
  - `pnpm lint` run just eslint
32
195
  - `pnpm test` run lint and tests
33
196
 
34
-
35
-
36
-
37
197
  # Copyright & License
38
198
 
39
199
  Copyright (c) 2013-2026 Ghost Foundation - Released under the [MIT license](LICENSE).
package/index.js CHANGED
@@ -1,3 +1,5 @@
1
1
  import LinkFixer from './lib/LinkFixer.js';
2
+ import {stringUtils} from '@tryghost/mg-utils';
2
3
 
3
4
  export default LinkFixer;
5
+ export const cleanURL = stringUtils.cleanURL;
package/lib/LinkFixer.js CHANGED
@@ -1,15 +1,14 @@
1
- import {join} from 'node:path';
2
- import _ from 'lodash';
3
- import {domUtils} from '@tryghost/mg-utils';
1
+ import {domUtils, stringUtils} from '@tryghost/mg-utils';
4
2
 
5
3
  const {processFragment} = domUtils;
4
+ const {cleanURL} = stringUtils;
6
5
 
7
6
  // @TODO: expand this list
8
7
  const htmlFields = ['html'];
9
8
  const lexicalFields = ['lexical'];
10
9
 
11
- const isHTMLField = field => _.includes(htmlFields, field);
12
- const isLexicalField = field => _.includes(lexicalFields, field);
10
+ const isHTMLField = field => htmlFields.includes(field);
11
+ const isLexicalField = field => lexicalFields.includes(field);
13
12
 
14
13
  function mapObject(obj, fn) {
15
14
  return Object.fromEntries(
@@ -28,29 +27,13 @@ export default class LinkFixer {
28
27
  this.linkMap = {};
29
28
  }
30
29
 
31
- /**
32
- * Clean the URL
33
- * @param {String} url The given URL
34
- * @returns {String} A cleaned URL with no protocol or parameters
35
- *
36
- * @example
37
- * cleanURL('https://exampleurl.com/sample-page/child-sample-page/?dolor=simet');
38
- * => exampleurl.com/sample-page/child-sample-page/
39
- *
40
- * @example
41
- * cleanURL('https://exampleurl.com/sample-page/');
42
- * => exampleurl.com/sample-page/
43
- */
30
+ // Delegate to shared utility; kept as static + instance for backward compatibility
31
+ static cleanURL(url) {
32
+ return cleanURL(url);
33
+ }
34
+
44
35
  cleanURL(url) {
45
- try {
46
- const urlParts = new URL(url);
47
- const cleanedURL = join(urlParts.host, urlParts.pathname);
48
-
49
- return cleanedURL;
50
- } catch (error) {
51
- // If it's an invalid URL, return the original string
52
- return url;
53
- }
36
+ return cleanURL(url);
54
37
  }
55
38
 
56
39
  buildMap(ctx) {
@@ -71,13 +54,13 @@ export default class LinkFixer {
71
54
  const postURLDomain = new URL(url);
72
55
 
73
56
  // We need to handle the domain with http: and https:, so build part of the regexp pattern that accounts for both
74
- const siteURL = new URL(ctx.options.url || postURLDomain.origin);
57
+ const siteURL = new URL(postURLDomain.origin);
75
58
 
76
59
  siteURL.protocol = 'http:';
77
- const siteURLHttp = siteURL.toString().replace(/\/$/, ''); // Trim trailing slashes
60
+ const siteURLHttp = siteURL.toString().replace(/\/$/, '');
78
61
 
79
62
  siteURL.protocol = 'https:';
80
- const siteURLHttps = siteURL.toString().replace(/\/$/, ''); // Trim trailing slashes
63
+ const siteURLHttps = siteURL.toString().replace(/\/$/, '');
81
64
 
82
65
  const siteURLBothProtocols = `(?:${siteURLHttp}|${siteURLHttps})`;
83
66
 
@@ -124,11 +107,38 @@ export default class LinkFixer {
124
107
 
125
108
  // Remove the protocol, ensuring we treat `http` and `https` sites in the same way
126
109
  Object.keys(this.linkMap).forEach((key) => {
127
- let updatedURL = this.cleanURL(key);
110
+ let updatedURL = LinkFixer.cleanURL(key);
128
111
  this.linkMap[updatedURL] = this.linkMap[key];
129
112
  });
130
113
  }
131
114
 
115
+ /**
116
+ * Cross-populate the linkMap so that every known path is accessible via every provided domain.
117
+ * Call after buildMap() when the source site used multiple domains.
118
+ * @param {String|String[]} urls One or more site URLs
119
+ */
120
+ expandForDomains(urls) {
121
+ const siteURLs = [].concat(urls || []).filter(Boolean);
122
+ if (siteURLs.length < 2) {
123
+ return;
124
+ }
125
+ const hosts = siteURLs.map(u => new URL(u).host);
126
+ const pathMap = {};
127
+ for (const [key, value] of Object.entries(this.linkMap)) {
128
+ for (const host of hosts) {
129
+ if (key.startsWith(host + '/')) {
130
+ pathMap[key.slice(host.length)] = value;
131
+ break;
132
+ }
133
+ }
134
+ }
135
+ for (const [path, value] of Object.entries(pathMap)) {
136
+ for (const host of hosts) {
137
+ this.linkMap[host + path] = value;
138
+ }
139
+ }
140
+ }
141
+
132
142
  async processHTML(html) {
133
143
  return processFragment(html, (parsed) => {
134
144
  for (const el of parsed.$('a')) {
@@ -139,7 +149,7 @@ export default class LinkFixer {
139
149
  }
140
150
 
141
151
  // Clean the URL, matching the links stored in the linkMap
142
- let updatedURL = this.cleanURL(href);
152
+ let updatedURL = LinkFixer.cleanURL(href);
143
153
 
144
154
  if (this.linkMap[updatedURL]) {
145
155
  el.setAttribute('href', this.linkMap[updatedURL]);
@@ -155,9 +165,9 @@ export default class LinkFixer {
155
165
 
156
166
  const mappedObject = mapObject(parsedLexical, (key, value) => {
157
167
  if (key === 'url') {
158
- let updatedURL = this.cleanURL(value);
168
+ let updatedURL = LinkFixer.cleanURL(value);
159
169
 
160
- return this.linkMap[updatedURL];
170
+ return this.linkMap[updatedURL] || value;
161
171
  } else {
162
172
  return value;
163
173
  }
@@ -166,21 +176,74 @@ export default class LinkFixer {
166
176
  return JSON.stringify(mappedObject);
167
177
  }
168
178
 
179
+ /**
180
+ * Fix links in a single post using a lookup function instead of the in-memory linkMap.
181
+ * The post is duck-typed — it only needs get(field) and set(field, value) methods.
182
+ * The lookupFn receives a cleaned URL (host/path, no protocol or query params) and
183
+ * should return the new relative path, or null/undefined if no match.
184
+ *
185
+ * @param {Object} post Object with get(field) and set(field, value) methods
186
+ * @param {Function} lookupFn (cleanedUrl: string) => string | null
187
+ */
188
+ async fixPost(post, lookupFn) {
189
+ for (const field of htmlFields) {
190
+ const value = post.get(field);
191
+ if (!value) {
192
+ continue;
193
+ }
194
+
195
+ const fixed = await processFragment(value, (parsed) => {
196
+ for (const el of parsed.$('a')) {
197
+ const href = el.getAttribute('href');
198
+ if (!href) {
199
+ continue;
200
+ }
201
+
202
+ const cleanedURL = LinkFixer.cleanURL(href);
203
+ const newURL = lookupFn(cleanedURL);
204
+ if (newURL) {
205
+ el.setAttribute('href', newURL);
206
+ }
207
+ }
208
+ return parsed.html();
209
+ });
210
+
211
+ post.set(field, fixed);
212
+ }
213
+
214
+ for (const field of lexicalFields) {
215
+ const value = post.get(field);
216
+ if (!value) {
217
+ continue;
218
+ }
219
+
220
+ const parsed = JSON.parse(value);
221
+ const mapped = mapObject(parsed, (key, val) => {
222
+ if (key === 'url') {
223
+ const cleanedURL = LinkFixer.cleanURL(val);
224
+ return lookupFn(cleanedURL) || val;
225
+ }
226
+ return val;
227
+ });
228
+ post.set(field, JSON.stringify(mapped));
229
+ }
230
+ }
231
+
169
232
  fix(ctx, task) {
170
233
  let tasks = [];
171
234
  let json = ctx.result;
172
235
 
173
- if (_.size(this.linkMap) === 0) {
236
+ if (Object.keys(this.linkMap).length === 0) {
174
237
  task.skip('Link map not available');
175
238
  return;
176
239
  }
177
240
 
178
241
  // For each resource type e.g. posts, users
179
- _.forEach(json.data, (resources, type) => {
242
+ for (const [type, resources] of Object.entries(json.data)) {
180
243
  // For each individual resource
181
- _.forEach(resources, (resource) => {
244
+ for (const resource of resources) {
182
245
  // For each field
183
- _.forEach(resource, (value, field) => {
246
+ for (const [field, value] of Object.entries(resource)) {
184
247
  if (isLexicalField(field)) {
185
248
  tasks.push({
186
249
  title: `${type}: ${resource.slug} ${field}`,
@@ -207,9 +270,9 @@ export default class LinkFixer {
207
270
  }
208
271
  });
209
272
  }
210
- });
211
- });
212
- });
273
+ }
274
+ }
275
+ }
213
276
 
214
277
  return tasks;
215
278
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tryghost/mg-linkfixer",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/TryGhost/migrate.git",
@@ -20,12 +20,11 @@
20
20
  "devDependencies": {
21
21
  "eslint": "8.57.1",
22
22
  "listr": "0.14.3",
23
- "@tryghost/mg-json": "0.17.0",
24
- "@tryghost/listr-smart-renderer": "0.10.0"
23
+ "@tryghost/mg-json": "0.18.0",
24
+ "@tryghost/listr-smart-renderer": "0.11.0"
25
25
  },
26
26
  "dependencies": {
27
- "lodash": "4.18.1",
28
- "@tryghost/mg-utils": "0.6.0"
27
+ "@tryghost/mg-utils": "0.7.0"
29
28
  },
30
29
  "scripts": {
31
30
  "dev": "echo \"Implement me!\"",