@joplo-app/server 0.2.18 → 0.3.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.
@@ -0,0 +1,35 @@
1
+ import path from 'node:path';
2
+ import { JoploError } from '@joplo-app/core';
3
+ /** Reserved build base: every generated local asset reference must be consumed before delivery. */
4
+ export const PLUGIN_ASSET_BASE = '/__joplo_plugin_asset__/';
5
+ const MIME = {
6
+ '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.avif': 'image/avif', '.ico': 'image/x-icon', '.bmp': 'image/bmp',
7
+ '.woff2': 'font/woff2', '.woff': 'font/woff', '.ttf': 'font/ttf', '.otf': 'font/otf', '.eot': 'application/vnd.ms-fontobject',
8
+ '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.ogg': 'audio/ogg', '.mp4': 'video/mp4', '.webm': 'video/webm',
9
+ '.wasm': 'application/wasm', '.json': 'application/json', '.txt': 'text/plain', '.js': 'text/javascript', '.glb': 'model/gltf-binary', '.gltf': 'model/gltf+json',
10
+ };
11
+ /** Inline emitted resources and install CSS with the runtime in both npm dev and file:// builds. */
12
+ export function inlinePluginAssets(id, code, output) {
13
+ const css = output.filter(a => a.fileName.endsWith('.css'));
14
+ const assets = output.filter(a => !a.fileName.endsWith('.css'));
15
+ const references = assets.flatMap(a => {
16
+ const mime = MIME[path.extname(a.fileName).toLowerCase()] ?? 'application/octet-stream';
17
+ const data = `data:${mime};base64,${Buffer.from(a.source).toString('base64')}`;
18
+ return [...new Set([a.fileName, encodeURI(a.fileName)])].map(name => [PLUGIN_ASSET_BASE + name, data]);
19
+ });
20
+ const inline = (text) => {
21
+ for (const [reference, url] of references)
22
+ text = text.replaceAll(reference, () => url);
23
+ if (text.includes(PLUGIN_ASSET_BASE))
24
+ throw new JoploError('EXPORT_FAILED', `Plugin ${id}: a generated asset reference could not be bundled`);
25
+ return text;
26
+ };
27
+ const body = inline(code);
28
+ if (!css.length)
29
+ return body;
30
+ const styles = inline(css.map(a => typeof a.source === 'string' ? a.source : Buffer.from(a.source).toString('utf8')).join('\n'));
31
+ const key = JSON.stringify(`joplo-plugin-style:${id}`);
32
+ // A block avoids colliding with the bundler's local names; replacing text updates HMR
33
+ // without duplicate style sheets. textContent cannot break out of a style element.
34
+ return `{const key=${key};let style=document.getElementById(key);if(!style){style=document.createElement('style');style.id=key;document.head.append(style);}style.textContent=${JSON.stringify(styles)};}\n${body}`;
35
+ }
@@ -0,0 +1,35 @@
1
+ import type { PluginKey } from '@joplo-app/kit/plugin';
2
+ export declare class PluginKeyStore {
3
+ private home;
4
+ private env;
5
+ constructor(home?: string, env?: Record<string, string | undefined>);
6
+ file(plugin: string, id: string): string;
7
+ private saved;
8
+ resolve(plugin: string, declarations: readonly PluginKey[]): Record<string, string>;
9
+ status(plugin: string, d: PluginKey): {
10
+ plugin: string;
11
+ saved: boolean;
12
+ envSet: boolean;
13
+ file: string;
14
+ id: string;
15
+ title: string;
16
+ description: string;
17
+ url: string;
18
+ env: string;
19
+ };
20
+ save(plugin: string, d: PluginKey, key: unknown): {
21
+ plugin: string;
22
+ saved: boolean;
23
+ envSet: boolean;
24
+ file: string;
25
+ id: string;
26
+ title: string;
27
+ description: string;
28
+ url: string;
29
+ env: string;
30
+ };
31
+ }
32
+ /** Child processes inherit no account credentials; declared keys travel over stdin only. */
33
+ export declare function compilerEnvironment(): {
34
+ [k: string]: string;
35
+ };
@@ -0,0 +1,66 @@
1
+ /** Plugin declaration → project key cards → guarded save → local 0600 files → own local compiler.
2
+ * Values are never project/IR data. Status contains metadata and presence only.
3
+ */
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import os from 'node:os';
7
+ import crypto from 'node:crypto';
8
+ import { joploHome } from "./home.js";
9
+ const valid = (id) => {
10
+ if (!/^[a-z][a-z0-9-]*$/.test(id))
11
+ throw new Error('Invalid plugin key identity');
12
+ return id;
13
+ };
14
+ export class PluginKeyStore {
15
+ home;
16
+ env;
17
+ constructor(home = joploHome(), env = process.env) {
18
+ this.home = home;
19
+ this.env = env;
20
+ }
21
+ file(plugin, id) {
22
+ return path.join(this.home, 'plugins', valid(plugin), 'keys', `${valid(id)}.json`);
23
+ }
24
+ saved(plugin, id) {
25
+ try {
26
+ const key = JSON.parse(fs.readFileSync(this.file(plugin, id), 'utf8')).key;
27
+ return typeof key === 'string' ? key : undefined;
28
+ }
29
+ catch {
30
+ return undefined;
31
+ }
32
+ }
33
+ resolve(plugin, declarations) {
34
+ return Object.fromEntries(declarations.flatMap(d => {
35
+ const key = this.env[d.env]?.trim() || this.saved(plugin, d.id);
36
+ return key ? [[d.id, key]] : [];
37
+ }));
38
+ }
39
+ status(plugin, d) {
40
+ const file = this.file(plugin, d.id);
41
+ return {
42
+ ...d, plugin, saved: !!this.saved(plugin, d.id), envSet: !!this.env[d.env]?.trim(),
43
+ file: file.startsWith(os.homedir() + path.sep) ? '~' + file.slice(os.homedir().length) : file,
44
+ };
45
+ }
46
+ save(plugin, d, key) {
47
+ const file = this.file(plugin, d.id);
48
+ if (key !== null && (typeof key !== 'string' || !key.trim() || key.length > 4096 || /[\r\n]/.test(key)))
49
+ throw new Error('Invalid API key');
50
+ if (key === null)
51
+ fs.rmSync(file, { force: true });
52
+ else {
53
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
54
+ const temp = `${file}.${crypto.randomUUID()}.tmp`;
55
+ fs.writeFileSync(temp, JSON.stringify({ key: key.trim() }) + '\n', { mode: 0o600 });
56
+ fs.chmodSync(temp, 0o600);
57
+ fs.renameSync(temp, file);
58
+ }
59
+ return this.status(plugin, d);
60
+ }
61
+ }
62
+ /** Child processes inherit no account credentials; declared keys travel over stdin only. */
63
+ export function compilerEnvironment() {
64
+ // HOME preserves local tool configuration (e.g. installed MIDI compilers), not credential values.
65
+ return Object.fromEntries(['PATH', 'HOME', 'USERPROFILE', 'SystemRoot', 'WINDIR', 'TMPDIR', 'TEMP', 'TMP'].flatMap(k => process.env[k] ? [[k, process.env[k]]] : []));
66
+ }
package/dist/project.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { ResourceRequest } from '@joplo-app/kit/plugin';
2
+ import { LocalResources } from './local-resources.js';
1
3
  import { type CompileMode, type Diagnostic, type Project } from '@joplo-app/core';
