@joplo-app/server 0.2.17 → 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,68 @@
1
+ import fs from 'node:fs/promises';
2
+ import { Input, ALL_FORMATS, BufferSource, BufferTarget, Output, WebMOutputFormat, EncodedPacketSink, EncodedAudioPacketSource, EncodedVideoPacketSource } from 'mediabunny';
3
+ /** MediaRecorder packet arrival PTS can jitter. Keep the exact continuous decoded-sample clock. */
4
+ export function audioSampleClock(packets, durations) {
5
+ if (packets.length !== durations.length)
6
+ throw new Error('Audio packet/decode count mismatch');
7
+ let time = 0;
8
+ return packets.map((packet, i) => {
9
+ const duration = durations[i];
10
+ if (!Number.isFinite(duration) || duration <= 0)
11
+ throw new Error('Invalid decoded audio packet duration');
12
+ const result = packet.clone({ timestamp: time, duration });
13
+ time += duration;
14
+ return result;
15
+ });
16
+ }
17
+ /** Packet copy only (VP8/VP9 and Opus): no native codec, ffmpeg executable, decode or re-encode. */
18
+ export async function muxRecordedAudio(videoFile, audio, offsetSeconds, trim) {
19
+ const video = new Input({ formats: ALL_FORMATS, source: new BufferSource(await fs.readFile(videoFile)) });
20
+ const sound = new Input({ formats: ALL_FORMATS, source: new BufferSource(audio) });
21
+ try {
22
+ const v = await video.getPrimaryVideoTrack(), a = await sound.getPrimaryAudioTrack();
23
+ if (!v || !a)
24
+ throw new Error('Video export did not produce both a video and an audio track');
25
+ const vc = await v.getCodec(), ac = await a.getCodec();
26
+ if (!vc || !ac)
27
+ throw new Error('Unknown recorded media codec');
28
+ const target = new BufferTarget(), output = new Output({ format: new WebMOutputFormat(), target });
29
+ const vs = new EncodedVideoPacketSource(vc), as = new EncodedAudioPacketSource(ac);
30
+ output.addVideoTrack(vs);
31
+ output.addAudioTrack(as);
32
+ await output.start();
33
+ const copyVideo = async () => {
34
+ const decoderConfig = await v.getDecoderConfig();
35
+ if (!decoderConfig)
36
+ throw new Error('Missing video decoder configuration');
37
+ for await (const packet of new EncodedPacketSink(v).packets()) {
38
+ if (trim && packet.timestamp >= trim.videoEnd)
39
+ break;
40
+ await vs.add(packet, { decoderConfig });
41
+ }
42
+ vs.close();
43
+ };
44
+ const copyAudio = async () => {
45
+ const decoderConfig = await a.getDecoderConfig();
46
+ if (!decoderConfig)
47
+ throw new Error('Missing audio decoder configuration');
48
+ const packets = [];
49
+ for await (const packet of new EncodedPacketSink(a).packets())
50
+ packets.push(packet);
51
+ for (const packet of trim?.audioDurations ? audioSampleClock(packets, trim.audioDurations) : packets) {
52
+ if (trim && packet.timestamp + packet.duration > trim.audioEnd)
53
+ break;
54
+ if (packet.timestamp + offsetSeconds < 0)
55
+ continue;
56
+ await as.add(packet.clone({ timestamp: packet.timestamp + offsetSeconds }), { decoderConfig });
57
+ }
58
+ as.close();
59
+ };
60
+ await Promise.all([copyVideo(), copyAudio()]);
61
+ await output.finalize();
62
+ await fs.writeFile(videoFile, new Uint8Array(target.buffer));
63
+ }
64
+ finally {
65
+ video.dispose();
66
+ sound.dispose();
67
+ }
68
+ }
@@ -33,6 +33,7 @@
33
33
  const cx = r.left + r.width / 2;
34
34
  const cy = r.top + r.height / 2;
35
35
  if (cx < sr.left || cx > sr.right || cy < sr.top || cy > sr.bottom) {
36
+ if (el.closest('[data-jreport-viewport]') && el.dataset.jid !== args.nextTargetId) return;
36
37
  warnings.push(`Outside frame: "${e.label}"(${e.id}) has its center outside the frame`);
37
38
  return;
38
39
  }
