@joplo-app/server 0.6.2 → 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/film.js CHANGED
@@ -14,13 +14,20 @@
14
14
  * 停留时间与开着朗读的发布站一致。
15
15
  */
16
16
  import fs from 'node:fs';
17
+ import { createHash } from 'node:crypto';
17
18
  import path from 'node:path';
18
- import { JoploError, displaySceneId } from '@joplo-app/core';
19
+ import { JoploError, VIEWPORT_SIZE, displaySceneId } from '@joplo-app/core';
19
20
  import { createDev } from "./dev.js";
20
21
  import { realProjectDir } from "./vite-shared.js";
21
22
  import { joploHome } from "./home.js";
22
23
  import { loadPlaywright } from "./export-runtime.js";
23
- import { launch } from "./render.js";
24
+ import { assertNotProjectData, launch } from "./render.js";
25
+ import { encodeMp4 } from "./video-format.js";
26
+ import { commitOutput, writeOutput } from "./output-file.js";
27
+ import { createLayoutAuditSession } from "./layout-audit.js";
28
+ import { checkpointCommitsMatch, contentIdentity, exportRuntimeRoots } from "./checkpoint.js";
29
+ import { capture, geometryQuery } from "./capture.js";
30
+ import { frameTime, persistTimeline, playbackTimeline } from "./timeline.js";
24
31
  import { EXPORT_SIZE, defaultRecorder, srt } from "./export.js";
25
32
  /** 单帧整屏突变:变化像素占比至少这么多,且是前后帧的 CUT_RATIO 倍以上(排除持续的快速运镜)。 */
26
33
  export const CUT_CHANGED = 0.3;
@@ -29,6 +36,11 @@ export const CUT_RATIO = 2.5;
29
36
  export const STILL_CHANGED = 0.004;
30
37
  /** 一个像素的 RGB 平均差超过这个值才算“变了”(0–1)。 */
31
38
  const PIXEL_THRESHOLD = 0.08;
39
+ function distinctOutputs(paths) {
40
+ const values = paths.filter((p) => !!p).map(p => path.resolve(p));
41
+ if (new Set(values).size !== values.length)
42
+ throw new JoploError('USAGE', 'Export output, timeline, subtitles and checkpoint paths must differ');
43
+ }
32
44
  const MAX_MS = 10 * 60_000;
33
45
  /** 纯函数:从逐帧的相邻差找出硬切。changed[i] 是第 i 帧与第 i-1 帧之间变化像素的占比。 */
