@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/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 {};
@@ -0,0 +1,86 @@
1
+ /** Browser geometry diagnostics. No Core layout rules, resource generation or automatic edits. */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { JoploError } from '@joplo-app/core';
5
+ const browserSource = fs.readFileSync(path.join(import.meta.dirname, 'layout-audit-browser.js'), 'utf8').replace(/^\/\*[\s\S]*?\*\/\s*/, '');
6
+ function area(value) {
7
+ if (typeof value === 'string')
8
+ return value.trim().length > 0;
9
+ if (!value || typeof value !== 'object' || Array.isArray(value))
10
+ return false;
11
+ const v = value;
12
+ return Object.keys(v).every(k => ['x', 'y', 'width', 'height'].includes(k)) && ['x', 'y', 'width', 'height'].every(k => typeof v[k] === 'number' && Number.isFinite(v[k])) && v.width > 0 && v.height > 0;
13
+ }
14
+ export function layoutAuditOptions(value) {
15
+ const options = value === true ? {} : value;
16
+ if (!options || typeof options !== 'object' || Array.isArray(options) || Object.keys(options).some(k => !['content', 'safeAreas', 'important', 'exclude', 'everyMs'].includes(k)))
17
+ throw new JoploError('USAGE', 'Invalid layout audit options');
18
+ if (options.content !== undefined && !area(options.content) || options.safeAreas !== undefined && (!Array.isArray(options.safeAreas) || !options.safeAreas.every(area)))
19
+ throw new JoploError('USAGE', 'Layout content/safe areas must be CSS selectors or finite positive CSS rectangles');
20
+ if (options.everyMs !== undefined && (!Number.isFinite(options.everyMs) || options.everyMs < 20 || options.everyMs > 1000))
21
+ throw new JoploError('USAGE', 'Layout audit everyMs must be 20–1000 engine milliseconds');
22
+ for (const key of ['important', 'exclude'])
23
+ if (options[key] !== undefined && (!Array.isArray(options[key]) || !options[key].every(selector => typeof selector === 'string' && selector.trim())))
24
+ throw new JoploError('USAGE', `Layout audit ${key} must contain CSS selectors`);
25
+ return options;
26
+ }
27
+ export async function auditLayout(page, options, crop) {
28
+ layoutAuditOptions(options);
29
+ await page.evaluate(() => document.fonts.ready);
30
+ try {
31
+ return await page.evaluate(`(${browserSource})(${JSON.stringify({ ...options, crop })})`);
32
+ }
33
+ catch (error) {
34
+ throw new JoploError('RENDER_FAILED', `Layout geometry audit failed: ${error instanceof Error ? error.message : String(error)}`);
35
+ }
36
+ }
37
+ export function writeLayoutReport(file, samples, overwrite = false, sampleToleranceMs = null) {
38
+ fs.mkdirSync(path.dirname(file), { recursive: true });
39
+ const report = { schemaVersion: 1, kind: 'layout-audit', sampling: 'actual-rendered-css-geometry', sampleToleranceMs, findings: samples.reduce((n, s) => n + s.findings.length, 0), samples, limitations: [
40
+ 'Bounds are page CSS pixels after actual fonts and transforms. Evidence may be cropped/scaled; root/content bounds provide the coordinate origin. Static samples have no engine timestamp and do not verify motion.',
41
+ 'Importance is explicitly selected, never inferred from semantic meaning. Excluded decorations and intentional overlaps are not diagnosed. Geometry overlap is only a warning and does not prove paint occlusion.',
42
+ 'No contrast, screen-reader, reading-order or copyright assessment. Rotation, masks and nonrectangular clipping remain unknown. Transparent/hidden important elements are reported as unknown rather than guessed visible.',
43
+ 'Playback samples use the existing export engine clock. Commit and declared plugin/entry phase deadlines are observed on the export sample grid within sampleToleranceMs; phases interrupted by a later step or absent from plugin hints are not guaranteed. Unobserved intervals can contain additional problems.',
44
+ ] };
45
+ fs.writeFileSync(file, JSON.stringify(report, null, 2), overwrite ? undefined : { flag: 'wx' });
46
+ return { path: file, findings: report.findings, samples: samples.length };
47
+ }
48
+ export function layoutReportPath(out) { return out.replace(/\.[^.]+$/, '') + '.layout.json'; }
49
+ export function createLayoutAuditSession(config) {
50
+ const options = layoutAuditOptions(config.options), reportPath = layoutReportPath(config.out), samples = [];
51
+ if (config.sampleMs > 50)
52
+ throw new JoploError('USAGE', 'Motion layout audit requires sampleMs <= 50 to observe commit and animation phases');
53
+ if (fs.existsSync(reportPath) && !config.overwrite)
54
+ throw new JoploError('USAGE', `Layout report already exists: ${reportPath}`);
55
+ let nextInterval = 0, previous = '', pending = [];
56
+ return {
57
+ async sample(page, frame) {
58
+ const identity = `${frame.scenarioId}#${frame.position}`, changed = identity !== previous;
59
+ if (changed)
60
+ pending = [];
61
+ const due = pending.filter(p => p.identity === identity && p.atMs <= frame.atMs + .01);
62
+ pending = pending.filter(p => !due.includes(p));
63
+ if (!changed && !due.length && frame.atMs < nextInterval)
64
+ return;
65
+ const measured = await auditLayout(page, options, config.crop);
66
+ const phaseNames = [...new Set([...(changed ? [frame.position ? 'post-commit' : 'initial'] : []), ...due.map(p => p.phase), ...(!changed && !due.length ? ['interval'] : [])])];
67
+ for (const hint of measured.phases) {
68
+ const atMs = frame.atMs + hint.afterMs;
69
+ if (hint.afterMs > .01 && !pending.some(p => p.identity === identity && p.phase === hint.phase && Math.abs(p.atMs - atMs) <= config.sampleMs))
70
+ pending.push({ atMs, phase: hint.phase, identity });
71
+ }
72
+ let evidence = null;
73
+ if (measured.findings.length || measured.unknowns.length) {
74
+ const directory = config.out.replace(/\.[^.]+$/, '') + '.layout-evidence';
75
+ fs.mkdirSync(directory, { recursive: true });
76
+ evidence = path.join(directory, `${String(Math.round(frame.atMs)).padStart(8, '0')}.jpg`);
77
+ fs.writeFileSync(evidence, Buffer.from(frame.jpg, 'base64'), config.overwrite ? undefined : { flag: 'wx' });
78
+ }
79
+ const scenario = config.project.scenarios[frame.scenarioId];
80
+ samples.push({ ...measured, phaseHints: measured.phases, phases: phaseNames, atMs: frame.atMs, timeBasis: 'engine-clock', scenarioId: frame.scenarioId, position: frame.position, stepId: scenario?.steps[frame.position - 1]?.id ?? null, workId: scenario?.workId ?? null, evidence });
81
+ previous = identity;
82
+ nextInterval = frame.atMs + (options.everyMs ?? 250);
83
+ },
84
+ finish() { return writeLayoutReport(reportPath, samples, config.overwrite, config.sampleMs); },
85
+ };
86
+ }
@@ -1,5 +1,6 @@
1
1
  /** Node-only resource host. Work runs in a disposable process, never the browser. */
