hd-garden 0.10.2 → 0.10.4

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/eslint.config.mjs CHANGED
@@ -16,6 +16,7 @@ const eslintConfig = defineConfig([
16
16
  // Bundled output of the editor preview and plugins.
17
17
  "ui/preview/dist/**",
18
18
  "editors/*/dist/**",
19
+ "editors/dist/**",
19
20
  "next-env.d.ts",
20
21
  ]),
21
22
  ]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hd-garden",
3
- "version": "0.10.2",
3
+ "version": "0.10.4",
4
4
  "private": false,
5
5
  "description": "用 Markdown 写作、用 GitHub Pages 发布的个人博客引擎。",
6
6
  "license": "MIT",
@@ -27,6 +27,7 @@
27
27
  "bin",
28
28
  "build",
29
29
  "docs/handbook",
30
+ "editors/dist",
30
31
  "public/favicon.svg",
31
32
  "public/apple-touch-icon.png",
32
33
  "public/og.png",
@@ -68,7 +69,8 @@
68
69
  "test": "npm run build && node --experimental-strip-types --test tests/*.test.mjs",
69
70
  "ui:build": "node scripts/build-ui-preview.mjs",
70
71
  "editors:build": "node editors/vscode/build.mjs && node editors/obsidian/build.mjs && node editors/typora/build.mjs",
71
- "prepack": "node scripts/build-ui-preview.mjs",
72
+ "editors:pack": "node scripts/pack-editors.mjs",
73
+ "prepack": "node scripts/pack-editors.mjs",
72
74
  "lint": "node bin/garden.mjs sync && eslint . --ignore-pattern dist --ignore-pattern .next --ignore-pattern .garden --ignore-pattern templates"
73
75
  },
