@valaxyjs/devtools 1.0.0-rc.11 → 1.0.0-rc.12
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 +138 -12
- package/dist/client/assets/FeedbackEmptyState-Dj1YkJE0.js +1 -0
- package/dist/client/assets/LayoutCard-qUVYVRud.js +1 -0
- package/dist/client/assets/PopperContent-CgXMlFkV.js +3 -0
- package/dist/client/assets/VDCheckbox-CH2V3bFJ.js +1 -0
- package/dist/client/assets/VDNumberField-DVmMsYPC.js +1 -0
- package/dist/client/assets/VDPostListItem-D3Rn_PcJ.js +1 -0
- package/dist/client/assets/VDPostPanel-BWZUkoQC.js +1 -0
- package/dist/client/assets/VDPostPanel-CbCth8UW.css +1 -0
- package/dist/client/assets/VDSelect-4SBTowKT.js +1 -0
- package/dist/client/assets/VDToggleGroup-BOVPTJ4m.js +1 -0
- package/dist/client/assets/addons-CF1AfuFX.js +1 -0
- package/dist/client/assets/archives-CDa7i8eC.js +1 -0
- package/dist/client/assets/batch-edit-DIvZaav7.js +1 -0
- package/dist/client/assets/batch-edit-UNPFWmV7.css +1 -0
- package/dist/client/assets/browser-agent-rpc-BXhoSh1z-BPEkUHEg.js +1 -0
- package/dist/client/assets/categories-Bk3lMeb1.js +1 -0
- package/dist/client/assets/collections-BHxAwkoL.js +1 -0
- package/dist/client/assets/colors-CdKJdJxa.js +1 -0
- package/dist/client/assets/config-B09dyTTS.js +1 -0
- package/dist/client/assets/debug-CMQbsCep.js +1 -0
- package/dist/client/assets/debug-DcFlBZjk.css +1 -0
- package/dist/client/assets/index-Cyol-EzD.css +1 -0
- package/dist/client/assets/index-DUZ9khG8.js +4 -0
- package/dist/client/assets/nanoid-Cya-tyvy.js +1 -0
- package/dist/client/assets/pages-BWRkr8em.js +1 -0
- package/dist/client/assets/posts-mlMGwcAv.js +1 -0
- package/dist/client/assets/rpc-D36U2nIU.js +4 -0
- package/dist/client/assets/runtime-core.esm-bundler-B8D2lM98.js +3 -0
- package/dist/client/assets/runtime-dom.esm-bundler-Btnku4nR.js +2 -0
- package/dist/client/assets/settings-BZuYgjIU.js +1 -0
- package/dist/client/assets/splitpanes.esm-CrBmgK88.js +1 -0
- package/dist/client/assets/tags-DUuGVO-R.js +1 -0
- package/dist/client/assets/virtual_intlify-i18n-0-CRury7qB.js +1 -0
- package/dist/client/assets/virtual_intlify-i18n-1-FM-gmUYx.js +1 -0
- package/{LICENSE → dist/client/icons/LICENSE} +1 -1
- package/dist/client/icons/README.md +2 -0
- package/dist/client/icons/archive.svg +1 -0
- package/dist/client/icons/article.svg +1 -0
- package/dist/client/icons/books.svg +1 -0
- package/dist/client/icons/bug.svg +1 -0
- package/dist/client/icons/folders.svg +1 -0
- package/dist/client/icons/gear-six.svg +1 -0
- package/dist/client/icons/hash.svg +1 -0
- package/dist/client/icons/pencil-simple.svg +1 -0
- package/dist/client/icons/puzzle-piece.svg +1 -0
- package/dist/client/icons/sliders-horizontal.svg +1 -0
- package/dist/client/icons/squares-four.svg +1 -0
- package/dist/client/index.html +9 -5
- package/dist/client-api.d.mts +18 -0
- package/dist/client-api.d.ts +18 -0
- package/dist/client-api.mjs +52 -0
- package/dist/index.d.mts +10 -5
- package/dist/index.d.ts +10 -5
- package/dist/index.mjs +114 -626
- package/dist/node/definition.d.mts +9 -0
- package/dist/node/definition.d.ts +9 -0
- package/dist/node/definition.mjs +826 -0
- package/dist/node/mcp.d.mts +26 -0
- package/dist/node/mcp.d.ts +26 -0
- package/dist/node/mcp.mjs +250 -0
- package/dist/page.d.mts +12 -0
- package/dist/page.d.ts +12 -0
- package/dist/page.mjs +29 -0
- package/dist/plugin.d.mts +48 -0
- package/dist/plugin.d.ts +48 -0
- package/dist/plugin.mjs +5 -0
- package/dist/shared/devtools.B-vZo-vB.mjs +46 -0
- package/dist/shared/devtools.BOLo8y6t.d.mts +58 -0
- package/dist/shared/devtools.BzWtXMed.mjs +3 -0
- package/dist/shared/devtools.CBhjeyeH.mjs +16 -0
- package/dist/shared/devtools.CNAj6Cjx.d.ts +58 -0
- package/dist/shared/devtools.DV0tVpWA.d.mts +95 -0
- package/dist/shared/devtools.O-VZ9RtQ.d.mts +30 -0
- package/dist/shared/devtools.O-VZ9RtQ.d.ts +30 -0
- package/dist/shared/devtools.lzRAl5dD.d.ts +95 -0
- package/dist/shared/rpc.d.mts +171 -0
- package/dist/shared/rpc.d.ts +171 -0
- package/dist/shared/rpc.mjs +1 -0
- package/package.json +52 -26
- package/rpc.d.ts +1 -100
- package/dist/client/assets/VDButton-BxA3M5c6.js +0 -1
- package/dist/client/assets/VDCheckbox-BsLMqi9S.js +0 -1
- package/dist/client/assets/VDInput-B27GE15-.js +0 -1
- package/dist/client/assets/VDInput-BtxYqBt3.css +0 -1
- package/dist/client/assets/VDNumberField-YjWV-ued.js +0 -1
- package/dist/client/assets/VDPostListItem-DF0Kvz0k.js +0 -1
- package/dist/client/assets/VDPostPanel-Bkkd-Lkf.css +0 -1
- package/dist/client/assets/VDPostPanel-Dci0SDJM.js +0 -1
- package/dist/client/assets/VDSelect-C-luq5qS.js +0 -1
- package/dist/client/assets/VDToggleGroup-epojOkcK.js +0 -1
- package/dist/client/assets/archives-DSGEfYQX.js +0 -1
- package/dist/client/assets/batch-edit-BYL9g3v4.css +0 -1
- package/dist/client/assets/batch-edit-DUNlYX2Q.js +0 -1
- package/dist/client/assets/categories-O8ONgJl6.js +0 -1
- package/dist/client/assets/collections-Rf9R5xIW.js +0 -1
- package/dist/client/assets/config-B6eJg8re.js +0 -1
- package/dist/client/assets/index-BjYrNlmK.js +0 -6
- package/dist/client/assets/index-wVxzDvm5.css +0 -1
- package/dist/client/assets/pages-CHon8Zex.js +0 -1
- package/dist/client/assets/posts-B80Fz55d.js +0 -1
- package/dist/client/assets/settings-B9Vkun7j.js +0 -1
- package/dist/client/assets/splitpanes.esm-B-DN0qHF.js +0 -1
- package/dist/client/assets/tags-B_Je2XwK.js +0 -1
- package/dist/client/assets/virtual_intlify-i18n-0-C_fbdMlw.js +0 -1
- package/dist/client/assets/virtual_intlify-i18n-1-CjutLn3A.js +0 -1
- package/dist/client/assets/vue.runtime.esm-bundler-DqDZGG6R.js +0 -4
|
@@ -0,0 +1,826 @@
|
|
|
1
|
+
import { normalizeRepositoryUrl } from '@valaxyjs/utils';
|
|
2
|
+
import { defineDevframe, defineRpcFunction } from 'devframe';
|
|
3
|
+
import * as v from 'valibot';
|
|
4
|
+
import { a as resolveInsideRoot, r as resolvePageFile, p as pkg } from '../shared/devtools.B-vZo-vB.mjs';
|
|
5
|
+
import { dirname, resolve } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { R as RESOURCES_STATE, c as resolveAddonBase, d as DEVTOOLS_ID, r as resolveDevtoolsBase, b as resolveDevtoolsLogo } from '../shared/devtools.CBhjeyeH.mjs';
|
|
8
|
+
import fs from 'fs-extra';
|
|
9
|
+
import pathe from 'pathe';
|
|
10
|
+
import { generateCode, parseModule } from 'magicast';
|
|
11
|
+
import process from 'node:process';
|
|
12
|
+
import dayjs from 'dayjs';
|
|
13
|
+
import { launchEditor } from 'devframe/utils/launch-editor';
|
|
14
|
+
import fg from 'fast-glob';
|
|
15
|
+
import matter from 'gray-matter';
|
|
16
|
+
import { dump, JSON_SCHEMA, load } from 'js-yaml';
|
|
17
|
+
import { realpath, readFile, writeFile } from 'node:fs/promises';
|
|
18
|
+
import { createHash } from 'node:crypto';
|
|
19
|
+
|
|
20
|
+
const packageRoot = dirname(fileURLToPath(import.meta.resolve("@valaxyjs/devtools/package.json")));
|
|
21
|
+
const DIR_DIST = resolve(packageRoot, "dist");
|
|
22
|
+
const DIR_CLIENT = resolve(DIR_DIST, "client");
|
|
23
|
+
|
|
24
|
+
const DANGEROUS_FIELD_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
25
|
+
function validateFieldPath(fieldPath) {
|
|
26
|
+
const parts = fieldPath.split(".");
|
|
27
|
+
return parts.every((part) => part.length > 0 && !DANGEROUS_FIELD_KEYS.has(part));
|
|
28
|
+
}
|
|
29
|
+
function assertInsideRoot(root, targetFile) {
|
|
30
|
+
const relative = pathe.relative(root, targetFile);
|
|
31
|
+
if (relative.startsWith("..") || pathe.isAbsolute(relative))
|
|
32
|
+
throw new Error(`Config path is outside user root: ${targetFile}`);
|
|
33
|
+
}
|
|
34
|
+
function setNestedValue(obj, path, value) {
|
|
35
|
+
const parts = path.split(".");
|
|
36
|
+
let current = obj;
|
|
37
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
38
|
+
const part = parts[i];
|
|
39
|
+
if (current[part] == null || typeof current[part] !== "object") {
|
|
40
|
+
current[part] = {};
|
|
41
|
+
}
|
|
42
|
+
current = current[part];
|
|
43
|
+
}
|
|
44
|
+
current[parts.at(-1)] = value;
|
|
45
|
+
}
|
|
46
|
+
async function parseConfigFile(filePath) {
|
|
47
|
+
const content = await fs.readFile(filePath, "utf-8");
|
|
48
|
+
const mod = parseModule(content);
|
|
49
|
+
return mod;
|
|
50
|
+
}
|
|
51
|
+
function serializeProxy(value) {
|
|
52
|
+
try {
|
|
53
|
+
if (value == null)
|
|
54
|
+
return value;
|
|
55
|
+
if (typeof value !== "object")
|
|
56
|
+
return value;
|
|
57
|
+
if (value.$type === "function-call") {
|
|
58
|
+
const callee = value.$callee ?? "";
|
|
59
|
+
const args = value.$args ?? [];
|
|
60
|
+
const serializedArgs = args.map(
|
|
61
|
+
(a) => typeof a === "string" ? `'${a}'` : JSON.stringify(a)
|
|
62
|
+
).join(", ");
|
|
63
|
+
return `${callee}(${serializedArgs})`;
|
|
64
|
+
}
|
|
65
|
+
if (value.$type === "identifier") {
|
|
66
|
+
return String(value.$id ?? value);
|
|
67
|
+
}
|
|
68
|
+
if (value.$type && value.$type !== "object") {
|
|
69
|
+
return `<${value.$type}>`;
|
|
70
|
+
}
|
|
71
|
+
if (Array.isArray(value)) {
|
|
72
|
+
return value.map((item) => {
|
|
73
|
+
try {
|
|
74
|
+
return serializeProxy(item);
|
|
75
|
+
} catch {
|
|
76
|
+
return "<unsupported>";
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
const result = {};
|
|
81
|
+
for (const key of Object.keys(value)) {
|
|
82
|
+
if (key.startsWith("$"))
|
|
83
|
+
continue;
|
|
84
|
+
try {
|
|
85
|
+
result[key] = serializeProxy(value[key]);
|
|
86
|
+
} catch {
|
|
87
|
+
result[key] = "<unsupported expression>";
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return result;
|
|
91
|
+
} catch {
|
|
92
|
+
return "<unsupported expression>";
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
async function readConfigs(userRoot) {
|
|
96
|
+
const siteConfigPath = pathe.resolve(userRoot, "site.config.ts");
|
|
97
|
+
const valaxyConfigPath = pathe.resolve(userRoot, "valaxy.config.ts");
|
|
98
|
+
let siteConfig = {};
|
|
99
|
+
let valaxyConfig = {};
|
|
100
|
+
let themeConfig = {};
|
|
101
|
+
const siteConfigExists = await fs.pathExists(siteConfigPath);
|
|
102
|
+
const valaxyConfigExists = await fs.pathExists(valaxyConfigPath);
|
|
103
|
+
if (siteConfigExists) {
|
|
104
|
+
try {
|
|
105
|
+
const mod = await parseConfigFile(siteConfigPath);
|
|
106
|
+
const defaultExport = mod.exports.default;
|
|
107
|
+
if (defaultExport && typeof defaultExport === "object") {
|
|
108
|
+
siteConfig = serializeProxy(defaultExport.$args?.[0] ?? defaultExport);
|
|
109
|
+
}
|
|
110
|
+
} catch (e) {
|
|
111
|
+
console.error("[devtools] Failed to parse site.config.ts:", e);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (valaxyConfigExists) {
|
|
115
|
+
try {
|
|
116
|
+
const mod = await parseConfigFile(valaxyConfigPath);
|
|
117
|
+
const defaultExport = mod.exports.default;
|
|
118
|
+
if (defaultExport && typeof defaultExport === "object") {
|
|
119
|
+
const configObj = defaultExport.$args?.[0] ?? defaultExport;
|
|
120
|
+
const raw = serializeProxy(configObj);
|
|
121
|
+
if (raw.themeConfig) {
|
|
122
|
+
themeConfig = raw.themeConfig;
|
|
123
|
+
delete raw.themeConfig;
|
|
124
|
+
}
|
|
125
|
+
if (raw.siteConfig) {
|
|
126
|
+
delete raw.siteConfig;
|
|
127
|
+
}
|
|
128
|
+
valaxyConfig = raw;
|
|
129
|
+
}
|
|
130
|
+
} catch (e) {
|
|
131
|
+
console.error("[devtools] Failed to parse valaxy.config.ts:", e);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
siteConfig,
|
|
136
|
+
valaxyConfig,
|
|
137
|
+
themeConfig,
|
|
138
|
+
siteConfigExists,
|
|
139
|
+
valaxyConfigExists,
|
|
140
|
+
siteConfigPath,
|
|
141
|
+
valaxyConfigPath
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
const SITE_CONFIG_TEMPLATE = `import { defineSiteConfig } from 'valaxy'
|
|
145
|
+
|
|
146
|
+
export default defineSiteConfig({
|
|
147
|
+
})
|
|
148
|
+
`;
|
|
149
|
+
const VALAXY_CONFIG_TEMPLATE = `import { defineValaxyConfig } from 'valaxy'
|
|
150
|
+
|
|
151
|
+
export default defineValaxyConfig({
|
|
152
|
+
})
|
|
153
|
+
`;
|
|
154
|
+
async function writeConfigField(userRoot, configType, fieldPath, value) {
|
|
155
|
+
if (!validateFieldPath(fieldPath)) {
|
|
156
|
+
throw new Error(`Invalid field path: ${fieldPath}`);
|
|
157
|
+
}
|
|
158
|
+
const targetFile = configType === "site" ? pathe.resolve(userRoot, "site.config.ts") : pathe.resolve(userRoot, "valaxy.config.ts");
|
|
159
|
+
const template = configType === "site" ? SITE_CONFIG_TEMPLATE : VALAXY_CONFIG_TEMPLATE;
|
|
160
|
+
assertInsideRoot(userRoot, targetFile);
|
|
161
|
+
await resolveInsideRoot(userRoot, targetFile);
|
|
162
|
+
if (!await fs.pathExists(targetFile)) {
|
|
163
|
+
await fs.writeFile(targetFile, template, "utf-8");
|
|
164
|
+
}
|
|
165
|
+
const mod = await parseConfigFile(targetFile);
|
|
166
|
+
const defaultExport = mod.exports.default;
|
|
167
|
+
if (!defaultExport) {
|
|
168
|
+
throw new Error(`No default export found in ${targetFile}`);
|
|
169
|
+
}
|
|
170
|
+
const configObj = defaultExport.$args?.[0] ?? defaultExport;
|
|
171
|
+
if (configType === "theme") {
|
|
172
|
+
if (!configObj.themeConfig || typeof configObj.themeConfig !== "object") {
|
|
173
|
+
configObj.themeConfig = {};
|
|
174
|
+
}
|
|
175
|
+
setNestedValue(configObj.themeConfig, fieldPath, value);
|
|
176
|
+
} else if (configType === "valaxy") {
|
|
177
|
+
setNestedValue(configObj, fieldPath, value);
|
|
178
|
+
} else {
|
|
179
|
+
setNestedValue(configObj, fieldPath, value);
|
|
180
|
+
}
|
|
181
|
+
const { code } = generateCode(mod);
|
|
182
|
+
await fs.writeFile(targetFile, code, "utf-8");
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const reservedFields = /* @__PURE__ */ new Set(["title", "date", "updated", "draft", "hide", "type", "tags", "categories", "excerpt", "excerpt_type", "cover", "toc", "password", "password_hint", "encryptedContent", "partiallyEncryptedContents", "layout", "path", "permalink", "abbrlink", "url", "author", "top", "sticky", "comment"]);
|
|
186
|
+
const identifier = /^[a-z][a-z0-9-]*$/;
|
|
187
|
+
async function resolveDevtoolsPlugins(options) {
|
|
188
|
+
const plugins = [];
|
|
189
|
+
const ids = /* @__PURE__ */ new Set();
|
|
190
|
+
const fields = /* @__PURE__ */ new Set();
|
|
191
|
+
for (const load of options.plugins || []) {
|
|
192
|
+
const loaded = typeof load === "function" ? await load() : load;
|
|
193
|
+
const plugin = "default" in loaded ? loaded.default : loaded;
|
|
194
|
+
if (plugin.apiVersion !== 1 || !identifier.test(plugin.id) || !plugin.name || ids.has(plugin.id))
|
|
195
|
+
throw new Error(`Invalid or duplicate Valaxy DevTools plugin: ${plugin.id}`);
|
|
196
|
+
ids.add(plugin.id);
|
|
197
|
+
const panelIds = /* @__PURE__ */ new Set();
|
|
198
|
+
for (const panel of plugin.panels || []) {
|
|
199
|
+
if (!identifier.test(panel.id) || panelIds.has(panel.id) || !panel.title)
|
|
200
|
+
throw new Error(`Invalid or duplicate panel: ${plugin.id}:${panel.id}`);
|
|
201
|
+
panelIds.add(panel.id);
|
|
202
|
+
if (!pathe.isAbsolute(panel.clientAssets) || !await fs.pathExists(pathe.join(panel.clientAssets, "index.html")))
|
|
203
|
+
throw new Error(`Panel ${plugin.id}:${panel.id} requires a built clientAssets directory with index.html`);
|
|
204
|
+
}
|
|
205
|
+
for (const field of plugin.editor?.fields || []) {
|
|
206
|
+
if (!/^[a-z][\w-]*$/i.test(field.key) || DANGEROUS_FIELD_KEYS.has(field.key) || reservedFields.has(field.key) || fields.has(field.key) || !field.label)
|
|
207
|
+
throw new Error(`Invalid or duplicate editor field: ${field.key}`);
|
|
208
|
+
fields.add(field.key);
|
|
209
|
+
if (!["text", "textarea", "boolean", "number", "select"].includes(field.type))
|
|
210
|
+
throw new Error(`Unsupported editor field type: ${field.key}`);
|
|
211
|
+
if (field.type === "select" && (!field.options.length || new Set(field.options.map((o) => o.value)).size !== field.options.length || field.options.some((o) => typeof o.value !== "string" || !o.label)))
|
|
212
|
+
throw new Error(`Invalid select options: ${field.key}`);
|
|
213
|
+
if (field.type === "number" && (field.step !== void 0 && (!Number.isFinite(field.step) || field.step <= 0) || field.min !== void 0 && !Number.isFinite(field.min) || field.max !== void 0 && !Number.isFinite(field.max) || field.min !== void 0 && field.max !== void 0 && field.min > field.max))
|
|
214
|
+
throw new Error(`Invalid number limits: ${field.key}`);
|
|
215
|
+
if ((field.type === "text" || field.type === "textarea") && field.maxLength !== void 0 && (!Number.isInteger(field.maxLength) || field.maxLength < 0))
|
|
216
|
+
throw new Error(`Invalid text limit: ${field.key}`);
|
|
217
|
+
}
|
|
218
|
+
const actions = /* @__PURE__ */ new Set();
|
|
219
|
+
for (const action of plugin.editor?.actions || []) {
|
|
220
|
+
if (!identifier.test(action.id) || actions.has(action.id) || !action.label || typeof action.run !== "function")
|
|
221
|
+
throw new Error(`Invalid or duplicate editor action: ${plugin.id}:${action.id}`);
|
|
222
|
+
actions.add(action.id);
|
|
223
|
+
}
|
|
224
|
+
plugins.push(plugin);
|
|
225
|
+
}
|
|
226
|
+
return plugins;
|
|
227
|
+
}
|
|
228
|
+
function validateEditorFields(plugins, frontmatter) {
|
|
229
|
+
for (const plugin of plugins) {
|
|
230
|
+
for (const field of plugin.editor?.fields || []) {
|
|
231
|
+
if (!Object.hasOwn(frontmatter, field.key))
|
|
232
|
+
continue;
|
|
233
|
+
const value = frontmatter[field.key];
|
|
234
|
+
let valid;
|
|
235
|
+
switch (field.type) {
|
|
236
|
+
case "boolean":
|
|
237
|
+
valid = typeof value === "boolean";
|
|
238
|
+
break;
|
|
239
|
+
case "number":
|
|
240
|
+
valid = typeof value === "number" && Number.isFinite(value) && (field.min === void 0 || value >= field.min) && (field.max === void 0 || value <= field.max);
|
|
241
|
+
break;
|
|
242
|
+
case "select":
|
|
243
|
+
valid = field.options.some((option) => option.value === value);
|
|
244
|
+
break;
|
|
245
|
+
default:
|
|
246
|
+
valid = typeof value === "string" && (field.maxLength === void 0 || value.length <= field.maxLength);
|
|
247
|
+
}
|
|
248
|
+
if (!valid)
|
|
249
|
+
throw new Error(`${plugin.name}: invalid value for ${field.label} (${field.key})`);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
function createManifest(plugins, base) {
|
|
254
|
+
return {
|
|
255
|
+
apiVersion: 1,
|
|
256
|
+
plugins: plugins.map((plugin) => ({
|
|
257
|
+
id: plugin.id,
|
|
258
|
+
name: plugin.name,
|
|
259
|
+
panels: (plugin.panels || []).map((panel) => ({ id: `valaxy:addon:${plugin.id}:${panel.id}`, title: panel.title, icon: panel.icon || "ph:puzzle-piece", url: `${resolveAddonBase(base)}${plugin.id}/${panel.id}/` })),
|
|
260
|
+
fields: plugin.editor?.fields || [],
|
|
261
|
+
actions: (plugin.editor?.actions || []).map((action) => ({ id: `${plugin.id}:${action.id}`, label: action.label }))
|
|
262
|
+
}))
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
async function setupExtensions(ctx, plugins, manifest, data, onDispose) {
|
|
266
|
+
for (const [index, plugin] of plugins.entries()) {
|
|
267
|
+
for (const [panelIndex, panel] of (plugin.panels || []).entries()) {
|
|
268
|
+
const view = manifest.plugins[index].panels[panelIndex];
|
|
269
|
+
await ctx.host.mountConnectionMeta?.(view.url);
|
|
270
|
+
await ctx.host.mountStatic(view.url, panel.clientAssets);
|
|
271
|
+
}
|
|
272
|
+
await plugin.setup?.({ data, rpc: ctx.scope(`valaxy:addon:${plugin.id}`).rpc, onDispose });
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
function createDataApi(ctx, functions, onDispose) {
|
|
276
|
+
return {
|
|
277
|
+
...functions,
|
|
278
|
+
async onChanged(listener) {
|
|
279
|
+
const state = await ctx.rpc.sharedState.get(RESOURCES_STATE);
|
|
280
|
+
const stop = state.on("updated", listener);
|
|
281
|
+
onDispose(stop);
|
|
282
|
+
return stop;
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const matterOptions = {
|
|
288
|
+
engines: {
|
|
289
|
+
yaml: {
|
|
290
|
+
parse: (source) => load(source, { schema: JSON_SCHEMA }),
|
|
291
|
+
stringify: (data) => dump(data, { schema: JSON_SCHEMA })
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
async function migration(path, frontmatter, validateFrontmatter = () => {
|
|
296
|
+
}) {
|
|
297
|
+
if (fs.existsSync(path)) {
|
|
298
|
+
const rawMd = await fs.readFile(path, "utf-8");
|
|
299
|
+
const matterFile = matter(rawMd, matterOptions);
|
|
300
|
+
let mod = false;
|
|
301
|
+
for (const key in frontmatter) {
|
|
302
|
+
if (key in matterFile.data) {
|
|
303
|
+
matterFile.data[frontmatter[key]] = matterFile.data[key];
|
|
304
|
+
delete matterFile.data[key];
|
|
305
|
+
mod = true;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
if (mod) {
|
|
309
|
+
validateFrontmatter(matterFile.data);
|
|
310
|
+
const newMd = matter.stringify(matterFile.content, matterFile.data);
|
|
311
|
+
await fs.writeFile(path, newMd);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const pendingWrites = /* @__PURE__ */ new Map();
|
|
317
|
+
async function updatePageFile(file, update) {
|
|
318
|
+
const canonical = await realpath(file);
|
|
319
|
+
const previous = pendingWrites.get(canonical) || Promise.resolve();
|
|
320
|
+
const operation = previous.catch(() => {
|
|
321
|
+
}).then(async () => {
|
|
322
|
+
const { content, result } = update(await readFile(canonical, "utf8"));
|
|
323
|
+
await writeFile(canonical, content, "utf8");
|
|
324
|
+
return result;
|
|
325
|
+
});
|
|
326
|
+
pendingWrites.set(canonical, operation);
|
|
327
|
+
try {
|
|
328
|
+
return await operation;
|
|
329
|
+
} finally {
|
|
330
|
+
if (pendingWrites.get(canonical) === operation)
|
|
331
|
+
pendingWrites.delete(canonical);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function snapshot(content) {
|
|
336
|
+
return { content, revision: createHash("sha256").update(content).digest("hex") };
|
|
337
|
+
}
|
|
338
|
+
async function readPostContent(userRoot, filePath) {
|
|
339
|
+
const file = await resolvePageFile(userRoot, filePath);
|
|
340
|
+
return snapshot(matter(await readFile(file, "utf8")).content);
|
|
341
|
+
}
|
|
342
|
+
async function writePostContent(userRoot, filePath, content, revision) {
|
|
343
|
+
const file = await resolvePageFile(userRoot, filePath);
|
|
344
|
+
return updatePageFile(file, (raw) => {
|
|
345
|
+
const previous = matter(raw).content;
|
|
346
|
+
if (snapshot(previous).revision !== revision)
|
|
347
|
+
throw new Error("The article body changed on disk. Reload it before saving.");
|
|
348
|
+
return { content: raw.slice(0, raw.length - previous.length) + content, result: snapshot(content) };
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function ensurePrefix(prefix, str) {
|
|
353
|
+
if (!str.startsWith(prefix))
|
|
354
|
+
return prefix + str;
|
|
355
|
+
return str;
|
|
356
|
+
}
|
|
357
|
+
function extractStringField(content, field) {
|
|
358
|
+
const regex = new RegExp(`\\b${field}\\s*:\\s*['"\`]([^'"\`]*)['"\`]`);
|
|
359
|
+
const match = content.match(regex);
|
|
360
|
+
return match?.[1] || "";
|
|
361
|
+
}
|
|
362
|
+
function extractBooleanField(content, field, defaultValue) {
|
|
363
|
+
const regex = new RegExp(`\\b${field}\\s*:\\s*(true|false)`);
|
|
364
|
+
const match = content.match(regex);
|
|
365
|
+
if (!match)
|
|
366
|
+
return defaultValue;
|
|
367
|
+
return match[1] === "true";
|
|
368
|
+
}
|
|
369
|
+
function extractConfigItems(content) {
|
|
370
|
+
const items = [];
|
|
371
|
+
const itemsMatch = content.match(/items\s*:\s*\[([^\]]*)\]/);
|
|
372
|
+
if (!itemsMatch)
|
|
373
|
+
return items;
|
|
374
|
+
const itemsContent = itemsMatch[1];
|
|
375
|
+
const objectRegex = /\{([^}]*)\}/g;
|
|
376
|
+
let objMatch;
|
|
377
|
+
while ((objMatch = objectRegex.exec(itemsContent)) !== null) {
|
|
378
|
+
const block = objMatch[1];
|
|
379
|
+
const keyMatch = block.match(/key\s*:\s*['"`]([^'"`]*)['"`]/);
|
|
380
|
+
const titleMatch = block.match(/title\s*:\s*['"`]([^'"`]*)['"`]/);
|
|
381
|
+
const linkMatch = block.match(/link\s*:\s*['"`]([^'"`]*)['"`]/);
|
|
382
|
+
items.push({
|
|
383
|
+
key: keyMatch?.[1],
|
|
384
|
+
title: titleMatch?.[1],
|
|
385
|
+
link: linkMatch?.[1]
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
return items;
|
|
389
|
+
}
|
|
390
|
+
function getFunctions(devtoolsOptions, validateFrontmatter = () => {
|
|
391
|
+
}) {
|
|
392
|
+
const userRoot = pathe.resolve(devtoolsOptions.userRoot || process.cwd());
|
|
393
|
+
function getRoutePath(filePath) {
|
|
394
|
+
const relativePath = pathe.relative(pathe.resolve(userRoot, "pages"), filePath).slice(0, -".md".length);
|
|
395
|
+
return ensurePrefix("/", relativePath);
|
|
396
|
+
}
|
|
397
|
+
return {
|
|
398
|
+
getPostContent: (filePath) => readPostContent(userRoot, filePath),
|
|
399
|
+
updatePostContent: (req) => writePostContent(userRoot, req.filePath, req.content, req.revision),
|
|
400
|
+
async openInEditor({ file, line = 0, column = 0 }) {
|
|
401
|
+
const resolved = await resolveInsideRoot(userRoot, file);
|
|
402
|
+
launchEditor(`${resolved}:${line}:${column}`, process.env.EDITOR);
|
|
403
|
+
},
|
|
404
|
+
async getOptions() {
|
|
405
|
+
return {
|
|
406
|
+
userRoot,
|
|
407
|
+
siteUrl: devtoolsOptions.siteUrl?.()
|
|
408
|
+
};
|
|
409
|
+
},
|
|
410
|
+
async getPostList() {
|
|
411
|
+
const files = await fg(`${userRoot}/pages/posts/**/*.md`);
|
|
412
|
+
const posts = [];
|
|
413
|
+
for await (const file of files) {
|
|
414
|
+
const md = await fs.readFile(file, "utf-8");
|
|
415
|
+
const { data } = matter(md);
|
|
416
|
+
posts.push({
|
|
417
|
+
routePath: getRoutePath(file),
|
|
418
|
+
frontmatter: data,
|
|
419
|
+
filePath: file
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
return {
|
|
423
|
+
// sort by updated
|
|
424
|
+
posts: posts.sort((a, b) => {
|
|
425
|
+
const bDateValue = dayjs(b.frontmatter.updated || b.frontmatter.date).valueOf();
|
|
426
|
+
const aDateValue = dayjs(a.frontmatter.updated || a.frontmatter.date).valueOf();
|
|
427
|
+
return bDateValue - aDateValue;
|
|
428
|
+
}),
|
|
429
|
+
root: userRoot
|
|
430
|
+
};
|
|
431
|
+
},
|
|
432
|
+
async getPageData(pagePath) {
|
|
433
|
+
const relativePath = pagePath.startsWith("/pages/") ? pagePath.slice(1) : pagePath;
|
|
434
|
+
const file = await resolvePageFile(userRoot, relativePath);
|
|
435
|
+
const { data } = matter(await fs.readFile(file, "utf-8"));
|
|
436
|
+
return {
|
|
437
|
+
routePath: getRoutePath(file),
|
|
438
|
+
filePath: file,
|
|
439
|
+
frontmatter: data
|
|
440
|
+
};
|
|
441
|
+
},
|
|
442
|
+
async updateFrontmatter(req) {
|
|
443
|
+
const { filePath, frontmatter: newFm } = req;
|
|
444
|
+
const resolved = await resolvePageFile(userRoot, filePath);
|
|
445
|
+
for (const key of Object.keys(newFm)) {
|
|
446
|
+
if (DANGEROUS_FIELD_KEYS.has(key))
|
|
447
|
+
throw new Error("Invalid frontmatter field");
|
|
448
|
+
}
|
|
449
|
+
validateFrontmatter(newFm);
|
|
450
|
+
if (!fs.existsSync(resolved))
|
|
451
|
+
throw new Error(`File not found: ${resolved}`);
|
|
452
|
+
return updatePageFile(resolved, (rawMd) => {
|
|
453
|
+
const matterFile = matter(rawMd);
|
|
454
|
+
return { content: matter.stringify(matterFile.content, newFm), result: { success: true } };
|
|
455
|
+
});
|
|
456
|
+
},
|
|
457
|
+
async getCollectionList() {
|
|
458
|
+
const collectionsRoot = pathe.resolve(userRoot, "pages", "collections");
|
|
459
|
+
if (!await fs.pathExists(collectionsRoot))
|
|
460
|
+
return [];
|
|
461
|
+
const entries = await fs.readdir(collectionsRoot, { withFileTypes: true });
|
|
462
|
+
const dirs = entries.filter((f) => f.isDirectory()).map((f) => f.name);
|
|
463
|
+
const result = [];
|
|
464
|
+
for (const dir of dirs) {
|
|
465
|
+
const indexPath = pathe.join(collectionsRoot, dir, "index.ts");
|
|
466
|
+
if (!await fs.pathExists(indexPath))
|
|
467
|
+
continue;
|
|
468
|
+
const indexContent = await fs.readFile(indexPath, "utf-8");
|
|
469
|
+
const title = extractStringField(indexContent, "title");
|
|
470
|
+
const cover = extractStringField(indexContent, "cover");
|
|
471
|
+
const description = extractStringField(indexContent, "description");
|
|
472
|
+
const collapse = extractBooleanField(indexContent, "collapse", true);
|
|
473
|
+
const mdFiles = await fg(`${collectionsRoot}/${dir}/*.md`);
|
|
474
|
+
const items = [];
|
|
475
|
+
for (const file of mdFiles) {
|
|
476
|
+
const basename = pathe.basename(file, ".md");
|
|
477
|
+
if (basename === "index")
|
|
478
|
+
continue;
|
|
479
|
+
const md = await fs.readFile(file, "utf-8");
|
|
480
|
+
const { data } = matter(md);
|
|
481
|
+
items.push({
|
|
482
|
+
title: data.title || basename,
|
|
483
|
+
key: basename,
|
|
484
|
+
filePath: file,
|
|
485
|
+
frontmatter: data
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
const configItems = extractConfigItems(indexContent);
|
|
489
|
+
if (configItems.length > 0) {
|
|
490
|
+
for (const ci of configItems) {
|
|
491
|
+
if (ci.link && !items.some((i) => i.key === ci.key)) {
|
|
492
|
+
items.push({
|
|
493
|
+
title: ci.title || ci.link,
|
|
494
|
+
key: ci.key || "",
|
|
495
|
+
link: ci.link,
|
|
496
|
+
filePath: "",
|
|
497
|
+
frontmatter: {}
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
const orderMap = /* @__PURE__ */ new Map();
|
|
502
|
+
configItems.forEach((ci, i) => {
|
|
503
|
+
if (ci.key)
|
|
504
|
+
orderMap.set(`key:${ci.key}`, i);
|
|
505
|
+
else if (ci.link)
|
|
506
|
+
orderMap.set(`link:${ci.link}`, i);
|
|
507
|
+
});
|
|
508
|
+
items.sort((a, b) => {
|
|
509
|
+
const aIdx = (a.key ? orderMap.get(`key:${a.key}`) : orderMap.get(`link:${a.link}`)) ?? Infinity;
|
|
510
|
+
const bIdx = (b.key ? orderMap.get(`key:${b.key}`) : orderMap.get(`link:${b.link}`)) ?? Infinity;
|
|
511
|
+
if (aIdx === bIdx)
|
|
512
|
+
return 0;
|
|
513
|
+
return aIdx - bIdx;
|
|
514
|
+
});
|
|
515
|
+
} else {
|
|
516
|
+
items.sort((a, b) => {
|
|
517
|
+
const aVal = dayjs(a.frontmatter.date).valueOf();
|
|
518
|
+
const bVal = dayjs(b.frontmatter.date).valueOf();
|
|
519
|
+
const aDate = Number.isNaN(aVal) ? 0 : aVal;
|
|
520
|
+
const bDate = Number.isNaN(bVal) ? 0 : bVal;
|
|
521
|
+
return aDate - bDate;
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
const itemsSectionIndex = indexContent.indexOf("items:");
|
|
525
|
+
const topLevelArea = itemsSectionIndex === -1 ? indexContent : indexContent.slice(0, itemsSectionIndex);
|
|
526
|
+
const key = extractStringField(topLevelArea, "key") || dir;
|
|
527
|
+
result.push({
|
|
528
|
+
key,
|
|
529
|
+
title,
|
|
530
|
+
cover,
|
|
531
|
+
description,
|
|
532
|
+
collapse,
|
|
533
|
+
dirPath: pathe.join(collectionsRoot, dir),
|
|
534
|
+
items
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
return result;
|
|
538
|
+
},
|
|
539
|
+
async batchUpdateFrontmatter(filePaths, operations) {
|
|
540
|
+
const result = {
|
|
541
|
+
total: filePaths.length,
|
|
542
|
+
updated: 0,
|
|
543
|
+
errors: []
|
|
544
|
+
};
|
|
545
|
+
for (const filePath of filePaths) {
|
|
546
|
+
try {
|
|
547
|
+
const resolved = await resolvePageFile(userRoot, filePath);
|
|
548
|
+
if (!await fs.pathExists(resolved)) {
|
|
549
|
+
result.errors.push({ filePath, error: "File not found" });
|
|
550
|
+
continue;
|
|
551
|
+
}
|
|
552
|
+
const rawMd = await fs.readFile(resolved, "utf-8");
|
|
553
|
+
const matterFile = matter(rawMd);
|
|
554
|
+
let modified = false;
|
|
555
|
+
for (const op of operations) {
|
|
556
|
+
if (DANGEROUS_FIELD_KEYS.has(op.key) || op.type === "rename" && DANGEROUS_FIELD_KEYS.has(op.newKey))
|
|
557
|
+
continue;
|
|
558
|
+
switch (op.type) {
|
|
559
|
+
case "set":
|
|
560
|
+
matterFile.data[op.key] = op.value;
|
|
561
|
+
modified = true;
|
|
562
|
+
break;
|
|
563
|
+
case "delete":
|
|
564
|
+
if (op.key in matterFile.data) {
|
|
565
|
+
delete matterFile.data[op.key];
|
|
566
|
+
modified = true;
|
|
567
|
+
}
|
|
568
|
+
break;
|
|
569
|
+
case "rename":
|
|
570
|
+
if (op.key in matterFile.data && op.newKey) {
|
|
571
|
+
matterFile.data[op.newKey] = matterFile.data[op.key];
|
|
572
|
+
delete matterFile.data[op.key];
|
|
573
|
+
modified = true;
|
|
574
|
+
}
|
|
575
|
+
break;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
if (modified) {
|
|
579
|
+
validateFrontmatter(matterFile.data);
|
|
580
|
+
const newMd = matter.stringify(matterFile.content, matterFile.data);
|
|
581
|
+
await fs.writeFile(resolved, newMd);
|
|
582
|
+
result.updated++;
|
|
583
|
+
}
|
|
584
|
+
} catch (e) {
|
|
585
|
+
result.errors.push({ filePath, error: e.message || String(e) });
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
return result;
|
|
589
|
+
},
|
|
590
|
+
async getConfig() {
|
|
591
|
+
return readConfigs(userRoot);
|
|
592
|
+
},
|
|
593
|
+
async updateConfigField(configType, fieldPath, value) {
|
|
594
|
+
try {
|
|
595
|
+
await writeConfigField(userRoot, configType, fieldPath, value);
|
|
596
|
+
return { success: true };
|
|
597
|
+
} catch (e) {
|
|
598
|
+
return { success: false, error: e.message || String(e) };
|
|
599
|
+
}
|
|
600
|
+
},
|
|
601
|
+
async runMigration(filePaths, frontmatter) {
|
|
602
|
+
for (const [key, value] of Object.entries(frontmatter)) {
|
|
603
|
+
if (DANGEROUS_FIELD_KEYS.has(key) || DANGEROUS_FIELD_KEYS.has(value))
|
|
604
|
+
throw new Error("Invalid migration field");
|
|
605
|
+
}
|
|
606
|
+
const paths = await Promise.all(filePaths.map((path) => resolvePageFile(userRoot, path)));
|
|
607
|
+
const workers = paths.map((path) => migration(path, frontmatter, validateFrontmatter));
|
|
608
|
+
await Promise.all(workers);
|
|
609
|
+
return { success: true };
|
|
610
|
+
},
|
|
611
|
+
async createPost(options) {
|
|
612
|
+
try {
|
|
613
|
+
const { title, path: customPath, tags, categories } = options;
|
|
614
|
+
const postsDir = pathe.resolve(userRoot, "pages", "posts");
|
|
615
|
+
let filePath;
|
|
616
|
+
if (customPath) {
|
|
617
|
+
const normalized = customPath.endsWith(".md") ? customPath : `${customPath}.md`;
|
|
618
|
+
filePath = pathe.resolve(postsDir, normalized);
|
|
619
|
+
const rel = pathe.relative(postsDir, filePath);
|
|
620
|
+
if (rel.startsWith("..") || pathe.isAbsolute(rel))
|
|
621
|
+
return { success: false, error: "Invalid path: must be within posts directory" };
|
|
622
|
+
} else {
|
|
623
|
+
const slug = title.toLowerCase().replace(/[\s_]+/g, "-").replace(/[^\w\u4E00-\u9FFF-]/g, "").replace(/-+/g, "-").replace(/^-|-$/g, "") || `post-${Date.now()}`;
|
|
624
|
+
filePath = pathe.resolve(postsDir, `${slug}.md`);
|
|
625
|
+
}
|
|
626
|
+
await resolvePageFile(userRoot, filePath);
|
|
627
|
+
await fs.ensureDir(pathe.dirname(filePath));
|
|
628
|
+
const now = dayjs().format("YYYY-MM-DD HH:mm:ss");
|
|
629
|
+
const frontmatter = {
|
|
630
|
+
title,
|
|
631
|
+
date: now,
|
|
632
|
+
updated: now,
|
|
633
|
+
draft: true
|
|
634
|
+
};
|
|
635
|
+
if (tags && tags.length > 0)
|
|
636
|
+
frontmatter.tags = tags;
|
|
637
|
+
if (categories && categories.length > 0)
|
|
638
|
+
frontmatter.categories = categories;
|
|
639
|
+
const content = matter.stringify("\n", frontmatter);
|
|
640
|
+
const ext = pathe.extname(filePath);
|
|
641
|
+
const base = filePath.slice(0, -ext.length);
|
|
642
|
+
let counter = 0;
|
|
643
|
+
while (true) {
|
|
644
|
+
const entryExists = await fs.lstat(filePath).then(
|
|
645
|
+
() => true,
|
|
646
|
+
(error) => {
|
|
647
|
+
if (error.code === "ENOENT")
|
|
648
|
+
return false;
|
|
649
|
+
throw error;
|
|
650
|
+
}
|
|
651
|
+
);
|
|
652
|
+
if (entryExists) {
|
|
653
|
+
filePath = `${base}-${++counter}${ext}`;
|
|
654
|
+
continue;
|
|
655
|
+
}
|
|
656
|
+
try {
|
|
657
|
+
await fs.writeFile(filePath, content, { encoding: "utf-8", flag: "wx" });
|
|
658
|
+
break;
|
|
659
|
+
} catch (error) {
|
|
660
|
+
if (error.code !== "EEXIST")
|
|
661
|
+
throw error;
|
|
662
|
+
filePath = `${base}-${++counter}${ext}`;
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
return { success: true, filePath };
|
|
666
|
+
} catch (e) {
|
|
667
|
+
return { success: false, error: e.message || String(e) };
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
const fields = v.record(v.string(), v.unknown());
|
|
674
|
+
const filePaths = v.array(v.string());
|
|
675
|
+
const pageData = v.object({ routePath: v.string(), filePath: v.string(), frontmatter: fields });
|
|
676
|
+
const success = v.object({ success: v.boolean() });
|
|
677
|
+
const postContent = v.object({ content: v.string(), revision: v.string() });
|
|
678
|
+
function createRpcFunctions(functions) {
|
|
679
|
+
return [
|
|
680
|
+
defineRpcFunction({ name: "get-post-content", type: "query", jsonSerializable: true, args: [v.string()], returns: postContent, handler: functions.getPostContent }),
|
|
681
|
+
defineRpcFunction({
|
|
682
|
+
name: "update-post-content",
|
|
683
|
+
type: "action",
|
|
684
|
+
jsonSerializable: true,
|
|
685
|
+
args: [v.object({ filePath: v.string(), content: v.pipe(v.string(), v.maxLength(2e6)), revision: v.string() })],
|
|
686
|
+
returns: postContent,
|
|
687
|
+
handler: functions.updatePostContent
|
|
688
|
+
}),
|
|
689
|
+
defineRpcFunction({ name: "get-options", type: "query", jsonSerializable: true, handler: functions.getOptions }),
|
|
690
|
+
defineRpcFunction({ name: "get-post-list", type: "query", jsonSerializable: true, handler: functions.getPostList }),
|
|
691
|
+
defineRpcFunction({ name: "get-page-data", type: "query", jsonSerializable: true, args: [v.string()], returns: pageData, handler: functions.getPageData }),
|
|
692
|
+
defineRpcFunction({ name: "get-collection-list", type: "query", jsonSerializable: true, handler: functions.getCollectionList }),
|
|
693
|
+
defineRpcFunction({ name: "get-config", type: "query", jsonSerializable: true, handler: functions.getConfig }),
|
|
694
|
+
defineRpcFunction({
|
|
695
|
+
name: "create-post",
|
|
696
|
+
type: "action",
|
|
697
|
+
jsonSerializable: true,
|
|
698
|
+
args: [v.object({ title: v.pipe(v.string(), v.minLength(1)), path: v.optional(v.string()), tags: v.optional(v.array(v.string())), categories: v.optional(v.array(v.string())) })],
|
|
699
|
+
returns: v.object({ success: v.boolean(), filePath: v.optional(v.string()), error: v.optional(v.string()) }),
|
|
700
|
+
handler: functions.createPost
|
|
701
|
+
}),
|
|
702
|
+
defineRpcFunction({
|
|
703
|
+
name: "update-frontmatter",
|
|
704
|
+
type: "action",
|
|
705
|
+
jsonSerializable: true,
|
|
706
|
+
args: [v.object({ filePath: v.string(), frontmatter: fields })],
|
|
707
|
+
returns: success,
|
|
708
|
+
handler: functions.updateFrontmatter
|
|
709
|
+
}),
|
|
710
|
+
defineRpcFunction({
|
|
711
|
+
name: "batch-update-frontmatter",
|
|
712
|
+
type: "action",
|
|
713
|
+
jsonSerializable: true,
|
|
714
|
+
args: [filePaths, v.array(v.variant("type", [
|
|
715
|
+
v.object({ type: v.literal("set"), key: v.string(), value: v.unknown() }),
|
|
716
|
+
v.object({ type: v.literal("delete"), key: v.string() }),
|
|
717
|
+
v.object({ type: v.literal("rename"), key: v.string(), newKey: v.string() })
|
|
718
|
+
]))],
|
|
719
|
+
returns: v.object({ total: v.number(), updated: v.number(), errors: v.array(v.object({ filePath: v.string(), error: v.string() })) }),
|
|
720
|
+
handler: functions.batchUpdateFrontmatter
|
|
721
|
+
}),
|
|
722
|
+
defineRpcFunction({
|
|
723
|
+
name: "update-config-field",
|
|
724
|
+
type: "action",
|
|
725
|
+
jsonSerializable: true,
|
|
726
|
+
args: [v.picklist(["site", "valaxy", "theme"]), v.string(), v.unknown()],
|
|
727
|
+
returns: v.object({ success: v.boolean(), error: v.optional(v.string()) }),
|
|
728
|
+
handler: functions.updateConfigField
|
|
729
|
+
}),
|
|
730
|
+
defineRpcFunction({
|
|
731
|
+
name: "run-migration",
|
|
732
|
+
type: "action",
|
|
733
|
+
jsonSerializable: true,
|
|
734
|
+
args: [filePaths, v.record(v.string(), v.string())],
|
|
735
|
+
returns: success,
|
|
736
|
+
handler: functions.runMigration
|
|
737
|
+
}),
|
|
738
|
+
defineRpcFunction({
|
|
739
|
+
name: "open-in-editor",
|
|
740
|
+
type: "action",
|
|
741
|
+
args: [v.object({ file: v.string(), line: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0))), column: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0))) })],
|
|
742
|
+
returns: v.void(),
|
|
743
|
+
handler: functions.openInEditor
|
|
744
|
+
})
|
|
745
|
+
];
|
|
746
|
+
}
|
|
747
|
+
function createValaxyDevframe(options = {}) {
|
|
748
|
+
const cleanups = [];
|
|
749
|
+
let plugins = [];
|
|
750
|
+
const onDispose = (cleanup) => {
|
|
751
|
+
cleanups.push(cleanup);
|
|
752
|
+
};
|
|
753
|
+
async function dispose() {
|
|
754
|
+
const errors = [];
|
|
755
|
+
for (const cleanup of cleanups.splice(0).reverse()) {
|
|
756
|
+
try {
|
|
757
|
+
await cleanup();
|
|
758
|
+
} catch (error) {
|
|
759
|
+
errors.push(error);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
if (errors.length)
|
|
763
|
+
throw new AggregateError(errors, "Valaxy DevTools cleanup failed");
|
|
764
|
+
}
|
|
765
|
+
const definition = defineDevframe({
|
|
766
|
+
id: DEVTOOLS_ID,
|
|
767
|
+
name: "Valaxy",
|
|
768
|
+
version: pkg.version,
|
|
769
|
+
packageName: pkg.name,
|
|
770
|
+
importMetaUrl: import.meta.url,
|
|
771
|
+
homepage: normalizeRepositoryUrl(pkg.repository.url),
|
|
772
|
+
description: pkg.description,
|
|
773
|
+
icon: resolveDevtoolsLogo(options.base),
|
|
774
|
+
basePath: resolveDevtoolsBase(options.base),
|
|
775
|
+
clientAssets: DIR_CLIENT,
|
|
776
|
+
capabilities: { dev: true, build: false },
|
|
777
|
+
services: [{ package: "@devframes/service-shiki", options: { langs: ["json"] } }],
|
|
778
|
+
async setup(ctx) {
|
|
779
|
+
await ctx.rpc.sharedState.get(RESOURCES_STATE, { initialValue: { revision: 0 } });
|
|
780
|
+
plugins = await resolveDevtoolsPlugins(options);
|
|
781
|
+
const functions = getFunctions(options, (data2) => validateEditorFields(plugins, data2));
|
|
782
|
+
const data = createDataApi(ctx, {
|
|
783
|
+
getOptions: functions.getOptions,
|
|
784
|
+
getPostList: functions.getPostList,
|
|
785
|
+
getPageData: functions.getPageData,
|
|
786
|
+
getCollectionList: functions.getCollectionList,
|
|
787
|
+
getConfig: functions.getConfig
|
|
788
|
+
}, onDispose);
|
|
789
|
+
const scoped = ctx.scope(DEVTOOLS_ID);
|
|
790
|
+
for (const fn of createRpcFunctions(functions))
|
|
791
|
+
scoped.rpc.register(fn);
|
|
792
|
+
const manifest = createManifest(plugins, options.base);
|
|
793
|
+
for (const fn of createExtensionRpc(manifest, plugins, data))
|
|
794
|
+
scoped.rpc.register(fn);
|
|
795
|
+
try {
|
|
796
|
+
await setupExtensions(ctx, plugins, manifest, data, onDispose);
|
|
797
|
+
} catch (error) {
|
|
798
|
+
await dispose();
|
|
799
|
+
throw error;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
});
|
|
803
|
+
return Object.assign(definition, { dispose });
|
|
804
|
+
}
|
|
805
|
+
function createExtensionRpc(manifest, plugins, data) {
|
|
806
|
+
return [
|
|
807
|
+
defineRpcFunction({ name: "get-extensions", type: "query", jsonSerializable: true, handler: () => manifest }),
|
|
808
|
+
defineRpcFunction({
|
|
809
|
+
name: "run-editor-action",
|
|
810
|
+
type: "query",
|
|
811
|
+
jsonSerializable: true,
|
|
812
|
+
args: [v.string(), v.string(), fields],
|
|
813
|
+
returns: v.object({ message: v.string(), severity: v.optional(v.picklist(["success", "warn", "error", "info"])) }),
|
|
814
|
+
handler: async (id, filePath, draft) => {
|
|
815
|
+
const [pluginId, actionId, extra] = id.split(":");
|
|
816
|
+
const action = !extra && plugins.find((plugin) => plugin.id === pluginId)?.editor?.actions?.find((action2) => action2.id === actionId);
|
|
817
|
+
if (!action)
|
|
818
|
+
throw new Error(`Unknown editor action: ${id}`);
|
|
819
|
+
const page = await data.getPageData(filePath);
|
|
820
|
+
return action.run({ page, draft: structuredClone(draft), data });
|
|
821
|
+
}
|
|
822
|
+
})
|
|
823
|
+
];
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
export { createRpcFunctions, createValaxyDevframe };
|