2
2
  import fs from 'node:fs';
3
+ import { mediaBudgetDiagnostics } from "./media-check.js";
3
4
  import { PluginKeyStore, compilerEnvironment } from "./plugin-keys.js";
4
5
  import { joploHome } from "./home.js";
5
6
  import path from 'node:path';
@@ -360,9 +361,9 @@ export async function inlineResources(project, requests, host) {
360
361
  ? Number(bytes.readBigUInt64BE(18) & 0xfffffffffn) * 1000 / (bytes.readUInt32BE(18) >>> 12)
361
362
  : inspected.info?.durationMs;
362
363
  diagnostics.push({ severity: 'info', source: 'structure', code: 'MEDIA_ASSET', at: request.source, message: `${request.plugin}/${request.id}: ${bytes.length} bytes${durationMs ? `, ${(durationMs / 1000).toFixed(3)} s` : ''}` });
363
- // 96 kbps is 0.72 MB/min; 0.75 allows framing, while short probes may still warn.
364
- if (bytes.length > 2 * 1024 * 1024 || durationMs && bytes.length / durationMs * 60000 > 750000)
365
- diagnostics.push({ severity: 'warning', source: 'structure', code: 'MEDIA_ASSET_LARGE', at: request.source, message: `${request.plugin}/${request.id}: audio exceeds 2 MiB per track or 0.75 MB/min (including MP3 context/padding); shorten or split the score (short loops also pay fixed context overhead)` });
364
+ // Short clips pay fixed codec context overhead; only assess bitrate after 15 seconds.
365
+ if (bytes.length > 2 * 1024 * 1024 || durationMs && durationMs >= 15000 && bytes.length / durationMs * 60000 > 750000)
366
+ diagnostics.push({ severity: 'warning', source: 'structure', code: 'MEDIA_ASSET_LARGE', at: request.source, message: `${request.plugin}/${request.id}: audio exceeds 2 MiB per track or 0.75 MB/min for clips at least 15 s long; shorten large tracks or review encoding bitrate (splitting does not reduce bitrate)` });
366
367
  }
