@tryghost/mg-tinynews 0.10.8-0 → 0.11.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.
Files changed (42) hide show
  1. package/README.md +112 -30
  2. package/build/index.d.ts +8 -0
  3. package/build/index.js +5 -0
  4. package/build/index.js.map +1 -0
  5. package/build/lib/ingest.d.ts +18 -0
  6. package/build/lib/ingest.js +91 -0
  7. package/build/lib/ingest.js.map +1 -0
  8. package/build/lib/json-to-html.d.ts +35 -0
  9. package/build/lib/json-to-html.js +238 -0
  10. package/build/lib/json-to-html.js.map +1 -0
  11. package/build/lib/map.d.ts +26 -0
  12. package/build/lib/map.js +209 -0
  13. package/build/lib/map.js.map +1 -0
  14. package/build/lib/process.d.ts +76 -0
  15. package/build/lib/process.js +235 -0
  16. package/build/lib/process.js.map +1 -0
  17. package/build/lib/text.d.ts +6 -0
  18. package/build/lib/text.js +60 -0
  19. package/build/lib/text.js.map +1 -0
  20. package/build/lib/types.d.ts +112 -0
  21. package/build/lib/types.js +3 -0
  22. package/build/lib/types.js.map +1 -0
  23. package/build/test/helpers.d.ts +25 -0
  24. package/build/test/helpers.js +74 -0
  25. package/build/test/helpers.js.map +1 -0
  26. package/build/test/ingest.test.d.ts +1 -0
  27. package/build/test/ingest.test.js +134 -0
  28. package/build/test/ingest.test.js.map +1 -0
  29. package/build/test/json-to-html.test.d.ts +1 -0
  30. package/build/test/json-to-html.test.js +662 -0
  31. package/build/test/json-to-html.test.js.map +1 -0
  32. package/build/test/map.test.d.ts +1 -0
  33. package/build/test/map.test.js +367 -0
  34. package/build/test/map.test.js.map +1 -0
  35. package/build/test/process.test.d.ts +1 -0
  36. package/build/test/process.test.js +261 -0
  37. package/build/test/process.test.js.map +1 -0
  38. package/package.json +24 -10
  39. package/index.js +0 -7
  40. package/lib/json-to-html.js +0 -324
  41. package/lib/mapper.js +0 -368
  42. package/lib/text.js +0 -95