2
4
  import { discoverFiles } from '@joplo-app/core/node';
3
5
  import type { ViteDevServer } from 'vite';
@@ -7,7 +9,15 @@ export type CompileOutcome = {
7
9
  diagnostics: Diagnostic[];
8
10
  /** joplo.config 的 home(看板与发布站的首页路径)。 */
9
11
  home: string | null;
12
+ /** 启用的插件(D86):插件 id → 运行时入口的绝对路径(看板按它载入,build 按它打包)。 */
13
+ pluginRuntimes: Record<string, string>;
14
+ resources?: {
15
+ requests: ResourceRequest[];
16
+ host: LocalResources;
17
+ };
10
18
  };
19
+ /** config({ plugins }) 里每个插件的运行时入口(编译器另外校验清单;这里只取存在的文件)。 */
20
+ export declare function pluginRuntimesOf(plugins: unknown): Record<string, string>;
11
21
  export declare function compileProject(server: ViteDevServer, projectDir: string, mode: CompileMode): Promise<CompileOutcome>;
12
22
  /** 让项目源文件在下次载入时重新转译、重新求值。 */
13
23
  export declare function invalidateProjectModules(server: ViteDevServer, projectDir: string): void;
package/dist/project.js CHANGED
@@ -2,10 +2,22 @@
2
2
  * 用 Vite 的 ssrLoadModule 载入项目源文件,交给 core 的 loadAuthoring + compile。