367
368
  }
368
369
  if (r.diagnostic)
@@ -370,6 +371,7 @@ export async function inlineResources(project, requests, host) {
370
371
  }
371
372
  if (rawBytes)
372
373
  diagnostics.push({ severity: 'info', source: 'structure', code: 'MEDIA_BUDGET', message: `All audio: ${rawBytes} raw bytes, ${embeddedBytes} embedded base64/data-URI bytes` });
374
+ diagnostics.push(...mediaBudgetDiagnostics(project, audioInfo));
373
375
  return { assets, audioInfo, diagnostics, credits: [...credits], licenses: [...licenses], rawBytes, embeddedBytes };
374
376
  }
375
377
  export { nodeResourceIds as referencedResources, resolveResourceProps } from '@joplo-app/core';
@@ -7,3 +7,5 @@ export declare function inspectResources(project: Project | null, requests: Reso
7
7
  }>;
8
8
  /** Measure uninterrupted runs, not each individual step. Stop/replacement ends a run. */
9
9
  export declare function mediaDiagnostics(project: Project, info: Record<string, LocalResourceInfo>): Diagnostic[];
10
+ /** PCM memory is charged per resource, including both sides of an active crossfade. */
11
+ export declare function mediaBudgetDiagnostics(project: Project, info: Record<string, LocalResourceInfo | import('@joplo-app/kit/plugin').AudioRegion>): Diagnostic[];
@@ -16,7 +16,7 @@ export async function inspectResources(project, requests, host) {
16
16
  }
17
17
  /** Measure uninterrupted runs, not each individual step. Stop/replacement ends a run. */