@@ -43,6 +44,9 @@
43
44
  }
44
45
  const hit = document.elementFromPoint(cx, cy);
45
46
  if (hit && (hit === el || el.contains(hit))) return;
47
+ // 插件组件(D86)的锚点在插件自己的画布上方、不接收指针:被同一个插件根里的画布“盖住”是预期的,命中由插件自己判断
48
+ const pluginRoot = el.closest('[data-jplugin]');
49
+ if (pluginRoot && hit && pluginRoot.contains(hit)) return;
46
50
  // 弹窗打开时,背景被遮罩或弹窗面板覆盖是预期的层次,不算遮挡(窄屏下面板常盖住背景按钮)
47
51
  if ((hit?.closest('[data-jbackdrop]') || (dialogOpen && hit?.closest('[role="dialog"]'))) && !el.closest('[role="dialog"]')) return;
48
52
  warnings.push(`Occluded: "${e.label}"(${e.id}) has its center covered by ${hit ? name(hit) : 'content outside the frame'}`);
@@ -51,6 +55,11 @@
51
55
  if (offViewport.length)
52
56
  warnings.push(`Outside viewport: viewport ${vw}×${vh} is smaller than the stage; ${offViewport.length} interactive elements have centers outside the viewport; occlusion checks skipped (${offViewport.join(', ')})`);
53
57
 
58
+ // Plugins can mark a measured render surface and a panning viewport without adding family names to the host.
59
+ stage.querySelectorAll('[data-jreport-surface]').forEach((surface) => {
60
+ if (surface.clientWidth < 1 || surface.clientHeight < 1) warnings.push(`${surface.dataset.jreportSurface} has no size: ${name(surface)} is ${surface.clientWidth}×${surface.clientHeight}px; give its container a width and height`);
61
+ });
62
+
54
63
  // 2. 标签文字溢出
55
64
  stage.querySelectorAll('[data-jtext], .jtrunc').forEach((t) => {
56
65
  if (t.scrollWidth > t.clientWidth + 1) warnings.push(`Label text overflow: ${name(t)} text "${(t.textContent ?? '').slice(0, 40)}" is clipped`);
@@ -0,0 +1,5 @@
1
+ import type { Rollup } from 'vite';
2
+ /** Reserved build base: every generated local asset reference must be consumed before delivery. */
3
+ export declare const PLUGIN_ASSET_BASE = "/__joplo_plugin_asset__/";
4
+ /** Inline emitted resources and install CSS with the runtime in both npm dev and file:// builds. */
5
+ export declare function inlinePluginAssets(id: string, code: string, output: readonly Rollup.OutputAsset[]): string;
@@ -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) {
package/dist/render.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { Browser } from 'playwright-core';
2
2
  import { type AppearanceFont, type AppearanceStroke } from '@joplo-app/core';
3
- import type { RenderOptions, RenderResult } from './contract.js';
3
+ import type { RenderOptions, RenderResult, SheetOptions, SheetResult } from './contract.js';
4
4
  import { type PlaywrightModule } from './export-runtime.js';
5
5
  export { loadPlaywright, type PlaywrightModule } from './export-runtime.js';
6
6
  /** 浏览器启动失败时的一行提示(托管运行时与项目里的 Playwright 都适用:重装 Joplo 自己的导出组件)。 */
@@ -25,3 +25,9 @@ export declare function renderQuery(q: {
25
25
  };
26
26
  }): string;
27
27
  export declare function renderStep(opts: RenderOptions): Promise<RenderResult>;
28
+ /**
29
+ * 分镜(storyboard):一个场景从初始画面到最后一步,每一步截一张(与 renderStep 同一渲染路由),
30
+ * 拼成网格;每格下面写步号、字幕、旁白(narrate,没有时是台词 say)。Agent 一张图看完整场的画面与节奏,
31
+ * 检查空镜、出画、遮挡、字太小,再对照旁白读一遍。告警按步号前缀汇总。
32
+ */
33
+ export declare function renderSheet(opts: SheetOptions): Promise<SheetResult>;
package/dist/render.js CHANGED
@@ -160,4 +160,84 @@ export async function renderStep(opts) {
160
160
  await server.close();
161
161
  }
162
162
  }
