@joplo-app/server 0.2.16 → 0.2.18

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.js CHANGED
@@ -19,12 +19,12 @@ 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 { stepIdentity, hasScope, JoploError, orderedFeatures, resolveScope, scopeProject } from '@joplo-app/core';
22
+ import { stepIdentity, hasScope, JoploError, orderedFeatures, pruneMessages, 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";
26
26
  import { joploHome } from "./home.js";
27
- import { ProfileStore, bundleVoice } from "./voice.js";
27
+ import { ProfileStore, bundleVoice, reuseSharedVoice } from "./voice.js";
28
28
  /** 发布站只需要的 IR:去掉创作侧字段(publish 模式下它们本来就为空)。层级、镜头、角色(说话人、过渡卡、层级的 role)与 featureIds 顺序属于演示,保留(D43 / D56 / D61)。 */
29
29
  export function publishPayload(project, home) {
30
30
  // voiceConfig(D74):profile 名与音色属于作者本机的设置,发布站只需要 build 写进的 voiceIndex
@@ -35,7 +35,9 @@ export function publishPayload(project, home) {
35
35
  const { caseIds: _ci, ...sr } = s;
36
36
  return [id, { ...sr, caseIds: [], steps: s.steps.map(({ ruleIds: _ri, key: _key, ...st }) => ({ ...st, ruleIds: [] })) }];
37
37
  }));
38
- return { project: { ...rest, features, options, scenarios }, home: home && project.routes[home] ? home : null };
38
+ const out = { ...rest, features, options, scenarios };
39
+ // 译文(D84)在去掉创作侧字段之后再裁剪一次:约束等只给作者看的原文不能作为译文的键留在站点里
40
+ return { project: rest.i18n ? pruneMessages(out) : out, home: home && project.routes[home] ? home : null };
39
41
  }
40
42
  /** 把 JSON 安全地放进 <script type="application/json">。 */
41
43
  export const jsonForHtml = (v) => JSON.stringify(v).replace(/</g, '\\u003c').replace(/>/g, '\\u003e').replace(/&/g, '\\u0026').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
