@joplo-app/server 0.2.10 → 0.2.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/dist/build.d.ts CHANGED
@@ -12,6 +12,7 @@ export declare const jsonForHtml: (v: unknown) => string;
12
12
  export declare function finalizeHtml(html: string, readAsset: (rel: string) => string, inline: {
13
13
  project: unknown;
14
14
  home: string | null;
15
+ scoped?: true;
15
16
  }): {
16
17
  html: string;
17
18
  inlined: string[];
package/dist/build.js CHANGED
@@ -19,7 +19,7 @@ import os from 'node:os';
19
19
  import path from 'node:path';
20
20
  import tailwindcss from '@tailwindcss/vite';
21
21
  import { build as viteBuild, createServer } from 'vite';
22
- import { JoploError, orderedFeatures } from '@joplo-app/core';
22
+ import { hasScope, JoploError, orderedFeatures, resolveScope, scopeProject } from '@joplo-app/core';
23
23
  import { compileProject } from "./project.js";
24
24
  import { joploProjectPlugin, kitAliases, locateWebAssets, realProjectDir } from "./vite-shared.js";
25
25
  import { subsetSiteFonts } from "./site-fonts.js";
@@ -120,8 +120,18 @@ export async function buildSite(opts) {
120
120
  const errs = compiled.diagnostics.filter((d) => d.severity === 'error');
121
121
  throw new JoploError('EXPORT_FAILED', `Project compilation failed; no published site was generated: \n${errs.map((d) => `${d.at ?? ''} ${d.message}`).join('\n')}`, { diagnostics: compiled.diagnostics });
122
122
  }
123
- const project = compiled.project;
123
+ // 按场景保密分享(D75):先裁剪 IR,再生成产物;写错范围在写任何文件之前报错
124
+ let project = compiled.project;
125
+ let scope;
126
+ if (hasScope(opts.scope)) {
127
+ const mode = opts.review === true ? 'review' : 'publish';
128
+ const r = scopeProject(project, resolveScope(project, opts.scope, mode), mode);
129
+ project = r.project;
130
+ scope = r.info;
131
+ }
124
132
  const inline = publishPayload(project, compiled.home);
133
+ if (scope)
134
+ inline.scoped = true;
125
135
  // 2. vite build 到临时目录
126
136
  const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'joplo-build-'));
127
137
  let voiceReport;
@@ -135,8 +145,9 @@ export async function buildSite(opts) {
135
145
  await buildSourceSite(web, projectDir, staging);
136
146
  // 朗读(D74):当前声音已生成的音频拷进 voice/,IR 带上 voiceIndex;Key 不进产物
137
147
  const voice = bundleVoice(projectDir, project, staging, new ProfileStore(opts.home ?? joploHome()));
148
+ // 朗读角色只留范围内功能的(scopeProject 对 voiceIndex 的同一规则;bundleVoice 按声音配置生成全部角色)
138
149
  if (voice.index)
139
- inline.project.voiceIndex = voice.index;
150
+ inline.project.voiceIndex = scope ? scopeProject({ ...project, voiceIndex: voice.index }, scope.scenarios).project.voiceIndex : voice.index;
140
151
  voiceReport = voice.report;
141
152
  // 3. 后处理
142
153
  const siteHtml = path.join(staging, 'site.html');
@@ -167,6 +178,7 @@ export async function buildSite(opts) {
167
178
  scenarios: Object.keys(project.scenarios),
168
179
  diagnostics: compiled.diagnostics,
169
180
  ...(voiceReport && (voiceReport.clips || voiceReport.profile) ? { voice: voiceReport } : {}),
181
+ ...(scope ? { scope } : {}),
170
182
  };
171
183
  }
172
184
  /** 仓库里:直接编译 packages/web 的发布站入口。 */