163
+ const esc = (t) => t.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
164
+ /**
165
+ * 分镜(storyboard):一个场景从初始画面到最后一步,每一步截一张(与 renderStep 同一渲染路由),
166
+ * 拼成网格;每格下面写步号、字幕、旁白(narrate,没有时是台词 say)。Agent 一张图看完整场的画面与节奏,
167
+ * 检查空镜、出画、遮挡、字太小,再对照旁白读一遍。告警按步号前缀汇总。
168
+ */
169
+ export async function renderSheet(opts) {
170
+ const projectDir = realProjectDir(opts.projectDir);
171
+ const out = path.resolve(opts.out);
172
+ assertNotProjectData(projectDir, out);
173
+ if (fs.existsSync(out) && !opts.overwrite)
174
+ throw new JoploError('USAGE', `Output file already exists: ${out}. To overwrite, pass overwrite: true (CLI: --overwrite)`);
175
+ const columns = Math.max(1, Math.min(6, Math.round(opts.columns ?? 3)));
176
+ const cellWidth = Math.max(240, Math.min(1280, Math.round(opts.cellWidth ?? 480)));
177
+ const playwright = await loadPlaywright({ home: joploHome(), projectDir });
178
+ const server = await createDev({ projectDir, port: 0, watch: false, log: () => undefined });
179
+ let browser = null;
180
+ try {
181
+ const payload = server.payload();
182
+ if (!payload.project) {
183
+ const errs = payload.diagnostics.filter((d) => d.severity === 'error');
184
+ throw new JoploError('INVALID_SCHEMA', `Project compilation failed: ${errs.map((d) => `${d.at ?? ''} ${d.message}`).join('; ')}`, { diagnostics: payload.diagnostics });
185
+ }
186
+ const project = payload.project;
187
+ const sc = project.scenarios[opts.scenarioId];
188
+ if (!sc)
189
+ throw new JoploError('NOT_FOUND', `Scenario does not exist: ${opts.scenarioId} (available: ${Object.keys(project.scenarios).join(', ') || 'none'})`);
190
+ if (opts.content !== undefined && !project.i18n?.locales.includes(opts.content))
191
+ throw new JoploError('USAGE', project.i18n ? `--content ${opts.content} is not in config locales (${project.i18n.locales.join(', ')})` : `--content needs config({ locales }); this project has a single language`);
192
+ const theme = opts.theme ?? project.theme ?? 'sketch';
193
+ browser = await launch(playwright);
194
+ const cells = [];
195
+ const warnings = [];
196
+ for (let position = 0; position <= sc.steps.length; position++) {
197
+ const state = stateAt(project, sc.id, position);
198
+ const scene = project.scenes[displaySceneId(project, sc.id, position)];
199
+ const stage = STAGE_SIZE[scene.viewport === 'mobile' ? 'mobile' : 'desktop'];
200
+ const next = state.completed ? undefined : sc.steps[position];
201
+ const nextTargetId = next && 'target' in next.action ? next.action.target : null;
202
+ const page = await browser.newPage({ viewport: { width: stage.width, height: stage.height + SUBTITLE_HEIGHT }, deviceScaleFactor: 1, reducedMotion: 'reduce' });
203
+ const q = renderQuery({ projectId: server.projectId, scenarioId: sc.id, position, theme, locale: opts.locale, content: opts.content, font: opts.font, stroke: opts.stroke });
204
+ await page.goto(`${server.url}?${q}`, { waitUntil: 'domcontentloaded' });
205
+ await page.waitForFunction(() => window.__JOPLO_READY__ === true, null, { timeout: 60000 });
206
+ const err = await page.evaluate(() => window.__JOPLO_ERROR__ ?? null);
207
+ if (err)
208
+ throw new JoploError('RENDER_FAILED', `Render route reported an error at step ${position}: ${err}`);
209
+ const report = (await page.evaluate(`(${COLLECT_REPORT})(${JSON.stringify({ nextTargetId, theme })})`));
210
+ for (const w of report.warnings)
211
+ warnings.push(`Step ${position}: ${w}`);
212
+ const png = await page.locator('[data-jrender]').screenshot({ type: 'png', animations: 'disabled' });
213
+ await page.close();
214
+ const step = position > 0 ? sc.steps[position - 1] : undefined;
215
+ cells.push({
216
+ png: png.toString('base64'),
217
+ label: position === 0 ? '0 · start' : `${position} · ${step.kind}`,
218
+ caption: step?.caption ?? sc.description ?? sc.name,
219
+ voice: step?.narrate ?? step?.say ?? '',
220
+ });
221
+ }
222
+ const html = `<!doctype html><meta charset="utf-8"><style>
223
+ body{margin:0;padding:24px;background:#16181d;color:#e8e8ea;font:14px/1.45 -apple-system,"PingFang SC","Noto Sans SC",system-ui,sans-serif}
224
+ h1{font-size:18px;margin:0 0 16px} .grid{display:grid;grid-template-columns:repeat(${columns},${cellWidth}px);gap:18px}
225
+ .cell img{width:100%;display:block;border-radius:6px;border:1px solid #2c2f38} .meta{padding:6px 2px 0}
226
+ .n{color:#ffb020;font-weight:700} .cap{font-weight:600} .voice{color:#a0a4b0;margin-top:2px}
227
+ </style><h1>${esc(sc.name)} · ${esc(sc.id)} · ${sc.steps.length} steps</h1><div class="grid">${cells.map((c) => `<div class="cell"><img src="data:image/png;base64,${c.png}"><div class="meta"><span class="n">${esc(c.label)}</span> <span class="cap">${esc(c.caption)}</span>${c.voice ? `<div class="voice">${esc(c.voice)}</div>` : ''}</div></div>`).join('')}</div>`;
228
+ const sheet = await browser.newPage({ viewport: { width: columns * cellWidth + (columns - 1) * 18 + 48, height: 800 }, deviceScaleFactor: 1 });
229
+ await sheet.setContent(html, { waitUntil: 'load' });
230
+ const png = await sheet.screenshot({ type: 'png', fullPage: true });
231
+ fs.mkdirSync(path.dirname(out), { recursive: true });
232
+ if (opts.overwrite)
233
+ fs.writeFileSync(out, png);
234
+ else
235
+ fs.writeFileSync(out, png, { flag: 'wx' });
236
+ return { path: out, steps: sc.steps.length, warnings };
237
+ }
238
+ finally {
239
+ await browser?.close().catch(() => undefined);
240
+ await server.close();
241
+ }
242
+ }
163
243
  const COLLECT_REPORT = fs.readFileSync(path.join(import.meta.dirname, 'page-report.js'), 'utf8').replace(/^\/\*[\s\S]*?\*\/\s*/, '');