74
76
  "dependencies": {
@@ -19,6 +19,8 @@ import { buildFullIndex, buildSearchIndex } from "../ui/garden/search-index.mjs"
19
19
  import { coverImageSet, loadSharp } from "./cover-images.mjs";
20
20
  import { readFileSizeCache } from "./file-sizes.mjs";
21
21
  import { previewDocument, previewFileName, renderFilePreview } from "./file-preview.mjs";
22
+ import { ensureExcalidrawSvg, isExcalidrawPath } from "./excalidraw.mjs";
23
+ import { embedExcalidrawImages, embedExcalidrawImgTags } from "../ui/garden/excalidraw-inline.mjs";
22
24
  import { parseGardenBlock, parseGardenInfo, scanFences } from "../ui/garden/parse.mjs";
23
25
  import { checkGardenMarkdown } from "../ui/garden/check.mjs";
24
26
  import {
@@ -152,23 +154,40 @@ const assetCache = new Map();
152
154
  /** Published URL → original file and its copy, for making resized covers later. */
153
155
  const assetFiles = new Map();
154
156
 
155
- function copyLocalAsset(value, markdownPath, sourcePath, options = {}) {
156
- if (!value || isExternalAsset(value)) return value;
157
-
157
+ function locateLocalAsset(value, markdownPath, sourcePath, options = {}) {
158
+ if (!value || isExternalAsset(value)) return null;
158
159
  const baseDir = options.baseDir ?? path.dirname(markdownPath);
159
160
  const allowedRoot = options.allowedRoot ?? contentRoot;
160
- const mediaPrefix = options.mediaPrefix ?? "";
161
161
  const [assetPath, suffix = ""] = value.split(/(?=[?#])/u, 2);
162
162
  const decodedPath = decodeURIComponent(assetPath.replace(/^<|>$/g, ""));
163
163
  const absoluteSource = path.resolve(baseDir, decodedPath);
164
164
  const relativeSource = path.relative(allowedRoot, absoluteSource);
165
+ if (relativeSource.startsWith("..") || path.isAbsolute(relativeSource)) {
166
+ fail(sourcePath, options.missingMessage ?? `找不到本地媒体文件 ${value}`);
167
+ }
168
+ return { absoluteSource, relativeSource, decodedPath, suffix, mediaPrefix: options.mediaPrefix ?? "" };
169
+ }
165
170
 
166
- if (
167
- relativeSource.startsWith("..") ||
168
- path.isAbsolute(relativeSource) ||
169
- !fs.existsSync(absoluteSource) ||
170
- !fs.statSync(absoluteSource).isFile()
171
- ) {
171
+ /** Export the sibling flat SVG and return its text. The page inlines this; it is not an image URL. */
172
+ function readExportedSvg(value, markdownPath, sourcePath, options = {}) {
173
+ const located = locateLocalAsset(value, markdownPath, sourcePath, options);
174
+ if (!located || !isExcalidrawPath(located.decodedPath)) {
175
+ fail(sourcePath, `找不到 Excalidraw 源文件 ${value}`);
176
+ }
177
+ try {
178
+ const svgPath = ensureExcalidrawSvg(located.absoluteSource);
179
+ return fs.readFileSync(svgPath, "utf8");
180
+ } catch (error) {
181
+ fail(sourcePath, error instanceof Error ? error.message : String(error));
182
+ }
183
+ }
184
+
185
+ function copyLocalAsset(value, markdownPath, sourcePath, options = {}) {
186
+ const located = locateLocalAsset(value, markdownPath, sourcePath, options);
187
+ if (!located) return value;
188
+ const { absoluteSource, relativeSource, suffix, mediaPrefix } = located;
189
+
190
+ if (!fs.existsSync(absoluteSource) || !fs.statSync(absoluteSource).isFile()) {
172
191
  fail(sourcePath, options.missingMessage ?? `找不到本地媒体文件 ${value}`);
173
192
  }
174
193
 
@@ -194,15 +213,21 @@ function copyLocalAsset(value, markdownPath, sourcePath, options = {}) {
194
213
  function rewriteMarkdownAssets(content, markdownPath, sourcePath, options = {}) {
195
214
  // `![alt](<a b (1).png>)` keeps its angle brackets: without them the space
196
215
  // and the parentheses would no longer be one destination.
197
- const markdownImages = replaceInlineLinks(content, (link) =>
198
- link.image ? formatInlineLink(link, copyLocalAsset(link.url, markdownPath, sourcePath, options)) : undefined,
199
- );
216
+ // `.excalidraw` images stay in the source until the AST embed below, which
217
+ // swaps them for the inline SVG instead of an image URL.
218
+ const markdownImages = replaceInlineLinks(content, (link) => {
219
+ if (!link.image || isExcalidrawPath(link.url)) return undefined;
220
+ return formatInlineLink(link, copyLocalAsset(link.url, markdownPath, sourcePath, options));
221
+ });
200
222
 
201
- return markdownImages.replace(
223
+ const withAssets = markdownImages.replace(
202
224
  /(<(?:img|audio|video|source)\b[^>]*\bsrc=["'])([^"']+)(["'])/giu,
203
- (_, prefix, src, suffix) =>
204
- `${prefix}${copyLocalAsset(src, markdownPath, sourcePath, options)}${suffix}`,
225
+ (tag, prefix, src, suffix) =>
226
+ isExcalidrawPath(src) ? tag : `${prefix}${copyLocalAsset(src, markdownPath, sourcePath, options)}${suffix}`,
205
227
  );
228
+
229
+ const read = (url) => readExportedSvg(url, markdownPath, sourcePath, options);
230
+ return embedExcalidrawImgTags(embedExcalidrawImages(withAssets, read), read);
206
231
  }
207
232
 
208
233
  function markdownStem(markdownPath) {
@@ -0,0 +1,352 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import readline from "node:readline/promises";
6
+ import { stdin, stdout } from "node:process";
7
+ import { gardenPackageRoot } from "./garden-paths.mjs";
8
+
9
+ export const TYPORA_PLUGIN_ID = "hedon954.garden-intelligent-ui";
10
+ const OFFERED_MARKER = ".install-offered";
11
+ const TYPORA_FRAMEWORK_URL =
12
+ "https://github.com/typora-community-plugin/typora-community-plugin/blob/main/docs/en-us/user-guide/1a-installation.md";
13
+
14
+ const text = {
15
+ zh: {
16
+ askVscode: "安装 VS Code / Cursor 的 Garden Intelligent UI 插件? [y/N] ",
17
+ askTypora: "安装 Typora 的 Garden Intelligent UI 插件? [y/N] ",
18
+ hints: `编辑器插件已复制到 .garden/editors/(VS Code / Cursor 的 VSIX,以及 Typora 插件)。
19
+ 这次没有交互安装:当前不是可交互终端,或 CI=1,或设置了 GARDEN_SKIP_EDITORS=1。
20
+ 安装到本机编辑器:
21
+ npx garden editors install
22
+ 只装其中一个,或在脚本里直接装:
23
+ npx garden editors install --vscode
24
+ npx garden editors install --typora
25
+ npx garden editors install --yes
26
+ `,
27
+ missing: "没有找到已打包的编辑器插件(editors/dist)。在 Garden 引擎仓库运行 npm run editors:pack 后再安装。\n",
28
+ declined: "没有安装编辑器插件。之后可以运行 npx garden editors install。\n",
29
+ installedCli: (editor, file) => `已用 ${editor} 安装扩展:${file}\n`,
30
+ cliFailed: (editor, file) => `${editor} --install-extension 失败。可改为手动安装:${file}\n`,
31
+ manual: (file) => `没有找到 code 或 cursor 命令。请手动从 VSIX 安装:
32
+ 1. 打开 VS Code 或 Cursor。
33
+ 2. 打开扩展视图,点右上角「…」,选择 Install from VSIX(从 VSIX 安装)。
34
+ 3. 选这个文件:
35
+ ${file}
36
+ `,
37
+ noVsix: "没有找到 VSIX。先运行 npm run editors:pack,或确认站点 .garden/editors/vscode/ 里有 .vsix 文件。\n",
38
+ noTypora: "没有找到 Typora 插件产物(manifest.json、main.js、style.css)。\n",
39
+ typoraCopied: (dirs) => `已把 Typora 插件复制到:
40
+ ${dirs.map((dir) => ` ${dir}`).join("\n")}
41
+ `,
42
+ typoraMissingFramework: `没有在常见位置检测到 typora-community-plugin。Typora 没有官方插件接口;若还没装,请先安装这个社区框架:
43
+ ${TYPORA_FRAMEWORK_URL}
44
+ `,
45
+ typoraEnable: "打开 Typora,在「设置 → 已安装插件」里勾选 Garden Intelligent UI。\n",
46
+ typoraUpgrade:
47
+ "升级 Typora 会覆盖社区框架改过的程序文件。升级后需要重新安装 typora-community-plugin,再勾选本插件。稿件里的围栏原文还在。\n",
48
+ },
49
+ en: {
50
+ askVscode: "Install the Garden Intelligent UI extension for VS Code / Cursor? [y/N] ",
51
+ askTypora: "Install the Garden Intelligent UI plugin for Typora? [y/N] ",
52
+ hints: `Editor plugins are in .garden/editors/ (a VSIX for VS Code / Cursor, and the Typora plugin).
53
+ This run did not ask for an install: there is no interactive terminal, or CI=1, or GARDEN_SKIP_EDITORS=1 is set.
54
+ Install them into your editors with:
55
+ npx garden editors install
56
+ Install one of them, or install from a script:
57
+ npx garden editors install --vscode
58
+ npx garden editors install --typora
59
+ npx garden editors install --yes
60
+ `,
61
+ missing: "Packaged editor plugins were not found (editors/dist). From the Garden engine repository, run npm run editors:pack, then install.\n",
62
+ declined: "Editor plugins were not installed. Run npx garden editors install when you want them.\n",
63
+ installedCli: (editor, file) => `Installed the extension with ${editor}: ${file}\n`,
64
+ cliFailed: (editor, file) => `${editor} --install-extension failed. Install the VSIX manually: ${file}\n`,
65
+ manual: (file) => `No code or cursor command was found. Install from VSIX instead:
66
+ 1. Open VS Code or Cursor.
67
+ 2. Open the Extensions view, choose the ... menu, then Install from VSIX.
68
+ 3. Select this file:
69
+ ${file}
70
+ `,
71
+ noVsix: "No VSIX was found. Run npm run editors:pack, or check .garden/editors/vscode/ for a .vsix file.\n",
72
+ noTypora: "Typora plugin files were not found (manifest.json, main.js, style.css).\n",
73
+ typoraCopied: (dirs) => `Copied the Typora plugin to:
74
+ ${dirs.map((dir) => ` ${dir}`).join("\n")}
75
+ `,
76
+ typoraMissingFramework: `typora-community-plugin was not found in the usual locations. Typora has no official plugin API; install that community framework if it is not already installed:
77
+ ${TYPORA_FRAMEWORK_URL}
78
+ `,
79
+ typoraEnable: "Open Typora, then enable Garden Intelligent UI under Settings -> Installed plugins.\n",
80
+ typoraUpgrade:
81
+ "A Typora upgrade overwrites the community framework inside the app. Reinstall typora-community-plugin after upgrading, then enable this plugin again. The fences in your posts stay in the Markdown.\n",
82
+ },
83
+ };
84
+
85
+ function strings(lang) {
86
+ return text[lang === "en" ? "en" : "zh"];
87
+ }
88
+
89
+ function write(message) {
90
+ stdout.write(message.endsWith("\n") ? message : `${message}\n`);
91
+ }
92
+
93
+ /** Automatic init/sync prompts only. An explicit `garden editors install` ignores this. */
94
+ export function editorsPromptAllowed() {
95
+ if (process.env.GARDEN_SKIP_EDITORS === "1") return false;
96
+ if (process.env.CI === "1" || process.env.CI === "true") return false;
97
+ return Boolean(stdin.isTTY && stdout.isTTY);
98
+ }
99
+
100
+ function editorDist() {
101
+ return path.join(gardenPackageRoot, "editors", "dist");
102
+ }
103
+
104
+ function siteEditors(siteRoot) {
105
+ return path.join(siteRoot, ".garden", "editors");
106
+ }
107
+
108
+ function offeredMarker(siteRoot) {
109
+ return path.join(siteEditors(siteRoot), OFFERED_MARKER);
110
+ }
111
+
112
+ function markOffered(siteRoot) {
113
+ const marker = offeredMarker(siteRoot);
114
+ fs.mkdirSync(path.dirname(marker), { recursive: true });
115
+ if (!fs.existsSync(marker)) fs.writeFileSync(marker, "offered\n");
116
+ }
117
+
118
+ export function copyEditorArtifacts(siteRoot) {
119
+ const from = editorDist();
120
+ const groups = ["vscode", "typora"].filter((name) => fs.existsSync(path.join(from, name)));
121
+ if (!groups.length) return false;
122
+ const to = siteEditors(siteRoot);
123
+ fs.mkdirSync(to, { recursive: true });
124
+ for (const name of groups) {
125
+ const dest = path.join(to, name);
126
+ fs.rmSync(dest, { recursive: true, force: true });
127
+ fs.cpSync(path.join(from, name), dest, { recursive: true });
128
+ }
129
+ return true;
130
+ }
131
+
132
+ function samePackageSite(siteRoot) {
133
+ return path.resolve(siteRoot) === path.resolve(gardenPackageRoot);
134
+ }
135
+
136
+ function firstVsix(directory) {
137
+ if (!fs.existsSync(directory)) return null;
138
+ const names = fs.readdirSync(directory).filter((name) => name.endsWith(".vsix")).sort();
139
+ if (!names.length) return null;
140
+ return path.join(directory, names[names.length - 1]);
141
+ }
142
+
143
+ function locateVsix(siteRoot) {
144
+ return firstVsix(path.join(siteEditors(siteRoot), "vscode")) ?? firstVsix(path.join(editorDist(), "vscode"));
145
+ }
146
+
147
+ function locateTyporaSource(siteRoot) {
148
+ const candidates = [path.join(siteEditors(siteRoot), "typora"), path.join(editorDist(), "typora")];
149
+ for (const directory of candidates) {
150
+ if (["manifest.json", "main.js", "style.css"].every((name) => fs.existsSync(path.join(directory, name)))) {
151
+ return directory;
152
+ }
153
+ }
154
+ return null;
155
+ }
156
+
157
+ function commandPath(name) {
158
+ const entries = (process.env.PATH ?? "").split(path.delimiter).filter(Boolean);
159
+ const suffixes = process.platform === "win32" ? (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";") : [""];
160
+ for (const directory of entries) {
161
+ for (const suffix of suffixes) {
162
+ const candidate = path.join(directory, suffix ? `${name}${suffix}` : name);
163
+ try {
164
+ const stat = fs.statSync(candidate);
165
+ if (!stat.isFile()) continue;
166
+ if (process.platform !== "win32" && (stat.mode & 0o111) === 0) continue;
167
+ return candidate;
168
+ } catch {
169
+ // Try the next PATH entry.
170
+ }
171
+ }
172
+ }
173
+ return null;
174
+ }
175
+
176
+ function editorClis() {
177
+ const found = [];
178
+ for (const name of ["cursor", "code"]) {
179
+ const bin = commandPath(name);
180
+ if (bin) found.push({ name, bin });
181
+ }
182
+ return found;
183
+ }
184
+
185
+ async function confirm(question) {
186
+ const rl = readline.createInterface({ input: stdin, output: stdout });
187
+ try {
188
+ const answer = (await rl.question(question)).trim().toLowerCase();
189
+ return answer === "y" || answer === "yes" || answer === "是";
190
+ } catch {
191
+ return false;
192
+ } finally {
193
+ rl.close();
194
+ }
195
+ }
196
+
197
+ function installVsix(siteRoot, lang) {
198
+ const copy = strings(lang);
199
+ const vsix = locateVsix(siteRoot);
200
+ if (!vsix) {
201
+ write(copy.noVsix);
202
+ return false;
203
+ }
204
+ const clis = editorClis();
205
+ if (!clis.length) {
206
+ write(copy.manual(vsix));
207
+ return true;
208
+ }
209
+ let ok = true;
210
+ for (const cli of clis) {
211
+ write(`${cli.name} --install-extension ${vsix}`);
212
+ const result = spawnSync(cli.bin, ["--install-extension", vsix], { stdio: "inherit" });
213
+ if (result.status === 0) write(copy.installedCli(cli.name, vsix));
214
+ else {
215
+ ok = false;
216
+ write(copy.cliFailed(cli.name, vsix));
217
+ }
218
+ }
219
+ return ok;
220
+ }
221
+
222
+ function fileHas(file, needle) {
223
+ try {
224
+ const stat = fs.statSync(file);
225
+ if (!stat.isFile() || stat.size > 8 * 1024 * 1024) return false;
226
+ return fs.readFileSync(file, "utf8").includes(needle);
227
+ } catch {
228
+ return false;
229
+ }
230
+ }
231
+
232
+ function typoraFrameworkFound(home) {
233
+ if (fs.existsSync(path.join(home, ".typora", "community-plugins"))) return true;
234
+ if (fs.existsSync(path.join(home, "Library", "Application Support", "abnerworks.Typora", "plugins", "loader.js"))) return true;
235
+ const apps = [];
236
+ if (process.platform === "darwin") {
237
+ apps.push(
238
+ "/Applications/Typora.app/Contents/Resources/TypeMark/index.html",
239
+ "/Applications/Typora.app/Contents/Resources/app/index.html",
240
+ path.join(home, "Applications/Typora.app/Contents/Resources/TypeMark/index.html"),
241
+ );
242
+ } else if (process.platform === "win32") {
243
+ for (const base of [process.env.LOCALAPPDATA, process.env.ProgramFiles, process.env["ProgramFiles(x86)"]]) {
244
+ if (!base) continue;
245
+ apps.push(
246
+ path.join(base, "Typora", "resources", "TypeMark", "index.html"),
247
+ path.join(base, "Programs", "Typora", "resources", "TypeMark", "index.html"),
248
+ );
249
+ }
250
+ } else {
251
+ apps.push(
252
+ "/usr/share/typora/resources/TypeMark/index.html",
253
+ "/usr/lib/typora/resources/TypeMark/index.html",
254
+ "/opt/Typora/resources/TypeMark/index.html",
255
+ );
256
+ }
257
+ return apps.some((file) => fileHas(file, "typora-community-plugin"));
258
+ }
259
+
260
+ /** Directories Typora loads. Every platform gets ~/.typora; macOS core also reads Application Support. */
261
+ export function typoraPluginDirs(home, platform = process.platform) {
262
+ const dirs = [path.join(home, ".typora", "community-plugins", "plugins", TYPORA_PLUGIN_ID)];
263
+ if (platform === "darwin") {
264
+ dirs.push(path.join(home, "Library", "Application Support", "abnerworks.Typora", "plugins", "plugins", TYPORA_PLUGIN_ID));
265
+ }
266
+ return dirs;
267
+ }
268
+
269
+ function installTypora(siteRoot, lang) {
270
+ const copy = strings(lang);
271
+ const source = locateTyporaSource(siteRoot);
272
+ if (!source) {
273
+ write(copy.noTypora);
274
+ return false;
275
+ }
276
+ const home = os.homedir();
277
+ // Check before copy: copying the plugin creates the plugin directory the detector also looks at.
278
+ const framework = typoraFrameworkFound(home);
279
+ const destinations = typoraPluginDirs(home);
280
+ for (const destination of destinations) {
281
+ fs.rmSync(destination, { recursive: true, force: true });
282
+ fs.cpSync(source, destination, { recursive: true });
283
+ }
284
+ if (!framework) write(copy.typoraMissingFramework);
285
+ write(copy.typoraCopied(destinations));
286
+ write(copy.typoraEnable);
287
+ write(copy.typoraUpgrade);
288
+ return true;
289
+ }
290
+
291
+ async function installChosen(siteRoot, lang, { vscode, typora }) {
292
+ let ok = true;
293
+ if (vscode) ok = installVsix(siteRoot, lang) && ok;
294
+ if (typora) ok = installTypora(siteRoot, lang) && ok;
295
+ return ok;
296
+ }
297
+
298
+ /** Copies artifacts, then asks once. Later syncs only refresh the files. */
299
+ export async function offerEditorsOnce(siteRoot, lang) {
300
+ if (fs.existsSync(offeredMarker(siteRoot))) {
301
+ copyEditorArtifacts(siteRoot);
302
+ return;
303
+ }
304
+ const copied = copyEditorArtifacts(siteRoot);
305
+ if (!copied) {
306
+ if (!samePackageSite(siteRoot)) write(strings(lang).missing);
307
+ return;
308
+ }
309
+ const copy = strings(lang);
310
+ if (!editorsPromptAllowed()) {
311
+ write(copy.hints);
312
+ markOffered(siteRoot);
313
+ return;
314
+ }
315
+ const vscode = await confirm(copy.askVscode);
316
+ const typora = await confirm(copy.askTypora);
317
+ if (vscode || typora) await installChosen(siteRoot, lang, { vscode, typora });
318
+ else write(copy.declined);
319
+ markOffered(siteRoot);
320
+ }
321
+
322
+ /**
323
+ * `garden editors install`. Flags are explicit consent. With no flags, a TTY
324
+ * asks separately; otherwise this prints the same hint as init/sync and returns.
325
+ */
326
+ export async function editorsInstall(siteRoot, lang, flags) {
327
+ const explicit = flags.vscode || flags.typora;
328
+ const copied = copyEditorArtifacts(siteRoot);
329
+ const copy = strings(lang);
330
+ if (!explicit && !flags.yes && !editorsPromptAllowed()) {
331
+ write(copied ? copy.hints : copy.missing);
332
+ return 0;
333
+ }
334
+ let vscode = explicit ? flags.vscode : true;
335
+ let typora = explicit ? flags.typora : true;
336
+ if (!explicit && !flags.yes) {
337
+ vscode = await confirm(copy.askVscode);
338
+ typora = await confirm(copy.askTypora);
339
+ }
340
+ if (!vscode && !typora) {
341
+ write(copy.declined);
342
+ markOffered(siteRoot);
343
+ return 0;
344
+ }
345
+ if (!copied) {
346
+ write(copy.missing);
347
+ return 1;
348
+ }
349
+ const ok = await installChosen(siteRoot, lang, { vscode, typora });
350
+ markOffered(siteRoot);
351
+ return ok ? 0 : 1;
352
+ }