@joplo-app/server 0.2.10 → 0.2.13
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/dist/build.d.ts +3 -2
- package/dist/build.js +19 -7
- package/dist/cloud.d.ts +85 -0
- package/dist/cloud.js +110 -0
- package/dist/contract.d.ts +17 -2
- package/dist/dev.d.ts +5 -1
- package/dist/dev.js +57 -5
- package/dist/feature-diff-locales.json +882 -0
- package/dist/feature-diff-runtime.js +427 -0
- package/dist/feature-diff-viewer.d.ts +3 -0
- package/dist/feature-diff-viewer.js +130 -0
- package/dist/feature-diff.d.ts +14 -0
- package/dist/feature-diff.js +56 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -0
- package/dist/local-review.d.ts +18 -0
- package/dist/local-review.js +133 -0
- package/dist/render.js +6 -3
- package/dist/voice-http.d.ts +10 -1
- package/dist/voice-http.js +25 -10
- package/dist/voice.d.ts +16 -6
- package/dist/voice.js +21 -1
- package/package.json +5 -4
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, mkdtemp } from 'node:fs/promises';
|
|
2
|
+
import { dirname, join, resolve, sep } from 'node:path';
|
|
3
|
+
import { readFeatureDiffBuild, featureDiff, JoploError } from '@joplo-app/core';
|
|
4
|
+
import { writeFile } from 'node:fs/promises';
|
|
5
|
+
import { diffViewerHtml } from "./feature-diff-viewer.js";
|
|
6
|
+
export const publicIRFromHtml = readFeatureDiffBuild;
|
|
7
|
+
/** Copy only a build's public payload; no project files, review attachments or symlinks. */
|
|
8
|
+
async function checkFiles(dir, prefix = '') {
|
|
9
|
+
for (const e of await readdir(dir, { withFileTypes: true })) {
|
|
10
|
+
const relative = prefix + e.name;
|
|
11
|
+
if (e.isSymbolicLink() || /[\\?#%\x00-\x1f\x7f]/.test(e.name) || (!prefix && !['index.html', 'assets', 'fonts', 'voice', '_joplo'].includes(e.name)))
|
|
12
|
+
throw new JoploError('INVALID_SCHEMA', `Not a standalone public build: ${relative}`);
|
|
13
|
+
if (e.isDirectory())
|
|
14
|
+
await checkFiles(join(dir, e.name), relative + '/');
|
|
15
|
+
else if (!e.isFile())
|
|
16
|
+
throw new JoploError('INVALID_SCHEMA', 'Build contains a non-regular file');
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export async function buildFeatureDiff(opts) {
|
|
20
|
+
const before = await realpath(opts.beforeDir), after = await realpath(opts.afterDir);
|
|
21
|
+
// Never clear an existing directory. Validate both builds before creating any output.
|
|
22
|
+
const output = resolve(opts.outDir);
|
|
23
|
+
await mkdir(dirname(output), { recursive: true });
|
|
24
|
+
const outDir = join(await realpath(dirname(output)), output.slice(dirname(output).length + 1));
|
|
25
|
+
if ([before, after].some(p => outDir === p || p.startsWith(outDir + sep) || outDir.startsWith(p + sep)))
|
|
26
|
+
throw new JoploError('USAGE', 'Diff output must be separate from both input sites');
|
|
27
|
+
try {
|
|
28
|
+
await lstat(outDir);
|
|
29
|
+
throw new JoploError('USAGE', 'Diff output already exists; choose a new directory');
|
|
30
|
+
}
|
|
31
|
+
catch (e) {
|
|
32
|
+
if (e.code !== 'ENOENT')
|
|
33
|
+
throw e;
|
|
34
|
+
}
|
|
35
|
+
await checkFiles(before);
|
|
36
|
+
await checkFiles(after);
|
|
37
|
+
const beforeHtml = await readFile(join(before, 'index.html'), 'utf8'), afterHtml = await readFile(join(after, 'index.html'), 'utf8');
|
|
38
|
+
let m = featureDiff(publicIRFromHtml(beforeHtml), publicIRFromHtml(afterHtml), opts);
|
|
39
|
+
if (![beforeHtml, afterHtml].every(html => html.includes('<meta name="joplo-feature-diff-player" content="1">'))) {
|
|
40
|
+
m = { ...m, status: 'incompatible', reasons: [...m.reasons, 'player-version'], scenarios: [], summary: { added: [], modified: [], removed: [] } };
|
|
41
|
+
}
|
|
42
|
+
const staging = await mkdtemp(join(dirname(outDir), '.joplo-diff-'));
|
|
43
|
+
try {
|
|
44
|
+
if (m.status !== 'incompatible') {
|
|
45
|
+
await cp(before, join(staging, 'before'), { recursive: true, dereference: false });
|
|
46
|
+
await cp(after, join(staging, 'after'), { recursive: true, dereference: false });
|
|
47
|
+
}
|
|
48
|
+
await writeFile(join(staging, 'feature-diff.json'), JSON.stringify(m, null, 2) + '\n');
|
|
49
|
+
await writeFile(join(staging, 'index.html'), diffViewerHtml(m));
|
|
50
|
+
await rename(staging, outDir);
|
|
51
|
+
}
|
|
52
|
+
finally {
|
|
53
|
+
await rm(staging, { recursive: true, force: true });
|
|
54
|
+
}
|
|
55
|
+
return { outDir, manifest: m };
|
|
56
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -6,8 +6,9 @@
|
|
|
6
6
|
* - renderStep:某个场景某一步之后的截图、元素索引(带 at)与渲染告警。
|
|
7
7
|
* - exportRuntimeStatus / installExportRuntime / uninstallExportRuntime:Joplo 托管的导出组件(D66,`joplo setup export`)。
|
|
8
8
|
*/
|
|
9
|
-
export type { BuildOptions, BuildResult, DevHandle, DevOptions, RenderOptions, RenderResult, RenderedElement } from './contract.js';
|
|
9
|
+
export type { BuildOptions, BuildResult, CloudAccount, CloudBridge, CloudJob, CloudJobError, CloudPublishRequest, CloudPublishResult, DevHandle, DevOptions, RenderOptions, RenderResult, RenderedElement } from './contract.js';
|
|
10
10
|
export { startDev } from './dev.js';
|
|
11
11
|
export { buildSite } from './build.js';
|
|
12
12
|
export { renderStep } from './render.js';
|
|
13
13
|
export { EXPORT_DOWNLOAD_MB, PLAYWRIGHT_VERSION, SETUP_COMMAND, exportRuntimeStatus, installExportRuntime, uninstallExportRuntime, type ExportRuntimeStatus, type InstallProgress, type InstallResult } from './export-runtime.js';
|
|
14
|
+
export { buildFeatureDiff, publicIRFromHtml, type DiffBuildOptions, type DiffBuildResult } from './feature-diff.js';
|
package/dist/index.js
CHANGED
|
@@ -2,3 +2,4 @@ export { startDev } from "./dev.js";
|
|
|
2
2
|
export { buildSite } from "./build.js";
|
|
3
3
|
export { renderStep } from "./render.js";
|
|
4
4
|
export { EXPORT_DOWNLOAD_MB, PLAYWRIGHT_VERSION, SETUP_COMMAND, exportRuntimeStatus, installExportRuntime, uninstallExportRuntime } from "./export-runtime.js";
|
|
5
|
+
export { buildFeatureDiff, publicIRFromHtml } from "./feature-diff.js";
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type LocalReviewContext, type LocalReviewLocation, type LocalReviewState, type LocalReviewWrite, type Project } from '@joplo-app/core';
|
|
2
|
+
export declare function localReviewRevision(project: Project, optionId: string): string;
|
|
3
|
+
export declare function localReviewContext(project: Project, optionId: string, input: LocalReviewLocation): LocalReviewContext;
|
|
4
|
+
/** 一个 Hub 是一个不可复用的实例身份;不同 Hub 即使打开同一项目,也写不同的会话文件。 */
|
|
5
|
+
export declare class LocalReviewHub {
|
|
6
|
+
private baseUrl;
|
|
7
|
+
readonly instanceId: `${string}-${string}-${string}-${string}-${string}`;
|
|
8
|
+
private current;
|
|
9
|
+
private sessions;
|
|
10
|
+
constructor(baseUrl: () => string);
|
|
11
|
+
private key;
|
|
12
|
+
private persist;
|
|
13
|
+
private closeSession;
|
|
14
|
+
sync(dir: string, projectId: string, project: Project): void;
|
|
15
|
+
invalidate(dir: string, reason: 'source_changed' | 'compile_error' | 'server_stopped'): void;
|
|
16
|
+
state(dir: string, optionId: string): LocalReviewState;
|
|
17
|
+
write(dir: string, project: Project, input: LocalReviewWrite): LocalReviewState;
|
|
18
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { JoploError, LOCAL_REVIEW_MAX_EVENTS, LOCAL_REVIEW_MAX_FILE_BYTES, LocalReviewSession, localReviewStatus, stateAt } from '@joplo-app/core';
|
|
3
|
+
import { localReviewFile, localReviewWatcherCount, writeLocalReview } from '@joplo-app/core/node';
|
|
4
|
+
/** 对象键的插入顺序不构成新版本;数组顺序属于方案内容。 */
|
|
5
|
+
function stable(value) {
|
|
6
|
+
if (Array.isArray(value))
|
|
7
|
+
return value.map(stable);
|
|
8
|
+
if (value && typeof value === 'object')
|
|
9
|
+
return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, stable(v)]));
|
|
10
|
+
return value;
|
|
11
|
+
}
|
|
12
|
+
export function localReviewRevision(project, optionId) {
|
|
13
|
+
const option = project.options[optionId];
|
|
14
|
+
const feature = project.features[option.featureId];
|
|
15
|
+
const own = (values) => Object.fromEntries(Object.entries(values).filter(([, v]) => v.optionId === optionId || (v.optionId == null && (v.featureId == null || v.featureId === option.featureId))));
|
|
16
|
+
const value = { name: project.name, description: project.description, theme: project.theme, themes: project.themes, autoFocus: project.autoFocus,
|
|
17
|
+
feature, option, scenes: own(project.scenes), scenarios: own(project.scenarios), rules: own(project.rules), issues: own(project.issues),
|
|
18
|
+
cases: Object.fromEntries(Object.entries(project.cases).filter(([, c]) => c.featureId === option.featureId)),
|
|
19
|
+
};
|
|
20
|
+
return crypto.createHash('sha256').update(JSON.stringify(stable(value))).digest('hex');
|
|
21
|
+
}
|
|
22
|
+
export function localReviewContext(project, optionId, input) {
|
|
23
|
+
const option = project.options[optionId];
|
|
24
|
+
const scene = project.scenes[input.sceneId];
|
|
25
|
+
if (!option || !scene)
|
|
26
|
+
throw new JoploError('INVALID_REFERENCE', 'Review page or option no longer exists');
|
|
27
|
+
const layerScenes = Object.values(option.layers).map(l => l.sceneId);
|
|
28
|
+
let stepId = null;
|
|
29
|
+
let source = scene.root.source ?? option.source ?? null;
|
|
30
|
+
let scenarioName = null;
|
|
31
|
+
if (input.scenarioId !== null) {
|
|
32
|
+
const scenario = project.scenarios[input.scenarioId];
|
|
33
|
+
if (!scenario || scenario.optionId !== optionId || input.position > scenario.steps.length)
|
|
34
|
+
throw new JoploError('INVALID_REFERENCE', 'Review scenario or step does not belong to this option');
|
|
35
|
+
const state = stateAt(project, scenario.id, input.position);
|
|
36
|
+
if (state.sceneId !== scene.id && !layerScenes.includes(scene.id))
|
|
37
|
+
throw new JoploError('INVALID_REFERENCE', 'Review page is not visible at this step');
|
|
38
|
+
const step = scenario.steps[input.position - 1];
|
|
39
|
+
stepId = step?.id ?? null;
|
|
40
|
+
source = step?.source ?? source;
|
|
41
|
+
scenarioName = scenario.name;
|
|
42
|
+
}
|
|
43
|
+
else if (input.position !== 0 || (scene.optionId !== optionId && !layerScenes.includes(scene.id))) {
|
|
44
|
+
throw new JoploError('INVALID_REFERENCE', 'Review page does not belong to this option');
|
|
45
|
+
}
|
|
46
|
+
return { ...input, route: scene.route, pageTitle: scene.name, stepId, source, scenarioName };
|
|
47
|
+
}
|
|
48
|
+
/** 一个 Hub 是一个不可复用的实例身份;不同 Hub 即使打开同一项目,也写不同的会话文件。 */
|
|
49
|
+
export class LocalReviewHub {
|
|
50
|
+
baseUrl;
|
|
51
|
+
instanceId = crypto.randomUUID();
|
|
52
|
+
current = new Map();
|
|
53
|
+
sessions = new Map();
|
|
54
|
+
constructor(baseUrl) {
|
|
55
|
+
this.baseUrl = baseUrl;
|
|
56
|
+
}
|
|
57
|
+
key(dir, option) { return `${dir}\0${option}`; }
|
|
58
|
+
persist(session) {
|
|
59
|
+
if (!LocalReviewSession.safeParse(session).success)
|
|
60
|
+
throw new JoploError('INVALID_SCHEMA', 'Invalid local review record');
|
|
61
|
+
if (Buffer.byteLength(JSON.stringify(session)) > LOCAL_REVIEW_MAX_FILE_BYTES - (session.events.at(-1)?.type === 'feedback' ? 16_384 : 0))
|
|
62
|
+
throw new JoploError('USAGE', 'Local review storage limit reached. Confirm this review before starting another');
|
|
63
|
+
writeLocalReview(localReviewFile(session.projectDir, session.id), session);
|
|
64
|
+
this.sessions.set(session.id, session);
|
|
65
|
+
this.current.set(this.key(session.projectDir, session.optionId), session);
|
|
66
|
+
return session;
|
|
67
|
+
}
|
|
68
|
+
closeSession(session, reason) {
|
|
69
|
+
if (localReviewStatus(session) !== 'open')
|
|
70
|
+
return;
|
|
71
|
+
this.persist({ ...session, events: [...session.events, { sessionId: session.id, seq: session.events.length + 1, requestId: crypto.randomUUID(), createdAt: new Date().toISOString(), type: 'closed', reason }] });
|
|
72
|
+
}
|
|
73
|
+
sync(dir, projectId, project) {
|
|
74
|
+
for (const s of [...this.current.values()])
|
|
75
|
+
if (s.projectDir === dir && !project.options[s.optionId]) {
|
|
76
|
+
this.closeSession(s, 'option_removed');
|
|
77
|
+
this.current.delete(this.key(dir, s.optionId));
|
|
78
|
+
}
|
|
79
|
+
for (const option of Object.values(project.options)) {
|
|
80
|
+
const revision = localReviewRevision(project, option.id);
|
|
81
|
+
const old = this.current.get(this.key(dir, option.id));
|
|
82
|
+
if (old?.revision === revision && localReviewStatus(old) !== 'closed')
|
|
83
|
+
continue;
|
|
84
|
+
if (old)
|
|
85
|
+
this.closeSession(old, 'source_changed');
|
|
86
|
+
const id = `rv_${crypto.randomBytes(16).toString('hex')}`;
|
|
87
|
+
this.persist({ v: 1, id, instanceId: this.instanceId, ownerPid: process.pid, projectId, projectDir: dir, projectName: project.name,
|
|
88
|
+
featureId: option.featureId, featureName: project.features[option.featureId].name, optionId: option.id, optionName: option.name,
|
|
89
|
+
revision, createdAt: new Date().toISOString(), url: `${this.baseUrl()}#/${encodeURIComponent(projectId)}/f/${encodeURIComponent(option.featureId)}?o=${encodeURIComponent(option.id)}`,
|
|
90
|
+
events: [], });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
invalidate(dir, reason) {
|
|
94
|
+
for (const session of [...this.current.values()])
|
|
95
|
+
if (session.projectDir === dir) {
|
|
96
|
+
this.closeSession(session, reason);
|
|
97
|
+
this.current.delete(this.key(dir, session.optionId));
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
state(dir, optionId) {
|
|
101
|
+
const session = this.current.get(this.key(dir, optionId));
|
|
102
|
+
if (!session)
|
|
103
|
+
throw new JoploError('NOT_FOUND', 'No current review for this option. Wait for a successful compilation');
|
|
104
|
+
return { session, watchers: localReviewWatcherCount(dir, session.id) };
|
|
105
|
+
}
|
|
106
|
+
write(dir, project, input) {
|
|
107
|
+
const session = this.sessions.get(input.sessionId);
|
|
108
|
+
if (!session || session.projectDir !== dir)
|
|
109
|
+
throw new JoploError('NOT_FOUND', 'Review session does not belong to this project and instance');
|
|
110
|
+
const previous = session.events.find(e => e.requestId === input.requestId);
|
|
111
|
+
if (previous) {
|
|
112
|
+
const same = previous.type === input.type && (previous.type !== 'feedback' || input.type === 'feedback' && previous.body === input.body &&
|
|
113
|
+
previous.context.sceneId === input.context.sceneId && previous.context.scenarioId === input.context.scenarioId && previous.context.position === input.context.position);
|
|
114
|
+
if (!same)
|
|
115
|
+
throw new JoploError('IDEMPOTENCY_MISMATCH', 'Request id was already used for different feedback');
|
|
116
|
+
return { session, watchers: localReviewWatcherCount(dir, session.id) };
|
|
117
|
+
}
|
|
118
|
+
if (this.current.get(this.key(dir, session.optionId))?.id !== session.id || localReviewRevision(project, session.optionId) !== session.revision)
|
|
119
|
+
throw new JoploError('REVISION_CONFLICT', 'The option changed. Open its current review before submitting');
|
|
120
|
+
if (input.type === 'approved' && localReviewStatus(session) === 'approved')
|
|
121
|
+
return this.state(dir, session.optionId);
|
|
122
|
+
if (localReviewStatus(session) !== 'open')
|
|
123
|
+
throw new JoploError('REVISION_CONFLICT', 'This review has ended');
|
|
124
|
+
if (input.type === 'feedback' && session.events.length >= LOCAL_REVIEW_MAX_EVENTS - 1)
|
|
125
|
+
throw new JoploError('USAGE', 'This review has reached its feedback limit. Confirm it before starting a new review');
|
|
126
|
+
const base = { sessionId: session.id, seq: session.events.length + 1, requestId: input.requestId, createdAt: new Date().toISOString() };
|
|
127
|
+
const event = input.type === 'feedback'
|
|
128
|
+
? { ...base, type: 'feedback', body: input.body, context: localReviewContext(project, session.optionId, input.context) }
|
|
129
|
+
: { ...base, type: 'approved' };
|
|
130
|
+
this.persist({ ...session, events: [...session.events, event] });
|
|
131
|
+
return this.state(dir, session.optionId);
|
|
132
|
+
}
|
|
133
|
+
}
|
package/dist/render.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import fs from 'node:fs';
|
|
10
10
|
import path from 'node:path';
|
|
11
|
-
import { JoploError, SUBTITLE_HEIGHT, VIEWPORT_SIZE, isAppearanceFont, isAppearanceStroke, displaySceneId, findNode, isNodeDisabled, nodeLabel, positionAfterStep, resolveProps, stateAt, walkNodes } from '@joplo-app/core';
|
|
11
|
+
import { JoploError, SUBTITLE_HEIGHT, VIEWPORT_SIZE, isAppearanceFont, isAppearanceStroke, displaySceneId, findNode, isNodeDisabled, nodeLabel, positionAfterStep, resolveProps, scopeProject, stateAt, walkNodes } from '@joplo-app/core';
|
|
12
12
|
import { exportLocale } from "./locale.js";
|
|
13
13
|
import { createDev } from "./dev.js";
|
|
14
14
|
import { realProjectDir } from "./vite-shared.js";
|
|
@@ -92,11 +92,14 @@ export async function renderStep(opts) {
|
|
|
92
92
|
let browser = null;
|
|
93
93
|
try {
|
|
94
94
|
const payload = server.payload();
|
|
95
|
-
|
|
96
|
-
if (!project) {
|
|
95
|
+
if (!payload.project) {
|
|
97
96
|
const errs = payload.diagnostics.filter((d) => d.severity === 'error');
|
|
98
97
|
throw new JoploError('INVALID_SCHEMA', `Project compilation failed: ${errs.map((d) => `${d.at ?? ''} ${d.message}`).join('; ')}`, { diagnostics: payload.diagnostics });
|
|
99
98
|
}
|
|
99
|
+
// 按场景保密分享(D75):渲染页从同一个 payload 读 IR,替换成裁剪后的(watch: false,不会被重新编译覆盖)
|
|
100
|
+
if (opts.scope?.length)
|
|
101
|
+
payload.project = scopeProject(payload.project, opts.scope, 'publish').project;
|
|
102
|
+
const project = payload.project;
|
|
100
103
|
const sc = project.scenarios[opts.scenarioId];
|
|
101
104
|
if (!sc)
|
|
102
105
|
throw new JoploError('NOT_FOUND', `Scenario does not exist: ${opts.scenarioId} (available: ${Object.keys(project.scenarios).join(', ') || 'none'})`);
|
package/dist/voice-http.d.ts
CHANGED
|
@@ -2,6 +2,11 @@ import type http from 'node:http';
|
|
|
2
2
|
import type { Project } from '@joplo-app/core';
|
|
3
3
|
import { ProfileStore, type FetchLike, type PublicProfile } from './voice.js';
|
|
4
4
|
export type VoiceState = {
|
|
5
|
+
/**
|
|
6
|
+
* 版本:每次算状态时递增(以微秒时钟为下限,dev 重启后也不会变小)。看板只接受 rev 不比当前小的状态:
|
|
7
|
+
* 推送、选择 / 生成的返回、profilesChanged 之后的重新读取可能乱序到达,晚到的旧状态不能覆盖新的。
|
|
8
|
+
*/
|
|
9
|
+
rev: number;
|
|
5
10
|
/** 看板里选的 profile(config 写了 voice.profile 时以 config 为准,见 source)。 */
|
|
6
11
|
selected: string | null;
|
|
7
12
|
source: 'config' | 'board' | null;
|
|
@@ -38,14 +43,18 @@ type Ctx = {
|
|
|
38
43
|
}>;
|
|
39
44
|
send: (status: number, body: unknown) => void;
|
|
40
45
|
};
|
|
46
|
+
/** 用户目录写成 ~(看板显示 profile 存在哪里;不在用户目录下时原样)。 */
|
|
47
|
+
export declare function tildify(file: string, home?: string): string;
|
|
41
48
|
export declare class VoiceHub {
|
|
42
49
|
private readonly opts;
|
|
43
50
|
readonly store: ProfileStore;
|
|
44
51
|
private jobs;
|
|
45
|
-
/**
|
|
52
|
+
/** 正在生成的段:项目 → (片段键 → 结果)。批量生成与边放边生成共用,同一段只请求一次。 */
|
|
46
53
|
private inflight;
|
|
54
|
+
private inflightOf;
|
|
47
55
|
constructor(home: string, opts: {
|
|
48
56
|
emit: (projectId: string, state: VoiceState) => void;
|
|
57
|
+
profilesChanged?: () => void;
|
|
49
58
|
fetch?: FetchLike;
|
|
50
59
|
env?: Record<string, string | undefined>;
|
|
51
60
|
});
|
package/dist/voice-http.js
CHANGED
|
@@ -2,28 +2,44 @@
|
|
|
2
2
|
* 朗读(D74)的看板接口。写接口都经 dev.ts 的 guardWrite(Origin + 本机令牌 + JSON)。
|
|
3
3
|
*
|
|
4
4
|
* 全局(本机):
|
|
5
|
-
* - GET /__joplo/voice/profiles → { profiles: PublicProfile[] }(不含 Key
|
|
5
|
+
* - GET /__joplo/voice/profiles → { profiles: PublicProfile[], file }(不含 Key;file = 本机存储文件,所有项目共用)
|
|
6
6
|
* - PUT /__joplo/voice/profiles/:id|new { profile, key? } → { profile, profiles }(key:省略 = 不改,null / '' = 删掉)
|
|
7
7
|
* - DELETE /__joplo/voice/profiles/:id → { profiles }(自建的删除,预设恢复默认)
|
|
8
|
+
* 保存、删除成功后调 opts.profilesChanged:dev.ts 推 joplo:voice { profilesChanged },打开着的看板重新取自己项目的声音状态
|
|
9
|
+
* (Key 是否保存、音色、声音指纹都可能变了)。
|
|
8
10
|
* - POST /__joplo/voice/test { id?, profile?, key?, text? } → { ok: true, audio: data URL, bytes, contentType }
|
|
9
11
|
* | { ok: false, error: { code, message, hint? } }(hint = 建议的返回内容与字段路径)
|
|
10
12
|
* 项目:
|
|
11
13
|
* - GET /__joplo/p/:id/voice → VoiceState
|
|
12
14
|
* - PUT /__joplo/p/:id/voice { profileId | null } → VoiceState(看板里选的,记在 .joplo/voice/index.json)
|
|
13
|
-
* - POST /__joplo/p/:id/voice/clip { locale, segment: { stepId, text, role } } → { key, url }
|
|
15
|
+
* - POST /__joplo/p/:id/voice/clip { locale, segment: { stepId, text, role } } → { key, url }(边放边生成一段;与批量生成共用 inflight,同一段并发只生成一次)
|
|
14
16
|
* - POST /__joplo/p/:id/voice/generate { locale, segments: [{ stepId, text, role }] } → { summary, state };进度推 joplo:voice
|
|
15
17
|
* - GET /__joplo/p/:id/voice/clips/:file → 音频
|
|
16
18
|
*/
|
|
17
19
|
import fs from 'node:fs';
|
|
20
|
+
import os from 'node:os';
|
|
21
|
+
import path from 'node:path';
|
|
18
22
|
import { AUDIO_TYPES, ProfileStore, VoiceCache, VoiceError, normalizeProfile, resolveVoices, synthesize } from "./voice.js";
|
|
19
23
|
const MAX_SEGMENTS = 2000;
|
|
24
|
+
let lastRev = 0;
|
|
25
|
+
const nextRev = () => (lastRev = Math.max(lastRev + 1, Date.now() * 1000));
|
|
26
|
+
/** 用户目录写成 ~(看板显示 profile 存在哪里;不在用户目录下时原样)。 */
|
|
27
|
+
export function tildify(file, home = os.homedir()) {
|
|
28
|
+
return home && (file === home || file.startsWith(home + path.sep)) ? '~' + file.slice(home.length) : file;
|
|
29
|
+
}
|
|
20
30
|
const MAX_TEXT = 2000;
|
|
21
31
|
export class VoiceHub {
|
|
22
32
|
opts;
|
|
23
33
|
store;
|
|
24
34
|
jobs = new Map();
|
|
25
|
-
/**
|
|
35
|
+
/** 正在生成的段:项目 → (片段键 → 结果)。批量生成与边放边生成共用,同一段只请求一次。 */
|
|
26
36
|
inflight = new Map();
|
|
37
|
+
inflightOf(projectId) {
|
|
38
|
+
let m = this.inflight.get(projectId);
|
|
39
|
+
if (!m)
|
|
40
|
+
this.inflight.set(projectId, (m = new Map()));
|
|
41
|
+
return m;
|
|
42
|
+
}
|
|
27
43
|
constructor(home, opts) {
|
|
28
44
|
this.opts = opts;
|
|
29
45
|
this.store = new ProfileStore(home, opts.env ?? process.env);
|
|
@@ -38,7 +54,7 @@ export class VoiceHub {
|
|
|
38
54
|
async handleGlobal(rest, req, ctx) {
|
|
39
55
|
const method = req.method ?? 'GET';
|
|
40
56
|
if (rest === 'profiles' && method === 'GET')
|
|
41
|
-
return ctx.send(200, { profiles: this.profiles() }), true;
|
|
57
|
+
return ctx.send(200, { profiles: this.profiles(), file: tildify(this.store.file) }), true;
|
|
42
58
|
const pm = /^profiles\/([a-z0-9][a-z0-9_-]{0,39}|new)$/.exec(rest);
|
|
43
59
|
if (pm && method === 'PUT') {
|
|
44
60
|
if (!ctx.guardWrite())
|
|
@@ -51,6 +67,7 @@ export class VoiceHub {
|
|
|
51
67
|
const key = body.key === undefined ? undefined : body.key === null ? null : typeof body.key === 'string' ? body.key : (() => { throw new VoiceError('INVALID', 'key must be a string or null'); })();
|
|
52
68
|
const saved = this.store.upsert(pm[1] === 'new' ? null : pm[1], body.profile, key);
|
|
53
69
|
ctx.send(200, { profile: this.store.publicOf(saved), profiles: this.profiles() });
|
|
70
|
+
this.opts.profilesChanged?.();
|
|
54
71
|
}
|
|
55
72
|
catch (e) {
|
|
56
73
|
this.error(ctx, e);
|
|
@@ -63,6 +80,7 @@ export class VoiceHub {
|
|
|
63
80
|
try {
|
|
64
81
|
this.store.remove(pm[1]);
|
|
65
82
|
ctx.send(200, { profiles: this.profiles() });
|
|
83
|
+
this.opts.profilesChanged?.();
|
|
66
84
|
}
|
|
67
85
|
catch (e) {
|
|
68
86
|
this.error(ctx, e);
|
|
@@ -108,6 +126,7 @@ export class VoiceHub {
|
|
|
108
126
|
const job = this.jobs.get(projectId);
|
|
109
127
|
const enc = encodeURIComponent;
|
|
110
128
|
return {
|
|
129
|
+
rev: nextRev(),
|
|
111
130
|
selected: idx.profileId,
|
|
112
131
|
source: r.source,
|
|
113
132
|
missing: r.missing,
|
|
@@ -161,6 +180,7 @@ export class VoiceHub {
|
|
|
161
180
|
summary = await cache.generate(segs, typeof body.locale === 'string' ? body.locale.slice(0, 20) : 'en', resolved, this.store, {
|
|
162
181
|
fetch: this.opts.fetch,
|
|
163
182
|
signal: job.abort.signal,
|
|
183
|
+
inflight: this.inflightOf(projectId),
|
|
164
184
|
onProgress: (done, total, failed) => {
|
|
165
185
|
Object.assign(job, { done, total, failed });
|
|
166
186
|
this.opts.emit(projectId, this.state(projectId, dir, project));
|
|
@@ -190,12 +210,7 @@ export class VoiceHub {
|
|
|
190
210
|
const plan = cache.plan(seg, resolved);
|
|
191
211
|
if (!plan)
|
|
192
212
|
return ctx.send(400, { error: { code: 'INVALID', message: 'No voice provider is selected for this project' } }), true;
|
|
193
|
-
const
|
|
194
|
-
let p = this.inflight.get(k);
|
|
195
|
-
if (!p) {
|
|
196
|
-
p = cache.generateOne(seg, typeof body.locale === 'string' ? body.locale.slice(0, 20) : 'en', resolved, this.store, { fetch: this.opts.fetch }).finally(() => this.inflight.delete(k));
|
|
197
|
-
this.inflight.set(k, p);
|
|
198
|
-
}
|
|
213
|
+
const p = cache.generateOne(seg, typeof body.locale === 'string' ? body.locale.slice(0, 20) : 'en', resolved, this.store, { fetch: this.opts.fetch, inflight: this.inflightOf(projectId) });
|
|
199
214
|
try {
|
|
200
215
|
const r = await p;
|
|
201
216
|
if (r.generated)
|
package/dist/voice.d.ts
CHANGED
|
@@ -148,6 +148,13 @@ export type ClipRecord = {
|
|
|
148
148
|
bytes: number;
|
|
149
149
|
at: string;
|
|
150
150
|
};
|
|
151
|
+
export type GeneratedClip = {
|
|
152
|
+
key: string;
|
|
153
|
+
file: string;
|
|
154
|
+
generated: boolean;
|
|
155
|
+
};
|
|
156
|
+
/** 正在生成的片段:片段键 → 结果(每个项目一张,见 VoiceCache.generateOne)。 */
|
|
157
|
+
export type Inflight = Map<string, Promise<GeneratedClip>>;
|
|
151
158
|
type IndexFile = {
|
|
152
159
|
version: 1;
|
|
153
160
|
profileId: string | null;
|
|
@@ -197,6 +204,7 @@ export declare class VoiceCache {
|
|
|
197
204
|
*/
|
|
198
205
|
/** 记一段成功:重新读索引再写(看板的批量生成与边放边生成可能同时进行,不能互相覆盖)。 */
|
|
199
206
|
private record;
|
|
207
|
+
/** 记一段失败;这一段已经有音频(别的请求先成功了)时不记。 */
|
|
200
208
|
private recordFailure;
|
|
201
209
|
/** 这一段的键与要用的音色;文字为空或没有供应商时为 null。 */
|
|
202
210
|
plan(seg: Segment, resolved: ResolvedVoices): {
|
|
@@ -207,21 +215,23 @@ export declare class VoiceCache {
|
|
|
207
215
|
} | null;
|
|
208
216
|
/** 已有的片段文件名(文件还在时)。 */
|
|
209
217
|
clipOf(key: string): string | null;
|
|
210
|
-
/**
|
|
218
|
+
/**
|
|
219
|
+
* 生成一段(已有就直接返回):返回文件名;失败记进 failures 并抛 VoiceError。
|
|
220
|
+
* inflight:同一个项目共用的“正在生成”表(片段键 → 结果)。批量生成与边放边生成传同一张表,同一段同时只请求一次,后来的等先来的结果(generated 为 false)。
|
|
221
|
+
*/
|
|
211
222
|
generateOne(seg: Segment, locale: string, resolved: ResolvedVoices, store: ProfileStore, opts?: {
|
|
212
223
|
fetch?: FetchLike;
|
|
213
224
|
signal?: AbortSignal;
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
generated: boolean;
|
|
218
|
-
}>;
|
|
225
|
+
inflight?: Inflight;
|
|
226
|
+
}): Promise<GeneratedClip>;
|
|
227
|
+
private synthesizeOne;
|
|
219
228
|
/**
|
|
220
229
|
* 生成缺的片段(已有的跳过),并发 2。每段完成后调 onProgress。失败记进 failures,成功时清掉这个键的失败。
|
|
221
230
|
*/
|
|
222
231
|
generate(segments: Segment[], locale: string, resolved: ResolvedVoices, store: ProfileStore, opts?: {
|
|
223
232
|
fetch?: FetchLike;
|
|
224
233
|
signal?: AbortSignal;
|
|
234
|
+
inflight?: Inflight;
|
|
225
235
|
onProgress?: (done: number, total: number, failed: number) => void;
|
|
226
236
|
}): Promise<GenerateSummary>;
|
|
227
237
|
}
|
package/dist/voice.js
CHANGED
|
@@ -475,7 +475,10 @@ export class VoiceCache {
|
|
|
475
475
|
delete idx.failures[k];
|
|
476
476
|
this.write(idx);
|
|
477
477
|
}
|
|
478
|
+
/** 记一段失败;这一段已经有音频(别的请求先成功了)时不记。 */
|
|
478
479
|
recordFailure(k, stepId, message) {
|
|
480
|
+
if (this.clipOf(k))
|
|
481
|
+
return;
|
|
479
482
|
const idx = this.read();
|
|
480
483
|
idx.failures[k] = { stepId, message, at: new Date().toISOString() };
|
|
481
484
|
this.write(idx);
|
|
@@ -495,7 +498,10 @@ export class VoiceCache {
|
|
|
495
498
|
const c = this.read().clips[key];
|
|
496
499
|
return c && FILE_RE.test(c.file) && fs.existsSync(path.join(this.clipsDir, c.file)) ? c.file : null;
|
|
497
500
|
}
|
|
498
|
-
/**
|
|
501
|
+
/**
|
|
502
|
+
* 生成一段(已有就直接返回):返回文件名;失败记进 failures 并抛 VoiceError。
|
|
503
|
+
* inflight:同一个项目共用的“正在生成”表(片段键 → 结果)。批量生成与边放边生成传同一张表,同一段同时只请求一次,后来的等先来的结果(generated 为 false)。
|
|
504
|
+
*/
|
|
499
505
|
async generateOne(seg, locale, resolved, store, opts = {}) {
|
|
500
506
|
const p = resolved.profile;
|
|
501
507
|
const j = this.plan(seg, resolved);
|
|
@@ -504,6 +510,20 @@ export class VoiceCache {
|
|
|
504
510
|
const have = this.clipOf(j.key);
|
|
505
511
|
if (have)
|
|
506
512
|
return { key: j.key, file: have, generated: false };
|
|
513
|
+
const running = opts.inflight?.get(j.key);
|
|
514
|
+
if (running)
|
|
515
|
+
return { ...(await running), generated: false };
|
|
516
|
+
const run = this.synthesizeOne(seg, locale, p, j, store, opts);
|
|
517
|
+
opts.inflight?.set(j.key, run);
|
|
518
|
+
try {
|
|
519
|
+
return await run;
|
|
520
|
+
}
|
|
521
|
+
finally {
|
|
522
|
+
if (opts.inflight?.get(j.key) === run)
|
|
523
|
+
opts.inflight.delete(j.key);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
async synthesizeOne(seg, locale, p, j, store, opts) {
|
|
507
527
|
const key = store.keyOf(p);
|
|
508
528
|
try {
|
|
509
529
|
if (!key && p.kind !== 'http')
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@joplo-app/server",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.13",
|
|
4
4
|
"description": "Joplo 本地服务:dev 看板、build 发布站、render 截图",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -15,15 +15,16 @@
|
|
|
15
15
|
"dist"
|
|
16
16
|
],
|
|
17
17
|
"dependencies": {
|
|
18
|
-
"@joplo-app/core": "0.2.
|
|
19
|
-
"@joplo-app/kit": "0.2.
|
|
20
|
-
"@joplo-app/web": "0.2.
|
|
18
|
+
"@joplo-app/core": "0.2.13",
|
|
19
|
+
"@joplo-app/kit": "0.2.13",
|
|
20
|
+
"@joplo-app/web": "0.2.13",
|
|
21
21
|
"@tailwindcss/vite": "4.3.4",
|
|
22
22
|
"tailwindcss": "4.3.4",
|
|
23
23
|
"vite": "8.3.5",
|
|
24
24
|
"zod": "4.6.7"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
|
+
"@joplo-app/core-legacy": "npm:@joplo-app/core@0.2.10",
|
|
27
28
|
"@vitejs/plugin-react": "6.2.1",
|
|
28
29
|
"playwright": "1.64.1",
|
|
29
30
|
"playwright-core": "1.64.1"
|