3
3
  * dev(看板、截图)与 build(发布站)共用这一条路径。
4
4
  */
5
+ import fs from 'node:fs';
5
6
  import path from 'node:path';
7
+ import { inspectResources, mediaDiagnostics } from "./media-check.js";
8
+ import { LocalResources, referencedResources } from "./local-resources.js";
9
+ import { isPluginDef } from '@joplo-app/kit/plugin';
6
10
  import { compile } from '@joplo-app/core';
7
- import { discoverFiles, elkLayout, loadAuthoring } from '@joplo-app/core/node';
11
+ import { discoverFiles, loadAuthoring, enabledPlugins } from '@joplo-app/core/node';
8
12
  import { isProjectSource } from "./vite-shared.js";
13
+ /** config({ plugins }) 里每个插件的运行时入口(编译器另外校验清单;这里只取存在的文件)。 */
14
+ export function pluginRuntimesOf(plugins) {
15
+ const out = {};
16
+ for (const p of enabledPlugins(plugins))
17
+ if (isPluginDef(p) && typeof p.runtime === 'string' && path.isAbsolute(p.runtime) && fs.existsSync(p.runtime))
18
+ out[p.id] ??= fs.realpathSync(p.runtime);
19
+ return out;
20
+ }
9
21
  const LOC_IN_MESSAGE = /((?:[\w@.-]+\/)*[\w@.-]+\.(?:tsx|ts|jsx|js|mts)):(\d+):(\d+)/;
10
22
  /** 运行时错误(模块求值时抛出):从调用栈里找第一处项目文件位置。 */
11
23
  function stackLoc(projectDir, e) {
@@ -60,13 +72,28 @@ export async function compileProject(server, projectDir, mode) {
60
72
  diagnostics.push(out);
61
73
  }
62
74
  if (!loaded.authoring)
63
- return { project: null, diagnostics, home: null };
75
+ return { project: null, diagnostics, home: null, pluginRuntimes: {} };
64
76
  const home = loaded.authoring.config.home ?? null;
77
+ const pluginRuntimes = pluginRuntimesOf(loaded.authoring.config.plugins);
65
78
  if (diagnostics.some((d) => d.severity === 'error'))
66
- return { project: null, diagnostics, home };
67
- // 图表布局在编译期由 ELK 算好写进 IR(D69):看板与发布站只渲染
68
- const r = compile(loaded.authoring, mode, { layout: elkLayout });
69
- return { project: r.project, diagnostics: [...diagnostics, ...r.diagnostics], home };
79
+ return { project: null, diagnostics, home, pluginRuntimes };
80
+ // Enabled plugins derive their own layout and drawing snapshots; the host schedules resources.
81
+ const requests = [];
82
+ const entries = Object.fromEntries(enabledPlugins(loaded.authoring.config.plugins).filter(isPluginDef).filter(p => p.local).map(p => [p.id, p.local]));
83
+ const resources = { requests, host: new LocalResources(projectDir, entries, Object.fromEntries(enabledPlugins(loaded.authoring.config.plugins).filter(isPluginDef).map(p => [p.id, p.keys ?? []]))) };
84
+ const first = compile(loaded.authoring, mode, { onResource: request => requests.push(request) });
85
+ const inspected = await inspectResources(first.project, requests, resources.host);
86
+ const r = Object.keys(inspected.resourceInfo).length ? compile(loaded.authoring, mode, { resourceInfo: inspected.resourceInfo }) : first;
87
+ diagnostics.push(...inspected.diagnostics, ...(r.project ? mediaDiagnostics(r.project, inspected.resourceInfo) : []));
88
+ const missing = Object.keys(r.project?.plugins ?? {}).filter((id) => !pluginRuntimes[id]);
89
+ const extra = missing.map((id) => ({ severity: 'error', code: 'PLUGIN_RUNTIME_MISSING', message: `Plugin ${id}: runtime file not found; reinstall the plugin package`, source: 'reference', at: `${loaded.authoring.config.file}:1:1` }));
90
+ for (const request of requests)
91
+ if (referencedResources(r.project).has(request.id)) {
92
+ const result = await resources.host.ensure(request);
93
+ if (result.diagnostic)
94
+ diagnostics.push(result.diagnostic);
95
+ }
96
+ return { project: extra.length ? null : r.project, diagnostics: [...diagnostics, ...r.diagnostics, ...extra], home, pluginRuntimes, resources };
70
97
  }