@@ -0,0 +1,85 @@
1
+ /**
2
+ * 看板直接发布到云端(D76)。云端能力(登录、构建、上传)在 CLI 里,由 `joplo dev` 启动看板时注入(CloudBridge);
3
+ * 看板只转发请求、记录发布任务、把进度推给页面。令牌只在本机进程里,页面只拿到账号邮箱和套餐。
4
+ *
5
+ * 数据流:
6
+ * - 账号:`GET /__joplo/cloud/account`(本机令牌)→ bridge.account() → 浮层的“已登录 / 需要登录(可复制的登录命令)”。
7
+ * - 发布:`POST /__joplo/p/<id>/cloud/publish`(令牌 + Origin + JSON,body = 范围)→ bridge.publish()(即 CLI 的 share())
8
+ * → 任务状态(running → done / failed)存在 CloudHub,变化时推 `joplo:cloud`;`GET …/cloud/publish` 读当前任务。
9
+ * - 同一项目同时只有一个发布任务:再次 POST 返回正在进行的那个,不另起。
10
+ * - 旧版 CLI 启动的看板没有 bridge:account 返回 available: false,页面禁用这一项并提示重启 joplo dev。
11
+ */
12
+ import type http from 'node:http';
13
+ import type { ScopeInfo } from '@joplo-app/core';
14
+ export declare const CLOUD_EVENT = "joplo:cloud";
15
+ export type CloudAccount = {
16
+ signedIn: true;
17
+ server: string;
18
+ email: string;
19
+ plan: 'free' | 'pro' | null;
20
+ } | {
21
+ signedIn: false;
22
+ server: string;
23
+ loginCommand: string;
24
+ message?: string;
25
+ };
26
+ /** 范围:都为空 = 整个项目(D75)。 */
27
+ export type CloudPublishRequest = {
28
+ scenarios?: string[];
29
+ features?: string[];
30
+ };
31
+ export type CloudPublishResult = {
32
+ shareId: string;
33
+ url: string;
34
+ expiresAt: string | null;
35
+ version: number;
36
+ plan: 'free' | 'pro';
37
+ scope?: ScopeInfo;
38
+ };
39
+ /** CLI 实现:account 只读本机登录(必要时问一次云端套餐);publish 就是 share(),progress 是它写给终端的每一行。 */
40
+ export type CloudBridge = {
41
+ account(): Promise<CloudAccount>;
42
+ publish(projectDir: string, request: CloudPublishRequest, progress: (line: string) => void): Promise<CloudPublishResult>;
43
+ };
44
+ /** 发布失败:code 来自 CLI(AUTH_REQUIRED、NOT_FOUND、NETWORK…);需要登录时带 loginCommand。 */
45
+ export type CloudJobError = {
46
+ code: string;
47
+ message: string;
48
+ loginCommand?: string;
49
+ };
50
+ export type CloudJob = {
51
+ id: string;
52
+ state: 'running' | 'done' | 'failed';
53
+ request: CloudPublishRequest;
54
+ startedAt: number;
55
+ /** 进度:CLI 写给终端的行(英文,页面按开头识别阶段)。 */
56
+ lines: string[];
57
+ result?: CloudPublishResult;
58
+ error?: CloudJobError;
59
+ };
60
+ type Ctx = {
61
+ guardWrite: (needJson?: boolean) => boolean;
62
+ jsonBody: () => Promise<{
63
+ ok: true;
64
+ body: unknown;
65
+ } | {
66
+ ok: false;
67
+ }>;
68
+ send: (status: number, body: unknown) => void;
69
+ };
70
+ export declare class CloudHub {
71
+ private readonly bridge;
72
+ private readonly emit;
73
+ private jobs;
74
+ private seq;
75
+ constructor(bridge: CloudBridge | undefined, emit: (projectId: string, job: CloudJob) => void);
76
+ get available(): boolean;
77
+ /** `/__joplo/cloud/<sub>`:sub = 'account'。 */
78
+ handleGlobal(sub: string, req: http.IncomingMessage, ctx: Ctx): Promise<boolean>;
79
+ /** `/__joplo/p/<id>/cloud/<sub>`:sub = 'publish'(GET 读任务,POST 开始发布)。 */
80
+ handleProject(projectId: string, dir: string, sub: string, req: http.IncomingMessage, ctx: Ctx): Promise<boolean>;
81
+ private start;
82
+ /** 测试:等当前任务结束。 */
83
+ settled(projectId: string): Promise<CloudJob | null>;
84
+ }
85
+ export {};
package/dist/cloud.js ADDED
@@ -0,0 +1,110 @@
1
+ export const CLOUD_EVENT = 'joplo:cloud';
2
+ const MAX_LINES = 40;
3
+ const strings = (v, name) => {
4
+ if (v === undefined)
5
+ return undefined;
6
+ if (!Array.isArray(v) || v.length > 200 || v.some((x) => typeof x !== 'string' || !x || x.length > 512))
7
+ throw new Error(`${name} must be an array of non-empty strings`);
8
+ return v;
9
+ };
10
+ export class CloudHub {
11
+ bridge;
12
+ emit;
13
+ jobs = new Map();
14
+ seq = 0;
15
+ constructor(bridge, emit) {
16
+ this.bridge = bridge;
17
+ this.emit = emit;
18
+ }
19
+ get available() {
20
+ return !!this.bridge;
21
+ }
22
+ /** `/__joplo/cloud/<sub>`:sub = 'account'。 */
23
+ async handleGlobal(sub, req, ctx) {
24
+ if (sub !== 'account' || (req.method ?? 'GET') !== 'GET')
25
+ return false;
26
+ if (!ctx.guardWrite(false))
27
+ return true;
28
+ if (!this.bridge)
29
+ return ctx.send(200, { available: false }), true;
30
+ try {
31
+ ctx.send(200, { available: true, account: await this.bridge.account() });
32
+ }
33
+ catch (e) {
34
+ ctx.send(500, { error: { code: 'INTERNAL', message: e instanceof Error ? e.message : String(e) } });
35
+ }
36
+ return true;
37
+ }
38
+ /** `/__joplo/p/<id>/cloud/<sub>`:sub = 'publish'(GET 读任务,POST 开始发布)。 */
39
+ async handleProject(projectId, dir, sub, req, ctx) {
40
+ if (sub !== 'publish')
41
+ return false;
42
+ const method = req.method ?? 'GET';
43
+ if (method === 'GET') {
44
+ if (!ctx.guardWrite(false))
45
+ return true;
46
+ ctx.send(200, { available: this.available, job: this.jobs.get(projectId) ?? null });
47
+ return true;
48
+ }
49
+ if (method !== 'POST')
50
+ return false;
51
+ if (!ctx.guardWrite())
52
+ return true;
53
+ if (!this.bridge)
54
+ return ctx.send(409, { error: { code: 'UNSUPPORTED_ACTION', message: 'This board process cannot publish to the cloud. Stop it and run joplo dev again' } }), true;
55
+ const b = await ctx.jsonBody();
56
+ if (!b.ok)
57
+ return true;
58
+ let request;
59
+ try {
60
+ const body = (b.body ?? {});
61
+ const scenarios = strings(body.scenarios, 'scenarios');
62
+ const features = strings(body.features, 'features');
63
+ request = { ...(scenarios?.length ? { scenarios } : {}), ...(features?.length ? { features } : {}) };
64
+ }
65
+ catch (e) {
66
+ return ctx.send(400, { error: { code: 'USAGE', message: e instanceof Error ? e.message : String(e) } }), true;
67
+ }
68
+ const running = this.jobs.get(projectId);
69
+ if (running?.state === 'running')
70
+ return ctx.send(200, { job: running }), true;
71
+ ctx.send(202, { job: this.start(projectId, dir, request) });
72
+ return true;
73
+ }
74
+ start(projectId, dir, request) {
75
+ const job = { id: `c${++this.seq}`, state: 'running', request, startedAt: Date.now(), lines: [] };
76
+ this.jobs.set(projectId, job);
77
+ const push = () => this.emit(projectId, job);
78
+ push();
79
+ void this.bridge
80
+ .publish(dir, request, (line) => {
81
+ job.lines = [...job.lines, line].slice(-MAX_LINES);
82
+ push();
83
+ })
84
+ .then((result) => {
85
+ job.state = 'done';
86
+ job.result = result;
87
+ })
88
+ .catch((e) => {
89
+ const err = e;
90
+ job.state = 'failed';
91
+ job.error = {
92
+ code: typeof err.code === 'string' ? err.code : 'INTERNAL',
93
+ message: typeof err.message === 'string' ? err.message : String(e),
94
+ ...(typeof err.loginCommand === 'string' ? { loginCommand: err.loginCommand } : {}),
95
+ };
96
+ })
97
+ .finally(push);
98
+ return job;
99
+ }
100
+ /** 测试:等当前任务结束。 */
101
+ async settled(projectId) {
102
+ for (let i = 0; i < 2000; i++) {
103
+ const j = this.jobs.get(projectId);
104
+ if (!j || j.state !== 'running')
105
+ return j ?? null;
106
+ await new Promise((r) => setTimeout(r, 5));
107
+ }
108
+ return this.jobs.get(projectId) ?? null;
109
+ }
110
+ }
@@ -1,13 +1,20 @@
1
1
  /**
2
2
  * v2 接口(ADR-0002):CLI 只依赖这里导出的三个函数。由 T-board 实现,届时 index.ts 改为导出它们。
3
3
  */
