@tryghost/mg-blogger 0.4.0 → 0.6.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 (3) hide show
  1. package/README.md +7 -7
  2. package/lib/process.js +172 -171
  3. package/package.json +3 -3
package/README.md CHANGED
@@ -20,7 +20,7 @@ To use this package in your own project:
20
20
 
21
21
  or
22
22
 
23
- `yarn add @tryghost/mg-blogger`
23
+ `pnpm add @tryghost/mg-blogger`
24
24
 
25
25
 
26
26
  ## Usage
@@ -77,26 +77,26 @@ This will fetch posts only from 2 sites, and add a 'Blog Posts' tag to each post
77
77
 
78
78
  ## Develop
79
79
 
80
- This is a mono repository, managed with [Nx](https://nx.dev/) and yarn workspaces.
80
+ This is a mono repository, managed with [Nx](https://nx.dev/) and pnpm workspaces.
81
81
 
82
82
  Follow the instructions for the top-level repo.
83
83
  1. `git clone` this repo & `cd` into it as usual
84
- 2. Run `yarn` to install top-level dependencies.
84
+ 2. Run `pnpm install` to install top-level dependencies.
85
85
 
86
86
 
87
87
  ## Run
88
88
 
89
- To run a local development copy, `cd` into this directory, and use `yarn dev` instead of `migrate` like so:
89
+ To run a local development copy, `cd` into this directory, and use `pnpm dev` instead of `migrate` like so:
90
90
 
91
91
  ```sh
92
- yarn dev blogger --apiKey abcd --blogID 1234
92
+ pnpm dev blogger --apiKey abcd --blogID 1234
93
93
  ```
94
94
 
95
95
 
96
96
  ## Test
97
97
 
98
- - `yarn lint` run just eslint
99
- - `yarn test` run lint and tests
98
+ - `pnpm lint` run just eslint
99
+ - `pnpm test` run lint and tests
100
100
 
101
101
 
102
102
  # Copyright & License
package/lib/process.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import {basename} from 'node:path';
2
- import * as cheerio from 'cheerio';
2
+ import {domUtils} from '@tryghost/mg-utils';
3
3
  import autop from 'autop';
4
4
  import sanitizeHtml from 'sanitize-html';
5
5
  import {slugify} from '@tryghost/string';
@@ -7,6 +7,8 @@ import errors from '@tryghost/errors';
7
7
  import SimpleDom from 'simple-dom';
8
8
  import imageCard from '@tryghost/kg-default-cards/lib/cards/image.js';
9
9
 
10
+ const {serializeChildren, replaceWith, wrap} = domUtils;
11
+
10
12
  const serializer = new SimpleDom.HTMLSerializer(SimpleDom.voidMap);
11
13
 
12
14
  const cleanExcerpt = (htmlContent) => {
@@ -35,54 +37,48 @@ const increaseImageSize = (src) => {
35
37
  return updatedSrc;
36
38
  };
37
39
 
38
- const getAllAttributes = function (el) {
39
- return el.attributes || Object.keys(el.attribs).map(
40
- name => ({name, value: el.attribs[name]})
41
- );
42
- };
43
-
44
40
  const handleFirstImage = (args) => {
45
41
  let {postData, html} = args;
46
42
 
47
- const $html = cheerio.load(html, {
48
- xml: {
49
- xmlMode: false,
50
- decodeEntities: false,
51
- scriptingEnabled: false
43
+ return domUtils.processFragment(html, (parsed) => {
44
+ const firstContentElement = parsed.body.children[0];
45
+
46
+ if (!firstContentElement) {
47
+ postData.html = parsed.html().trim();
48
+ return postData;
52
49
  }
53
- }, false); // This `false` is `isDocument`. If `true`, <html>, <head>, and <body> elements are introduced
54
-
55
- const firstContentElement = $html('*').first();
56
-
57
- if (firstContentElement[0].name === 'img') {
58
- $html(firstContentElement).remove();
59
- postData.feature_image = $html(firstContentElement).attr('src');
60
- } else if ($html(firstContentElement).text().trim() === '') {
61
- const firstContentElementImgSrc = $html(firstContentElement).find('img').attr('src');
62
- const firstContentElementImgBasename = firstContentElementImgSrc ? basename(firstContentElementImgSrc) : null;
63
- const firstContentElementAHref = $html(firstContentElement).find('a').attr('href');
64
- const firstContentElementAHrefBasename = firstContentElementAHref ? basename(firstContentElementAHref) : null;
65
-
66
- if (firstContentElementImgBasename === firstContentElementAHrefBasename) {
67
- $html(firstContentElement).remove();
68
- postData.feature_image = firstContentElementImgSrc;
69
- } else if (firstContentElementImgSrc && !firstContentElementAHref) {
70
- $html(firstContentElement).remove();
71
- postData.feature_image = firstContentElementImgSrc;
72
- } else {
73
- const firstContentElementImgBasenameNoSize = firstContentElementImgBasename.replace(/(.*)((-=|-|=)w[0-9]{2,5}-h[0-9]{2,5}|(-=|-|=)s[0-9]{2,5})/, '$1');
74
- const firstContentElementAHrefBasenameNoSize = firstContentElementAHrefBasename.replace(/(.*)((-=|-|=)w[0-9]{2,5}-h[0-9]{2,5}|(-=|-|=)s[0-9]{2,5})/, '$1');
75
-
76
- if (firstContentElementImgBasenameNoSize === firstContentElementAHrefBasenameNoSize) {
77
- $html(firstContentElement).remove();
50
+
51
+ if (firstContentElement.tagName === 'IMG') {
52
+ postData.feature_image = firstContentElement.getAttribute('src');
53
+ firstContentElement.remove();
54
+ } else if ((firstContentElement.textContent || '').trim() === '') {
55
+ const img = firstContentElement.querySelector('img');
56
+ const a = firstContentElement.querySelector('a');
57
+ const firstContentElementImgSrc = img?.getAttribute('src') ?? null;
58
+ const firstContentElementImgBasename = firstContentElementImgSrc ? basename(firstContentElementImgSrc) : null;
59
+ const firstContentElementAHref = a?.getAttribute('href') ?? null;
60
+ const firstContentElementAHrefBasename = firstContentElementAHref ? basename(firstContentElementAHref) : null;
61
+
62
+ if (firstContentElementImgBasename === firstContentElementAHrefBasename) {
63
+ firstContentElement.remove();
78
64
  postData.feature_image = firstContentElementImgSrc;
65
+ } else if (firstContentElementImgSrc && !firstContentElementAHref) {
66
+ firstContentElement.remove();
67
+ postData.feature_image = firstContentElementImgSrc;
68
+ } else {
69
+ const firstContentElementImgBasenameNoSize = firstContentElementImgBasename.replace(/(.*)((-=|-|=)w[0-9]{2,5}-h[0-9]{2,5}|(-=|-|=)s[0-9]{2,5})/, '$1');
70
+ const firstContentElementAHrefBasenameNoSize = firstContentElementAHrefBasename.replace(/(.*)((-=|-|=)w[0-9]{2,5}-h[0-9]{2,5}|(-=|-|=)s[0-9]{2,5})/, '$1');
71
+
72
+ if (firstContentElementImgBasenameNoSize === firstContentElementAHrefBasenameNoSize) {
73
+ firstContentElement.remove();
74
+ postData.feature_image = firstContentElementImgSrc;
75
+ }
79
76
  }
80
77
  }
81
- }
82
78
 
83
- postData.html = $html.html().trim();
84
-
85
- return postData;
79
+ postData.html = parsed.html().trim();
80
+ return postData;
81
+ });
86
82
  };
87
83
 
88
84
  const processHTMLContent = async (args) => {
@@ -90,163 +86,171 @@ const processHTMLContent = async (args) => {
90
86
 
91
87
  html = autop(html);
92
88
 
93
- const $html = cheerio.load(html, {
94
- xml: {
95
- xmlMode: false,
96
- decodeEntities: false,
97
- scriptingEnabled: false
98
- }
99
- }, false); // This `false` is `isDocument`. If `true`, <html>, <head>, and <body> elements are introduced
89
+ html = domUtils.processFragment(html, (parsed) => {
90
+ parsed.$('div.separator').forEach((el) => {
91
+ replaceWith(el, `<hr><div>${serializeChildren(el).trim()}</div>`);
92
+ });
100
93
 
101
- $html('div.separator').each((i, el) => {
102
- $html(el).replaceWith(`<hr><div>${$html(el).html().trim()}</div>`);
103
- });
94
+ parsed.$('img').forEach((el) => {
95
+ const imgSrc = el.getAttribute('src');
96
+ const largerSrc = increaseImageSize(imgSrc);
104
97
 
105
- $html('img').each((i, el) => {
106
- const imgSrc = $html(el).attr('src');
107
- const largerSrc = increaseImageSize(imgSrc);
98
+ el.setAttribute('src', largerSrc);
99
+ el.removeAttribute('width');
100
+ el.removeAttribute('height');
101
+ });
108
102
 
109
- $html(el).attr('src', largerSrc);
110
- $html(el).removeAttr('width');
111
- $html(el).removeAttr('height');
112
- });
103
+ parsed.$('.tr-caption-container').forEach((el) => {
104
+ const img = el.querySelector('img');
105
+ const imgParentA = img?.closest('a');
106
+ const hasLink = !!imgParentA;
107
+ const href = hasLink ? imgParentA.getAttribute('href') : null;
108
+ const imgSrc = img?.getAttribute('src') ?? null;
109
+ const captionEl = el.querySelector('.tr-caption');
110
+ const caption = captionEl ? serializeChildren(captionEl) : '';
111
+ const cleanedExcerpt = cleanExcerpt(caption);
112
+
113
+ if (!imgSrc || imgSrc.length === 0) {
114
+ return;
115
+ }
113
116
 
114
- $html('.tr-caption-container').each((i, el) => {
115
- const hasLink = $html(el).find('img').parent('a').length;
116
- const href = (hasLink) ? $html(el).find('img').parent('a').attr('href') : null;
117
- const imgSrc = $html(el).find('img').attr('src');
118
- const caption = $html(el).find('.tr-caption').html();
119
- const cleanedExcerpt = cleanExcerpt(caption);
117
+ // Update image size so we get the biggest image
118
+ const updatedImgSrc = increaseImageSize(imgSrc);
120
119
 
121
- if (!imgSrc || imgSrc.length === 0) {
122
- return;
123
- }
120
+ let cardOpts = {
121
+ env: {dom: new SimpleDom.Document()},
122
+ payload: {
123
+ src: updatedImgSrc,
124
+ caption: cleanedExcerpt
125
+ }
126
+ };
124
127
 
125
- // Update image size so we get the biggest image
126
- const updatedImgSrc = increaseImageSize(imgSrc);
128
+ if (hasLink) {
129
+ const updatedHref = increaseImageSize(href);
127
130
 
128
- let cardOpts = {
129
- env: {dom: new SimpleDom.Document()},
130
- payload: {
131
- src: updatedImgSrc,
132
- caption: cleanedExcerpt
131
+ if (updatedImgSrc !== updatedHref) {
132
+ cardOpts.payload.href = href;
133
+ }
133
134
  }
134
- };
135
135
 
136
- if (hasLink) {
137
- const updatedHref = increaseImageSize(href);
136
+ const newCard = serializer.serialize(imageCard.render(cardOpts));
138
137
 
139
- if (updatedImgSrc !== updatedHref) {
140
- cardOpts.payload.href = href;
141
- }
142
- }
143
-
144
- const newCard = serializer.serialize(imageCard.render(cardOpts));
138
+ replaceWith(el, newCard);
139
+ });
145
140
 
146
- $html(el).replaceWith(newCard);
147
- });
141
+ parsed.$('a > img').forEach((el) => {
142
+ const parentA = el.parentElement;
143
+ if (!parentA || parentA.tagName !== 'A') {
144
+ return;
145
+ }
148
146
 
149
- $html('a > img').each((i, el) => {
150
- const aHref = $html(el).parent().attr('href');
151
- const imgSrc = $html(el).attr('src');
147
+ const aHref = parentA.getAttribute('href');
148
+ const imgSrc = el.getAttribute('src');
152
149
 
153
- const updatedaHref = increaseImageSize(aHref);
154
- const updatedImgSrc = increaseImageSize(imgSrc);
150
+ const updatedaHref = increaseImageSize(aHref);
151
+ const updatedImgSrc = increaseImageSize(imgSrc);
155
152
 
156
- // Don't touch Koenig cards
157
- if ($html(el).parent().attr('class')?.includes('kg-') || $html(el).attr('class')?.includes('kg-')) {
158
- return;
159
- }
153
+ // Don't touch Koenig cards
154
+ if (parentA.getAttribute('class')?.includes('kg-') || el.getAttribute('class')?.includes('kg-')) {
155
+ return;
156
+ }
160
157
 
161
- if (updatedaHref === updatedImgSrc) {
162
- $html(el).parent().replaceWith(`<img src="${imgSrc}">`);
163
- }
164
- });
158
+ if (updatedaHref === updatedImgSrc) {
159
+ replaceWith(parentA, `<img src="${imgSrc}">`);
160
+ }
161
+ });
165
162
 
166
- // Convert weird lists to real lists
167
- $html('span[style*="white-space: pre"]').each((i, el) => {
168
- const parent = $html(el).parent('div');
169
- if (parent.html()?.includes('•') || parent.html()?.includes('&#x2022;')) {
170
- parent[0].tagName = 'li';
171
- parent.find('span[style*="white-space: pre"]').each((ii, ell) => {
172
- $html(ell).remove();
173
- });
174
- parent.html(parent.html().replace('&#x2022;', '').trim());
175
- }
176
- });
163
+ // Convert weird lists to real lists
164
+ parsed.$('span[style*="white-space: pre"]').forEach((el) => {
165
+ const parentDiv = el.closest('div');
166
+ if (!parentDiv) {
167
+ return;
168
+ }
177
169
 
178
- // Wrap <li>s in <ul>
179
- $html('li').each((i, el) => {
180
- if ($html(el).prev('ul').length) {
181
- $html(el).prev('ul').append($html(el));
182
- } else {
183
- $html(el).wrap('<ul></ul>');
184
- }
185
- });
170
+ const parentHTML = serializeChildren(parentDiv);
171
+ if (parentHTML.includes('•') || parentHTML.includes('&#x2022;')) {
172
+ // Change div to li by replacing with a new li element
173
+ const newLi = parsed.document.createElement('li');
174
+ // Copy children, remove the whitespace-pre spans
175
+ newLi.innerHTML = serializeChildren(parentDiv);
176
+ newLi.querySelectorAll('span[style*="white-space: pre"]').forEach((span) => {
177
+ span.remove();
178
+ });
179
+ newLi.innerHTML = newLi.innerHTML.replace('&#x2022;', '').trim();
180
+ replaceWith(parentDiv, newLi);
181
+ }
182
+ });
186
183
 
187
- $html('div[style*="color"][style*="font-family"][style*="font-size"][style*="white-space: pre-line"]').each((i, el) => {
188
- $html(el).replaceWith(`<p>${$html(el).html().trim()}</p>`);
189
- });
184
+ // Wrap <li>s in <ul>
185
+ parsed.$('li').forEach((el) => {
186
+ const prevSibling = el.previousElementSibling;
187
+ if (prevSibling && prevSibling.tagName === 'UL') {
188
+ prevSibling.appendChild(el);
189
+ } else {
190
+ wrap(el, '<ul></ul>');
191
+ }
192
+ });
190
193
 
191
- $html('span[style*="background-color"][style*="color"][style*="font-family"][style*="font-size"][style*="white-space: pre-line"]').each((i, el) => {
192
- $html(el).replaceWith(`<p>${$html(el).html().trim()}</p>`);
193
- });
194
+ parsed.$('div[style*="color"][style*="font-family"][style*="font-size"][style*="white-space: pre-line"]').forEach((el) => {
195
+ replaceWith(el, `<p>${serializeChildren(el).trim()}</p>`);
196
+ });
194
197
 
195
- $html('div[style="text-align: center;"]').each((i, el) => {
196
- $html(el).replaceWith(`<p>${$html(el).html().trim()}</p>`);
197
- });
198
+ parsed.$('span[style*="background-color"][style*="color"][style*="font-family"][style*="font-size"][style*="white-space: pre-line"]').forEach((el) => {
199
+ replaceWith(el, `<p>${serializeChildren(el).trim()}</p>`);
200
+ });
198
201
 
199
- $html('h1, h2, h3, h4, h5, h6').each((i, el) => {
200
- const attrs = getAllAttributes(el);
202
+ parsed.$('div[style="text-align: center;"]').forEach((el) => {
203
+ replaceWith(el, `<p>${serializeChildren(el).trim()}</p>`);
204
+ });
201
205
 
202
- const styleIndex = attrs.findIndex(e => e.name === 'style');
203
- if (styleIndex > -1) {
204
- if (attrs[styleIndex].value === 'text-align: left;') {
205
- $html(el).removeAttr(`style`);
206
+ parsed.$('h1, h2, h3, h4, h5, h6').forEach((el) => {
207
+ const styleAttr = el.getAttribute('style');
208
+ if (styleAttr === 'text-align: left;') {
209
+ el.removeAttribute('style');
206
210
  }
207
- }
208
- });
211
+ });
209
212
 
210
- $html('h3 b').each((i, el) => {
211
- const $el = $html(el);
212
- $el.replaceWith($el.html());
213
- });
213
+ parsed.$('h3 b').forEach((el) => {
214
+ replaceWith(el, serializeChildren(el));
215
+ });
214
216
 
215
- $html('div, p').each((i, el) => {
216
- const attrs = getAllAttributes(el);
217
- const children = $html(el).children();
217
+ parsed.$('div, p').forEach((el) => {
218
+ const attrs = el.attributes;
219
+ const children = el.children;
218
220
 
219
- if ($html(el).html().trim() === '' && attrs.length === 0) {
220
- $html(el).remove();
221
- } else if ($html(el).html() === '&#xA0;') {
222
- $html(el).remove();
223
- } else if (attrs.length === 0 && children.length === 1 && children[0].name === 'img') {
224
- $html(el).replaceWith($html(el).html().trim());
225
- }
226
- });
221
+ if (serializeChildren(el).trim() === '' && attrs.length === 0) {
222
+ el.remove();
223
+ } else if (serializeChildren(el) === '&#xA0;') {
224
+ el.remove();
225
+ } else if (attrs.length === 0 && children.length === 1 && children[0].tagName === 'IMG') {
226
+ replaceWith(el, serializeChildren(el).trim());
227
+ }
228
+ });
227
229
 
228
- $html('p').each((i, el) => {
229
- if ($html(el).html().trim() === '' || $html(el).html() === '&#xA0;' || $html(el).html().trim() === '&nbsp;') {
230
- $html(el).remove();
231
- }
232
- });
230
+ parsed.$('p').forEach((el) => {
231
+ const innerHtml = serializeChildren(el);
232
+ if (innerHtml.trim() === '' || innerHtml === '&#xA0;' || innerHtml.trim() === '&nbsp;') {
233
+ el.remove();
234
+ }
235
+ });
233
236
 
234
- $html('div').each((i, el) => {
235
- const attrs = getAllAttributes(el);
236
- const children = $html(el).children();
237
+ parsed.$('div').forEach((el) => {
238
+ const attrs = el.attributes;
239
+ const children = el.children;
237
240
 
238
- if (attrs.length === 0 && children.length === 0) {
239
- $html(el).replaceWith(`<p>${$html(el).html().trim()}</p>`);
240
- }
241
- });
241
+ if (attrs.length === 0 && children.length === 0) {
242
+ replaceWith(el, `<p>${serializeChildren(el).trim()}</p>`);
243
+ }
244
+ });
242
245
 
243
- $html('iframe[src*="youtube.com"]').each((i, el) => {
244
- $html(el).attr('width', 160);
245
- $html(el).attr('height', 90);
246
- });
246
+ parsed.$('iframe[src*="youtube.com"]').forEach((el) => {
247
+ el.setAttribute('width', '160');
248
+ el.setAttribute('height', '90');
249
+ });
247
250
 
248
- // Convert back to plain HTML
249
- html = $html.html();
251
+ // Convert back to plain HTML
252
+ return parsed.html();
253
+ });
250
254
 
251
255
  // Trim whitespace
252
256
  html = html.trim();
@@ -351,8 +355,6 @@ const processPost = async (postData, options) => {
351
355
  }
352
356
  });
353
357
 
354
- // console.log(post);
355
-
356
358
  return post;
357
359
  };
358
360
 
@@ -394,6 +396,5 @@ export default {
394
396
  export {
395
397
  cleanExcerpt,
396
398
  slugFromURL,
397
- increaseImageSize,
398
- getAllAttributes
399
+ increaseImageSize
399
400
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tryghost/mg-blogger",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/TryGhost/migrate.git",
@@ -25,10 +25,10 @@
25
25
  "@tryghost/kg-default-cards": "10.2.10",
26
26
  "@tryghost/string": "0.3.1",
27
27
  "autop": "1.0.1",
28
- "cheerio": "1.2.0",
29
28
  "node-fetch": "3.3.2",
30
29
  "sanitize-html": "2.17.2",
31
- "simple-dom": "1.4.0"
30
+ "simple-dom": "1.4.0",
31
+ "@tryghost/mg-utils": "0.6.0"
32
32
  },
33
33
  "scripts": {
34
34
  "dev": "echo \"Implement me!\"",