@tryghost/mg-substack 0.8.9 → 0.9.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 (2) hide show
  1. package/lib/process.js +210 -197
  2. package/package.json +10 -12
package/lib/process.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {promises as fs} from 'node:fs';
2
2
  import {join, basename} from 'node:path';
3
3
  import url from 'node:url';
4
- import * as cheerio from 'cheerio';
4
+ import {domUtils} from '@tryghost/mg-utils';
5
5
  import errors from '@tryghost/errors';
6
6
  import SimpleDom from 'simple-dom';
7
7
  import imageCard from '@tryghost/kg-default-cards/lib/cards/image.js';
@@ -15,6 +15,8 @@ import {_base as debugFactory} from '@tryghost/debug';
15
15
  import {slugify} from '@tryghost/string';
16
16
  import _ from 'lodash';
17
17
 
18
+ const {parseFragment, serializeChildren, replaceWith, insertBefore, insertAfter, attr, parents} = domUtils;
19
+
18
20
  const serializer = new SimpleDom.HTMLSerializer(SimpleDom.voidMap);
19
21
  const debug = debugFactory('migrate:substack:process');
20
22
 
@@ -78,9 +80,9 @@ const getImageDimensions = (str) => {
78
80
  }
79
81
  };
80
82
 
81
- const largestSrc = ($imageElem) => {
82
- const src = $imageElem.attr('src') ?? false;
83
- const srcset = $imageElem.attr('srcset') ?? false;
83
+ const largestSrc = (imageElem) => {
84
+ const src = attr(imageElem, 'src');
85
+ const srcset = attr(imageElem, 'srcset');
84
86
 
85
87
  if (!src || !src.length) {
86
88
  return '';
@@ -115,40 +117,40 @@ const processContent = (post, siteUrl, options) => {
115
117
  return post;
116
118
  }
117
119
 
118
- // As there is HTML, pass it to Cheerio inside a `<div class="migrate-substack-wrapper"></div>` element so we have a global wrapper to target later on
119
- const $html = cheerio.load(`<div class="migrate-substack-wrapper">${html}</div>`, {}, false);
120
+ // Parse the HTML inside a wrapper element so we have a global wrapper to target later on
121
+ const parsed = parseFragment(`<div class="migrate-substack-wrapper">${html}</div>`);
120
122
 
121
123
  // Change paywall card to comment
122
- $html('.paywall-jump').each((i, el) => {
123
- $html(el).replaceWith('<!--members-only-->');
124
+ parsed.$('.paywall-jump').forEach((el) => {
125
+ replaceWith(el, '<!--members-only-->');
124
126
  });
125
127
 
126
128
  // Empty text elements are commonplace and are not needed
127
- $html('p').each((i, el) => {
128
- let content = $html(el).html().trim();
129
+ parsed.$('p').forEach((el) => {
130
+ let content = serializeChildren(el).trim();
129
131
 
130
132
  if (content.length === 0) {
131
- $html(el).remove();
133
+ el.remove();
132
134
  }
133
135
  });
134
136
 
135
137
  // Wrap these in a HTML card so they can be handled by publishers as needed
136
- $html('div.latex-rendered').each((i, el) => {
137
- $html(el).before('<!--kg-card-begin: html-->');
138
- $html(el).after('<!--kg-card-end: html-->');
138
+ parsed.$('div.latex-rendered').forEach((el) => {
139
+ insertBefore(el, '<!--kg-card-begin: html-->');
140
+ insertAfter(el, '<!--kg-card-end: html-->');
139
141
  });
140
142
 
141
143
  // We don't currently handle these, so remove them to clean up the document
142
- $html('div.native-video-embed').each((i, el) => {
143
- $html(el).remove();
144
+ parsed.$('div.native-video-embed').forEach((el) => {
145
+ el.remove();
144
146
  });
145
147
 
146
- $html('div.poll-embed').each((i, el) => {
147
- $html(el).remove();
148
+ parsed.$('div.poll-embed').forEach((el) => {
149
+ el.remove();
148
150
  });
149
151
 
150
- $html('.image3').each((i, el) => {
151
- const attrs = $html(el).attr('data-attrs');
152
+ parsed.$('.image3').forEach((el) => {
153
+ const attrs = attr(el, 'data-attrs');
152
154
  const attrsObj = JSON.parse(attrs);
153
155
 
154
156
  let cardOpts = {
@@ -160,7 +162,7 @@ const processContent = (post, siteUrl, options) => {
160
162
  }
161
163
  };
162
164
 
163
- $html(el).replaceWith(serializer.serialize(imageCard.render(cardOpts)));
165
+ replaceWith(el, serializer.serialize(imageCard.render(cardOpts)));
164
166
  });
165
167
 
166
168
  // We use the `'og:image` as the feature image. If the first item in the content is an image and is the same as the `og:image`, remove it
@@ -169,47 +171,57 @@ const processContent = (post, siteUrl, options) => {
169
171
  post.data.feature_image = largeImageUrl(post.data.og_image);
170
172
  }
171
173
 
172
- let firstElement = $html('.migrate-substack-wrapper *').first();
174
+ let firstElement = parsed.$('.migrate-substack-wrapper *')[0];
173
175
 
174
- if (firstElement.tagName === 'img' || ($html(firstElement).get(0) && $html(firstElement).get(0).name === 'img') || $html(firstElement).find('img').length) {
175
- let theElementItself = (firstElement.tagName === 'img' || $html(firstElement).get(0).name === 'img') ? firstElement : $html(firstElement).find('img');
176
- let firstImgSrc = $html(theElementItself).attr('src');
176
+ if (firstElement) {
177
+ const isImg = firstElement.tagName === 'IMG';
178
+ const hasImg = !isImg && parsed.$('img', firstElement).length > 0;
177
179
 
178
- if (firstImgSrc.length > 0) {
179
- let unsizedFirstSrc = getUnsizedImageName(firstImgSrc);
180
+ if (isImg || hasImg) {
181
+ let theElementItself = isImg ? firstElement : parsed.$('img', firstElement)[0];
182
+ let firstImgSrc = attr(theElementItself, 'src');
180
183
 
181
- let ogImgSrc = post.data.og_image;
182
- let unsizedOgSrc = getUnsizedImageName(ogImgSrc);
184
+ if (firstImgSrc.length > 0) {
185
+ let unsizedFirstSrc = getUnsizedImageName(firstImgSrc);
183
186
 
184
- if (unsizedFirstSrc === unsizedOgSrc) {
185
- if ($html(firstElement).find('figcaption').length) {
186
- post.data.feature_image_caption = $html(firstElement).find('figcaption').html();
187
- }
187
+ let ogImgSrc = post.data.og_image;
188
+ let unsizedOgSrc = getUnsizedImageName(ogImgSrc);
189
+
190
+ if (unsizedFirstSrc === unsizedOgSrc) {
191
+ if (parsed.$('figcaption', firstElement).length) {
192
+ post.data.feature_image_caption = serializeChildren(parsed.$('figcaption', firstElement)[0]);
193
+ }
188
194
 
189
- $html(firstElement).remove();
195
+ firstElement.remove();
196
+ }
190
197
  }
191
198
  }
192
199
  }
193
200
  }
194
201
 
195
202
  if (useFirstImage && !post.data.feature_image) {
196
- let firstElement = $html('.migrate-substack-wrapper *').first();
203
+ let firstElement = parsed.$('.migrate-substack-wrapper *')[0];
197
204
 
198
- if (firstElement.tagName === 'img' || ($html(firstElement).get(0) && $html(firstElement).get(0).name === 'img') || $html(firstElement).find('img').length) {
199
- let theElementItself = (firstElement.tagName === 'img' || $html(firstElement).get(0).name === 'img') ? firstElement : $html(firstElement).find('img');
200
- let firstImgSrc = $html(theElementItself).attr('src');
205
+ if (firstElement) {
206
+ const isImg = firstElement.tagName === 'IMG';
207
+ const hasImg = !isImg && parsed.$('img', firstElement).length > 0;
201
208
 
202
- if (firstImgSrc.length > 0) {
203
- let unsizedFirstSrc = largeImageUrl(firstImgSrc);
209
+ if (isImg || hasImg) {
210
+ let theElementItself = isImg ? firstElement : parsed.$('img', firstElement)[0];
211
+ let firstImgSrc = attr(theElementItself, 'src');
204
212
 
205
- if (unsizedFirstSrc) {
206
- post.data.feature_image = unsizedFirstSrc;
213
+ if (firstImgSrc.length > 0) {
214
+ let unsizedFirstSrc = largeImageUrl(firstImgSrc);
207
215
 
208
- if ($html(firstElement).find('figcaption').length) {
209
- post.data.feature_image_caption = $html(firstElement).find('figcaption').html();
210
- }
216
+ if (unsizedFirstSrc) {
217
+ post.data.feature_image = unsizedFirstSrc;
211
218
 
212
- $html(firstElement).remove();
219
+ if (parsed.$('figcaption', firstElement).length) {
220
+ post.data.feature_image_caption = serializeChildren(parsed.$('figcaption', firstElement)[0]);
221
+ }
222
+
223
+ firstElement.remove();
224
+ }
213
225
  }
214
226
  }
215
227
  }
@@ -240,25 +252,32 @@ const processContent = (post, siteUrl, options) => {
240
252
  const buildCard = audioCard.render(cardOpts);
241
253
  const cardHTML = buildCard.nodeValue;
242
254
 
243
- $html('.migrate-substack-wrapper').prepend(cardHTML);
255
+ const wrapper = parsed.$('.migrate-substack-wrapper')[0];
256
+ wrapper.insertAdjacentHTML('afterbegin', cardHTML);
244
257
  }
245
258
  }
246
259
 
247
- $html('div.tweet').each((i, el) => {
248
- let src = $html(el).children('a').attr('href');
249
- let parsed = url.parse(src);
260
+ parsed.$('div.tweet').forEach((el) => {
261
+ let childAnchors = parsed.$(':scope > a', el);
262
+ let src = attr(childAnchors[0], 'href');
263
+ let parsedUrl = url.parse(src);
250
264
 
251
- if (parsed.search) {
265
+ if (parsedUrl.search) {
252
266
  // remove possible query params
253
- parsed.search = null;
267
+ parsedUrl.search = null;
254
268
  }
255
- src = url.format(parsed, {search: false});
256
-
257
- let tweetText = $html(el)?.find('.tweet-text')?.html()?.replace(/(?:\r\n|\r|\n)/g, '<br>') ?? false;
258
- let tweetAuthorName = $html(el)?.find('.tweet-author-name')?.html()?.trim() ?? false;
259
- let tweetAuthorHandle = $html(el)?.find('.tweet-author-handle')?.html()?.trim() ?? false;
260
- let tweetDateTime = $html(el)?.find('.tweet-date')?.text()?.trim() ?? false;
261
- let tweetURL = $html(el)?.find('.tweet-link-top')?.attr('href') ?? false;
269
+ src = url.format(parsedUrl, {search: false});
270
+
271
+ const tweetTextEl = parsed.$('.tweet-text', el)[0];
272
+ let tweetText = tweetTextEl ? serializeChildren(tweetTextEl).replace(/(?:\r\n|\r|\n)/g, '<br>') : false;
273
+ const tweetAuthorNameEl = parsed.$('.tweet-author-name', el)[0];
274
+ let tweetAuthorName = tweetAuthorNameEl ? serializeChildren(tweetAuthorNameEl).trim() : false;
275
+ const tweetAuthorHandleEl = parsed.$('.tweet-author-handle', el)[0];
276
+ let tweetAuthorHandle = tweetAuthorHandleEl ? serializeChildren(tweetAuthorHandleEl).trim() : false;
277
+ const tweetDateTimeEl = parsed.$('.tweet-date', el)[0];
278
+ let tweetDateTime = tweetDateTimeEl ? (tweetDateTimeEl.textContent || '').trim() : false;
279
+ const tweetLinkEl = parsed.$('.tweet-link-top', el)[0];
280
+ let tweetURL = tweetLinkEl ? attr(tweetLinkEl, 'href') : false;
262
281
 
263
282
  let theHtml = [];
264
283
 
@@ -286,21 +305,12 @@ const processContent = (post, siteUrl, options) => {
286
305
 
287
306
  theHtml.push(`</a>`);
288
307
 
289
- let $figure = $html('<figure class="kg-card kg-embed-card"></figure>');
290
- let $blockquote = $html(`<blockquote class="twitter-tweet">${theHtml.join(' ')}</blockquote>`);
291
- let $anchor = $html(`<a href="${src}"></a>`);
292
- let $script = $html('<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>');
293
-
294
- $blockquote.append($anchor);
295
-
296
- $figure.append($blockquote);
297
- $figure.append($script);
298
-
299
- $html(el).replaceWith($figure);
308
+ const tweetHtml = `<figure class="kg-card kg-embed-card"><blockquote class="twitter-tweet">${theHtml.join(' ')}<a href="${src}"></a></blockquote><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></figure>`;
309
+ replaceWith(el, tweetHtml);
300
310
  });
301
311
 
302
- $html('.image-gallery-embed').each((i, el) => {
303
- const attrs = $html(el).attr('data-attrs');
312
+ parsed.$('.image-gallery-embed').forEach((el) => {
313
+ const attrs = attr(el, 'data-attrs');
304
314
  const attrsObj = JSON.parse(attrs);
305
315
 
306
316
  let items = [];
@@ -331,21 +341,22 @@ const processContent = (post, siteUrl, options) => {
331
341
  }
332
342
  };
333
343
 
334
- $html(el).replaceWith(serializer.serialize(galleryCard.render(cardOpts)));
344
+ replaceWith(el, serializer.serialize(galleryCard.render(cardOpts)));
335
345
  });
336
346
 
337
- $html('[class*="ImageGallery-module__imageGallery"]').each((i, el) => {
338
- const $row = $html(el).find('[class*="ImageGallery-module__imageRow"]');
339
- const caption = $html(el).find('figcaption').html();
347
+ parsed.$('[class*="ImageGallery-module__imageGallery"]').forEach((el) => {
348
+ const rows = parsed.$('[class*="ImageGallery-module__imageRow"]', el);
349
+ const figcaptionEl = parsed.$('figcaption', el)[0];
350
+ const caption = figcaptionEl ? serializeChildren(figcaptionEl) : null;
340
351
 
341
352
  let items = [];
342
353
 
343
- $row.each((ii, row) => {
344
- const $pictures = $html(row).find('picture');
354
+ rows.forEach((row) => {
355
+ const pictures = parsed.$('picture', row);
345
356
 
346
- $pictures.each((iii, picture) => {
347
- const $img = $html(picture).find('img');
348
- const src = largestSrc($img);
357
+ pictures.forEach((picture) => {
358
+ const img = parsed.$('img', picture)[0];
359
+ const src = largestSrc(img);
349
360
  const dimensions = getImageDimensions(src);
350
361
 
351
362
  items.push({
@@ -372,14 +383,18 @@ const processContent = (post, siteUrl, options) => {
372
383
  }
373
384
  };
374
385
 
375
- $html(el).replaceWith(serializer.serialize(galleryCard.render(cardOpts)));
386
+ replaceWith(el, serializer.serialize(galleryCard.render(cardOpts)));
376
387
  });
377
388
 
378
- $html('.captioned-image-container').each((i, div) => {
379
- const imgAlt = $html(div).find('img[alt]').attr('alt') || '';
380
- const linkHref = $html(div).find('a.image-link').attr('href') || false;
381
- const imgCaption = $html(div).find('figcaption').html() || false;
382
- const imageSrc = largestSrc($html(div).find('img'));
389
+ parsed.$('.captioned-image-container').forEach((div) => {
390
+ const imgAltEl = parsed.$('img[alt]', div)[0];
391
+ const imgAlt = imgAltEl ? attr(imgAltEl, 'alt') : '';
392
+ const linkEl = parsed.$('a.image-link', div)[0];
393
+ const linkHref = linkEl ? attr(linkEl, 'href') : false;
394
+ const figcaptionEl = parsed.$('figcaption', div)[0];
395
+ const imgCaption = figcaptionEl ? serializeChildren(figcaptionEl) : false;
396
+ const imgEl = parsed.$('img', div)[0];
397
+ const imageSrc = largestSrc(imgEl);
383
398
 
384
399
  let cardOpts = {
385
400
  env: {dom: new SimpleDom.Document()},
@@ -394,13 +409,15 @@ const processContent = (post, siteUrl, options) => {
394
409
  cardOpts.payload.href = linkHref;
395
410
  }
396
411
 
397
- $html(div).replaceWith(serializer.serialize(imageCard.render(cardOpts)));
412
+ replaceWith(div, serializer.serialize(imageCard.render(cardOpts)));
398
413
  });
399
414
 
400
- $html('.image-link').each((i, anchor) => {
401
- const imgAlt = $html(anchor).find('img[alt]').attr('alt') || '';
402
- const linkHref = $html(anchor).attr('href');
403
- const imageSrc = largestSrc($html(anchor).find('img'));
415
+ parsed.$('.image-link').forEach((anchor) => {
416
+ const imgAltEl = parsed.$('img[alt]', anchor)[0];
417
+ const imgAlt = imgAltEl ? attr(imgAltEl, 'alt') : '';
418
+ const linkHref = attr(anchor, 'href');
419
+ const imgEl = parsed.$('img', anchor)[0];
420
+ const imageSrc = largestSrc(imgEl);
404
421
 
405
422
  let cardOpts = {
406
423
  env: {dom: new SimpleDom.Document()},
@@ -416,13 +433,16 @@ const processContent = (post, siteUrl, options) => {
416
433
  cardOpts.payload.href = linkHref;
417
434
  }
418
435
 
419
- $html(anchor).replaceWith(serializer.serialize(imageCard.render(cardOpts)));
436
+ replaceWith(anchor, serializer.serialize(imageCard.render(cardOpts)));
420
437
  });
421
438
 
422
- $html('.file-embed-wrapper').each((i, el) => {
423
- const fileSrc = $html(el).find('.file-embed-button').attr('href');
424
- const fileTitle = $html(el).find('.file-embed-details-h1').text();
425
- const fileDetails = $html(el).find('.file-embed-details-h2').text();
439
+ parsed.$('.file-embed-wrapper').forEach((el) => {
440
+ const fileSrcEl = parsed.$('.file-embed-button', el)[0];
441
+ const fileSrc = attr(fileSrcEl, 'href');
442
+ const fileTitleEl = parsed.$('.file-embed-details-h1', el)[0];
443
+ const fileTitle = fileTitleEl ? fileTitleEl.textContent : '';
444
+ const fileDetailsEl = parsed.$('.file-embed-details-h2', el)[0];
445
+ const fileDetails = fileDetailsEl ? fileDetailsEl.textContent : '';
426
446
 
427
447
  const fileSizeMatch = fileDetails.match(/([\d.]+)([KMGT]B)/i);
428
448
  let fileSizeBytes = 0;
@@ -459,15 +479,15 @@ const processContent = (post, siteUrl, options) => {
459
479
  }
460
480
  };
461
481
 
462
- $html(el).replaceWith(serializer.serialize(fileCard.render(cardOpts)));
482
+ replaceWith(el, serializer.serialize(fileCard.render(cardOpts)));
463
483
  });
464
484
 
465
- $html('.comment').each((i, el) => {
466
- $html(el).remove();
485
+ parsed.$('.comment').forEach((el) => {
486
+ el.remove();
467
487
  });
468
488
 
469
- $html('.digest-post-embed').each((i, el) => {
470
- const attrsRaw = $html(el).attr('data-attrs');
489
+ parsed.$('.digest-post-embed').forEach((el) => {
490
+ const attrsRaw = attr(el, 'data-attrs');
471
491
 
472
492
  let attrs;
473
493
 
@@ -505,56 +525,56 @@ const processContent = (post, siteUrl, options) => {
505
525
 
506
526
  const bookmarkHtml = serializer.serialize(bookmarkCard.render(cardOpts));
507
527
 
508
- $html(el).replaceWith(bookmarkHtml);
528
+ replaceWith(el, bookmarkHtml);
509
529
  });
510
530
 
511
- $html('a > style').each((i, style) => {
512
- $html(style).remove();
531
+ parsed.$('a > style').forEach((style) => {
532
+ style.remove();
513
533
  });
514
534
 
515
- $html('ul, ol').each((i, list) => {
516
- if ($html(list).find('img, div, figure, blockquote, .button-wrapper').length) {
517
- $html(list).before('<!--kg-card-begin: html-->');
518
- $html(list).after('<!--kg-card-end: html-->');
535
+ parsed.$('ul, ol').forEach((list) => {
536
+ if (parsed.$('img, div, figure, blockquote, .button-wrapper', list).length) {
537
+ insertBefore(list, '<!--kg-card-begin: html-->');
538
+ insertAfter(list, '<!--kg-card-end: html-->');
519
539
  }
520
540
  });
521
541
 
522
542
  // Remove Substack share buttons
523
- $html('p.button-wrapper').each((i, button) => {
524
- let shareLinks = $html(button).children('a.button');
543
+ parsed.$('p.button-wrapper').forEach((button) => {
544
+ let shareLinks = parsed.$(':scope > a.button', button);
525
545
  if (shareLinks.length === 1 && siteUrl) {
526
- let shareLink = $html(shareLinks).get(0);
527
- let src = $html(shareLink).attr('href');
528
- let parsed = url.parse(src);
546
+ let shareLink = shareLinks[0];
547
+ let src = attr(shareLink, 'href');
548
+ let parsedUrl = url.parse(src);
529
549
 
530
550
  // If it's a share button, there's no use for it and completely remove the button
531
- if (parsed.search && parsed.search.indexOf('action=share') >= 0) {
532
- $html(button).remove();
551
+ if (parsedUrl.search && parsedUrl.search.indexOf('action=share') >= 0) {
552
+ button.remove();
533
553
  return;
534
554
  }
535
555
 
536
556
  // If it's a gift button, there's no use for it and completely remove the button
537
- if (parsed.search && parsed.search.indexOf('gift=true') >= 0) {
538
- $html(button).remove();
557
+ if (parsedUrl.search && parsedUrl.search.indexOf('gift=true') >= 0) {
558
+ button.remove();
539
559
  return;
540
560
  }
541
561
  }
542
562
  });
543
563
 
544
564
  // Update button elements
545
- $html('p.button-wrapper').each((i, button) => {
546
- let buttons = $html(button).children('a.button');
565
+ parsed.$('p.button-wrapper').forEach((button) => {
566
+ let buttons = parsed.$(':scope > a.button', button);
547
567
  if (buttons.length === 1 && siteUrl) {
548
568
  let siteRegex = new RegExp(`^(?:${siteUrl}(?:\\/?)(?:p\\/)?)([a-zA-Z-_\\d]*)(?:\\/?)`, 'gi');
549
- let buttonLink = $html(buttons).get(0);
550
- let buttonHref = $html(buttonLink).attr('href');
551
- let buttonText = $html(buttonLink).text();
552
- let parsed = url.parse(buttonHref);
569
+ let buttonLink = buttons[0];
570
+ let buttonHref = attr(buttonLink, 'href');
571
+ let buttonText = buttonLink.textContent;
572
+ let parsedUrl = url.parse(buttonHref);
553
573
 
554
574
  // remove possible query params
555
- parsed.search = null;
575
+ parsedUrl.search = null;
556
576
 
557
- buttonHref = url.format(parsed, {search: false});
577
+ buttonHref = url.format(parsedUrl, {search: false});
558
578
 
559
579
  if (buttonHref.match(siteRegex)) {
560
580
  buttonHref = buttonHref.replace(siteRegex, '/$1/');
@@ -562,7 +582,7 @@ const processContent = (post, siteUrl, options) => {
562
582
 
563
583
  if (buttonHref === '/subscribe/') {
564
584
  if (options.noSubscribeButtons) {
565
- $html(button).remove();
585
+ button.remove();
566
586
  return;
567
587
  }
568
588
  buttonHref = options.subscribeLink || '#/portal/signup';
@@ -572,63 +592,67 @@ const processContent = (post, siteUrl, options) => {
572
592
  buttonHref = options.commentLink || '#ghost-comments-root';
573
593
 
574
594
  if (!options.comments) {
575
- $html(button).remove();
595
+ button.remove();
576
596
  return;
577
597
  }
578
598
  }
579
599
 
580
- $html(button).replaceWith(`<div class="kg-card kg-button-card kg-align-center"><a href="${buttonHref}" class="kg-btn kg-btn-accent">${buttonText}</a></div>`);
600
+ replaceWith(button, `<div class="kg-card kg-button-card kg-align-center"><a href="${buttonHref}" class="kg-btn kg-btn-accent">${buttonText}</a></div>`);
581
601
  }
582
602
  });
583
603
 
584
604
  // TODO: this should be a parser plugin
585
605
  // Wrap nested lists in HTML card
586
- $html('ul li ul, ol li ol, ol li ul, ul li ol').each((i, nestedList) => {
587
- let $parent = $html(nestedList).parentsUntil('ul, ol').parent();
588
- $parent.before('<!--kg-card-begin: html-->');
589
- $parent.after('<!--kg-card-end: html-->');
606
+ parsed.$('ul li ul, ol li ol, ol li ul, ul li ol').forEach((nestedList) => {
607
+ const parentList = parents(nestedList, 'ul, ol')[0];
608
+ if (parentList) {
609
+ insertBefore(parentList, '<!--kg-card-begin: html-->');
610
+ insertAfter(parentList, '<!--kg-card-end: html-->');
611
+ }
590
612
  });
591
613
 
592
614
  // Handle footnotes
593
- let footnotesMarkup = $html(`<div class="footnotes"><hr><ol></ol></div>`);
615
+ let footnotesItems = [];
594
616
  let footnotesCount = 0;
595
- $html('.footnote').each((i, el) => {
596
- let footnoteBodyAnchor = $html(el).find('a').attr('href');
597
-
598
- let footnoteID = null;
599
- if ($html(el).attr('id')) {
600
- footnoteID = $html(el).attr('id');
601
- } else {
602
- footnoteID = $html(el).find('a').attr('id');
603
- }
617
+ parsed.$('.footnote').forEach((el) => {
618
+ const footnoteAnchor = parsed.$('a', el)[0];
619
+ let footnoteBodyAnchor = attr(footnoteAnchor, 'href');
620
+
621
+ let footnoteID = attr(el, 'id') || attr(footnoteAnchor, 'id');
604
622
 
605
623
  let footnoteNumber = footnoteID.replace('footnote-', '');
606
- let footnoteContent = $html(el).find('.footnote-content');
624
+ let footnoteContent = parsed.$('.footnote-content', el)[0];
607
625
 
608
- footnoteContent.find('p').last().append(` <a href="${footnoteBodyAnchor}" title="Jump back to footnote ${footnoteNumber} in the text.">↩</a>`);
609
- footnotesMarkup.find('ol').append(`<li id="${footnoteID}">${footnoteContent.html()}</li>`);
610
- $html(el).remove();
626
+ const pElements = parsed.$('p', footnoteContent);
627
+ const lastP = pElements[pElements.length - 1];
628
+ if (lastP) {
629
+ lastP.insertAdjacentHTML('beforeend', ` <a href="${footnoteBodyAnchor}" title="Jump back to footnote ${footnoteNumber} in the text.">↩</a>`);
630
+ }
631
+
632
+ footnotesItems.push(`<li id="${footnoteID}">${serializeChildren(footnoteContent)}</li>`);
633
+ el.remove();
611
634
 
612
635
  footnotesCount = footnotesCount + 1;
613
636
  });
614
637
 
615
638
  if (footnotesCount > 0) {
616
- let footnotedHTML = $html.html($html(footnotesMarkup));
617
- $html('.migrate-substack-wrapper').append(`<!--kg-card-begin: html-->${footnotedHTML}<!--kg-card-end: html-->`);
639
+ let footnotedHTML = `<div class="footnotes"><hr><ol>${footnotesItems.join('')}</ol></div>`;
640
+ const wrapper = parsed.$('.migrate-substack-wrapper')[0];
641
+ wrapper.insertAdjacentHTML('beforeend', `<!--kg-card-begin: html-->${footnotedHTML}<!--kg-card-end: html-->`);
618
642
  }
619
643
 
620
644
  // Wrap content that has footnote anchors in HTML tags to retain the footnote jump anchor
621
- $html('p, ul, ol').each((i, el) => {
622
- if ($html(el).find('a.footnote-anchor').length > 0) {
623
- $html(el).before('<!--kg-card-begin: html-->');
624
- $html(el).after('<!--kg-card-end: html-->');
645
+ parsed.$('p, ul, ol').forEach((el) => {
646
+ if (parsed.$('a.footnote-anchor', el).length > 0) {
647
+ insertBefore(el, '<!--kg-card-begin: html-->');
648
+ insertAfter(el, '<!--kg-card-end: html-->');
625
649
  }
626
650
  });
627
651
 
628
652
  // Remove or replace subscribe links on the same domain
629
653
  if (options.noSubscribeButtons) {
630
- $html('a').each((i, anchor) => {
631
- let href = $html(anchor).attr('href');
654
+ parsed.$('a').forEach((anchor) => {
655
+ let href = attr(anchor, 'href');
632
656
  let linkRegex = new RegExp(`^(${siteUrl})?(/subscribe)(.*)`, 'gi');
633
657
 
634
658
  if (!href) {
@@ -638,12 +662,12 @@ const processContent = (post, siteUrl, options) => {
638
662
  let matches = href.replace(linkRegex, '$2');
639
663
 
640
664
  if (matches === '/subscribe') {
641
- $html(anchor).remove();
665
+ anchor.remove();
642
666
  }
643
667
  });
644
668
  } else if (options.subscribeLink) {
645
- $html('a').each((i, anchor) => {
646
- let href = $html(anchor).attr('href');
669
+ parsed.$('a').forEach((anchor) => {
670
+ let href = attr(anchor, 'href');
647
671
  let linkRegex = new RegExp(`^(${siteUrl})?(/subscribe)(.*)`, 'gi');
648
672
 
649
673
  if (!href) {
@@ -653,29 +677,30 @@ const processContent = (post, siteUrl, options) => {
653
677
  let matches = href.replace(linkRegex, '$2');
654
678
 
655
679
  if (matches === '/subscribe') {
656
- $html(anchor).attr('href', options.subscribeLink);
680
+ attr(anchor, 'href', options.subscribeLink);
657
681
  }
658
682
  });
659
683
  }
660
684
 
661
685
  // Remove or replace signup forms with a Portal signup button
662
686
  if (options.noSubscribeButtons) {
663
- $html('.subscription-widget-wrap, .subscription-widget-wrap-editor').each((i, div) => {
664
- $html(div).remove();
687
+ parsed.$('.subscription-widget-wrap, .subscription-widget-wrap-editor').forEach((div) => {
688
+ div.remove();
665
689
  });
666
690
  } else if (options.subscribeLink) {
667
- $html('.subscription-widget-wrap, .subscription-widget-wrap-editor').each((i, div) => {
668
- const hasForm = $html(div).find('form');
691
+ parsed.$('.subscription-widget-wrap, .subscription-widget-wrap-editor').forEach((div) => {
692
+ const hasForm = parsed.$('form', div);
669
693
 
670
694
  if (hasForm.length) {
671
- const buttonText = $html(div).find('form input[type="submit"]').attr('value');
672
- $html(div).replaceWith(`<div class="kg-card kg-button-card kg-align-center"><a href="${options.subscribeLink}" class="kg-btn kg-btn-accent">${buttonText}</a></div>`);
695
+ const submitEl = parsed.$('form input[type="submit"]', div)[0];
696
+ const buttonText = submitEl ? attr(submitEl, 'value') : '';
697
+ replaceWith(div, `<div class="kg-card kg-button-card kg-align-center"><a href="${options.subscribeLink}" class="kg-btn kg-btn-accent">${buttonText}</a></div>`);
673
698
  }
674
699
  });
675
700
  }
676
701
 
677
- $html('.embedded-post-wrap').each((i, div) => {
678
- const attrs = $html(div).attr('data-attrs') || false;
702
+ parsed.$('.embedded-post-wrap').forEach((div) => {
703
+ const attrs = attr(div, 'data-attrs') || false;
679
704
 
680
705
  if (!attrs) {
681
706
  return;
@@ -690,65 +715,53 @@ const processContent = (post, siteUrl, options) => {
690
715
  let bookmarkTitle = bookmarkJSON.title;
691
716
  let bookmarkContent = bookmarkJSON.truncated_body_text;
692
717
 
693
- let $bookmark = $html('<figure class="kg-card kg-bookmark-card"></figure>');
694
- let $link = $html(`<a class="kg-bookmark-container" href="${bookmarkLink}"></a>`);
695
- let $content = $html(`<div class="kg-bookmark-content"><div class="kg-bookmark-title">${bookmarkTitle}</div><div class="kg-bookmark-description">${bookmarkContent}</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="${bookmarkPubIcon}"><span class="kg-bookmark-author">${bookmarkPubName}</span></div></div>`);
696
-
697
- $link.append($content);
698
- $bookmark.append($link);
718
+ const embeddedHtml = `<figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="${bookmarkLink}"><div class="kg-bookmark-content"><div class="kg-bookmark-title">${bookmarkTitle}</div><div class="kg-bookmark-description">${bookmarkContent}</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="${bookmarkPubIcon}"><span class="kg-bookmark-author">${bookmarkPubName}</span></div></div></a></figure>`;
699
719
 
700
- $html(div).replaceWith($bookmark);
701
- $bookmark.before('<!--kg-card-begin: html-->');
702
- $bookmark.after('<!--kg-card-end: html-->');
720
+ replaceWith(div, `<!--kg-card-begin: html-->${embeddedHtml}<!--kg-card-end: html-->`);
703
721
  });
704
722
 
705
- $html('div.instagram').each((i, el) => {
706
- let src = $html(el).find('a.instagram-image').attr('href');
723
+ parsed.$('div.instagram').forEach((el) => {
724
+ const instagramLink = parsed.$('a.instagram-image', el)[0];
725
+ let src = instagramLink ? attr(instagramLink, 'href') : '';
707
726
 
708
727
  if (!src) {
709
728
  return;
710
729
  }
711
730
 
712
- let parsed = url.parse(src);
731
+ let parsedUrl = url.parse(src);
713
732
 
714
- if (parsed.search) {
733
+ if (parsedUrl.search) {
715
734
  // remove possible query params
716
- parsed.search = null;
735
+ parsedUrl.search = null;
717
736
  }
718
- src = url.format(parsed, {search: false});
719
-
720
- let $iframe = $html('<iframe class="instagram-media instagram-media-rendered" id="instagram-embed-0" allowtransparency="true" allowfullscreen="true" frameborder="0" height="968" data-instgrm-payload-id="instagram-media-payload-0" scrolling="no" style="background: white; max-width: 658px; width: calc(100% - 2px); border-radius: 3px; border: 1px solid rgb(219, 219, 219); box-shadow: none; display: block; margin: 0px 0px 12px; min-width: 326px; padding: 0px;"></iframe>');
721
- let $script = $html('<script async="" src="//www.instagram.com/embed.js"></script>');
722
- let $figure = $html('<figure class="instagram"></figure>');
737
+ src = url.format(parsedUrl, {search: false});
723
738
 
724
739
  // Trim the trailing slash from src if it exists
725
740
  if (src.endsWith('/')) {
726
741
  src = src.slice(0, -1);
727
742
  }
728
743
 
729
- $iframe.attr('src', `${src}/embed/captioned/`);
730
- $figure.append($iframe);
731
- $figure.append($script);
732
-
733
- $html(el).replaceWith($figure);
744
+ const instagramHtml = `<figure class="instagram"><iframe class="instagram-media instagram-media-rendered" id="instagram-embed-0" allowtransparency="true" allowfullscreen="true" frameborder="0" height="968" data-instgrm-payload-id="instagram-media-payload-0" scrolling="no" style="background: white; max-width: 658px; width: calc(100% - 2px); border-radius: 3px; border: 1px solid rgb(219, 219, 219); box-shadow: none; display: block; margin: 0px 0px 12px; min-width: 326px; padding: 0px;" src="${src}/embed/captioned/"></iframe><script async="" src="//www.instagram.com/embed.js"></script></figure>`;
745
+ replaceWith(el, instagramHtml);
734
746
  });
735
747
 
736
748
  // For each image and link, alter the path to remove cropping & sizing for image paths
737
- $html('img[src], a[href]').each((i, el) => {
738
- const src = $html(el).attr('src');
739
- const href = $html(el).attr('href');
749
+ parsed.$('img[src], a[href]').forEach((el) => {
750
+ const src = attr(el, 'src');
751
+ const href = attr(el, 'href');
740
752
 
741
753
  if (src) {
742
- $html(el).attr('src', largeImageUrl(src));
754
+ attr(el, 'src', largeImageUrl(src));
743
755
  }
744
756
 
745
757
  if (href) {
746
- $html(el).attr('href', largeImageUrl(href));
758
+ attr(el, 'href', largeImageUrl(href));
747
759
  }
748
760
  });
749
761
 
750
762
  // convert HTML back to a string
751
- html = $html('.migrate-substack-wrapper').html();
763
+ const wrapper = parsed.$('.migrate-substack-wrapper')[0];
764
+ html = serializeChildren(wrapper);
752
765
 
753
766
  // Remove empty attributes
754
767
  html = html.replace(/=""/g, '');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tryghost/mg-substack",
3
- "version": "0.8.9",
3
+ "version": "0.9.0",
4
4
  "repository": "https://github.com/TryGhost/migrate/tree/main/packages/mg-substack",
5
5
  "author": "Ghost Foundation",
6
6
  "license": "MIT",
@@ -8,7 +8,7 @@
8
8
  "type": "module",
9
9
  "scripts": {
10
10
  "dev": "echo \"Implement me!\"",
11
- "test": "NODE_OPTIONS=--experimental-vm-modules jest",
11
+ "test": "node --test 'test/**/*.test.js'",
12
12
  "lint": "eslint . --ext .js --cache",
13
13
  "posttest": "yarn lint"
14
14
  },
@@ -20,22 +20,20 @@
20
20
  "access": "public"
21
21
  },
22
22
  "devDependencies": {
23
- "eslint": "8.57.0",
24
- "jest": "30.2.0",
25
- "jest-extended": "7.0.0"
23
+ "eslint": "8.57.1"
26
24
  },
27
25
  "dependencies": {
28
- "@tryghost/debug": "0.1.36",
29
- "@tryghost/errors": "1.3.8",
30
- "@tryghost/kg-default-cards": "10.2.6",
31
- "@tryghost/mg-fs-utils": "0.16.4",
32
- "@tryghost/string": "0.2.21",
33
- "cheerio": "1.2.0",
26
+ "@tryghost/debug": "2.0.1",
27
+ "@tryghost/errors": "3.0.1",
28
+ "@tryghost/kg-default-cards": "10.2.8",
29
+ "@tryghost/mg-fs-utils": "0.16.6",
30
+ "@tryghost/mg-utils": "0.1.0",
31
+ "@tryghost/string": "0.3.1",
34
32
  "he": "1.2.0",
35
33
  "html-entities": "2.6.0",
36
34
  "lodash": "4.17.23",
37
35
  "simple-dom": "1.4.0",
38
36
  "srcset": "5.0.3"
39
37
  },
40
- "gitHead": "ac9a868976ef5963df7fc2426af9e298bd5d8666"
38
+ "gitHead": "e1680568191322d738c188f03298910aa3622735"
41
39
  }