4
- import type { AppearanceFont, AppearanceStroke, Diagnostic } from '@joplo-app/core';
4
+ import type { AppearanceFont, AppearanceStroke, Diagnostic, ScopeInfo, ScopeRequest } from '@joplo-app/core';
5
+ import type { CloudBridge } from './cloud.js';
6
+ export type { CloudAccount, CloudBridge, CloudJob, CloudJobError, CloudPublishRequest, CloudPublishResult } from './cloud.js';
5
7
  export type DevOptions = {
6
8
  projectDir: string;
7
9
  /** 缺省 4790;被占用时报错,不静默换端口。 */
8
10
  port?: number;
9
11
  open?: boolean;
10
12
  log?: (line: string) => void;
13
+ /**
14
+ * 直接发布到云端(D76):CLI 注入登录与 share();看板「导出 ▾」里的「发布到 Joplo Cloud」用它。
15
+ * 只在本进程启动看板时生效(加入已有看板时,那个进程用它自己的)。
16
+ */
17
+ cloud?: CloudBridge;
11
18
  };
12
19
  /** 单进程:同一个 JOPLO_HOME 下只有一个看板进程,同时服务多个项目(编译、热更新、选中、导出)。 */
13
20
  /**
@@ -32,6 +39,11 @@ export type BuildOptions = {
32
39
  review?: boolean;
33
40
  /** 本机目录(缺省 JOPLO_HOME 或 ~/.joplo):读声音供应商 profile(D74);测试指向临时目录。 */