71
98
  /** 让项目源文件在下次载入时重新转译、重新求值。 */
72
99
  export function invalidateProjectModules(server, projectDir) {
@@ -0,0 +1,31 @@
1
+ /** Explicit local-resource generation. No network before per-item confirmation. */
2
+ export declare function generateResources(directory: string, opts?: {
3
+ dryRun?: boolean;
4
+ allowSpend?: boolean;
5
+ confirm?: (message: string) => Promise<boolean>;
6
+ onProgress?: (message: string) => void;
7
+ }): Promise<({
8
+ id: string;
9
+ cached: boolean;
10
+ credits: number;
11
+ diagnostic?: undefined;
12
+ generated?: undefined;
13
+ } | {
14
+ id: string;
15
+ credits: number | undefined;
16
+ diagnostic: import("@joplo-app/core").Diagnostic | undefined;
17
+ cached?: undefined;
18
+ generated?: undefined;
19
+ } | {
20
+ id: string;
21
+ diagnostic: import("@joplo-app/core").Diagnostic | undefined;
22
+ cached?: undefined;
23
+ credits?: undefined;
24
+ generated?: undefined;
25
+ } | {
26
+ id: string;
27
+ generated: boolean;
28
+ diagnostic: import("@joplo-app/core").Diagnostic | undefined;
29
+ cached?: undefined;
30
+ credits?: undefined;
31
+ })[]>;
@@ -0,0 +1,43 @@
1
+ import { createServer } from 'vite';
2
+ import { compileProject } from "./project.js";
3
+ import { realProjectDir, joploProjectPlugin, locateWebAssets, kitAliases } from "./vite-shared.js";
4
+ /** Explicit local-resource generation. No network before per-item confirmation. */
5
+ export async function generateResources(directory, opts = {}) {
6
+ const projectDir = realProjectDir(directory), web = locateWebAssets();
7
+ const loader = await createServer({ configFile: false, envDir: false, root: projectDir, logLevel: 'silent', appType: 'custom', resolve: { alias: kitAliases(web, projectDir) }, plugins: [joploProjectPlugin(projectDir, web)], server: { middlewareMode: true, hmr: false, watch: null }, optimizeDeps: { noDiscovery: true, include: [] } });
8
+ try {
9
+ const compiled = await compileProject(loader, projectDir, 'dev');
10
+ if (!compiled.project || !compiled.resources || compiled.diagnostics.some(d => d.severity === 'error'))
11
+ throw new Error('Project compilation failed; run joplo check for diagnostics.');
12
+ const { host, requests } = compiled.resources, results = [];
13
+ for (const request of requests) {
14
+ const description = await host.describe(request);
15
+ if (!description.persistent)
16
+ continue;
17
+ const cached = await host.ensure(request);
18
+ if (cached.url) {
19
+ results.push({ id: request.id, cached: true, credits: 0 });
20
+ continue;
21
+ }
22
+ const message = `${request.plugin}/${request.compiler} ${request.id}: estimated ${description.credits ?? 'unknown'} credits`;
23
+ opts.onProgress?.(message);
24
+ if (opts.dryRun) {
25
+ results.push({ id: request.id, credits: description.credits, diagnostic: cached.diagnostic });
26
+ continue;
27
+ }
28
+ const allowed = opts.allowSpend === true || await opts.confirm?.(`${message}. Generate?`) === true;
29
+ if (!allowed) {
30
+ results.push({ id: request.id, diagnostic: cached.diagnostic });
31
+ continue;
32
+ }
33
+ const result = await host.ensure(request, { allowSpend: true });
34
+ results.push({ id: request.id, generated: !!result.url, diagnostic: result.diagnostic });
35
+ if (result.diagnostic)
36
+ break;
37
+ }
38
+ return results;
39
+ }
40
+ finally {
41
+ await loader.close();
42
+ }
43
+ }
@@ -100,7 +100,7 @@ export function findPackageJson(dir, name) {
100
100
  cur = parent;
101
101
  }
102
102
  }
