@joplo-app/server 0.6.1 → 0.7.1

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/render.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { auditLayout, layoutAuditOptions, layoutReportPath, writeLayoutReport } from "./layout-audit.js";
1
2
  /**
2
3
  * renderStep:用随机端口启动一次性的 dev 服务(只编译一次、不监听),Playwright 打开渲染路由,
3
4
  * 截取舞台并返回元素索引(带 at)与渲染告警:遮挡、溢出、Toast 重叠、字体(PRD 8.8 / AC-22)。
@@ -8,12 +9,13 @@
8
9
  */
9
10
  import fs from 'node:fs';
10
11
  import path from 'node:path';
11
- import { JoploError, VIEWPORT_SIZE, isAppearanceFont, isAppearanceStroke, displaySceneId, findNode, isNodeDisabled, nodeLabel, positionAfterStep, resolveProps, scopeProject, stateAt, walkNodes } from '@joplo-app/core';
12
+ import { JoploError, narrationText, VIEWPORT_SIZE, isAppearanceFont, isAppearanceStroke, displaySceneId, findNode, isNodeDisabled, nodeLabel, positionAfterStep, resolveProps, scopeProject, stateAt, walkNodes } from '@joplo-app/core';
12
13
  import { exportLocale } from "./locale.js";
13
14
  import { createDev } from "./dev.js";
14
15
  import { realProjectDir } from "./vite-shared.js";
15
16
  import { joploHome } from "./home.js";
16
17
  import { EXPORT_DOWNLOAD_MB, NOT_NEEDED, SETUP_COMMAND, loadPlaywright } from "./export-runtime.js";
18
+ import { capture, geometryQuery } from "./capture.js";
17
19
  const STAGE_SIZE = VIEWPORT_SIZE;
18
20
  export { loadPlaywright } from "./export-runtime.js";
19
21
  /** 浏览器启动失败时的一行提示(托管运行时与项目里的 Playwright 都适用:重装 Joplo 自己的导出组件)。 */
@@ -53,7 +55,7 @@ function realish(p) {
53
55
  }
54
56
  }
55
57
  /** 截图不得覆盖项目源文件或 .joplo/(即使传了 overwrite)。 */
56
- function assertNotProjectData(projectDir, out) {
58
+ export function assertNotProjectData(projectDir, out) {
57
59
  const fold = (p) => (process.platform === 'darwin' || process.platform === 'win32' ? p.toLowerCase() : p);
58
60
  const o = fold(realish(out));
59
61
  const dir = fold(realish(projectDir));
@@ -87,6 +89,11 @@ export async function renderStep(opts) {
87
89
  assertNotProjectData(projectDir, out);
88
90
  if (fs.existsSync(out) && !opts.overwrite)
89
91
  throw new JoploError('USAGE', `Output file already exists: ${out}. To overwrite, pass overwrite: true (CLI: --overwrite)`);
92
+ if (opts.auditLayout) {
93
+ layoutAuditOptions(opts.auditLayout);
94
+ if (fs.existsSync(layoutReportPath(out)) && !opts.overwrite)
95
+ throw new JoploError('USAGE', `Layout report already exists: ${layoutReportPath(out)}`);
96
+ }
90
97
  // 先确认 Playwright 可用,再启动编译服务(缺失时尽快失败)
91
98
  const playwright = await loadPlaywright({ home: joploHome(), projectDir });
92
99
  const server = await createDev({ projectDir, port: 0, watch: false, log: () => undefined });
@@ -114,20 +121,23 @@ export async function renderStep(opts) {
114
121
  const theme = opts.theme ?? project.theme ?? 'sketch';
115
122
  const next = state.completed ? undefined : sc.steps[position];
116
123
  const nextTargetId = next && 'target' in next.action ? next.action.target : null;
117
- const stage = STAGE_SIZE[scene.viewport === 'mobile' ? 'mobile' : 'desktop'];
124
+ const stage = opts.logicalViewport ?? STAGE_SIZE[scene.viewport === 'mobile' ? 'mobile' : 'desktop'];
118
125
  // 字幕与步骤标题条浮在舞台上(D97):页面就是舞台大小
119
126
  const viewport = opts.viewport ?? { width: stage.width, height: stage.height };
120
127
  browser = await launch(playwright);
121
128
  const page = await browser.newPage({ viewport, deviceScaleFactor: opts.scale ?? 1, reducedMotion: 'reduce' });
122
129
  // D44:舞台宽度固定为页面自己的 viewport;指定 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 } : {}) });
130
+ const q0 = 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 } : {}) });
131
+ const q = new URLSearchParams(q0);
132
+ for (const [key, value] of Object.entries(geometryQuery(opts)))
133
+ q.set(key, value);
124
134
  await page.goto(`${server.url}?${q}`, { waitUntil: 'domcontentloaded' });
125
135
  await page.waitForFunction(() => window.__JOPLO_READY__ === true, null, { timeout: 60000 });
126
136
  const err = await page.evaluate(() => window.__JOPLO_ERROR__ ?? null);
127
137
  if (err)
128
138
  throw new JoploError('RENDER_FAILED', `Render route reported an error: ${err}`);
129
139
  const report = (await page.evaluate(`(${COLLECT_REPORT})(${JSON.stringify({ nextTargetId, theme })})`));