34
46
  export function findCuts(samples) {
@@ -78,15 +90,18 @@ const round = (n) => Math.round(n * 10000) / 10000;
78
90
  const esc = (t) => t.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
79
91
  /** 辅助页:解码 JPEG、裁掉字幕区,与上一帧、静止起点比较。状态留在页面里,每帧只传一次图片。 */
80
92
  const DIFF_PAGE = `<!doctype html><canvas id=c></canvas><script>
81
- let prev=null, anchor=null, anchorT=0;
93
+ let prev=null, anchor=null, anchorT=0, history=[];
82
94
  async function load(b64){ const img=new Image(); img.src='data:image/jpeg;base64,'+b64; await img.decode(); return img; }
83
95
  function pixels(img, h){ const c=document.getElementById('c'); c.width=img.width; c.height=h; const g=c.getContext('2d',{willReadFrequently:true}); g.drawImage(img,0,0); return g.getImageData(0,0,img.width,h).data; }
84
96
  function compare(a,b,th){ let sum=0, changed=0; const n=a.length/4; for(let i=0;i<a.length;i+=4){ const d=(Math.abs(a[i]-b[i])+Math.abs(a[i+1]-b[i+1])+Math.abs(a[i+2]-b[i+2]))/765; sum+=d; if(d>th) changed++; } return { diff: sum/n, changed: changed/n }; }
97
+ window.dump = (back=0) => {const state=history[Math.max(0,history.length-1-back)]||{prev,anchor,anchorT};return {prev:Array.from(state.prev||[]),anchor:Array.from(state.anchor||[]),anchorT:state.anchorT};};
98
+ window.restore = (s) => {prev=new Uint8ClampedArray(s.prev);anchor=new Uint8ClampedArray(s.anchor);anchorT=s.anchorT;history=[{prev,anchor,anchorT}];};
85
99
  window.step = async (b64, cropRatio, t, th, stillTh) => {
86
100
  const img = await load(b64); const d = pixels(img, Math.max(1, Math.round(img.height*cropRatio)));
87
101
  const adj = prev ? compare(prev, d, th) : { diff: 0, changed: 0 };
88
102
  prev = d;
89
103
  if (!anchor || compare(anchor, d, th).changed > stillTh) { anchor = d; anchorT = t; }
104
+ history.push({prev,anchor,anchorT}); if(history.length>12)history.shift();
90
105
  return { ...adj, still: t - anchorT };
91
106
  };
92
107
  </script>`;
@@ -110,6 +125,7 @@ async function flush(page) {
110
125
  }
111
126
  function check(opts) {
112
127
  const out = path.resolve(opts.out);
128
+ assertNotProjectData(opts.projectDir, out);
113
129
  if (fs.existsSync(out) && !opts.overwrite)
114
130
  throw new JoploError('USAGE', `Output file already exists: ${out}. To overwrite, pass overwrite: true (CLI: --overwrite)`);
115
131
  const dataDir = path.join(realProjectDir(opts.projectDir), '.joplo');
@@ -121,7 +137,7 @@ async function compiled(projectDir) {
121
137
  const server = await createDev({ projectDir, port: 0, watch: false, log: () => undefined });
122
138
  const payload = server.payload();
123
139
  if (!payload.project) {
124
- await server.close();
140
+ await server.close().catch(() => undefined);
125
141
  const errs = payload.diagnostics.filter((d) => d.severity === 'error');
126
142
  throw new JoploError('INVALID_SCHEMA', `Project compilation failed: ${errs.map((d) => `${d.at ?? ''} ${d.message}`).join('; ')}`, { diagnostics: payload.diagnostics });
127
143
  }
@@ -139,14 +155,38 @@ function recordUrl(base, projectId, project, o) {
139
155
  if (o.content !== undefined && !project.i18n?.locales.includes(o.content))
140
156
  throw new JoploError('USAGE', project.i18n ? `--content ${o.content} is not in config locales (${project.i18n.locales.join(', ')})` : `--content needs config({ locales }); this project has a single language`);
141
157
  const voice = o.voice ?? 'estimate';
142
- const q = new URLSearchParams({ render: '1', project: projectId, scenario: o.scenarioId, position: '0', theme: o.theme ?? project.theme ?? 'sketch', frame: '1', record: '1', ...(voice !== 'off' ? { voice } : {}), ...(o.chain ? { chain: '1' } : {}), ...(o.audio === false ? { audio: '0' } : {}), ...(o.locale ? { locale: o.locale } : {}), ...(o.content ? { content: o.content } : {}), ...(o.hide?.length ? { hide: o.hide.join(',') } : {}), ...(o.canvas ? { w: String(o.canvas.width), h: String(o.canvas.height) } : {}) });
158
+ const q = new URLSearchParams({ render: '1', project: projectId, scenario: o.scenarioId, position: '0', theme: o.theme ?? project.theme ?? 'sketch', frame: '1', record: '1', ...(voice !== 'off' ? { voice } : {}), ...(o.chain ? { chain: '1' } : {}), ...(o.audio === false ? { audio: '0' } : {}), ...(o.locale ? { locale: o.locale } : {}), ...(o.content ? { content: o.content } : {}), ...(o.hide?.length ? { hide: o.hide.join(',') } : {}), ...geometryQuery(o), ...(o.canvas ? { w: String(o.canvas.width), h: String(o.canvas.height) } : {}) });
143
159
  const device = project.scenes[displaySceneId(project, o.scenarioId, 0)]?.viewport === 'mobile' ? 'mobile' : 'desktop';
144
- return { url: `${base}?${q}`, size: EXPORT_SIZE[device], device };
160
+ return { url: `${base}?${q}`, size: o.logicalViewport ?? (o.noFrame ? VIEWPORT_SIZE[device] : EXPORT_SIZE[device]), device };
145
161
  }
146
162
  /** 胶片条:按引擎时间逐帧定格取样。 */
147
- export async function renderFilm(opts) {
163
+ async function samplePlayback(opts) {
164
+ if (opts.auditLayout && opts.resume)
165
+ throw new JoploError('USAGE', 'Layout audit requires a fresh render; do not combine it with --resume');
166
+ if (opts.auditLayout && opts.framesOnly)
167
+ throw new JoploError('USAGE', 'Layout audit supports static screenshots and --film, not --frames-out');
168
+ const baselineRssBytes = process.memoryUsage().rss;
148
169
  const projectDir = realProjectDir(opts.projectDir);
149
170
  const out = check({ ...opts, projectDir });
171
+ const metadataOut = check({ projectDir, out: out.replace(/(\.png)?$/i, '.json'), overwrite: opts.overwrite });
172
+ if (opts.timeline) {
173
+ check({ projectDir, out: opts.timeline, overwrite: opts.overwrite });
174
+ assertNotProjectData(projectDir, path.join(`${path.resolve(opts.timeline).replace(/\.json$/i, '')}.assets`, '__asset.wav'));
175
+ }
176
+ distinctOutputs([out, metadataOut, opts.timeline, opts.checkpoint]);
177
+ geometryQuery(opts);
178
+ if (opts.voice && !['real', 'estimate', 'off'].includes(opts.voice))
179
+ throw new JoploError('USAGE', '--voice must be real, estimate or off');
180
+ if (opts.hide?.some(h => !['cover', 'cursor', 'title', 'subtitles'].includes(h)))
181
+ throw new JoploError('USAGE', 'Unknown hide item');
182
+ if (opts.chapterTimeoutMs !== undefined && (!Number.isFinite(opts.chapterTimeoutMs) || opts.chapterTimeoutMs <= 0))
183
+ throw new JoploError('USAGE', 'chapterTimeoutMs must be positive');
184
+ if (opts.sampleMs !== undefined && !Number.isFinite(opts.sampleMs))
185
+ throw new JoploError('USAGE', 'sampleMs must be finite');
186
+ if ((opts.width === undefined) !== (opts.height === undefined))
187
+ throw new JoploError('USAGE', 'Film width and height must be provided together');
188
+ if (opts.width !== undefined && ![opts.width, opts.height].every(n => Number.isInteger(n) && n > 0 && n <= 8192))
189
+ throw new JoploError('USAGE', 'Film dimensions must be integers from 1 to 8192');
150
190
  const sampleMs = Math.max(20, Math.min(250, Math.round(opts.sampleMs ?? 50)));
151
191
  const every = Math.max(sampleMs, Math.round((opts.every ?? 250) / sampleMs) * sampleMs);
152
192
  const stillMs = opts.stillMs ?? 1500;
@@ -154,12 +194,37 @@ export async function renderFilm(opts) {
154
194
  const cellWidth = Math.max(120, Math.min(640, Math.round(opts.cellWidth ?? 224)));
155
195
  const playwright = await loadPlaywright({ home: joploHome(), projectDir });
156
196
  const { server, project } = await compiled(projectDir);
197
+ let fingerprint = '';
198
+ const checkpointFile = opts.checkpoint ? path.resolve(opts.checkpoint) : null;
199
+ if (checkpointFile)
200
+ assertNotProjectData(projectDir, checkpointFile);
201
+ let checkpoint = null;
202
+ if (opts.resume) {
203
+ if (!checkpointFile) {
204
+ await server.close();
205
+ throw new JoploError('USAGE', '--resume requires --checkpoint');
206
+ }
207
+ try {
208
+ checkpoint = JSON.parse(fs.readFileSync(checkpointFile, 'utf8'));
209
+ if (!checkpoint || typeof checkpoint.fingerprint !== 'string' || !Array.isArray(checkpoint.samples) || checkpoint.samples.length === 0 || !Array.isArray(checkpoint.commits) || checkpoint.commits.some(c => typeof c.stepId !== 'string' || !Number.isFinite(c.commitMs)))
210
+ throw new Error('Invalid checkpoint schema');
211
+ }
212
+ catch {
213
+ await server.close();
214
+ throw new JoploError('USAGE', 'Checkpoint is absent or invalid');
215
+ }
216
+ }
217
+ const startedAt = Date.now();
157
218
  let browser = null;
158
219
  try {
159
- const { url, size } = recordUrl(server.url, server.projectId, project, { ...opts, audio: false });
220
+ const audit = opts.auditLayout ? createLayoutAuditSession({ out, project, crop: opts.crop, options: opts.auditLayout, overwrite: opts.overwrite, sampleMs }) : null;
221
+ const canvas = opts.width && opts.height ? { width: opts.width, height: opts.height } : opts.logicalViewport;
222
+ const { url, size: defaultSize } = recordUrl(server.url, server.projectId, project, { ...opts, audio: false, voice: opts.voice ?? (opts.framesOnly ? 'real' : 'estimate'), ...(canvas ? { canvas } : {}) });
223
+ const size = canvas ?? defaultSize;
160
224
  browser = await launch(playwright);
161
- const ctx = await browser.newContext({ viewport: size, deviceScaleFactor: 0.5 });
225
+ const ctx = await browser.newContext({ viewport: size, deviceScaleFactor: opts.framesOnly ? opts.frameScale ?? 1 : 0.5 });
162
226
  const page = await ctx.newPage();
227
+ const captureSession = await ctx.newCDPSession(page);
163
228
  await page.clock.install({ time: 0 });
164
229
  // 先冻结空白页,避免读 now 与 pauseAt 两次调用之间的墙钟竞态。
165
230
  await page.clock.pauseAt(86_400_000);
@@ -180,32 +245,94 @@ export async function renderFilm(opts) {
180
245
  throw new JoploError('RENDER_FAILED', `Render route reported an error: ${err}`);
181
246
  // 加载期间也只按 16ms 网格推进;开播相位不随网络和字体加载耗时改变。
182
247
  await flush(page);
248
+ await page.evaluate(() => window.__JOPLO_RECORD__.prepare());
249
+ if (checkpointFile) {
250
+ const excluded = [out, metadataOut, opts.timeline, opts.timeline ? opts.timeline.replace(/\.json$/i, '') + '.assets' : null, opts.frames, checkpointFile].filter((p) => !!p);
251
+ const outStem = path.basename(out).replace(/\.png$/i, '');
252
+ for (const name of fs.existsSync(path.dirname(out)) ? fs.readdirSync(path.dirname(out)) : [])
253
+ if (name.startsWith(outStem + '-') && name.endsWith('.png'))
254
+ excluded.push(path.join(path.dirname(out), name));
255
+ const sourceIdentity = contentIdentity([projectDir, ...exportRuntimeRoots(projectDir, server.payload().plugins ?? {})], excluded);
256
+ const { projectDir: _projectDir, out: _out, overwrite: _overwrite, resume: _resume, checkpoint: _checkpoint, timeline: _timeline, frames: _frames, ...rendering } = opts;
257
+ const voiceIdentity = await page.evaluate(() => window.__JOPLO_RECORD__.voiceIdentity());
258
+ fingerprint = createHash('sha256').update(JSON.stringify({ version: 2, browser: browser.version(), platform: process.platform, arch: process.arch, node: process.versions.node, project, voiceIdentity, sourceIdentity, rendering, sampleMs, every, stillMs, plugins: server.payload().plugins })).digest('hex');
259
+ if (checkpoint?.fingerprint !== undefined && checkpoint.fingerprint !== fingerprint)
260
+ throw new JoploError('USAGE', 'Checkpoint source, version or rendering options changed; start a fresh render');
261
+ }
183
262
  const helper = await ctx.newPage();
184
263
  await helper.setContent(DIFF_PAGE);
185
264
  // 字幕与步骤标题条浮在画面上(D97):胶片条只看画面本身的运动,采样时把它们藏起来,文字换行不算镜头切换
186
265
  await page.addStyleTag({ content: '[data-jsubtitle],[data-testid="step-title"]{visibility:hidden!important}' });
187
266
  const stageRatio = 1;
188
267
  const samples = [];
268
+ let lastChapter = null;
269
+ let chapterStartedAt = Date.now();
270
+ const rssSamples = [];
271
+ let nextMemoryAt = 0;
189
272
  let tail = -1;
190
273
  // 第一帧在开播之前采(封面 / 第 0 步):开播那一下的切换也要量到
191
- for (let t = 0; t <= MAX_MS; t += sampleMs) {
192
- if (t === sampleMs) {
274
+ let previousTime = 0;
275
+ for (let index = 0;; index++) {
276
+ const t = opts.frameFps ? frameTime(index, opts.frameFps) : index * sampleMs;
277
+ if (t > MAX_MS)
278
+ break;
279
+ if (index === 1) {
193
280
  await page.evaluate(() => window.__JOPLO_RECORD__.play());
194
281
  await flush(page);
195
282
  }
196
283
  if (t > 0)
197
- await page.clock.runFor(sampleMs);
284
+ await page.clock.runFor(t - previousTime);
285
+ previousTime = t;
198
286
  await flush(page);
199
287
  const p = await page.evaluate(() => window.__JOPLO_RECORD__.progress);
200
288
  if (p.error)
201
289
  throw new JoploError('RENDER_FAILED', `Playback failed at ${t} ms: ${p.error}`);
202
- const jpg = (await page.locator('[data-jexport]').screenshot({ type: 'jpeg', quality: 72 })).toString('base64');
203
- const d = await helper.evaluate(([b64, crop, time, th, st]) => window.step(b64, crop, time, th, st), [jpg, stageRatio, t, PIXEL_THRESHOLD, STILL_CHANGED]);
204
- samples.push({ t, ...d, scenarioId: p.scenarioId, position: p.position, activeStep: p.activeStep, ...(t % every === 0 ? { jpg } : {}) });
205
- if (opts.frames && t % every === 0) {
290
+ if (p.scenarioId !== lastChapter)
291
+ chapterStartedAt = Date.now();
292
+ if (Date.now() - chapterStartedAt > (opts.chapterTimeoutMs ?? 180_000))
293
+ throw new JoploError('RENDER_FAILED', `Chapter ${p.scenarioId} timed out at ${t} ms (wall clock); completed checkpoint was preserved`);
294
+ if (t >= nextMemoryAt) {
295
+ rssSamples.push({ engineMs: t, rssBytes: process.memoryUsage().rss });
296
+ nextMemoryAt = t + 5000;
297
+ }
298
+ const restored = checkpoint?.samples[index];
299
+ if (restored) {
300
+ samples.push(restored);
301
+ if (index === checkpoint.samples.length - 1) {
302
+ const currentStep = p.scenarioId ? project.scenarios[p.scenarioId]?.steps[p.position - 1]?.id ?? null : null;
303
+ if (restored.scenarioId !== p.scenarioId || restored.position !== p.position || restored.activeStep !== p.activeStep || restored.stepId !== currentStep)
304
+ throw new JoploError('RENDER_FAILED', `Checkpoint stable state diverged at ${t} ms; rerun without --resume`);
305
+ const raw = await page.evaluate(() => window.__JOPLO_RECORD__.timeline());
306
+ const commits = playbackTimeline(raw).steps.map(s => ({ stepId: s.stepId, commitMs: s.commitMs }));
307
+ if (!checkpointCommitsMatch(checkpoint.commits, commits))
308
+ throw new JoploError('RENDER_FAILED', 'Checkpoint playback commits differ by more than 50 ms; rerun without --resume');
309
+ await helper.evaluate((state) => window.restore(state), checkpoint.diff);
310
+ }
311
+ lastChapter = p.scenarioId;
312
+ continue;
313
+ }
314
+ const jpg = (await capture(page, '[data-jexport]', opts.crop, 'jpeg', opts.framesOnly ? 95 : 72, captureSession, t)).toString('base64');
315
+ await audit?.sample(page, { atMs: t, scenarioId: p.scenarioId ?? opts.scenarioId, position: p.position, jpg });
316
+ const d = opts.framesOnly ? { diff: 0, changed: 0, still: 0 } : await helper.evaluate(([b64, crop, time, th, st]) => window.step(b64, crop, time, th, st), [jpg, stageRatio, t, PIXEL_THRESHOLD, STILL_CHANGED]);
317
+ samples.push({ t, ...d, scenarioId: p.scenarioId, position: p.position, activeStep: p.activeStep, stepId: p.scenarioId ? project.scenarios[p.scenarioId]?.steps[p.position - 1]?.id ?? null : null, ...(!opts.framesOnly && t % every === 0 ? { jpg } : {}) });
318
+ if (opts.frames && (opts.framesOnly || t % every === 0)) {
206
319
  fs.mkdirSync(opts.frames, { recursive: true });
207
320
  fs.writeFileSync(path.join(opts.frames, `${String(t).padStart(7, '0')}.jpg`), Buffer.from(jpg, 'base64'));
208
321
  }
322
+ if (checkpointFile && lastChapter && lastChapter !== p.scenarioId && samples.length > 4) {
323
+ // Keep a stable final-state anchor before the seam. Its small tail is
324
+ // recomputed, so accepted one-sample scheduling jitter never reuses seam pixels.
325
+ const back = Math.min(10, Math.ceil(100 / sampleMs) + 1), prefix = samples.slice(0, -back);
326
+ const diff = await helper.evaluate(back => window.dump(back), back);
327
+ const raw = await page.evaluate(() => window.__JOPLO_RECORD__.timeline());
328
+ const cutoff = prefix.at(-1).t;
329
+ const commits = playbackTimeline({ ...raw, events: raw.events.filter(e => e.at - (raw.startedAt ?? 0) <= cutoff) }).steps.map(s => ({ stepId: s.stepId, commitMs: s.commitMs }));
330
+ fs.mkdirSync(path.dirname(checkpointFile), { recursive: true });
331
+ const temp = `${checkpointFile}.${process.pid}.tmp`;
332
+ fs.writeFileSync(temp, JSON.stringify({ fingerprint, samples: prefix, diff, commits }));
333
+ fs.renameSync(temp, checkpointFile);
334
+ }
335
+ lastChapter = p.scenarioId;
209
336
  if (p.done && tail < 0)
210
337
  tail = t + 1000;
211
338
  if (tail >= 0 && t >= tail)
@@ -213,6 +340,11 @@ export async function renderFilm(opts) {
213
340
  }
214
341
  if (tail < 0)
215
342
  throw new JoploError('RENDER_FAILED', `Playback did not finish within ${MAX_MS / 60000} minutes of engine time`);
343
+ const raw = await page.evaluate(() => window.__JOPLO_RECORD__.timeline());
344
+ if (opts.timeline) {
345
+ const file = check({ projectDir, out: opts.timeline, overwrite: opts.overwrite });
346
+ await persistTimeline(file, playbackTimeline(raw), project.mediaAssets ?? {}, server.url, opts.overwrite, server.token, project.mediaInfo);
347
+ }
216
348
  const cuts = findCuts(samples);
217
349
  const stills = findStills(samples, stillMs);
218
350
  const boundaries = stepBoundaries(samples);
@@ -256,25 +388,36 @@ export async function renderFilm(opts) {
256
388
  const png = await sheet.screenshot({ type: 'png', fullPage: true });
257
389
  await sheet.close();
258
390
  fs.mkdirSync(path.dirname(file), { recursive: true });
259
- fs.writeFileSync(file, png, opts.overwrite ? undefined : { flag: 'wx' });
391
+ await writeOutput(file, png, opts.overwrite);
260
392
  files.push(file);
261
393
  }
262
394
  await ctx.close();
263
- const result = { path: files[0], files, durationMs, sampleMs, every, samples: samples.length, cuts, stills, boundaries, maxDiff: round(Math.max(0, ...samples.map((s) => s.diff))), warnings: [] };
395
+ const result = { ...(audit ? { audit: audit.finish() } : {}), path: files[0] ?? out, files, durationMs, sampleMs, every, samples: samples.length, cuts, stills, boundaries, maxDiff: round(Math.max(0, ...samples.map((s) => s.diff))), warnings: sampleMs > 50 ? ['Coarse analysis: transitions shorter than the computation interval may be missed; use 50 ms for final QA.'] : [], measurement: { baselineRssBytes, endRssBytes: process.memoryUsage().rss, memoryScope: 'node-process-lifetime', rssSamples, wallMs: Date.now() - startedAt, peakRssBytes: process.resourceUsage().maxRSS * 1024, resumedSamples: checkpoint?.samples.length ?? 0 } };
264
396
  // 完整的判读数据(每一步提交前后的最大帧差、硬切、静止)放在胶片条旁边,评审时可以引用具体数字
265
- fs.writeFileSync(out.replace(/(\.png)?$/i, '.json'), JSON.stringify({ ...result, frames: samples.map(({ jpg: _jpg, ...rest }) => rest) }, null, 1));
397
+ await writeOutput(metadataOut, JSON.stringify({ ...result, frames: samples.map(({ jpg: _jpg, ...rest }) => rest) }, null, 1), opts.overwrite);
266
398
  return result;
267
399
  }
268
400
  finally {
269
401
  await browser?.close().catch(() => undefined);
270
- await server.close();
402
+ await server.close().catch(() => undefined);
271
403
  }
272
404
  }
405
+ export function renderFilm(opts) { return samplePlayback(opts); }
273
406
  const HIDE = ['cover', 'cursor', 'title', 'subtitles'];
274
407
  /** 视频:与看板导出相同的录制器(真实时间)。 */
275
408
  export async function renderVideo(opts) {
276
409
  const projectDir = realProjectDir(opts.projectDir);
277
410
  const out = check({ ...opts, projectDir });
411
+ distinctOutputs([out, opts.timeline, opts.srt]);
412
+ geometryQuery(opts);
413
+ if (opts.auditLayout)
414
+ throw new JoploError('USAGE', 'Layout audit supports static screenshots and --film, not --video');
415
+ if (opts.crop)
416
+ throw new JoploError('USAGE', 'Video crop is not supported; use --viewport/--no-frame or --frames-out with --crop');
417
+ if (opts.timeline) {
418
+ check({ projectDir, out: opts.timeline, overwrite: opts.overwrite });
419
+ assertNotProjectData(projectDir, path.join(`${path.resolve(opts.timeline).replace(/\.json$/i, '')}.assets`, '__asset.wav'));
420
+ }
278
421
  if ((opts.width === undefined) !== (opts.height === undefined))
279
422
  throw new JoploError('USAGE', 'Video width and height must be provided together');
280
423
  const video = opts.width !== undefined ? { width: videoDimension('width', opts.width), height: videoDimension('height', opts.height) } : null;
@@ -288,21 +431,54 @@ export async function renderVideo(opts) {
288
431
  if (srtOut && srtOut === out)
289
432
  throw new JoploError('USAGE', 'The subtitle file must differ from the video file');
290
433
  const { server, project } = await compiled(projectDir);
434
+ let videoWork = null;
291
435
  try {
292
436
  // 输出分辨率(#55):视口就是视频分辨率,渲染路由把舞台等比缩放进这块画布(录屏按 CSS 像素取帧,deviceScaleFactor 不会让它更清晰)
293
437
  const { url, size } = recordUrl(server.url, server.projectId, project, { ...opts, voice, hide: opts.hide ?? [], ...(video ? { canvas: video } : {}) });
294
438
  fs.mkdirSync(path.dirname(out), { recursive: true });
295
- if (opts.overwrite)
296
- fs.rmSync(out, { force: true });
297
439
  const started = Date.now();
298
- const outcome = await defaultRecorder((dir) => loadPlaywright({ home: joploHome(), projectDir: dir }))({ projectDir, url, size: video ?? size, out, total: 0, progress: () => undefined, signal: new AbortController().signal, maxMs: MAX_MS });
440
+ const mp4 = path.extname(out).toLowerCase() === '.mp4';
441
+ videoWork = fs.mkdtempSync(path.join(path.dirname(out), '.joplo-video-'));
442
+ const recordingOut = path.join(videoWork, 'recording.webm');
443
+ const encodedOut = mp4 ? path.join(videoWork, 'encoded.mp4') : recordingOut;
444
+ const outcome = await defaultRecorder((dir) => loadPlaywright({ home: joploHome(), projectDir: dir }))({ projectDir, url, size: video ?? size, out: recordingOut, total: 0, progress: () => undefined, signal: new AbortController().signal, maxMs: MAX_MS });
445
+ if (mp4)
446
+ await encodeMp4(recordingOut, encodedOut);
299
447
  if (srtOut) {
300
448
  fs.mkdirSync(path.dirname(srtOut), { recursive: true });
301
449
  fs.writeFileSync(srtOut, srt(outcome?.cues ?? []), opts.overwrite ? undefined : { flag: 'wx' });
302
450
  }
303
- return { path: out, durationMs: Date.now() - started, size: video ?? size, srt: srtOut, voice: outcome?.voice ?? { mode: voice, missing: [] } };
451
+ if (opts.timeline && outcome?.timeline) {
452
+ const file = check({ projectDir, out: opts.timeline, overwrite: opts.overwrite });
453
+ await persistTimeline(file, outcome.timeline, project.mediaAssets ?? {}, server.url, opts.overwrite, server.token, project.mediaInfo);
454
+ }
455
+ await commitOutput(encodedOut, out, opts.overwrite);
456
+ return { ...(outcome?.sync ? { sync: outcome.sync } : {}), path: out, durationMs: Date.now() - started, size: video ?? size, srt: srtOut, voice: outcome?.voice ?? { mode: voice, missing: [] } };
304
457
  }
305
458
  finally {
306
- await server.close();
459
+ if (videoWork)
460
+ fs.rmSync(videoWork, { recursive: true, force: true });
461
+ await server.close().catch(() => undefined);
307
462
  }
308
463
  }
464
+ /** Public offline frame export. No audio synthesis or private browser bridge is needed by callers. */
465
+ export async function renderFrames(opts) {
466
+ const fps = opts.fps ?? 30;
467
+ if (!Number.isFinite(fps) || fps < 1 || fps > 120)
468
+ throw new JoploError('USAGE', 'fps must be from 1 to 120');
469
+ if (opts.scale !== undefined && (!Number.isFinite(opts.scale) || opts.scale <= 0 || opts.scale > 4))
470
+ throw new JoploError('USAGE', 'Frame scale must be above 0 and at most 4');
471
+ const dir = path.resolve(opts.framesOut);
472
+ assertNotProjectData(opts.projectDir, path.join(dir, '__frame.jpg'));
473
+ if (dir === realProjectDir(opts.projectDir))
474
+ throw new JoploError('USAGE', 'Frame output directory must differ from the project root');
475
+ if (fs.existsSync(dir) && fs.readdirSync(dir).length && !opts.overwrite)
476
+ throw new JoploError('USAGE', 'Frame directory is not empty; use --overwrite');
477
+ const timeline = opts.timeline ?? path.join(dir, 'timeline.json');
478
+ if (opts.overwrite && fs.existsSync(dir))
479
+ for (const name of fs.readdirSync(dir))
480
+ if (/^\d{7}\.jpg$/.test(name))
481
+ fs.rmSync(path.join(dir, name));
482
+ const result = await samplePlayback({ ...opts, hide: opts.hide ?? ['cover', 'cursor', 'title', 'subtitles'], out: path.join(dir, 'film.png'), frames: dir, timeline, frameFps: fps, frameScale: opts.scale, framesOnly: true });
483
+ return { directory: dir, timeline, fps, frames: result.samples, durationMs: result.durationMs, toleranceMs: 50 };
484
+ }
package/dist/index.d.ts CHANGED
@@ -13,9 +13,14 @@ export { startPreview, SITE_CONTENT_TYPES, type PreviewHandle } from './preview.
13
13
  export { generateProjectVoice, type VoiceRunOptions, type VoiceRunResult } from './voice-run.js';
14
14
  export type { CloudSpeechRequest, CloudSpeechResult, CloudVoice, CloudVoiceBridge, CloudVoiceCatalog, CloudVoiceInfo, CloudVoiceStatus, VoiceQuota } from './cloud.js';
15
15
  export { renderSheet, renderStep } from './render.js';
16
- export { renderFilm, renderVideo } from './film.js';
16
+ export { renderFilm, renderVideo, renderFrames } from './film.js';
17
17
  export { EXPORT_DOWNLOAD_MB, PLAYWRIGHT_VERSION, SETUP_COMMAND, exportRuntimeStatus, installExportRuntime, uninstallExportRuntime, type ExportRuntimeStatus, type InstallProgress, type InstallResult } from './export-runtime.js';
18
18
  export { buildFeatureDiff, publicIRFromHtml, type DiffBuildOptions, type DiffBuildResult } from './feature-diff.js';
19
19
  export { generateResources } from './resources-run.js';
20
20
  export { LocalResources } from './local-resources.js';
21
21
  export { inspectResources, mediaDiagnostics } from './media-check.js';
22
+ export { watchConfigDiagnostics } from './watch-config.js';
23
+ export { assetUsage, type AssetUsageReport, type AssetUsageEntry, type AssetUsageReference } from './asset-usage.js';
24
+ export type { ExportCrop, FramesOptions, FilmOptions, FilmResult, VideoOptions, VideoResult } from './contract.js';
25
+ export type { PlaybackTimeline, PlaybackEvent } from './timeline.js';
26
+ export { auditLayout, createLayoutAuditSession, type LayoutAuditOptions, type LayoutFinding, type LayoutAuditSample } from './layout-audit.js';
package/dist/index.js CHANGED
@@ -3,9 +3,12 @@ export { buildSite } from "./build.js";
3
3
  export { startPreview, SITE_CONTENT_TYPES } from "./preview.js";
4
4
  export { generateProjectVoice } from "./voice-run.js";
5
5
  export { renderSheet, renderStep } from "./render.js";
6
- export { renderFilm, renderVideo } from "./film.js";
6
+ export { renderFilm, renderVideo, renderFrames } from "./film.js";
7
7
  export { EXPORT_DOWNLOAD_MB, PLAYWRIGHT_VERSION, SETUP_COMMAND, exportRuntimeStatus, installExportRuntime, uninstallExportRuntime } from "./export-runtime.js";
8
8
  export { buildFeatureDiff, publicIRFromHtml } from "./feature-diff.js";
9
9
  export { generateResources } from "./resources-run.js";
10
10
  export { LocalResources } from "./local-resources.js";
11
11
  export { inspectResources, mediaDiagnostics } from "./media-check.js";
12
+ export { watchConfigDiagnostics } from "./watch-config.js";
13
+ export { assetUsage } from "./asset-usage.js";
14
+ export { auditLayout, createLayoutAuditSession } from "./layout-audit.js";
@@ -0,0 +1,114 @@
1
+ /* Browser-only read-only geometry audit; source-injected to avoid transpiler helpers. */
2
+ (options) => {
3
+ const root = document.querySelector('[data-jexport],[data-jshot],[data-jrender]') || document.querySelector('[data-joplo-stage]');
4
+ if (!root) throw new Error('Layout audit has no render surface');
5
+ const box = r => ({ x: r.left ?? r.x, y: r.top ?? r.y, width: r.width, height: r.height });
6
+ const right = r => r.x + r.width, bottom = r => r.y + r.height;
7
+ const outside = (a, b) => a.x < b.x - 1 || a.y < b.y - 1 || right(a) > right(b) + 1 || bottom(a) > bottom(b) + 1;
8
+ const intersection = (a, b) => Math.max(0, Math.min(right(a), right(b)) - Math.max(a.x, b.x)) * Math.max(0, Math.min(bottom(a), bottom(b)) - Math.max(a.y, b.y));
9
+ const unknowns = [], rootBox = box(root.getBoundingClientRect());
10
+ const matches = selector => Array.from(root.querySelectorAll(selector)).concat(root.matches(selector) ? [root] : []);
11
+ const area = value => {
12
+ if (typeof value !== 'string') return { ...value, x: rootBox.x + value.x, y: rootBox.y + value.y };
13
+ const elements = matches(value);
14
+ if (elements.length !== 1) throw new Error(`Layout area ${value} must match exactly one element inside the render surface`);
15
+ return box(elements[0].getBoundingClientRect());
16
+ };
17
+ const content = options.content ? area(options.content) : options.crop ? area(options.crop) : rootBox;
18
+ if (content.width <= 0 || content.height <= 0 || outside(content, rootBox)) throw new Error('Layout content area must be inside the render surface');
19
+ const safeAreas = (options.safeAreas ?? []).map(area);
20
+ const exclude = (options.exclude ?? []).flatMap(matches);
21
+ const ignored = el => exclude.some(x => x === el || x.contains(el));
22
+ const styledVisible = el => {
23
+ for (let e = el; e; e = e.parentElement) {
24
+ const s = getComputedStyle(e);
25
+ if (s.display === 'none' || s.visibility === 'hidden' || s.visibility === 'collapse' || Number(s.opacity) === 0 || e.hasAttribute('hidden')) return false;
26
+ if (e === root) break;
27
+ }
28
+ return true;
29
+ };
30
+ const identity = el => {
31
+ const owner = el.closest('[data-jid]:not([data-jtype="#text"])');
32
+ return { elementId: owner?.getAttribute('data-jid') ?? null, source: owner?.getAttribute('data-jat') ?? null, tag: el.tagName.toLowerCase() };
33
+ };
34
+ const unsupportedClip = el => {
35
+ for (let e = el; e; e = e.parentElement) {
36
+ const s = getComputedStyle(e), matrix = s.transform === 'none' ? null : new DOMMatrixReadOnly(s.transform);
37
+ if (s.clipPath !== 'none' || s.maskImage !== 'none' || (matrix && (Math.abs(matrix.b) > .0001 || Math.abs(matrix.c) > .0001))) return true;
38
+ if (e === root) break;
39
+ }
40
+ return false;
41
+ };
42
+ const important = [...new Set((options.important ?? []).flatMap(selector => {
43
+ const found = matches(selector);
44
+ if (!found.length) unknowns.push({ elementId: null, source: null, reason: `Important selector ${selector} matched no rendered elements; visibility is unknown` });
45
+ return found;
46
+ }))].filter(el => !ignored(el));
47
+ const importantSet = important.filter(styledVisible);
48
+ for (const el of important.filter(el => !styledVisible(el))) unknowns.push({ ...identity(el), reason: 'Important element is hidden or transparent at this sample; no visible geometry claim is made' });
49
+ const isImportant = el => importantSet.some(x => x === el || x.contains(el));
50
+ const findings = [], textBoxes = [], seen = new Set(), unknownOwners = new Set();
51
+ const add = (code, el, rect, detail, other) => {
52
+ const id = identity(el), key = `${code}:${id.elementId}:${detail}`;
53
+ if (seen.has(key)) return;
54
+ seen.add(key); findings.push({ code, severity: 'warning', ...id, box: rect, detail, ...(other ? { relatedBox: other } : {}) });
55
+ };
56
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
57
+ let node, count = 0;
58
+ while ((node = walker.nextNode())) {
59
+ if (++count > 5000) break;
60
+ if (!node.textContent?.trim()) continue;
61
+ const el = node.parentElement;
62
+ if (!el || ignored(el) || !styledVisible(el) || /^(script|style|noscript)$/.test(el.tagName.toLowerCase())) continue;
63
+ if (unsupportedClip(el)) {
64
+ const owner = identity(el);
65
+ if (!unknownOwners.has(owner.elementId)) { unknownOwners.add(owner.elementId); unknowns.push({ ...owner, reason: 'Rotation, mask or nonrectangular clipping makes exact text visibility unknown; inspect the evidence' }); }
66
+ continue;
67
+ }
68
+ const range = document.createRange(); range.selectNodeContents(node);
69
+ for (const r of range.getClientRects()) {
70
+ if (r.width < .1 || r.height < .1) continue;
71
+ const rect = box(r); textBoxes.push({ ...identity(el), box: rect, text: node.textContent.trim().slice(0, 100) });
72
+ if (outside(rect, content)) add('TEXT_OUTSIDE_CONTENT', el, rect, 'Rendered text line exceeds the declared content frame', content);
73
+ for (let parent = el; parent && parent !== root.parentElement; parent = parent.parentElement) {
74
+ const style = getComputedStyle(parent), clipX = /hidden|clip|auto|scroll/.test(style.overflowX), clipY = /hidden|clip|auto|scroll/.test(style.overflowY);
75
+ if (!clipX && !clipY) continue;
76
+ const r = parent.getBoundingClientRect(), sx = parent.offsetWidth ? r.width / parent.offsetWidth : 1, sy = parent.offsetHeight ? r.height / parent.offsetHeight : 1;
77
+ const boundary = { x: r.left + parent.clientLeft * sx, y: r.top + parent.clientTop * sy, width: parent.clientWidth * sx, height: parent.clientHeight * sy };
78
+ if ((clipX && (rect.x < boundary.x - 1 || right(rect) > right(boundary) + 1)) || (clipY && (rect.y < boundary.y - 1 || bottom(rect) > bottom(boundary) + 1))) {
79
+ add('TEXT_CLIPPED', el, rect, 'Rendered text line crosses an ancestor padding-box clipping boundary', boundary); break;
80
+ }
81
+ }
82
+ if (isImportant(el)) for (const region of safeAreas) if (intersection(rect, region) > 1) add('IMPORTANT_IN_SAFE_AREA', el, rect, 'Declared important text intersects a reserved safe area', region);
83
+ }
84
+ range.detach();
85
+ }
86
+ const elements = importantSet.slice(0, 500).map(el => ({ el, ...identity(el), box: box(el.getBoundingClientRect()) }));
87
+ for (let i = 0; i < elements.length; i++) {
88
+ const a = elements[i];
89
+ if (a.box.width <= 0 || a.box.height <= 0) continue;
90
+ if (unsupportedClip(a.el)) { unknowns.push({ ...identity(a.el), reason: 'Declared important geometry has rotation/masking; visibility is unknown' }); continue; }
91
+ if (outside(a.box, content)) add('IMPORTANT_OUTSIDE_CONTENT', a.el, a.box, 'Declared important element exceeds the content frame', content);
92
+ for (const region of safeAreas) if (intersection(a.box, region) > 1) add('IMPORTANT_IN_SAFE_AREA', a.el, a.box, 'Declared important element intersects a reserved safe area', region);
93
+ for (let j = i + 1; j < elements.length; j++) {
94
+ const b = elements[j];
95
+ if (a.el.contains(b.el) || b.el.contains(a.el)) continue;
96
+ const overlap = intersection(a.box, b.box), smaller = Math.min(a.box.width * a.box.height, b.box.width * b.box.height);
97
+ if (smaller > 0 && overlap / smaller > .1) add('POSSIBLE_OCCLUSION', a.el, a.box, `Geometry-only heuristic overlaps ${b.elementId ?? b.tag}; paint order and actual occlusion are not proven`, b.box);
98
+ }
99
+ }
100
+ const phases = [];
101
+ for (const animation of root.getAnimations({ subtree: true })) {
102
+ if (animation.id !== 'jenter') continue;
103
+ const current = animation.currentTime, end = animation.effect?.getComputedTiming().endTime;
104
+ if (typeof current === 'number' && typeof end === 'number' && Number.isFinite(end) && end >= current) phases.push({ phase: 'enter-end', afterMs: end - current });
105
+ }
106
+ for (const el of [...root.querySelectorAll('[data-joplo-audit-phases]'), ...(root.hasAttribute('data-joplo-audit-phases') ? [root] : [])]) {
107
+ try {
108
+ const hints = JSON.parse(el.getAttribute('data-joplo-audit-phases'));
109
+ if (!Number.isFinite(hints.clockMs) || !Array.isArray(hints.phases)) throw new Error();
110
+ for (const hint of hints.phases) if (['camera-end', 'camera-waypoint', 'drift-mid', 'drift-end'].includes(hint.phase) && Number.isFinite(hint.atMs) && hint.atMs >= hints.clockMs) phases.push({ phase: hint.phase, afterMs: hint.atMs - hints.clockMs });
111
+ } catch { unknowns.push({ ...identity(el), reason: 'Invalid plugin audit phase hints were ignored' }); }
112
+ }
113
+ return { root: rootBox, content, safeAreas, elements: elements.map(({ el, ...rest }) => rest), textBoxes, findings, unknowns, phases, truncated: count > 5000 || important.length > 500, coordinates: 'page-css-pixels', fonts: { status: document.fonts.status, families: [...new Set(textBoxes.map(t => t.elementId).filter(Boolean).map(id => { const el = root.querySelector(`[data-jid="${CSS.escape(id)}"]`); return el ? getComputedStyle(el).fontFamily : ''; }))] } };
114
+ }
@@ -0,0 +1,94 @@
1
+ import type { Page } from 'playwright-core';
2
+ import { type Project } from '@joplo-app/core';
3
+ import type { ExportCrop } from './contract.js';
4
+ export type LayoutAuditOptions = {
5
+ content?: ExportCrop;
6
+ safeAreas?: ExportCrop[];
7
+ important?: string[];
8
+ exclude?: string[]; /** Interval between diagnostic probes in engine milliseconds, 20–1000 (default 250). */
9
+ everyMs?: number;
10
+ };
11
+ export type LayoutBox = {
12
+ x: number;
13
+ y: number;
14
+ width: number;
15
+ height: number;
16
+ };
17
+ export type LayoutFinding = {
18
+ code: 'TEXT_OUTSIDE_CONTENT' | 'TEXT_CLIPPED' | 'IMPORTANT_IN_SAFE_AREA' | 'IMPORTANT_OUTSIDE_CONTENT' | 'POSSIBLE_OCCLUSION';
19
+ severity: 'warning';
20
+ elementId: string | null;
21
+ source: string | null;
22
+ tag: string;
23
+ box: LayoutBox;
24
+ relatedBox?: LayoutBox;
25
+ detail: string;
26
+ };
27
+ type Identity = {
28
+ elementId: string | null;
29
+ source: string | null;
30
+ tag?: string;
31
+ };
32
+ type Geometry = {
33
+ coordinates: 'page-css-pixels';
34
+ root: LayoutBox;
35
+ content: LayoutBox;
36
+ safeAreas: LayoutBox[];
37
+ elements: (Identity & {
38
+ box: LayoutBox;
39
+ })[];
40
+ textBoxes: (Identity & {
41
+ box: LayoutBox;
42
+ text: string;
43
+ })[];
44
+ findings: LayoutFinding[];
45
+ unknowns: (Identity & {
46
+ reason: string;
47
+ })[];
48
+ phases: {
49
+ phase: string;
50
+ afterMs: number;
51
+ }[];
52
+ fonts: {
53
+ status: string;
54
+ families: string[];
55
+ };
56
+ truncated: boolean;
57
+ };
58
+ export type LayoutAuditSample = Omit<Geometry, 'phases'> & {
59
+ phaseHints?: Geometry['phases'];
60
+ atMs: number | null;
61
+ timeBasis: 'engine-clock' | 'static-final-state';
62
+ phases: string[];
63
+ scenarioId: string;
64
+ position: number;
65
+ stepId: string | null;
66
+ workId: string | null;
67
+ evidence: string | null;
68
+ };
69
+ export type LayoutAuditResult = {
70
+ path: string;
71
+ findings: number;
72
+ samples: number;
73
+ };
74
+ export declare function layoutAuditOptions(value: boolean | LayoutAuditOptions): LayoutAuditOptions;
75
+ export declare function auditLayout(page: Page, options: LayoutAuditOptions, crop?: ExportCrop): Promise<Geometry>;
76
+ export declare function writeLayoutReport(file: string, samples: LayoutAuditSample[], overwrite?: boolean, sampleToleranceMs?: number | null): LayoutAuditResult;
77
+ export declare function layoutReportPath(out: string): string;
78
+ export declare function createLayoutAuditSession(config: {
79
+ out: string;
80
+ project: Project;
81
+ crop?: ExportCrop;
82
+ options: boolean | LayoutAuditOptions;
83
+ overwrite?: boolean;
84
+ sampleMs: number;
85
+ }): {
86
+ sample(page: Page, frame: {
87
+ atMs: number;
88
+ scenarioId: string;
89
+ position: number;
90
+ jpg: string;
91
+ }): Promise<void>;
92
+ finish(): LayoutAuditResult;
93
+ };
94
+ export {};