cook-ssg 2.9.0 → 2.11.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 +7 -5
- package/package.json +3 -2
- package/scripts/build.js +15 -6
- package/scripts/dev.js +4 -0
- package/scripts/plugins/headers.js +30 -0
- package/scripts/plugins/social-links.js +58 -0
- package/scripts/plugins/socialspec-files.js +118 -0
- package/scripts/social/accounts.js +160 -0
- package/scripts/social/catalog.js +19 -0
- package/scripts/social/index.js +10 -0
- package/scripts/social/render.js +28 -0
- package/scripts/social/socialspec.js +130 -0
- package/scripts/utils/config/config.js +16 -1
- package/scripts/utils/layouts/serialize.js +4 -1
package/README.md
CHANGED
|
@@ -147,6 +147,7 @@ The build process performs the following steps, in this order:
|
|
|
147
147
|
* Repeats elements for each item in collections (`[data-repeat]`, nesting supported)
|
|
148
148
|
* Replaces custom elements and `[data-component]` elements with templates (nesting supported; flat or Declarative Shadow DOM)
|
|
149
149
|
* Replaces ES6 template strings (`${}`) with front matter + global data
|
|
150
|
+
* Fills empty `<social-links>` elements with profile links from `config/social.json`
|
|
150
151
|
* Rewrites `<img>` to responsive `<picture>` elements
|
|
151
152
|
* Detects custom elements and manages component JS loading (`autoComponents` config)
|
|
152
153
|
* Pre-renders Declarative Shadow DOM from a manifest (`dsd` config)
|
|
@@ -157,11 +158,12 @@ The build process performs the following steps, in this order:
|
|
|
157
158
|
* Minifies HTML, CSS, and JS source (production only)
|
|
158
159
|
8. **Generates fragments** - A sibling `_fragment.html` per page for SPA-style navigation (`fragments` config)
|
|
159
160
|
9. **Generates formats** - Markdown copies under `/md/`, JSON under `/api/`, Atom feed, and `llms.txt` (`formats` config)
|
|
160
|
-
10. **
|
|
161
|
-
11. **Creates
|
|
162
|
-
12. **
|
|
163
|
-
13. **
|
|
164
|
-
14. **
|
|
161
|
+
10. **Writes SocialSpec files** - With `about`, `contact` or `following` in `config/social.json`, writes `following.opml`, `about.md` and `contact.vcf` under `/.well-known/` and adds their `_headers` blocks
|
|
162
|
+
11. **Creates `sitemap.xml`** - When `sitemap.url` is set, written to the site root (`/dist`, or `/dist/<siteRoot>`); fragments excluded
|
|
163
|
+
12. **Creates bundled files** - `.css` and `.js` bundles are written
|
|
164
|
+
13. **Fingerprints assets** - Opt-in content-hash filenames with HTML and JS-import rewriting (`fingerprint` config)
|
|
165
|
+
14. **Applies `basePath`** - When set, prefixes root-relative URLs in built HTML for sub-path hosting (production only)
|
|
166
|
+
15. **Runs custom-user `after` plugins** - Runs once after file processing
|
|
165
167
|
|
|
166
168
|
A page that fails during the loop is reported (with its path) and skipped; the rest of the site still builds, a failure summary prints at the end, and the process exits non-zero so CI catches it.
|
|
167
169
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cook-ssg",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.11.0",
|
|
4
4
|
"description": "Cook your static pages into a beautifully performing site. Static site generation the web platform way.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
".": "./scripts/build.js",
|
|
12
12
|
"./build": "./scripts/build.js",
|
|
13
13
|
"./dev": "./scripts/dev.js",
|
|
14
|
-
"./layouts": "./scripts/layouts.js"
|
|
14
|
+
"./layouts": "./scripts/layouts.js",
|
|
15
|
+
"./social": "./scripts/social/index.js"
|
|
15
16
|
},
|
|
16
17
|
"files": [
|
|
17
18
|
"bin/",
|
package/scripts/build.js
CHANGED
|
@@ -38,6 +38,9 @@ import processHtmlFrontmatter from './plugins/process-html-frontmatter.js';
|
|
|
38
38
|
import replaceInclude from './plugins/replace-include.js';
|
|
39
39
|
import replaceInline from './plugins/replace-inline.js';
|
|
40
40
|
import replaceMissingExternalLinkProtocol from './plugins/replace-external-link-protocol.js';
|
|
41
|
+
import { socialData, fillSocialLinks } from './plugins/social-links.js';
|
|
42
|
+
import { writeSocialspecFiles } from './plugins/socialspec-files.js';
|
|
43
|
+
import { writeHeaderBlocks } from './plugins/headers.js';
|
|
41
44
|
import replaceTemplateStrings from './plugins/replace-template-strings.js';
|
|
42
45
|
import conditionalSections from './plugins/conditional-sections.js';
|
|
43
46
|
import setActiveLinks from './plugins/set-active-links.js';
|
|
@@ -107,6 +110,9 @@ class Build {
|
|
|
107
110
|
// PLUGIN: Programs: `programs` / `programAreas` data from config/programs.json
|
|
108
111
|
await programsData({data});
|
|
109
112
|
|
|
113
|
+
// PLUGIN: Social: `social` data from config/social.json (or main.js `social`)
|
|
114
|
+
await socialData({data});
|
|
115
|
+
|
|
110
116
|
// PLUGIN: Generate responsive image derivatives (AVIF/WebP at multiple widths)
|
|
111
117
|
await optimizeImagesGenerate({store});
|
|
112
118
|
|
|
@@ -191,6 +197,9 @@ class Build {
|
|
|
191
197
|
const templateData = file.frontMatter ? { ...data, ...file.frontMatter } : data;
|
|
192
198
|
replaceTemplateStrings({file, data: templateData, allowType: ['.html', '.json', '.webmanifest']});
|
|
193
199
|
|
|
200
|
+
// PLUGIN: Fill empty <social-links> elements with the site's profile links
|
|
201
|
+
fillSocialLinks({file, data, allowType: ['.html']});
|
|
202
|
+
|
|
194
203
|
// PLUGIN: Rewrite <img> to <picture> with responsive srcset
|
|
195
204
|
await optimizeImagesRewrite({file, store, allowType: ['.html']});
|
|
196
205
|
|
|
@@ -261,13 +270,13 @@ class Build {
|
|
|
261
270
|
// built-in post-loop plugin so they all work with plain root paths.
|
|
262
271
|
await applyBasePath();
|
|
263
272
|
|
|
264
|
-
// Sandboxed programs: `_headers` rules (Cloudflare Pages,
|
|
265
|
-
// to the site's own `_headers`, which copySrc already placed
|
|
273
|
+
// Sandboxed programs and SocialSpec files: `_headers` rules (Cloudflare Pages,
|
|
274
|
+
// Netlify) appended to the site's own `_headers`, which copySrc already placed
|
|
275
|
+
// in dist. One read-modify-write for both sources.
|
|
266
276
|
if (!Util.validatePageChange()) {
|
|
267
|
-
const
|
|
268
|
-
const
|
|
269
|
-
|
|
270
|
-
if (headers !== null) fs.writeFileSync(headersFile, headers);
|
|
277
|
+
const rootDir = siteRootDir(distPath, siteRoot);
|
|
278
|
+
const socialBlocks = writeSocialspecFiles({ data, rootDir });
|
|
279
|
+
writeHeaderBlocks(rootDir, [programHeaders(allPrograms(), null), socialBlocks]);
|
|
271
280
|
}
|
|
272
281
|
|
|
273
282
|
// CUSTOM PLUGINS: Run custom user plugins after file loop
|
package/scripts/dev.js
CHANGED
|
@@ -173,3 +173,7 @@ browserSync.watch(themeJson).on('change', file => { rebuild(file); }).on('add',
|
|
|
173
173
|
// config/programs.json (Vanilla Press) feeds the programs data: rebuild on change.
|
|
174
174
|
const programsJson = `${process.cwd()}/config/programs.json`;
|
|
175
175
|
browserSync.watch(programsJson).on('change', file => { rebuild(file); }).on('add', file => { rebuild(file); });
|
|
176
|
+
|
|
177
|
+
// config/social.json (Vanilla Press) feeds <social-links>: rebuild on change.
|
|
178
|
+
const socialJson = `${process.cwd()}/config/social.json`;
|
|
179
|
+
browserSync.watch(socialJson).on('change', file => { rebuild(file); }).on('add', file => { rebuild(file); });
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file headers.js
|
|
3
|
+
* @description One read-modify-write of the site's `_headers` (Cloudflare Pages,
|
|
4
|
+
* Netlify), shared by sandboxed programs and SocialSpec files. The site's own
|
|
5
|
+
* lines stay first and untouched; generated blocks follow in the order given.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import fs from 'fs-extra';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Append generated header blocks to the existing `_headers` text.
|
|
13
|
+
* @param {string|null} existing
|
|
14
|
+
* @param {Array<string|null>} blocks - block texts; null/empty are skipped
|
|
15
|
+
* @returns {string|null} null when there is nothing to add
|
|
16
|
+
*/
|
|
17
|
+
export function appendHeaderBlocks(existing, blocks) {
|
|
18
|
+
const add = blocks.filter(Boolean);
|
|
19
|
+
if (!add.length) return null;
|
|
20
|
+
const text = add.join('\n');
|
|
21
|
+
return existing ? `${existing}\n${text}` : text;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Read `<rootDir>/_headers`, append the blocks, write once. No-op when none. */
|
|
25
|
+
export function writeHeaderBlocks(rootDir, blocks) {
|
|
26
|
+
const headersFile = path.join(rootDir, '_headers');
|
|
27
|
+
const existing = fs.existsSync(headersFile) ? fs.readFileSync(headersFile, 'utf-8') : null;
|
|
28
|
+
const out = appendHeaderBlocks(existing, blocks);
|
|
29
|
+
if (out !== null) fs.writeFileSync(headersFile, out);
|
|
30
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file social-links.js
|
|
3
|
+
* @description Social accounts: reads config/social.json (or main.js `social`),
|
|
4
|
+
* exposes `social.accounts` / `social.allAccounts` data, and fills each empty
|
|
5
|
+
* `<social-links>` element with a `<ul>` of profile links at build time.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import chalk from 'chalk';
|
|
9
|
+
import { marked } from 'marked';
|
|
10
|
+
import Util from '../utils/util/util.js';
|
|
11
|
+
import { getSocial } from '../utils/config/config.js';
|
|
12
|
+
import { resolveAboutBody } from './socialspec-files.js';
|
|
13
|
+
import { normalizeAccounts, renderSocialLinks } from '../social/index.js';
|
|
14
|
+
|
|
15
|
+
const TAG = '[social] ';
|
|
16
|
+
const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
17
|
+
const SKIP_INSIDE = 'pre, code, template, textarea';
|
|
18
|
+
|
|
19
|
+
let visibleAccounts = [];
|
|
20
|
+
|
|
21
|
+
/** The about body (or the contents of `about.file`) as HTML; undefined when there is none. */
|
|
22
|
+
function aboutHtml(about) {
|
|
23
|
+
const md = resolveAboutBody(about, process.cwd());
|
|
24
|
+
return md.trim() ? marked.parse(md) : undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Set `social` on the data store when a social config exists. */
|
|
28
|
+
export async function socialData({ data }) {
|
|
29
|
+
visibleAccounts = [];
|
|
30
|
+
const raw = getSocial();
|
|
31
|
+
if (raw === undefined) return;
|
|
32
|
+
const { all, visible, warnings } = normalizeAccounts(raw);
|
|
33
|
+
for (const w of warnings) console.log(chalk.yellow(`${TAG}${w}`));
|
|
34
|
+
visibleAccounts = visible;
|
|
35
|
+
data.social = { ...(isObj(raw) ? raw : {}), accounts: visible, allAccounts: all };
|
|
36
|
+
const html = aboutHtml(isObj(raw) ? raw.about : undefined);
|
|
37
|
+
if (html !== undefined) data.social.aboutHtml = html;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Fill each `<social-links>` that has no element child. Leaves the page's bytes
|
|
42
|
+
* alone when it has no live `<social-links>`.
|
|
43
|
+
*/
|
|
44
|
+
export function fillSocialLinks({ file, allowType }) {
|
|
45
|
+
if (!Util.isAllowedType({ file, allowType })) return;
|
|
46
|
+
if (typeof file.src !== 'string' || !file.src.includes('<social-links')) return;
|
|
47
|
+
const dom = Util.fileDom(file);
|
|
48
|
+
const live = [...dom.window.document.querySelectorAll('social-links')]
|
|
49
|
+
.filter((el) => !el.closest(SKIP_INSIDE) && el.children.length === 0);
|
|
50
|
+
let changed = false;
|
|
51
|
+
for (const el of live) {
|
|
52
|
+
const html = renderSocialLinks(visibleAccounts, { services: el.getAttribute('services') ?? undefined });
|
|
53
|
+
if (!html) continue;
|
|
54
|
+
el.innerHTML = html;
|
|
55
|
+
changed = true;
|
|
56
|
+
}
|
|
57
|
+
Util.commitDom(file, dom, changed);
|
|
58
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The about text as raw Markdown: `body` when it has text, else the contents of
|
|
3
|
+
* `about.file` (a path from `cwd`); '' when there is neither or the file is unreadable.
|
|
4
|
+
* Used by both the `social.aboutHtml` data and the about.md writer.
|
|
5
|
+
* @param {object} about
|
|
6
|
+
* @param {string} [cwd]
|
|
7
|
+
* @returns {string}
|
|
8
|
+
*/
|
|
9
|
+
export function resolveAboutBody(about, cwd = process.cwd()) {
|
|
10
|
+
if (!isObj(about)) return '';
|
|
11
|
+
if (nonEmpty(about.body)) return about.body;
|
|
12
|
+
if (nonEmpty(about.file)) {
|
|
13
|
+
try { return fs.readFileSync(path.resolve(cwd, about.file), 'utf-8'); } catch { return ''; }
|
|
14
|
+
}
|
|
15
|
+
return '';
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @file socialspec-files.js
|
|
20
|
+
* @description Writes the SocialSpec profile files under `<siteRoot>/.well-known/`
|
|
21
|
+
* (following.opml, about.md, contact.vcf) from the `social` config, and returns
|
|
22
|
+
* their `_headers` blocks. Each key is optional; a site with none writes nothing.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import chalk from 'chalk';
|
|
26
|
+
import fs from 'fs-extra';
|
|
27
|
+
import path from 'node:path';
|
|
28
|
+
import { getSocial, formats as formatsConfig } from '../utils/config/config.js';
|
|
29
|
+
import { renderOpml, renderAbout, renderVcard } from '../social/index.js';
|
|
30
|
+
|
|
31
|
+
const TAG = '[social] ';
|
|
32
|
+
const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
33
|
+
const nonEmpty = (v) => typeof v === 'string' && v.trim() !== '';
|
|
34
|
+
const warn = (msg) => console.log(chalk.yellow(`${TAG}${msg}`));
|
|
35
|
+
/** 'https', 'http' or null (not an absolute http(s) URL). */
|
|
36
|
+
const scheme = (u) => {
|
|
37
|
+
try {
|
|
38
|
+
const p = new URL(u).protocol;
|
|
39
|
+
return p === 'https:' ? 'https' : p === 'http:' ? 'http' : null;
|
|
40
|
+
} catch { return null; }
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const TYPES = {
|
|
44
|
+
'following.opml': 'text/x-opml; charset=utf-8',
|
|
45
|
+
'about.md': 'text/markdown; charset=utf-8',
|
|
46
|
+
'contact.vcf': 'text/vcard; charset=utf-8',
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/** `_headers` block for one written file. */
|
|
50
|
+
export function socialHeaderBlock(name) {
|
|
51
|
+
return `/.well-known/${name}\n Content-Type: ${TYPES[name]}\n Access-Control-Allow-Origin: *\n`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* @param {object} opts
|
|
56
|
+
* @param {object} opts.data - build data (`siteUrl`, `siteTitle`)
|
|
57
|
+
* @param {string} opts.rootDir - the site root directory inside dist
|
|
58
|
+
* @param {string} [opts.cwd] - base for `about.file`
|
|
59
|
+
* @returns {string|null} `_headers` blocks for the files written, or null
|
|
60
|
+
*/
|
|
61
|
+
export function writeSocialspecFiles({ data, rootDir, cwd = process.cwd() }) {
|
|
62
|
+
const raw = getSocial();
|
|
63
|
+
if (!isObj(raw)) return null;
|
|
64
|
+
const hasFollowing = Array.isArray(raw.following) && raw.following.some((e) => e && e.public !== false);
|
|
65
|
+
const hasAbout = isObj(raw.about);
|
|
66
|
+
const hasContact = isObj(raw.contact);
|
|
67
|
+
if (!hasFollowing && !hasAbout && !hasContact) return null;
|
|
68
|
+
|
|
69
|
+
const siteUrl = nonEmpty(data?.siteUrl) ? data.siteUrl.replace(/\/+$/, '') : '';
|
|
70
|
+
if (!siteUrl) warn('no siteUrl in the site data; SocialSpec URLs cannot be made absolute');
|
|
71
|
+
if (!formatsConfig?.feed) warn('formats.feed is not set. SocialSpec profiles start from the site feed');
|
|
72
|
+
|
|
73
|
+
const out = {};
|
|
74
|
+
|
|
75
|
+
if (hasFollowing) {
|
|
76
|
+
const kept = [];
|
|
77
|
+
for (const e of raw.following) {
|
|
78
|
+
if (!e || e.public === false) continue;
|
|
79
|
+
if (!nonEmpty(e.feedUrl)) { warn(`following "${e.title || '(untitled)'}": no feedUrl, entry skipped`); continue; }
|
|
80
|
+
const label = e.title || e.feedUrl;
|
|
81
|
+
const feed = scheme(e.feedUrl);
|
|
82
|
+
if (!feed) { warn(`following "${label}": feedUrl must be an absolute URL, entry skipped`); continue; }
|
|
83
|
+
if (feed === 'http') warn(`following "${label}": feedUrl is http, not https`);
|
|
84
|
+
let entry = e;
|
|
85
|
+
if (nonEmpty(e.siteUrl)) {
|
|
86
|
+
const site = scheme(e.siteUrl);
|
|
87
|
+
if (!site) { warn(`following "${label}": siteUrl must be an absolute URL, htmlUrl omitted`); entry = { ...e, siteUrl: undefined }; }
|
|
88
|
+
else if (site === 'http') warn(`following "${label}": siteUrl is http, not https`);
|
|
89
|
+
}
|
|
90
|
+
kept.push(entry);
|
|
91
|
+
}
|
|
92
|
+
const title = `${nonEmpty(data?.siteTitle) ? data.siteTitle : 'Site'} follows`;
|
|
93
|
+
const text = renderOpml(kept, { title });
|
|
94
|
+
if (text) out['following.opml'] = text;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (hasAbout) {
|
|
98
|
+
const about = raw.about;
|
|
99
|
+
if (!nonEmpty(about.body) && nonEmpty(about.file) && !fs.existsSync(path.resolve(cwd, about.file))) {
|
|
100
|
+
warn(`about.file "${about.file}" not found`);
|
|
101
|
+
}
|
|
102
|
+
const text = renderAbout({ ...about, body: resolveAboutBody(about, cwd) }, { siteUrl });
|
|
103
|
+
if (text) out['about.md'] = text;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (hasContact) {
|
|
107
|
+
const { text, warning } = renderVcard(raw.contact, { siteUrl });
|
|
108
|
+
if (warning) warn(warning.replace(/^social: /, ''));
|
|
109
|
+
if (text) out['contact.vcf'] = text;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const names = Object.keys(out);
|
|
113
|
+
if (!names.length) return null;
|
|
114
|
+
const dir = path.join(rootDir, '.well-known');
|
|
115
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
116
|
+
for (const n of names) fs.writeFileSync(path.join(dir, n), out[n]);
|
|
117
|
+
return names.map(socialHeaderBlock).join('\n');
|
|
118
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file accounts.js
|
|
3
|
+
* @description Parse and validate social account handles, build profile URLs and
|
|
4
|
+
* normalize the `accounts` list from config/social.json. Pure: no fs, no config.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { serviceById } from './catalog.js';
|
|
8
|
+
|
|
9
|
+
const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
10
|
+
|
|
11
|
+
const DOMAIN = /^(?=.{3,253}$)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
|
|
12
|
+
const GITHUB = /^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$/;
|
|
13
|
+
const MASTODON_USER = /^[A-Za-z0-9_](?:[A-Za-z0-9_.-]*[A-Za-z0-9_])?$/;
|
|
14
|
+
const LINKEDIN_SLUG = /^[A-Za-z0-9_%-]+$/;
|
|
15
|
+
const YOUTUBE = /^@[A-Za-z0-9._-]+$/;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* If `s` is a pasted URL on `host` (optional `https?://` and `www.`, optional trailing
|
|
19
|
+
* slash), return the path after the host; otherwise null. Bare handles never match.
|
|
20
|
+
*/
|
|
21
|
+
const urlPath = (s, host) => {
|
|
22
|
+
const m = s.match(new RegExp(`^(?:https?://)?(?:www\\.)?${host.replace(/\./g, '\\.')}/(.+?)/*$`, 'i'));
|
|
23
|
+
return m ? m[1] : null;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const fail = (error) => ({ error });
|
|
27
|
+
|
|
28
|
+
/** @param {string} v */
|
|
29
|
+
function isHttpsUrl(v) {
|
|
30
|
+
if (!/^https:\/\//i.test(v)) return false;
|
|
31
|
+
try {
|
|
32
|
+
return new URL(v).protocol === 'https:';
|
|
33
|
+
} catch {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Turn what a person typed (or pasted) into the stored handle.
|
|
40
|
+
* @param {string} service
|
|
41
|
+
* @param {string} input
|
|
42
|
+
* @returns {{ handle: string } | { error: string }}
|
|
43
|
+
*/
|
|
44
|
+
export function parseHandle(service, input) {
|
|
45
|
+
if (typeof input !== 'string') return fail('Enter a handle');
|
|
46
|
+
const raw = input.trim();
|
|
47
|
+
if (!raw) return fail('Enter a handle');
|
|
48
|
+
|
|
49
|
+
switch (service) {
|
|
50
|
+
case 'bluesky': {
|
|
51
|
+
const m = (urlPath(raw, 'bsky.app') || '').match(/^profile\/([^/]+)$/i);
|
|
52
|
+
const handle = (m ? m[1] : raw).replace(/^@/, '').toLowerCase();
|
|
53
|
+
return DOMAIN.test(handle) ? { handle } : fail('Bluesky handles look like name.bsky.social');
|
|
54
|
+
}
|
|
55
|
+
case 'mastodon': {
|
|
56
|
+
const s = raw;
|
|
57
|
+
const m = s.match(/^(?:https?:\/\/)?([^/@\s]+)\/@([^/@]+)\/*$/i);
|
|
58
|
+
let user;
|
|
59
|
+
let instance;
|
|
60
|
+
if (m) {
|
|
61
|
+
[, instance, user] = m;
|
|
62
|
+
} else {
|
|
63
|
+
const parts = s.replace(/^@/, '').split('@');
|
|
64
|
+
if (parts.length !== 2) return fail('Mastodon handles look like @user@instance');
|
|
65
|
+
[user, instance] = parts;
|
|
66
|
+
}
|
|
67
|
+
instance = instance.toLowerCase();
|
|
68
|
+
if (!MASTODON_USER.test(user) || !DOMAIN.test(instance)) return fail('Mastodon handles look like @user@instance');
|
|
69
|
+
return { handle: `@${user}@${instance}` };
|
|
70
|
+
}
|
|
71
|
+
case 'github': {
|
|
72
|
+
const p = urlPath(raw, 'github.com');
|
|
73
|
+
const handle = (p && !p.includes('/') ? p : raw).replace(/^@/, '');
|
|
74
|
+
return GITHUB.test(handle) ? { handle } : fail('GitHub usernames are 1 to 39 letters, digits or single hyphens');
|
|
75
|
+
}
|
|
76
|
+
case 'linkedin': {
|
|
77
|
+
const m = (urlPath(raw, 'linkedin.com') || '').match(/^in\/([^/]+)$/i) || raw.match(/^in\/([^/]+?)\/*$/i);
|
|
78
|
+
const slug = m ? m[1] : raw;
|
|
79
|
+
return LINKEDIN_SLUG.test(slug) ? { handle: slug } : fail('Use the part after linkedin.com/in/');
|
|
80
|
+
}
|
|
81
|
+
case 'youtube': {
|
|
82
|
+
const p = urlPath(raw, 'youtube.com');
|
|
83
|
+
const handle = p && !p.includes('/') ? p : raw;
|
|
84
|
+
return YOUTUBE.test(handle) ? { handle } : fail('YouTube handles look like @name');
|
|
85
|
+
}
|
|
86
|
+
case 'link':
|
|
87
|
+
return isHttpsUrl(raw) ? { handle: raw } : fail('Links must start with https://');
|
|
88
|
+
default:
|
|
89
|
+
return fail(`Unknown service "${service}"`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The public profile URL for an account, or null when it can't be built.
|
|
95
|
+
* @param {{ service?: string, handle?: string, url?: string } | null | undefined} account
|
|
96
|
+
* @returns {string | null}
|
|
97
|
+
*/
|
|
98
|
+
export function profileUrl(account) {
|
|
99
|
+
if (!isObj(account)) return null;
|
|
100
|
+
const { service, handle, url } = account;
|
|
101
|
+
if (service === 'link') return typeof url === 'string' && isHttpsUrl(url) ? url : null;
|
|
102
|
+
if (typeof handle !== 'string' || !handle) return null;
|
|
103
|
+
switch (service) {
|
|
104
|
+
case 'bluesky': return `https://bsky.app/profile/${handle}`;
|
|
105
|
+
case 'mastodon': {
|
|
106
|
+
const m = handle.match(/^@([^@]+)@([^@]+)$/);
|
|
107
|
+
return m ? `https://${m[2]}/@${m[1]}` : null;
|
|
108
|
+
}
|
|
109
|
+
case 'github': return `https://github.com/${handle}`;
|
|
110
|
+
case 'linkedin': return `https://www.linkedin.com/in/${handle}`;
|
|
111
|
+
case 'youtube': return `https://www.youtube.com/${handle}`;
|
|
112
|
+
default: return null;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Validate the raw contents of config/social.json. A bad entry is skipped with a
|
|
118
|
+
* warning; the rest still build.
|
|
119
|
+
* @param {unknown} raw
|
|
120
|
+
* @returns {{ all: object[], visible: object[], warnings: string[] }}
|
|
121
|
+
*/
|
|
122
|
+
export function normalizeAccounts(raw) {
|
|
123
|
+
const warnings = [];
|
|
124
|
+
const all = [];
|
|
125
|
+
const list = isObj(raw) ? raw.accounts : undefined;
|
|
126
|
+
if (list !== undefined && !Array.isArray(list)) warnings.push('accounts must be an array; ignoring it');
|
|
127
|
+
|
|
128
|
+
(Array.isArray(list) ? list : []).forEach((entry, i) => {
|
|
129
|
+
const at = `accounts[${i}]`;
|
|
130
|
+
if (!isObj(entry)) return void warnings.push(`${at}: not an object; skipped`);
|
|
131
|
+
const svc = typeof entry.service === 'string' ? serviceById(entry.service) : undefined;
|
|
132
|
+
if (!svc) return void warnings.push(`${at}: unknown service ${JSON.stringify(entry.service)}; skipped`);
|
|
133
|
+
|
|
134
|
+
const hidden = entry.hidden === true;
|
|
135
|
+
if (svc.id === 'link') {
|
|
136
|
+
const label = typeof entry.label === 'string' ? entry.label.trim() : '';
|
|
137
|
+
const url = typeof entry.url === 'string' ? entry.url.trim() : '';
|
|
138
|
+
if (!label) return void warnings.push(`${at}: link needs a label; skipped`);
|
|
139
|
+
if (!isHttpsUrl(url)) return void warnings.push(`${at}: link url must be https:; skipped`);
|
|
140
|
+
all.push({ service: 'link', handle: '', url, name: label, icon: 'link', hidden });
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const parsed = parseHandle(svc.id, entry.handle);
|
|
145
|
+
if ('error' in parsed) return void warnings.push(`${at}: ${svc.id} handle ${JSON.stringify(entry.handle)}: ${parsed.error}; skipped`);
|
|
146
|
+
const account = {
|
|
147
|
+
service: svc.id,
|
|
148
|
+
handle: parsed.handle,
|
|
149
|
+
url: profileUrl({ service: svc.id, handle: parsed.handle }),
|
|
150
|
+
name: svc.name,
|
|
151
|
+
icon: svc.id,
|
|
152
|
+
hidden,
|
|
153
|
+
};
|
|
154
|
+
if (svc.id === 'bluesky' && typeof entry.did === 'string' && entry.did.startsWith('did:')) account.did = entry.did;
|
|
155
|
+
all.push(account);
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
return { all, visible: all.filter((a) => !a.hidden), warnings };
|
|
159
|
+
}
|
|
160
|
+
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file catalog.js
|
|
3
|
+
* @description The services Cook knows how to link to: ids, display names and
|
|
4
|
+
* whether Vanilla Press can check a handle against the service. Pure data, no
|
|
5
|
+
* dependencies.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** @type {Array<{ id: string, name: string, checkable: boolean }>} */
|
|
9
|
+
export const SERVICES = [
|
|
10
|
+
{ id: 'bluesky', name: 'Bluesky', checkable: true },
|
|
11
|
+
{ id: 'mastodon', name: 'Mastodon', checkable: true },
|
|
12
|
+
{ id: 'github', name: 'GitHub', checkable: true },
|
|
13
|
+
{ id: 'linkedin', name: 'LinkedIn', checkable: false },
|
|
14
|
+
{ id: 'youtube', name: 'YouTube', checkable: false },
|
|
15
|
+
{ id: 'link', name: 'Link', checkable: false },
|
|
16
|
+
];
|
|
17
|
+
|
|
18
|
+
/** @param {string} id */
|
|
19
|
+
export const serviceById = (id) => SERVICES.find((s) => s.id === id);
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file index.js
|
|
3
|
+
* @description Public entry for `cook-ssg/social`: the service catalog, account
|
|
4
|
+
* parsing and the profile-links renderer. Pure and dependency-free.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export { SERVICES } from './catalog.js';
|
|
8
|
+
export { parseHandle, profileUrl, normalizeAccounts } from './accounts.js';
|
|
9
|
+
export { renderSocialLinks } from './render.js';
|
|
10
|
+
export { renderOpml, renderAbout, renderVcard } from './socialspec.js';
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file render.js
|
|
3
|
+
* @description Render normalized accounts as the `<ul>` of profile links that
|
|
4
|
+
* goes inside `<social-links>`. Pure: no fs, no config.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const escapeHtml = (s) =>
|
|
8
|
+
String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @param {Array<{ service: string, url: string, name: string, icon?: string }>} accounts
|
|
12
|
+
* @param {{ services?: string, variant?: string }} [options] `variant` is for CSS and
|
|
13
|
+
* is copied onto the element by the fill step; it does not change the list.
|
|
14
|
+
* @returns {string} the `<ul>…</ul>`, or '' when nothing matches
|
|
15
|
+
*/
|
|
16
|
+
export function renderSocialLinks(accounts, { services } = {}) {
|
|
17
|
+
if (!Array.isArray(accounts)) return '';
|
|
18
|
+
const wanted = typeof services === 'string' && services.trim()
|
|
19
|
+
? new Set(services.split(',').map((s) => s.trim()).filter(Boolean))
|
|
20
|
+
: null;
|
|
21
|
+
const items = accounts
|
|
22
|
+
.filter((a) => a && a.url && (!wanted || wanted.has(a.service)))
|
|
23
|
+
.map((a) => {
|
|
24
|
+
const rel = a.service === 'mastodon' ? ' rel="me"' : '';
|
|
25
|
+
return `<li><a href="${escapeHtml(a.url)}"${rel}><span class="social-icon" data-service="${escapeHtml(a.service)}" aria-hidden="true"></span><span>${escapeHtml(a.name)}</span></a></li>`;
|
|
26
|
+
});
|
|
27
|
+
return items.length ? `<ul>${items.join('')}</ul>` : '';
|
|
28
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file socialspec.js
|
|
3
|
+
* @description Pure renderers for the three SocialSpec profile files:
|
|
4
|
+
* `following.opml` (FollowSpec), `about.md` (AboutSpec) and `contact.vcf`
|
|
5
|
+
* (ContactSpec). No fs and no config reads; `about.file` is read through an
|
|
6
|
+
* injected `readFile`.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const nonEmpty = (v) => typeof v === 'string' && v.trim() !== '';
|
|
10
|
+
|
|
11
|
+
const escapeXml = (s) =>
|
|
12
|
+
String(s)
|
|
13
|
+
.replace(/&/g, '&')
|
|
14
|
+
.replace(/</g, '<')
|
|
15
|
+
.replace(/>/g, '>')
|
|
16
|
+
.replace(/"/g, '"');
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* OPML 2.0 subscription list. Public entries only, in the order given.
|
|
20
|
+
* @param {Array<{ title?: string, feedUrl?: string, siteUrl?: string, public?: boolean }>} following
|
|
21
|
+
* @param {{ title?: string }} [options]
|
|
22
|
+
* @returns {string|null} null when there is no public entry with a feedUrl
|
|
23
|
+
*/
|
|
24
|
+
export function renderOpml(following, { title } = {}) {
|
|
25
|
+
if (!Array.isArray(following)) return null;
|
|
26
|
+
const outlines = following
|
|
27
|
+
.filter((e) => e && e.public !== false && nonEmpty(e.feedUrl))
|
|
28
|
+
.map((e) => {
|
|
29
|
+
const text = escapeXml(nonEmpty(e.title) ? e.title : e.feedUrl);
|
|
30
|
+
const html = nonEmpty(e.siteUrl) ? ` htmlUrl="${escapeXml(e.siteUrl)}"` : '';
|
|
31
|
+
return ` <outline type="rss" text="${text}" title="${text}" xmlUrl="${escapeXml(e.feedUrl)}"${html}/>`;
|
|
32
|
+
});
|
|
33
|
+
if (!outlines.length) return null;
|
|
34
|
+
const head = escapeXml(nonEmpty(title) ? title : 'Following');
|
|
35
|
+
return [
|
|
36
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
37
|
+
'<opml version="2.0">',
|
|
38
|
+
' <head>',
|
|
39
|
+
` <title>${head}</title>`,
|
|
40
|
+
' </head>',
|
|
41
|
+
' <body>',
|
|
42
|
+
...outlines,
|
|
43
|
+
' </body>',
|
|
44
|
+
'</opml>',
|
|
45
|
+
'',
|
|
46
|
+
].join('\n');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* about.md: optional `summary` front matter, then the Markdown body with
|
|
51
|
+
* root-relative link and image targets made absolute.
|
|
52
|
+
* @param {{ summary?: string, body?: string, file?: string }} about `body` wins over `file`
|
|
53
|
+
* @param {{ siteUrl?: string, readFile?: (path: string) => string }} [options]
|
|
54
|
+
* @returns {string|null} null when there is no summary and no body
|
|
55
|
+
*/
|
|
56
|
+
export function renderAbout(about, { siteUrl, readFile } = {}) {
|
|
57
|
+
if (!about || typeof about !== 'object') return null;
|
|
58
|
+
let body = '';
|
|
59
|
+
if (nonEmpty(about.body)) {
|
|
60
|
+
body = about.body;
|
|
61
|
+
} else if (nonEmpty(about.file) && typeof readFile === 'function') {
|
|
62
|
+
try {
|
|
63
|
+
body = String(readFile(about.file));
|
|
64
|
+
} catch {
|
|
65
|
+
body = '';
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
body = body.replace(/\r\n?/g, '\n').trim();
|
|
69
|
+
if (siteUrl && body) {
|
|
70
|
+
const base = String(siteUrl).replace(/\/+$/, '');
|
|
71
|
+
// `](/path` but not protocol-relative `](//host`
|
|
72
|
+
body = body.replace(/\]\(\/(?!\/)/g, `](${base}/`);
|
|
73
|
+
}
|
|
74
|
+
const summary = nonEmpty(about.summary) ? about.summary.trim() : '';
|
|
75
|
+
if (!summary && !body) return null;
|
|
76
|
+
// A JSON string is a valid YAML double-quoted scalar: safe for `:`, quotes, `#`, newlines.
|
|
77
|
+
const front = summary ? `---\nsummary: ${JSON.stringify(summary)}\n---\n\n` : '';
|
|
78
|
+
return `${front}${body}\n`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const escapeVcardText = (s) =>
|
|
82
|
+
String(s)
|
|
83
|
+
.replace(/\\/g, '\\\\')
|
|
84
|
+
.replace(/\r\n|\r|\n/g, '\\n')
|
|
85
|
+
.replace(/,/g, '\\,')
|
|
86
|
+
.replace(/;/g, '\\;');
|
|
87
|
+
|
|
88
|
+
/** Fold one content line at 75 octets (RFC 6350), never splitting a character. */
|
|
89
|
+
function fold(line) {
|
|
90
|
+
if (Buffer.byteLength(line) <= 75) return line;
|
|
91
|
+
const parts = [];
|
|
92
|
+
let cur = '';
|
|
93
|
+
let curBytes = 0;
|
|
94
|
+
let limit = 75;
|
|
95
|
+
for (const ch of line) {
|
|
96
|
+
const n = Buffer.byteLength(ch);
|
|
97
|
+
if (curBytes + n > limit) {
|
|
98
|
+
parts.push(cur);
|
|
99
|
+
cur = '';
|
|
100
|
+
curBytes = 0;
|
|
101
|
+
limit = 74; // continuation lines carry a leading space
|
|
102
|
+
}
|
|
103
|
+
cur += ch;
|
|
104
|
+
curBytes += n;
|
|
105
|
+
}
|
|
106
|
+
parts.push(cur);
|
|
107
|
+
return parts.join('\r\n ');
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* vCard 4.0 for contact.vcf.
|
|
112
|
+
* @param {{ name?: string, email?: string, url?: string, org?: string, title?: string }} contact
|
|
113
|
+
* @param {{ siteUrl?: string }} [options] `URL` defaults to siteUrl
|
|
114
|
+
* @returns {{ text: string|null, warning?: string }}
|
|
115
|
+
*/
|
|
116
|
+
export function renderVcard(contact, { siteUrl } = {}) {
|
|
117
|
+
const c = contact && typeof contact === 'object' ? contact : {};
|
|
118
|
+
if (!nonEmpty(c.name)) {
|
|
119
|
+
return { text: null, warning: 'social: contact has no name, so contact.vcf was not written (FN is required)' };
|
|
120
|
+
}
|
|
121
|
+
const lines = ['BEGIN:VCARD', 'VERSION:4.0', `FN:${escapeVcardText(c.name.trim())}`];
|
|
122
|
+
if (nonEmpty(c.org)) lines.push(`ORG:${escapeVcardText(c.org.trim())}`);
|
|
123
|
+
if (nonEmpty(c.title)) lines.push(`TITLE:${escapeVcardText(c.title.trim())}`);
|
|
124
|
+
if (nonEmpty(c.email)) lines.push(`EMAIL;PREF=1:${escapeVcardText(c.email.trim())}`);
|
|
125
|
+
const url = nonEmpty(c.url) ? c.url : siteUrl;
|
|
126
|
+
// URI value type: not text-escaped (RFC 6350); only strip whitespace so it cannot break a line.
|
|
127
|
+
if (nonEmpty(url)) lines.push(`URL:${String(url).replace(/\s+/g, '')}`);
|
|
128
|
+
lines.push('END:VCARD');
|
|
129
|
+
return { text: lines.map(fold).join('\r\n') + '\r\n' };
|
|
130
|
+
}
|
|
@@ -49,6 +49,21 @@ function getPrograms() {
|
|
|
49
49
|
}
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
+
// config/social.json (written by Vanilla Press): the site's social accounts; main.js `social` wins when defined
|
|
53
|
+
const socialJsonPath = `${cwd}/config/social.json`;
|
|
54
|
+
|
|
55
|
+
/** The social config. Re-read on every call, like getTheme. */
|
|
56
|
+
function getSocial() {
|
|
57
|
+
if (userConfig.social !== undefined) return userConfig.social;
|
|
58
|
+
if (!fs.existsSync(socialJsonPath)) return undefined;
|
|
59
|
+
try {
|
|
60
|
+
return JSON.parse(fs.readFileSync(socialJsonPath, 'utf8'));
|
|
61
|
+
} catch (err) {
|
|
62
|
+
console.log(chalk.yellow(`[social] config/social.json: ${err.message}`));
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
52
67
|
|
|
53
68
|
// DEFINE DEFAULT CONFIG
|
|
54
69
|
// -----------------------------
|
|
@@ -349,7 +364,7 @@ const config = mergeConfigs(defaultConfig, userConfig);
|
|
|
349
364
|
export default config;
|
|
350
365
|
|
|
351
366
|
// Named exports for destructuring imports
|
|
352
|
-
export { getTheme, getPrograms };
|
|
367
|
+
export { getTheme, getPrograms, getSocial };
|
|
353
368
|
export const {
|
|
354
369
|
activeLink,
|
|
355
370
|
autoComponents,
|
|
@@ -12,8 +12,11 @@
|
|
|
12
12
|
const INDENT = ' ';
|
|
13
13
|
|
|
14
14
|
const escapeAttr = (value) => String(value).replace(/&/g, '&').replace(/"/g, '"');
|
|
15
|
+
// Invisible characters are written as references, so they show in the file
|
|
16
|
+
const INVISIBLE_REFS = { '\u00a0': ' ', '\u00ad': '­', '\u200b': '​', '\u2060': '⁠' };
|
|
15
17
|
const escapeMarkup = (text) => text
|
|
16
|
-
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
|
18
|
+
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
|
19
|
+
.replace(/[\u00a0\u00ad\u200b\u2060]/g, (c) => INVISIBLE_REFS[c]);
|
|
17
20
|
// A text run is literal: a `${` in it must not become a placeholder
|
|
18
21
|
const escapeText = (text) => escapeMarkup(text).replace(/\$\{/g, '${');
|
|
19
22
|
|