130
- const png = await page.locator(opts.viewport ? '[data-jshot]' : '[data-jrender]').screenshot({ type: 'png', animations: 'disabled' });
140
+ const png = await capture(page, opts.viewport ? '[data-jshot]' : '[data-jrender]', opts.crop);
131
141
  fs.mkdirSync(path.dirname(out), { recursive: true });
132
142
  if (opts.overwrite)
133
143
  fs.writeFileSync(out, png);
@@ -149,11 +159,12 @@ export async function renderStep(opts) {
149
159
  box: { x: 0, y: 0, width: 0, height: 0 },
150
160
  });
151
161
  });
162
+ const audit = opts.auditLayout ? writeLayoutReport(layoutReportPath(out), [{ ...await auditLayout(page, layoutAuditOptions(opts.auditLayout), opts.crop), phases: ['static-final'], atMs: null, timeBasis: 'static-final-state', scenarioId: sc.id, position, stepId: sc.steps[position - 1]?.id ?? null, workId: sc.workId, evidence: out }], opts.overwrite) : undefined;
152
163
  const elements = [...report.elements, ...hidden];
153
164
  const warnings = [...report.warnings];
154
165
  if (nextTargetId && findNode(scene, nextTargetId) && !elements.find((e) => e.id === nextTargetId && e.visible))
155
166
  warnings.push(`Next action target ${nextTargetId} is not visible in the stage`);
156
- return { path: out, sceneId: scene.id, position, elements, warnings, scale: opts.scale ?? 1 };
167
+ return { ...(audit ? { audit } : {}), path: out, sceneId: scene.id, position, elements, warnings, scale: opts.scale ?? 1 };
157
168
  }
