mirror of
https://github.com/LamGC/wp-asciiplayer.git
synced 2026-11-26 20:55:48 +00:00
fix: bound recording resources and add security regressions (#41)
Build and WordPress integration / Build and publish pristine package (push) Canceled after 0s
Build and WordPress integration / PHP 8.3 syntax and regression tests (push) Canceled after 0s
Build and WordPress integration / PHP 7.4 syntax and regression tests (push) Canceled after 0s
Build and WordPress integration / WordPress 6.3 / PHP 7.4 (push) Canceled after 0s
Build and WordPress integration / WordPress latest / PHP 8.2 (push) Canceled after 0s
Build and WordPress integration / Plugin Check (advisory) (push) Canceled after 0s
Build and WordPress integration / Build and publish pristine package (push) Canceled after 0s
Build and WordPress integration / PHP 8.3 syntax and regression tests (push) Canceled after 0s
Build and WordPress integration / PHP 7.4 syntax and regression tests (push) Canceled after 0s
Build and WordPress integration / WordPress 6.3 / PHP 7.4 (push) Canceled after 0s
Build and WordPress integration / WordPress latest / PHP 8.2 (push) Canceled after 0s
Build and WordPress integration / Plugin Check (advisory) (push) Canceled after 0s
- Bound recording bytes, JSON structure, events, markers, terminal dimensions and timestamp arithmetic before unsafe player allocation or scheduling. - Share validated playback data and metadata; cancel stale, failed and timed-out loads. - Add PHP 7.4-compatible predecode budgets and preserve supported v1/v2/v3 behavior. - Add localized errors, documented limits and 110 official/seeded recording fixtures. Verified 325 Node tests, native PHP 7.4/8.3 regression suites and 55 Chromium tests on each WordPress CI matrix. Preserve plugin version, vendor files and isolated package artifacts.
This commit is contained in:
+20
-13
@@ -4,7 +4,8 @@ import { useRef, useState } from '@wordpress/element';
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { normalizePlayerOptions, previewHeight } from './options.js';
|
||||
import { playerAssets, playerForDocument } from './player-bridge.js';
|
||||
import { readRecordingSize } from './recording-metadata.js';
|
||||
import { loadRecording, validateInitialDimensions } from './recording-loader.js';
|
||||
import { recordingErrorMessage } from './recording-errors.js';
|
||||
|
||||
export default function Preview( { source, attributes, attempt, onRetry, onRecordingSize } ) {
|
||||
const [ status, setStatus ] = useState( 'loading' );
|
||||
@@ -42,19 +43,26 @@ export default function Preview( { source, attributes, attempt, onRetry, onRecor
|
||||
canvasWindow.clearTimeout( deadline );
|
||||
setStatus( 'ready' );
|
||||
};
|
||||
deadline = canvasWindow.setTimeout( () => fail( recordingErrorMessage( { code: 'timeout' } ) ), 30000 );
|
||||
playerForDocument( container.ownerDocument, playerAssets() ).then( ( api ) => {
|
||||
if ( disposed ) return;
|
||||
if ( disposed || failed ) return;
|
||||
try {
|
||||
validateInitialDimensions( JSON.parse( optionsJSON ) );
|
||||
} catch ( error ) {
|
||||
fail( recordingErrorMessage( error ) );
|
||||
return;
|
||||
}
|
||||
player = api.create( {
|
||||
data: async () => {
|
||||
// The parser checks instanceof Response in the canvas realm.
|
||||
// Reuse this one request for playback and original-size hints.
|
||||
const response = await canvasWindow.fetch( source, { signal: request.signal } );
|
||||
if ( ! response.ok ) throw new Error( `Recording request failed: ${ response.status }` );
|
||||
readRecordingSize( response ).then( ( size ) => {
|
||||
if ( ! failed ) reportSize( size );
|
||||
} );
|
||||
return response;
|
||||
},
|
||||
data: () => loadRecording( source, {
|
||||
fetchImpl: canvasWindow.fetch.bind( canvasWindow ),
|
||||
signal: request.signal,
|
||||
options: JSON.parse( optionsJSON ),
|
||||
onMetadata: ( size ) => { if ( ! failed ) reportSize( size ); },
|
||||
} ).catch( ( error ) => {
|
||||
const message = recordingErrorMessage( error );
|
||||
if ( message ) fail( message );
|
||||
throw error;
|
||||
} ),
|
||||
}, container, JSON.parse( optionsJSON ) );
|
||||
player.addEventListener( 'error', () => fail( __( 'Unable to load the recording. Check the URL, file format, and the source server’s CORS permissions.', 'wp-asciiplayer' ) ) );
|
||||
player.addEventListener( 'playing', ready );
|
||||
@@ -65,7 +73,6 @@ export default function Preview( { source, attributes, attempt, onRetry, onRecor
|
||||
if ( typeof duration === 'number' && Number.isFinite( duration ) ) ready();
|
||||
};
|
||||
readinessTimer = canvasWindow.setInterval( checkReady, 150 );
|
||||
deadline = canvasWindow.setTimeout( () => fail( __( 'The recording is taking too long to load. Check your connection and try again.', 'wp-asciiplayer' ) ), 30000 );
|
||||
checkReady();
|
||||
} ).catch( () => fail( __( 'The local player could not start. Try again, or check that the plugin’s built assets are installed.', 'wp-asciiplayer' ) ) );
|
||||
return () => {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { __ } from '@wordpress/i18n';
|
||||
|
||||
/** Never expose remote content or raw exception messages in a recording notice. */
|
||||
export function recordingErrorMessage( error, { frontend = false } = {} ) {
|
||||
switch ( error?.code ) {
|
||||
case 'aborted': return '';
|
||||
case 'bytes': return __( 'This recording exceeds the file size limit.', 'wp-asciiplayer' );
|
||||
case 'line': return __( 'This recording contains a line that exceeds the size limit.', 'wp-asciiplayer' );
|
||||
case 'events': return __( 'This recording contains too many events.', 'wp-asciiplayer' );
|
||||
case 'markers': return __( 'This recording contains too many markers.', 'wp-asciiplayer' );
|
||||
case 'dimensions': return __( 'This recording requests terminal dimensions that exceed the supported limits.', 'wp-asciiplayer' );
|
||||
case 'cells': return __( 'This recording requests too many terminal cells.', 'wp-asciiplayer' );
|
||||
case 'complexity': return __( 'This recording is too complex to load safely.', 'wp-asciiplayer' );
|
||||
case 'timeout': return __( 'The recording is taking too long to load. Check your connection and try again.', 'wp-asciiplayer' );
|
||||
case 'time': return __( 'This recording contains an invalid or unsupported timestamp.', 'wp-asciiplayer' );
|
||||
// Invalid data, network/CORS failures, missing stream support, and policy
|
||||
// configuration errors retain the existing localized fallback guidance.
|
||||
default: return frontend
|
||||
? __( 'Unable to load this terminal recording. The file may be unavailable, invalid, or blocked by the source server’s CORS policy.', 'wp-asciiplayer' )
|
||||
: __( 'Unable to load the recording. Check the URL, file format, and the source server’s CORS permissions.', 'wp-asciiplayer' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
/** Resource policy for untrusted recordings, before handing data to the player. */
|
||||
export const DEFAULT_LIMITS = Object.freeze( {
|
||||
bytes: 32 * 1024 * 1024, v1Bytes: 2 * 1024 * 1024, lineBytes: 256 * 1024,
|
||||
depth: 15, containers: 100016, tokens: 400000, lineTokens: 20000,
|
||||
events: 100000, lines: 100000, markers: 1000, dimension: 1000, cells: 40000,
|
||||
// Web timers take a signed 32-bit millisecond delay (~24.85 days). This
|
||||
// horizon also keeps upstream's 16.67 ms output batches numerically distinct.
|
||||
timelineMs: 2147483647,
|
||||
totalTimeoutMs: 30000, idleTimeoutMs: 10000,
|
||||
} );
|
||||
|
||||
export class RecordingLoadError extends Error {
|
||||
constructor( code ) {
|
||||
super( `Recording load failed: ${ code }` );
|
||||
this.name = 'RecordingLoadError';
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
const fail = ( code ) => { throw new RecordingLoadError( code ); };
|
||||
const boundedTime = ( value, maxMs ) => typeof value === 'number' && value >= 0 && value * 1000 <= maxMs;
|
||||
const object = ( value ) => value !== null && typeof value === 'object' && ! Array.isArray( value );
|
||||
|
||||
/** Guard the terminal allocated by api.create before its data loader runs. */
|
||||
export function validateInitialDimensions( options = {}, limits = {} ) {
|
||||
const dimension = limits.dimension ?? DEFAULT_LIMITS.dimension;
|
||||
const cells = limits.cells ?? DEFAULT_LIMITS.cells;
|
||||
if ( ! Number.isSafeInteger( dimension ) || dimension <= 0 || ! Number.isSafeInteger( cells ) || cells <= 0 ) fail( 'policy' );
|
||||
const cols = options.cols ?? 80;
|
||||
const rows = options.rows ?? 24;
|
||||
if ( ! Number.isSafeInteger( cols ) || cols < 1 || cols > dimension || ! Number.isSafeInteger( rows ) || rows < 1 || rows > dimension ) fail( 'dimensions' );
|
||||
if ( cols * rows > cells ) fail( 'cells' );
|
||||
}
|
||||
|
||||
/** Count allocation-driving JSON tokens before JSON.parse allocates containers. */
|
||||
function parseBounded( text, limits, v1 = false ) {
|
||||
let quoted = false;
|
||||
let escaped = false;
|
||||
let primitive = false;
|
||||
let depth = 0;
|
||||
let tokens = 0;
|
||||
let containers = 0;
|
||||
const tokenLimit = v1 ? limits.tokens : limits.lineTokens;
|
||||
for ( const character of text ) {
|
||||
if ( quoted ) {
|
||||
if ( escaped ) escaped = false;
|
||||
else if ( character === '\\' ) escaped = true;
|
||||
else if ( character === '"' ) quoted = false;
|
||||
continue;
|
||||
}
|
||||
if ( character === '"' ) {
|
||||
quoted = true;
|
||||
primitive = false;
|
||||
tokens++;
|
||||
} else if ( character === '[' || character === '{' ) {
|
||||
primitive = false;
|
||||
if ( ++depth > limits.depth || ++containers > limits.containers ) fail( 'complexity' );
|
||||
} else if ( character === ']' || character === '}' ) {
|
||||
primitive = false;
|
||||
if ( --depth < 0 ) fail( 'invalid' );
|
||||
} else if ( character === ',' || character === ':' || /\s/.test( character ) ) {
|
||||
primitive = false;
|
||||
} else if ( ! primitive ) {
|
||||
primitive = true;
|
||||
tokens++;
|
||||
}
|
||||
if ( tokens > tokenLimit ) fail( 'complexity' );
|
||||
}
|
||||
if ( quoted || depth !== 0 ) fail( 'invalid' );
|
||||
try { return JSON.parse( text ); } catch { fail( 'invalid' ); }
|
||||
}
|
||||
|
||||
/** Inspect version and structural completeness without allocating a JSON tree. */
|
||||
function inspectFirstLine( text ) {
|
||||
let depth = 0;
|
||||
let quoted = false;
|
||||
let escaped = false;
|
||||
let start = 0;
|
||||
let version;
|
||||
function member( end ) {
|
||||
let cursor = start;
|
||||
while ( cursor < end && /\s/.test( text[ cursor ] ) ) cursor++;
|
||||
if ( text[ cursor ] !== '"' ) return;
|
||||
const keyStart = cursor++;
|
||||
let escape = false;
|
||||
while ( cursor < end ) {
|
||||
const character = text[ cursor++ ];
|
||||
if ( escape ) escape = false;
|
||||
else if ( character === '\\' ) escape = true;
|
||||
else if ( character === '"' ) break;
|
||||
}
|
||||
// "version" has seven characters, at most six JSON bytes each.
|
||||
if ( cursor - keyStart > 44 ) return;
|
||||
let key;
|
||||
try { key = JSON.parse( text.slice( keyStart, cursor ) ); } catch { return; }
|
||||
if ( key !== 'version' ) return;
|
||||
version = undefined;
|
||||
while ( cursor < end && /\s/.test( text[ cursor ] ) ) cursor++;
|
||||
if ( text[ cursor++ ] !== ':' ) return;
|
||||
while ( cursor < end && /\s/.test( text[ cursor ] ) ) cursor++;
|
||||
while ( end > cursor && /\s/.test( text[ end - 1 ] ) ) end--;
|
||||
// Numeric conversion allocates no JSON containers; the complete parser
|
||||
// will still reject malformed numeric spellings or nonnumeric values.
|
||||
version = Number( text.slice( cursor, end ) );
|
||||
}
|
||||
for ( let index = 0; index < text.length; index++ ) {
|
||||
const character = text[ index ];
|
||||
if ( quoted ) {
|
||||
if ( escaped ) escaped = false;
|
||||
else if ( character === '\\' ) escaped = true;
|
||||
else if ( character === '"' ) quoted = false;
|
||||
continue;
|
||||
}
|
||||
if ( character === '"' ) quoted = true;
|
||||
else if ( character === '[' || character === '{' ) {
|
||||
if ( ++depth === 1 ) start = index + 1;
|
||||
} else if ( character === ']' || character === '}' ) {
|
||||
if ( depth === 1 ) member( index );
|
||||
depth--;
|
||||
} else if ( character === ',' && depth === 1 ) {
|
||||
member( index );
|
||||
start = index + 1;
|
||||
}
|
||||
}
|
||||
return { version, incomplete: depth > 0 || quoted };
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch once, count actual decoded-body bytes, and validate everything before
|
||||
* returning an upstream-compatible v1 object or v2/v3 [header, ...events] array.
|
||||
* limits are intended for policy configuration/tests, never recording metadata.
|
||||
*/
|
||||
export async function loadRecording( source, { fetchImpl = globalThis.fetch, signal, onMetadata, options = {}, limits = {} } = {} ) {
|
||||
const policy = { ...DEFAULT_LIMITS };
|
||||
for ( const key of Object.keys( policy ) ) {
|
||||
if ( Object.hasOwn( limits, key ) ) {
|
||||
if ( ! Number.isSafeInteger( limits[ key ] ) || limits[ key ] <= 0 ) fail( 'policy' );
|
||||
policy[ key ] = limits[ key ];
|
||||
}
|
||||
}
|
||||
// Policy overrides may lower this safety ceiling, but cannot expand the
|
||||
// platform timer range. Callers supply already-normalized player options.
|
||||
if ( policy.timelineMs > DEFAULT_LIMITS.timelineMs ) fail( 'policy' );
|
||||
const speed = options.speed ?? 1;
|
||||
if ( typeof speed !== 'number' || ! Number.isFinite( speed ) || speed < 0.01 || speed > 100 ) fail( 'time' );
|
||||
for ( const key of [ 'startAt', 'idleTimeLimit' ] ) {
|
||||
if ( options[ key ] !== undefined && ! boundedTime( options[ key ], policy.timelineMs ) ) fail( 'time' );
|
||||
}
|
||||
if ( typeof options.poster === 'string' && options.poster.startsWith( 'npt:' ) ) {
|
||||
// Match upstream parseNpt's order of arithmetic for normalized timecodes.
|
||||
const posterTime = options.poster.slice( 4 ).split( ':' ).reverse().map( parseFloat ).reduce( ( sum, part, index ) => sum + part * 60 ** index, 0 );
|
||||
if ( ! boundedTime( posterTime, policy.timelineMs ) ) fail( 'time' );
|
||||
}
|
||||
function checkTimeline( milliseconds ) {
|
||||
// Core passes (target - elapsed) / speed directly to setTimeout. Bound
|
||||
// the whole horizon conservatively: adjacent gaps alone are insufficient
|
||||
// because output batching can consume future events ahead of wall time.
|
||||
if ( ! Number.isFinite( milliseconds ) || milliseconds > policy.timelineMs || milliseconds / speed > DEFAULT_LIMITS.timelineMs ) fail( 'time' );
|
||||
}
|
||||
const controller = new AbortController();
|
||||
let reader;
|
||||
let totalTimer;
|
||||
let rejectStopped;
|
||||
let stoppedError;
|
||||
const deadline = Date.now() + policy.totalTimeoutMs;
|
||||
const stopped = new Promise( ( _, reject ) => { rejectStopped = reject; } );
|
||||
// A synchronous validation failure can precede the first Promise.race.
|
||||
stopped.catch( () => {} );
|
||||
const stop = ( code ) => {
|
||||
if ( stoppedError ) return;
|
||||
stoppedError = new RecordingLoadError( code );
|
||||
rejectStopped( stoppedError );
|
||||
controller.abort();
|
||||
};
|
||||
const abort = () => stop( 'aborted' );
|
||||
async function waitFor( operation ) {
|
||||
// Also enforce elapsed time when synthetic/cached streams resolve reads in
|
||||
// microtasks without giving browser timer callbacks a turn.
|
||||
if ( Date.now() >= deadline ) stop( 'timeout' );
|
||||
if ( stoppedError ) {
|
||||
Promise.resolve( operation ).catch( () => {} );
|
||||
throw stoppedError;
|
||||
}
|
||||
let idleTimer;
|
||||
try {
|
||||
idleTimer = setTimeout( () => stop( 'timeout' ), policy.idleTimeoutMs );
|
||||
return await Promise.race( [ operation, stopped ] );
|
||||
} finally { clearTimeout( idleTimer ); }
|
||||
}
|
||||
const dimension = ( value, zero = false ) => Number.isSafeInteger( value ) && value >= ( zero ? 0 : 1 ) && value <= policy.dimension;
|
||||
function checkSize( cols, rows, zero = false ) {
|
||||
if ( ! dimension( cols, zero ) || ! dimension( rows, zero ) ) fail( 'dimensions' );
|
||||
// Upstream applies each override independently, including every resize.
|
||||
const effectiveCols = options.cols ?? ( cols || 80 );
|
||||
const effectiveRows = options.rows ?? ( rows || 24 );
|
||||
if ( ! dimension( effectiveCols ) || ! dimension( effectiveRows ) ) fail( 'dimensions' );
|
||||
if ( ( cols || 80 ) * ( rows || 24 ) > policy.cells || effectiveCols * effectiveRows > policy.cells ) fail( 'cells' );
|
||||
}
|
||||
let bytes = 0;
|
||||
let mode = 'first';
|
||||
let header;
|
||||
let timeMs = 0;
|
||||
let lines = 0;
|
||||
let markerCount = Array.isArray( options.markers ) ? options.markers.length : 0;
|
||||
const events = [];
|
||||
const v1Parts = [];
|
||||
let lineParts = [];
|
||||
let lineBytes = 0;
|
||||
const decoder = new TextDecoder( 'utf-8', { fatal: true, ignoreBOM: true } );
|
||||
function checkHeader( value ) {
|
||||
if ( ! object( value ) || ! [ 1, 2, 3 ].includes( value.version ) ) fail( 'invalid' );
|
||||
if ( value.version === 3 ) {
|
||||
if ( ! object( value.term ) ) fail( 'dimensions' );
|
||||
checkSize( value.term.cols, value.term.rows, true );
|
||||
} else checkSize( value.width, value.height, true );
|
||||
for ( const key of [ 'duration', 'idle_time_limit' ] ) {
|
||||
if ( Object.hasOwn( value, key ) && ! boundedTime( value[ key ], policy.timelineMs ) ) fail( 'time' );
|
||||
}
|
||||
}
|
||||
function acceptLine( text, size, newline ) {
|
||||
if ( mode === 'first' ) {
|
||||
// Response.text strips only the document's initial UTF-8 BOM. Keep
|
||||
// later BOMs intact so resetting at LF cannot turn ignored lines into events.
|
||||
if ( text.charCodeAt( 0 ) === 0xfeff ) text = text.slice( 1 );
|
||||
// Pretty-printed v1 is the only supported multiline JSON document.
|
||||
// A syntax-incomplete first line is collected under the smaller v1 cap.
|
||||
const first = inspectFirstLine( text );
|
||||
// A v1 document may put version after a long stdout/title member.
|
||||
// Incomplete first lines therefore use the whole-document v1 budget.
|
||||
if ( first.version === 1 || first.incomplete ) {
|
||||
mode = 'v1';
|
||||
v1Parts.push( text, newline ? '\n' : '' );
|
||||
return;
|
||||
}
|
||||
if ( size + Number( newline ) > policy.lineBytes ) fail( 'line' );
|
||||
try { header = parseBounded( text, policy ); } catch ( error ) {
|
||||
if ( error.code !== 'invalid' ) throw error;
|
||||
mode = 'v1';
|
||||
v1Parts.push( text, newline ? '\n' : '' );
|
||||
return;
|
||||
}
|
||||
if ( header?.version === 1 ) {
|
||||
mode = 'v1';
|
||||
v1Parts.push( text, newline ? '\n' : '' );
|
||||
return;
|
||||
}
|
||||
if ( size + Number( newline ) > policy.lineBytes ) fail( 'line' );
|
||||
checkHeader( header );
|
||||
mode = 'jsonl';
|
||||
return;
|
||||
}
|
||||
if ( size + Number( newline ) > policy.lineBytes ) fail( 'line' );
|
||||
// Match 3.17's JSONL filter: blank, comment, and other non-event lines
|
||||
// (including indented arrays) are ignored, but still byte/line bounded.
|
||||
if ( ++lines > policy.lines ) fail( 'events' );
|
||||
if ( text[ 0 ] !== '[' ) return;
|
||||
if ( events.length >= policy.events ) fail( 'events' );
|
||||
const event = parseBounded( text, policy );
|
||||
if ( ! Array.isArray( event ) || event.length !== 3 || typeof event[ 1 ] !== 'string' || ! event[ 1 ] || typeof event[ 2 ] !== 'string' ) fail( 'invalid' );
|
||||
if ( ! boundedTime( event[ 0 ], policy.timelineMs ) ) fail( 'time' );
|
||||
const eventMs = event[ 0 ] * 1000;
|
||||
if ( header.version === 2 && events.length && event[ 0 ] < events[ events.length - 1 ][ 0 ] ) fail( 'time' );
|
||||
// v1/v3 upstream converts each interval before adding, which can round
|
||||
// differently from summing seconds and multiplying the result by 1000.
|
||||
timeMs = header.version === 3 ? timeMs + eventMs : eventMs;
|
||||
checkTimeline( timeMs );
|
||||
if ( event[ 1 ] === 'r' ) {
|
||||
const match = /^([1-9][0-9]{0,3})x([1-9][0-9]{0,3})$/.exec( event[ 2 ] );
|
||||
if ( ! match ) fail( 'dimensions' );
|
||||
checkSize( Number( match[ 1 ] ), Number( match[ 2 ] ) );
|
||||
}
|
||||
if ( event[ 1 ] === 'm' && ++markerCount > policy.markers ) fail( 'markers' );
|
||||
events.push( event );
|
||||
}
|
||||
try {
|
||||
if ( markerCount > policy.markers ) fail( 'markers' );
|
||||
if ( signal?.aborted ) fail( 'aborted' );
|
||||
signal?.addEventListener( 'abort', abort, { once: true } );
|
||||
totalTimer = setTimeout( () => stop( 'timeout' ), policy.totalTimeoutMs );
|
||||
const response = await waitFor( Promise.resolve().then( () => fetchImpl( source, { signal: controller.signal, credentials: 'same-origin' } ) ) );
|
||||
if ( ! response.ok ) fail( 'network' );
|
||||
if ( ! response.body?.getReader ) fail( 'stream' );
|
||||
reader = response.body.getReader();
|
||||
while ( true ) {
|
||||
const { value, done } = await waitFor( reader.read() );
|
||||
if ( done ) break;
|
||||
bytes += value.byteLength;
|
||||
if ( bytes > policy.bytes || ( mode === 'v1' && bytes > policy.v1Bytes ) ) fail( 'bytes' );
|
||||
if ( mode === 'v1' ) {
|
||||
v1Parts.push( decoder.decode( value, { stream: true } ) );
|
||||
continue;
|
||||
}
|
||||
let start = 0;
|
||||
for ( let index = 0; index <= value.length; index++ ) {
|
||||
if ( index !== value.length && value[ index ] !== 10 ) continue;
|
||||
const part = value.subarray( start, index );
|
||||
lineBytes += part.byteLength;
|
||||
if ( lineBytes > ( mode === 'first' ? policy.v1Bytes : policy.lineBytes ) ) fail( 'line' );
|
||||
if ( part.byteLength ) lineParts.push( decoder.decode( part, { stream: true } ) );
|
||||
if ( index < value.length ) {
|
||||
lineParts.push( decoder.decode() );
|
||||
acceptLine( lineParts.join( '' ), lineBytes, true );
|
||||
lineParts = [];
|
||||
lineBytes = 0;
|
||||
start = index + 1;
|
||||
if ( mode === 'v1' ) {
|
||||
if ( bytes > policy.v1Bytes ) fail( 'bytes' );
|
||||
v1Parts.push( decoder.decode( value.subarray( start ), { stream: true } ) );
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const tail = decoder.decode();
|
||||
if ( mode === 'v1' ) v1Parts.push( tail );
|
||||
else {
|
||||
lineParts.push( tail );
|
||||
if ( lineBytes || mode === 'first' ) acceptLine( lineParts.join( '' ), lineBytes, false );
|
||||
}
|
||||
let result;
|
||||
if ( mode === 'v1' ) {
|
||||
if ( bytes > policy.v1Bytes ) fail( 'bytes' );
|
||||
header = parseBounded( v1Parts.join( '' ), policy, true );
|
||||
checkHeader( header );
|
||||
if ( header.version !== 1 || ! Array.isArray( header.stdout ) ) fail( 'invalid' );
|
||||
if ( header.stdout.length > policy.events ) fail( 'events' );
|
||||
for ( const event of header.stdout ) {
|
||||
if ( ! Array.isArray( event ) || event.length !== 2 || typeof event[ 1 ] !== 'string' ) fail( 'invalid' );
|
||||
if ( ! boundedTime( event[ 0 ], policy.timelineMs ) ) fail( 'time' );
|
||||
timeMs += event[ 0 ] * 1000;
|
||||
checkTimeline( timeMs );
|
||||
}
|
||||
result = header;
|
||||
} else result = [ header, ...events ];
|
||||
const cols = header.version === 3 ? header.term.cols : header.width;
|
||||
const rows = header.version === 3 ? header.term.rows : header.height;
|
||||
if ( Date.now() >= deadline ) stop( 'timeout' );
|
||||
if ( stoppedError ) throw stoppedError;
|
||||
onMetadata?.( cols > 0 && rows > 0 ? { cols, rows } : null );
|
||||
return result;
|
||||
} catch ( error ) {
|
||||
controller.abort();
|
||||
// Cancellation can itself stall (especially custom/teed streams). Never
|
||||
// await it; the public promise must settle promptly on abort/timeout.
|
||||
try { Promise.resolve( reader?.cancel() ).catch( () => {} ); } catch { /* Already closed. */ }
|
||||
if ( stoppedError ) throw stoppedError;
|
||||
if ( error instanceof RecordingLoadError ) throw error;
|
||||
fail( error instanceof TypeError && reader ? 'invalid' : 'network' );
|
||||
} finally {
|
||||
clearTimeout( totalTimer );
|
||||
signal?.removeEventListener( 'abort', abort );
|
||||
try { reader?.releaseLock(); } catch { /* A rejected read may still be pending. */ }
|
||||
}
|
||||
}
|
||||
+78
-17
@@ -1,23 +1,52 @@
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { normalizePlayerOptions, normalizeSource } from './options.js';
|
||||
import { loadRecording, validateInitialDimensions } from './recording-loader.js';
|
||||
import { recordingErrorMessage } from './recording-errors.js';
|
||||
|
||||
const instances = new WeakMap();
|
||||
const documents = new WeakMap();
|
||||
|
||||
function showError( container ) {
|
||||
function showError( container, error ) {
|
||||
const message = recordingErrorMessage( error, { frontend: true } );
|
||||
if ( ! message ) return;
|
||||
container.dataset.apStatus = 'error';
|
||||
if ( container.querySelector( '.asciiplayer-error' ) ) return;
|
||||
const notice = container.ownerDocument.createElement( 'p' );
|
||||
notice.className = 'asciiplayer-error';
|
||||
notice.setAttribute( 'role', 'status' );
|
||||
notice.textContent = __( 'Unable to load this terminal recording. The file may be unavailable, invalid, or blocked by the source server’s CORS policy.', 'wp-asciiplayer' );
|
||||
notice.textContent = message;
|
||||
container.appendChild( notice );
|
||||
}
|
||||
|
||||
/** One observer per document, visiting only owned players on removals. */
|
||||
function watchRemoval( container, dispose ) {
|
||||
const document = container.ownerDocument;
|
||||
let state = documents.get( document );
|
||||
if ( ! state ) {
|
||||
const entries = new Map();
|
||||
const observer = new document.defaultView.MutationObserver( ( records ) => {
|
||||
if ( ! records.some( ( record ) => record.removedNodes.length ) ) return;
|
||||
for ( const [ node, cleanup ] of entries ) if ( ! node.isConnected ) cleanup();
|
||||
} );
|
||||
observer.observe( document.documentElement, { childList: true, subtree: true } );
|
||||
state = { entries, observer };
|
||||
documents.set( document, state );
|
||||
}
|
||||
state.entries.set( container, dispose );
|
||||
return () => {
|
||||
state.entries.delete( container );
|
||||
if ( ! state.entries.size ) {
|
||||
state.observer.disconnect();
|
||||
documents.delete( document );
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** One explicit instance per front-end container; never scan an editor canvas. */
|
||||
export function mountPlayers( root = document ) {
|
||||
const ownerDocument = root.ownerDocument || root;
|
||||
if ( ownerDocument.body?.classList.contains( 'wp-admin' ) || ownerDocument.querySelector( '.editor-styles-wrapper, .block-editor-block-list__layout' ) ) return;
|
||||
const api = ownerDocument.defaultView?.AsciinemaPlayer;
|
||||
const canvasWindow = ownerDocument.defaultView;
|
||||
const api = canvasWindow?.AsciinemaPlayer;
|
||||
if ( typeof api?.create !== 'function' ) return;
|
||||
root.querySelectorAll( '.asciiplayer-container' ).forEach( ( container ) => {
|
||||
if ( instances.has( container ) ) return;
|
||||
@@ -25,8 +54,7 @@ export function mountPlayers( root = document ) {
|
||||
if ( ! source ) return showError( container );
|
||||
let options;
|
||||
try {
|
||||
// New markup uses escaped plain JSON. The legacy adapter used URL-encoded
|
||||
// JSON; accepting it also lets cached old pages use the new local player.
|
||||
// Accept both current plain JSON and the legacy URL-encoded options.
|
||||
const serialized = container.dataset.apOptions;
|
||||
options = serialized ? JSON.parse( serialized ) : JSON.parse( decodeURIComponent( container.dataset.apOpts || '{}' ) );
|
||||
if ( ! options || Array.isArray( options ) || typeof options !== 'object' ) throw new Error( 'Invalid player options.' );
|
||||
@@ -35,26 +63,59 @@ export function mountPlayers( root = document ) {
|
||||
showError( container );
|
||||
return;
|
||||
}
|
||||
const request = new canvasWindow.AbortController();
|
||||
let disposed = false;
|
||||
let failed = false;
|
||||
let player;
|
||||
let timer;
|
||||
let unwatch;
|
||||
const dispose = () => {
|
||||
if ( disposed ) return;
|
||||
disposed = true;
|
||||
request.abort();
|
||||
canvasWindow.clearInterval( timer );
|
||||
unwatch?.();
|
||||
player?.dispose();
|
||||
instances.delete( container );
|
||||
};
|
||||
const fail = ( error ) => {
|
||||
if ( disposed || failed || ! recordingErrorMessage( error ) ) return;
|
||||
failed = true;
|
||||
request.abort();
|
||||
canvasWindow.clearInterval( timer );
|
||||
showError( container, error );
|
||||
};
|
||||
const ready = () => {
|
||||
if ( ! disposed && ! failed ) {
|
||||
container.dataset.apStatus = 'ready';
|
||||
canvasWindow.clearInterval( timer );
|
||||
}
|
||||
};
|
||||
try {
|
||||
validateInitialDimensions( options );
|
||||
container.dataset.apStatus = 'loading';
|
||||
const player = api.create( source, container, options );
|
||||
instances.set( container, player );
|
||||
player.addEventListener( 'error', () => showError( container ) );
|
||||
player.addEventListener( 'playing', () => { container.dataset.apStatus = 'ready'; } );
|
||||
// The upstream player owns loading/error/controls; readiness is confirmed
|
||||
// by its parsed duration rather than merely by a mounted DOM wrapper.
|
||||
// The player calls data lazily: preload=false causes no eager request.
|
||||
player = api.create( { data: () => loadRecording( source, {
|
||||
fetchImpl: canvasWindow.fetch.bind( canvasWindow ), signal: request.signal, options,
|
||||
} ).catch( ( error ) => { fail( error ); throw error; } ) }, container, options );
|
||||
instances.set( container, { player, dispose } );
|
||||
unwatch = watchRemoval( container, dispose );
|
||||
player.addEventListener( 'error', () => fail() );
|
||||
player.addEventListener( 'playing', ready );
|
||||
if ( options.preload || options.autoPlay || options.poster?.startsWith( 'npt:' ) ) {
|
||||
let ticks = 0;
|
||||
const timer = ownerDocument.defaultView.setInterval( () => {
|
||||
timer = canvasWindow.setInterval( () => {
|
||||
if ( ! container.isConnected ) return dispose();
|
||||
const duration = player.getDuration();
|
||||
if ( typeof duration === 'number' && Number.isFinite( duration ) ) container.dataset.apStatus = 'ready';
|
||||
if ( ! container.isConnected || container.dataset.apStatus !== 'loading' || ++ticks > 200 ) ownerDocument.defaultView.clearInterval( timer );
|
||||
if ( typeof duration === 'number' && Number.isFinite( duration ) ) ready();
|
||||
if ( ++ticks > 200 ) canvasWindow.clearInterval( timer );
|
||||
}, 150 );
|
||||
} else {
|
||||
container.dataset.apStatus = 'idle';
|
||||
}
|
||||
} catch {
|
||||
showError( container );
|
||||
} catch ( error ) {
|
||||
fail( error );
|
||||
dispose();
|
||||
}
|
||||
} );
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user