34
41
  home?: string;
42
+ /**
43
+ * 按场景保密分享(D75,`--scenario` / `--feature`):构建时把 IR 裁剪到这些场景,产物里不出现范围外的功能、方案、场景。
44
+ * 缺省(或两个数组都为空)时与原来完全一致。写错场景 / 功能时报错,不写任何文件。
45
+ */
46
+ scope?: ScopeRequest;
35
47
  };
36
48
  /** 静态发布站:只含选定方案(compile 的 publish 模式),离线可打开,可直接 `wrangler deploy`。 */
37
49
  /**
@@ -49,7 +61,8 @@ export type BuildResult = {
49
61
  bytes: number;
50
62
  missing: number;
51
63
  profile: string | null;
52
- };
64
+ }; /** 有 scope 时:范围与借用了哪些别的功能的内容(D75)。 */
65
+ scope?: ScopeInfo;
53
66
  };
54
67
  export declare function buildSite(opts: BuildOptions): Promise<BuildResult>;
55
68
  export type RenderOptions = {
@@ -73,6 +86,8 @@ export type RenderOptions = {
73
86
  height: number;
74
87
  };
75
88
  scale?: number;
89
+ /** 按场景保密分享(D75):只用这些场景裁剪后的 IR 渲染(share 的预览图),画面上不出现范围外功能堆进来的元素。 */
90
+ scope?: string[];
76
91
  };