103
- const KIT_SUBPATHS = ['ui', 'node', 'jsx-runtime', 'jsx-dev-runtime'];
103
+ const KIT_SUBPATHS = ['node', 'plugin', 'jsx-runtime', 'jsx-dev-runtime'];
104
104
  /**
105
105
  * 项目源文件里的 `@joplo-app/kit` 怎样解析:
106
106
  * - source:指向仓库里的 kit 源码(项目可在任意目录,不需要自己的 node_modules);`@/` 指向 web 源码。
@@ -110,7 +110,7 @@ export function kitAliases(web, projectDir) {
110
110
  if (web.mode === 'source')
111
111
  return [
112
112
  { find: /^@joplo-app\/kit$/, replacement: path.join(web.kitSrc, 'index.ts') },
113
- { find: /^@joplo-app\/kit\/(ui|node|jsx-runtime|jsx-dev-runtime)$/, replacement: path.join(web.kitSrc, '$1.ts') },
113
+ { find: /^@joplo-app\/kit\/(node|plugin|jsx-runtime|jsx-dev-runtime)$/, replacement: path.join(web.kitSrc, '$1.ts') },
114
114
  { find: /^@\//, replacement: path.join(web.webDir, 'src') + '/' },
115
115
  ];
116
116
  if (findPackageJson(projectDir, '@joplo-app/kit'))
@@ -122,6 +122,6 @@ export function kitAliases(web, projectDir) {
122
122
  const ext = path.extname(main);
123
123
  return [
124
124
  { find: /^@joplo-app\/kit$/, replacement: main },
125
- { find: /^@joplo-app\/kit\/(ui|node|jsx-runtime|jsx-dev-runtime)$/, replacement: path.join(path.dirname(main), `$1${ext}`) },
125
+ { find: /^@joplo-app\/kit\/(node|plugin|jsx-runtime|jsx-dev-runtime)$/, replacement: path.join(path.dirname(main), `$1${ext}`) },
126
126
  ];
127
127
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joplo-app/server",
3
- "version": "0.2.18",
3
+ "version": "0.3.0",
4
4
  "description": "Joplo 本地服务:dev 看板、build 发布站、render 截图",
5
5
  "license": "PolyForm-Shield-1.0.0",
6
6
  "type": "module",
@@ -15,16 +15,16 @@
15
15
  "dist"
16
16
  ],
17
17
  "dependencies": {
18
- "@joplo-app/core": "0.2.18",
19
- "@joplo-app/kit": "0.2.18",
20
- "@joplo-app/web": "0.2.18",
18
+ "@joplo-app/core": "0.3.0",
19
+ "@joplo-app/kit": "0.3.0",
20
+ "@joplo-app/web": "0.3.0",
21
21
  "@tailwindcss/vite": "4.3.4",
22
+ "mediabunny": "1.65.2",
22
23
  "tailwindcss": "4.3.4",
23
24
  "vite": "8.3.5",
24
25
  "zod": "4.6.7"
25
26
  },
26
27
  "devDependencies": {
27
- "@joplo-app/core-legacy": "npm:@joplo-app/core@0.2.10",
28
28
  "@vitejs/plugin-react": "6.2.1",
29
29
  "playwright": "1.64.1",
30
30
  "playwright-core": "1.64.1"