@joplo-app/server 0.2.17 → 0.3.0

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.
@@ -0,0 +1,47 @@
1
+ import type { ResourceRequest, PluginKey, LocalResourceInfo, AudioRegion } from '@joplo-app/kit/plugin';
2
+ import { type Project, type Diagnostic } from '@joplo-app/core';
3
+ type Result = {
4
+ url?: string;
5
+ audio?: AudioRegion;
6
+ credit?: string;
7
+ license?: string;
8
+ bytes?: number;
9
+ diagnostic?: Diagnostic;
10
+ };
11
+ export declare class LocalResources {
12
+ readonly directory: string;
13
+ private entries;
14
+ readonly keys: Record<string, readonly PluginKey[]>;
15
+ private bundles;
16
+ private descriptions;
17
+ constructor(directory: string, entries: Record<string, string>, keys?: Record<string, readonly PluginKey[]>);
18
+ private bundle;
19
+ describe(request: ResourceRequest): Promise<{
20
+ persistent: boolean;
21
+ credits?: number;
22
+ timeoutMs?: number;
23
+ inspect?: boolean;
24
+ requiresAttribution?: boolean;
25
+ }>;
26
+ /** Lightweight author-only metadata. No rendering, bank download or provider spend. */
27
+ inspect(request: ResourceRequest): Promise<{
28
+ info?: LocalResourceInfo;
29
+ diagnostic?: Diagnostic;
30
+ }>;
31
+ ensure(request: ResourceRequest, limits?: {
32
+ timeoutMs?: number;
33
+ maxBytes?: number;
34
+ allowSpend?: boolean;
35
+ home?: string;
36
+ }): Promise<Result>;
37
+ }
38
+ export declare function inlineResources(project: Project, requests: ResourceRequest[], host: LocalResources): Promise<{
39
+ assets: Record<string, string>;
40
+ audioInfo: Record<string, AudioRegion>;
41
+ diagnostics: Diagnostic[];
42
+ credits: string[];
43
+ licenses: string[];
44
+ rawBytes: number;
45
+ embeddedBytes: number;
46
+ }>;
47
+ export { nodeResourceIds as referencedResources, resolveResourceProps } from '@joplo-app/core';
@@ -0,0 +1,368 @@
1
+ /** Node-only resource host. Work runs in a disposable process, never the browser. */
2
+ import fs from 'node:fs';
3
+ import { PluginKeyStore, compilerEnvironment } from "./plugin-keys.js";
4
+ import { joploHome } from "./home.js";
5
+ import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+ import { spawn } from 'node:child_process';
8
+ import { build } from 'vite';
9
+ import { AudioRegionSchema, nodeResourceIds as referencedResources, mediaResourceIds } from '@joplo-app/core';
10
+ const inflight = new Map();
11
+ const digest = (s) => crypto.createHash('sha256').update(s).digest('hex');
12
+ const LIMIT = 50 * 1024 * 1024;
13
+ /** Serialize separate board/build processes too; crashed owners do not poison the cache. */
14
+ async function resourceLease(directory, timeoutMs = 65000) {
15
+ const token = crypto.randomUUID(), started = Date.now();
16
+ while (true) {
17
+ try {
18
+ fs.mkdirSync(directory);
19
+ fs.writeFileSync(path.join(directory, 'owner.json'), JSON.stringify({ pid: process.pid, token }));
20
+ return () => {
21
+ try {
22
+ if (JSON.parse(fs.readFileSync(path.join(directory, 'owner.json'), 'utf8')).token === token)
23
+ fs.rmSync(directory, { recursive: true, force: true });
24
+ }
25
+ catch { /* already removed */ }
26
+ };
27
+ }
28
+ catch (e) {
29
+ if (e.code !== 'EEXIST')
30
+ throw e;
31
+ try {
32
+ const owner = JSON.parse(fs.readFileSync(path.join(directory, 'owner.json'), 'utf8'));
33
+ try {
34
+ process.kill(owner.pid, 0);
35
+ }
36
+ catch (e) {
37
+ if (e.code === 'ESRCH') {
38
+ fs.rmSync(directory, { recursive: true, force: true });
39
+ continue;
40
+ }
41
+ }
42
+ }
43
+ catch {
44
+ if (Date.now() - (fs.statSync(directory, { throwIfNoEntry: false })?.mtimeMs ?? 0) > 65000) {
45
+ fs.rmSync(directory, { recursive: true, force: true });
46
+ continue;
47
+ }
48
+ }
49
+ if (Date.now() - started > timeoutMs)
50
+ throw Object.assign(new Error('Timed out waiting for resource compiler'), { code: 'LOCAL_RESOURCE_TIMEOUT' });
51
+ await new Promise(r => setTimeout(r, 25));
52
+ }
53
+ }
54
+ }
55
+ export class LocalResources {
56
+ directory;
57
+ entries;
58
+ keys;
59
+ bundles = new Map();
60
+ descriptions = new Map();
61
+ constructor(directory, entries, keys = {}) {
62
+ this.directory = directory;
63
+ this.entries = entries;
64
+ this.keys = keys;
65
+ }
66
+ bundle(plugin) {
67
+ if (!this.bundles.has(plugin))
68
+ this.bundles.set(plugin, (async () => {
69
+ const entry = this.entries[plugin];
70
+ if (!entry || !fs.existsSync(entry))
71
+ throw new Error(`Plugin ${plugin}: local entry missing; reinstall the plugin`);
72
+ const result = await build({ configFile: false, envDir: false, root: this.directory, logLevel: 'silent', ssr: { noExternal: true }, build: { ssr: entry, write: false, minify: false, sourcemap: false, rolldownOptions: { output: { format: 'es', codeSplitting: false, banner: "import {fileURLToPath as __joploFile} from 'node:url'; import {dirname as __joploDir} from 'node:path'; const __filename=__joploFile(import.meta.url), __dirname=__joploDir(__filename);" } } } });
73
+ const output = Array.isArray(result) ? result[0] : result;
74
+ if (!output || !('output' in output))
75
+ throw new Error('Local entry could not be bundled');
76
+ return output.output.filter(x => x.type === 'chunk').map(x => x.code).join('\n');
77
+ })());
78
+ return this.bundles.get(plugin);
79
+ }
80
+ async describe(request) {
81
+ const code = await this.bundle(request.plugin), dir = path.join(this.directory, '.joplo', 'resources');
82
+ fs.mkdirSync(dir, { recursive: true });
83
+ const entry = path.join(dir, `${digest(code)}.mjs`);
84
+ if (!fs.existsSync(entry)) {
85
+ const tmp = `${entry}.${crypto.randomUUID()}.tmp`;
86
+ fs.writeFileSync(tmp, code);
87
+ fs.renameSync(tmp, entry);
88
+ }
89
+ const key = JSON.stringify([entry, request.compiler, request.input]);
90
+ if (!this.descriptions.has(key))
91
+ this.descriptions.set(key, new Promise((resolve, reject) => {
92
+ // Even metadata is evaluated in a bounded child: plugin top-level code never runs in the host.
93
+ const script = `import {pathToFileURL} from 'node:url';
94
+ let input='';for await(const chunk of process.stdin)input+=chunk;const r=JSON.parse(input);
95
+ try {const c=(await import(pathToFileURL(r.entry).href)).default?.compilers?.[r.compiler];
96
+ if(!c)throw new Error();const estimate=c.estimate?.(r.input);
97
+ if(estimate && (!Number.isFinite(estimate.credits)||estimate.credits<0))throw new Error();
98
+ process.stdout.write(JSON.stringify({requiresAttribution:c.requiresAttribution===true,persistent:c.persistent===true,inspect:typeof c.inspect==='function',timeoutMs:Math.max(1000,Math.min(180000,c.timeoutMs??30000)),...(estimate?{credits:estimate.credits}:{})}));
99
+ }catch{process.exitCode=1;}`;
100
+ const child = spawn(process.execPath, ['--input-type=module', '-e', script], { stdio: ['pipe', 'pipe', 'ignore'], env: compilerEnvironment() });
101
+ let output = '', settled = false;
102
+ const finish = (ok) => { if (settled)
103
+ return; settled = true; clearTimeout(timer); child.kill('SIGKILL'); if (ok) {
104
+ try {
105
+ resolve(JSON.parse(output));
106
+ return;
107
+ }
108
+ catch { }
109
+ } reject(new Error('Invalid local resource declaration or estimate')); };
110
+ const timer = setTimeout(() => finish(false), 5000);
111
+ child.stdout.on('data', b => { output += b; if (output.length > 4096)
112
+ finish(false); });
113
+ child.on('error', () => finish(false));
114
+ child.on('close', status => finish(status === 0));
115
+ child.stdin.on('error', () => { });
116
+ child.stdin.end(JSON.stringify({ entry, compiler: request.compiler, input: request.input }));
117
+ }));
118
+ return this.descriptions.get(key);
119
+ }
120
+ /** Lightweight author-only metadata. No rendering, bank download or provider spend. */
121
+ async inspect(request) {
122
+ try {
123
+ if (!(await this.describe(request)).inspect)
124
+ return {};
125
+ const code = await this.bundle(request.plugin), dir = path.join(this.directory, '.joplo', 'resources');
126
+ const key = digest(JSON.stringify([code, request.compiler, request.input]));
127
+ const cache = path.join(dir, `${key}.info.json`);
128
+ try {
129
+ return { info: JSON.parse(fs.readFileSync(cache, 'utf8')) };
130
+ }
131
+ catch { /* no successful inspection cached */ }
132
+ const job = fs.mkdtempSync(path.join(dir, 'inspect-'));
133
+ try {
134
+ const entry = path.join(dir, `${digest(code)}.mjs`);
135
+ const info = await new Promise((resolve, reject) => {
136
+ const script = `import {pathToFileURL} from 'node:url';
137
+ let s=''; for await(const c of process.stdin)s+=c; const r=JSON.parse(s);
138
+ try { const c=(await import(pathToFileURL(r.entry).href)).default.compilers[r.compiler];
139
+ process.stdout.write(JSON.stringify({info:await c.inspect(r.input,{directory:r.directory})}));
140
+ }catch(e){process.stdout.write(JSON.stringify({error:String(e.message)}));process.exitCode=1;}`;
141
+ const child = spawn(process.execPath, ['--input-type=module', '-e', script], { cwd: job, stdio: ['pipe', 'pipe', 'ignore'], detached: process.platform !== 'win32' });
142
+ let output = '', settled = false;
143
+ const finish = (error, value) => {
144
+ if (settled)
145
+ return;
146
+ settled = true;
147
+ clearTimeout(timer);
148
+ try {
149
+ if (process.platform !== 'win32')
150
+ process.kill(-child.pid, 'SIGKILL');
151
+ else
152
+ child.kill('SIGKILL');
153
+ }
154
+ catch { /* exited */ }
155
+ if (error)
156
+ reject(error);
157
+ else
158
+ resolve(value);
159
+ };
160
+ const timer = setTimeout(() => finish(new Error('Local resource inspection timed out (30s)')), 30000);
161
+ child.stdout.on('data', b => { output += b; if (output.length > 128 * 1024)
162
+ finish(new Error('Local resource metadata exceeds 128 KiB')); });
163
+ child.on('error', e => finish(e));
164
+ child.on('close', status => { try {
165
+ const r = JSON.parse(output);
166
+ if (status || !r.info || typeof r.info !== 'object')
167
+ throw new Error(r.error || 'Invalid resource metadata');
168
+ finish(undefined, r.info);
169
+ }
170
+ catch (e) {
171
+ finish(e);
172
+ } });
173
+ child.stdin.on('error', () => { });
174
+ child.stdin.end(JSON.stringify({ entry, compiler: request.compiler, input: request.input, directory: job }));
175
+ });
176
+ const tmp = `${cache}.${crypto.randomUUID()}.tmp`;
177
+ fs.writeFileSync(tmp, JSON.stringify(info));
178
+ fs.renameSync(tmp, cache);
179
+ return { info };
180
+ }
181
+ finally {
182
+ fs.rmSync(job, { recursive: true, force: true });
183
+ }
184
+ }
185
+ catch (e) {
186
+ return { diagnostic: { severity: 'warning', source: 'structure', code: 'LOCAL_RESOURCE_INSPECTION_FAILED', message: `${request.plugin}/${request.compiler}: ${e.message}`, at: request.source?.replace(this.directory + path.sep, '') ?? 'joplo.config.ts:1:1' } };
187
+ }
188
+ }
189
+ async ensure(request, limits = {}) {
190
+ const warning = (code, message) => ({ diagnostic: { severity: code === 'LOCAL_RESOURCE_ATTRIBUTION_MISSING' ? 'error' : 'warning', source: 'structure', code, message: `${request.plugin}/${request.compiler}: ${message}`, at: request.source ? request.source.replace(this.directory + path.sep, '') : 'joplo.config.ts:1:1' } });
191
+ try {
192
+ const secrets = limits.allowSpend ? new PluginKeyStore(limits.home ?? joploHome()).resolve(request.plugin, this.keys[request.plugin] ?? []) : {};
193
+ const redact = (text) => Object.values(secrets).reduce((out, key) => out.split(key).join('[REDACTED]'), text);
194
+ const code = await this.bundle(request.plugin);
195
+ const description = await this.describe(request);
196
+ // Compiler version is part of the bundled declaration; code changes also invalidate.
197
+ const key = digest(JSON.stringify([request.plugin, request.compiler, code, request.input]));
198
+ const dir = path.join(this.directory, '.joplo', 'resources');
199
+ const cache = path.join(dir, `${key}.json`);
200
+ const maxBytes = Math.min(LIMIT, limits.maxBytes ?? LIMIT);
201
+ const cached = () => {
202
+ if (description.persistent)
203
+ return undefined;
204
+ try {
205
+ const saved = JSON.parse(fs.readFileSync(cache, 'utf8'));
206
+ if (typeof saved.url !== 'string' || !Number.isInteger(saved.bytes) || saved.bytes < 0 || saved.bytes > maxBytes || saved.url.length > maxBytes * 1.4 + 256)
207
+ return undefined;
208
+ if (saved.audio)
209
+ saved.audio = AudioRegionSchema.parse(saved.audio);
210
+ if (description.requiresAttribution && (!saved.credit || !saved.license))
211
+ return warning('LOCAL_RESOURCE_ATTRIBUTION_MISSING', 'Cached audio has no attribution/license; restore the complete artifact cache or render it again');
212
+ return saved;
213
+ }
214
+ catch {
215
+ return undefined;
216
+ }
217
+ };
218
+ const hit = cached();
219
+ if (hit)
220
+ return hit;
221
+ const lock = `${cache}:${maxBytes}:${!!limits.allowSpend}:${limits.timeoutMs ?? 30000}`;
222
+ const existing = inflight.get(lock);
223
+ if (existing) {
224
+ const r = await existing;
225
+ return r.diagnostic ? warning(r.diagnostic.code, r.diagnostic.message) : r;
226
+ }
227
+ const work = (async () => {
228
+ fs.mkdirSync(dir, { recursive: true });
229
+ const release = description.persistent ? () => { } : await resourceLease(`${cache}.lock`, (description.timeoutMs ?? 30000) + 5000);
230
+ try {
231
+ const hit = cached();
232
+ if (hit)
233
+ return hit;
234
+ const entry = path.join(dir, `${digest(code)}.mjs`);
235
+ if (!fs.existsSync(entry)) {
236
+ const tmp = `${entry}.${crypto.randomUUID()}.tmp`;
237
+ fs.writeFileSync(tmp, code);
238
+ fs.renameSync(tmp, entry);
239
+ }
240
+ const jobDir = fs.mkdtempSync(path.join(dir, 'job-'));
241
+ try {
242
+ const result = await new Promise((resolve, reject) => {
243
+ const script = `import {pathToFileURL} from 'node:url';
244
+ const alive=setInterval(()=>{},1000); let input=''; for await (const chunk of process.stdin) input+=chunk;
245
+ const r=JSON.parse(input); const m=await import(pathToFileURL(r.entry).href);
246
+ const c=m.default?.compilers?.[r.compiler];
247
+ try {
248
+ if(!c || typeof c.version!=='string' || !/^[a-z]+\\/[a-z0-9.+-]+$/.test(c.mime)) throw new Error('Invalid local compiler declaration');
249
+ const artifact=await c.compile(r.input,{directory:r.directory,projectDir:r.projectDir,cacheDir:r.cacheDir,keys:r.keys,allowSpend:r.allowSpend,maxBytes:r.maxBytes});
250
+ const bytes=artifact instanceof Uint8Array?artifact:artifact?.bytes;
251
+ if(!(bytes instanceof Uint8Array)) throw new Error('Compiler must return bytes');
252
+ if(c.requiresAttribution&&(!artifact.credit||!artifact.license))throw Object.assign(new Error('Audio attribution/license missing'),{code:'LOCAL_RESOURCE_ATTRIBUTION_MISSING'});
253
+ if(bytes.byteLength>r.maxBytes) throw Object.assign(new Error('Resource exceeds size limit'),{code:'LOCAL_RESOURCE_TOO_LARGE'});
254
+ process.stdout.write(JSON.stringify({mime:c.mime,data:Buffer.from(bytes).toString('base64'),bytes:bytes.byteLength,...(artifact.audio?{audio:artifact.audio}:{}),...(artifact.credit?{credit:artifact.credit}:{}),...(artifact.license?{license:artifact.license}:{})}));
255
+ } catch(e) { process.stdout.write(JSON.stringify({error:String(e.message),code:e.code})); process.exitCode=1; } finally { clearInterval(alive); }`;
256
+ const child = spawn(process.execPath, ['--input-type=module', '-e', script], { cwd: jobDir, stdio: ['pipe', 'pipe', 'pipe'], env: compilerEnvironment(), detached: process.platform !== 'win32' });
257
+ let stdout = '', stderr = '', settled = false;
258
+ const kill = () => { try {
259
+ if (process.platform !== 'win32')
260
+ process.kill(-child.pid, 'SIGKILL');
261
+ else
262
+ child.kill('SIGKILL');
263
+ }
264
+ catch { /* exited */ } };
265
+ const finish = (error, value) => { if (settled)
266
+ return; settled = true; clearTimeout(timer); kill(); if (error)
267
+ reject(error);
268
+ else
269
+ resolve(value); };
270
+ const timer = setTimeout(() => finish(Object.assign(new Error('Compilation timed out'), { code: 'LOCAL_RESOURCE_TIMEOUT' })), (limits.allowSpend ? 21 * 60 * 1000 : Math.min(180000, limits.timeoutMs ?? description.timeoutMs ?? 30000)));
271
+ child.stdout.on('data', b => { stdout += b; if (stdout.length > maxBytes * 1.4 + 16384)
272
+ finish(Object.assign(new Error('Resource exceeds size limit'), { code: 'LOCAL_RESOURCE_TOO_LARGE' })); });
273
+ child.stderr.on('data', b => { if (stderr.length < 4000)
274
+ stderr += b; });
275
+ child.on('error', e => finish(e));
276
+ child.on('close', status => { try {
277
+ const value = JSON.parse(stdout);
278
+ if (status || value.error)
279
+ finish(Object.assign(new Error(value.error ?? stderr), { code: value.code }));
280
+ else
281
+ finish(undefined, value);
282
+ }
283
+ catch {
284
+ finish(new Error(stderr || 'Compiler exited without a resource'));
285
+ } });
286
+ child.stdin.on('error', () => { });
287
+ child.stdin.end(JSON.stringify({ entry, compiler: request.compiler, input: request.input, directory: jobDir, projectDir: this.directory, cacheDir: path.join(limits.home ?? joploHome(), 'plugins', request.plugin, 'cache'), keys: secrets, allowSpend: limits.allowSpend === true, maxBytes }));
288
+ });
289
+ if (Object.values(secrets).some(key => result.mime.includes(key) || Buffer.from(result.data, 'base64').includes(Buffer.from(key))))
290
+ throw new Error('Compiler output contains a local credential');
291
+ if (result.audio)
292
+ result.audio = AudioRegionSchema.parse(result.audio);
293
+ const url = `data:${result.mime};base64,${result.data}`;
294
+ const tmp = `${cache}.${crypto.randomUUID()}.tmp`;
295
+ if (!description.persistent) {
296
+ fs.writeFileSync(tmp, JSON.stringify({ url, bytes: result.bytes, audio: result.audio, credit: result.credit, license: result.license }));
297
+ fs.renameSync(tmp, cache);
298
+ }
299
+ return { url, bytes: result.bytes, audio: result.audio, credit: result.credit, license: result.license };
300
+ }
301
+ catch (e) {
302
+ const err = e;
303
+ const safeCode = redact(err.code ?? '');
304
+ return warning(/^LOCAL_RESOURCE_[A-Z0-9_]+$/.test(safeCode) ? safeCode : 'LOCAL_RESOURCE_FAILED', redact(err.message).slice(0, 2000));
305
+ }
306
+ finally {
307
+ fs.rmSync(jobDir, { recursive: true, force: true });
308
+ }
309
+ }
310
+ finally {
311
+ release();
312
+ }
313
+ })();
314
+ inflight.set(lock, work);
315
+ try {
316
+ return await work;
317
+ }
318
+ finally {
319
+ inflight.delete(lock);
320
+ }
321
+ }
322
+ catch (e) {
323
+ return warning('LOCAL_RESOURCE_FAILED', e instanceof Error ? e.message : String(e));
324
+ }
325
+ }
326
+ }
327
+ export async function inlineResources(project, requests, host) {
328
+ const used = mediaResourceIds(project);
329
+ for (const id of referencedResources(project))
330
+ used.add(id);
331
+ const assets = {}, diagnostics = [], credits = new Set(), licenses = new Set(), audioInfo = {};
332
+ let rawBytes = 0, embeddedBytes = 0;
333
+ for (const request of requests)
334
+ if (used.has(request.id)) {
335
+ const r = await host.ensure(request);
336
+ if (r.url) {
337
+ assets[request.id] = r.url;
338
+ const inspected = await host.inspect(request);
339
+ if (inspected.diagnostic)
340
+ diagnostics.push(inspected.diagnostic);
341
+ if (r.credit)
342
+ credits.add(r.credit);
343
+ if (r.license)
344
+ licenses.add(r.license);
345
+ if (r.audio)
346
+ audioInfo[request.id] = r.audio;
347
+ if (r.url.startsWith('data:audio/')) {
348
+ const bytes = Buffer.from(r.url.slice(r.url.indexOf(',') + 1), 'base64');
349
+ // Native FLAC STREAMINFO stores the precise PCM length, including a non-looping tail.
350
+ rawBytes += bytes.length;
351
+ embeddedBytes += r.url.length;
352
+ const durationMs = r.audio ? r.audio.contentFrames / r.audio.sourceSampleRate * 1000 : bytes.toString('ascii', 0, 4) === 'fLaC' && bytes.length >= 42
353
+ ? Number(bytes.readBigUInt64BE(18) & 0xfffffffffn) * 1000 / (bytes.readUInt32BE(18) >>> 12)
354
+ : inspected.info?.durationMs;
355
+ 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` : ''}` });
356
+ // 96 kbps is 0.72 MB/min; 0.75 allows framing, while short probes may still warn.
357
+ if (bytes.length > 2 * 1024 * 1024 || durationMs && bytes.length / durationMs * 60000 > 750000)
358
+ 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)` });
359
+ }
360
+ }
361
+ if (r.diagnostic)
362
+ diagnostics.push(r.diagnostic);
363
+ }
364
+ if (rawBytes)
365
+ diagnostics.push({ severity: 'info', source: 'structure', code: 'MEDIA_BUDGET', message: `All audio: ${rawBytes} raw bytes, ${embeddedBytes} embedded base64/data-URI bytes` });
366
+ return { assets, audioInfo, diagnostics, credits: [...credits], licenses: [...licenses], rawBytes, embeddedBytes };
367
+ }
368
+ export { nodeResourceIds as referencedResources, resolveResourceProps } from '@joplo-app/core';
@@ -1,3 +1,4 @@
1
+ import { projectThemes } from '@joplo-app/core';
1
2
  import crypto from 'node:crypto';
2
3
  import { JoploError, LOCAL_REVIEW_MAX_EVENTS, LOCAL_REVIEW_MAX_FILE_BYTES, LocalReviewSession, localReviewStatus, stateAt } from '@joplo-app/core';
3
4
  import { localReviewFile, localReviewWatcherCount, writeLocalReview } from '@joplo-app/core/node';
@@ -13,7 +14,7 @@ export function localReviewRevision(project, optionId) {
13
14
  const option = project.options[optionId];
14
15
  const feature = project.features[option.featureId];
15
16
  const own = (values) => Object.fromEntries(Object.entries(values).filter(([, v]) => v.optionId === optionId || (v.optionId == null && (v.featureId == null || v.featureId === option.featureId))));
16
- const value = { name: project.name, description: project.description, theme: project.theme, themes: project.themes, autoFocus: project.autoFocus,
17
+ const value = { name: project.name, description: project.description, theme: project.theme, themes: projectThemes(project), autoFocus: project.autoFocus,
17
18
  feature, option, scenes: own(project.scenes), scenarios: own(project.scenarios), rules: own(project.rules), issues: own(project.issues),
18
19
  cases: Object.fromEntries(Object.entries(project.cases).filter(([, c]) => c.featureId === option.featureId)),
19
20
  };
@@ -0,0 +1,8 @@
1
+ import type { Page } from 'playwright-core';
2
+ /** Read actual recorded PTS, independent of page creation, wall clocks and recorder start latency. */
3
+ export declare function recordedCalibration(page: Page, videoFile: string, audioBytes: Uint8Array): Promise<{
4
+ videoPTS: number;
5
+ audioPTS: number;
6
+ audioDurations: number[];
7
+ offsetSeconds: number;
8
+ }>;
@@ -0,0 +1,67 @@
1
+ import fs from 'node:fs/promises';
2
+ import { Input, ALL_FORMATS, BufferSource, EncodedPacketSink } from 'mediabunny';
3
+ /** Read actual recorded PTS, independent of page creation, wall clocks and recorder start latency. */
4
+ export async function recordedCalibration(page, videoFile, audioBytes) {
5
+ const video = new Input({ formats: ALL_FORMATS, source: new BufferSource(await fs.readFile(videoFile)) });
6
+ const audio = new Input({ formats: ALL_FORMATS, source: new BufferSource(audioBytes) });
7
+ try {
8
+ const v = await video.getPrimaryVideoTrack(), a = await audio.getPrimaryAudioTrack();
9
+ if (!v || !a)
10
+ throw new Error('Calibration tracks missing');
11
+ const vc = await v.getDecoderConfig(), ac = await a.getDecoderConfig();
12
+ if (!vc || !ac)
13
+ throw new Error('Calibration decoder configuration missing');
14
+ const vs = new EncodedPacketSink(v), as = new EncodedPacketSink(a);
15
+ const vp = [], ap = [];
16
+ const first = await vs.getKeyPacket(Math.max(0, (await v.computeDuration()) - 2));
17
+ for await (const p of vs.packets(first ?? undefined))
18
+ vp.push({ type: p.type, timestamp: Math.round(p.timestamp * 1e6), duration: Math.round(p.duration * 1e6), data: Array.from(p.data) });
19
+ for await (const p of as.packets())
20
+ ap.push({ type: p.type, timestamp: Math.round(p.timestamp * 1e6), duration: Math.round(p.duration * 1e6), data: Array.from(p.data) });
21
+ return await page.evaluate(async ({ vc, ac, vp, ap, audioFloor }) => {
22
+ let videoPTS = Infinity, audioPTS = Infinity;
23
+ let audioTime = 0;
24
+ const audioDurations = [];
25
+ const canvas = document.createElement('canvas');
26
+ canvas.width = 1;
27
+ canvas.height = 1;
28
+ const ctx = canvas.getContext('2d');
29
+ const decoder = new VideoDecoder({ output(frame) { ctx.drawImage(frame, 0, 0, 1, 1); const c = ctx.getImageData(0, 0, 1, 1).data; if (c[0] > 220 && c[2] > 220 && c[1] < 40)
30
+ videoPTS = Math.min(videoPTS, frame.timestamp / 1e6); frame.close(); }, error(e) { throw e; } });
31
+ decoder.configure({ ...vc, description: vc.description ? new Uint8Array(vc.description) : undefined });
32
+ for (const p of vp) {
33
+ decoder.decode(new EncodedVideoChunk({ ...p, data: new Uint8Array(p.data) }));
34
+ if (decoder.decodeQueueSize > 20)
35
+ await new Promise(r => setTimeout(r, 0));
36
+ }
37
+ await decoder.flush();
38
+ decoder.close();
39
+ const sound = new AudioDecoder({ output(frame) { const data = new Float32Array(frame.numberOfFrames); frame.copyTo(data, { planeIndex: 0, format: 'f32-planar' }); const origin = audioTime, duration = frame.numberOfFrames / frame.sampleRate; audioDurations.push(duration); audioTime += duration; for (let i = 0; i < data.length; i++)
40
+ if (origin + i / frame.sampleRate >= audioFloor && Math.abs(data[i]) > .3) {
41
+ audioPTS = Math.min(audioPTS, origin + i / frame.sampleRate);
42
+ break;
43
+ } frame.close(); }, error(e) { throw e; } });
44
+ sound.configure({ ...ac, description: ac.description ? new Uint8Array(ac.description) : undefined });
45
+ for (const p of ap) {
46
+ sound.decode(new EncodedAudioChunk({ ...p, data: new Uint8Array(p.data) }));
47
+ if (sound.decodeQueueSize > 20)
48
+ await new Promise(r => setTimeout(r, 0));
49
+ }
50
+ await sound.flush();
51
+ sound.close();
52
+ if (audioDurations.length !== ap.length)
53
+ throw new Error('Unexpected audio calibration decoder batching');
54
+ if (!Number.isFinite(videoPTS) || !Number.isFinite(audioPTS))
55
+ throw new Error('Recorded calibration signal was not found');
56
+ // A color change becomes visible in the next recorded frame. Center that
57
+ // quantization interval instead of introducing a systematic full-frame delay.
58
+ const durations = vp.map(p => p.duration / 1e6).filter(d => d > 0 && d < .1).sort((a, b) => a - b);
59
+ const halfFrame = (durations[Math.floor(durations.length / 2)] ?? .04) / 2;
60
+ return { videoPTS, audioPTS, audioDurations, offsetSeconds: videoPTS - halfFrame - audioPTS };
61
+ }, { vc: { ...vc, description: vc.description ? Array.from(new Uint8Array(vc.description)) : undefined }, ac: { ...ac, description: ac.description ? Array.from(new Uint8Array(ac.description)) : undefined }, vp, ap, audioFloor: Math.max(0, ap.reduce((n, p) => n + p.duration / 1e6, 0) - .6) });
62
+ }
63
+ finally {
64
+ video.dispose();
65
+ audio.dispose();
66
+ }
67
+ }
@@ -0,0 +1,9 @@
1
+ import { type Diagnostic, type Project } from '@joplo-app/core';
2
+ import type { LocalResourceInfo, ResourceRequest } from '@joplo-app/kit/plugin';
3
+ import type { LocalResources } from './local-resources.js';
4
+ export declare function inspectResources(project: Project | null, requests: ResourceRequest[], host: LocalResources): Promise<{
5
+ resourceInfo: Record<string, LocalResourceInfo>;
6
+ diagnostics: Diagnostic[];
7
+ }>;
8
+ /** Measure uninterrupted runs, not each individual step. Stop/replacement ends a run. */
9
+ export declare function mediaDiagnostics(project: Project, info: Record<string, LocalResourceInfo>): Diagnostic[];
@@ -0,0 +1,56 @@
1
+ import { mediaResourceIds, nodeResourceIds } from '@joplo-app/core';
2
+ export async function inspectResources(project, requests, host) {
3
+ const used = project ? mediaResourceIds(project) : new Set();
4
+ for (const id of nodeResourceIds(project))
5
+ used.add(id);
6
+ const resourceInfo = {}, diagnostics = [];
7
+ for (const request of requests)
8
+ if (used.has(request.id)) {
9
+ const result = await host.inspect(request);
10
+ if (result.info)
11
+ resourceInfo[request.id] = result.info;
12
+ if (result.diagnostic)
13
+ diagnostics.push(result.diagnostic);
14
+ }
15
+ return { resourceInfo, diagnostics };
16
+ }
17
+ /** Measure uninterrupted runs, not each individual step. Stop/replacement ends a run. */
18
+ export function mediaDiagnostics(project, info) {
19
+ const diagnostics = [];
20
+ for (const sc of Object.values(project.scenarios)) {
21
+ const runs = new Map();
22
+ const finish = (key) => {
23
+ const run = runs.get(key);
24
+ if (!run)
25
+ return;
26
+ runs.delete(key);
27
+ const length = info[run.resource]?.durationMs;
28
+ if (!length)
29
+ return;
30
+ const left = Math.max(0, length - run.offset);
31
+ const code = run.loop && length < 8000 && run.duration >= Math.max(30000, length * 4) ? 'MUSIC_LOOP_SHORT'
32
+ : !run.loop && run.duration - left > 5000 && left < run.duration * .75 ? 'MUSIC_ENDS_EARLY' : undefined;
33
+ if (code)
34
+ diagnostics.push({ code, severity: 'warning', source: 'structure', at: run.at, message: `${sc.name}: music ${(length / 1000).toFixed(2)} s, starts ${(run.offset / 1000).toFixed(2)} s, scene playback ${(run.duration / 1000).toFixed(2)} s${run.loop ? '; short loop may become repetitive' : '; music ends well before this run finishes'}` });
35
+ };
36
+ for (const step of sc.steps) {
37
+ const tracks = step.media ?? {};
38
+ for (const key of [...runs.keys()])
39
+ if (!tracks[key])
40
+ finish(key);
41
+ for (const [key, t] of Object.entries(tracks)) {
42
+ const previous = runs.get(key);
43
+ if (previous && (previous.resource !== t.resource || Math.abs(previous.offset + previous.duration - t.offsetMs) > 1))
44
+ finish(key);
45
+ if (!runs.has(key))
46
+ runs.set(key, { resource: t.resource, offset: t.offsetMs, duration: 0, loop: t.loop, at: step.source });
47
+ runs.get(key).duration += Math.min(step.hold ?? 3000, t.stopAfterMs ?? Infinity);
48
+ if (t.stopAfterMs !== undefined && t.stopAfterMs <= (step.hold ?? 3000))
49
+ finish(key);
50
+ }
51
+ }
52
+ for (const key of [...runs.keys()])
53
+ finish(key);
54
+ }
55
+ return diagnostics;
56
+ }
@@ -0,0 +1,9 @@
1
+ import { type EncodedPacket } from 'mediabunny';
2
+ /** MediaRecorder packet arrival PTS can jitter. Keep the exact continuous decoded-sample clock. */
3
+ export declare function audioSampleClock(packets: readonly EncodedPacket[], durations: readonly number[]): EncodedPacket[];
4
+ /** Packet copy only (VP8/VP9 and Opus): no native codec, ffmpeg executable, decode or re-encode. */
5
+ export declare function muxRecordedAudio(videoFile: string, audio: Uint8Array, offsetSeconds: number, trim?: {
6
+ videoEnd: number;
7
+ audioEnd: number;
8
+ audioDurations?: number[];
9
+ }): Promise<void>;