@@ -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
+ }
@@ -1,15 +1,35 @@
1
1
  import type http from 'node:http';
2
2
  import type { Project } from '@joplo-app/core';
3
- import { ProfileStore, type FetchLike, type PublicProfile } from './voice.js';
3
+ import type { CloudVoiceBridge, VoiceQuota } from './cloud.js';
4
+ import { ProfileStore, type FetchLike, type PublicProfile, type ResolvedVoices } from './voice.js';
5
+ /** 看板里托管朗读的状态(D85)。null = 这个看板没有 bridge(旧 CLI 启动),只能用浏览器朗读与自带 Key 的供应商。 */
6
+ export type VoiceCloudView = {
7
+ signedIn: boolean;
8
+ server: string | null;
9
+ /** 没登录时给的登录命令(看板里可复制)。 */
10
+ loginCommand: string | null;
11
+ /** 已登录且云端给了 /api/v1/voice(连不上或旧云端 404 时为 false,看板不显示数字)。 */
12
+ available: boolean;
13
+ /** 额度:云端给的,每段合成后用响应头里的剩余字数更新。 */
14
+ quota: VoiceQuota | null;
15
+ /** 控制台的用量页(`<server>/usage`,买加油包也在这里)。 */
16
+ usageUrl: string | null;
17
+ /** 上一次 cloud 合成收到 402:需要多少、还剩多少。 */
18
+ exhausted: {
19
+ neededChars: number | null;
20
+ remainingChars: number | null;
21
+ } | null;
22
+ };
4
23
  export type VoiceState = {
5
24
  /**
6
25
  * 版本:每次算状态时递增(以微秒时钟为下限,dev 重启后也不会变小)。看板只接受 rev 不比当前小的状态:
7
26
  * 推送、选择 / 生成的返回、profilesChanged 之后的重新读取可能乱序到达,晚到的旧状态不能覆盖新的。
8
27
  */
9
28
  rev: number;
10
- /** 看板里选的 profile(config 写了 voice.profile 时以 config 为准,见 source)。 */
29
+ /** 看板里选的 profile(config 写了 voice.profile 时以 config 为准,见 source);没选过为 null,看 source 是否为 default。 */
11
30
  selected: string | null;
12
- source: 'config' | 'board' | null;
31
+ /** config / board / default(没选过,已登录时默认 cloud)/ null(浏览器朗读)。 */
32
+ source: ResolvedVoices['source'];
13
33
  /** config 里写了、本机没有的 profile 名。 */
14
34
  missing: string | null;
15
35
  profile: PublicProfile | null;
@@ -41,6 +61,8 @@ export type VoiceState = {
41
61
  roles: Record<string, string>;
42
62
  };
43
63
  }>;