18
18
  export function mediaDiagnostics(project, info) {
19
- const diagnostics = [];
19
+ const diagnostics = mediaBudgetDiagnostics(project, info);
20
20
  for (const sc of Object.values(project.scenarios)) {
21
21
  const runs = new Map();
22
22
  const finish = (key) => {
@@ -56,3 +56,33 @@ export function mediaDiagnostics(project, info) {
56
56
  }
57
57
  return diagnostics;
58
58
  }
59
+ /** PCM memory is charged per resource, including both sides of an active crossfade. */
60
+ export function mediaBudgetDiagnostics(project, info) {
61
+ const out = [], budget = 32 * 1024 * 1024;
62
+ for (const sc of Object.values(project.scenarios)) {
63
+ const seen = new Set();
64
+ for (const [position, snapshot, at] of [[0, sc.media, undefined], ...sc.steps.map((s, i) => [i + 1, s.media, s.source])]) {
65
+ const ids = [...new Set(Object.values(snapshot ?? {}).filter(t => t.stopAfterMs === undefined || t.stopAfterMs > 0).map(t => t.resource))].sort();
66
+ const key = ids.join(',');
67
+ if (!key || seen.has(key))
68
+ continue;
69
+ seen.add(key);
70
+ let known = 0;
71
+ const bytes = (rate) => ids.reduce((sum, id) => {
72
+ const m = info[id];
73
+ if (!m)
74
+ return sum;
75
+ const seconds = 'decodedFrames' in m ? m.decodedFrames / m.sourceSampleRate : (m.durationMs ?? 0) / 1000;
76
+ if (seconds > 0 && rate === 48000)
77
+ known++;
78
+ return sum + Math.ceil(seconds * rate) * ('channels' in m ? m.channels : 2) * 4;
79
+ }, 0);
80
+ const at48 = bytes(48000), at96 = bytes(96000);
81
+ const code = at48 > budget ? 'MEDIA_DECODE_BUDGET' : at96 > budget ? 'MEDIA_DECODE_HEADROOM' : null;
82
+ if (code)
83
+ out.push({ code, severity: 'warning', source: 'structure', at,
84
+ message: `${sc.id} position ${position}: simultaneous audio [${ids.join(', ')}] needs ${(at48 / 1048576).toFixed(2)} MiB at 48 kHz and ${(at96 / 1048576).toFixed(2)} MiB at 96 kHz (32 MiB decoded budget${known < ids.length ? '; some resources unknown' : ''}). Shorten overlapping tracks or avoid crossfading them; actual device sample rate and decoder padding affect usage.` });
85
+ }
86
+ }
87
+ return out;
88
+ }
@@ -0,0 +1,3 @@
1
+ /** Publish only complete files; exclusive link avoids an overwrite race between CLI processes. */
2
+ export declare function commitOutput(temporary: string, destination: string, overwrite?: boolean): Promise<void>;
3
+ export declare function writeOutput(destination: string, bytes: Uint8Array | string, overwrite?: boolean): Promise<void>;
@@ -0,0 +1,23 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ /** Publish only complete files; exclusive link avoids an overwrite race between CLI processes. */
5
+ export async function commitOutput(temporary, destination, overwrite = false) {
6
+ if (overwrite)
7
+ await fs.rename(temporary, destination);
8
+ else {
9
+ await fs.link(temporary, destination);
10
+ await fs.unlink(temporary);
11
+ }
12
+ }
13
+ export async function writeOutput(destination, bytes, overwrite = false) {
14
+ await fs.mkdir(path.dirname(destination), { recursive: true });
15
+ const temporary = path.join(path.dirname(destination), `.${path.basename(destination)}.${randomUUID()}.tmp`);
16
+ try {
17
+ await fs.writeFile(temporary, bytes, { flag: 'wx' });
18
+ await commitOutput(temporary, destination, overwrite);
19
+ }
20
+ finally {
21
+ await fs.rm(temporary, { force: true });
22
+ }
23
+ }
package/dist/project.d.ts CHANGED
@@ -11,6 +11,7 @@ export type CompileOutcome = {
11
11
  home: string | null;
12
12
  /** 启用的插件(D86):插件 id → 运行时入口的绝对路径(看板按它载入,build 按它打包)。 */
13
13
  pluginRuntimes: Record<string, string>;
14
+ watchIgnore?: string[];
14
15
  resources?: {
15
16
  requests: ResourceRequest[];
16
17
  host: LocalResources;
package/dist/project.js CHANGED
@@ -3,13 +3,14 @@
3
3
  * dev(看板、截图)与 build(发布站)共用这一条路径。
4
4
  */
5
5
  import fs from 'node:fs';
6
+ import { watchConfigDiagnostics } from "./watch-config.js";
6
7
  import path from 'node:path';
7
8
  import { inspectResources, mediaDiagnostics } from "./media-check.js";
8
9
  import { LocalResources, referencedResources } from "./local-resources.js";
9
10
  import { isPluginDef } from '@joplo-app/kit/plugin';
10
11
  import { compile } from '@joplo-app/core';
11
12
  import { discoverFiles, loadAuthoring, enabledPlugins } from '@joplo-app/core/node';
12
- import { isProjectSource } from "./vite-shared.js";
13
+ import { isProjectSource, isSharedJoploSource } from "./vite-shared.js";
13
14
  /** config({ plugins }) 里每个插件的运行时入口(编译器另外校验清单;这里只取存在的文件)。 */
14
15
  export function pluginRuntimesOf(plugins) {
15
16
  const out = {};
@@ -19,19 +20,38 @@ export function pluginRuntimesOf(plugins) {
19
20
  return out;
20
21
  }
21
22
  const LOC_IN_MESSAGE = /((?:[\w@.-]+\/)*[\w@.-]+\.(?:tsx|ts|jsx|js|mts)):(\d+):(\d+)/;
22
- /** 运行时错误(模块求值时抛出):从调用栈里找第一处项目文件位置。 */
23
+ /** 运行时错误(模块求值时抛出):从调用栈里找第一处项目文件位置(项目外按 Joplo JSX 转译的共享文件也算,路径相对项目目录)。 */
23
24
  function stackLoc(projectDir, e) {
24
25
  const stack = e instanceof Error ? (e.stack ?? '') : '';
26
+ const jsxMissing = jsxRuntimeMissing(e);
25
27
  for (const line of stack.split('\n')) {
26
28
  const m = /\(?((?:file:\/\/)?\/[^():\s]+):(\d+):(\d+)\)?\s*$/.exec(line);
27
29
  if (!m)
28
30
  continue;
29
31
  const file = decodeURIComponent(m[1].replace(/^file:\/\//, ''));
30
- if (isProjectSource(projectDir, file))
32
+ // JSX 运行时没生效(#61):抛错的就是那个没有按 Joplo JSX 转译的 TSX,不管它在不在项目里
33
+ const culprit = jsxMissing && /\.(tsx|jsx)$/.test(file) && !file.split(path.sep).includes('node_modules');
34
+ if (culprit || isProjectSource(projectDir, file) || isSharedJoploSource(projectDir, file))
31
35
  return `${path.relative(projectDir, file).split(path.sep).join('/')}:${m[2]}:${m[3]}`;
32
36
  }
33
37
  return null;
34
38
  }
39
+ /**
40
+ * JSX 没有走 Joplo 的运行时(项目外、最近的 tsconfig 不是 Joplo 的 JSX 设置):经典转译后找不到 React,
41
+ * 或自动转译去找 react/jsx-dev-runtime。返回能确定的那个文件(绝对路径),只知道是这类错误时返回 true。
42
+ */
43
+ function jsxRuntimeMissing(e) {
44
+ const msg = e instanceof Error ? e.message : '';
45
+ if (e instanceof ReferenceError && /\bReact is not defined\b/.test(msg))
46
+ return true;
47
+ const m = /Cannot find (?:module|package) '(?:react\/jsx-(?:dev-)?runtime|react)' imported from '([^']+)'/.exec(msg);
48
+ if (!m)
49
+ return false;
50
+ // 只有导入方是作者写的 TSX / JSX 时才是“JSX 运行时没生效”;依赖包真的缺 react 时保留原错误
51
+ const file = decodeURIComponent(m[1].replace(/^file:\/\//, ''));
52
+ return /\.(tsx|jsx)$/.test(file) && !file.split(path.sep).includes('node_modules') ? file : false;
53
+ }
54
+ const JSX_HINT = "was compiled without Joplo's JSX runtime. TSX outside the project uses the JSX settings of its nearest tsconfig.json: give that folder a tsconfig.json with jsx: \"react-jsxdev\" and jsxImportSource: \"@joplo-app/kit\", or start the file with /** @jsxRuntime automatic */ /** @jsxImportSource @joplo-app/kit */";
35
55
  export async function compileProject(server, projectDir, mode) {
36
56
  const errorAt = new Map(); // 载入失败的文件(绝对路径)→ 精确位置
37
57
  const importer = async (abs) => {
@@ -44,6 +64,14 @@ export async function compileProject(server, projectDir, mode) {
44
64
  const at = m ? `${m[1]}:${m[2]}:${m[3]}` : stackLoc(projectDir, e);
45
65
  if (at)
46
66
  errorAt.set(abs, at);
67
+ const jsx = jsxRuntimeMissing(e);
68
+ if (jsx) {
69
+ // 能从报错里确定文件时以它为准(位置只知道文件,记为第 1 行)
70
+ const culprit = typeof jsx === 'string' ? `${path.relative(projectDir, jsx).split(path.sep).join('/')}:1:1` : at;
71
+ if (culprit)
72
+ errorAt.set(abs, culprit);
73
+ throw new Error(`${culprit ? culprit.replace(/:\d+:\d+$/, '') : 'A TSX file'} ${JSX_HINT}`);
74
+ }
47
75
  throw e instanceof Error ? e : new Error(msg);
48
76
  }
49
77
  };
@@ -73,6 +101,7 @@ export async function compileProject(server, projectDir, mode) {
73
101
  }
74
102
  if (!loaded.authoring)
75
103
  return { project: null, diagnostics, home: null, pluginRuntimes: {} };
104
+ diagnostics.push(...watchConfigDiagnostics(loaded.authoring.config.watch, loaded.authoring.config.source));
76
105
  const home = loaded.authoring.config.home ?? null;
77
106
  const pluginRuntimes = pluginRuntimesOf(loaded.authoring.config.plugins);
78
107
  if (diagnostics.some((d) => d.severity === 'error'))
@@ -119,7 +148,7 @@ export async function compileProject(server, projectDir, mode) {
119
148
  if (result.diagnostic)
120
149
  diagnostics.push(result.diagnostic);
121
150
  }
122
- return { project: extra.length ? null : r.project, diagnostics: [...diagnostics, ...r.diagnostics, ...extra], home, pluginRuntimes, resources };
151
+ return { watchIgnore: loaded.authoring.config.watch?.ignore, project: extra.length ? null : r.project, diagnostics: [...diagnostics, ...r.diagnostics, ...extra], home, pluginRuntimes, resources };
123
152
  }
124
153
  const requestKey = (request) => JSON.stringify([request.plugin, request.compiler, request.input]);
125
154
  /** 项目目录 → 上一次编译检查到的资源元数据(按请求内容)。只是让第一遍编译用得上的提示;每次编译仍会重新检查并核对。 */
@@ -174,7 +203,7 @@ export function invalidateProjectModules(server, projectDir) {
174
203
  for (const env of Object.values(server.environments)) {
175
204
  const graph = env.moduleGraph;
176
205
  for (const mod of graph.idToModuleMap.values())
177
- if (mod.file && isProjectSource(projectDir, mod.file))
206
+ if (mod.file && (isProjectSource(projectDir, mod.file) || isSharedJoploSource(projectDir, mod.file)))
178
207
  graph.invalidateModule(mod);
179
208
  }
180
209
  }
package/dist/render.d.ts CHANGED
@@ -6,6 +6,8 @@ export { loadPlaywright, type PlaywrightModule } from './export-runtime.js';
6
6
  /** 浏览器启动失败时的一行提示(托管运行时与项目里的 Playwright 都适用:重装 Joplo 自己的导出组件)。 */
7
7
  export declare function launchHint(e: unknown): string;
8
8
  export declare function launch({ chromium }: PlaywrightModule): Promise<Browser>;
9
+ /** 截图不得覆盖项目源文件或 .joplo/(即使传了 overwrite)。 */
10
+ export declare function assertNotProjectData(projectDir: string, out: string): void;
9
11
  /**
10
12
  * 渲染路由的参数(纯函数):主题必填(调用方缺省时传项目主题);字体与线条(D55)只在指定且合法时带上,
11
13
  * 缺省 = 跟随主题,与 D55 之前的截图一致。