158
169
  finally {
159
170
  await browser?.close().catch(() => undefined);
@@ -196,11 +207,14 @@ export async function renderSheet(opts) {
196
207
  for (let position = 0; position <= sc.steps.length; position++) {
197
208
  const state = stateAt(project, sc.id, position);
198
209
  const scene = project.scenes[displaySceneId(project, sc.id, position)];
199
- const stage = STAGE_SIZE[scene.viewport === 'mobile' ? 'mobile' : 'desktop'];
210
+ const stage = opts.logicalViewport ?? STAGE_SIZE[scene.viewport === 'mobile' ? 'mobile' : 'desktop'];
200
211
  const next = state.completed ? undefined : sc.steps[position];
201
212
  const nextTargetId = next && 'target' in next.action ? next.action.target : null;
202
213
  const page = await browser.newPage({ viewport: { width: stage.width, height: stage.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 });
214
+ const q0 = renderQuery({ projectId: server.projectId, scenarioId: sc.id, position, theme, locale: opts.locale, content: opts.content, font: opts.font, stroke: opts.stroke });
215
+ const q = new URLSearchParams(q0);
216
+ for (const [key, value] of Object.entries(geometryQuery(opts)))
217
+ q.set(key, value);
204
218
  await page.goto(`${server.url}?${q}`, { waitUntil: 'domcontentloaded' });
205
219
  await page.waitForFunction(() => window.__JOPLO_READY__ === true, null, { timeout: 60000 });
206
220
  const err = await page.evaluate(() => window.__JOPLO_ERROR__ ?? null);
@@ -209,14 +223,14 @@ export async function renderSheet(opts) {
209
223
  const report = (await page.evaluate(`(${COLLECT_REPORT})(${JSON.stringify({ nextTargetId, theme })})`));
210
224
  for (const w of report.warnings)
211
225
  warnings.push(`Step ${position}: ${w}`);
212
- const png = await page.locator('[data-jrender]').screenshot({ type: 'png', animations: 'disabled' });
226
+ const png = await capture(page, '[data-jrender]', opts.crop);
213
227
  await page.close();
214
228
  const step = position > 0 ? sc.steps[position - 1] : undefined;
215
229
  cells.push({
216
230
  png: png.toString('base64'),
217
231
  label: position === 0 ? '0 · start' : `${position} · ${step.kind}`,
218
232
  caption: step?.caption ?? sc.description ?? sc.name,
219
- voice: step?.narrate ?? step?.say ?? '',
233
+ voice: step ? narrationText(step, step.caption) : '',
220
234
  });
221
235
  }
222
236
  const html = `<!doctype html><meta charset="utf-8"><style>
@@ -0,0 +1,76 @@
1
+ import type { AudioRegion } from '@joplo-app/kit/plugin';
2
+ /** Versioned actual-playback observation schema. Times are milliseconds, never outline estimates. */
3
+ export type TimelineStep = {
4
+ scenarioId: string;
5
+ stepId: string;
6
+ position: number;
7
+ commitMs: number;
8
+ outputCommitMs: number;
9
+ endMs: number;
10
+ outputEndMs: number;
11
+ camera: unknown;
12
+ media: unknown;
13
+ text: unknown;
14
+ };
15
+ export type TimelineMediaEvent = {
16
+ track: string;
17
+ action: 'play' | 'stop' | 'seek' | 'volume';
18
+ engineMs: number;
19
+ outputMs: number;
20
+ resource: string;
21
+ offsetMs: number;
22
+ volume: number;
23
+ fadeMs: number;
24
+ snapshot: Record<string, unknown>;
25
+ };
26
+ export type PlaybackTimeline = {
27
+ completion?: {
28
+ completed: boolean;
29
+ scenarioId: string | null;
30
+ engineMs: number;
31
+ outputMs: number;
32
+ };
33
+ mediaEvents: TimelineMediaEvent[];
34
+ assets?: {
35
+ id: string;
36
+ kind: 'narration' | 'media';
37
+ file: string;
38
+ audioInfo?: AudioRegion;
39
+ }[];
40
+ steps: TimelineStep[];
41
+ chapters: {
42
+ scenarioId: string;
43
+ startMs: number;
44
+ endMs: number;
45
+ }[];
46
+ schemaVersion: 1;
47
+ origin: 'playback';
48
+ timing: {
49
+ sampleToleranceMs: number;
50
+ outputOriginMs: number;
51
+ };
52
+ events: PlaybackEvent[];
53
+ };
54
+ export type PlaybackEvent = {
55
+ at: number;
56
+ engineMs: number;
57
+ outputMs: number;
58
+ scenarioId?: string | null;
59
+ position?: number;
60
+ stepId?: string | null;
61
+ [key: string]: unknown;
62
+ };
63
+ export type RawTimeline = {
64
+ completed?: boolean;
65
+ schemaVersion: 1;
66
+ startedAt: number | null;
67
+ events: (Record<string, unknown> & {
68
+ at: number;
69
+ engineMs: number;
70
+ })[];
71
+ };
72
+ export declare function playbackTimeline(raw: RawTimeline, outputOriginMs?: number, sampleToleranceMs?: number): PlaybackTimeline;
73
+ /** Accumulated integer targets avoid ceil(1000 / fps) drift in Playwright runFor. */
74
+ export declare function frameTime(index: number, fps: number): number;
75
+ /** Make the timeline useful after its temporary recording server has closed. Only referenced audio is copied. */
76
+ export declare function persistTimeline(file: string, timeline: PlaybackTimeline, mediaAssets: Readonly<Record<string, string>>, baseUrl: string, overwrite?: boolean, localToken?: string, mediaInfo?: Readonly<Record<string, AudioRegion>>): Promise<void>;
@@ -0,0 +1,139 @@
1
+ import { writeOutput } from "./output-file.js";
2
+ export function playbackTimeline(raw, outputOriginMs = raw.startedAt ?? 0, sampleToleranceMs = 50) {
3
+ const steps = [], chapters = [];
4
+ const ended = new Set(), dwelled = new Set();
5
+ for (const e of raw.events) {
6
+ const sid = typeof e.scenarioId === 'string' ? e.scenarioId : null;
7
+ if (!sid)
8
+ continue;
9
+ if (chapters.at(-1)?.scenarioId !== sid) {
10
+ if (chapters.length)
11
+ chapters.at(-1).endMs = e.engineMs;
12
+ chapters.push({ scenarioId: sid, startMs: e.engineMs, endMs: e.engineMs });
13
+ }
14
+ chapters.at(-1).endMs = e.engineMs;
15
+ if (typeof e.stepId === 'string' && !steps.some(s => s.stepId === e.stepId)) {
16
+ if (steps.length && !ended.has(steps.at(-1).stepId)) {
17
+ steps.at(-1).endMs = e.engineMs;
18
+ steps.at(-1).outputEndMs = e.at - outputOriginMs;
19
+ }
20
+ steps.push({ scenarioId: sid, stepId: e.stepId, position: Number(e.position), commitMs: e.engineMs, outputCommitMs: e.at - outputOriginMs, endMs: e.engineMs, outputEndMs: e.at - outputOriginMs, camera: e.camera, media: e.media, text: e.text });
21
+ }
22
+ const current = steps.at(-1);
23
+ if (current && !ended.has(current.stepId)) {
24
+ current.endMs = e.engineMs;
25
+ current.outputEndMs = e.at - outputOriginMs;
26
+ if (e.dwell && e.stepId === current.stepId)
27
+ dwelled.add(current.stepId);
28
+ if ((dwelled.has(current.stepId) && e.dwell === null && e.activeStep === null) || (e.position === current.position && e.activeStep === e.position) || e.playing === false)
29
+ ended.add(current.stepId);
30
+ }
31
+ }
32
+ const mediaEvents = [];
33
+ let previous = {}, previousCommit = '';
34
+ for (const e of raw.events) {
35
+ if (!e.media || typeof e.media !== 'object')
36
+ continue;
37
+ const key = `${e.scenarioId}:${e.position}`;
38
+ if (key === previousCommit)
39
+ continue;
40
+ previousCommit = key;
41
+ const current = e.media;
42
+ const emit = (track, action, value, fadeMs = 0) => mediaEvents.push({ track, action, engineMs: e.engineMs, outputMs: e.at - outputOriginMs, resource: String(value.resource), offsetMs: Number(value.offsetMs ?? 0), volume: Number(value.volume ?? 1), fadeMs, snapshot: value });
43
+ for (const [track, value] of Object.entries(current)) {
44
+ const before = previous[track];
45
+ if (!before || before.resource !== value.resource)
46
+ emit(track, 'play', value, Number(value.fadeInMs ?? 0));
47
+ else if (value.startOffsetMs !== undefined && value.startOffsetMs !== before.startOffsetMs)
48
+ emit(track, 'seek', value, Number(value.fadeInMs ?? 0));
49
+ if (value.stopAfterMs !== undefined && before?.stopAfterMs === undefined)
50
+ emit(track, 'stop', value, Number(value.stopAfterMs));
51
+ else if (before && value.volume !== before.volume && value.stopAfterMs === undefined)
52
+ emit(track, 'volume', value);
53
+ }
54
+ for (const [track, value] of Object.entries(previous))
55
+ if (!current[track] && value.stopAfterMs === undefined && value.endAfterMs === undefined)
56
+ emit(track, 'stop', value);
57
+ previous = current;
58
+ }
59
+ const final = raw.events.at(-1);
60
+ return { completion: { completed: raw.completed ?? false, scenarioId: typeof final?.scenarioId === 'string' ? final.scenarioId : null, engineMs: final?.engineMs ?? 0, outputMs: final ? final.at - outputOriginMs : 0 }, mediaEvents, steps, chapters, schemaVersion: 1, origin: 'playback', timing: { sampleToleranceMs, outputOriginMs }, events: raw.events.map(e => ({ ...e, at: e.at - (raw.startedAt ?? 0), outputMs: e.at - outputOriginMs, ...(typeof e.endAt === 'number' ? { endAt: e.endAt - (raw.startedAt ?? 0), outputEndMs: e.endAt - outputOriginMs } : {}) })) };
61
+ }
62
+ /** Accumulated integer targets avoid ceil(1000 / fps) drift in Playwright runFor. */
63
+ export function frameTime(index, fps) { return Math.round(index * 1000 / fps); }
64
+ /** Make the timeline useful after its temporary recording server has closed. Only referenced audio is copied. */
65
+ export async function persistTimeline(file, timeline, mediaAssets, baseUrl, overwrite = false, localToken, mediaInfo = {}) {
66
+ const fs = await import('node:fs/promises'), path = await import('node:path'), crypto = await import('node:crypto');
67
+ const directory = `${file.replace(/\.json$/i, '')}.assets`, assets = [];
68
+ const copy = async (id, kind, source, audioInfo) => {
69
+ const url = new URL(source, baseUrl);
70
+ let response;
71
+ if (localToken && url.origin === new URL(baseUrl).origin && /^\/__joplo\/p\/[^/]+\/resources\//.test(url.pathname)) {
72
+ const resolved = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', 'x-joplo-token': localToken }, body: '{}' });
73
+ if (!resolved.ok)
74
+ throw new Error(`Timeline media resource ${id} could not be resolved (${resolved.status})`);
75
+ const result = await resolved.json();
76
+ audioInfo = result.audio ?? audioInfo;
77
+ if (!result.url?.startsWith('data:'))
78
+ throw new Error(`Timeline media resource ${id} is unavailable; prepare local resources first`);
79
+ response = await fetch(result.url);
80
+ }
81
+ else
82
+ response = await fetch(url);
83
+ if (!response.ok)
84
+ throw new Error(`Timeline audio asset ${id} could not be read (${response.status})`);
85
+ const bytes = Buffer.from(await response.arrayBuffer());
86
+ const mime = response.headers.get('content-type') ?? '';
87
+ const suffix = mime.includes('wav') ? '.wav' : mime.includes('ogg') ? '.ogg' : mime.includes('flac') ? '.flac' : mime.includes('webm') ? '.webm' : '.mp3';
88
+ const name = crypto.createHash('sha256').update(bytes).digest('hex') + suffix;
89
+ await fs.mkdir(directory, { recursive: true });
90
+ const destination = path.join(directory, name);
91
+ let existing = null;
92
+ try {
93
+ existing = await fs.readFile(destination);
94
+ }
95
+ catch (e) {
96
+ if (e.code !== 'ENOENT')
97
+ throw e;
98
+ }
99
+ const valid = existing?.length === bytes.length && crypto.createHash('sha256').update(existing).digest('hex') === name.split('.')[0];
100
+ if (existing && !valid && !overwrite)
101
+ throw new Error(`Timeline asset ${name} is incomplete or corrupt; use --overwrite to replace it`);
102
+ if (!valid) {
103
+ try {
104
+ await writeOutput(destination, bytes, !!existing && overwrite);
105
+ }
106
+ catch (e) {
107
+ if (e.code !== 'EEXIST')
108
+ throw e;
109
+ const raced = await fs.readFile(destination);
110
+ if (raced.length !== bytes.length || crypto.createHash('sha256').update(raced).digest('hex') !== name.split('.')[0])
111
+ throw new Error(`Concurrent timeline asset ${name} failed content validation`);
112
+ }
113
+ }
114
+ const relative = `${path.basename(directory)}/${name}`;
115
+ if (!assets.some(a => a.id === id && a.kind === kind))
116
+ assets.push({ id, kind, file: relative, ...(audioInfo ? { audioInfo } : {}) });
117
+ return relative;
118
+ };
119
+ const voiceFiles = new Map();
120
+ for (const event of timeline.events)
121
+ if (event.type === 'narration' && event.source === 'clip' && typeof event.file === 'string') {
122
+ const source = event.file;
123
+ if (!voiceFiles.has(source))
124
+ voiceFiles.set(source, await copy(String(event.clipId ?? source), 'narration', source));
125
+ event.file = voiceFiles.get(source);
126
+ }
127
+ const resources = new Set();
128
+ for (const event of timeline.events)
129
+ if (event.media && typeof event.media === 'object')
130
+ for (const track of Object.values(event.media))
131
+ if (track.resource)
132
+ resources.add(track.resource);
133
+ for (const id of resources)
134
+ if (mediaAssets[id])
135
+ await copy(id, 'media', mediaAssets[id], mediaInfo[id]);
136
+ timeline.assets = assets;
137
+ await fs.mkdir(path.dirname(file), { recursive: true });
138
+ await writeOutput(file, JSON.stringify(timeline, null, 2), overwrite);
139
+ }
@@ -0,0 +1,2 @@
1
+ /** Optional local encoder. Capture and sample-clock calibration always happen before conversion. */
2
+ export declare function encodeMp4(input: string, output: string, overwrite?: boolean): Promise<void>;
@@ -0,0 +1,12 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { JoploError } from '@joplo-app/core';
3
+ /** Optional local encoder. Capture and sample-clock calibration always happen before conversion. */
4
+ export async function encodeMp4(input, output, overwrite = false) {
5
+ await new Promise((resolve, reject) => {
6
+ const child = spawn('ffmpeg', ['-nostdin', '-v', 'error', overwrite ? '-y' : '-n', '-i', input, '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-movflags', '+faststart', output], { stdio: ['ignore', 'ignore', 'pipe'] });
7
+ let stderr = '';
8
+ child.stderr.on('data', b => { stderr = (stderr + String(b)).slice(-16000); });
9
+ child.once('error', e => reject(new JoploError('EXPORT_FAILED', `MP4 needs local ffmpeg with H.264/AAC support: ${e.message}. Use .webm to export without it.`)));
10
+ child.once('close', code => code === 0 ? resolve() : reject(new JoploError('EXPORT_FAILED', `MP4 encoding failed (exit ${code}): ${stderr}`)));
11
+ });
12
+ }
@@ -5,7 +5,13 @@ export { kitAliases, locateWebAssets } from './web-assets.js';
5
5
  export declare function realProjectDir(dir: string): string;
6
6
  /** 不参与编译的项目子目录。 */
7
7
  export declare const IGNORED_DIRS: string[];
8
- export declare function isProjectSource(projectDir: string, file: string): boolean;
8
+ export declare function isProjectSource(projectDir: string, file: string, ignored?: readonly string[]): boolean;
9
+ /**
10
+ * 项目目录之外、不在 node_modules 里的源文件(例如一个仓库里多个 Joplo 项目共用的上层组件):
11
+ * 最近的 tsconfig.json 声明了 jsxImportSource "@joplo-app/kit" 时,同样按 Joplo 的 JSX 运行时转译(#61)。
12
+ * 其余文件(Joplo 自己的界面源码等)保持原样。每次都重新查找(只在转译时调用),新建或修改 tsconfig 立即生效。
13
+ */
14
+ export declare function isSharedJoploSource(projectDir: string, file: string): boolean;
9
15
  /** 语法错误的位置:从转译器报错里取 `文件:行:列`。 */
10
16
  export type SourceLoc = {
11
17
  file: string;
@@ -23,12 +23,48 @@ export function realProjectDir(dir) {
23
23
  }
24
24
  /** 不参与编译的项目子目录。 */
25
25
  export const IGNORED_DIRS = ['.joplo', 'dist', 'node_modules', '.git'];
26
- export function isProjectSource(projectDir, file) {
26
+ export function isProjectSource(projectDir, file, ignored = []) {
27
27
  if (!file.startsWith(projectDir + path.sep))
28
28
  return false;
29
29
  const rel = file.slice(projectDir.length + 1);
30
30
  const first = rel.split(path.sep)[0] ?? '';
31
- return !IGNORED_DIRS.includes(first);
31
+ return !IGNORED_DIRS.includes(first) && !ignored.some(p => rel.split(path.sep).join('/') === p || rel.split(path.sep).join('/').startsWith(p + '/'));
32
+ }
33
+ /** 读 tsconfig(允许注释与尾逗号),沿相对路径的 extends 找 compilerOptions.jsxImportSource。 */
34
+ function tsconfigJsxSource(file, depth = 0) {
35
+ let raw;
36
+ try {
37
+ const text = fs.readFileSync(file, 'utf8').replace(/\/\*[\s\S]*?\*\/|("(?:\\.|[^"\\])*")|\/\/[^\n]*/g, (m, str) => str ?? '').replace(/,(\s*[}\]])/g, '$1');
38
+ raw = JSON.parse(text);
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ const own = raw?.compilerOptions?.jsxImportSource;
44
+ if (typeof own === 'string')
45
+ return own;
46
+ const ext = raw?.extends;
47
+ if (depth < 5 && typeof ext === 'string' && ext.startsWith('.')) {
48
+ const next = path.resolve(path.dirname(file), ext.endsWith('.json') ? ext : `${ext}.json`);
49
+ return tsconfigJsxSource(next, depth + 1);
50
+ }
51
+ return null;
52
+ }
53
+ /**
54
+ * 项目目录之外、不在 node_modules 里的源文件(例如一个仓库里多个 Joplo 项目共用的上层组件):
55
+ * 最近的 tsconfig.json 声明了 jsxImportSource "@joplo-app/kit" 时,同样按 Joplo 的 JSX 运行时转译(#61)。
56
+ * 其余文件(Joplo 自己的界面源码等)保持原样。每次都重新查找(只在转译时调用),新建或修改 tsconfig 立即生效。
57
+ */
58
+ export function isSharedJoploSource(projectDir, file) {
59
+ if (!path.isAbsolute(file) || file.startsWith(projectDir + path.sep) || file.split(path.sep).includes('node_modules'))
60
+ return false;
61
+ for (let dir = path.dirname(file);; dir = path.dirname(dir)) {
62
+ const cfg = path.join(dir, 'tsconfig.json');
63
+ if (fs.existsSync(cfg))
64
+ return tsconfigJsxSource(cfg) === '@joplo-app/kit';
65
+ if (path.dirname(dir) === dir)
66
+ return false;
67
+ }
32
68
  }
33
69
  const stripAnsi = (s) => s.replace(/\x1b\[[0-9;]*m/g, '');
34
70
  export class ProjectSyntaxError extends Error {
@@ -83,7 +119,7 @@ export function joploProjectPlugin(projectDir, web = locateWebAssets(), publicCs
83
119
  css = css.replace(/@import\s+["']tailwindcss["']/, `@import ${JSON.stringify(tailwindIndexCss())}`);
84
120
  return { code: `${css}\n@source ${JSON.stringify(publicCssSource ?? projectDir)};\n`, map: null };
85
121
  }
86
- if (!isProjectSource(projectDir, file) || !/\.(tsx|ts|jsx|js|mts)$/.test(file))
122
+ if (!/\.(tsx|ts|jsx|js|mts)$/.test(file) || !(isProjectSource(projectDir, file) || isSharedJoploSource(projectDir, file)))
87
123
  return;
88
124
  const lang = file.endsWith('.tsx') ? 'tsx' : file.endsWith('.jsx') ? 'jsx' : file.endsWith('.js') ? 'js' : 'ts';
89
125
  try {
@@ -302,7 +302,7 @@ export class VoiceHub {
302
302
  this.jobs.set(projectId, job);
303
303
  let summary;
304
304
  try {
305
- summary = await cache.generate(segs, content ?? (typeof body.locale === 'string' ? body.locale.slice(0, 20) : 'en'), resolved, this.store, {
305
+ summary = await cache.generate(segs, content ?? project?.i18n?.default ?? (typeof body.locale === 'string' ? body.locale.slice(0, 20) : 'und'), resolved, this.store, {
306
306
  fetch: this.opts.fetch,
307
307
  signal: job.abort.signal,
308
308
  inflight: this.inflightOf(projectId),
@@ -347,7 +347,7 @@ export class VoiceHub {
347
347
  // Joplo Cloud 朗读不在播放时现场生成(会花用户的字数):只有「生成缺少的音频」或 joplo voice 才请求云端;缺音频的步骤用浏览器朗读
348
348
  if (resolved.profile?.kind === 'cloud')
349
349
  return ctx.send(409, { error: { code: 'CLOUD_GENERATE_ONLY', message: 'Joplo Cloud narration is generated only with Generate missing audio (or npx joplo voice); this step uses the browser voice' } }), true;
350
- const p = cache.generateOne(seg, content ?? (typeof body.locale === 'string' ? body.locale.slice(0, 20) : 'en'), resolved, this.store, {
350
+ const p = cache.generateOne(seg, content ?? project?.i18n?.default ?? (typeof body.locale === 'string' ? body.locale.slice(0, 20) : 'und'), resolved, this.store, {
351
351
  fetch: this.opts.fetch,
352
352
  inflight: this.inflightOf(projectId),
353
353
  cloud: this.opts.cloud,
@@ -21,13 +21,27 @@ export type VoiceRunOptions = {
21
21
  /** 托管朗读(CLI 的 cloud bridge 的 voice)。 */
22
22
  cloud?: CloudVoiceBridge;
23
23
  dryRun?: boolean;
24
+ /** Exact compiled work id; CLI resolves standalone entry keys without splitting ids. */
25
+ workId?: string;
26
+ scenarioId?: string;
24
27
  /** 只做这几种内容语言(必须是项目声明的);缺省全部。 */
25
28
  locales?: string[];
26
29
  onProgress?: (line: string) => void;
27
30
  /** 测试:OpenAI / ElevenLabs 的 fetch。 */
28
31
  fetch?: (url: string, init?: RequestInit) => Promise<Response>;
29
32
  };
33
+ /** Estimates use local cache only; remote Cloud cache hits can reduce the actual charge to zero. */
34
+ export type VoiceStepDetail = {
35
+ workId: string;
36
+ scenarioId: string;
37
+ stepId: string;
38
+ text: string;
39
+ chars: number;
40
+ missing: boolean;
41
+ estimatedBillableChars: number;
42
+ };
30
43
  export type VoiceRunLocale = {
44
+ details?: VoiceStepDetail[];
31
45
  locale: string | null;
32
46
  segments: number;
33
47
  missing: number;
@@ -67,5 +81,6 @@ export type VoiceRunResult = {
67
81
  } | null;
68
82
  };
69
83
  /** 选定方案的全部场景里,每一步要读的段(文字为空的跳过)。 */
70
- export declare function projectSegments(project: Project): Segment[];
84
+ export declare function voiceScenarioIds(project: Project, scope?: Pick<VoiceRunOptions, 'workId' | 'scenarioId'>): Set<string>;
85
+ export declare function projectSegments(project: Project, scope?: Pick<VoiceRunOptions, 'workId' | 'scenarioId'>): Segment[];
71
86
  export declare function generateProjectVoice(opts: VoiceRunOptions): Promise<VoiceRunResult>;
package/dist/voice-run.js CHANGED
@@ -1,12 +1,30 @@
1
- import { localizeProject, speakerRoleAt, spokenLine } from '@joplo-app/core';
1
+ import { JoploError, localizeProject, speakerRoleAt, spokenLine, spokenChars } from '@joplo-app/core';
2
2
  import { joploHome } from "./home.js";
3
3
  import { ProfileStore, UNSUPPORTED_MESSAGE, VoiceCache, VoiceError, estimateVoice, resolveVoices, voiceLocaleOf } from "./voice.js";
4
4
  /** 选定方案的全部场景里,每一步要读的段(文字为空的跳过)。 */
5
- export function projectSegments(project) {
5
+ export function voiceScenarioIds(project, scope = {}) {
6
+ const { workId, scenarioId } = scope;
7
+ if (workId && (!project.works[workId] || project.works[workId].draft))
8
+ throw new JoploError('USAGE', `Unknown or draft work: ${workId}`);
9
+ if (scenarioId && (!project.scenarios[scenarioId] || project.works[project.scenarios[scenarioId].workId]?.draft))
10
+ throw new JoploError('USAGE', `Unknown or draft scenario: ${scenarioId}`);
11
+ if (workId && scenarioId && project.scenarios[scenarioId]?.workId !== workId)
12
+ throw new JoploError('USAGE', `Scenario ${scenarioId} does not belong to work ${workId}`);
6
13
  const picked = new Set(Object.values(project.works).filter(w => !w.draft && (!w.featureId || project.features[w.featureId]?.pick === w.id)).map(w => w.id));
14
+ const ids = new Set(Object.values(project.scenarios).filter(sc => scenarioId ? sc.id === scenarioId : workId ? sc.workId === workId : picked.has(sc.workId)).map(sc => sc.id));
15
+ // Continuing chapters depend on their predecessors, even when selecting one chapter.
16
+ for (const id of ids) {
17
+ const from = project.scenarios[id]?.from;
18
+ if (from && project.scenarios[from] && !project.works[project.scenarios[from].workId]?.draft)
19
+ ids.add(from);
20
+ }
21
+ return ids;
22
+ }
23
+ export function projectSegments(project, scope = {}) {
24
+ const ids = voiceScenarioIds(project, scope);
7
25
  const out = [];
8
26
  for (const sc of Object.values(project.scenarios)) {
9
- if (!picked.has(sc.workId))
27
+ if (!ids.has(sc.id))
10
28
  continue;
11
29
  sc.steps.forEach((st, i) => {
12
30
  const line = spokenLine(st, st.caption, speakerRoleAt(project, sc.id, i + 1));
@@ -17,6 +35,7 @@ export function projectSegments(project) {
17
35
  return out;
18
36
  }
19
37
  export async function generateProjectVoice(opts) {
38
+ voiceScenarioIds(opts.project, opts);
20
39
  const status = opts.cloud ? await opts.cloud.status().catch(() => null) : null;
21
40
  const live = status?.signedIn && status.voice ? status.voice : null;
22
41
  const store = new ProfileStore(opts.home ?? joploHome(), process.env, { catalog: () => live });
@@ -55,9 +74,29 @@ export async function generateProjectVoice(opts) {
55
74
  for (const locale of locales) {
56
75
  const p = locale ? localizeProject(project, locale) : project;
57
76
  const resolved = resolveVoices(project.voiceConfig, selected, store, voiceLocaleOf(project, locale), fallback, cache.pins(), cache.officialCloud());
58
- const segments = projectSegments(p);
77
+ const segments = projectSegments(p, opts);
59
78
  const est = estimateVoice(segments, resolved, cache);
60
- const row = { locale, segments: segments.length, missing: est.steps, chars: est.chars, generated: 0, skipped: 0, failed: [] };
79
+ const seen = new Set();
80
+ const segmentById = new Map(segments.map(s => [s.stepId, s]));
81
+ const selectedIds = voiceScenarioIds(p, opts);
82
+ const details = [];
83
+ for (const sc of Object.values(p.scenarios))
84
+ for (const st of sc.steps) {
85
+ if (!selectedIds.has(sc.id))
86
+ continue;
87
+ const seg = segmentById.get(st.id);
88
+ if (!seg) {
89
+ details.push({ workId: sc.workId, scenarioId: sc.id, stepId: st.id, text: '', chars: 0, missing: false, estimatedBillableChars: 0 });
90
+ continue;
91
+ }
92
+ const planned = cache.plan(seg, resolved);
93
+ const missing = !!planned && !cache.clipOf(planned.key);
94
+ const estimatedBillableChars = missing && planned && !seen.has(planned.key) ? spokenChars(planned.text) : 0;
95
+ if (planned)
96
+ seen.add(planned.key);
97
+ details.push({ workId: sc.workId, scenarioId: sc.id, stepId: st.id, text: seg.text, chars: spokenChars(seg.text), missing, estimatedBillableChars });
98
+ }
99
+ const row = { details, locale, segments: segments.length, missing: est.steps, chars: est.chars, generated: 0, skipped: 0, failed: [] };
61
100
  result.locales.push(row);
62
101
  result.total.segments += segments.length;
63
102
  result.total.missing += est.steps;
@@ -65,7 +104,7 @@ export async function generateProjectVoice(opts) {
65
104
  if (opts.dryRun || !est.steps || result.exhausted)
66
105
  continue;
67
106
  opts.onProgress?.(`Generating ${est.steps} clip(s)${locale ? ` for ${locale}` : ''} with ${base.profile.name} (about ${est.chars} characters)...`);
68
- const summary = await cache.generate(segments, locale ?? 'en', resolved, store, {
107
+ const summary = await cache.generate(segments, locale ?? 'und', resolved, store, {
69
108
  cloud: opts.cloud,
70
109
  fetch: opts.fetch,
71
110
  project: project.name,
package/dist/voice.js CHANGED
@@ -827,7 +827,7 @@ export async function reuseSharedVoice(projectDir, project, shared, store, devCo
827
827
  continue;
828
828
  const file = rel.replace(/^voice\//, '');
829
829
  const bytes = await shared.fetch(rel).catch(() => null);
830
- if (bytes && cache.adopt(key, file, bytes, { stepId: st.id, fp, text, locale: locale ?? 'en', origin: 'shared' }))
830
+ if (bytes && cache.adopt(key, file, bytes, { stepId: st.id, fp, text, locale: locale ?? project.i18n?.default ?? 'und', origin: 'shared' }))
831
831
  reused++;
832
832
  }
833
833
  return reused;
@@ -883,7 +883,7 @@ export function bundleVoice(projectDir, project, outDir, store, devConfig, fallb
883
883
  .filter(([key, c]) => {
884
884
  if (c.stepId !== st.id || (locale && c.locale !== locale) || typeof c.text !== 'string')
885
885
  return false;
886
- const expected = automaticCaption(st.captionAuto, c.locale);
886
+ const expected = c.locale === 'und' ? st.caption : automaticCaption(st.captionAuto, c.locale);
887
887
  // 先证明文字仍属于当前内容,再考虑来源优先级;未知语言、旧文字或错配缓存键均不能发布。
888
888
  return expected !== null && c.text.replace(/\s+/g, ' ').trim() === expected.replace(/\s+/g, ' ').trim()
889
889
  && key === clipKey(c.fp, expected) && !!cache.clipOf(key);
@@ -0,0 +1,3 @@
1
+ import type { Diagnostic } from '@joplo-app/core';
2
+ /** Dev-service policy, deliberately outside the playback/compiler model. */
3
+ export declare function watchConfigDiagnostics(value: unknown, at?: string): Diagnostic[];
@@ -0,0 +1,10 @@
1
+ /** Dev-service policy, deliberately outside the playback/compiler model. */
2
+ export function watchConfigDiagnostics(value, at = 'joplo.config.ts:1:1') {
3
+ if (value === undefined)
4
+ return [];
5
+ const w = value;
6
+ if (!w || typeof w !== 'object' || Array.isArray(w) || Object.keys(w).some(k => k !== 'ignore') ||
7
+ (w.ignore !== undefined && (!Array.isArray(w.ignore) || w.ignore.some(p => typeof p !== 'string' || !p || /[\\:*?\[\]{}\x00]/.test(p) || p.startsWith('/') || p.split('/').some(s => !s || s === '.' || s === '..') || /^joplo\.config\.tsx?$/.test(p)))))
8
+ return [{ code: 'WATCH_CONFIG_INVALID', severity: 'error', source: 'schema', at, message: 'watch.ignore must contain project-relative file or directory paths (no globs, dot segments, or joplo.config.ts); restart dev after changing it' }];
9
+ return [];
10
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joplo-app/server",
3
- "version": "0.6.1",
3
+ "version": "0.7.1",
4
4
  "description": "Joplo 作品本地服务:dev 看板、build 静态发布站、render 截图,服务链接与嵌入交付",
5
5
  "license": "PolyForm-Shield-1.0.0",
6
6
  "type": "module",
@@ -15,9 +15,9 @@
15
15
  "dist"
16
16
  ],
17
17
  "dependencies": {
18
- "@joplo-app/core": "0.6.1",
19
- "@joplo-app/kit": "0.6.1",
20
- "@joplo-app/web": "0.6.1",
18
+ "@joplo-app/core": "0.7.1",
19
+ "@joplo-app/kit": "0.7.1",
20
+ "@joplo-app/web": "0.7.1",
21
21
  "@tailwindcss/vite": "4.3.4",
22
22
  "mediabunny": "1.65.2",
23
23
  "tailwindcss": "4.3.4",