@@ -43,6 +45,8 @@ export const jsonForHtml = (v) => JSON.stringify(v).replace(/</g, '\\u003c').rep
43
45
  export function finalizeHtml(html, readAsset, inline, identity) {
44
46
  const inlined = [];
45
47
  let out = html.replace(/\s+crossorigin(?:="[^"]*")?/g, '');
48
+ // 作者标记只由 Cloud 注入,不能随本地构建或导出传播。
49
+ out = out.replace(/<meta\b[^>]*\bname\s*=\s*["']joplo-author["'][^>]*>/gi, '');
46
50
  out = out.replace(/<link rel="modulepreload"[^>]*>\s*/g, '');
47
51
  out = out.replace(/<script type="module" src="\.\/([^"]+)"><\/script>/g, (_m, rel) => {
48
52
  inlined.push(rel);
@@ -144,7 +148,12 @@ export async function buildSite(opts) {
144
148
  else
145
149
  await buildSourceSite(web, projectDir, staging);
146
150
  // 朗读(D74):当前声音已生成的音频拷进 voice/,IR 带上 voiceIndex;Key 不进产物
147
- const voice = bundleVoice(projectDir, project, staging, new ProfileStore(opts.home ?? joploHome()));
151
+ const store = new ProfileStore(opts.home ?? joploHome());
152
+ // 重新发布(D84):先从上一次的分享沿用本机没有的音频(同样的文字与声音),不重新生成
153
+ const reused = opts.sharedVoice ? await reuseSharedVoice(projectDir, project, opts.sharedVoice, store, undefined, opts.voiceDefault) : 0;
154
+ const voice = bundleVoice(projectDir, project, staging, store, undefined, opts.sharedVoice?.index, opts.voiceDefault);
155
+ if (reused)
156
+ voice.report.reused = reused;
148
157
  // 朗读角色只留范围内功能的(scopeProject 对 voiceIndex 的同一规则;bundleVoice 按声音配置生成全部角色)
149
158
  if (voice.index)
150
159
  inline.project.voiceIndex = scope ? scopeProject({ ...project, voiceIndex: voice.index }, scope.scenarios).project.voiceIndex : voice.index;
package/dist/cloud.d.ts CHANGED
@@ -12,45 +12,172 @@
12
12
  import type http from 'node:http';
13
13
  import type { ScopeInfo } from '@joplo-app/core';
14
14
  export declare const CLOUD_EVENT = "joplo:cloud";
15
+ export type CloudVisibility = 'public' | 'private';
16
+ export type CloudPortfolio = {
17
+ workUrl: string | null;
18
+ profileUrl: string | null;
19
+ needsUsername: boolean;
20
+ setupPath: string;
21
+ };
22
+ export type CloudLinks = {
23
+ main: {
24
+ visibility?: CloudVisibility;
25
+ passwordProtected?: boolean;
26
+ } | null;
27
+ scoped?: Record<string, {
28
+ visibility?: CloudVisibility;
29
+ passwordProtected?: boolean;
30
+ }>;
31
+ };
15
32
  export type CloudAccount = {
16
33
  signedIn: true;
17
34
  server: string;
18
35
  email: string;
19
36
  plan: 'free' | 'pro' | null;
37
+ /** 账号容量(C27);云端连不上或旧云端时没有。 */
38
+ storage?: CloudStorage;
39
+ /** 托管朗读额度(D85,`GET /api/v1/voice` 的 quota);云端连不上或旧云端(404)时没有。 */
40
+ voice?: VoiceQuota;
41
+ username?: string | null;
42
+ portfolioUrl?: string | null;
20
43
  } | {
21
44
  signedIn: false;
22
45
  server: string;
23
46
  loginCommand: string;
24
47
  message?: string;
25
48
  };
49
+ /** 托管朗读额度(D85,与 Cloud 契约 `GET /api/v1/voice` 的 quota 一致):免费是一次性的体验额度(trial),Pro 按月(month)。字数 = Array.from(文字).length。 */
50
+ export type VoiceQuota = {
51
+ plan: string;
52
+ period: 'trial' | 'month';
53
+ allowanceChars: number;
54
+ usedChars: number;
55
+ remainingChars: number;
56
+ /** 本月额度的重置时间(ISO);体验额度为 null。 */
57
+ resetsAt: string | null;
58
+ /** 加油包:各自剩余与到期时间。 */
59
+ packs: {
60
+ remainingChars: number;
61
+ expiresAt: string;
62
+ }[];
63
+ /** 当月(或体验)剩余 + 加油包剩余。看板与 CLI 显示的“剩 N 字”就是它。 */
64
+ totalRemainingChars: number;
65
+ };
66
+ /** Joplo 音色(Cloud 固定 6 个,都是多语言):labels / samples 按界面语言(10 种之一)。 */
67
+ export type CloudVoice = {
68
+ id: string;
69
+ gender: 'female' | 'male';
70
+ labels: Record<string, string>;
71
+ samples: Record<string, string>;
72
+ };
73
+ /** `GET /api/v1/voice` 去掉 quota 之后的部分:音色表、每种语言的推荐音色、默认音色。 */
74
+ export type CloudVoiceCatalog = {
75
+ model: string;
76
+ voices: CloudVoice[];
77
+ recommended: Record<string, string[]>;
78
+ defaultVoice: string;
79
+ };
80
+ export type CloudVoiceInfo = CloudVoiceCatalog & {
81
+ quota: VoiceQuota;
82
+ };
83
+ /**
84
+ * 托管朗读的状态:没登录时给登录命令;已登录时 voice 是 `GET /api/v1/voice` 的内容,云端连不上或旧云端(404)时为 null(看板退回浏览器朗读)。
85
+ */
86
+ export type CloudVoiceStatus = {
87
+ signedIn: false;
88
+ server: string;
89
+ loginCommand: string;
90
+ } | {
91
+ signedIn: true;
92
+ server: string;
93
+ voice: CloudVoiceInfo | null;
94
+ };
95
+ /** `POST /api/v1/voice/speech` 的请求:locale 是内容语言(D84,不知道时不带),project 是项目名(控制台明细用)。 */
96
+ export type CloudSpeechRequest = {
97
+ text: string;
98
+ voice: string;
99
+ locale?: string;
100
+ project?: string;
101
+ };
102
+ /** 合成结果:音频与响应头(X-Joplo-Chars-Charged / -Remaining、X-Joplo-Cache、X-Joplo-Audio-Sha256),头缺失或不合法时为 null。 */
103
+ export type CloudSpeechResult = {
104
+ audio: Uint8Array;
105
+ contentType: string;
106
+ charged: number | null;
107
+ remaining: number | null;
108
+ cache: 'hit' | 'miss' | null;
109
+ sha256: string | null;
110
+ };
111
+ /**
112
+ * 托管朗读(D85)的 CLI 一侧:看板与 `joplo voice` 共用。server 包不依赖 CLI,由 CLI 注入(与 publish 一样)。
113
+ * speech 失败时抛 `{ code, message, data? }`:TTS_QUOTA_EXCEEDED(data: neededChars / remainingChars / usageUrl)、AUTH_REQUIRED、AUTH_EXPIRED、
114
+ * EMAIL_UNVERIFIED、FORBIDDEN、RATE_LIMITED、TTS_UNAVAILABLE、BAD_REQUEST、NOT_FOUND(旧云端)、NETWORK。
115
+ */
116
+ export type CloudVoiceBridge = {
117
+ status(): Promise<CloudVoiceStatus>;
118
+ speech(req: CloudSpeechRequest): Promise<CloudSpeechResult>;
119
+ };
120
+ /** 账号容量(C27):已用 / 上限,字节。 */
121
+ export type CloudStorage = {
122
+ usedBytes: number;
123
+ quotaBytes: number;
124
+ };
125
+ /** 容量不足(QUOTA_EXCEEDED,kind: storage):数字可能缺;两个链接已拼好当前 server。 */
126
+ export type CloudStorageFull = {
127
+ usedBytes?: number;
128
+ quotaBytes?: number;
129
+ shareBytes?: number;
130
+ replacedBytes?: number;
131
+ manageUrl: string;
132
+ upgradeUrl: string;
133
+ };
26
134
  /** 范围:都为空 = 整个项目(D75)。 */
27
135
  export type CloudPublishRequest = {
136
+ password?: string | null;
137
+ visibility?: CloudVisibility;
138
+ review?: boolean;
28
139
  scenarios?: string[];
29
140
  features?: string[];
30
141
  };
31
142
  export type CloudPublishResult = {
143
+ passwordProtected?: boolean;
144
+ mode?: 'review';
145
+ visibility?: CloudVisibility;
146
+ portfolio?: CloudPortfolio;
147
+ review?: {
148
+ url: string;
149
+ shareId: string;
150
+ };
32
151
  shareId: string;
33
152
  url: string;
34
153
  expiresAt: string | null;
35
154
  version: number;
36
155
  plan: 'free' | 'pro';
37
- scope?: ScopeInfo;
156
+ scope?: ScopeInfo; /** 发布后的账号容量与这次大小(C27)。 */
157
+ storage?: CloudStorage & {
158
+ shareBytes: number;
159
+ };
38
160
  };
39
161
  /** CLI 实现:account 只读本机登录(必要时问一次云端套餐);publish 就是 share(),progress 是它写给终端的每一行。 */
40
162
  export type CloudBridge = {
41
163
  account(): Promise<CloudAccount>;
164
+ links?(projectDir: string): Promise<CloudLinks>;
42
165
  publish(projectDir: string, request: CloudPublishRequest, progress: (line: string) => void): Promise<CloudPublishResult>;
166
+ /** 托管朗读(D85);旧 CLI 没有这一项时看板只用浏览器朗读与自带 Key 的供应商。 */
167
+ voice?: CloudVoiceBridge;
43
168
  };
44
169
  /** 发布失败:code 来自 CLI(AUTH_REQUIRED、NOT_FOUND、NETWORK…);需要登录时带 loginCommand。 */
45
170
  export type CloudJobError = {
46
171
  code: string;
47
172
  message: string;
48
173
  loginCommand?: string;
174
+ upgradeUrl?: string; /** 容量不足时的数字与链接(C27)。 */
175
+ storage?: CloudStorageFull;
49
176
  };
50
177
  export type CloudJob = {
51
178
  id: string;
52
179
  state: 'running' | 'done' | 'failed';
53
- request: CloudPublishRequest;
180
+ request: Omit<CloudPublishRequest, 'password'>;
54
181
  startedAt: number;
55
182
  /** 进度:CLI 写给终端的行(英文,页面按开头识别阶段)。 */
56
183
  lines: string[];
package/dist/cloud.js CHANGED
@@ -37,6 +37,12 @@ export class CloudHub {
37
37
  }
38
38
  /** `/__joplo/p/<id>/cloud/<sub>`:sub = 'publish'(GET 读任务,POST 开始发布)。 */
39
39
  async handleProject(projectId, dir, sub, req, ctx) {
40
+ if (sub === 'links' && req.method === 'GET') {
41
+ if (!ctx.guardWrite(false))
42
+ return true;
43
+ ctx.send(200, { links: await this.bridge?.links?.(dir) ?? { main: null } });
44
+ return true;
45
+ }
40
46
  if (sub !== 'publish')
41
47
  return false;
42
48
  const method = req.method ?? 'GET';
@@ -60,7 +66,19 @@ export class CloudHub {
60
66
  const body = (b.body ?? {});
61
67
  const scenarios = strings(body.scenarios, 'scenarios');
62
68
  const features = strings(body.features, 'features');
63
- request = { ...(scenarios?.length ? { scenarios } : {}), ...(features?.length ? { features } : {}) };
69
+ if (body.visibility !== 'public' && body.visibility !== 'private')
70
+ throw new Error('Choose visibility: public / private');
71
+ if (typeof body.review !== 'boolean')
72
+ throw new Error('Choose review: true / false');
73
+ if (body.visibility === 'public' && (scenarios?.length || features?.length))
74
+ throw new Error('Scoped shares must be private');
75
+ if (body.password !== undefined) {
76
+ if (body.visibility !== 'private')
77
+ throw new Error('Passwords require a private share');
78
+ if (body.password !== null && (typeof body.password !== 'string' || Array.from(body.password).length < 8 || Array.from(body.password).length > 128))
79
+ throw new Error('Access password must contain 8–128 characters');
80
+ }
81
+ request = { ...(body.password !== undefined ? { password: body.password } : {}), visibility: body.visibility, review: body.review, ...(scenarios?.length ? { scenarios } : {}), ...(features?.length ? { features } : {}) };
64
82
  }
65
83
  catch (e) {
66
84
  return ctx.send(400, { error: { code: 'USAGE', message: e instanceof Error ? e.message : String(e) } }), true;
@@ -72,27 +90,32 @@ export class CloudHub {
72
90
  return true;
73
91
  }
74
92
  start(projectId, dir, request) {
75
- const job = { id: `c${++this.seq}`, state: 'running', request, startedAt: Date.now(), lines: [] };
93
+ const { password, ...safeRequest } = request;
94
+ const redact = (text) => typeof password === 'string' && password ? text.split(password).join('[REDACTED]') : text;
95
+ const safe = (value) => JSON.parse(JSON.stringify(value, (_key, v) => typeof v === 'string' ? redact(v) : v));
96
+ const job = { id: `c${++this.seq}`, state: 'running', request: safe(safeRequest), startedAt: Date.now(), lines: [] };
76
97
  this.jobs.set(projectId, job);
77
98
  const push = () => this.emit(projectId, job);
78
99
  push();
79
100
  void this.bridge
80
101
  .publish(dir, request, (line) => {
81
- job.lines = [...job.lines, line].slice(-MAX_LINES);
102
+ job.lines = [...job.lines, redact(line)].slice(-MAX_LINES);
82
103
  push();
83
104
  })
84
105
  .then((result) => {
85
106
  job.state = 'done';
86
- job.result = result;
107
+ job.result = safe(result);
87
108
  })
88
109
  .catch((e) => {
89
110
  const err = e;
90
111
  job.state = 'failed';
91
- job.error = {
112
+ job.error = safe({
92
113
  code: typeof err.code === 'string' ? err.code : 'INTERNAL',
93
114
  message: typeof err.message === 'string' ? err.message : String(e),
94
115
  ...(typeof err.loginCommand === 'string' ? { loginCommand: err.loginCommand } : {}),
95
- };
116
+ ...(err.storage && typeof err.storage === 'object' ? { storage: err.storage } : {}),
117
+ ...(typeof err.upgradeUrl === 'string' ? { upgradeUrl: err.upgradeUrl } : {}),
118
+ });
96
119
  })
97
120
  .finally(push);
98
121
  return job;
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * v2 接口(ADR-0002):CLI 只依赖这里导出的三个函数。由 T-board 实现,届时 index.ts 改为导出它们。
3
3
  */
4
- import type { AppearanceFont, AppearanceStroke, Diagnostic, ScopeInfo, ScopeRequest } from '@joplo-app/core';
4
+ import type { AppearanceFont, AppearanceStroke, Diagnostic, ScopeInfo, ScopeRequest, VoiceIndex } from '@joplo-app/core';
5
5
  import type { CloudBridge } from './cloud.js';
6
6
  export type { CloudAccount, CloudBridge, CloudJob, CloudJobError, CloudPublishRequest, CloudPublishResult } from './cloud.js';
7
7
  export type DevOptions = {
@@ -44,6 +44,19 @@ export type BuildOptions = {
44
44
  * 缺省(或两个数组都为空)时与原来完全一致。写错场景 / 功能时报错,不写任何文件。
45
45
  */
46
46
  scope?: ScopeRequest;
47
+ /**
48
+ * 上一次发布的分享(D84,`joplo share` 重新发布时传):它的 voiceIndex 与取文件的方法。本机没有、分享里有的音频
49
+ * (同样的文字和声音)下载进本机缓存后照常打包,不重新生成;本机没有声音供应商时按分享里的声音指纹带上。
50
+ */
51
+ sharedVoice?: {
52
+ index: VoiceIndex;
53
+ fetch: (file: string) => Promise<Uint8Array | null>;
54
+ };
55
+ /**
56
+ * 项目没选过声音来源、config 也没写时用哪个(D85):CLI 已登录 Joplo Cloud 时传 'cloud'(与看板同一规则),
57
+ * 这样看板里默认用 cloud 生成的音频也会带上。缺省 null:只用看板里选过的(与原来一致)。
58
+ */
59
+ voiceDefault?: string | null;
47
60
  };
48
61
  /** 静态发布站:只含选定方案(compile 的 publish 模式),离线可打开,可直接 `wrangler deploy`。 */
49
62
  /**
@@ -61,6 +74,10 @@ export type BuildResult = {
61
74
  bytes: number;
62
75
  missing: number;
63
76
  profile: string | null;
77
+ reused?: number;
78
+ locales?: Record<string, {
79
+ missing: number;
80
+ }>;
64
81
  }; /** 有 scope 时:范围与借用了哪些别的功能的内容(D75)。 */
65
82
  scope?: ScopeInfo;
66
83
  };
@@ -74,6 +91,8 @@ export type RenderOptions = {
74
91
  theme?: string;
75
92
  /** UI language for the standalone render route. Unsupported values are ignored. */
76
93
  locale?: string;
94
+ /** Author content language (D84): one of config locales; the screenshot shows that translation. */
95
+ content?: string;
77
96
  /** 字体(D55):hand / sans / serif / kai / mono;缺省跟随主题。 */
78
97
  font?: AppearanceFont | null;
79
98
  /** 线条(D55):rough / clean;缺省跟随主题。 */
@@ -112,3 +131,14 @@ export type RenderResult = {
112
131
  warnings: string[];
113
132
  };
114
133
  export declare function renderStep(opts: RenderOptions): Promise<RenderResult>;
134
+ /** 分镜(storyboard):一个场景的每一步拼成一张图,每格下面是步号、字幕与旁白。 */
135
+ export type SheetOptions = Omit<RenderOptions, 'stepId' | 'viewport' | 'scope'> & {
136
+ columns?: number; /** 每格宽度(像素),默认 480。 */
137
+ cellWidth?: number;
138
+ };
139
+ export type SheetResult = {
140
+ path: string;
141
+ steps: number;
142
+ warnings: string[];
143
+ };
144
+ export declare function renderSheet(opts: SheetOptions): Promise<SheetResult>;
package/dist/dev.js CHANGED
@@ -337,6 +337,8 @@ export async function createHub(opts = {}) {
337
337
  });
338
338
  // 朗读(D74):声音供应商 profile(本机)与项目音频缓存;状态变化推 joplo:voice
339
339
  const voiceHub = new VoiceHub(opts.home ?? joploHome(), {
340
+ // 托管朗读(D85):CLI 注入的登录与合成;旧 CLI 没有时只用浏览器朗读与自带 Key 的供应商
341
+ cloud: opts.cloud?.voice,
340
342
  emit: (projectId, state) => {
341
343
  if (!closed)
342
344
  server?.ws.send({ type: 'custom', event: VOICE_EVENT, data: { projectId, state } });
package/dist/export.js CHANGED
@@ -58,7 +58,7 @@ function parseRequest(project, body, needPosition) {
58
58
  const device = project.scenes[sceneId]?.viewport === 'mobile' ? 'mobile' : 'desktop';
59
59
  // 主题(D51):请求里的主题名,没有或不合法时用项目配置的主题
60
60
  const theme = typeof b.theme === 'string' && THEME_NAME.test(b.theme) ? b.theme : project.theme;
61
- return { sc, position, device, look: { theme, ...exportAppearance(body), locale: exportLocale(b.locale) } };
61
+ return { sc, position, device, look: { theme, ...exportAppearance(body), locale: exportLocale(b.locale), ...(exportLocale(b.contentLocale) ? { content: exportLocale(b.contentLocale) } : {}) } };
62
62
  }
63
63
  const fileSafe = (s) => s.replace(/[^\w.-]+/g, '_').slice(0, 80) || 'scenario';
64
64
  const stamp = (d = new Date()) => `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}-${String(d.getHours()).padStart(2, '0')}${String(d.getMinutes()).padStart(2, '0')}${String(d.getSeconds()).padStart(2, '0')}`;
@@ -204,7 +204,7 @@ export class ExportHub {
204
204
  const browser = await launch(pw);
205
205
  try {
206
206
  const page = await browser.newPage({ viewport: EXPORT_SIZE[device], deviceScaleFactor: 2, reducedMotion: 'reduce' });
207
- await page.goto(this.renderUrl(projectId, { scenario: scenarioId, position: String(position), theme: look.theme, ...appearanceParams(look), ...(look.locale ? { locale: look.locale } : {}), frame: '1' }), { waitUntil: 'domcontentloaded' });
207
+ await page.goto(this.renderUrl(projectId, { scenario: scenarioId, position: String(position), theme: look.theme, ...appearanceParams(look), ...(look.locale ? { locale: look.locale } : {}), ...(look.content ? { content: look.content } : {}), frame: '1' }), { waitUntil: 'domcontentloaded' });
208
208
  await waitReady(page);
209
209
  return await page.locator('[data-jexport]').screenshot({ type: 'png', animations: 'disabled' });
210
210
  }
@@ -225,7 +225,7 @@ export class ExportHub {
225
225
  this.update(job, { phase: 'starting', percent: 2 });
226
226
  await this.deps.recordVideo({
227
227
  projectDir: dir,
228
- url: this.renderUrl(projectId, { scenario: scenarioId, position: '0', theme: look.theme, ...appearanceParams(look), ...(look.locale ? { locale: look.locale } : {}), frame: '1', record: '1' }),
228
+ url: this.renderUrl(projectId, { scenario: scenarioId, position: '0', theme: look.theme, ...appearanceParams(look), ...(look.locale ? { locale: look.locale } : {}), ...(look.content ? { content: look.content } : {}), frame: '1', record: '1' }),
229
229
  size: EXPORT_SIZE[device],
230
230
  out,
231
231
  total,
package/dist/index.d.ts CHANGED
@@ -9,6 +9,8 @@
9
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
- export { renderStep } from './render.js';
12
+ export { generateProjectVoice, type VoiceRunOptions, type VoiceRunResult } from './voice-run.js';
13
+ export type { CloudSpeechRequest, CloudSpeechResult, CloudVoice, CloudVoiceBridge, CloudVoiceCatalog, CloudVoiceInfo, CloudVoiceStatus, VoiceQuota } from './cloud.js';
14
+ export { renderSheet, renderStep } from './render.js';
13
15
  export { EXPORT_DOWNLOAD_MB, PLAYWRIGHT_VERSION, SETUP_COMMAND, exportRuntimeStatus, installExportRuntime, uninstallExportRuntime, type ExportRuntimeStatus, type InstallProgress, type InstallResult } from './export-runtime.js';
14
16
  export { buildFeatureDiff, publicIRFromHtml, type DiffBuildOptions, type DiffBuildResult } from './feature-diff.js';
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export { startDev } from "./dev.js";
2
2
  export { buildSite } from "./build.js";
3
- export { renderStep } from "./render.js";
3
+ export { generateProjectVoice } from "./voice-run.js";
4
+ export { renderSheet, renderStep } from "./render.js";
4
5
  export { EXPORT_DOWNLOAD_MB, PLAYWRIGHT_VERSION, SETUP_COMMAND, exportRuntimeStatus, installExportRuntime, uninstallExportRuntime } from "./export-runtime.js";
5
6
  export { buildFeatureDiff, publicIRFromHtml } from "./feature-diff.js";
@@ -33,6 +33,8 @@
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
+ // 画布(Canvas)里的元素被镜头移出画面是常态:只在它是下一步要操作的目标时才提示
37
+ if (el.closest('[data-jcanvas-world]') && el.dataset.jid !== args.nextTargetId) return;
36
38
  warnings.push(`Outside frame: "${e.label}"(${e.id}) has its center outside the frame`);
37
39
  return;
38
40
  }
@@ -51,6 +53,11 @@
51
53
  if (offViewport.length)
52
54
  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
55
 
56
+ // 1b. 画布(Canvas)没有尺寸:放在没有宽 / 高的容器里时整块不可见
57
+ stage.querySelectorAll('[data-jcanvas]').forEach((c) => {
58
+ if (c.clientWidth < 1 || c.clientHeight < 1) warnings.push(`Canvas has no size: ${name(c)} is ${c.clientWidth}×${c.clientHeight}px, so nothing in it is visible; give its container a width and height (h="100%" in a layer) or let it size from its view ratio`);
59
+ });
60
+
54
61
  // 2. 标签文字溢出
55
62
  stage.querySelectorAll('[data-jtext], .jtrunc').forEach((t) => {
56
63
  if (t.scrollWidth > t.clientWidth + 1) warnings.push(`Label text overflow: ${name(t)} text "${(t.textContent ?? '').slice(0, 40)}" is clipped`);
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 自己的导出组件)。 */
@@ -16,6 +16,7 @@ export declare function renderQuery(q: {
16
16
  position: number;
17
17
  theme: string;
18
18
  locale?: string;
19
+ content?: string;
19
20
  font?: AppearanceFont | null;
20
21
  stroke?: AppearanceStroke | null;
21
22
  viewport?: {
@@ -24,3 +25,9 @@ export declare function renderQuery(q: {
24
25
  };
25
26
  }): string;
26
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
@@ -75,6 +75,7 @@ export function renderQuery(q) {
75
75
  position: String(q.position),
76
76
  theme: q.theme,
77
77
  ...(exportLocale(q.locale) ? { locale: exportLocale(q.locale) } : {}),
78
+ ...(exportLocale(q.content) ? { content: exportLocale(q.content) } : {}),
78
79
  ...(isAppearanceFont(q.font) ? { font: q.font } : {}),
79
80
  ...(isAppearanceStroke(q.stroke) ? { stroke: q.stroke } : {}),
80
81
  ...(q.viewport ? { w: String(q.viewport.width), h: String(q.viewport.height) } : {}),
@@ -103,6 +104,9 @@ export async function renderStep(opts) {
103
104
  const sc = project.scenarios[opts.scenarioId];
104
105
  if (!sc)
105
106
  throw new JoploError('NOT_FOUND', `Scenario does not exist: ${opts.scenarioId} (available: ${Object.keys(project.scenarios).join(', ') || 'none'})`);
107
+ // 内容语言(D84)写错时报错,不静默按源语言截图
108
+ if (opts.content !== undefined && !project.i18n?.locales.includes(opts.content))
109
+ 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`);
106
110
  const position = opts.stepId ? positionAfterStep(project, sc.id, opts.stepId) : 0;
107
111
  const state = stateAt(project, sc.id, position); // 回放失败会抛出 PLAYBACK_FAILED
108
112
  // 有层级的方案:截图与元素索引用这一步导演层的画面(每层一个独立画面)
@@ -116,7 +120,7 @@ export async function renderStep(opts) {
116
120
  browser = await launch(playwright);
117
121
  const page = await browser.newPage({ viewport, deviceScaleFactor: opts.scale ?? 1, reducedMotion: 'reduce' });
118
122
  // D44:舞台宽度固定为页面自己的 viewport;指定 viewport 时它只是截图尺寸(舞台按比例放进去)
119
- const q = renderQuery({ projectId: server.projectId, scenarioId: sc.id, position, theme, locale: opts.locale, font: opts.font, stroke: opts.stroke, ...(opts.viewport ? { viewport: opts.viewport } : {}) });
123
+ const q = renderQuery({ projectId: server.projectId, scenarioId: sc.id, position, theme, locale: opts.locale, content: opts.content, font: opts.font, stroke: opts.stroke, ...(opts.viewport ? { viewport: opts.viewport } : {}) });
120
124
  await page.goto(`${server.url}?${q}`, { waitUntil: 'domcontentloaded' });
121
125
  await page.waitForFunction(() => window.__JOPLO_READY__ === true, null, { timeout: 60000 });
122
126
  const err = await page.evaluate(() => window.__JOPLO_ERROR__ ?? null);
@@ -156,4 +160,84 @@ export async function renderStep(opts) {
156
160
  await server.close();
157
161
  }
158
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
+ }
159
243
  const COLLECT_REPORT = fs.readFileSync(path.join(import.meta.dirname, 'page-report.js'), 'utf8').replace(/^\/\*[\s\S]*?\*\/\s*/, '');