64
+ /** 托管朗读(D85)。 */
65
+ cloud: VoiceCloudView | null;
44
66
  };
45
67
  type Ctx = {
46
68
  guardWrite: (needJson?: boolean) => boolean;
@@ -61,17 +83,44 @@ export declare class VoiceHub {
61
83
  /** 正在生成的段:项目 → (片段键 → 结果)。批量生成与边放边生成共用,同一段只请求一次。 */
62
84
  private inflight;
63
85
  private inflightOf;
86
+ /** 托管朗读状态(内存,CLOUD_TTL_MS):status = null 表示问云端时出错(当作连不上)。 */
87
+ private cloudCache;
88
+ private exhausted;
64
89
  constructor(home: string, opts: {
65
90
  emit: (projectId: string, state: VoiceState) => void;
66
91
  profilesChanged?: () => void;
67
92
  fetch?: FetchLike;
68
93
  env?: Record<string, string | undefined>;
94
+ cloud?: CloudVoiceBridge;
95
+ now?: () => number;
69
96
  });
97
+ private now;
98
+ private liveInfo;
99
+ /** 托管朗读的状态:内存里有、没过期就直接用;否则问一次 bridge(并发的请求共用一次)。出错不抛,当作连不上。 */
100
+ private cloudStatus;
101
+ private cloudView;
102
+ /** 没选过来源时的默认(D85):已登录用 cloud,否则浏览器朗读。云端暂时连不上时仍算已登录(音色用本机记下的)。 */
103
+ private fallbackOf;
104
+ /** 每段 cloud 合成成功:剩余字数以响应头为准(不在本地估算)。 */
105
+ private receipt;
106
+ /** 402:记下需要 / 剩余,剩余字数也以 402 里的为准。 */
107
+ private quotaHit;
70
108
  private profiles;
71
109
  private error;
72
110
  /** /__joplo/voice/<rest>;不认识的路径返回 false。 */
73
111
  handleGlobal(rest: string, req: http.IncomingMessage, ctx: Ctx): Promise<boolean>;
74
- state(projectId: string, dir: string, project: Project | null): VoiceState;
112
+ /** 项目的声音状态(看板浮层、播放时找音频)。refresh:重新问一次云端额度。 */
113
+ state(projectId: string, dir: string, project: Project | null, refresh?: boolean): Promise<VoiceState>;
114
+ private emitState;
115
+ /** 生成用的声音:与 state() 同一套默认来源。 */
116
+ private resolveFor;
117
+ /**
118
+ * cloud 现在能不能生成(P1-4):没登录 → AUTH_REQUIRED;云端连不上或旧云端没有朗读(404)→ TTS_UNAVAILABLE。
119
+ * 这时不请求云端(否则每一段都要经 CLI 重试好几秒),已有的音频照常按 cloud 指纹播放与打包。能生成时返回 null。
120
+ */
121
+ private cloudBlocked;
122
+ /** cloud 请求的内容语言(D84):项目写了 locales 时是当前内容语言(没传时是默认语言);没写时不带,由云端按文字判断。 */
123
+ private speechLocaleOf;
75
124
  /** /__joplo/p/:id/voice[/…];不认识的路径返回 false。 */
76
125
  handleProject(projectId: string, dir: string, project: Project | null, rest: string, req: http.IncomingMessage, res: http.ServerResponse, ctx: Ctx): Promise<boolean>;
77
126
  /** 关闭看板时停掉正在生成的任务。 */