77
92
  export type RenderedElement = {
78
93
  id: string;
package/dist/dev.d.ts CHANGED
@@ -3,6 +3,7 @@ import { type ViteDevServer } from 'vite';
3
3
  import { type Diagnostic, type Project } from '@joplo-app/core';
4
4
  import type { DevHandle, DevOptions } from './contract.js';
5
5
  import { type ExportDeps } from './export.js';
6
+ import { CLOUD_EVENT, type CloudBridge } from './cloud.js';
6
7
  import type { DistWeb } from './web-assets.js';
7
8
  /** 推给看板的编译结果。`project` 始终是最近一次成功的 IR;`ok=false` 时看板显示错误列表、保留画面。 */
8
9
  export type DevPayload = {
@@ -26,6 +27,7 @@ export declare const IR_EVENT = "joplo:ir";
26
27
  export declare const PROJECTS_EVENT = "joplo:projects";
27
28
  /** 朗读状态变化(D74):{ projectId, state }。 */
28
29
  export declare const VOICE_EVENT = "joplo:voice";
30
+ export { CLOUD_EVENT };
29
31
  export declare function sendJson(res: http.ServerResponse, status: number, body: unknown): void;
30
32
  /** Content-Type 必须是 application/json,只允许附带 charset=utf-8 参数。 */
31
33
  export declare function isJsonContentType(ct: string | undefined): boolean;
@@ -56,6 +58,8 @@ export type HubOptions = {
56
58
  exportDeps?: Partial<ExportDeps>;
57
59
  /** 启动这个看板的项目目录(写进 server.json,后来加入的 joplo dev 会说明)。 */
58
60
  startedIn?: string;
61
+ /** 直接发布到云端(D76):由 CLI 注入;没有时看板禁用「发布到 Joplo Cloud」。 */
62
+ cloud?: CloudBridge;
59
63
  };
60
64
  export declare function serverVersion(): string;
61
65
  export type Hub = {
@@ -77,7 +81,7 @@ export type Hub = {
77
81
  close(): Promise<void>;
78
82
  };
79
83
  export declare function createHub(opts?: HubOptions): Promise<Hub>;
80
- export type InternalDevOptions = DevOptions & Pick<HubOptions, 'watch' | 'home' | 'exportDeps'>;
84
+ export type InternalDevOptions = DevOptions & Pick<HubOptions, 'watch' | 'home' | 'exportDeps' | 'cloud'>;
81
85
  export type InternalDevHandle = DevHandle & {
82
86
  token: string;
83
87
  port: number;
package/dist/dev.js CHANGED
@@ -18,9 +18,11 @@ import fs from 'node:fs';
18
18
  import path from 'node:path';
19
19
  import tailwindcss from '@tailwindcss/vite';
20
20
  import { createLogger, createServer } from 'vite';
21
- import { JoploError } from '@joplo-app/core';
21
+ import { JoploError, LocalReviewWrite } from '@joplo-app/core';
22
+ import { LocalReviewHub } from "./local-review.js";
22
23
  import { ExportHub } from "./export.js";
23
24
  import { VoiceHub } from "./voice-http.js";
25
+ import { CLOUD_EVENT, CloudHub } from "./cloud.js";
24
26
  import { Registry, clearServerInfo, joploHome, normalizeSettings, pidAlive, projectIdOf, readServerInfo, readSettings, writeServerInfo, writeSettings } from "./home.js";
25
27
  import { compileProject, invalidateProjectModules } from "./project.js";
26
28
  import { SelectionBody, readSelection, resolveSelection, writeSelection } from "./selection.js";
@@ -29,6 +31,7 @@ export const IR_EVENT = 'joplo:ir';
29
31
  export const PROJECTS_EVENT = 'joplo:projects';
30
32
  /** 朗读状态变化(D74):{ projectId, state }。 */
31
33
  export const VOICE_EVENT = 'joplo:voice';
34
+ export { CLOUD_EVENT };
32
35
  const MAX_BODY = 64 * 1024;
33
36
  const SECURITY_HEADERS = {
34
37
  'x-content-type-options': 'nosniff',
@@ -174,6 +177,7 @@ export async function createHub(opts = {}) {
174
177
  const allowedHosts = () => new Set([`127.0.0.1:${actualPort}`, `localhost:${actualPort}`]);
175
178
  const allowedOrigins = () => new Set([`http://127.0.0.1:${actualPort}`, `http://localhost:${actualPort}`]);
176
179
  const baseUrl = () => `http://127.0.0.1:${actualPort}/`;
180
+ const reviewHub = new LocalReviewHub(baseUrl);
177
181
  const activeDirs = () => [...slots.values()].filter((s) => !s.closed).map((s) => s.dir);
178
182
  const slotOfFile = (file) => [...slots.values()].find((s) => !s.closed && isProjectSource(s.dir, file)) ?? null;
179
183
  const recordOf = (id) => registry.list().find((r) => projectIdOf(r.dir) === id) ?? null;
@@ -216,6 +220,10 @@ export async function createHub(opts = {}) {
216
220
  log(`[joplo] ${path.basename(slot.dir)} compilation failed (${errors.length}): ${errors.map((d) => `${d.at ?? ''} ${d.message}`).join('; ').slice(0, 400)}`);
217
221
  if (out.project && out.project.name)
218
222
  registry.rename(slot.dir, out.project.name);
223
+ if (out.project && !errors.length)
224
+ reviewHub.sync(slot.dir, slot.id, out.project);
225
+ else
226
+ reviewHub.invalidate(slot.dir, 'compile_error');
219
227
  if (!closed)
220
228
  server?.ws.send({ type: 'custom', event: IR_EVENT, data: { projectId: slot.id, ...slot.payload } });
221
229
  broadcastProjects();
@@ -236,6 +244,7 @@ export async function createHub(opts = {}) {
236
244
  await recompile(slot);
237
245
  }
238
246
  catch (e) {
247
+ reviewHub.invalidate(slot.dir, 'compile_error');
239
248
  log(`[joplo] Compilation exception: ${e instanceof Error ? e.message : String(e)}`);
240
249
  }
241
250
  } while (slot.dirty && !slot.closed);
@@ -277,6 +286,7 @@ export async function createHub(opts = {}) {
277
286
  if (slot.timer)
278
287
  clearTimeout(slot.timer);
279
288
  await slot.running?.catch(() => undefined);
289
+ reviewHub.invalidate(slot.dir, 'server_stopped');
280
290
  await slot.loader?.close().catch(() => undefined);
281
291
  if (watch && server)
282
292
  server.watcher.unwatch(slot.dir);
@@ -331,6 +341,16 @@ export async function createHub(opts = {}) {
331
341
  if (!closed)
332
342
  server?.ws.send({ type: 'custom', event: VOICE_EVENT, data: { projectId, state } });
333
343
  },
344
+ // profile 是本机共用的:改了就通知所有看板,各自重新取自己项目的声音状态
345
+ profilesChanged: () => {
346
+ if (!closed)
347
+ server?.ws.send({ type: 'custom', event: VOICE_EVENT, data: { profilesChanged: true } });
348
+ },
349
+ });
350
+ // 直接发布到云端(D76):发布任务变化推 joplo:cloud
351
+ const cloudHub = new CloudHub(opts.cloud, (projectId, job) => {
352
+ if (!closed)
353
+ server?.ws.send({ type: 'custom', event: CLOUD_EVENT, data: { projectId, job } });
334
354
  });
335
355
  // ---------- HTTP ----------
336
356
  const deny = (res, status, message) => sendJson(res, status, { error: { code: 'PERMISSION_DENIED', message } });
@@ -359,11 +379,31 @@ export async function createHub(opts = {}) {
359
379
  };
360
380
  const fail = (res, e) => {
361
381
  const code = e instanceof JoploError ? e.code : 'INTERNAL';
362
- const status = code === 'NOT_FOUND' ? 404 : code === 'USAGE' ? 400 : code === 'RENDER_FAILED' || code === 'EXPORT_COMPONENT_MISSING' ? 503 : 500;
382
+ const status = code === 'NOT_FOUND' ? 404 : code === 'USAGE' || code === 'INVALID_REFERENCE' ? 400 : code === 'REVISION_CONFLICT' || code === 'IDEMPOTENCY_MISMATCH' ? 409 : code === 'RENDER_FAILED' || code === 'EXPORT_COMPONENT_MISSING' ? 503 : 500;
363
383
  sendJson(res, status, { error: { code, message: e instanceof Error ? e.message : String(e) } });
364
384
  };
365
385
  async function handleProject(id, rest, req, res) {
366
386
  const method = req.method ?? 'GET';
387
+ if (rest === 'review' && (method === 'GET' || method === 'POST')) {
388
+ if (!guardWrite(req, res, 403, method === 'POST'))
389
+ return;
390
+ const slot = await ensure(id);
391
+ if (slot.compiling || slot.dirty || slot.timer || !slot.payload.ok || !slot.payload.project || slot.payload.diagnostics.some(d => d.severity === 'error'))
392
+ throw new JoploError('REVISION_CONFLICT', 'Wait for the project to compile successfully before reviewing');
393
+ if (method === 'GET') {
394
+ const optionId = new URL(req.url, baseUrl()).searchParams.get('option');
395
+ if (!optionId)
396
+ throw new JoploError('USAGE', 'option is required');
397
+ return sendJson(res, 200, reviewHub.state(slot.dir, optionId));
398
+ }
399
+ const body = await jsonBody(req, res);
400
+ if (!body.ok)
401
+ return;
402
+ const input = LocalReviewWrite.safeParse(body.body);
403
+ if (!input.success)
404
+ throw new JoploError('USAGE', 'Invalid review request: include a sessionId, requestId, type, and page context for feedback (1–10000 characters)');
405
+ return sendJson(res, 200, reviewHub.write(slot.dir, slot.payload.project, input.data));
406
+ }
367
407
  if (rest === 'ir' && method === 'GET') {
368
408
  const slot = await ensure(id);
369
409
  return sendJson(res, 200, { projectId: id, ...slot.payload });
@@ -422,6 +462,12 @@ export async function createHub(opts = {}) {
422
462
  if (await voiceHub.handleProject(id, slot.dir, slot.payload.project, rest === 'voice' ? '' : rest.slice('voice/'.length), req, res, ctx))
423
463
  return;
424
464
  }
465
+ if (rest.startsWith('cloud/')) {
466
+ const slot = await ensure(id);
467
+ const ctx = { guardWrite: (needJson = true) => guardWrite(req, res, 403, needJson), jsonBody: () => jsonBody(req, res), send: (status, body) => sendJson(res, status, body) };
468
+ if (await cloudHub.handleProject(id, slot.dir, rest.slice('cloud/'.length), req, ctx))
469
+ return;
470
+ }
425
471
  if (rest.startsWith('export/')) {
426
472
  const slot = await ensure(id);
427
473
  return exportsHub.handle(rest.slice('export/'.length), req, res, { projectId: id, dir: slot.dir, project: slot.payload.project, guardWrite: (needJson = true) => guardWrite(req, res, 403, needJson), jsonBody: () => jsonBody(req, res), fail: (e) => fail(res, e) });
@@ -495,6 +541,11 @@ export async function createHub(opts = {}) {
495
541
  if (await voiceHub.handleGlobal(url.pathname.slice('/__joplo/voice/'.length), req, ctx))
496
542
  return;
497
543
  }
544
+ if (url.pathname.startsWith('/__joplo/cloud/')) {
545
+ const ctx = { guardWrite: (needJson = true) => guardWrite(req, res, 403, needJson), jsonBody: () => jsonBody(req, res), send: (status, body) => sendJson(res, status, body) };
546
+ if (await cloudHub.handleGlobal(url.pathname.slice('/__joplo/cloud/'.length), req, ctx))
547
+ return;
548
+ }
498
549
  if (url.pathname.startsWith('/__joplo/export-runtime/'))
499
550
  return exportsHub.handleRuntime(url.pathname.slice('/__joplo/export-runtime/'.length), req, res, { guardWrite: (needJson = true) => guardWrite(req, res, 403, needJson), jsonBody: () => jsonBody(req, res), fail: (e) => fail(res, e) });
500
551
  const pm = /^\/__joplo\/p\/([^/]+)\/(.+)$/.exec(url.pathname);
@@ -573,9 +624,10 @@ export async function createHub(opts = {}) {
573
624
  const slot = slotOfFile(path.resolve(file));
574
625
  if (!slot)
575
626
  return;
627
+ reviewHub.invalidate(slot.dir, 'source_changed');
576
628
  if (slot.timer)
577
629
  clearTimeout(slot.timer);
578
- slot.timer = setTimeout(() => void run(slot), 60);
630
+ slot.timer = setTimeout(() => { slot.timer = null; void run(slot); }, 60);
579
631
  });
580
632
  }
581
633
  return {
@@ -604,7 +656,7 @@ export async function createHub(opts = {}) {
604
656
  }
605
657
  /** 启动一个看板进程并打开一个项目(等首次编译完成)。缺省不持久化。 */
606
658
  export async function createDev(opts) {
607
- const hub = await createHub({ port: opts.port, log: opts.log, watch: opts.watch, home: opts.home ?? null, exportDeps: opts.exportDeps });
659
+ const hub = await createHub({ port: opts.port, log: opts.log, watch: opts.watch, home: opts.home ?? null, exportDeps: opts.exportDeps, cloud: opts.cloud });
608
660
  try {
609
661
  const { id, url, slot } = hub.addProject(opts.projectDir);
610
662
  await slot.ready;
@@ -687,7 +739,7 @@ export async function startDev(opts) {
687
739
  return existing;
688
740
  let hub;
689
741
  try {
690
- hub = await createHub({ port: opts.port, log, home, exportDeps: opts.exportDeps, startedIn: projectDir });
742
+ hub = await createHub({ port: opts.port, log, home, exportDeps: opts.exportDeps, startedIn: projectDir, cloud: opts.cloud });
691
743
  }
692
744
  catch (e) {
693
745
  // 另一个 joplo dev 恰好同时启动:端口被它占了,改为加入它
package/dist/index.d.ts CHANGED
@@ -6,7 +6,7 @@
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';
@@ -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
- const project = payload.project;
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'})`);
@@ -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
  });
@@ -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 k = `${projectId}|${plan.key}`;
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
- /** 生成一段(已有就直接返回):返回文件名;失败记进 failures 并抛 VoiceError。 */
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
- }): Promise<{
215
- key: string;
216
- file: string;
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
- /** 生成一段(已有就直接返回):返回文件名;失败记进 failures 并抛 VoiceError。 */
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.10",
3
+ "version": "0.2.12",
4
4
  "description": "Joplo 本地服务:dev 看板、build 发布站、render 截图",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -15,9 +15,9 @@
15
15
  "dist"
16
16
  ],
17
17
  "dependencies": {
18
- "@joplo-app/core": "0.2.10",
19
- "@joplo-app/kit": "0.2.10",
20
- "@joplo-app/web": "0.2.10",
18
+ "@joplo-app/core": "0.2.12",
19
+ "@joplo-app/kit": "0.2.12",
20
+ "@joplo-app/web": "0.2.12",
21
21
  "@tailwindcss/vite": "4.3.4",
22
22
  "tailwindcss": "4.3.4",
23
23
  "vite": "8.3.5",