@@ -0,0 +1,26 @@
1
+ import { MigrateContext } from '@tryghost/mg-context';
2
+ import type { MappingSummary, SourceRecord } from '@tryghost/mg-context';
3
+ import type { GhostUser } from '@tryghost/mg-ghost-authors';
4
+ import type { TinyNewsOptions } from './types.js';
5
+ export type { MappingSummary };
6
+ export interface MappingServices {
7
+ /** Existing Ghost users; an author whose email matches one keeps that user's ID, slug and roles. */
8
+ ghostUsers?: Iterable<GhostUser> | AsyncIterable<GhostUser>;
9
+ }
10
+ /** A stable Ghost ID for a post key, tag slug or author key, scoped to the site. */
11
+ export declare function ghostId(site: string, kind: string, key: string): string;
12
+ /**
13
+ * The URL of a stored article, page or newsletter on the live site, or `null` when it has none: an article's or
14
+ * page's `live_url`, or `<url>/newsletters/<slug>` for a newsletter.
15
+ */
16
+ export declare function sourceUrl(options: TinyNewsOptions, record: SourceRecord): string | null;
17
+ /**
18
+ * Rebuild posts, tags and authors from the stored export. Articles become posts and pages become pages, published
19
+ * or draft as in Tiny News, from their first translation, with their category and tags (internal when unpublished)
20
+ * and `#tinynews`. Newsletter editions become published posts tagged `#newsletter` and `#tinynews`, by the
21
+ * Newsletter author. Records without a key or translation, published records without a valid date, and records with
22
+ * more than 500 tags are skipped with a `record:skipped` diagnostic. Content blocks that cannot be converted are left
23
+ * out with an `operation:warning`. A draft without a date is dated when the export was read, so remapping is
24
+ * repeatable.
25
+ */
26
+ export declare function map(options: TinyNewsOptions, context: MigrateContext, services?: MappingServices): Promise<MappingSummary>;
@@ -0,0 +1,209 @@
1
+ import { AuthorContext, MappingState, PostContext, RecordDataError, TagContext, ghostId as coreGhostId } from '@tryghost/mg-context';
2
+ import { mergeUsersWithGhost } from '@tryghost/mg-ghost-authors';
3
+ import { stringUtils, urlUtils } from '@tryghost/mg-utils';
4
+ import { DEFAULT_AUTHOR, NEWSLETTER_AUTHOR, emailAuthor, newsletterUrl, personAuthor, processArticle, processNewsletter } from './process.js';
5
+ const ROLES = ['Contributor', 'Author', 'Editor', 'Administrator'];
6
+ /** Ghost relationship limit for one post. */
7
+ const MAX_RELATIONS = 500;
8
+ const LABELS = { article: 'Article', page: 'Page', newsletter: 'Newsletter' };
9
+ /** A stable Ghost ID for a post key, tag slug or author key, scoped to the site. */
10
+ export function ghostId(site, kind, key) {
11
+ return coreGhostId('mg-tinynews:1', site, kind, key);
12
+ }
13
+ /** The live site's URL without a trailing slash, and its host and path, which scope stable Ghost IDs to one site. */
14
+ function site(value) {
15
+ const url = urlUtils.httpUrl(value);
16
+ if (!url) {
17
+ throw new Error('Tiny News migrations need the site URL (--url) as an HTTP or HTTPS URL.');
18
+ }
19
+ return { url: urlUtils.trimTrailingSlashes(url.href), scope: urlUtils.canonicalSite(url) };
20
+ }
21
+ /**
22
+ * The URL of a stored article, page or newsletter on the live site, or `null` when it has none: an article's or
23
+ * page's `live_url`, or `<url>/newsletters/<slug>` for a newsletter.
24
+ */
25
+ export function sourceUrl(options, record) {
26
+ const item = JSON.parse(record.content);
27
+ return record.metadata.type === 'newsletter'
28
+ ? newsletterUrl(site(options.url).url, item)
29
+ : (urlUtils.httpUrl(item.live_url)?.href ?? null);
30
+ }
31
+ /** Authors in the authors file are matched to an article's author by first names and last name. */
32
+ const nameKey = (author) => JSON.stringify([author.first_names ?? null, author.last_name ?? null]);
33
+ const placeholderEmail = (slug) => `${slug.slice(0, 50).replace(/-+$/, '')}@example.com`;
34
+ /**
35
+ * The saved author for a processed author, identified by its key, so authors whose slugs collide stay separate users
36
+ * with distinct slugs and placeholder emails. A Ghost user with the author's email supplies its ID, slug and roles.
37
+ */
38
+ function authorEntity(state, scope, source) {
39
+ const context = state.context;
40
+ const binding = state.getBinding('author', source.key);
41
+ if (binding) {
42
+ return AuthorContext.fromRow(context.db.stmts.findAuthorById.get(binding));
43
+ }
44
+ const base = source.slug || 'author';
45
+ let data = {
46
+ name: source.name,
47
+ slug: base,
48
+ email: source.email ?? placeholderEmail(base),
49
+ roles: ['Contributor'],
50
+ profile_image: source.profile_image,
51
+ bio: source.bio
52
+ };
53
+ const match = state.get('ghost-user', data.email.toLowerCase());
54
+ if (match) {
55
+ // Authors that share an email are the same Ghost user.
56
+ const same = state.getBinding('ghost-author', match.id);
57
+ if (same) {
58
+ state.bind('author', source.key, same);
59
+ return AuthorContext.fromRow(context.db.stmts.findAuthorById.get(same));
60
+ }
61
+ data = { ...mergeUsersWithGhost([{ url: '', data: data }], [match])[0].data };
62
+ }
63
+ const id = data.id || ghostId(scope, 'author', source.key);
64
+ delete data.id;
65
+ if (data.roles.some((role) => !ROLES.includes(role))) {
66
+ context.recordDiagnostic('operation:warning', {
67
+ author: source.name,
68
+ reason: 'Unsupported author roles replaced by supported Ghost roles'
69
+ });
70
+ data.roles = data.roles.filter((role) => ROLES.includes(role));
71
+ if (!data.roles.length) {
72
+ data.roles = ['Contributor'];
73
+ }
74
+ }
75
+ data.slug = state.uniqueSlug('author', data.slug, id);
76
+ if (!match && !source.email && data.slug !== base) {
77
+ // Distinct authors need distinct emails as well as slugs.
78
+ data.email = placeholderEmail(data.slug);
79
+ }
80
+ const author = new AuthorContext();
81
+ for (const [field, value] of Object.entries(data)) {
82
+ if (value !== undefined) {
83
+ author.set(field, value);
84
+ }
85
+ }
86
+ author.ghostId = id;
87
+ author.save(context.db);
88
+ state.bind('author', source.key, author.dbId);
89
+ state.bind('ghost-author', id, author.dbId);
90
+ return author;
91
+ }
92
+ /** The saved tag for a slug; the first name seen for a slug is kept. */
93
+ function tagEntity(state, scope, source) {
94
+ const context = state.context;
95
+ const binding = state.getBinding('tag', source.slug);
96
+ if (binding) {
97
+ return TagContext.fromRow(context.db.stmts.findTagById.get(binding));
98
+ }
99
+ const id = ghostId(scope, 'tag', source.slug);
100
+ const tag = new TagContext({ name: source.name, slug: state.uniqueSlug('tag', source.slug, id) });
101
+ tag.ghostId = id;
102
+ tag.save(context.db);
103
+ state.bind('tag', source.slug, tag.dbId);
104
+ return tag;
105
+ }
106
+ /**
107
+ * An article's or page's author: its first author, enriched from the matching author in the authors file; otherwise
108
+ * its translation's `created_by_email`; otherwise the only author in the authors file; otherwise the default author.
109
+ * Also returns the authors-file record that contributed, if any.
110
+ */
111
+ function articleAuthor(state, item, soleAuthor) {
112
+ const nested = item.author?.[0]?.author;
113
+ if (nested && typeof nested === 'object') {
114
+ const profile = state.find('author-name', nameKey(nested), 1)[0] ?? null;
115
+ const author = personAuthor(nested, profile && JSON.parse(profile.content));
116
+ if (author) {
117
+ return { author, profile };
118
+ }
119
+ }
120
+ const byEmail = emailAuthor(item.translations?.[0]?.created_by_email);
121
+ if (byEmail) {
122
+ return { author: byEmail, profile: null };
123
+ }
124
+ const sole = soleAuthor && personAuthor(JSON.parse(soleAuthor.content));
125
+ if (sole) {
126
+ return { author: sole, profile: soleAuthor };
127
+ }
128
+ return { author: DEFAULT_AUTHOR, profile: null };
129
+ }
130
+ /**
131
+ * Rebuild posts, tags and authors from the stored export. Articles become posts and pages become pages, published
132
+ * or draft as in Tiny News, from their first translation, with their category and tags (internal when unpublished)
133
+ * and `#tinynews`. Newsletter editions become published posts tagged `#newsletter` and `#tinynews`, by the
134
+ * Newsletter author. Records without a key or translation, published records without a valid date, and records with
135
+ * more than 500 tags are skipped with a `record:skipped` diagnostic. Content blocks that cannot be converted are left
136
+ * out with an `operation:warning`. A draft without a date is dated when the export was read, so remapping is
137
+ * repeatable.
138
+ */
139
+ export async function map(options, context, services = {}) {
140
+ if (!context.sources.hasCompletedIngestion) {
141
+ throw new Error('Ingest a complete Tiny News export before mapping.');
142
+ }
143
+ const { url: siteUrl, scope } = site(options.url);
144
+ const readAt = new Date(context.sources.currentIngestion.completedAt);
145
+ const state = new MappingState(context, 'mg-tinynews');
146
+ return context.rebuildMappedContent(async () => {
147
+ for await (const user of services.ghostUsers ?? []) {
148
+ state.reserveSlug('author', user.slug, user.id);
149
+ if (user.email) {
150
+ state.set('ghost-user', user.email.toLowerCase(), user);
151
+ }
152
+ }
153
+ let soleAuthor = null;
154
+ for await (const record of context.sources.records({ kind: 'author' })) {
155
+ state.index('author-name', nameKey(JSON.parse(record.content)), record.id);
156
+ soleAuthor = record;
157
+ }
158
+ if (context.sources.count('author') !== 1) {
159
+ soleAuthor = null;
160
+ }
161
+ return context.mapRecords(context.sources.records({ kind: 'post' }), async (record) => {
162
+ const type = String(record.metadata.type);
163
+ const label = LABELS[type];
164
+ if (!record.key) {
165
+ throw new RecordDataError(`${label} has no id or slug`);
166
+ }
167
+ const item = JSON.parse(record.content);
168
+ const processed = type === 'newsletter'
169
+ ? processNewsletter(item, siteUrl)
170
+ : processArticle(item, type === 'page' ? 'page' : 'post', {
171
+ onUnhandled: reason => context.recordDiagnostic('operation:warning', { ...record.metadata, reason }, record.id)
172
+ });
173
+ const published = processed.published ?? (processed.fields.status === 'draft' ? readAt : null);
174
+ if (!published) {
175
+ throw new RecordDataError(`Published ${label.toLowerCase()} has no valid date`);
176
+ }
177
+ if (processed.tags.length > MAX_RELATIONS) {
178
+ throw new RecordDataError('Post exceeds Ghost tag relationship limit');
179
+ }
180
+ const post = new PostContext({ lookupKey: record.key });
181
+ post.ghostId = ghostId(scope, 'post', record.key);
182
+ for (const [field, value] of Object.entries(processed.fields)) {
183
+ post.set(field, value);
184
+ }
185
+ post.set('created_at', processed.created ?? published);
186
+ post.set('published_at', published);
187
+ post.set('updated_at', processed.updated ?? published);
188
+ const { author, profile } = type === 'newsletter'
189
+ ? { author: NEWSLETTER_AUTHOR, profile: null }
190
+ : articleAuthor(state, item, soleAuthor);
191
+ const authorContext = authorEntity(state, scope, author);
192
+ post.addAuthor(authorContext);
193
+ context.sources.link(record.id, { type: 'author', id: authorContext.dbId });
194
+ if (profile) {
195
+ context.sources.link(profile.id, { type: 'author', id: authorContext.dbId });
196
+ }
197
+ for (const tag of processed.tags.map(source => tagEntity(state, scope, source))) {
198
+ post.addTag(tag);
199
+ context.sources.link(record.id, { type: 'tag', id: tag.dbId });
200
+ }
201
+ post.save(context.db);
202
+ context.sources.link(record.id, { type: 'post', id: post.dbId });
203
+ if (processed.url) {
204
+ context.addLink(stringUtils.cleanURL(processed.url), `/${post.get('slug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,MAAM,CAAC,EAAE,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC;gBAC9E,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBACjB,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,EAAC,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE,GAAG,CAAC,IAAK,EAAC,CAAC,CAAC;YAClE,CAAC;YAED,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;YACtB,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,EAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,IAAI,CAAC,IAAK,EAAC,CAAC,CAAC;YAChE,IAAI,SAAS,CAAC,GAAG,EAAE,CAAC;gBAChB,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,QAAQ,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE,IAAI,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YAClF,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACP,CAAC"}
@@ -0,0 +1,76 @@
1
+ import { type JsonToHtmlOptions } from './json-to-html.js';
2
+ import type { TinyNewsArticle, TinyNewsAuthor, TinyNewsNewsletter } from './types.js';
3
+ /** A tag of a processed post. Internal tags have a `#` name and a `hash-` slug. */
4
+ export interface ProcessedTag {
5
+ name: string;
6
+ slug: string;
7
+ }
8
+ /** An author of a processed post. */
9
+ export interface ProcessedAuthor {
10
+ /** Identifies the author across posts: `email:<address>` when the email is known, otherwise `name:<name>`. */
11
+ key: string;
12
+ name: string;
13
+ slug: string;
14
+ /** The author's own email, or `null` for a `<slug>@example.com` placeholder. */
15
+ email: string | null;
16
+ profile_image?: string;
17
+ bio?: string;
18
+ }
19
+ /** An article, page or newsletter as Ghost post fields, without its authors. */
20
+ export interface ProcessedPost {
21
+ /** Ghost post fields other than dates, tags and authors. Blank optional fields are `null`. */
22
+ fields: {
23
+ title: string;
24
+ slug: string;
25
+ type: 'post' | 'page';
26
+ status: 'published' | 'draft';
27
+ visibility: 'public';
28
+ html: string;
29
+ custom_excerpt: string | null;
30
+ [field: string]: string | null;
31
+ };
32
+ /** The post's URL on the live site, or `null` when it has none. */
33
+ url: string | null;
34
+ /** When it was first published or sent, if known. */
35
+ published: Date | null;
36
+ /** When it was last published, if known. */
37
+ updated: Date | null;
38
+ /** When it was created, if known. */
39
+ created: Date | null;
40
+ /** Public tags first, then internal tags, one per slug. */
41
+ tags: ProcessedTag[];
42
+ }
43
+ /** The author of posts with no author, created_by_email or single author in the authors file. */
44
+ export declare const DEFAULT_AUTHOR: ProcessedAuthor;
45
+ /** The author of every newsletter. */
46
+ export declare const NEWSLETTER_AUTHOR: ProcessedAuthor;
47
+ /** A trimmed string, or `undefined` when the value is not a string or is blank. */
48
+ export declare function text(value: unknown): string | undefined;
49
+ /** The text of an HTML string, trimmed. */
50
+ export declare function textOnly(html: string): string;
51
+ /** An article's category, then its tags, then `#tinynews`. */
52
+ export declare function articleTags(item: TinyNewsArticle): ProcessedTag[];
53
+ /**
54
+ * An article or page from its first translation: its fields, URL, dates and tags. The feature image is the
55
+ * translation's main image or, for a page, the first `mainImage` block of its content. Content blocks that cannot be
56
+ * converted are left out and passed to `onUnhandled`. Throws `RecordDataError` when the item has no translation.
57
+ */
58
+ export declare function processArticle(item: TinyNewsArticle, type: 'post' | 'page', options?: JsonToHtmlOptions): ProcessedPost;
59
+ /**
60
+ * Clean a newsletter edition's HTML: keep basic formatting, links and images, turn `<div>`s into paragraphs, and
61
+ * remove the "Made with Letterhead" link and empty paragraphs. The result is one HTML card.
62
+ */
63
+ export declare function processNewsletterContent(html: string): string;
64
+ /** A newsletter edition's URL on the live site, `<site>/newsletters/<slug>`, or `null` when it has no slug. */
65
+ export declare function newsletterUrl(site: string, item: TinyNewsNewsletter): string | null;
66
+ /** A newsletter edition as a published post tagged `#newsletter` and `#tinynews`. */
67
+ export declare function processNewsletter(item: TinyNewsNewsletter, site: string): ProcessedPost;
68
+ /** An author's first names and last name. */
69
+ export declare function authorName(author: TinyNewsAuthor): string | undefined;
70
+ /**
71
+ * An author nested in an article or listed in the authors file, or `null` when it has no name. The email, photo and
72
+ * bio of `profile`, the matching author in the authors file, are preferred to the article's own.
73
+ */
74
+ export declare function personAuthor(author: TinyNewsAuthor, profile?: TinyNewsAuthor | null): ProcessedAuthor | null;
75
+ /** The author for an article's `created_by_email`, named after the email's local part, or `null` when it has none. */
76
+ export declare function emailAuthor(value: unknown): ProcessedAuthor | null;
@@ -0,0 +1,235 @@
1
+ import sanitizeHtml from 'sanitize-html';
2
+ import { RecordDataError } from '@tryghost/mg-context';
3
+ import { dateUtils, domUtils, urlUtils } from '@tryghost/mg-utils';
4
+ import { slugify } from '@tryghost/string';
5
+ import { jsonToHtml } from './json-to-html.js';
6
+ const FACEBOOK_SDK = '<div id="fb-root"></div><script async defer src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v3.2"></script>';
7
+ /** The author of posts with no author, created_by_email or single author in the authors file. */
8
+ export const DEFAULT_AUTHOR = { key: 'default', name: 'Author', slug: 'author', email: null };
9
+ /** The author of every newsletter. */
10
+ export const NEWSLETTER_AUTHOR = {
11
+ key: 'newsletter',
12
+ name: 'Newsletter',
13
+ slug: 'newsletter',
14
+ email: null
15
+ };
16
+ const TINYNEWS_TAG = { name: '#tinynews', slug: 'hash-tinynews' };
17
+ const NEWSLETTER_TAG = { name: '#newsletter', slug: 'hash-newsletter' };
18
+ /** A trimmed string, or `undefined` when the value is not a string or is blank. */
19
+ export function text(value) {
20
+ return (typeof value === 'string' && value.trim()) || undefined;
21
+ }
22
+ /** The text of an HTML string, trimmed. */
23
+ export function textOnly(html) {
24
+ return sanitizeHtml(html, { allowedTags: [], allowedAttributes: {} }).trim();
25
+ }
26
+ /** Public tags first, then internal (`#`) tags, keeping their order otherwise and the first tag for each slug. */
27
+ function sortTags(tags) {
28
+ const unique = tags.filter((tag, index) => tags.findIndex(other => other.slug === tag.slug) === index);
29
+ return unique.sort((a, b) => Number(a.name.startsWith('#')) - Number(b.name.startsWith('#')));
30
+ }
31
+ /** A category or tag, internal when it is unpublished in Tiny News, or `null` when it has neither slug nor name. */
32
+ function processTag(tag, title) {
33
+ const name = title ?? text(tag.slug);
34
+ const slug = slugify(text(tag.slug) ?? name ?? '');
35
+ if (!name || !slug) {
36
+ return null;
37
+ }
38
+ return tag.published === false ? { name: `#${name}`, slug: `hash-${slug}` } : { name, slug };
39
+ }
40
+ /** An article's category, then its tags, then `#tinynews`. */
41
+ export function articleTags(item) {
42
+ const tags = [];
43
+ if (item.category && typeof item.category === 'object') {
44
+ tags.push(processTag(item.category, text(item.category.title)));
45
+ }
46
+ for (const entry of item.tags ?? []) {
47
+ const tag = entry?.tag;
48
+ if (tag && typeof tag === 'object') {
49
+ tags.push(processTag(tag, text(tag.tag_translations?.[0]?.title)));
50
+ }
51
+ }
52
+ tags.push(TINYNEWS_TAG);
53
+ return sortTags(tags.filter((tag) => tag !== null));
54
+ }
55
+ /**
56
+ * An article or page from its first translation: its fields, URL, dates and tags. The feature image is the
57
+ * translation's main image or, for a page, the first `mainImage` block of its content. Content blocks that cannot be
58
+ * converted are left out and passed to `onUnhandled`. Throws `RecordDataError` when the item has no translation.
59
+ */
60
+ export function processArticle(item, type, options = {}) {
61
+ const translation = item.translations?.[0];
62
+ if (!translation || typeof translation !== 'object') {
63
+ throw new RecordDataError(`${type === 'page' ? 'Page' : 'Article'} has no translation`);
64
+ }
65
+ const title = text(translation.headline) ?? '(Untitled)';
66
+ const html = jsonToHtml(translation.content, options);
67
+ const fields = {
68
+ title,
69
+ slug: text(item.slug) ?? slugify(title),
70
+ type,
71
+ status: translation.published ? 'published' : 'draft',
72
+ visibility: 'public',
73
+ html,
74
+ custom_excerpt: text(translation.search_description) ?? null,
75
+ og_title: text(translation.facebook_title) ?? null,
76
+ og_description: text(translation.facebook_description) ?? null,
77
+ twitter_title: text(translation.twitter_title) ?? null,
78
+ twitter_description: text(translation.twitter_description) ?? null,
79
+ meta_title: text(translation.search_title) ?? null,
80
+ meta_description: text(translation.search_description) ?? null
81
+ };
82
+ if (html.includes('class="fb-post')) {
83
+ fields.codeinjection_head = FACEBOOK_SDK;
84
+ }
85
+ const mainImage = translation.main_image?.children?.[0];
86
+ const imageUrl = text(mainImage?.imageUrl);
87
+ if (imageUrl) {
88
+ fields.feature_image = imageUrl;
89
+ // Tiny News shows the alt text as the caption
90
+ fields.feature_image_alt = text(mainImage.imageAlt) ?? null;
91
+ fields.feature_image_caption = fields.feature_image_alt;
92
+ }
93
+ // A page's main image is a block of its content
94
+ if (type === 'page' && Array.isArray(translation.content)) {
95
+ const block = translation.content.find(contentBlock => contentBlock?.type === 'mainImage');
96
+ const pageImage = text(block?.children?.[0]?.imageUrl);
97
+ if (pageImage) {
98
+ fields.feature_image = pageImage;
99
+ }
100
+ }
101
+ const published = dateUtils.parseDate(translation.first_published_at) ??
102
+ dateUtils.parseDate(translation.last_published_at) ??
103
+ null;
104
+ return {
105
+ fields,
106
+ url: urlUtils.httpUrl(item.live_url)?.href ?? null,
107
+ published,
108
+ updated: dateUtils.parseDate(translation.last_published_at) ?? published,
109
+ created: published,
110
+ tags: articleTags(item)
111
+ };
112
+ }
113
+ /**
114
+ * Clean a newsletter edition's HTML: keep basic formatting, links and images, turn `<div>`s into paragraphs, and
115
+ * remove the "Made with Letterhead" link and empty paragraphs. The result is one HTML card.
116
+ */
117
+ export function processNewsletterContent(html) {
118
+ const cleanedContent = sanitizeHtml(html, {
119
+ allowedTags: [
120
+ 'b',
121
+ 'i',
122
+ 'em',
123
+ 'strong',
124
+ 'a',
125
+ 'p',
126
+ 'br',
127
+ 'ul',
128
+ 'ol',
129
+ 'li',
130
+ 'blockquote',
131
+ 'figure',
132
+ 'figcaption',
133
+ 'img',
134
+ 'h1',
135
+ 'h2',
136
+ 'h3',
137
+ 'h4',
138
+ 'h5',
139
+ 'h6',
140
+ 'div'
141
+ ],
142
+ allowedAttributes: {
143
+ a: ['href', 'title', 'rel', 'target'],
144
+ img: ['src', 'alt', 'title']
145
+ },
146
+ transformTags: {
147
+ div: 'p'
148
+ }
149
+ });
150
+ const cleanedHTML = domUtils.processFragment(cleanedContent, parsed => {
151
+ // :contains is a jQuery-specific selector, so filter manually
152
+ parsed.$('a').forEach(el => {
153
+ if ((el.textContent || '').includes('Made with Letterhead')) {
154
+ el.remove();
155
+ }
156
+ });
157
+ parsed.$('p').forEach(el => {
158
+ const innerHtml = domUtils.serializeChildren(el).trim();
159
+ if (!innerHtml.length || innerHtml === '<br>' || innerHtml === '<br/>') {
160
+ el.remove();
161
+ }
162
+ });
163
+ return parsed.html().trim();
164
+ });
165
+ return `<!--kg-card-begin: html-->${cleanedHTML}<!--kg-card-end: html-->`;
166
+ }
167
+ /** A newsletter edition's URL on the live site, `<site>/newsletters/<slug>`, or `null` when it has no slug. */
168
+ export function newsletterUrl(site, item) {
169
+ const slug = text(item.slug);
170
+ return slug ? `${urlUtils.trimTrailingSlashes(site)}/newsletters/${slug}` : null;
171
+ }
172
+ /** A newsletter edition as a published post tagged `#newsletter` and `#tinynews`. */
173
+ export function processNewsletter(item, site) {
174
+ const title = text(item.headline) ?? '(Untitled)';
175
+ const content = text(item.content);
176
+ const published = dateUtils.parseDate(item.newsletter_published_at) ?? dateUtils.parseDate(item.newsletter_created_at) ?? null;
177
+ return {
178
+ fields: {
179
+ title,
180
+ slug: text(item.slug) ?? slugify(title),
181
+ type: 'post',
182
+ status: 'published',
183
+ visibility: 'public',
184
+ html: content ? processNewsletterContent(content) : '',
185
+ custom_excerpt: text(item.subheadline) ?? null
186
+ },
187
+ url: newsletterUrl(site, item),
188
+ published,
189
+ updated: published,
190
+ created: dateUtils.parseDate(item.newsletter_created_at) ?? published,
191
+ tags: [NEWSLETTER_TAG, TINYNEWS_TAG]
192
+ };
193
+ }
194
+ /** A bio's text, or `undefined` when it has none. */
195
+ const cleanBio = (value) => text(textOnly(text(value) ?? ''));
196
+ /** An author's first names and last name. */
197
+ export function authorName(author) {
198
+ return text(`${text(author.first_names) ?? ''} ${text(author.last_name) ?? ''}`);
199
+ }
200
+ /**
201
+ * An author nested in an article or listed in the authors file, or `null` when it has no name. The email, photo and
202
+ * bio of `profile`, the matching author in the authors file, are preferred to the article's own.
203
+ */
204
+ export function personAuthor(author, profile) {
205
+ const name = authorName(author);
206
+ if (!name) {
207
+ return null;
208
+ }
209
+ const email = text(profile?.email) ?? text(author.email) ?? null;
210
+ const result = {
211
+ key: email ? `email:${email.toLowerCase()}` : `name:${name}`,
212
+ name,
213
+ slug: slugify(name),
214
+ email
215
+ };
216
+ const image = text(profile?.photoUrl) ?? text(author.photoUrl);
217
+ if (image) {
218
+ result.profile_image = image;
219
+ }
220
+ const bio = cleanBio(profile?.translations?.[0]?.bio) ?? cleanBio(author.translations?.[0]?.bio);
221
+ if (bio) {
222
+ result.bio = bio;
223
+ }
224
+ return result;
225
+ }
226
+ /** The author for an article's `created_by_email`, named after the email's local part, or `null` when it has none. */
227
+ export function emailAuthor(value) {
228
+ const email = text(value) ?? '';
229
+ const name = text(email.split('@')[0]);
230
+ if (!name) {
231
+ return null;
232
+ }
233
+ return { key: `email:${email.toLowerCase()}`, name, slug: slugify(name), email };
234
+ }
235
+ //# sourceMappingURL=process.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process.js","sourceRoot":"","sources":["../../src/lib/process.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,EAAC,eAAe,EAAC,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAC,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAC,MAAM,oBAAoB,CAAC;AACjE,OAAO,EAAC,OAAO,EAAC,MAAM,kBAAkB,CAAC;AACzC,OAAO,EAAC,UAAU,EAAyB,MAAM,mBAAmB,CAAC;AAGrE,MAAM,YA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,OAAO,CAAC,IAAI,CAAC,EAAE,KAAK,EAAC,CAAC;AACnF,CAAC"}
@@ -0,0 +1,6 @@
1
+ import type { TinyNewsBlock } from './types.js';
2
+ /** A text block as a heading, paragraph or preformatted block, or `null` when it has no text. */
3
+ declare const TextNode: ({ node }: {
4
+ node: TinyNewsBlock;
5
+ }) => string | null;
6
+ export { TextNode };
@@ -0,0 +1,60 @@
1
+ // No space is added before a child that starts with one of these
2
+ const supportedPunctuation = [',', '.', '?', '!', ';', ':', '"', '“', '”', ')'];
3
+ // or after a child that ends with one of these
4
+ const supportedTrailingPunctuation = ['?', '!', ';', '"', '“', '”', '('];
5
+ const WRAPPERS = {
6
+ TITLE: 'h1',
7
+ SUBTITLE: 'h2',
8
+ HEADING_1: 'h1',
9
+ HEADING_2: 'h2',
10
+ HEADING_3: 'h3',
11
+ HEADING_4: 'h4',
12
+ NORMAL_TEXT: 'p',
13
+ FORMATTED_TEXT: 'pre'
14
+ };
15
+ /** One child of a text block, which has nonempty `content`. */
16
+ const processChild = (child, nextChild) => {
17
+ const nextContent = nextChild?.content;
18
+ let delimiterSpaceChar = ' ';
19
+ if ((nextContent && supportedPunctuation.includes(nextContent[0])) ||
20
+ supportedTrailingPunctuation.includes(child.content.slice(-1))) {
21
+ delimiterSpaceChar = '';
22
+ }
23
+ let text = `${child.content}${child.link ? '' : delimiterSpaceChar}`;
24
+ if (child.content.trim().length === 0 && nextContent && nextContent.trim().length !== 0) {
25
+ text = '<br />';
26
+ }
27
+ if (child.style) {
28
+ if (child.style.underline && !child.link) {
29
+ text = `${delimiterSpaceChar}<u>${text}</u>${delimiterSpaceChar}`;
30
+ }
31
+ if (child.style.italic) {
32
+ text = `<em>${text}</em>${delimiterSpaceChar}`;
33
+ }
34
+ if (child.style.bold) {
35
+ text = `<strong>${text}</strong>${delimiterSpaceChar}`;
36
+ }
37
+ }
38
+ else {
39
+ text = `${text}${child.link ? '' : delimiterSpaceChar}`;
40
+ }
41
+ if (child.link) {
42
+ text = `${delimiterSpaceChar}<a href="${child.link}">${text}</a>${delimiterSpaceChar}`;
43
+ }
44
+ return text;
45
+ };
46
+ /** A text block as a heading, paragraph or preformatted block, or `null` when it has no text. */
47
+ const TextNode = ({ node }) => {
48
+ const nodeChildren = node.children ?? [];
49
+ const children = nodeChildren
50
+ .filter((child) => Boolean(child.content) && child.content !== 'FORMAT START' && child.content !== 'FORMAT END')
51
+ // The next child is looked up among all children, including those left out.
52
+ .map((child, i) => processChild(child, nodeChildren[i + 1]));
53
+ if (children.length === 0) {
54
+ return null;
55
+ }
56
+ const tag = WRAPPERS[node.style ?? ''];
57
+ return tag ? `<${tag}>${children.join('')}</${tag}>` : children.join('');
58
+ };
59
+ export { TextNode };
60
+ //# sourceMappingURL=text.js.map