eleventy-blog 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,94 @@
1
- # Temporary Holding Version
1
+ # eleventy-blog
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Command-line tool for [eleventy-plugin-blog](https://sielay.github.io/eleventy-plugin-blog/).
4
+ Add the blog to an Eleventy site, write posts, publish drafts, tidy tags,
5
+ and check the site before you deploy.
6
+
7
+ You do not install it. Run it with `npx` in your site's folder:
8
+
9
+ ```bash
10
+ npx eleventy-blog init
11
+ ```
12
+
13
+ It needs Node.js 18.3 or later, and Eleventy 3 installed in the site.
14
+
15
+ ## Commands
16
+
17
+ Command | What it does
18
+ ------- | ------------
19
+ `init` | Installs the plugin, adds it to your Eleventy config, and writes a first post if there is none
20
+ `new "Title" [--tags a,b]` | Writes a draft post under your blog folder, named after the date and title
21
+ `list [--drafts] [--json]` | Lists posts, newest first, with date, status, and title
22
+ `publish <post>` | Publishes a draft: removes `draft: true` and sets today's date. `--keep-date` keeps the date
23
+ `tag list` | Lists tags with counts, and flags a tag spelled more than one way, such as `Belarus` and `belarus`
24
+ `tag rename <old> <new>` | Renames a tag in every post, and tells you which redirect to add
25
+ `studio [--open]` | Opens a visual editor for your posts in the browser, with a live preview. See [The studio](#the-studio)
26
+ `check` | Builds the site into a temporary folder and reports problems: posts with no title, unreadable dates, tags spelled two ways, broken internal links, and missing images. Exits with code 1 on errors, so it can stop a deploy
27
+
28
+ `<post>` is a path, a file name, or part of the title. If it matches more
29
+ than one post, the command lists them and changes nothing.
30
+
31
+ ## The studio
32
+
33
+ ```bash
34
+ npx eleventy-blog studio --open
35
+ ```
36
+
37
+ The studio runs on your computer only. It shows your posts, a visual
38
+ editor, a form for the title, date, description, tags, and draft flag,
39
+ and a preview from Eleventy's own dev server.
40
+
41
+ - **Your files stay clean.** On save, the studio merges your edit into
42
+ the original file, so lines you did not touch keep their exact
43
+ formatting. Front matter you did not edit keeps its bytes.
44
+ - **Format from the toolbar.** Text style (paragraph or heading), bold,
45
+ italic, strikethrough, inline code, link, bulleted and numbered lists,
46
+ quote, code block, divider, image, undo, and redo. Buttons show what
47
+ applies at the cursor. Press Ctrl+K (⌘K on a Mac) to add or change a
48
+ link; Markdown shortcuts such as `## ` and `**bold**` also work.
49
+ - **Posts the editor would change open in Source view.** Some Markdown,
50
+ such as unusual list indentation, reads differently in a visual
51
+ editor. The studio checks each post when it opens it, and shows those
52
+ as plain Markdown instead.
53
+ - **Drop images into a post.** They are saved next to your posts in
54
+ `images/`. Change this with `--images <folder>` and `--images-url
55
+ <prefix>`, and make sure Eleventy copies that folder, for example with
56
+ `addPassthroughCopy`.
57
+ - **Nothing leaves your computer.** The studio listens on `127.0.0.1`
58
+ only, needs the private address it prints, and never commits, pushes,
59
+ or deploys. Publish sets `draft` off and today's date, then saves.
60
+ - **It will not overwrite outside edits.** If a file changed on disk since
61
+ you opened it, saving stops and asks you to reload it.
62
+
63
+ Studio options: `--port <number>`, `--no-preview`, `--open`.
64
+
65
+ The editor is [Milkdown](https://milkdown.dev/). The choice and its
66
+ test results are in the
67
+ [editor trial](https://github.com/sielay/eleventy-plugin-blog/blob/master/docs/EDITOR-TRIAL.md).
68
+
69
+ ## Changes are shown first
70
+
71
+ Every command that changes files prints the change and asks before it
72
+ writes. Pass `--yes` to apply without asking, for example in a script.
73
+ Without a terminal and without `--yes`, nothing changes.
74
+
75
+ Front matter edits keep your comments, key order, and list style. Only
76
+ the keys the command touches change.
77
+
78
+ ## Options
79
+
80
+ Option | What it does
81
+ ------ | ------------
82
+ `--cwd <folder>` | Run in another folder
83
+ `--yes`, `-y` | Apply changes without asking
84
+ `--help`, `-h` | Show help
85
+
86
+ ## Use in CI
87
+
88
+ ```yaml
89
+ - run: npx eleventy-blog check
90
+ ```
91
+
92
+ ## Made by
93
+
94
+ Made by [Lukasz Sielski](https://sielay.com). MIT licence.
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env node
2
+ const { parseArgs } = require("util");
3
+
4
+ const COMMANDS = {
5
+ init: () => require("../lib/commands/init"),
6
+ new: () => require("../lib/commands/new"),
7
+ list: () => require("../lib/commands/list"),
8
+ publish: () => require("../lib/commands/publish"),
9
+ tag: () => require("../lib/commands/tag"),
10
+ check: () => require("../lib/commands/check"),
11
+ studio: () => require("../lib/commands/studio"),
12
+ };
13
+
14
+ const HELP = `eleventy-blog: write and maintain an Eleventy blog
15
+
16
+ Usage: eleventy-blog <command> [options]
17
+
18
+ Commands:
19
+ init Add eleventy-plugin-blog to this site
20
+ new "Title" [--tags a,b] Write a new draft post
21
+ list [--drafts] [--json] List posts, newest first
22
+ publish <post> Publish a draft (sets today's date; --keep-date keeps it)
23
+ tag list List tags, and flag tags spelled more than one way
24
+ tag rename <old> <new> Rename a tag in every post
25
+ check Find problems before you deploy
26
+ studio [--open] Edit posts in your browser, with a live preview
27
+
28
+ Options:
29
+ --cwd <folder> Run in another folder
30
+ --yes, -y Apply changes without asking
31
+ --help, -h Show this help
32
+
33
+ Commands that change files show the change and ask first.
34
+ Docs: https://sielay.github.io/eleventy-plugin-blog/
35
+ `;
36
+
37
+ async function main(argv) {
38
+ const { values, positionals } = parseArgs({
39
+ args: argv,
40
+ allowPositionals: true,
41
+ options: {
42
+ cwd: { type: "string" },
43
+ yes: { type: "boolean", short: "y" },
44
+ help: { type: "boolean", short: "h" },
45
+ tags: { type: "string" },
46
+ dir: { type: "string" },
47
+ drafts: { type: "boolean" },
48
+ json: { type: "boolean" },
49
+ "keep-date": { type: "boolean" },
50
+ open: { type: "boolean" },
51
+ port: { type: "string" },
52
+ images: { type: "string" },
53
+ "images-url": { type: "string" },
54
+ "no-preview": { type: "boolean" },
55
+ },
56
+ });
57
+ const [command, ...rest] = positionals;
58
+ if (!command || values.help) {
59
+ console.log(HELP);
60
+ return 0;
61
+ }
62
+ const load = COMMANDS[command];
63
+ if (!load) {
64
+ console.error(`Unknown command "${command}".\n`);
65
+ console.log(HELP);
66
+ return 1;
67
+ }
68
+ const args = { ...values, positionals: rest, cwd: require("path").resolve(values.cwd || process.cwd()) };
69
+ return load()(args);
70
+ }
71
+
72
+ main(process.argv.slice(2))
73
+ .then((code) => {
74
+ process.exitCode = code || 0;
75
+ })
76
+ .catch((error) => {
77
+ console.error(error.message);
78
+ process.exitCode = 1;
79
+ });
@@ -0,0 +1,118 @@
1
+ const fs = require("fs");
2
+ const os = require("os");
3
+ const path = require("path");
4
+ const { loadSite, readPosts, dateValue, fileDate } = require("../site");
5
+ const { groupTags } = require("./tag");
6
+ const { yamlError } = require("../frontmatter");
7
+ const { colour, plural } = require("../ui");
8
+
9
+ function walk(dir) {
10
+ const files = [];
11
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
12
+ const full = path.join(dir, entry.name);
13
+ if (entry.isDirectory()) files.push(...walk(full));
14
+ else files.push(full);
15
+ }
16
+ return files;
17
+ }
18
+
19
+ /** Does a site path exist in the build output? */
20
+ function existsInOutput(outDir, urlPath) {
21
+ const clean = decodeURIComponent(urlPath.split(/[?#]/)[0]);
22
+ const target = path.join(outDir, clean);
23
+ if (!target.startsWith(outDir)) return true; // outside the site; not ours to judge
24
+ return [target, path.join(target, "index.html"), `${target}.html`].some(
25
+ (candidate) => fs.existsSync(candidate) && fs.statSync(candidate).isFile()
26
+ );
27
+ }
28
+
29
+ /** Find internal links and images that point at nothing. */
30
+ function findBrokenLinks(outDir, pathPrefix) {
31
+ const prefix = pathPrefix.replace(/\/+$/, "");
32
+ const problems = [];
33
+ for (const file of walk(outDir).filter((f) => f.endsWith(".html"))) {
34
+ const html = fs.readFileSync(file, "utf8");
35
+ const pageUrl = `/${path.relative(outDir, file).split(path.sep).join("/")}`;
36
+ for (const match of html.matchAll(/\s(href|src)=["']([^"']+)["']/g)) {
37
+ const [, attr, raw] = match;
38
+ if (/^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i.test(raw)) continue; // external, mailto, data, anchors
39
+ let resolved = new URL(raw, `http://site${pageUrl}`).pathname;
40
+ if (prefix && resolved.startsWith(prefix)) resolved = resolved.slice(prefix.length) || "/";
41
+ if (!existsInOutput(outDir, resolved)) {
42
+ problems.push({
43
+ page: pageUrl.replace(/index\.html$/, ""),
44
+ kind: attr === "src" ? "missing file" : "broken link",
45
+ target: raw,
46
+ });
47
+ }
48
+ }
49
+ }
50
+ return problems;
51
+ }
52
+
53
+ module.exports = async function check(args) {
54
+ const site = await loadSite(args.cwd);
55
+ const posts = await readPosts(site);
56
+ const errors = [];
57
+ const warnings = [];
58
+
59
+ // Front matter.
60
+ for (const post of posts) {
61
+ const where = path.relative(args.cwd, post.file);
62
+ if (!post.data.title) errors.push(`${where}: no title`);
63
+ const yaml = yamlError(post);
64
+ if (yaml) warnings.push(`${where}: front matter is not strict YAML, so eleventy-blog cannot edit it: ${yaml}`);
65
+ if (!post.data.date && !post.data.created && !fileDate(post.file)) {
66
+ warnings.push(`${where}: no date in front matter or file name, so Eleventy uses the file's modified time`);
67
+ } else if (!dateValue(post)) {
68
+ errors.push(`${where}: the date cannot be read`);
69
+ }
70
+ }
71
+
72
+ // Tags that land on the same page under different spellings.
73
+ for (const group of groupTags(site, posts)) {
74
+ if (!group.slug) {
75
+ errors.push(`A tag has no usable letters, so it has no page: ${[...group.spellings.keys()].join(", ")}`);
76
+ } else if (group.spellings.size > 1) {
77
+ warnings.push(
78
+ `Tag "${group.slug}" is spelled ${group.spellings.size} ways: ${[...group.spellings.keys()].join(", ")}. ` +
79
+ `Run: eleventy-blog tag rename "<spelling>" "<one spelling>"`
80
+ );
81
+ }
82
+ }
83
+
84
+ // Build into a temporary folder, then look for broken links.
85
+ const outDir = fs.mkdtempSync(path.join(os.tmpdir(), "eleventy-blog-check-"));
86
+ const previous = process.cwd();
87
+ process.chdir(args.cwd);
88
+ try {
89
+ const elev = new site.Eleventy(undefined, outDir, {
90
+ quietMode: true,
91
+ ...(site.configPath ? { configPath: site.configPath } : {}),
92
+ });
93
+ elev.disableLogger?.();
94
+ await elev.write();
95
+ for (const problem of findBrokenLinks(outDir, site.pathPrefix)) {
96
+ errors.push(`${problem.page}: ${problem.kind} ${problem.target}`);
97
+ }
98
+ } catch (error) {
99
+ let cause = error;
100
+ while (cause.originalError || cause.cause) cause = cause.originalError || cause.cause;
101
+ errors.push(`The build failed: ${cause.message}`);
102
+ } finally {
103
+ process.chdir(previous);
104
+ fs.rmSync(outDir, { recursive: true, force: true });
105
+ }
106
+
107
+ const drafts = posts.filter((post) => post.data.draft).length;
108
+ warnings.forEach((line) => console.log(`${colour.yellow("warning")} ${line}`));
109
+ errors.forEach((line) => console.log(`${colour.red("error")} ${line}`));
110
+ console.log(
111
+ `\n${plural(posts.length, "post")} (${plural(drafts, "draft")}): ` +
112
+ (errors.length ? colour.red(plural(errors.length, "error")) : colour.green("no errors")) +
113
+ `, ${plural(warnings.length, "warning")}`
114
+ );
115
+ return errors.length ? 1 : 0;
116
+ };
117
+
118
+ module.exports.findBrokenLinks = findBrokenLinks;
@@ -0,0 +1,137 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const { spawnSync } = require("child_process");
4
+ const { findConfig, resolveFromSite, loadSite } = require("../site");
5
+ const { newPostText } = require("../frontmatter");
6
+ const { colour, confirm, printChange } = require("../ui");
7
+
8
+ const PLUGIN = "eleventy-plugin-blog";
9
+
10
+ /** Is the package an ES module package? */
11
+ function isModulePackage(cwd) {
12
+ try {
13
+ return JSON.parse(fs.readFileSync(path.join(cwd, "package.json"), "utf8")).type === "module";
14
+ } catch {
15
+ return false;
16
+ }
17
+ }
18
+
19
+ function isEsm(file, cwd) {
20
+ if (file.endsWith(".mjs")) return true;
21
+ if (file.endsWith(".cjs")) return false;
22
+ return isModulePackage(cwd);
23
+ }
24
+
25
+ /**
26
+ * Add the plugin to a config file's text. Returns the new text, or null
27
+ * when the shape of the file is not one this command recognises.
28
+ */
29
+ function addPluginToConfig(text, esm) {
30
+ if (text.includes(PLUGIN)) return text;
31
+ const fn = esm
32
+ ? /export\s+default\s+(?:async\s+)?function\s*\w*\s*\(\s*(\w+)[^)]*\)\s*\{/
33
+ : /module\.exports\s*=\s*(?:async\s+)?(?:function\s*\w*\s*\(\s*(\w+)[^)]*\)|\(\s*(\w+)[^)]*\)\s*=>)\s*\{/;
34
+ const match = text.match(fn);
35
+ if (!match) return null;
36
+ const configName = match[1] || match[2];
37
+ const importLine = esm
38
+ ? `import blog from "${PLUGIN}";\n\n`
39
+ : `const blog = require("${PLUGIN}");\n\n`;
40
+ const at = match.index + match[0].length;
41
+ const withCall = `${text.slice(0, at)}\n ${configName}.addPlugin(blog);${text.slice(at)}`;
42
+ return importLine + (withCall.startsWith("\n") ? withCall.slice(1) : withCall);
43
+ }
44
+
45
+ function newConfigText(esm) {
46
+ return esm
47
+ ? `import blog from "${PLUGIN}";\n\nexport default function (eleventyConfig) {\n eleventyConfig.addPlugin(blog);\n}\n`
48
+ : `const blog = require("${PLUGIN}");\n\nmodule.exports = function (eleventyConfig) {\n eleventyConfig.addPlugin(blog);\n};\n`;
49
+ }
50
+
51
+ function today() {
52
+ return new Date().toISOString().slice(0, 10);
53
+ }
54
+
55
+ module.exports = async function init(args) {
56
+ const cwd = args.cwd;
57
+ if (!fs.existsSync(path.join(cwd, "package.json"))) {
58
+ console.error(colour.red("No package.json here. Run this in your site's folder, or run `npm init -y` first."));
59
+ return 1;
60
+ }
61
+ if (!resolveFromSite(cwd, "@11ty/eleventy")) {
62
+ console.error(colour.red("Eleventy is not installed. Run `npm install --save-dev @11ty/eleventy` first."));
63
+ return 1;
64
+ }
65
+
66
+ // 1. Install the plugin.
67
+ if (!resolveFromSite(cwd, PLUGIN)) {
68
+ if (await confirm(`Install ${PLUGIN} as a dev dependency?`, args)) {
69
+ const result = spawnSync("npm", ["install", "--save-dev", PLUGIN], {
70
+ cwd,
71
+ stdio: "inherit",
72
+ shell: process.platform === "win32",
73
+ });
74
+ if (result.status !== 0) {
75
+ console.error(colour.red("npm install failed. Nothing else was changed."));
76
+ return 1;
77
+ }
78
+ } else {
79
+ console.log(`Install it later with: npm install --save-dev ${PLUGIN}`);
80
+ }
81
+ } else {
82
+ console.log(colour.dim(`${PLUGIN} is already installed.`));
83
+ }
84
+
85
+ // 2. Add it to the config.
86
+ const configPath = findConfig(cwd);
87
+ if (configPath) {
88
+ const before = fs.readFileSync(configPath, "utf8");
89
+ const after = addPluginToConfig(before, isEsm(configPath, cwd));
90
+ if (after === null) {
91
+ console.log(colour.yellow(`Could not find where to add the plugin in ${path.basename(configPath)}. Add these lines yourself:`));
92
+ console.log(isEsm(configPath, cwd) ? ` import blog from "${PLUGIN}";` : ` const blog = require("${PLUGIN}");`);
93
+ console.log(" eleventyConfig.addPlugin(blog);");
94
+ } else if (after === before) {
95
+ console.log(colour.dim(`${path.basename(configPath)} already uses the plugin.`));
96
+ } else {
97
+ printChange(path.relative(cwd, configPath), before, after);
98
+ if (await confirm("Apply this change?", args)) fs.writeFileSync(configPath, after);
99
+ }
100
+ } else {
101
+ const file = path.join(cwd, "eleventy.config.js");
102
+ const text = newConfigText(isModulePackage(cwd));
103
+ printChange("eleventy.config.js (new)", null, text);
104
+ if (await confirm("Create this file?", args)) fs.writeFileSync(file, text);
105
+ }
106
+
107
+ // 3. Make sure there is somewhere to write.
108
+ let blogDir = path.join(cwd, "blog");
109
+ try {
110
+ blogDir = (await loadSite(cwd)).blogDir;
111
+ } catch (error) {
112
+ // Eleventy refuses to load when the input folder does not exist yet,
113
+ // as in a new site. Its message names the folder; use it.
114
+ const missing = String(error.message).match(/"([^"]+)" `input` parameter/);
115
+ if (missing) blogDir = path.join(cwd, missing[1], "blog");
116
+ }
117
+ const hasPosts = fs.existsSync(blogDir) && fs.readdirSync(blogDir).length > 0;
118
+ if (!hasPosts) {
119
+ const file = path.join(blogDir, `${today()}-hello.md`);
120
+ const text = newPostText({
121
+ title: "Hello",
122
+ date: today(),
123
+ draft: false,
124
+ body: "\nThis is the first post. Edit it, or run `npx eleventy-blog new \"Title\"` for another.\n",
125
+ });
126
+ printChange(`${path.relative(cwd, file)} (new)`, null, text);
127
+ if (await confirm("Create a first post?", args)) {
128
+ fs.mkdirSync(blogDir, { recursive: true });
129
+ fs.writeFileSync(file, text);
130
+ }
131
+ }
132
+
133
+ console.log(colour.green("Done. Run `npx @11ty/eleventy --serve` and open /blog/."));
134
+ return 0;
135
+ };
136
+
137
+ module.exports.addPluginToConfig = addPluginToConfig;
@@ -0,0 +1,39 @@
1
+ const path = require("path");
2
+ const { loadSite, readPosts, dateValue } = require("../site");
3
+ const { colour, printTable, plural } = require("../ui");
4
+
5
+ const shorten = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
6
+
7
+ module.exports = async function list(args) {
8
+ const site = await loadSite(args.cwd);
9
+ let posts = await readPosts(site);
10
+ if (args.drafts) posts = posts.filter((post) => post.data.draft);
11
+
12
+ if (args.json) {
13
+ const rows = posts.map((post) => ({
14
+ file: path.relative(args.cwd, post.file),
15
+ title: post.data.title || null,
16
+ date: dateValue(post) ? new Date(dateValue(post)).toISOString().slice(0, 10) : null,
17
+ draft: Boolean(post.data.draft),
18
+ tags: [].concat(post.data.tags || []),
19
+ }));
20
+ console.log(JSON.stringify(rows, null, 2));
21
+ return 0;
22
+ }
23
+
24
+ if (!posts.length) {
25
+ console.log(args.drafts ? "No drafts." : `No posts in ${path.relative(args.cwd, site.blogDir) || "."}.`);
26
+ return 0;
27
+ }
28
+ printTable(
29
+ posts.map((post) => [
30
+ dateValue(post) ? new Date(dateValue(post)).toISOString().slice(0, 10) : "no date ",
31
+ post.data.draft ? colour.yellow("draft") : colour.green("live "),
32
+ post.data.title ? shorten(String(post.data.title), 60) : colour.red("(no title)"),
33
+ colour.dim(path.relative(args.cwd, post.file)),
34
+ ])
35
+ );
36
+ const drafts = posts.filter((post) => post.data.draft).length;
37
+ console.log(colour.dim(`\n${plural(posts.length, "post")}, ${plural(drafts, "draft")}`));
38
+ return 0;
39
+ };
@@ -0,0 +1,32 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const { loadSite } = require("../site");
4
+ const { newPostText } = require("../frontmatter");
5
+ const { colour } = require("../ui");
6
+
7
+ function today() {
8
+ return new Date().toISOString().slice(0, 10);
9
+ }
10
+
11
+ module.exports = async function newPost(args) {
12
+ const title = args.positionals.join(" ").trim();
13
+ if (!title) {
14
+ console.error(colour.red('Give the post a title: eleventy-blog new "My first post"'));
15
+ return 1;
16
+ }
17
+ const site = await loadSite(args.cwd);
18
+ const dir = args.dir ? path.resolve(args.cwd, args.dir) : site.blogDir;
19
+ const date = today();
20
+ const slug = site.slug(title.toLowerCase()) || "post";
21
+ const file = path.join(dir, `${date}-${slug}.md`);
22
+ if (fs.existsSync(file)) {
23
+ console.error(colour.red(`${path.relative(args.cwd, file)} already exists.`));
24
+ return 1;
25
+ }
26
+ const tags = args.tags ? args.tags.split(",").map((tag) => tag.trim()).filter(Boolean) : [];
27
+ fs.mkdirSync(dir, { recursive: true });
28
+ fs.writeFileSync(file, newPostText({ title, date, tags, draft: true, body: "\n" }));
29
+ console.log(`${colour.green("Created")} ${path.relative(args.cwd, file)} ${colour.dim("(draft)")}`);
30
+ console.log(colour.dim(`Publish it with: eleventy-blog publish ${slug}`));
31
+ return 0;
32
+ };
@@ -0,0 +1,48 @@
1
+ const path = require("path");
2
+ const { loadSite, readPosts, matchPosts } = require("../site");
3
+ const { serialisePost, writePost, touch } = require("../frontmatter");
4
+ const { colour, confirm, printChange } = require("../ui");
5
+
6
+ function today() {
7
+ return new Date().toISOString().slice(0, 10);
8
+ }
9
+
10
+ module.exports = async function publish(args) {
11
+ const query = args.positionals.join(" ").trim();
12
+ if (!query) {
13
+ console.error(colour.red("Name the post: eleventy-blog publish <file or part of its name>"));
14
+ return 1;
15
+ }
16
+ const site = await loadSite(args.cwd);
17
+ const posts = await readPosts(site);
18
+ const matches = matchPosts(posts, query, args.cwd);
19
+ if (matches.length === 0) {
20
+ console.error(colour.red(`No post matches "${query}". Run eleventy-blog list to see them.`));
21
+ return 1;
22
+ }
23
+ if (matches.length > 1) {
24
+ console.error(colour.red(`"${query}" matches ${matches.length} posts. Be more specific:`));
25
+ matches.forEach((post) => console.error(` ${path.relative(args.cwd, post.file)}`));
26
+ return 1;
27
+ }
28
+
29
+ const post = matches[0];
30
+ if (!post.data.draft) {
31
+ console.log(`${path.relative(args.cwd, post.file)} is already published.`);
32
+ return 0;
33
+ }
34
+ try {
35
+ touch(post);
36
+ } catch (error) {
37
+ console.error(colour.red(error.message));
38
+ return 1;
39
+ }
40
+ post.doc.delete("draft");
41
+ if (!args["keep-date"]) post.doc.set("date", today());
42
+ const after = serialisePost(post);
43
+ printChange(path.relative(args.cwd, post.file), post.text, after);
44
+ if (!(await confirm("Publish this post?", args))) return 1;
45
+ writePost(post);
46
+ console.log(colour.green("Published. It appears on the next build."));
47
+ return 0;
48
+ };
@@ -0,0 +1,104 @@
1
+ const fs = require("fs");
2
+ const net = require("net");
3
+ const path = require("path");
4
+ const crypto = require("crypto");
5
+ const { spawn } = require("child_process");
6
+ const { loadSite, eleventyBin } = require("../site");
7
+ const { createStudioServer } = require("../studio/server");
8
+ const { colour } = require("../ui");
9
+
10
+ const DIST = path.join(__dirname, "..", "..", "studio-dist", "app.js");
11
+
12
+ function freePort() {
13
+ return new Promise((resolve, reject) => {
14
+ const probe = net.createServer();
15
+ probe.once("error", reject);
16
+ probe.listen(0, "127.0.0.1", () => {
17
+ const { port } = probe.address();
18
+ probe.close(() => resolve(port));
19
+ });
20
+ });
21
+ }
22
+
23
+ /** Map each input file to its URL, from one in-memory build. */
24
+ async function buildUrlMap(site) {
25
+ const previous = process.cwd();
26
+ process.chdir(site.cwd);
27
+ try {
28
+ const elev = new site.Eleventy(undefined, undefined, {
29
+ quietMode: true,
30
+ ...(site.configPath ? { configPath: site.configPath } : {}),
31
+ });
32
+ const results = await elev.toJSON();
33
+ return new Map(results.map((entry) => [path.resolve(site.cwd, entry.inputPath), entry.url]));
34
+ } finally {
35
+ process.chdir(previous);
36
+ }
37
+ }
38
+
39
+ module.exports = async function studio(args) {
40
+ if (!fs.existsSync(DIST)) {
41
+ console.error(colour.red("The studio is not built. In the repository, run: npm run build --workspace cli"));
42
+ return 1;
43
+ }
44
+ const site = await loadSite(args.cwd);
45
+ const imagesDir = path.resolve(args.cwd, args.images || path.join(site.blogDir, "images"));
46
+ const imagesUrl = args["images-url"] || `/${path.relative(site.input, imagesDir).split(path.sep).join("/")}/`;
47
+
48
+ let urls = new Map();
49
+ const refreshUrls = async () => {
50
+ try {
51
+ urls = await buildUrlMap(site);
52
+ } catch (error) {
53
+ console.log(colour.yellow(`Preview addresses unavailable: ${error.message}`));
54
+ }
55
+ };
56
+ await refreshUrls();
57
+
58
+ // Eleventy's own dev server renders the preview.
59
+ let preview = null;
60
+ let previewUrl = null;
61
+ if (!args["no-preview"]) {
62
+ const bin = eleventyBin(site.cwd);
63
+ if (bin) {
64
+ const port = await freePort();
65
+ preview = spawn(process.execPath, [bin, "--serve", `--port=${port}`, "--quiet"], {
66
+ cwd: site.cwd,
67
+ stdio: ["ignore", "ignore", "inherit"],
68
+ });
69
+ previewUrl = `http://localhost:${port}`;
70
+ }
71
+ }
72
+
73
+ const token = crypto.randomBytes(18).toString("base64url");
74
+ const server = createStudioServer(site, {
75
+ token,
76
+ imagesDir,
77
+ imagesUrl,
78
+ previewUrl,
79
+ urlFor: (file) => urls.get(file) || null,
80
+ onSaved: () => setTimeout(refreshUrls, 300),
81
+ });
82
+ const port = await server.start(args.port ? Number(args.port) : 0);
83
+ const address = `http://127.0.0.1:${port}/?token=${token}`;
84
+
85
+ console.log(`${colour.green("Studio running:")} ${address}`);
86
+ console.log(colour.dim(`Images go to ${path.relative(args.cwd, imagesDir)}/, served at ${imagesUrl}`));
87
+ console.log(colour.dim("Make sure Eleventy copies that folder, for example with addPassthroughCopy."));
88
+ console.log(colour.dim("Press Ctrl+C to stop."));
89
+
90
+ if (args.open) {
91
+ const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
92
+ spawn(opener, [address], { stdio: "ignore", detached: true, shell: process.platform === "win32" }).unref();
93
+ }
94
+
95
+ await new Promise((resolve) => {
96
+ const stop = () => {
97
+ if (preview) preview.kill();
98
+ server.close(() => resolve());
99
+ };
100
+ process.once("SIGINT", stop);
101
+ process.once("SIGTERM", stop);
102
+ });
103
+ return 0;
104
+ };