mirror of
https://github.com/LamGC/wp-asciiplayer.git
synced 2026-11-26 20:55:48 +00:00
Refresh wp-asciiplayer with native block editor playback (#36)
Build and WordPress integration / PHP 7.4 syntax and regression tests (push) Canceled after 0s
Build and WordPress integration / PHP 8.3 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 / PHP 7.4 syntax and regression tests (push) Canceled after 0s
Build and WordPress integration / PHP 8.3 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
* Refresh player with native block editor preview and local assets Preserve shortcode rendering, normalize options, bundle the player locally, and add reproducible packaging and WordPress integration tests. * Fix emitted frontend boot and verify bundled runtime initialization * Record verified WordPress 7.1.3 compatibility * Use WordPress readme major-version compatibility format * Add responsive player layout, captions and native terminal sizing * Keep editor caption geometry stable during block selection * Respect WordPress editor gutters with border-box sizing * Improve automatic previews and toolbar terminal sizing (1.2.1) * Show native cast dimensions and add Media Library recordings (1.2.2) * Fix Media Library test storage and scope sidebar selectors * Document bounded temporary-upload stream exceptions * Move block explanations into collapsed sidebar help (1.2.3) * Add bundled English and Simplified Chinese UI translations (1.1.0-dev) * Use native RichText labels and supported Chinese HTML language tags in locale tests
This commit is contained in:
@@ -0,0 +1,105 @@
|
||||
# Real WordPress browser integration
|
||||
|
||||
These tests run Chromium against WordPress itself. They do not replace WordPress,
|
||||
PHP rendering, the editor iframe, the media parser, or the player with static mocks.
|
||||
Recording files are small local fixtures; playback does not depend on a public CDN.
|
||||
|
||||
## Run locally (Docker)
|
||||
|
||||
Use Node 24 and Docker, then run from the repository root:
|
||||
|
||||
```sh
|
||||
npm ci
|
||||
npm run build
|
||||
npm test
|
||||
npm run package
|
||||
mkdir -p .wp-env-uploads
|
||||
npm run wp-env -- start
|
||||
npm run wp-env -- run cli wp plugin install /var/www/html/wp-content/asciiplayer-packages/wp-asciiplayer.zip --activate --force
|
||||
npm run wp-env -- run cli wp language core install zh_CN
|
||||
npm run wp-env -- run cli wp site switch-language en_US
|
||||
npm run wp-env -- run cli wp user meta update admin locale en_US
|
||||
npx --no-install playwright install chromium
|
||||
npm run test:e2e
|
||||
npm run wp-env -- stop
|
||||
```
|
||||
|
||||
The default site is http://localhost:8888 with wp-env's development-only account
|
||||
`admin` / `password`. Never use these credentials on a public site. `WP_BASE_URL`,
|
||||
`WP_USERNAME` and `WP_PASSWORD` can override browser-test settings. Set
|
||||
`PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` to use an already-installed Chromium binary.
|
||||
|
||||
The plugin's source tree is deliberately not mounted as an active plugin in the
|
||||
committed wp-env configuration. The build ZIP is installed into WordPress through
|
||||
WP-CLI, so missing package files cause a real integration failure. Fixtures are
|
||||
mapped under uploads; the package directory is mapped separately for WP-CLI.
|
||||
The host-owned .wp-env-uploads directory keeps real Media Library uploads writable
|
||||
without relaxing file modes or modifying the fixture files.
|
||||
|
||||
## Coverage
|
||||
|
||||
- A real iframe editor loads and plays the real local player after applying a URL
|
||||
- The iframe player actually plays; Space pauses/resumes it and resizing stays inside the canvas
|
||||
- An inspector speed/theme change rebuilds the player without duplicate instances
|
||||
- Duplicate, delete, undo, save, reload, and front-end playback preserve the block
|
||||
- Posts and Pages work, including a mobile-width published Page
|
||||
- Multiple legacy shortcodes preserve false booleans, hidden controls, and camelCase options
|
||||
- HTTP 404, malformed asciicast, and an actual no-CORS second origin recover after a valid URL
|
||||
- Actual terminal output proves successful front-end parsing/playback
|
||||
- Editor and front-end requests must not load plugin assets from jsDelivr
|
||||
|
||||
The preview automatically loads valid saved URLs and debounces typed changes.
|
||||
Tests check the request count, stale-response cleanup, immediate Apply, error
|
||||
retry, and no requests for empty/invalid URLs or static inserter examples.
|
||||
Floating-toolbar dimension controls are checked against the collapsed sidebar,
|
||||
including keyboard focus, Escape/close/reopen, and shared attribute values.
|
||||
Both controls show the recording header's native columns and rows as placeholders
|
||||
without saving overrides. URL replacement, pending/error/invalid sources and late
|
||||
responses cover metadata cleanup; recorded resize events still control blank axes.
|
||||
Pretty-printed v1 and comment-bearing v3 fixtures also exercise actual parsing,
|
||||
native-size placeholders and playback output, alongside the existing v2 fixtures.
|
||||
|
||||
Media Library tests use WordPress's real upload dialog, file input and attachment
|
||||
tiles. They upload a valid `.cast`, select and play it without Apply URL, cancel a
|
||||
replacement, reopen to select the existing replacement, and reload the saved URL.
|
||||
A malformed `.cast` must be rejected by the real upload endpoint and shown as an
|
||||
upload error. These tests create small attachments in the isolated wp-env database.
|
||||
|
||||
## CI evidence and limits
|
||||
|
||||
GitHub Actions checks the minimum WordPress 6.3 / PHP 7.4 combination and the latest
|
||||
stable WordPress / PHP 8.2. It logs the actual core version, installs the ZIP, and
|
||||
retains screenshots, failure traces/video, WordPress logs, and the package. A
|
||||
separate job checks PHP 7.4 and 8.3 syntax and focused regression tests.
|
||||
|
||||
Latest WordPress also runs Plugin Check and retains its report as an advisory
|
||||
step. Advisory output is not a passing directory review. Review any findings
|
||||
before submission, and do not interpret a green browser job as marketplace
|
||||
approval. Tests do not cover every browser, theme, or third-party plugin.
|
||||
|
||||
WordPress Playground is also usable for local smoke tests when Docker is absent,
|
||||
but its SQLite/PHP-WASM runtime is additional evidence, not a substitute for the
|
||||
Docker/MySQL matrix above.
|
||||
|
||||
References:
|
||||
- https://developer.wordpress.org/block-editor/reference-guides/packages/packages-env/
|
||||
- https://developer.wordpress.org/block-editor/reference-guides/block-api/block-api-versions/block-migration-for-iframe-editor-compatibility/
|
||||
- https://github.com/WordPress/plugin-check/blob/trunk/docs/CLI.md
|
||||
|
||||
Native recording-size hints are checked against v1/v2/v3 headers, explicit
|
||||
overrides, URL replacement, error/empty states and recorded resize events.
|
||||
The Media Library tests use actual isolated WordPress upload dialogs to upload
|
||||
validated fixtures, reject malformed casts, cancel/reopen and select an existing
|
||||
recording. No production-site media is accessed.
|
||||
|
||||
## Plugin localization
|
||||
|
||||
Five `@i18n` cases set real site and user languages via the authenticated WordPress
|
||||
REST API, covering all en_US/zh_CN combinations and site-default inheritance.
|
||||
They verify bundled PHP upload errors, editor metadata and controls, recoverable
|
||||
preview errors, and logged-in/anonymous frontend messages. Author captions and
|
||||
actual recording content remain unchanged, and upstream player controls stay
|
||||
English. Original site/user locale values are restored after each test.
|
||||
Run these only against the isolated test site, with zh_CN installed first.
|
||||
CI runs the existing English suite before the locale suite and retains separate
|
||||
reports/screenshots. No catalog data is injected into the browser by the tests.
|
||||
@@ -0,0 +1,457 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { createServer } from 'node:http';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
|
||||
const blockName = 'lamgc/asciiplayer';
|
||||
const fixturePath = '/wp-content/uploads/asciiplayer-fixtures/hello.cast';
|
||||
|
||||
async function logIn(page) {
|
||||
await page.goto('/wp-login.php');
|
||||
await page.locator('#user_login').fill(process.env.WP_USERNAME || 'admin');
|
||||
await page.locator('#user_pass').fill(process.env.WP_PASSWORD || 'password');
|
||||
await page.locator('#wp-submit').click();
|
||||
await expect(page).toHaveURL(/\/wp-admin\//);
|
||||
}
|
||||
|
||||
async function openEditor(page, postType = 'post') {
|
||||
await page.goto(`/wp-admin/post-new.php?post_type=${postType}`);
|
||||
await page.waitForFunction((name) => Boolean(
|
||||
window.wp?.blocks?.getBlockType(name) &&
|
||||
window.wp?.data?.select('core/editor')?.getCurrentPostId()
|
||||
), blockName);
|
||||
await page.evaluate(() => {
|
||||
for (const scope of ['core/edit-post', 'core/editor']) {
|
||||
window.wp.data.dispatch('core/preferences').set(scope, 'welcomeGuide', false);
|
||||
}
|
||||
});
|
||||
// A block-pattern picker can appear on a new Page in some core releases.
|
||||
const closeDialog = page.getByRole('dialog').getByRole('button', { name: /close/i });
|
||||
if (await closeDialog.count()) await closeDialog.first().click();
|
||||
await expect(page.locator('iframe[name="editor-canvas"]')).toBeVisible();
|
||||
}
|
||||
|
||||
async function insertPlayer(page, attributes = {}) {
|
||||
return page.evaluate(({ name, attrs }) => {
|
||||
const block = window.wp.blocks.createBlock(name, attrs);
|
||||
window.wp.data.dispatch('core/block-editor').insertBlocks(block);
|
||||
window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId);
|
||||
return block.clientId;
|
||||
}, { name: blockName, attrs: attributes });
|
||||
}
|
||||
|
||||
function canvas(page) {
|
||||
return page.frameLocator('iframe[name="editor-canvas"]');
|
||||
}
|
||||
|
||||
function playerBlock(page, clientId) {
|
||||
return canvas(page).locator(`[data-block="${clientId}"]`);
|
||||
}
|
||||
|
||||
async function readyPreview(block) {
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
|
||||
await expect(block.locator('.asciiplayer-editor__player .ap-wrapper')).toHaveCount(1);
|
||||
await expect(block.locator('.ap-wrapper')).toBeVisible();
|
||||
}
|
||||
|
||||
async function publish(page, title) {
|
||||
return page.evaluate(async (postTitle) => {
|
||||
const editor = window.wp.data.dispatch('core/editor');
|
||||
editor.editPost({ title: postTitle, status: 'publish' });
|
||||
await editor.savePost();
|
||||
const state = window.wp.data.select('core/editor');
|
||||
if (state.didPostSaveRequestFail()) throw new Error('WordPress could not save the test post.');
|
||||
return { id: state.getCurrentPostId(), url: state.getPermalink() };
|
||||
}, title);
|
||||
}
|
||||
|
||||
async function createContent(page, postType, content) {
|
||||
return page.evaluate(async ({ type, html }) => window.wp.apiFetch({
|
||||
path: `/wp/v2/${type === 'page' ? 'pages' : 'posts'}`,
|
||||
method: 'POST',
|
||||
data: { title: `Asciiplayer integration ${Date.now()}`, status: 'publish', content: html },
|
||||
}), { type: postType, html: content });
|
||||
}
|
||||
|
||||
async function expectFrontendPlayer(container) {
|
||||
await expect(container.locator('.ap-wrapper')).toBeVisible();
|
||||
// This starts actual playback and checks parsed terminal output. Merely
|
||||
// finding the player's outer DOM would miss fetch/CORS/parser failures.
|
||||
const start = container.locator('.ap-overlay-start .ap-play-button');
|
||||
if (await start.isVisible()) await start.click();
|
||||
await expect(container).toContainText('Hello from wp-asciiplayer');
|
||||
}
|
||||
|
||||
async function screenshot(page, testInfo, name) {
|
||||
const path = testInfo.outputPath(`${name}.png`);
|
||||
await page.screenshot({ path, fullPage: true });
|
||||
await testInfo.attach(name, { path, contentType: 'image/png' });
|
||||
}
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await logIn(page);
|
||||
});
|
||||
|
||||
test('real iframe preview survives edits, duplicate, delete, undo, save and reload', async ({ page }, testInfo) => {
|
||||
const cdnRequests = [];
|
||||
const pageErrors = [];
|
||||
page.on('request', (request) => {
|
||||
if (new URL(request.url()).hostname.endsWith('jsdelivr.net')) cdnRequests.push(request.url());
|
||||
});
|
||||
page.on('pageerror', (error) => pageErrors.push(error.message));
|
||||
await openEditor(page);
|
||||
const source = new URL(fixturePath, page.url()).href;
|
||||
const id = await insertPlayer(page);
|
||||
const block = playerBlock(page, id);
|
||||
await block.getByRole('textbox', { name: 'Recording URL', exact: true }).fill(source);
|
||||
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
|
||||
await readyPreview(block);
|
||||
await block.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expect(block.locator('.ap-term-text')).toContainText('Hello from wp-asciiplayer');
|
||||
const playback = block.locator('.ap-playback-button');
|
||||
await expect(playback).toHaveAttribute('aria-label', 'Pause');
|
||||
await block.locator('.ap-term-text').press('Space');
|
||||
await expect(playback).toHaveAttribute('aria-label', 'Play');
|
||||
await block.locator('.ap-term-text').press('Space');
|
||||
await expect(playback).toHaveAttribute('aria-label', 'Pause');
|
||||
await block.locator('.ap-term-text').press('Space');
|
||||
await page.setViewportSize({ width: 900, height: 800 });
|
||||
await expect(block.locator('.ap-wrapper')).toBeVisible();
|
||||
const canvasWidth = await page.locator('iframe[name="editor-canvas"]').evaluate((element) => element.clientWidth);
|
||||
await expect.poll(async () => (await block.locator('.ap-wrapper').boundingBox()).width).toBeLessThanOrEqual(canvasWidth);
|
||||
await page.setViewportSize({ width: 1280, height: 720 });
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
|
||||
|
||||
// Exercise a real inspector input; data-store operations below cover core's
|
||||
// block lifecycle without depending on changing toolbar/menu copy.
|
||||
const speed = page.getByRole('spinbutton', { name: 'Playback speed', exact: true });
|
||||
await speed.fill('1.5');
|
||||
await speed.press('Tab');
|
||||
await expect.poll(() => page.evaluate((clientId) =>
|
||||
window.wp.data.select('core/block-editor').getBlockAttributes(clientId).speed, id
|
||||
)).toBe(1.5);
|
||||
await readyPreview(block);
|
||||
await page.getByRole('combobox', { name: 'Theme', exact: true }).selectOption('solarized-dark');
|
||||
await readyPreview(block);
|
||||
await expect(block.locator('.ap-player')).toHaveClass(/asciinema-player-theme-solarized-dark/);
|
||||
|
||||
const duplicateId = await page.evaluate(async (clientId) => {
|
||||
await window.wp.data.dispatch('core/block-editor').duplicateBlocks([clientId]);
|
||||
return window.wp.data.select('core/block-editor').getBlocks().find((entry) => entry.name === 'lamgc/asciiplayer' && entry.clientId !== clientId).clientId;
|
||||
}, id);
|
||||
await readyPreview(playerBlock(page, duplicateId));
|
||||
await expect(canvas(page).locator('.asciiplayer-editor__player .ap-wrapper')).toHaveCount(2);
|
||||
await page.evaluate((clientId) => window.wp.data.dispatch('core/block-editor').removeBlocks([clientId]), duplicateId);
|
||||
await expect(canvas(page).locator('.asciiplayer-editor__player .ap-wrapper')).toHaveCount(1);
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/editor').undo());
|
||||
await readyPreview(playerBlock(page, duplicateId));
|
||||
await expect(canvas(page).locator('.asciiplayer-editor__player .ap-wrapper')).toHaveCount(2);
|
||||
await page.evaluate((clientId) => window.wp.data.dispatch('core/block-editor').removeBlocks([clientId]), duplicateId);
|
||||
|
||||
const saved = await publish(page, 'Inline preview lifecycle integration');
|
||||
await screenshot(page, testInfo, 'real-wordpress-editor');
|
||||
await page.reload();
|
||||
await page.waitForFunction(() => window.wp?.data?.select('core/block-editor')?.getBlocks().length > 0);
|
||||
const reloaded = await page.evaluate(() => window.wp.data.select('core/block-editor').getBlocks().find((entry) => entry.name === 'lamgc/asciiplayer'));
|
||||
expect(reloaded.name).toBe(blockName);
|
||||
expect(reloaded.attributes).toMatchObject({ source, speed: 1.5, theme: 'solarized-dark' });
|
||||
await readyPreview(playerBlock(page, reloaded.clientId));
|
||||
|
||||
await page.goto(saved.url);
|
||||
const container = page.locator('.asciiplayer-container');
|
||||
await expect(container).toHaveCount(1);
|
||||
expect(JSON.parse(await container.getAttribute('data-ap-options'))).toMatchObject({ speed: 1.5, theme: 'solarized-dark' });
|
||||
await expectFrontendPlayer(container);
|
||||
await screenshot(page, testInfo, 'real-wordpress-post');
|
||||
expect(cdnRequests, 'No plugin runtime may be loaded from jsDelivr').toEqual([]);
|
||||
expect(pageErrors).toEqual([]);
|
||||
});
|
||||
|
||||
test('a published Page plays its block at desktop and mobile widths', async ({ page }, testInfo) => {
|
||||
await openEditor(page, 'page');
|
||||
const source = new URL(fixturePath, page.url()).href;
|
||||
const id = await insertPlayer(page, { source, controls: 'always', preload: true });
|
||||
await readyPreview(playerBlock(page, id));
|
||||
const saved = await publish(page, 'Page playback integration');
|
||||
await page.goto(saved.url);
|
||||
const container = page.locator('.asciiplayer-container');
|
||||
await expectFrontendPlayer(container);
|
||||
await page.setViewportSize({ width: 375, height: 812 });
|
||||
await expect(container.locator('.ap-wrapper')).toBeVisible();
|
||||
const bounds = await container.locator('.ap-wrapper').boundingBox();
|
||||
expect(bounds.width).toBeLessThanOrEqual(375);
|
||||
await screenshot(page, testInfo, 'real-wordpress-page-mobile');
|
||||
});
|
||||
|
||||
for (const postType of ['post', 'page']) {
|
||||
test(`legacy shortcodes play multiple recordings on a ${postType}`, async ({ page }) => {
|
||||
await openEditor(page, postType);
|
||||
const source = new URL(fixturePath, page.url()).href;
|
||||
const content = `[asciiplayer controls="false" autoPlay="true" startAt="0.1" idleTimeLimit="1" speed="1.5" loop="false" style="max-width: 640px;"]${source}[/asciiplayer]\n` +
|
||||
`[asciiplayer controls="true" theme="solarized-dark" preload="true"]${source}[/asciiplayer]`;
|
||||
const saved = await createContent(page, postType, content);
|
||||
await page.goto(saved.link);
|
||||
const containers = page.locator('.asciiplayer-container');
|
||||
await expect(containers).toHaveCount(2);
|
||||
const options = JSON.parse(await containers.nth(0).getAttribute('data-ap-options'));
|
||||
expect(options).toMatchObject({ autoPlay: true, startAt: 0.1, idleTimeLimit: 1, speed: 1.5, loop: false });
|
||||
expect(options.controls).toBe(false);
|
||||
const otherOptions = JSON.parse(await containers.nth(1).getAttribute('data-ap-options'));
|
||||
expect(otherOptions.controls).toBe(true);
|
||||
await expectFrontendPlayer(containers.nth(0));
|
||||
await expect(containers.nth(0).locator('.ap-control-bar')).toHaveCount(0);
|
||||
await expectFrontendPlayer(containers.nth(1));
|
||||
});
|
||||
}
|
||||
|
||||
for (const filename of ['missing.cast', 'malformed.cast']) {
|
||||
test(`a ${filename} recording produces a recoverable inline error`, async ({ page }) => {
|
||||
const pageErrors = [];
|
||||
page.on('pageerror', (error) => pageErrors.push(error.message));
|
||||
await openEditor(page);
|
||||
const source = new URL(`/wp-content/uploads/asciiplayer-fixtures/${filename}`, page.url()).href;
|
||||
const id = await insertPlayer(page);
|
||||
const block = playerBlock(page, id);
|
||||
await block.getByRole('textbox', { name: 'Recording URL', exact: true }).fill(source);
|
||||
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'error');
|
||||
await expect(block).toContainText('Unable to load the recording.');
|
||||
await expect(block.getByRole('button', { name: 'Retry preview', exact: true })).toBeVisible();
|
||||
await block.getByRole('textbox', { name: 'Recording URL', exact: true }).fill(new URL(fixturePath, page.url()).href);
|
||||
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
|
||||
await readyPreview(block);
|
||||
expect(pageErrors).toEqual([]);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
test('a real cross-origin server without CORS permission shows an error and recovers', async ({ page }) => {
|
||||
const recording = await readFile(new URL('../fixtures/hello.cast', import.meta.url));
|
||||
const server = createServer((_request, response) => {
|
||||
response.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
response.end(recording);
|
||||
});
|
||||
await new Promise((resolve, reject) => {
|
||||
server.once('error', reject);
|
||||
server.listen(0, '127.0.0.1', resolve);
|
||||
});
|
||||
try {
|
||||
await openEditor(page);
|
||||
const id = await insertPlayer(page);
|
||||
const block = playerBlock(page, id);
|
||||
const address = server.address();
|
||||
const crossOriginSource = `http://127.0.0.1:${address.port}/hello.cast`;
|
||||
await block.getByRole('textbox', { name: 'Recording URL', exact: true }).fill(crossOriginSource);
|
||||
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'error');
|
||||
await expect(block).toContainText('CORS permissions');
|
||||
await block.getByRole('textbox', { name: 'Recording URL', exact: true }).fill(new URL(fixturePath, page.url()).href);
|
||||
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
|
||||
await readyPreview(block);
|
||||
} finally {
|
||||
server.closeAllConnections();
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
}
|
||||
});
|
||||
|
||||
test('a saved Recording URL loads once without a click and never autoplays in the editor', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const source = new URL(`${fixturePath}?automatic=saved`, page.url()).href;
|
||||
const recording = await readFile(new URL('../fixtures/hello.cast', import.meta.url));
|
||||
const requests = [];
|
||||
await page.route(source, async (route) => {
|
||||
requests.push(route.request().url());
|
||||
await route.fulfill({ contentType: 'text/plain', body: recording });
|
||||
});
|
||||
const id = await insertPlayer(page, { source, autoPlay: true, preload: false });
|
||||
const block = playerBlock(page, id);
|
||||
await readyPreview(block);
|
||||
await expect(block.getByRole('button', { name: 'Load preview', exact: true })).toHaveCount(0);
|
||||
await expect(block.locator('.ap-overlay-start .ap-play-button')).toBeVisible();
|
||||
await expect(block.locator('.asciiplayer-editor__privacy')).toHaveCount(0);
|
||||
await expect(block.locator(':scope > .asciiplayer-editor__hint')).toHaveCount(0);
|
||||
await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toBeVisible();
|
||||
await expect(block.getByRole('button', { name: 'Choose recording', exact: true })).toBeVisible();
|
||||
await expect(block.locator('figcaption[contenteditable="true"]')).toBeVisible();
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
|
||||
const helpToggle = page.locator('.components-panel__body-toggle').filter({ hasText: /^Help$/ });
|
||||
await expect(helpToggle).toHaveAttribute('aria-expanded', 'false');
|
||||
await helpToggle.click();
|
||||
const help = page.locator('.components-panel__body').filter({ has: helpToggle });
|
||||
await expect(help.locator('.asciiplayer-editor__privacy')).toContainText(/automatic/i);
|
||||
await expect(help.locator('.asciiplayer-editor__privacy')).toContainText(/server/i);
|
||||
await expect(help).toContainText('Use the player controls to play, pause, and seek.');
|
||||
await helpToggle.click();
|
||||
await expect(helpToggle).toHaveAttribute('aria-expanded', 'false');
|
||||
await page.waitForTimeout(750); // Catch a second fetch from a pending debounce.
|
||||
expect(requests).toEqual([source]);
|
||||
await expect(block.locator('.ap-overlay-start .ap-play-button')).toBeVisible();
|
||||
});
|
||||
|
||||
test('rapid URL edits debounce to one recording fetch and Apply cancels its pending debounce', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const prefix = new URL(`${fixturePath}?automatic=`, page.url()).href;
|
||||
const recording = await readFile(new URL('../fixtures/hello.cast', import.meta.url));
|
||||
const requests = [];
|
||||
await page.route(`${prefix}*`, async (route) => {
|
||||
requests.push(route.request().url());
|
||||
await route.fulfill({ contentType: 'text/plain', body: recording });
|
||||
});
|
||||
const id = await insertPlayer(page);
|
||||
const block = playerBlock(page, id);
|
||||
const input = block.getByRole('textbox', { name: 'Recording URL', exact: true });
|
||||
await input.fill(`${prefix}first`);
|
||||
await input.fill(`${prefix}second`);
|
||||
await input.fill(`${prefix}final`);
|
||||
await readyPreview(block);
|
||||
await page.waitForTimeout(750);
|
||||
expect(requests).toEqual([`${prefix}final`]);
|
||||
await expect.poll(() => page.evaluate((clientId) =>
|
||||
window.wp.data.select('core/block-editor').getBlockAttributes(clientId).source, id
|
||||
)).toBe(`${prefix}final`);
|
||||
await input.fill(`${prefix}applied`);
|
||||
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
|
||||
await expect.poll(() => requests).toEqual([`${prefix}final`, `${prefix}applied`]);
|
||||
await readyPreview(block);
|
||||
await page.waitForTimeout(750);
|
||||
expect(requests).toEqual([`${prefix}final`, `${prefix}applied`]);
|
||||
});
|
||||
|
||||
test('replacing a pending recording ignores its stale response', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const source = new URL(`${fixturePath}?automatic=stale`, page.url()).href;
|
||||
const latest = new URL(`${fixturePath}?automatic=latest`, page.url()).href;
|
||||
const recording = await readFile(new URL('../fixtures/hello.cast', import.meta.url), 'utf8');
|
||||
let release;
|
||||
const pending = new Promise((resolve) => { release = resolve; });
|
||||
let oldRequested = false;
|
||||
let oldResponseSettled = false;
|
||||
await page.route(source, async (route) => {
|
||||
oldRequested = true;
|
||||
await pending;
|
||||
// Aborting a replaced player may cancel this intercepted request. Both
|
||||
// cancellation and safely ignoring a late response are valid outcomes.
|
||||
await route.fulfill({ contentType: 'text/plain', body: recording.replace('"width":64', '"width":120') }).catch(() => {});
|
||||
oldResponseSettled = true;
|
||||
});
|
||||
await page.route(latest, (route) => route.fulfill({ contentType: 'text/plain', body: recording }));
|
||||
try {
|
||||
const id = await insertPlayer(page, { source });
|
||||
const block = playerBlock(page, id);
|
||||
await expect.poll(() => oldRequested).toBe(true);
|
||||
await block.getByRole('textbox', { name: 'Recording URL', exact: true }).fill(latest);
|
||||
await expect.poll(() => page.evaluate((clientId) =>
|
||||
window.wp.data.select('core/block-editor').getBlockAttributes(clientId).source, id
|
||||
)).toBe(latest);
|
||||
await readyPreview(block);
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
|
||||
const columns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
|
||||
const rows = page.getByRole('spinbutton', { name: 'Rows', exact: true });
|
||||
if (!await columns.isVisible()) {
|
||||
await page.locator('.components-panel__body-toggle').filter({ hasText: /^Terminal size$/ }).click();
|
||||
}
|
||||
await expect(columns).toHaveAttribute('placeholder', '64');
|
||||
await expect(rows).toHaveAttribute('placeholder', '12');
|
||||
release();
|
||||
await expect.poll(() => oldResponseSettled).toBe(true);
|
||||
await page.waitForTimeout(750);
|
||||
await readyPreview(block);
|
||||
await expect.poll(() => block.locator('.ap-term').evaluate((terminal) =>
|
||||
Number(terminal.style.getPropertyValue('--term-cols'))
|
||||
)).toBe(64);
|
||||
// A late header from the old 120-column cast must not become a hint.
|
||||
await expect(columns).toHaveAttribute('placeholder', '64');
|
||||
await expect(rows).toHaveAttribute('placeholder', '12');
|
||||
await expect(columns).toHaveValue('');
|
||||
await expect(rows).toHaveValue('');
|
||||
await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue(latest);
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
});
|
||||
|
||||
test('automatic preview errors retry the unchanged URL through Retry preview and Apply URL', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const source = new URL(`${fixturePath}?automatic=retry`, page.url()).href;
|
||||
const recording = await readFile(new URL('../fixtures/hello.cast', import.meta.url));
|
||||
let requests = 0;
|
||||
await page.route(source, async (route) => {
|
||||
requests += 1;
|
||||
await route.fulfill(requests < 3
|
||||
? { status: 503, contentType: 'text/plain', body: 'Temporarily unavailable' }
|
||||
: { contentType: 'text/plain', body: recording });
|
||||
});
|
||||
const id = await insertPlayer(page, { source });
|
||||
const block = playerBlock(page, id);
|
||||
const preview = block.locator('.asciiplayer-editor__preview');
|
||||
await expect(preview).toHaveAttribute('data-preview-status', 'error');
|
||||
expect(requests).toBe(1);
|
||||
await block.getByRole('button', { name: 'Retry preview', exact: true }).click();
|
||||
await expect.poll(() => requests).toBe(2);
|
||||
await expect(preview).toHaveAttribute('data-preview-status', 'error');
|
||||
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
|
||||
await readyPreview(block);
|
||||
await page.waitForTimeout(750);
|
||||
expect(requests).toBe(3);
|
||||
});
|
||||
|
||||
test('empty and invalid sources never create a preview or fetch a recording', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const requests = [];
|
||||
page.on('request', (request) => {
|
||||
if (/\.cast(?:[?#]|$)|asciinema\.org|jsdelivr\.net/.test(request.url())) requests.push(request.url());
|
||||
});
|
||||
const emptyId = await insertPlayer(page);
|
||||
const empty = playerBlock(page, emptyId);
|
||||
const invalidId = await insertPlayer(page, { source: 'javascript:alert(1)' });
|
||||
const invalid = playerBlock(page, invalidId);
|
||||
await expect(empty.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue('');
|
||||
await expect(invalid.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue('javascript:alert(1)');
|
||||
await page.waitForTimeout(750);
|
||||
await expect(empty.locator('.asciiplayer-editor__preview')).toHaveCount(0);
|
||||
await expect(invalid.locator('.asciiplayer-editor__preview')).toHaveCount(0);
|
||||
const input = empty.getByRole('textbox', { name: 'Recording URL', exact: true });
|
||||
await input.fill(new URL(fixturePath, page.url()).href);
|
||||
await input.fill('');
|
||||
await page.waitForTimeout(750);
|
||||
await expect(empty.locator('.asciiplayer-editor__preview')).toHaveCount(0);
|
||||
await input.fill('https://');
|
||||
await page.waitForTimeout(750);
|
||||
await expect(empty.locator('.asciiplayer-editor__preview')).toHaveCount(0);
|
||||
expect(requests).toEqual([]);
|
||||
});
|
||||
|
||||
test('external source changes and undo clear an invalid draft error and restore the valid preview', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const original = new URL(`${fixturePath}?automatic=undo-original`, page.url()).href;
|
||||
const replacement = new URL(`${fixturePath}?automatic=undo-replacement`, page.url()).href;
|
||||
const id = await insertPlayer(page, { source: original });
|
||||
const block = playerBlock(page, id);
|
||||
const input = block.getByRole('textbox', { name: 'Recording URL', exact: true });
|
||||
const validation = block.locator('.asciiplayer-editor__source .components-notice');
|
||||
await readyPreview(block);
|
||||
// Save a baseline so Undo below targets the external source replacement,
|
||||
// rather than an insertion or another edit batched into the same history.
|
||||
await publish(page, 'Automatic preview source synchronization regression');
|
||||
await input.fill('https://');
|
||||
await expect(validation).toContainText('Enter an HTTP(S) recording URL');
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveCount(0);
|
||||
await page.evaluate(({ clientId, source }) =>
|
||||
window.wp.data.dispatch('core/block-editor').updateBlockAttributes(clientId, { source }),
|
||||
{ clientId: id, source: replacement });
|
||||
await expect(input).toHaveValue(replacement);
|
||||
await readyPreview(block);
|
||||
await expect(validation).toHaveCount(0);
|
||||
// An invalid local draft does not change the saved source or undo history.
|
||||
await input.fill('javascript:alert(1)');
|
||||
await expect(validation).toContainText('Enter an HTTP(S) recording URL');
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveCount(0);
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/editor').undo());
|
||||
await expect(input).toHaveValue(original);
|
||||
await readyPreview(block);
|
||||
await expect(validation).toHaveCount(0);
|
||||
await page.waitForTimeout(750); // A canceled invalid-draft timer cannot reappear.
|
||||
await expect(validation).toHaveCount(0);
|
||||
await expect.poll(() => page.evaluate((clientId) =>
|
||||
window.wp.data.select('core/block-editor').getBlockAttributes(clientId).source, id
|
||||
)).toBe(original);
|
||||
});
|
||||
@@ -0,0 +1,218 @@
|
||||
import { test as base, expect } from '@playwright/test';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
|
||||
const blockName = 'lamgc/asciiplayer';
|
||||
const fixturePath = '/wp-content/uploads/asciiplayer-fixtures';
|
||||
const copy = {
|
||||
en_US: {
|
||||
title: 'Asciicast Player', source: 'Recording URL', apply: 'Apply URL',
|
||||
choose: 'Choose recording', dimensions: 'Terminal size', columns: 'Columns', rows: 'Rows',
|
||||
help: 'Help', retry: 'Retry preview', captionLabel: 'Recording caption',
|
||||
previewError: 'Unable to load the recording. Check the URL, file format, and the source server’s CORS permissions.',
|
||||
frontendError: 'Unable to load this terminal recording. The file may be unavailable, invalid, or blocked by the source server’s CORS policy.',
|
||||
uploadError: 'Upload a valid Asciicast v2/v3 JSONL or pretty-printed v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, and 1,000 columns or rows).',
|
||||
},
|
||||
zh_CN: {
|
||||
title: 'Asciicast 播放器', source: '录制文件 URL', apply: '应用 URL',
|
||||
choose: '选择录制文件', dimensions: '终端尺寸', columns: '列数', rows: '行数',
|
||||
help: '帮助', retry: '重试预览', captionLabel: '录屏说明文字',
|
||||
previewError: '无法加载录制文件。请检查 URL、文件格式及来源服务器的跨域请求(CORS)权限。',
|
||||
frontendError: '无法加载此终端录屏。文件可能无法访问、格式无效,或被来源服务器的跨域请求(CORS)策略阻止。',
|
||||
uploadError: '请上传有效的 Asciicast v2/v3 JSONL 或格式化的 v1 .cast 录制文件(最大 32 MiB;v1 最大 2 MiB;最多 100,000 个事件;每行 JSONL最大 256 KiB;列数和行数均不超过 1,000)。',
|
||||
},
|
||||
};
|
||||
|
||||
async function login(page) {
|
||||
await page.goto('/wp-login.php');
|
||||
await page.locator('#user_login').fill(process.env.WP_USERNAME || 'admin');
|
||||
await page.locator('#user_pass').fill(process.env.WP_PASSWORD || 'password');
|
||||
await page.locator('#wp-submit').click();
|
||||
await expect(page).toHaveURL(/\/wp-admin\//);
|
||||
}
|
||||
|
||||
async function openEditor(page) {
|
||||
await page.goto('/wp-admin/post-new.php');
|
||||
await page.waitForFunction((name) => Boolean(
|
||||
window.wp?.apiFetch && window.wp?.blocks?.getBlockType(name) &&
|
||||
window.wp?.data?.select('core/editor')?.getCurrentPostId()
|
||||
), blockName);
|
||||
await page.evaluate(() => {
|
||||
for (const scope of ['core/edit-post', 'core/editor']) {
|
||||
window.wp.data.dispatch('core/preferences').set(scope, 'welcomeGuide', false);
|
||||
}
|
||||
});
|
||||
await expect(page.locator('iframe[name="editor-canvas"]')).toBeVisible();
|
||||
}
|
||||
|
||||
// Change actual WordPress settings, never navigator.language or wp.i18n mocks.
|
||||
// Keep an authenticated control page alive so cleanup also works if a test
|
||||
// finishes on the public site or fails during a player/media interaction.
|
||||
const test = base.extend({
|
||||
localeSession: async ({ context }, use) => {
|
||||
const control = await context.newPage();
|
||||
await login(control);
|
||||
await control.goto('/wp-admin/profile.php');
|
||||
const language = control.locator('#locale');
|
||||
await expect(language, 'Install the zh_CN core language pack before this suite.').toBeVisible();
|
||||
await expect(language.locator('option[value="zh_CN"]')).toHaveCount(1);
|
||||
const selectedUserLocale = await language.inputValue();
|
||||
const originalUserLocale = selectedUserLocale === 'site-default' ? '' : selectedUserLocale;
|
||||
await openEditor(control);
|
||||
const originalSiteLocale = await control.evaluate(async () =>
|
||||
(await window.wp.apiFetch({ path: '/wp/v2/settings' })).language
|
||||
);
|
||||
const setLocales = async (siteLocale, userLocale) => control.evaluate(async ({ site, user }) => {
|
||||
const settings = await window.wp.apiFetch({ path: '/wp/v2/settings', method: 'POST', data: { language: site } });
|
||||
const currentUser = await window.wp.apiFetch({ path: '/wp/v2/users/me', method: 'POST', data: { locale: user } });
|
||||
return { site: settings.language || 'en_US', user: currentUser.locale };
|
||||
}, { site: siteLocale, user: userLocale });
|
||||
try {
|
||||
await use({ setLocales, control });
|
||||
} finally {
|
||||
await setLocales(originalSiteLocale, originalUserLocale);
|
||||
await control.close();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
async function insertPlayer(page) {
|
||||
const id = await page.evaluate((name) => {
|
||||
const block = window.wp.blocks.createBlock(name, { controls: 'always' });
|
||||
window.wp.data.dispatch('core/block-editor').insertBlocks(block);
|
||||
window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId);
|
||||
return block.clientId;
|
||||
}, blockName);
|
||||
return page.frameLocator('iframe[name="editor-canvas"]').locator(`[data-block="${id}"]`);
|
||||
}
|
||||
|
||||
async function assertTranslatedError(locator, locale, kind) {
|
||||
// Expected strings are independent literals, never read from the loaded
|
||||
// catalog: a missing translation must fail instead of defining expectations.
|
||||
await expect(locator).toHaveText(copy[locale][kind]);
|
||||
}
|
||||
|
||||
async function rejectInvalidUpload(page, block, locale, testInfo) {
|
||||
await block.getByRole('button', { name: copy[locale].choose, exact: true }).click();
|
||||
const dialog = page.locator('.media-modal[role="dialog"]');
|
||||
await expect(dialog).toBeVisible();
|
||||
await dialog.locator('#menu-item-upload').click();
|
||||
const input = page.locator('.moxie-shim input[type="file"]').last();
|
||||
await expect(input).toBeAttached();
|
||||
const response = page.waitForResponse((result) =>
|
||||
/\/wp-admin\/async-upload\.php(?:\?|$)/.test(result.url()) && result.request().method() === 'POST'
|
||||
);
|
||||
await input.setInputFiles({
|
||||
name: `asciiplayer-locale-invalid-${Date.now()}-${testInfo.retry}.cast`,
|
||||
mimeType: 'application/x-asciicast',
|
||||
buffer: await readFile(new URL('../fixtures/malformed.cast', import.meta.url)),
|
||||
});
|
||||
const result = await (await response).json();
|
||||
expect(result.success, JSON.stringify(result)).toBe(false);
|
||||
expect(result.data.message).toBe(copy[locale].uploadError);
|
||||
await expect(dialog).toContainText(result.data.message);
|
||||
await expect(dialog.locator('.media-button-select')).toBeDisabled();
|
||||
await dialog.locator('.media-modal-close').click();
|
||||
}
|
||||
|
||||
async function verifyFrontend(page, url, locale) {
|
||||
await page.goto(url);
|
||||
await expect(page.locator('html')).toHaveAttribute('lang', locale === 'zh_CN' ? /^zh-(CN|Hans)$/ : 'en-US');
|
||||
const players = page.locator('.asciiplayer-container');
|
||||
await expect(players).toHaveCount(3);
|
||||
await assertTranslatedError(players.nth(1).locator('.asciiplayer-error'), locale, 'frontendError');
|
||||
for (const index of [0, 2]) {
|
||||
const player = players.nth(index);
|
||||
await expect(player.locator('.ap-wrapper')).toBeVisible();
|
||||
await player.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expect(player.locator('.ap-term-text')).toContainText('Hello from wp-asciiplayer');
|
||||
}
|
||||
await expect(page.locator('.asciiplayer-figure figcaption')).toHaveText('Author caption / 作者说明');
|
||||
}
|
||||
|
||||
test.describe('@i18n real WordPress site and user locales', () => {
|
||||
// Locale is site-global. The repository config has one worker; do not run
|
||||
// these cases concurrently against a shared WordPress database.
|
||||
test.describe.configure({ mode: 'default' });
|
||||
for (const [siteLocale, userLocale] of [
|
||||
['en_US', 'en_US'], ['zh_CN', 'zh_CN'],
|
||||
['zh_CN', 'en_US'], ['en_US', 'zh_CN'],
|
||||
]) {
|
||||
test(`site ${siteLocale}, user ${userLocale}: editor, PHP upload and public player`, async ({ page, browser, localeSession }, testInfo) => {
|
||||
test.setTimeout(150_000);
|
||||
const locales = await localeSession.setLocales(siteLocale, userLocale);
|
||||
expect(locales).toEqual({ site: siteLocale, user: userLocale });
|
||||
const ui = copy[userLocale];
|
||||
const pageErrors = [];
|
||||
page.on('pageerror', (error) => pageErrors.push(error.message));
|
||||
await openEditor(page);
|
||||
await expect(page.locator('html')).toHaveAttribute('lang', userLocale === 'zh_CN' ? /^zh-(CN|Hans)$/ : 'en-US');
|
||||
expect(await page.evaluate((name) => window.wp.blocks.getBlockType(name).title, blockName)).toBe(ui.title);
|
||||
const block = await insertPlayer(page);
|
||||
const source = block.getByRole('textbox', { name: ui.source, exact: true });
|
||||
await expect(source).toBeVisible();
|
||||
await expect(block.getByRole('button', { name: ui.apply, exact: true })).toBeVisible();
|
||||
await expect(block.getByRole('button', { name: ui.choose, exact: true })).toBeVisible();
|
||||
await expect(block.locator('figcaption[contenteditable="true"]')).toHaveAttribute('aria-label', ui.captionLabel);
|
||||
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
|
||||
await page.locator('.components-panel__body-toggle').filter({ hasText: new RegExp(`^${ui.dimensions}$`) }).click();
|
||||
await expect(page.getByRole('spinbutton', { name: ui.columns, exact: true })).toBeVisible();
|
||||
await expect(page.getByRole('spinbutton', { name: ui.rows, exact: true })).toBeVisible();
|
||||
await expect(page.locator('.components-panel__body-toggle').filter({ hasText: new RegExp(`^${ui.help}$`) })).toBeVisible();
|
||||
|
||||
const valid = new URL(`${fixturePath}/hello.cast`, page.url()).href;
|
||||
const missing = new URL(`${fixturePath}/missing-i18n.cast`, page.url()).href;
|
||||
await source.fill(missing);
|
||||
await block.getByRole('button', { name: ui.apply, exact: true }).click();
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'error');
|
||||
await assertTranslatedError(block.locator('.components-notice__content > p'), userLocale, 'previewError');
|
||||
await expect(block.getByRole('button', { name: ui.retry, exact: true })).toBeVisible();
|
||||
await source.fill(valid);
|
||||
await block.getByRole('button', { name: ui.apply, exact: true }).click();
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
|
||||
await block.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expect(block.locator('.ap-term-text')).toContainText('Hello from wp-asciiplayer');
|
||||
// Upstream 3.17.0 has no localization API. Its unmodified controls
|
||||
// deliberately retain their English accessibility labels in both locales.
|
||||
await expect(block.locator('.ap-playback-button')).toHaveAttribute('aria-label', 'Pause');
|
||||
await block.locator('.ap-playback-button').click();
|
||||
await expect(block.locator('.ap-playback-button')).toHaveAttribute('aria-label', 'Play');
|
||||
await rejectInvalidUpload(page, block, userLocale, testInfo);
|
||||
|
||||
const editorShot = testInfo.outputPath(`editor-${siteLocale}-${userLocale}.png`);
|
||||
await page.screenshot({ path: editorShot, fullPage: true });
|
||||
await testInfo.attach('editor-locale', { path: editorShot, contentType: 'image/png' });
|
||||
const saved = await page.evaluate(async ({ name, good, bad }) => {
|
||||
const blockContent = window.wp.blocks.serialize(window.wp.blocks.createBlock(name, {
|
||||
source: good, controls: 'always', preload: true, caption: 'Author caption / 作者说明',
|
||||
}));
|
||||
return window.wp.apiFetch({ path: '/wp/v2/posts', method: 'POST', data: {
|
||||
title: `Asciiplayer locale integration ${Date.now()}`, status: 'publish',
|
||||
content: `${blockContent}\n[asciiplayer preload="true"]${bad}[/asciiplayer]\n[asciiplayer preload="true"]${good}[/asciiplayer]`,
|
||||
} });
|
||||
}, { name: blockName, good: valid, bad: missing });
|
||||
// A logged-in user's language must not leak into public frontend JS.
|
||||
await verifyFrontend(page, saved.link, siteLocale);
|
||||
const anonymous = await browser.newContext();
|
||||
try {
|
||||
const visitor = await anonymous.newPage();
|
||||
visitor.on('pageerror', (error) => pageErrors.push(error.message));
|
||||
await verifyFrontend(visitor, saved.link, siteLocale);
|
||||
const frontendShot = testInfo.outputPath(`frontend-${siteLocale}-${userLocale}.png`);
|
||||
await visitor.screenshot({ path: frontendShot, fullPage: true });
|
||||
await testInfo.attach('frontend-locale', { path: frontendShot, contentType: 'image/png' });
|
||||
} finally {
|
||||
await anonymous.close();
|
||||
}
|
||||
expect(pageErrors).toEqual([]);
|
||||
});
|
||||
}
|
||||
|
||||
test('a user with the site default language inherits zh_CN in the editor', async ({ page, localeSession }) => {
|
||||
expect(await localeSession.setLocales('zh_CN', '')).toEqual({ site: 'zh_CN', user: 'zh_CN' });
|
||||
await openEditor(page);
|
||||
expect(await page.evaluate((name) => window.wp.blocks.getBlockType(name).title, blockName)).toBe(copy.zh_CN.title);
|
||||
const block = await insertPlayer(page);
|
||||
await expect(block.getByRole('textbox', { name: copy.zh_CN.source, exact: true })).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,548 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const blockName = 'lamgc/asciiplayer';
|
||||
const fixturePath = '/wp-content/uploads/asciiplayer-fixtures/hello.cast';
|
||||
|
||||
async function openEditor(page) {
|
||||
await page.goto('/wp-login.php');
|
||||
await page.locator('#user_login').fill(process.env.WP_USERNAME || 'admin');
|
||||
await page.locator('#user_pass').fill(process.env.WP_PASSWORD || 'password');
|
||||
await page.locator('#wp-submit').click();
|
||||
await expect(page).toHaveURL(/\/wp-admin\//);
|
||||
await page.goto('/wp-admin/post-new.php');
|
||||
await page.waitForFunction((name) => Boolean(
|
||||
window.wp?.blocks?.getBlockType(name) &&
|
||||
window.wp?.data?.select('core/editor')?.getCurrentPostId()
|
||||
), blockName);
|
||||
await page.evaluate(() => {
|
||||
for (const scope of ['core/edit-post', 'core/editor']) {
|
||||
window.wp.data.dispatch('core/preferences').set(scope, 'welcomeGuide', false);
|
||||
}
|
||||
});
|
||||
await expect(page.locator('iframe[name="editor-canvas"]')).toBeVisible();
|
||||
}
|
||||
|
||||
async function insertPlayer(page, attributes = {}) {
|
||||
const id = await page.evaluate(({ name, attrs }) => {
|
||||
const block = window.wp.blocks.createBlock(name, attrs);
|
||||
window.wp.data.dispatch('core/block-editor').insertBlocks(block);
|
||||
window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId);
|
||||
return block.clientId;
|
||||
}, { name: blockName, attrs: attributes });
|
||||
return { id, block: page.frameLocator('iframe[name="editor-canvas"]').locator(`[data-block="${id}"]`) };
|
||||
}
|
||||
|
||||
async function attributes(page, id) {
|
||||
return page.evaluate((clientId) => window.wp.data.select('core/block-editor').getBlockAttributes(clientId), id);
|
||||
}
|
||||
|
||||
async function readyPreview(block) {
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
|
||||
await expect(block.locator('.ap-wrapper')).toHaveCount(1);
|
||||
}
|
||||
|
||||
async function openInspectorPanel(page, name, control) {
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
|
||||
if (!await control.isVisible()) {
|
||||
await page.locator('.components-panel__body-toggle').filter({ hasText: new RegExp(`^${name}$`) }).click();
|
||||
}
|
||||
await expect(control).toBeVisible();
|
||||
}
|
||||
|
||||
async function publish(page, title) {
|
||||
return page.evaluate(async (postTitle) => {
|
||||
const editor = window.wp.data.dispatch('core/editor');
|
||||
editor.editPost({ title: postTitle, status: 'publish' });
|
||||
await editor.savePost();
|
||||
const state = window.wp.data.select('core/editor');
|
||||
if (state.didPostSaveRequestFail()) throw new Error('WordPress could not save the test post.');
|
||||
return { id: state.getCurrentPostId(), url: state.getPermalink() };
|
||||
}, title);
|
||||
}
|
||||
|
||||
async function grid(container) {
|
||||
// These are the live VT dimensions rendered by bundled asciinema-player,
|
||||
// not the WordPress attributes or an inferred CSS aspect ratio.
|
||||
return container.locator('.ap-term').evaluate((terminal) => ({
|
||||
cols: Number(terminal.style.getPropertyValue('--term-cols')),
|
||||
rows: Number(terminal.style.getPropertyValue('--term-rows')),
|
||||
}));
|
||||
}
|
||||
|
||||
async function expectGrid(container, cols, rows) {
|
||||
await expect(container.locator('.ap-term')).toBeVisible();
|
||||
await expect.poll(() => grid(container)).toEqual({ cols, rows });
|
||||
await expect(container.locator('.ap-term-text > .ap-line')).toHaveCount(rows);
|
||||
}
|
||||
|
||||
async function figureMetrics(figure) {
|
||||
return figure.evaluate((element) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
const parent = element.parentElement;
|
||||
const outer = parent.getBoundingClientRect();
|
||||
const style = getComputedStyle(parent);
|
||||
const left = outer.left + parseFloat(style.borderLeftWidth) + parseFloat(style.paddingLeft);
|
||||
const right = outer.right - parseFloat(style.borderRightWidth) - parseFloat(style.paddingRight);
|
||||
return {
|
||||
width: rect.width,
|
||||
available: right - left,
|
||||
leftGap: rect.left - left,
|
||||
rightGap: right - rect.right,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function expectAlignment(figure, alignment, fraction = 0.5) {
|
||||
await expect.poll(async () => {
|
||||
const dimensions = await figureMetrics(figure);
|
||||
return Math.abs(dimensions.width - dimensions.available * fraction);
|
||||
}).toBeLessThan(3);
|
||||
await expect.poll(async () => {
|
||||
const { leftGap, rightGap } = await figureMetrics(figure);
|
||||
return alignment === 'center' ? Math.abs(leftGap - rightGap) : Math.abs(alignment === 'left' ? leftGap : rightGap);
|
||||
}).toBeLessThan(3);
|
||||
}
|
||||
|
||||
async function screenshot(page, testInfo, name) {
|
||||
const path = testInfo.outputPath(`${name}.png`);
|
||||
await page.screenshot({ path, fullPage: true });
|
||||
await testInfo.attach(name, { path, contentType: 'image/png' });
|
||||
}
|
||||
|
||||
test('display width, alignment and caption survive editor save/reload without changing the recording grid', async ({ page }, testInfo) => {
|
||||
await openEditor(page);
|
||||
const source = new URL(fixturePath, page.url()).href;
|
||||
const { id, block } = await insertPlayer(page, { source, controls: 'always' });
|
||||
await readyPreview(block);
|
||||
await expectGrid(block, 64, 12);
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
const figure = block.locator('.asciiplayer-figure');
|
||||
const width = page.getByRole('combobox', { name: 'Player width', exact: true });
|
||||
await openInspectorPanel(page, 'Display', width);
|
||||
// Keep a marker on the actual terminal: display-only changes must neither
|
||||
// reconstruct it nor alter rows/columns, so playback position is preserved.
|
||||
await block.locator('.ap-term').evaluate((element) => { element.dataset.layoutIdentity = 'unchanged'; });
|
||||
await width.selectOption('50%');
|
||||
const alignment = page.getByRole('combobox', { name: 'Display alignment', exact: true });
|
||||
for (const value of ['left', 'center', 'right']) {
|
||||
await alignment.selectOption(value);
|
||||
await expectAlignment(figure, value);
|
||||
await expectGrid(block, 64, 12);
|
||||
await expect(block.locator('.ap-term')).toHaveAttribute('data-layout-identity', 'unchanged');
|
||||
}
|
||||
await width.selectOption('custom');
|
||||
const customWidth = page.getByRole('textbox', { name: 'Custom width', exact: true });
|
||||
await customWidth.fill('240px');
|
||||
await customWidth.press('Tab');
|
||||
await expect.poll(async () => Math.abs((await figure.boundingBox()).width - 240)).toBeLessThan(2);
|
||||
await customWidth.fill('calc(100% - 20px)');
|
||||
await customWidth.press('Tab');
|
||||
await expect(customWidth).toHaveAttribute('aria-invalid', 'true');
|
||||
expect((await attributes(page, id)).width).toBe('240px');
|
||||
await width.selectOption('50%');
|
||||
const caption = figure.locator('figcaption[contenteditable="true"]');
|
||||
await caption.fill('Example terminal session');
|
||||
await caption.press('Tab');
|
||||
await expect.poll(async () => (await attributes(page, id)).caption).toContain('Example terminal session');
|
||||
const saved = await publish(page, 'Player display layout regression');
|
||||
await screenshot(page, testInfo, 'layout-editor-desktop');
|
||||
await page.reload();
|
||||
await page.waitForFunction((name) => window.wp?.data?.select('core/block-editor')?.getBlocks().some((block) => block.name === name), blockName);
|
||||
const reloaded = await page.evaluate((name) => window.wp.data.select('core/block-editor').getBlocks().find((block) => block.name === name), blockName);
|
||||
expect(reloaded.attributes).toMatchObject({ source, width: '50%', displayAlign: 'right', caption: 'Example terminal session' });
|
||||
expect(reloaded.attributes.cols).toBeUndefined();
|
||||
expect(reloaded.attributes.rows).toBeUndefined();
|
||||
const reloadedBlock = page.frameLocator('iframe[name="editor-canvas"]').locator(`[data-block="${reloaded.clientId}"]`);
|
||||
await readyPreview(reloadedBlock);
|
||||
await expectGrid(reloadedBlock, 64, 12);
|
||||
await expectAlignment(reloadedBlock.locator('.asciiplayer-figure'), 'right');
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await expectGrid(reloadedBlock, 64, 12);
|
||||
const editorCanvasWidth = await page.locator('iframe[name="editor-canvas"]').evaluate((element) => element.clientWidth);
|
||||
await expect.poll(async () => (await reloadedBlock.locator('.ap-wrapper').boundingBox()).width).toBeLessThanOrEqual(editorCanvasWidth);
|
||||
await screenshot(page, testInfo, 'layout-editor-mobile');
|
||||
await page.setViewportSize({ width: 1280, height: 720 });
|
||||
await page.goto(saved.url);
|
||||
const frontend = page.locator('.asciiplayer-container');
|
||||
const frontendFigure = page.locator('.asciiplayer-figure');
|
||||
await expectGrid(frontend, 64, 12);
|
||||
await expect(frontendFigure.locator('figcaption')).toHaveText('Example terminal session');
|
||||
await expectAlignment(frontendFigure, 'right');
|
||||
const options = JSON.parse(await frontend.getAttribute('data-ap-options'));
|
||||
expect(options).not.toHaveProperty('cols');
|
||||
expect(options).not.toHaveProperty('rows');
|
||||
expect(options).not.toHaveProperty('width');
|
||||
expect(options).not.toHaveProperty('caption');
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await expectGrid(frontend, 64, 12);
|
||||
await expectAlignment(frontendFigure, 'right');
|
||||
const bounds = await frontendFigure.boundingBox();
|
||||
expect(bounds.x).toBeGreaterThanOrEqual(0);
|
||||
expect(bounds.x + bounds.width).toBeLessThanOrEqual(391);
|
||||
await screenshot(page, testInfo, 'layout-frontend-mobile');
|
||||
});
|
||||
|
||||
test('toolbar terminal dimensions are discoverable, preserve focus and synchronize with the collapsed sidebar', async ({ page }, testInfo) => {
|
||||
await openEditor(page);
|
||||
const source = new URL(fixturePath, page.url()).href;
|
||||
const { id, block } = await insertPlayer(page, { source });
|
||||
await readyPreview(block);
|
||||
await expect(block.getByRole('spinbutton', { name: 'Columns', exact: true })).toHaveCount(0);
|
||||
await expect(block.getByRole('spinbutton', { name: 'Rows', exact: true })).toHaveCount(0);
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').closeGeneralSidebar());
|
||||
// Core hides contextual tools while typing; mirror its own test utility.
|
||||
await page.mouse.move(50, 50);
|
||||
await page.mouse.move(75, 75);
|
||||
await page.mouse.move(100, 100);
|
||||
const toolbar = page.getByRole('toolbar', { name: 'Block tools', exact: true });
|
||||
const toggle = toolbar.getByRole('button', { name: 'Terminal size', exact: true });
|
||||
await expect(toggle).toBeVisible();
|
||||
await block.scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(300); // Let the sidebar-close layout transition settle.
|
||||
const before = await block.boundingBox();
|
||||
await toggle.click();
|
||||
const popover = page.getByRole('dialog', { name: 'Terminal size', exact: true });
|
||||
const columns = popover.getByRole('spinbutton', { name: 'Columns', exact: true });
|
||||
const rows = popover.getByRole('spinbutton', { name: 'Rows', exact: true });
|
||||
await expect(popover).toBeVisible();
|
||||
await expect(columns).toBeVisible();
|
||||
await expect(rows).toBeVisible();
|
||||
await expect(columns).toBeFocused();
|
||||
await expect(columns).toHaveValue('');
|
||||
await expect(rows).toHaveValue('');
|
||||
await expect(columns).toHaveAttribute('placeholder', '64');
|
||||
await expect(rows).toHaveAttribute('placeholder', '12');
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
const after = await block.boundingBox();
|
||||
expect(Math.abs(after.width - before.width)).toBeLessThan(2);
|
||||
expect(Math.abs(after.height - before.height)).toBeLessThan(2);
|
||||
await screenshot(page, testInfo, 'terminal-size-toolbar-popover');
|
||||
// Invalid overrides are cleared rather than changing the recording grid.
|
||||
await columns.fill('0');
|
||||
await columns.press('Tab');
|
||||
await rows.fill('1001');
|
||||
await rows.press('Tab');
|
||||
await expect(columns).toHaveValue('');
|
||||
await expect(rows).toHaveValue('');
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
await expectGrid(block, 64, 12);
|
||||
await columns.fill('88');
|
||||
await columns.press('Tab');
|
||||
await rows.fill('16');
|
||||
await rows.press('Tab');
|
||||
await expectGrid(block, 88, 16);
|
||||
await rows.press('Escape');
|
||||
await expect(popover).toBeHidden();
|
||||
await expect(toggle).toBeFocused();
|
||||
await toggle.click();
|
||||
await expect(columns).toHaveValue('88');
|
||||
await expect(rows).toHaveValue('16');
|
||||
// A manual override must not become the displayed recording metadata.
|
||||
await expect(columns).toHaveAttribute('placeholder', '64');
|
||||
await expect(rows).toHaveAttribute('placeholder', '12');
|
||||
await columns.fill('');
|
||||
await columns.press('Tab');
|
||||
await expectGrid(block, 64, 16);
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
await columns.fill('88');
|
||||
await columns.press('Tab');
|
||||
await expectGrid(block, 88, 16);
|
||||
await popover.getByRole('button', { name: 'Use recording size', exact: true }).click();
|
||||
await expectGrid(block, 64, 12);
|
||||
await expect(columns).toHaveValue('');
|
||||
await expect(rows).toHaveValue('');
|
||||
await columns.fill('88');
|
||||
await rows.fill('16');
|
||||
await rows.press('Tab');
|
||||
await expectGrid(block, 88, 16);
|
||||
await popover.getByRole('button', { name: 'Close', exact: true }).click();
|
||||
await expect(popover).toBeHidden();
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
|
||||
const panelToggle = page.locator('.components-panel__body-toggle').filter({ hasText: /^Terminal size$/ });
|
||||
await expect(panelToggle).toHaveAttribute('aria-expanded', 'false');
|
||||
await panelToggle.click();
|
||||
const sidebarColumns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
|
||||
const sidebarRows = page.getByRole('spinbutton', { name: 'Rows', exact: true });
|
||||
await expect(sidebarColumns).toHaveValue('88');
|
||||
await expect(sidebarRows).toHaveValue('16');
|
||||
await expect(sidebarColumns).toHaveAttribute('placeholder', '64');
|
||||
await expect(sidebarRows).toHaveAttribute('placeholder', '12');
|
||||
await sidebarRows.fill('');
|
||||
await sidebarRows.press('Tab');
|
||||
await expectGrid(block, 88, 12);
|
||||
await page.getByRole('button', { name: 'Use recording size', exact: true }).click();
|
||||
await expectGrid(block, 64, 12);
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
await toggle.click();
|
||||
await expect(columns).toHaveValue('');
|
||||
await expect(rows).toHaveValue('');
|
||||
await expect(columns).toHaveAttribute('placeholder', '64');
|
||||
await expect(rows).toHaveAttribute('placeholder', '12');
|
||||
await popover.getByRole('button', { name: 'Close', exact: true }).click();
|
||||
const saved = await publish(page, 'Reset terminal dimensions regression');
|
||||
await page.goto(saved.url);
|
||||
const frontend = page.locator('.asciiplayer-container');
|
||||
await expectGrid(frontend, 64, 12);
|
||||
const options = JSON.parse(await frontend.getAttribute('data-ap-options'));
|
||||
expect(options).not.toHaveProperty('cols');
|
||||
expect(options).not.toHaveProperty('rows');
|
||||
});
|
||||
|
||||
test('recorded resize events remain authoritative except on explicitly overridden axes', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const source = new URL('/wp-content/uploads/asciiplayer-fixtures/resize.cast', page.url()).href;
|
||||
const cases = [
|
||||
{ overrides: {}, cols: 96, rows: 18 },
|
||||
{ overrides: { cols: 80 }, cols: 80, rows: 18 },
|
||||
{ overrides: { rows: 24 }, cols: 96, rows: 24 },
|
||||
{ overrides: { cols: 80, rows: 24 }, cols: 80, rows: 24 },
|
||||
];
|
||||
for (const entry of cases) {
|
||||
const { id, block } = await insertPlayer(page, { source, startAt: 2, ...entry.overrides });
|
||||
await readyPreview(block);
|
||||
await expectGrid(block, entry.overrides.cols ?? 64, entry.overrides.rows ?? 12);
|
||||
await block.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expectGrid(block, entry.cols, entry.rows);
|
||||
const columns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
|
||||
const rows = page.getByRole('spinbutton', { name: 'Rows', exact: true });
|
||||
await openInspectorPanel(page, 'Terminal size', columns);
|
||||
// Placeholders describe the cast header, even after its resize event.
|
||||
await expect(columns).toHaveAttribute('placeholder', '64');
|
||||
await expect(rows).toHaveAttribute('placeholder', '12');
|
||||
expect((await attributes(page, id)).cols).toBe(entry.overrides.cols);
|
||||
expect((await attributes(page, id)).rows).toBe(entry.overrides.rows);
|
||||
}
|
||||
const saved = await publish(page, 'Recording resize and explicit axes regression');
|
||||
await page.goto(saved.url);
|
||||
const players = page.locator('.asciiplayer-container');
|
||||
await expect(players).toHaveCount(cases.length);
|
||||
for (const [index, entry] of cases.entries()) {
|
||||
await expectGrid(players.nth(index), entry.overrides.cols ?? 64, entry.overrides.rows ?? 12);
|
||||
await players.nth(index).locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expectGrid(players.nth(index), entry.cols, entry.rows);
|
||||
await expect(players.nth(index).locator('.ap-term-text')).toContainText('Resized recording grid');
|
||||
}
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
for (const [index, entry] of cases.entries()) await expectGrid(players.nth(index), entry.cols, entry.rows);
|
||||
});
|
||||
|
||||
test('published figures preserve all alignments, safe captions and terminal typography under theme CSS', async ({ page }, testInfo) => {
|
||||
await openEditor(page);
|
||||
const source = new URL(fixturePath, page.url()).href;
|
||||
const caption = 'Safe caption<br>with a second line & literal text';
|
||||
for (const displayAlign of ['left', 'center', 'right']) {
|
||||
await insertPlayer(page, { source, width: '50%', displayAlign, caption });
|
||||
}
|
||||
// Raw block attributes can come from REST/imported post content, bypassing
|
||||
// RichText's editor filtering. The server must sanitize them independently.
|
||||
await insertPlayer(page, {
|
||||
source,
|
||||
caption: '<script>window.__captionXss = true</script><img src="x" onerror="window.__captionXss = true"><a href="javascript:window.__captionXss=true">unsafe link</a><strong>Still safe</strong>',
|
||||
});
|
||||
const saved = await publish(page, 'Frontend figure and caption sanitization regression');
|
||||
await page.addInitScript((content) => {
|
||||
const install = () => {
|
||||
if (!document.documentElement) return false;
|
||||
const stylesheet = document.createElement('style');
|
||||
stylesheet.textContent = content;
|
||||
document.documentElement.appendChild(stylesheet);
|
||||
return true;
|
||||
};
|
||||
if (!install()) {
|
||||
const observer = new MutationObserver(() => { if (install()) observer.disconnect(); });
|
||||
observer.observe(document, { childList: true, subtree: true });
|
||||
}
|
||||
}, `
|
||||
body { letter-spacing: 1.5px; line-height: 2; text-align: center; }
|
||||
figure { margin: 2em 40px; }
|
||||
pre { padding: 24px !important; margin: 24px !important; font-family: serif !important; font-size: 24px !important; line-height: 2 !important; white-space: pre-wrap !important; border: 2px solid red !important; box-shadow: 0 0 0 3px red !important; }
|
||||
pre span { font-family: serif !important; font-size: 24px !important; line-height: 2 !important; letter-spacing: 2px !important; }
|
||||
button { border: 2px solid red !important; box-shadow: 0 0 0 3px red !important; }
|
||||
`);
|
||||
await page.goto(saved.url);
|
||||
const figures = page.locator('.asciiplayer-figure');
|
||||
const desktopFontSizes = [];
|
||||
await expect(figures).toHaveCount(4);
|
||||
for (const [index, displayAlign] of ['left', 'center', 'right'].entries()) {
|
||||
const figure = figures.nth(index);
|
||||
await expectAlignment(figure, displayAlign);
|
||||
await expectGrid(figure, 64, 12);
|
||||
await figure.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expect(figure.locator('.ap-term-text')).toContainText('Hello from wp-asciiplayer');
|
||||
await expect(figure.locator('figcaption')).toHaveText('Safe captionwith a second line & literal text');
|
||||
await expect(figure.locator('figcaption br')).toHaveCount(1);
|
||||
const typography = await figure.locator('.ap-term-text').evaluate((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
const parent = getComputedStyle(element.parentElement);
|
||||
return {
|
||||
padding: style.padding,
|
||||
margin: style.margin,
|
||||
whiteSpace: style.whiteSpace,
|
||||
borderWidth: style.borderWidth,
|
||||
boxShadow: style.boxShadow,
|
||||
familyMatches: style.fontFamily === parent.fontFamily,
|
||||
fontSizeMatches: style.fontSize === parent.fontSize,
|
||||
textAlign: style.textAlign,
|
||||
};
|
||||
});
|
||||
expect(typography).toEqual({ padding: '0px', margin: '0px', whiteSpace: 'pre', borderWidth: '0px', boxShadow: 'none', familyMatches: true, fontSizeMatches: true, textAlign: 'left' });
|
||||
desktopFontSizes.push(await figure.locator('.ap-term').evaluate((element) => parseFloat(getComputedStyle(element).fontSize)));
|
||||
const rowTypography = await figure.locator('.ap-term-text .ap-line').first().evaluate((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
const terminal = getComputedStyle(element.closest('.ap-term'));
|
||||
return { fontSizeMatches: style.fontSize === terminal.fontSize, familyMatches: style.fontFamily === terminal.fontFamily };
|
||||
});
|
||||
expect(rowTypography).toEqual({ fontSizeMatches: true, familyMatches: true });
|
||||
const spanTypography = await figure.locator('.ap-term-text .ap-line span').first().evaluate((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
const terminal = getComputedStyle(element.closest('.ap-term'));
|
||||
return { fontSizeMatches: style.fontSize === terminal.fontSize, familyMatches: style.fontFamily === terminal.fontFamily, letterSpacing: style.letterSpacing };
|
||||
});
|
||||
expect(spanTypography).toEqual({ fontSizeMatches: true, familyMatches: true, letterSpacing: 'normal' });
|
||||
const controls = await figure.locator('.ap-control-bar button.ap-button').first().evaluate((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
return { borderWidth: style.borderWidth, boxShadow: style.boxShadow };
|
||||
});
|
||||
expect(controls).toEqual({ borderWidth: '0px', boxShadow: 'none' });
|
||||
}
|
||||
const unsafeCaption = figures.nth(3).locator('figcaption');
|
||||
await expect(unsafeCaption).toContainText('Still safe');
|
||||
await expect(unsafeCaption.locator('script, img, iframe, a, strong, [onerror], [onclick]')).toHaveCount(0);
|
||||
expect(await page.evaluate(() => window.__captionXss)).toBeUndefined();
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
for (const [index, displayAlign] of ['left', 'center', 'right'].entries()) {
|
||||
await expectAlignment(figures.nth(index), displayAlign);
|
||||
await expectGrid(figures.nth(index), 64, 12);
|
||||
await expect.poll(() => figures.nth(index).locator('.ap-term').evaluate((element) => parseFloat(getComputedStyle(element).fontSize))).toBeLessThan(desktopFontSizes[index]);
|
||||
const scaledTypography = await figures.nth(index).locator('.ap-term').evaluate((terminal) => {
|
||||
const expected = getComputedStyle(terminal);
|
||||
return [...terminal.querySelectorAll('.ap-term-text, .ap-line, .ap-line span')].every((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
return style.fontSize === expected.fontSize && style.fontFamily === expected.fontFamily;
|
||||
});
|
||||
});
|
||||
expect(scaledTypography).toBe(true);
|
||||
}
|
||||
await screenshot(page, testInfo, 'layout-theme-css-mobile');
|
||||
// Physical left/right placement must remain the same inside RTL content.
|
||||
// This covers direction inheritance at runtime; generated RTL stylesheets
|
||||
// are independently protected by the source's rtlcss ignore directive.
|
||||
await page.evaluate(() => {
|
||||
document.documentElement.dir = 'rtl';
|
||||
for (const figure of document.querySelectorAll('.asciiplayer-figure')) {
|
||||
figure.parentElement.dir = 'rtl';
|
||||
}
|
||||
});
|
||||
for (const [index, displayAlign] of ['left', 'center', 'right'].entries()) {
|
||||
await expectAlignment(figures.nth(index), displayAlign);
|
||||
await expectGrid(figures.nth(index), 64, 12);
|
||||
}
|
||||
await screenshot(page, testInfo, 'layout-theme-css-mobile-rtl');
|
||||
});
|
||||
|
||||
test('the inserter example is a local static preview and makes no recording request', async ({ page }, testInfo) => {
|
||||
await openEditor(page);
|
||||
const example = await page.evaluate((name) => window.wp.blocks.getBlockType(name).example, blockName);
|
||||
expect(example).toMatchObject({ attributes: { isExample: true } });
|
||||
const recordingRequests = [];
|
||||
page.on('request', (request) => {
|
||||
if (/\.cast(?:[?#]|$)|asciinema\.org|jsdelivr\.net/.test(request.url())) recordingRequests.push(request.url());
|
||||
});
|
||||
// A saved URL must never turn an inserter example into a network preview.
|
||||
const { block } = await insertPlayer(page, { ...example.attributes, source: new URL(fixturePath, page.url()).href });
|
||||
await expect(block.locator('.asciiplayer-example')).toContainText('Hello, terminal!');
|
||||
await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveCount(0);
|
||||
await expect(block.locator('.ap-wrapper')).toHaveCount(0);
|
||||
await page.waitForTimeout(750); // Exceed the automatic URL debounce window.
|
||||
await screenshot(page, testInfo, 'static-inserter-example');
|
||||
expect(recordingRequests).toEqual([]);
|
||||
});
|
||||
|
||||
test('outer editor blocks respect WordPress content gutters and core wide/full boundaries', async ({ page }, testInfo) => {
|
||||
await openEditor(page);
|
||||
const source = new URL(fixturePath, page.url()).href;
|
||||
const cases = await page.evaluate(({ name, sourceUrl }) => {
|
||||
const { createBlock, getBlockType } = window.wp.blocks;
|
||||
const paragraph = (text) => createBlock('core/paragraph', { content: text });
|
||||
const before = paragraph('Paragraph before the player: the standard editor content boundary.');
|
||||
const player = createBlock(name, { source: sourceUrl, width: '100%' });
|
||||
const after = paragraph('Paragraph after the player: the same standard content boundary.');
|
||||
const blocks = [before, player, after];
|
||||
const entries = [{ alignment: 'default', playerId: player.clientId, referenceIds: [before.clientId, after.clientId] }];
|
||||
const supportsAlignment = (block, align) => {
|
||||
const support = getBlockType(block)?.supports?.align;
|
||||
return support === true || Array.isArray(support) && support.includes(align);
|
||||
};
|
||||
for (const align of ['wide', 'full']) {
|
||||
if (!supportsAlignment(name, align) || !supportsAlignment('core/group', align)) continue;
|
||||
// Paragraphs do not support wide/full. A core Group supplies the
|
||||
// native aligned boundary for its paragraph without custom sizing.
|
||||
const reference = createBlock('core/group', { align, layout: { type: 'default' } }, [
|
||||
paragraph(`${align} core Group paragraph: native WordPress alignment reference.`),
|
||||
]);
|
||||
const alignedPlayer = createBlock(name, { source: sourceUrl, width: '100%', align });
|
||||
blocks.push(reference, alignedPlayer);
|
||||
entries.push({ alignment: align, playerId: alignedPlayer.clientId, referenceIds: [reference.clientId] });
|
||||
}
|
||||
window.wp.data.dispatch('core/block-editor').insertBlocks(blocks);
|
||||
window.wp.data.dispatch('core/block-editor').selectBlock(player.clientId);
|
||||
return entries;
|
||||
}, { name: blockName, sourceUrl: source });
|
||||
const canvas = page.frameLocator('iframe[name="editor-canvas"]');
|
||||
for (const entry of cases) await readyPreview(canvas.locator(`[data-block="${entry.playerId}"]`));
|
||||
for (const viewport of [{ width: 1280, height: 900 }, { width: 390, height: 844 }]) {
|
||||
await page.setViewportSize(viewport);
|
||||
for (const entry of cases) {
|
||||
const block = canvas.locator(`[data-block="${entry.playerId}"]`);
|
||||
const measure = () => block.evaluate((element, referenceIds) => {
|
||||
const document = element.ownerDocument;
|
||||
const horizontal = (node) => {
|
||||
const box = node.getBoundingClientRect();
|
||||
return { left: box.left, right: box.right, width: box.width };
|
||||
};
|
||||
const outer = horizontal(element);
|
||||
const references = referenceIds.map((id) => horizontal(document.querySelector(`[data-block="${id}"]`)));
|
||||
const root = element.closest('.is-root-container');
|
||||
if (!root) throw new Error('WordPress editor content root was not found.');
|
||||
const rootBounds = horizontal(root);
|
||||
const rootStyle = getComputedStyle(root);
|
||||
const contentLeft = rootBounds.left + parseFloat(rootStyle.borderLeftWidth) + parseFloat(rootStyle.paddingLeft);
|
||||
const contentRight = rootBounds.right - parseFloat(rootStyle.borderRightWidth) - parseFloat(rootStyle.paddingRight);
|
||||
return {
|
||||
outer, references, contentLeft, contentRight,
|
||||
viewportWidth: document.documentElement.clientWidth,
|
||||
leftError: Math.max(...references.map((reference) => Math.abs(outer.left - reference.left))),
|
||||
rightError: Math.max(...references.map((reference) => Math.abs(outer.right - reference.right))),
|
||||
player: horizontal(element.querySelector('.ap-wrapper')),
|
||||
boxSizing: getComputedStyle(element).boxSizing,
|
||||
};
|
||||
}, entry.referenceIds);
|
||||
// Compare the OUTER border box to independently rendered native
|
||||
// blocks. Inner-figure/parent checks alone miss a 34px padding leak.
|
||||
await expect.poll(async () => (await measure()).leftError).toBeLessThan(2);
|
||||
await expect.poll(async () => (await measure()).rightError).toBeLessThan(2);
|
||||
const geometry = await measure();
|
||||
expect(geometry.boxSizing).toBe('border-box');
|
||||
expect(geometry.outer.left).toBeGreaterThanOrEqual(-2);
|
||||
expect(geometry.outer.right).toBeLessThanOrEqual(geometry.viewportWidth + 2);
|
||||
if (entry.alignment === 'default') {
|
||||
expect(geometry.outer.left).toBeGreaterThanOrEqual(geometry.contentLeft - 2);
|
||||
expect(geometry.outer.right).toBeLessThanOrEqual(geometry.contentRight + 2);
|
||||
expect(geometry.outer.left).toBeGreaterThan(0);
|
||||
expect(geometry.outer.right).toBeLessThan(geometry.viewportWidth);
|
||||
}
|
||||
expect(geometry.player.left).toBeGreaterThanOrEqual(geometry.outer.left);
|
||||
expect(geometry.player.right).toBeLessThanOrEqual(geometry.outer.right + 1);
|
||||
await expectGrid(block, 64, 12);
|
||||
await testInfo.attach(`editor-gutters-${entry.alignment}-${viewport.width}`, {
|
||||
body: Buffer.from(JSON.stringify(geometry, null, 2)), contentType: 'application/json',
|
||||
});
|
||||
}
|
||||
await canvas.locator(`[data-block="${cases[0].playerId}"]`).scrollIntoViewIfNeeded();
|
||||
await screenshot(page, testInfo, `editor-content-gutters-${viewport.width}`);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,290 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
|
||||
const blockName = 'lamgc/asciiplayer';
|
||||
const fixtures = '/wp-content/uploads/asciiplayer-fixtures';
|
||||
|
||||
async function openEditor(page) {
|
||||
await page.goto('/wp-login.php');
|
||||
await page.locator('#user_login').fill(process.env.WP_USERNAME || 'admin');
|
||||
await page.locator('#user_pass').fill(process.env.WP_PASSWORD || 'password');
|
||||
await page.locator('#wp-submit').click();
|
||||
await expect(page).toHaveURL(/\/wp-admin\//);
|
||||
await page.goto('/wp-admin/post-new.php');
|
||||
await page.waitForFunction((name) => Boolean(
|
||||
window.wp?.blocks?.getBlockType(name) &&
|
||||
window.wp?.data?.select('core/editor')?.getCurrentPostId()
|
||||
), blockName);
|
||||
await page.evaluate(() => {
|
||||
for (const scope of ['core/edit-post', 'core/editor']) {
|
||||
window.wp.data.dispatch('core/preferences').set(scope, 'welcomeGuide', false);
|
||||
}
|
||||
});
|
||||
await expect(page.locator('iframe[name="editor-canvas"]')).toBeVisible();
|
||||
}
|
||||
|
||||
function playerBlock(page, id) {
|
||||
return page.frameLocator('iframe[name="editor-canvas"]').locator(`[data-block="${id}"]`);
|
||||
}
|
||||
|
||||
async function insertPlayer(page, attributes = {}) {
|
||||
const id = await page.evaluate(({ name, attrs }) => {
|
||||
const block = window.wp.blocks.createBlock(name, attrs);
|
||||
window.wp.data.dispatch('core/block-editor').insertBlocks(block);
|
||||
window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId);
|
||||
return block.clientId;
|
||||
}, { name: blockName, attrs: attributes });
|
||||
return { id, block: playerBlock(page, id) };
|
||||
}
|
||||
|
||||
async function attributes(page, id) {
|
||||
return page.evaluate((clientId) => window.wp.data.select('core/block-editor').getBlockAttributes(clientId), id);
|
||||
}
|
||||
|
||||
async function readyPreview(block) {
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
|
||||
await expect(block.locator('.ap-wrapper')).toHaveCount(1);
|
||||
await expect(block.locator('.ap-term')).toBeVisible();
|
||||
}
|
||||
|
||||
async function expectGrid(block, cols, rows) {
|
||||
await expect.poll(() => block.locator('.ap-term').evaluate((terminal) => ({
|
||||
cols: Number(terminal.style.getPropertyValue('--term-cols')),
|
||||
rows: Number(terminal.style.getPropertyValue('--term-rows')),
|
||||
}))).toEqual({ cols, rows });
|
||||
}
|
||||
|
||||
async function openDimensions(page) {
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
|
||||
const columns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
|
||||
const rows = page.getByRole('spinbutton', { name: 'Rows', exact: true });
|
||||
if (!await columns.isVisible()) {
|
||||
await page.locator('.components-panel__body-toggle').filter({ hasText: /^Terminal size$/ }).click();
|
||||
}
|
||||
await expect(columns).toBeVisible();
|
||||
return { columns, rows };
|
||||
}
|
||||
|
||||
async function expectNativeSize(controls, cols, rows) {
|
||||
await expect(controls.columns).toHaveAttribute('placeholder', cols === undefined ? 'From recording' : String(cols));
|
||||
await expect(controls.rows).toHaveAttribute('placeholder', rows === undefined ? 'From recording' : String(rows));
|
||||
}
|
||||
|
||||
async function openMedia(page, block) {
|
||||
await block.getByRole('button', { name: 'Choose recording', exact: true }).click();
|
||||
const dialog = page.getByRole('dialog', { name: 'Choose an Asciicast recording', exact: true });
|
||||
await expect(dialog).toBeVisible();
|
||||
return dialog;
|
||||
}
|
||||
|
||||
async function uploadRecording(page, dialog, name, buffer) {
|
||||
await dialog.getByRole('tab', { name: 'Upload files', exact: true }).click();
|
||||
// Native WP media uses Plupload. Its file input is intentionally hidden and
|
||||
// may live outside the modal; setInputFiles exercises the actual uploader.
|
||||
const input = page.locator('.moxie-shim input[type="file"]').last();
|
||||
await expect(input).toBeAttached();
|
||||
const response = page.waitForResponse((result) =>
|
||||
/\/wp-admin\/async-upload\.php(?:\?|$)/.test(result.url()) && result.request().method() === 'POST'
|
||||
);
|
||||
await input.setInputFiles({ name, mimeType: 'application/x-asciicast', buffer });
|
||||
return (await response).json();
|
||||
}
|
||||
|
||||
async function selectAttachment(dialog, id) {
|
||||
await dialog.getByRole('tab', { name: 'Media Library', exact: true }).click();
|
||||
const attachment = dialog.locator(`.attachment[data-id="${id}"]`);
|
||||
await expect(attachment).toBeVisible();
|
||||
// Newly uploaded files are already selected; clicking them again deselects.
|
||||
if (!await attachment.evaluate((element) => element.classList.contains('selected'))) await attachment.click();
|
||||
const confirm = dialog.locator('.media-button-select');
|
||||
await expect(confirm).toBeEnabled();
|
||||
await confirm.click();
|
||||
await expect(dialog).toBeHidden();
|
||||
}
|
||||
|
||||
test('recording metadata follows URL changes, clears while loading or invalid, and never replaces explicit dimensions', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const original = new URL(`${fixtures}/hello.cast`, page.url()).href;
|
||||
const replacement = new URL(`${fixtures}/replacement.cast?metadata=delayed`, page.url()).href;
|
||||
const unavailable = new URL(`${fixtures}/missing.cast?metadata=error`, page.url()).href;
|
||||
const malformed = new URL(`${fixtures}/malformed.cast?metadata=valid-header`, page.url()).href;
|
||||
const recording = await readFile(new URL('../fixtures/replacement.cast', import.meta.url));
|
||||
let release;
|
||||
let requested = false;
|
||||
const pending = new Promise((resolve) => { release = resolve; });
|
||||
await page.route(replacement, async (route) => {
|
||||
requested = true;
|
||||
await pending;
|
||||
await route.fulfill({ contentType: 'text/plain', body: recording }).catch(() => {});
|
||||
});
|
||||
await page.route(unavailable, (route) => route.fulfill({ status: 503, contentType: 'text/plain', body: 'Unavailable' }));
|
||||
await page.route(malformed, (route) => route.fulfill({
|
||||
contentType: 'text/plain', body: '{"version":2,"width":101,"height":31}\n[invalid event]\n',
|
||||
}));
|
||||
try {
|
||||
const { id, block } = await insertPlayer(page, { source: original });
|
||||
await readyPreview(block);
|
||||
const dimensions = await openDimensions(page);
|
||||
await expectNativeSize(dimensions, 64, 12);
|
||||
await expect(dimensions.columns).toHaveValue('');
|
||||
await expect(dimensions.rows).toHaveValue('');
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
await dimensions.columns.fill('80');
|
||||
await dimensions.rows.fill('20');
|
||||
await dimensions.rows.press('Tab');
|
||||
await readyPreview(block);
|
||||
await expectGrid(block, 80, 20);
|
||||
await expectNativeSize(dimensions, 64, 12);
|
||||
|
||||
const input = block.getByRole('textbox', { name: 'Recording URL', exact: true });
|
||||
await input.fill(replacement);
|
||||
await expectNativeSize(dimensions);
|
||||
await expect.poll(() => requested).toBe(true);
|
||||
await expectNativeSize(dimensions);
|
||||
await expect(dimensions.columns).toHaveValue('80');
|
||||
await expect(dimensions.rows).toHaveValue('20');
|
||||
release();
|
||||
await readyPreview(block);
|
||||
await expectNativeSize(dimensions, 100, 30);
|
||||
await expectGrid(block, 80, 20);
|
||||
expect(await attributes(page, id)).toMatchObject({ source: replacement, cols: 80, rows: 20 });
|
||||
|
||||
await input.fill('javascript:alert(1)');
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveCount(0);
|
||||
await expectNativeSize(dimensions);
|
||||
// Invalid drafts do not overwrite the last valid saved URL or overrides.
|
||||
expect(await attributes(page, id)).toMatchObject({ source: replacement, cols: 80, rows: 20 });
|
||||
await input.fill(original);
|
||||
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
|
||||
await readyPreview(block);
|
||||
await expectNativeSize(dimensions, 64, 12);
|
||||
for (const failingSource of [unavailable, malformed]) {
|
||||
await input.fill(failingSource);
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'error');
|
||||
// Even a readable header must be discarded if the player fails.
|
||||
await expectNativeSize(dimensions);
|
||||
expect(await attributes(page, id)).toMatchObject({ source: failingSource, cols: 80, rows: 20 });
|
||||
}
|
||||
await input.fill('');
|
||||
await expect.poll(async () => (await attributes(page, id)).source).toBe('');
|
||||
await expectNativeSize(dimensions);
|
||||
expect(await attributes(page, id)).toMatchObject({ cols: 80, rows: 20 });
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
});
|
||||
|
||||
test('pretty v1 and commented v3 recordings play with native header dimensions', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
// Fixtures follow the official formats, including v1's multiline JSON and
|
||||
// v3's comments after its single-line header and relative event timestamps:
|
||||
// https://docs.asciinema.org/manual/asciicast/v1/
|
||||
// https://docs.asciinema.org/manual/asciicast/v3/
|
||||
const cases = [
|
||||
{ filename: 'v1-pretty.cast', cols: 72, rows: 18, output: 'Pretty v1 recording' },
|
||||
{ filename: 'v3-comments.cast', cols: 92, rows: 22, output: 'Commented v3 recording' },
|
||||
];
|
||||
for (const entry of cases) {
|
||||
const source = new URL(`${fixtures}/${entry.filename}`, page.url()).href;
|
||||
const { id, block } = await insertPlayer(page, { source });
|
||||
await readyPreview(block);
|
||||
await expectGrid(block, entry.cols, entry.rows);
|
||||
const dimensions = await openDimensions(page);
|
||||
await expectNativeSize(dimensions, entry.cols, entry.rows);
|
||||
await expect(dimensions.columns).toHaveValue('');
|
||||
await expect(dimensions.rows).toHaveValue('');
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
await block.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expect(block.locator('.ap-term-text')).toContainText(entry.output);
|
||||
}
|
||||
});
|
||||
|
||||
test('native Media Library uploads, selects and replaces a cast while cancel leaves the current recording intact', async ({ page }, testInfo) => {
|
||||
await openEditor(page);
|
||||
const { id, block } = await insertPlayer(page);
|
||||
const firstCast = await readFile(new URL('../fixtures/hello.cast', import.meta.url));
|
||||
const secondCast = await readFile(new URL('../fixtures/replacement.cast', import.meta.url));
|
||||
const unique = `${Date.now()}-${testInfo.retry}`;
|
||||
let dialog = await openMedia(page, block);
|
||||
const first = await uploadRecording(page, dialog, `asciiplayer-original-${unique}.cast`, firstCast);
|
||||
expect(first.success, JSON.stringify(first)).toBe(true);
|
||||
expect(first.data.mime).toBe('application/x-asciicast');
|
||||
await selectAttachment(dialog, first.data.id);
|
||||
const input = block.getByRole('textbox', { name: 'Recording URL', exact: true });
|
||||
await expect(input).toHaveValue(first.data.url);
|
||||
// Selecting in the native media frame applies and autoloads, with no Apply URL click.
|
||||
await readyPreview(block);
|
||||
await expectGrid(block, 64, 12);
|
||||
let dimensions = await openDimensions(page);
|
||||
await expectNativeSize(dimensions, 64, 12);
|
||||
expect(await attributes(page, id)).toMatchObject({ source: first.data.url });
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
await block.locator('.ap-term').evaluate((element) => { element.dataset.mediaIdentity = 'original'; });
|
||||
|
||||
dialog = await openMedia(page, block);
|
||||
const second = await uploadRecording(page, dialog, `asciiplayer-replacement-${unique}.cast`, secondCast);
|
||||
expect(second.success, JSON.stringify(second)).toBe(true);
|
||||
await dialog.locator('.media-modal-close').click();
|
||||
await expect(dialog).toBeHidden();
|
||||
await expect(input).toHaveValue(first.data.url);
|
||||
expect((await attributes(page, id)).source).toBe(first.data.url);
|
||||
await expectNativeSize(dimensions, 64, 12);
|
||||
await expect(block.locator('.ap-term')).toHaveAttribute('data-media-identity', 'original');
|
||||
|
||||
// The upload above is now an existing media item. Reopen the real frame and
|
||||
// select its tile rather than changing block attributes through the store.
|
||||
dialog = await openMedia(page, block);
|
||||
await selectAttachment(dialog, second.data.id);
|
||||
await expect(input).toHaveValue(second.data.url);
|
||||
await readyPreview(block);
|
||||
await expectGrid(block, 100, 30);
|
||||
await expectNativeSize(dimensions, 100, 30);
|
||||
await block.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expect(block.locator('.ap-term-text')).toContainText('Replacement recording');
|
||||
expect((await attributes(page, id)).source).toBe(second.data.url);
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
const path = testInfo.outputPath('media-library-selected-recording.png');
|
||||
await page.screenshot({ path, fullPage: true });
|
||||
await testInfo.attach('media-library-selected-recording', { path, contentType: 'image/png' });
|
||||
await page.evaluate(async () => {
|
||||
const editor = window.wp.data.dispatch('core/editor');
|
||||
editor.editPost({ title: 'Native media recording selection regression' });
|
||||
await editor.savePost();
|
||||
if (window.wp.data.select('core/editor').didPostSaveRequestFail()) throw new Error('WordPress could not save the test post.');
|
||||
});
|
||||
await page.reload();
|
||||
await page.waitForFunction((name) => window.wp?.data?.select('core/block-editor')?.getBlocks().some((entry) => entry.name === name), blockName);
|
||||
const reloaded = await page.evaluate((name) => {
|
||||
const block = window.wp.data.select('core/block-editor').getBlocks().find((entry) => entry.name === name);
|
||||
window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId);
|
||||
return block;
|
||||
}, blockName);
|
||||
expect(reloaded.attributes.source).toBe(second.data.url);
|
||||
expect(reloaded.attributes.cols).toBeUndefined();
|
||||
expect(reloaded.attributes.rows).toBeUndefined();
|
||||
await readyPreview(playerBlock(page, reloaded.clientId));
|
||||
dimensions = await openDimensions(page);
|
||||
await expectNativeSize(dimensions, 100, 30);
|
||||
});
|
||||
|
||||
test('native Media Library rejects an invalid cast upload without applying a source', async ({ page }, testInfo) => {
|
||||
await openEditor(page);
|
||||
const { id, block } = await insertPlayer(page);
|
||||
const dialog = await openMedia(page, block);
|
||||
const malformed = await readFile(new URL('../fixtures/malformed.cast', import.meta.url));
|
||||
const result = await uploadRecording(page, dialog, `asciiplayer-invalid-${Date.now()}-${testInfo.retry}.cast`, malformed);
|
||||
expect(result.success, JSON.stringify(result)).toBe(false);
|
||||
const validationMessage = 'Upload a valid Asciicast v2/v3 JSONL or pretty-printed v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, and 1,000 columns or rows).';
|
||||
// A filesystem/permission failure is not evidence of content validation.
|
||||
expect(result.data.message).toBe(validationMessage);
|
||||
await expect(dialog).toContainText(validationMessage);
|
||||
await expect(dialog.locator('.media-button-select')).toBeDisabled();
|
||||
await dialog.locator('.media-modal-close').click();
|
||||
await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue('');
|
||||
expect((await attributes(page, id)).source).toBe('');
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveCount(0);
|
||||
});
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
{"version":2,"width":64,"height":12,"timestamp":1700000000,"env":{"TERM":"xterm-256color","SHELL":"/bin/sh"},"title":"Local integration fixture"}
|
||||
[0.0,"o","$ printf 'Hello from wp-asciiplayer'\r\n"]
|
||||
[0.1,"o","Hello from wp-asciiplayer\r\n"]
|
||||
[12.0,"o","$ "]
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
This is deliberately not an asciicast recording.
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
{"version":2,"width":100,"height":30,"timestamp":1700000000,"env":{"TERM":"xterm-256color","SHELL":"/bin/sh"},"title":"Replacement recording with a different native size"}
|
||||
[0.0,"o","$ printf 'Replacement recording'\r\n"]
|
||||
[0.1,"o","Replacement recording\r\n"]
|
||||
[12.0,"o","$ "]
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
{"version":2,"width":64,"height":12,"timestamp":1700000000,"env":{"TERM":"xterm-256color","SHELL":"/bin/sh"},"title":"Recording-controlled terminal resize"}
|
||||
[0.0,"o","$ printf 'Original 64 x 12 grid'\r\n"]
|
||||
[0.1,"o","Original 64 x 12 grid\r\n"]
|
||||
[1.0,"r","96x18"]
|
||||
[1.1,"o","\u001b[2J\u001b[HResized recording grid: 96 x 18\r\n"]
|
||||
[30.0,"o","$ "]
|
||||
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"version": 1,
|
||||
"width": 72,
|
||||
"height": 18,
|
||||
"duration": 12,
|
||||
"command": "/bin/sh",
|
||||
"title": "Pretty-printed v1 integration fixture",
|
||||
"env": {
|
||||
"TERM": "xterm-256color",
|
||||
"SHELL": "/bin/sh"
|
||||
},
|
||||
"stdout": [
|
||||
[0.0, "$ printf 'Pretty v1 recording'\r\n"],
|
||||
[0.1, "Pretty v1 recording\r\n"],
|
||||
[11.9, "$ "]
|
||||
]
|
||||
}
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
{"version":3,"term":{"cols":92,"rows":22,"type":"xterm-256color"},"timestamp":1700000000,"title":"v3 recording with comments","env":{"SHELL":"/bin/sh"}}
|
||||
# Comments are permitted after the header in asciicast v3.
|
||||
[0.0,"o","$ printf 'Commented v3 recording'\r\n"]
|
||||
[0.1,"o","Commented v3 recording\r\n"]
|
||||
# v3 timestamps are delays from the previous event.
|
||||
[11.9,"o","$ "]
|
||||
@@ -0,0 +1,45 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import gettext from 'gettext-parser';
|
||||
|
||||
const po = gettext.po.parse(fs.readFileSync('languages/wp-asciiplayer-zh_CN.po'));
|
||||
const mo = gettext.mo.parse(fs.readFileSync('languages/wp-asciiplayer-zh_CN.mo'));
|
||||
const pot = gettext.po.parse(fs.readFileSync('languages/wp-asciiplayer.pot'));
|
||||
const editor = JSON.parse(fs.readFileSync('languages/wp-asciiplayer-zh_CN-lamgc-asciiplayer-editor.json')).locale_data.messages;
|
||||
const view = JSON.parse(fs.readFileSync('languages/wp-asciiplayer-zh_CN-lamgc-asciiplayer-view.json')).locale_data.messages;
|
||||
|
||||
test('all extracted strings and gettext contexts round-trip through MO and both script catalogs', () => {
|
||||
let count = 0;
|
||||
for (const [context, entries] of Object.entries(pot.translations)) {
|
||||
for (const entry of Object.values(entries)) {
|
||||
if (!entry.msgid) continue;
|
||||
count++;
|
||||
const translated = po.translations[context][entry.msgid].msgstr;
|
||||
assert.ok(translated[0]);
|
||||
assert.deepEqual(mo.translations[context][entry.msgid].msgstr, translated);
|
||||
const key = context ? `${context}\u0004${entry.msgid}` : entry.msgid;
|
||||
assert.deepEqual(editor[key], translated);
|
||||
assert.deepEqual(view[key], translated);
|
||||
}
|
||||
}
|
||||
assert.ok(count >= 75);
|
||||
});
|
||||
|
||||
test('catalogs use Chinese plural rules, exact locale, and standard WordPress textdomain', () => {
|
||||
assert.equal(po.headers.language, 'zh_CN');
|
||||
assert.equal(mo.headers.language, 'zh_CN');
|
||||
assert.equal(editor[''].lang, 'zh_CN');
|
||||
assert.equal(editor[''].domain, 'wp-asciiplayer');
|
||||
assert.equal(editor['']['plural-forms'], 'nplurals=1; plural=0;');
|
||||
assert.equal(editor['block title\u0004Asciicast Player'][0], 'Asciicast 播放器');
|
||||
assert.equal(editor['Recording URL'][0], '录制文件 URL');
|
||||
});
|
||||
|
||||
test('Unicode, punctuation, percentages and literal author content are preserved', () => {
|
||||
assert.equal(editor['Add a caption…'][0], '添加说明文字…');
|
||||
assert.match(editor['Use a CSS length, such as 480px or 65%. The player stays within its available space.'][0], /480px.*65%/);
|
||||
assert.equal(editor['Author caption / 作者说明'], undefined);
|
||||
const serialized = JSON.stringify(editor);
|
||||
assert.deepEqual(JSON.parse(serialized), editor);
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { normalizeDisplayAlign, normalizePlayerOptions, terminalDimension, normalizeWidth } from '../../src/options.js';
|
||||
test('display placement and scaling never create terminal grid overrides', () => {
|
||||
for (const width of ['25%', '480px', '100%']) {
|
||||
const options = normalizePlayerOptions({ width, displayAlign: 'right', caption: 'Demo' });
|
||||
assert.equal(options.cols, undefined);
|
||||
assert.equal(options.rows, undefined);
|
||||
assert.equal(options.width, undefined);
|
||||
assert.equal(options.caption, undefined);
|
||||
}
|
||||
assert.equal(normalizeDisplayAlign('right'), 'right');
|
||||
assert.equal(normalizeDisplayAlign('unsafe'), 'center');
|
||||
assert.equal(normalizeWidth('480px'), '480px');
|
||||
assert.equal(normalizeWidth('480px;display:none'), '100%');
|
||||
});
|
||||
test('terminal overrides are optional bounded integers', () => {
|
||||
for (const value of ['', '0', '-1', '2.5', '1001', 'Infinity', null]) assert.equal(terminalDimension(value), undefined);
|
||||
assert.equal(terminalDimension('120'), 120);
|
||||
assert.equal(terminalDimension(1), 1);
|
||||
const options = normalizePlayerOptions({ cols: terminalDimension('120'), rows: terminalDimension('') });
|
||||
assert.equal(options.cols, 120);
|
||||
assert.equal(options.rows, undefined);
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { attributesFromShortcode, booleanValue, canTransformShortcode, finiteNumber, normalizeControls, normalizePlayerOptions, normalizeSource, normalizeWidth, previewHeight, secondsValue } from '../../src/options.js';
|
||||
|
||||
test( 'source validation permits explicit web URLs and site-relative cast paths', () => {
|
||||
for ( const value of [ 'https://example.com/recording.cast', 'http://localhost:8888/a.cast?x=1&y=2', '/uploads/hello.cast', "https://example.com/it's.cast" ] ) assert.equal( normalizeSource( ` ${ value } ` ), value );
|
||||
} );
|
||||
|
||||
test( 'source validation rejects executable, credentialed, ambiguous and malformed URLs', () => {
|
||||
for ( const value of [ '', '//evil.test/cast', '/\\evil.test/cast', 'javascript:alert(1)', 'data:text/plain,cast', 'blob:https://example.com/a', 'file:///tmp/a.cast', 'https://user:[email protected]/a.cast', 'https://example.com/\na.cast', 'https://example.com/<script>', 'relative.cast', {}, null ] ) assert.equal( normalizeSource( value ), '' );
|
||||
} );
|
||||
|
||||
test( 'source validation rejects a missing HTTP authority separator', () => {
|
||||
assert.equal( normalizeSource( 'https:example.com/a.cast' ), '' );
|
||||
} );
|
||||
|
||||
test( 'source validation rejects a single HTTP authority slash', () => {
|
||||
assert.equal( normalizeSource( 'https:/example.com/a.cast' ), '' );
|
||||
} );
|
||||
|
||||
test( 'source validation rejects an extra HTTP authority slash', () => {
|
||||
assert.equal( normalizeSource( 'https:///example.com/a.cast' ), '' );
|
||||
} );
|
||||
|
||||
test( 'string false options never become true through truthiness', () => {
|
||||
for ( const value of [ false, 0, 'false', '0', 'off', 'no', ' FALSE ' ] ) assert.equal( booleanValue( value, true ), false );
|
||||
for ( const value of [ true, 1, 'true', '1', 'on', 'yes' ] ) assert.equal( booleanValue( value ), true );
|
||||
assert.equal( booleanValue( 'wrong', null ), null );
|
||||
} );
|
||||
|
||||
test( 'controls convert editor choices to the actual player API types', () => {
|
||||
assert.equal( normalizeControls( 'always' ), true );
|
||||
assert.equal( normalizeControls( 'true' ), true );
|
||||
assert.equal( normalizeControls( 'never' ), false );
|
||||
assert.equal( normalizeControls( 'false' ), false );
|
||||
assert.equal( normalizeControls( 'auto' ), 'auto' );
|
||||
assert.equal( normalizeControls( 'unexpected' ), 'auto' );
|
||||
} );
|
||||
|
||||
test( 'numeric validation rejects non-finite, empty and boolean values', () => {
|
||||
for ( const value of [ Infinity, NaN, '', ' ', {}, null, true, '-1', '101', '0x10', '0b10' ] ) assert.equal( finiteNumber( value, 5, 0, 100 ), 5 );
|
||||
assert.equal( finiteNumber( '0', 5 ), 0 );
|
||||
assert.equal( finiteNumber( '1.5', 5 ), 1.5 );
|
||||
} );
|
||||
|
||||
test( 'timecodes match the PHP supported syntax and preserve zero', () => {
|
||||
assert.equal( secondsValue( '1:02:03.5' ), 3723.5 );
|
||||
assert.equal( secondsValue( '2:03.5' ), 123.5 );
|
||||
assert.equal( secondsValue( ' 2:03 ' ), 123 );
|
||||
for ( const value of [ '1:99', '1:90:00', '1:2:3:4', -1, null ] ) assert.equal( secondsValue( value ), 0 );
|
||||
} );
|
||||
|
||||
test( 'preview forces only its own preload and autoplay settings', () => {
|
||||
const attributes = { autoPlay: true, preload: false, speed: 2, controls: 'always', loop: true };
|
||||
const saved = normalizePlayerOptions( attributes );
|
||||
const preview = normalizePlayerOptions( attributes, { preview: true } );
|
||||
assert.equal( saved.autoPlay, true );
|
||||
assert.equal( saved.preload, false );
|
||||
assert.equal( preview.autoPlay, false );
|
||||
assert.equal( preview.preload, true );
|
||||
assert.equal( preview.speed, 2 );
|
||||
assert.equal( preview.controls, true );
|
||||
assert.equal( attributes.autoPlay, true );
|
||||
} );
|
||||
|
||||
test( 'zero idle limit omits the override and finite legacy loops survive playback', () => {
|
||||
assert.equal( Object.hasOwn( normalizePlayerOptions( { idleTimeLimit: 0 } ), 'idleTimeLimit' ), false );
|
||||
assert.equal( normalizePlayerOptions( { idleTimeLimit: 2 } ).idleTimeLimit, 2 );
|
||||
assert.equal( normalizePlayerOptions( { loop: 3 } ).loop, 3 );
|
||||
assert.equal( normalizePlayerOptions( { fit: false } ).fit, 'none' );
|
||||
} );
|
||||
|
||||
test( 'optional dimensions, fonts and posters are validated consistently', () => {
|
||||
const options = normalizePlayerOptions( { cols: 120, rows: 35, terminalLineHeight: 0.1, terminalFontFamily: '"Fira Code", monospace', terminalFontSize: '1.2rem', poster: 'npt:2:03' } );
|
||||
assert.equal( options.cols, 120 );
|
||||
assert.equal( options.rows, 35 );
|
||||
assert.equal( options.terminalLineHeight, 0.1 );
|
||||
assert.equal( options.terminalFontSize, '1.2rem' );
|
||||
assert.equal( options.poster, 'npt:2:03' );
|
||||
const invalid = normalizePlayerOptions( { cols: 1.5, rows: 1001, terminalLineHeight: 11, terminalFontFamily: 'x; color:red', terminalFontSize: 'url(https://evil.test)', poster: 'https://evil.test/poster' } );
|
||||
for ( const key of [ 'cols', 'rows', 'terminalLineHeight', 'terminalFontFamily', 'terminalFontSize', 'poster' ] ) assert.equal( Object.hasOwn( invalid, key ), false );
|
||||
} );
|
||||
|
||||
test( 'width accepts safe CSS lengths only', () => {
|
||||
for ( const value of [ '0', '80%', '640px', '.5rem', '80vw', '30ch' ] ) assert.equal( normalizeWidth( value ), value );
|
||||
for ( const value of [ 'calc(100% - 1px)', '80%;color:red', 'expression(alert(1))', 'auto', null ] ) assert.equal( normalizeWidth( value ), '100%' );
|
||||
} );
|
||||
|
||||
test( 'legacy height fitting gets a usable preview without changing saved styles', () => {
|
||||
assert.equal( previewHeight( { fit: 'width' } ), undefined );
|
||||
assert.equal( previewHeight( { fit: 'height' } ), '320px' );
|
||||
assert.equal( previewHeight( { fit: 'both', legacyStyle: 'width:80%; height:400px;' } ), '400px' );
|
||||
assert.equal( previewHeight( { fit: 'height', legacyStyle: 'height:expression(alert(1))' } ), '320px' );
|
||||
} );
|
||||
|
||||
test( 'shortcode conversion maps lowercased legacy names and typed booleans', () => {
|
||||
const attrs = attributesFromShortcode( { controls: 'false', autoplay: 'true', preload: 'false', startat: '1:23', idletimelimit: '2', fontsize: 'small', fit: 'false', style: 'width: 80%; height: 300px;' }, 'https://example.com/test.cast' );
|
||||
assert.equal( attrs.source, 'https://example.com/test.cast' );
|
||||
assert.equal( attrs.controls, 'never' );
|
||||
assert.equal( attrs.autoPlay, true );
|
||||
assert.equal( attrs.preload, false );
|
||||
assert.equal( attrs.startAt, 83 );
|
||||
assert.equal( attrs.idleTimeLimit, 2 );
|
||||
assert.equal( attrs.terminalFontSize, 'small' );
|
||||
assert.equal( attrs.fit, 'none' );
|
||||
assert.equal( attrs.width, '80%' );
|
||||
assert.equal( attrs.legacyStyle, 'width: 80%; height: 300px;' );
|
||||
} );
|
||||
|
||||
test( 'shortcode conversion normalizes legacy option case and whitespace like PHP', () => {
|
||||
const attrs = attributesFromShortcode( { fit: ' HEIGHT ', fontsize: ' 15PX ', fontfamily: ' "Fira Code", monospace ' }, '/example.cast' );
|
||||
assert.equal( attrs.fit, 'height' );
|
||||
assert.equal( attrs.terminalFontSize, '15px' );
|
||||
assert.equal( attrs.terminalFontFamily, '"Fira Code", monospace' );
|
||||
} );
|
||||
|
||||
test( 'lossy transforms are refused, so unsupported legacy shortcodes remain untouched', () => {
|
||||
assert.equal( canTransformShortcode( { named: { loop: '2' } } ), false );
|
||||
assert.equal( canTransformShortcode( { named: { customOption: 'x' } } ), false );
|
||||
assert.equal( canTransformShortcode( { named: { style: 'width:calc(100% - 1px)' } } ), false );
|
||||
assert.equal( canTransformShortcode( { named: {}, numeric: [ 'unexpected' ] } ), false );
|
||||
assert.equal( canTransformShortcode( { named: { loop: 'true', controls: 'false', style: 'width:80%;height:300px' } } ), true );
|
||||
} );
|
||||
@@ -0,0 +1,115 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { playerForDocument } from '../../src/player-bridge.js';
|
||||
|
||||
const assets = { script: 'https://site.test/player.js', style: 'https://site.test/player.css' };
|
||||
const flush = () => new Promise( ( resolve ) => setImmediate( resolve ) );
|
||||
|
||||
function fakeDocument() {
|
||||
const nodes = [];
|
||||
const document = {
|
||||
defaultView: { setTimeout, clearTimeout },
|
||||
head: { appendChild( node ) { nodes.push( node ); } },
|
||||
get scripts() { return nodes.filter( ( node ) => node.tag === 'script' ); },
|
||||
querySelectorAll() { return nodes.filter( ( node ) => node.tag === 'link' ); },
|
||||
createElement( tag ) {
|
||||
const events = new Map();
|
||||
return {
|
||||
tag, dataset: {},
|
||||
addEventListener( name, callback ) { events.set( name, callback ); },
|
||||
removeEventListener( name ) { events.delete( name ); },
|
||||
dispatch( name ) { events.get( name )?.(); },
|
||||
remove() { const index = nodes.indexOf( this ); if ( index >= 0 ) nodes.splice( index, 1 ); },
|
||||
};
|
||||
},
|
||||
};
|
||||
return { document, nodes };
|
||||
}
|
||||
|
||||
test( 'bridge waits for CSS even if the player global already exists', async () => {
|
||||
const { document, nodes } = fakeDocument();
|
||||
const api = { create() {} };
|
||||
document.defaultView.AsciinemaPlayer = api;
|
||||
let resolved = false;
|
||||
const pending = playerForDocument( document, assets ).then( ( value ) => { resolved = true; return value; } );
|
||||
await flush();
|
||||
assert.equal( resolved, false );
|
||||
assert.equal( nodes.length, 1 );
|
||||
nodes[ 0 ].sheet = {};
|
||||
nodes[ 0 ].dispatch( 'load' );
|
||||
assert.equal( await pending, api );
|
||||
assert.equal( nodes.length, 1 );
|
||||
} );
|
||||
|
||||
test( 'parallel previews deduplicate local CSS and script and use the canvas realm', async () => {
|
||||
const { document, nodes } = fakeDocument();
|
||||
const first = playerForDocument( document, assets );
|
||||
const second = playerForDocument( document, assets );
|
||||
assert.equal( nodes.length, 1 );
|
||||
nodes[ 0 ].sheet = {};
|
||||
nodes[ 0 ].dispatch( 'load' );
|
||||
await flush();
|
||||
assert.equal( document.scripts.length, 1 );
|
||||
const canvasAPI = { create() {} };
|
||||
document.defaultView.AsciinemaPlayer = canvasAPI;
|
||||
document.scripts[ 0 ].dispatch( 'load' );
|
||||
assert.equal( await first, canvasAPI );
|
||||
assert.equal( await second, canvasAPI );
|
||||
assert.equal( await playerForDocument( document, assets ), canvasAPI );
|
||||
} );
|
||||
|
||||
test( 'failed owned script is removed and retry starts a new request', async () => {
|
||||
const { document, nodes } = fakeDocument();
|
||||
const pending = playerForDocument( document, assets );
|
||||
const rejection = assert.rejects( pending, /script could not be loaded/ );
|
||||
nodes[ 0 ].sheet = {};
|
||||
nodes[ 0 ].dispatch( 'load' );
|
||||
await flush();
|
||||
document.scripts[ 0 ].dispatch( 'error' );
|
||||
await rejection;
|
||||
assert.equal( document.scripts.length, 0 );
|
||||
const retry = playerForDocument( document, assets );
|
||||
await flush();
|
||||
assert.equal( document.scripts.length, 1 );
|
||||
document.defaultView.AsciinemaPlayer = { create() {} };
|
||||
document.scripts[ 0 ].dispatch( 'load' );
|
||||
assert.equal( await retry, document.defaultView.AsciinemaPlayer );
|
||||
} );
|
||||
|
||||
test( 'failed stylesheet is retryable and never starts a script before CSS', async () => {
|
||||
const { document, nodes } = fakeDocument();
|
||||
const pending = playerForDocument( document, assets );
|
||||
const rejection = assert.rejects( pending, /stylesheet could not be loaded/ );
|
||||
nodes[ 0 ].dispatch( 'error' );
|
||||
await rejection;
|
||||
assert.equal( nodes.length, 0 );
|
||||
const retry = playerForDocument( document, assets );
|
||||
assert.equal( nodes.length, 1 );
|
||||
nodes[ 0 ].sheet = {};
|
||||
nodes[ 0 ].dispatch( 'load' );
|
||||
await flush();
|
||||
document.defaultView.AsciinemaPlayer = { create() {} };
|
||||
document.scripts[ 0 ].dispatch( 'load' );
|
||||
await retry;
|
||||
} );
|
||||
|
||||
test( 'existing enqueued assets are reused while still loading', async () => {
|
||||
const { document, nodes } = fakeDocument();
|
||||
const style = document.createElement( 'link' );
|
||||
style.href = assets.style;
|
||||
style.sheet = {};
|
||||
const script = document.createElement( 'script' );
|
||||
script.src = assets.script;
|
||||
document.head.appendChild( style );
|
||||
document.head.appendChild( script );
|
||||
const pending = playerForDocument( document, assets );
|
||||
await flush();
|
||||
assert.equal( nodes.length, 2 );
|
||||
document.defaultView.AsciinemaPlayer = { create() {} };
|
||||
script.dispatch( 'load' );
|
||||
assert.equal( await pending, document.defaultView.AsciinemaPlayer );
|
||||
} );
|
||||
|
||||
test( 'document with no window fails cleanly', async () => {
|
||||
await assert.rejects( playerForDocument( { defaultView: null }, assets ), /canvas is unavailable/ );
|
||||
} );
|
||||
@@ -0,0 +1,124 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { MAX_HEADER_BYTES, readRecordingSize, recordingSizeFromHeader } from '../../src/recording-metadata.js';
|
||||
|
||||
test( 'original dimensions use each supported asciicast header schema', () => {
|
||||
assert.deepEqual( recordingSizeFromHeader( { version: 1, width: 132, height: 43 } ), { cols: 132, rows: 43 } );
|
||||
assert.deepEqual( recordingSizeFromHeader( { version: 2, width: 110, height: 35 } ), { cols: 110, rows: 35 } );
|
||||
assert.deepEqual( recordingSizeFromHeader( { version: 3, term: { cols: 150, rows: 50 }, width: 1, height: 1 } ), { cols: 150, rows: 50 } );
|
||||
assert.deepEqual( recordingSizeFromHeader( { version: 2, width: 1, height: 1000 } ), { cols: 1, rows: 1000 } );
|
||||
assert.deepEqual( recordingSizeFromHeader( { version: 2, width: 1500, height: 1200 } ), { cols: 1500, rows: 1200 } );
|
||||
assert.deepEqual( recordingSizeFromHeader( { version: 2, width: Number.MAX_SAFE_INTEGER, height: 1 } ), { cols: Number.MAX_SAFE_INTEGER, rows: 1 } );
|
||||
} );
|
||||
|
||||
test( 'missing, unsupported and invalid dimensions stay unknown, never 80 by 24', () => {
|
||||
for ( const header of [ null, undefined, '', [], {}, { width: 80, height: 24 }, { version: '2', width: 80, height: 24 }, { version: 4, width: 80, height: 24 }, { version: 3, width: 80, height: 24 }, { version: 3, term: {} } ] ) {
|
||||
assert.equal( recordingSizeFromHeader( header ), null );
|
||||
}
|
||||
for ( const invalid of [ undefined, null, '', '80', true, false, NaN, Infinity, -1, 0, 1.5, Number.MAX_SAFE_INTEGER + 1 ] ) {
|
||||
assert.equal( recordingSizeFromHeader( { version: 2, width: invalid, height: 24 } ), null );
|
||||
assert.equal( recordingSizeFromHeader( { version: 3, term: { cols: 80, rows: invalid } } ), null );
|
||||
}
|
||||
} );
|
||||
|
||||
test( 'metadata reads the first header and preserves the full original response for playback', async () => {
|
||||
const text = '{"version":2,"width":132,"height":43}\n[1,"r","200x60"]\n[2,"o","hello"]\n';
|
||||
const response = new Response( text );
|
||||
let clones = 0;
|
||||
const clone = response.clone.bind( response );
|
||||
response.clone = () => { clones++; return clone(); };
|
||||
assert.deepEqual( await readRecordingSize( response ), { cols: 132, rows: 43 } );
|
||||
assert.equal( clones, 1 );
|
||||
assert.equal( response.bodyUsed, false );
|
||||
assert.equal( await response.text(), text );
|
||||
} );
|
||||
|
||||
test( 'v3 reads terminal metadata, not nested output or subsequent resize events', async () => {
|
||||
const text = '{"version":3,"env":{"cols":500,"rows":500},"term":{"cols":120,"rows":30}}\n[0,"r","90x20"]\n';
|
||||
const response = new Response( text );
|
||||
assert.deepEqual( await readRecordingSize( response ), { cols: 120, rows: 30 } );
|
||||
await response.text();
|
||||
} );
|
||||
|
||||
function chunkedResponse( chunks ) {
|
||||
let reads = 0;
|
||||
let canceled = false;
|
||||
return {
|
||||
response: {
|
||||
ok: true,
|
||||
body: { getReader() { throw new Error( 'Do not read the original response.' ); } },
|
||||
clone: () => ( {
|
||||
body: { getReader: () => ( {
|
||||
async read() {
|
||||
const value = chunks[ reads++ ];
|
||||
return value ? { value, done: false } : { done: true };
|
||||
},
|
||||
cancel() {
|
||||
canceled = true;
|
||||
// A real tee's cancel can wait for its other branch.
|
||||
return new Promise( () => {} );
|
||||
},
|
||||
} ) },
|
||||
} ),
|
||||
},
|
||||
get reads() { return reads; },
|
||||
get canceled() { return canceled; },
|
||||
};
|
||||
}
|
||||
|
||||
test( 'pretty-printed v1 reads dimensions before stdout and does not await tee cancellation', async () => {
|
||||
const encode = new TextEncoder();
|
||||
const stream = chunkedResponse( [
|
||||
encode.encode( '{\n "version": 1,\n "width": 104,\n' ),
|
||||
encode.encode( ' "height": 28,\n "stdout": [\n' ),
|
||||
encode.encode( `[0,${ JSON.stringify( 'output'.repeat( MAX_HEADER_BYTES ) ) }]]}` ),
|
||||
] );
|
||||
assert.deepEqual( await readRecordingSize( stream.response ), { cols: 104, rows: 28 } );
|
||||
assert.equal( stream.reads, 2 );
|
||||
assert.equal( stream.canceled, true );
|
||||
} );
|
||||
|
||||
test( 'streaming JSON handles split UTF-8, escapes and nested objects without false fields', async () => {
|
||||
const text = JSON.stringify( { title: '尺寸 \\ " }, \\ ', env: { width: 300, height: 500 }, width: 137, height: 47, version: 1, stdout: [] } );
|
||||
const chunks = Array.from( new TextEncoder().encode( text ), ( value ) => Uint8Array.of( value ) );
|
||||
const stream = chunkedResponse( chunks );
|
||||
assert.deepEqual( await readRecordingSize( stream.response ), { cols: 137, rows: 47 } );
|
||||
assert.ok( stream.reads < chunks.length );
|
||||
assert.equal( stream.canceled, true );
|
||||
} );
|
||||
|
||||
test( 'headers over the byte limit stay unknown without draining the recording', async () => {
|
||||
const encode = new TextEncoder();
|
||||
const stream = chunkedResponse( [
|
||||
encode.encode( '{"version":2,"title":"' + 'x'.repeat( MAX_HEADER_BYTES ) ),
|
||||
encode.encode( '","width":132,"height":43}\n[1,"o","hello"]' ),
|
||||
] );
|
||||
assert.equal( await readRecordingSize( stream.response ), null );
|
||||
assert.equal( stream.reads, 1 );
|
||||
assert.equal( stream.canceled, true );
|
||||
} );
|
||||
|
||||
test( 'byte limit accepts a complete header at its boundary and ignores larger output chunks', async () => {
|
||||
const base = '{"version":2,"width":132,"height":43,"title":"';
|
||||
const header = base + 'x'.repeat( MAX_HEADER_BYTES - base.length - 2 ) + '"}';
|
||||
const stream = chunkedResponse( [ new TextEncoder().encode( header + '\n[1,"o","' + 'x'.repeat( MAX_HEADER_BYTES ) + '"]' ) ] );
|
||||
assert.deepEqual( await readRecordingSize( stream.response ), { cols: 132, rows: 43 } );
|
||||
assert.equal( stream.reads, 1 );
|
||||
} );
|
||||
|
||||
test( 'invalid JSON, nested lookalikes and incomplete dimensions never become defaults', async () => {
|
||||
for ( const text of [ '', 'not a cast', '<html>error</html>', '[]', '{}', '{"version":2,"env":{"width":80,"height":24}}', '{"version":2,"width":80,"height":24,}', '{"version":2,,"width":80,"height":24}', '{"version":2,"width":80,"height":24]', '{"version":2,"width":80,"height":24', '{"version":3,"term":{"cols":80}}' ] ) {
|
||||
const response = new Response( text );
|
||||
assert.equal( await readRecordingSize( response ), null, text );
|
||||
await response.text();
|
||||
}
|
||||
} );
|
||||
|
||||
test( 'failed responses, unavailable streams and rejected reads quietly stay unknown', async () => {
|
||||
assert.equal( await readRecordingSize( { ok: false } ), null );
|
||||
assert.equal( await readRecordingSize( { ok: true, body: null } ), null );
|
||||
assert.equal( await readRecordingSize( { ok: true, body: { getReader() {} }, clone() { throw new Error( 'locked' ); } } ), null );
|
||||
const broken = chunkedResponse( [] );
|
||||
broken.response.clone = () => ( { body: { getReader: () => ( { read: () => Promise.reject( new Error( 'aborted' ) ), cancel: () => Promise.reject( new Error( 'aborted' ) ) } ) } } );
|
||||
assert.equal( await readRecordingSize( broken.response ), null );
|
||||
} );
|
||||
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
/**
|
||||
* Minimal WordPress API doubles for focused, dependency-free plugin tests.
|
||||
* These verify plugin contracts, not the implementation of WordPress sanitizers.
|
||||
* Real WordPress/browser integration tests cover the latter separately.
|
||||
*/
|
||||
|
||||
define( 'ABSPATH', __DIR__ . '/' );
|
||||
define( 'PLUGIN_VERSION', 'some-other-plugin' );
|
||||
|
||||
$GLOBALS['ap_test'] = array();
|
||||
|
||||
function ap_record( $key, $value ) {
|
||||
$GLOBALS['ap_test'][ $key ][] = $value;
|
||||
}
|
||||
|
||||
function add_action( $hook, $callback, $priority = 10 ) {
|
||||
ap_record( 'actions', array( $hook, $callback, $priority ) );
|
||||
}
|
||||
function add_filter( $hook, $callback, $priority = 10, $accepted_args = 1 ) {
|
||||
ap_record( 'filters', array( $hook, $callback, $priority, $accepted_args ) );
|
||||
}
|
||||
function load_plugin_textdomain( $domain, $deprecated, $path ) {
|
||||
ap_record( 'textdomains', array( $domain, $path ) );
|
||||
}
|
||||
function plugin_basename( $file ) {
|
||||
return 'wp-asciiplayer/asciicast-player.php';
|
||||
}
|
||||
function __( $text, $domain = 'default' ) {
|
||||
return $text;
|
||||
}
|
||||
function current_user_can( $capability ) {
|
||||
return ! empty( $GLOBALS['ap_test']['capabilities'][ $capability ] );
|
||||
}
|
||||
function user_can( $user, $capability ) {
|
||||
return ! empty( $GLOBALS['ap_test']['user_capabilities'][ $user ][ $capability ] );
|
||||
}
|
||||
function is_multisite() {
|
||||
return ! empty( $GLOBALS['ap_test']['multisite'] );
|
||||
}
|
||||
function get_site_option( $key, $default = false ) {
|
||||
return $GLOBALS['ap_test']['site_options'][ $key ] ?? $default;
|
||||
}
|
||||
function get_allowed_mime_types() {
|
||||
return $GLOBALS['ap_test']['allowed_mimes'] ?? LamGC\Asciiplayer\allow_cast_upload_mime( array( 'txt' => 'text/plain', 'jpg' => 'image/jpeg' ) );
|
||||
}
|
||||
function wp_check_filetype( $filename, $mimes = null ) {
|
||||
// Mirrors core's empty-map fallback to cover explicit MIME deny-lists.
|
||||
if ( empty( $mimes ) ) {
|
||||
$mimes = get_allowed_mime_types();
|
||||
}
|
||||
foreach ( $mimes as $extension => $mime ) {
|
||||
if ( preg_match( '/\.(' . $extension . ')$/i', $filename, $matches ) ) {
|
||||
return array( 'ext' => $matches[1], 'type' => $mime );
|
||||
}
|
||||
}
|
||||
return array( 'ext' => false, 'type' => false );
|
||||
}
|
||||
function add_shortcode( $tag, $callback ) {
|
||||
ap_record( 'shortcodes', array( $tag, $callback ) );
|
||||
}
|
||||
function add_option() {
|
||||
throw new RuntimeException( 'Plugin must not write options on requests.' );
|
||||
}
|
||||
function update_option() {
|
||||
throw new RuntimeException( 'Plugin must not write options on requests.' );
|
||||
}
|
||||
function plugin_dir_url( $file ) {
|
||||
return 'https://wordpress.test/wp-content/plugins/wp-asciiplayer/';
|
||||
}
|
||||
function add_query_arg( $key, $value, $url ) {
|
||||
return $url . ( false === strpos( $url, '?' ) ? '?' : '&' ) . rawurlencode( $key ) . '=' . rawurlencode( $value );
|
||||
}
|
||||
function wp_parse_url( $value ) {
|
||||
return parse_url( $value );
|
||||
}
|
||||
function esc_url_raw( $value, $protocols = null ) {
|
||||
return $value;
|
||||
}
|
||||
function esc_url( $value, $protocols = null ) {
|
||||
return htmlspecialchars( $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8' );
|
||||
}
|
||||
function esc_attr( $value ) {
|
||||
return htmlspecialchars( $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8' );
|
||||
}
|
||||
function get_block_wrapper_attributes( $attributes ) {
|
||||
ap_record( 'block_wrappers', $attributes );
|
||||
$output = array();
|
||||
foreach ( $attributes as $key => $value ) {
|
||||
if ( '' !== $value ) {
|
||||
$output[] = $key . '="' . esc_attr( $value ) . '"';
|
||||
}
|
||||
}
|
||||
return implode( ' ', $output );
|
||||
}
|
||||
function wp_kses( $value, $allowed ) {
|
||||
// Contract-only double. Actual sanitizer coverage belongs to WP browser tests.
|
||||
return strip_tags( $value, '<br>' );
|
||||
}
|
||||
function wp_json_encode( $value, $flags = 0 ) {
|
||||
return json_encode( $value, $flags );
|
||||
}
|
||||
function safecss_filter_attr( $style ) {
|
||||
ap_record( 'filtered_css', $style );
|
||||
$safe = array();
|
||||
foreach ( explode( ';', $style ) as $declaration ) {
|
||||
if ( preg_match( '/^\s*(width|height|color)\s*:\s*([a-z0-9.%# -]+)\s*$/i', $declaration ) ) {
|
||||
$safe[] = trim( $declaration );
|
||||
}
|
||||
}
|
||||
return implode( ';', $safe );
|
||||
}
|
||||
function wp_register_script( $handle, $src, $deps, $version, $footer ) {
|
||||
$GLOBALS['ap_test']['scripts'][ $handle ] = compact( 'src', 'deps', 'version', 'footer' );
|
||||
}
|
||||
function wp_register_style( $handle, $src, $deps, $version ) {
|
||||
$GLOBALS['ap_test']['styles'][ $handle ] = compact( 'src', 'deps', 'version' );
|
||||
}
|
||||
function wp_add_inline_script( $handle, $source, $position ) {
|
||||
ap_record( 'inline_scripts', compact( 'handle', 'source', 'position' ) );
|
||||
}
|
||||
function wp_set_script_translations( $handle, $domain, $path ) {
|
||||
ap_record( 'translations', compact( 'handle', 'domain', 'path' ) );
|
||||
}
|
||||
function register_block_type( $path, $args ) {
|
||||
ap_record( 'blocks', compact( 'path', 'args' ) );
|
||||
}
|
||||
function wp_enqueue_script( $handle ) {
|
||||
$GLOBALS['ap_test']['enqueued_scripts'][ $handle ] = true;
|
||||
}
|
||||
function wp_enqueue_style( $handle ) {
|
||||
$GLOBALS['ap_test']['enqueued_styles'][ $handle ] = true;
|
||||
}
|
||||
function wp_style_is( $handle, $status ) {
|
||||
return ! empty( $GLOBALS['ap_test'][ 'done' === $status ? 'printed_styles' : 'enqueued_styles' ][ $handle ] );
|
||||
}
|
||||
function wp_print_styles( $handles ) {
|
||||
foreach ( $handles as $handle ) {
|
||||
$GLOBALS['ap_test']['printed_styles'][ $handle ] = true;
|
||||
ap_record( 'style_print_calls', $handle );
|
||||
}
|
||||
}
|
||||
function has_shortcode( $content, $tag ) {
|
||||
return false !== strpos( $content, '[' . $tag );
|
||||
}
|
||||
function has_block( $name, $content ) {
|
||||
return false !== strpos( $content, '<!-- wp:' . $name );
|
||||
}
|
||||
|
||||
require dirname( __DIR__, 2 ) . '/asciicast-player.php';
|
||||
@@ -0,0 +1,187 @@
|
||||
<?php
|
||||
/** Run with PHP 7.4+: php tests/php/run.php */
|
||||
|
||||
require __DIR__ . '/bootstrap.php';
|
||||
|
||||
use function LamGC\Asciiplayer\enqueue_content_assets;
|
||||
use function LamGC\Asciiplayer\normalize_attributes;
|
||||
use function LamGC\Asciiplayer\parse_boolean;
|
||||
use function LamGC\Asciiplayer\parse_number;
|
||||
use function LamGC\Asciiplayer\parse_time;
|
||||
use function LamGC\Asciiplayer\player_options;
|
||||
use function LamGC\Asciiplayer\player_style;
|
||||
use function LamGC\Asciiplayer\print_late_styles;
|
||||
use function LamGC\Asciiplayer\register_plugin;
|
||||
use function LamGC\Asciiplayer\render_block;
|
||||
use function LamGC\Asciiplayer\render_player;
|
||||
use function LamGC\Asciiplayer\render_shortcode;
|
||||
use function LamGC\Asciiplayer\sanitize_source;
|
||||
|
||||
$assertions = 0;
|
||||
function same( $expected, $actual, $message ) {
|
||||
global $assertions;
|
||||
++$assertions;
|
||||
if ( $expected !== $actual ) {
|
||||
throw new RuntimeException( $message . '\nExpected: ' . var_export( $expected, true ) . '\nActual: ' . var_export( $actual, true ) );
|
||||
}
|
||||
}
|
||||
function contains( $needle, $haystack, $message ) {
|
||||
same( true, false !== strpos( $haystack, $needle ), $message );
|
||||
}
|
||||
function options_from( $html ) {
|
||||
if ( ! preg_match( '/ data-ap-options="([^"]*)"/', $html, $matches ) ) {
|
||||
throw new RuntimeException( 'Missing JSON data-ap-options.' );
|
||||
}
|
||||
return json_decode( html_entity_decode( $matches[1], ENT_QUOTES, 'UTF-8' ), true );
|
||||
}
|
||||
function reset_enqueues() {
|
||||
$GLOBALS['ap_test']['enqueued_scripts'] = array();
|
||||
$GLOBALS['ap_test']['enqueued_styles'] = array();
|
||||
}
|
||||
|
||||
try {
|
||||
// All registration happens in init, without global option writes/collisions.
|
||||
same( 'some-other-plugin', PLUGIN_VERSION, 'No shared global version constant.' );
|
||||
same( false, function_exists( 'is_assoc' ), 'No generic global helper functions.' );
|
||||
same( 3, count( $GLOBALS['ap_test']['actions'] ), 'Register init, enqueue and late-style hooks.' );
|
||||
foreach ( $GLOBALS['ap_test']['actions'] as $action ) {
|
||||
same( true, is_callable( $action[1] ), 'Every registered callback is callable.' );
|
||||
}
|
||||
register_plugin();
|
||||
same( array( 'wp-asciiplayer', 'wp-asciiplayer/languages' ), $GLOBALS['ap_test']['textdomains'][0], 'Bundled PHP catalogs register during init.' );
|
||||
if ( file_exists( dirname( __DIR__, 2 ) . '/build/runtime.asset.php' ) ) {
|
||||
$versions = require dirname( __DIR__, 2 ) . '/build/runtime.asset.php';
|
||||
same( $versions['player.js'], $GLOBALS['ap_test']['scripts']['lamgc-asciiplayer-player']['version'], 'Player script uses its content hash.' );
|
||||
foreach ( array( 'lamgc-asciiplayer-player-style' => 'player.css', 'lamgc-asciiplayer-style' => 'style-index.css', 'lamgc-asciiplayer-editor-style' => 'index.css' ) as $handle => $file ) {
|
||||
same( $versions[ $file ], $GLOBALS['ap_test']['styles'][ $handle ]['version'], 'Each stylesheet uses its own content hash.' );
|
||||
}
|
||||
}
|
||||
same( 'asciiplayer', $GLOBALS['ap_test']['shortcodes'][0][0], 'Legacy shortcode stays registered.' );
|
||||
contains( '/build', $GLOBALS['ap_test']['blocks'][0]['path'], 'Block uses local metadata.' );
|
||||
same( 'LamGC\\Asciiplayer\\render_block', $GLOBALS['ap_test']['blocks'][0]['args']['render_callback'], 'Block is server rendered.' );
|
||||
foreach ( $GLOBALS['ap_test']['scripts'] as $script ) {
|
||||
contains( 'https://wordpress.test/wp-content/plugins/wp-asciiplayer/build/', $script['src'], 'Runtime JavaScript is locally bundled.' );
|
||||
same( true, $script['footer'], 'Scripts load in footer.' );
|
||||
}
|
||||
same( true, in_array( 'lamgc-asciiplayer-player', $GLOBALS['ap_test']['scripts']['lamgc-asciiplayer-view']['deps'], true ), 'Frontend adapter depends on local player.' );
|
||||
same( true, in_array( 'wp-i18n', $GLOBALS['ap_test']['scripts']['lamgc-asciiplayer-view']['deps'], true ), 'Frontend translations dependency registered.' );
|
||||
same( array( 'lamgc-asciiplayer-player-style' ), $GLOBALS['ap_test']['styles']['lamgc-asciiplayer-style']['deps'], 'Frontend style depends on player stylesheet.' );
|
||||
contains( 'window.wpAsciiplayerSettings = ', $GLOBALS['ap_test']['inline_scripts'][0]['source'], 'Editor iframe receives trusted runtime URLs.' );
|
||||
same( 'before', $GLOBALS['ap_test']['inline_scripts'][0]['position'], 'Settings are available before editor boot.' );
|
||||
contains( 'player.js?ver=' . $GLOBALS['ap_test']['scripts']['lamgc-asciiplayer-player']['version'], $GLOBALS['ap_test']['inline_scripts'][0]['source'], 'Bridge JavaScript cache-buster matches registered asset version.' );
|
||||
contains( 'player.css?ver=' . $GLOBALS['ap_test']['styles']['lamgc-asciiplayer-player-style']['version'], $GLOBALS['ap_test']['inline_scripts'][0]['source'], 'Bridge CSS cache-buster matches registered asset version.' );
|
||||
|
||||
// Source validation covers script, HTML, credential and relative-URL attacks.
|
||||
foreach ( array( '', 'javascript:alert(1)', 'data:text/html,test', 'file:///tmp/a.cast', '//evil.test/a.cast', '/\\evil.test/a.cast', "https://example.test/a\n.cast", 'https://x.test/" onmouseover="alert(1)', 'https://user:[email protected]/a.cast', 'https:///a.cast', 'a.cast', array( 'bad' ) ) as $source ) {
|
||||
same( '', sanitize_source( $source ), 'Reject unsafe or unsupported source.' );
|
||||
}
|
||||
foreach ( array( 'https://example.test/a.cast', 'http://example.test:8080/a.cast?x=1&y=2', '/wp-content/uploads/demo.cast', '/cast/demo.cast?x=1&y=2' ) as $source ) {
|
||||
same( $source, sanitize_source( $source ), 'Allow HTTP(S) or root-relative source.' );
|
||||
}
|
||||
same( 'https://example.test/a.cast?a=1&b=2', sanitize_source( ' https://example.test/a.cast?a=1&b=2 ' ), 'Decode editor entities and trim outer whitespace.' );
|
||||
|
||||
foreach ( array( false, 'false', '0', 0, 'off', 'no' ) as $value ) {
|
||||
same( false, parse_boolean( $value ), 'Explicit false remains false.' );
|
||||
}
|
||||
foreach ( array( true, 'true', '1', 1, 'on', 'yes' ) as $value ) {
|
||||
same( true, parse_boolean( $value ), 'Recognized true values.' );
|
||||
}
|
||||
same( null, parse_boolean( 'garbage' ), 'Unrecognized bool is ignored.' );
|
||||
same( null, parse_number( 'INF', 0, 100 ), 'Infinity is rejected.' );
|
||||
same( null, parse_number( true, 0, 100 ), 'Boolean is not a numeric option.' );
|
||||
same( null, parse_number( -1, 0, 100 ), 'Negative time is rejected.' );
|
||||
same( 0.0, parse_time( '0' ), 'Zero start time is retained.' );
|
||||
same( 123.0, parse_time( '2:03' ), 'Legacy mm:ss start time.' );
|
||||
same( 3723.5, parse_time( '1:02:03.5' ), 'Legacy hh:mm:ss fractional time.' );
|
||||
same( null, parse_time( '1:99' ), 'Invalid time components are rejected.' );
|
||||
|
||||
$attrs = normalize_attributes( array( 'autoplay' => 'false', 'startat' => '2:03', 'idle-time-limit' => '2', 'fontSize' => '15px', 'fontfamily' => "'Fira Code', monospace", 'lineheight' => 1.4, 'logger' => 'console', 'unknown' => 'bad', 0 => 'bare', 'rows' => array( 2 ) ) );
|
||||
same( false, isset( $attrs['unknown'] ), 'Unknown attributes are discarded.' );
|
||||
same( false, isset( $attrs['logger'] ), 'No executable logger objects.' );
|
||||
same( false, isset( $attrs['rows'] ), 'Nested option values are discarded.' );
|
||||
$options = player_options( $attrs );
|
||||
same( false, $options['autoPlay'], 'Lowercase autoplay normalizes and respects false.' );
|
||||
same( 123.0, $options['startAt'], 'Lowercase startAt normalizes.' );
|
||||
same( 2.0, $options['idleTimeLimit'], 'Hyphenated idleTimeLimit normalizes.' );
|
||||
same( '15px', $options['terminalFontSize'], 'Legacy font aliases map to current player options.' );
|
||||
same( "'Fira Code', monospace", $options['terminalFontFamily'], 'Font lists survive safely.' );
|
||||
same( 1.4, $options['terminalLineHeight'], 'Legacy lineHeight maps to current name.' );
|
||||
$options = player_options( normalize_attributes( array( 'controls' => 'false', 'preload' => 'false', 'loop' => 'false', 'fit' => 'false' ) ) );
|
||||
same( false, $options['controls'], 'controls=false is a boolean, never a truthy string.' );
|
||||
same( false, $options['preload'], 'preload=false is retained.' );
|
||||
same( false, $options['loop'], 'loop=false is retained.' );
|
||||
same( 'none', $options['fit'], 'Legacy fit=false maps to none.' );
|
||||
foreach ( array( 'always' => true, 'never' => false, 'auto' => 'auto' ) as $input => $expected ) {
|
||||
same( $expected, player_options( array( 'controls' => $input ) )['controls'], 'Block control enum converts to player API.' );
|
||||
}
|
||||
same( 3, player_options( array( 'loop' => '3' ) )['loop'], 'Finite replay counts stay supported in shortcodes.' );
|
||||
$options = player_options( array( 'speed' => -1, 'idleTimeLimit' => 0, 'cols' => 4.5, 'rows' => 1001, 'startAt' => -1, 'terminalFontSize' => '12px; color:red', 'terminalFontFamily' => 'url(https://bad.test)', 'theme' => 'x" onclick=bad', 'poster' => 'javascript:alert(1)' ) );
|
||||
same( array( 'autoPlay' => false, 'preload' => true, 'fit' => 'width' ), $options, 'Invalid options omitted, safe defaults retained.' );
|
||||
same( 'auto/dracula', player_options( array( 'theme' => 'auto/dracula' ) )['theme'], 'Player theme fallback syntax retained.' );
|
||||
same( 'npt:1:23', player_options( array( 'poster' => 'npt:1:23' ) )['poster'], 'Safe NPT poster supported.' );
|
||||
same( 'data:text/plain,<Hello>', player_options( array( 'poster' => 'data:text/plain,<Hello>' ) )['poster'], 'Plain terminal-text posters are supported.' );
|
||||
|
||||
reset_enqueues();
|
||||
same( '', render_shortcode( array() ), 'Unclosed/empty shortcode returns no player.' );
|
||||
same( '', render_player( array( 'source' => 'javascript:alert(1)' ) ), 'Invalid source emits no HTML.' );
|
||||
same( array(), $GLOBALS['ap_test']['enqueued_scripts'], 'Invalid source does not enqueue assets.' );
|
||||
$html = render_shortcode( array( 'controls' => 'false', 'autoPlay' => 'true', 'startAt' => '12', 'idleTimeLimit' => '2' ), 'https://example.test/demo.cast?a=1&b=2' );
|
||||
contains( 'class="asciiplayer-container"', $html, 'Render adapter class.' );
|
||||
contains( 'data-ap-src="https://example.test/demo.cast?a=1&b=2"', $html, 'URL is escaped for an HTML attribute.' );
|
||||
same( false, options_from( $html )['controls'], 'Markup has typed JSON false.' );
|
||||
same( true, options_from( $html )['autoPlay'], 'CamelCase boolean handled.' );
|
||||
same( 12, options_from( $html )['startAt'], 'JSON numeric startAt.' );
|
||||
same( 2, options_from( $html )['idleTimeLimit'], 'JSON numeric idleTimeLimit.' );
|
||||
same( true, isset( $GLOBALS['ap_test']['enqueued_scripts']['lamgc-asciiplayer-view'] ), 'Every valid render requests the frontend adapter.' );
|
||||
same( true, isset( $GLOBALS['ap_test']['enqueued_styles']['lamgc-asciiplayer-style'] ), 'Every valid render requests CSS.' );
|
||||
$html = render_block( array( 'source' => '/demo.cast', 'poster' => 'data:text/plain,"><script>alert(1)</script>', 'legacyStyle' => 'width:80%;color:red;background:url(javascript:alert(1))' ) );
|
||||
same( false, false !== strpos( $html, '<script>' ), 'Poster cannot escape JSON/HTML attribute.' );
|
||||
contains( 'style="color:red"', $html, 'Legacy player styles stay on the player mount point.' );
|
||||
contains( 'style="width:80%;"', $html, 'Legacy width moves to the figure.' );
|
||||
contains( 'background:url(javascript:alert(1))', end( $GLOBALS['ap_test']['filtered_css'] ), 'The original style is supplied to the WordPress sanitizer.' );
|
||||
same( 'width:80%;height:200px;width:50%;', player_style( array( 'legacyStyle' => 'width:80%;height:200px', 'width' => '50%' ) ), 'Dedicated width control overrides legacy width.' );
|
||||
same( '', player_style( array( 'width' => '100%;background:red' ) ), 'Width cannot inject extra declarations.' );
|
||||
same( options_from( render_player( array( 'source' => '/demo.cast', 'speed' => 2 ) ) ), options_from( render_block( array( 'source' => '/demo.cast', 'speed' => 2 ) ) ), 'Block uses shared player options.' );
|
||||
same( 'asciiplayer-block', end( $GLOBALS['ap_test']['block_wrappers'] )['class'], 'Block wrapper classes/layout pass through WordPress block supports.' );
|
||||
|
||||
$html = render_block( array( 'source' => '/demo.cast', 'width' => '480px', 'displayAlign' => 'right', 'caption' => 'Caption & detail<br>second line' ) );
|
||||
contains( '<figure ', $html, 'Block has semantic figure wrapper.' );
|
||||
contains( 'asciiplayer-align-right', $html, 'Validated display alignment.' );
|
||||
contains( 'width:480px;', $html, 'Display width belongs to figure.' );
|
||||
contains( '<figcaption class="wp-element-caption">Caption & detail<br>second line</figcaption>', $html, 'Caption is outside player mount point.' );
|
||||
contains( '</div><figcaption', $html, 'Player cannot dispose caption.' );
|
||||
$html = render_block( array( 'source' => '/demo.cast', 'displayAlign' => '\" onclick=alert(1)', 'caption' => '<img src=x onerror=alert(1)>Safe' ) );
|
||||
contains( 'asciiplayer-align-center', $html, 'Invalid alignment falls back safely.' );
|
||||
same( false, false !== strpos( $html, '<img' ), 'Caption does not allow image markup.' );
|
||||
same( false, isset( player_options( array() )['cols'] ), 'Default columns come from recording.' );
|
||||
same( false, isset( player_options( array() )['rows'] ), 'Default rows come from recording.' );
|
||||
same( 120, player_options( array( 'cols' => 120 ) )['cols'], 'Explicit column override is retained.' );
|
||||
same( false, isset( player_options( array( 'cols' => 120 ) )['rows'] ), 'One-axis override leaves other axis native.' );
|
||||
|
||||
$html = render_block( array( 'source' => '/demo.cast', 'legacyStyle' => 'height:200px;width:80%', 'caption' => 'Under player' ) );
|
||||
contains( 'class="asciiplayer-container" style="height:200px"', $html, 'Legacy height remains on the player, so caption contributes to figure height.' );
|
||||
// No is_single gate: query lookahead supports Pages and archive results.
|
||||
reset_enqueues();
|
||||
$GLOBALS['wp_query'] = (object) array( 'posts' => array( (object) array( 'post_content' => 'Ordinary content' ), (object) array( 'post_content' => '[asciiplayer]/demo.cast[/asciiplayer]' ) ) );
|
||||
enqueue_content_assets();
|
||||
same( true, isset( $GLOBALS['ap_test']['enqueued_scripts']['lamgc-asciiplayer-view'] ), 'Shortcode in any queried post receives assets.' );
|
||||
reset_enqueues();
|
||||
$GLOBALS['wp_query']->posts = array( (object) array( 'post_content' => '<!-- wp:lamgc/asciiplayer {"source":"/demo.cast"} /-->' ) );
|
||||
enqueue_content_assets();
|
||||
same( true, isset( $GLOBALS['ap_test']['enqueued_scripts']['lamgc-asciiplayer-view'] ), 'Block in query receives assets.' );
|
||||
reset_enqueues();
|
||||
$GLOBALS['wp_query']->posts = array( (object) array( 'post_content' => 'No players' ), 12 );
|
||||
enqueue_content_assets();
|
||||
same( array(), $GLOBALS['ap_test']['enqueued_scripts'], 'Ordinary content does not enqueue runtime.' );
|
||||
render_shortcode( array(), '/widget.cast' );
|
||||
print_late_styles();
|
||||
print_late_styles();
|
||||
same( array( 'lamgc-asciiplayer-style' ), $GLOBALS['ap_test']['style_print_calls'], 'Late/widget styles print once in the footer.' );
|
||||
|
||||
require __DIR__ . '/uploads.php';
|
||||
|
||||
echo "OK: {$assertions} assertions passed.\n";
|
||||
} catch ( Throwable $error ) {
|
||||
fwrite( STDERR, $error->getMessage() . "\n" );
|
||||
exit( 1 );
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
<?php
|
||||
/** Upload validation contracts. Included by run.php after its assertion helpers. */
|
||||
|
||||
use function LamGC\Asciiplayer\allow_cast_upload_mime;
|
||||
use function LamGC\Asciiplayer\check_cast_filetype;
|
||||
use function LamGC\Asciiplayer\is_valid_cast_file;
|
||||
use function LamGC\Asciiplayer\validate_cast_upload;
|
||||
|
||||
use const LamGC\Asciiplayer\CAST_MAX_BYTES;
|
||||
use const LamGC\Asciiplayer\CAST_MAX_EVENTS;
|
||||
use const LamGC\Asciiplayer\CAST_MAX_LINE_BYTES;
|
||||
use const LamGC\Asciiplayer\CAST_MAX_V1_BYTES;
|
||||
use const LamGC\Asciiplayer\CAST_MIME;
|
||||
|
||||
function cast_contents_are_valid( $contents ) {
|
||||
$path = tempnam( sys_get_temp_dir(), 'ap-cast-' );
|
||||
try {
|
||||
file_put_contents( $path, $contents );
|
||||
return is_valid_cast_file( $path );
|
||||
} finally {
|
||||
unlink( $path );
|
||||
}
|
||||
}
|
||||
|
||||
$required_filters = array(
|
||||
'upload_mimes' => array( 'LamGC\\Asciiplayer\\allow_cast_upload_mime', 2 ),
|
||||
'wp_check_filetype_and_ext' => array( 'LamGC\\Asciiplayer\\check_cast_filetype', 5 ),
|
||||
'wp_handle_upload_prefilter' => array( 'LamGC\\Asciiplayer\\validate_cast_upload', 1 ),
|
||||
'wp_handle_sideload_prefilter' => array( 'LamGC\\Asciiplayer\\validate_cast_upload', 1 ),
|
||||
);
|
||||
foreach ( $GLOBALS['ap_test']['filters'] ?? array() as $filter ) {
|
||||
if ( isset( $required_filters[ $filter[0] ] ) ) {
|
||||
same( $required_filters[ $filter[0] ][0], $filter[1], 'Upload hook uses the intended callback.' );
|
||||
same( $required_filters[ $filter[0] ][1], $filter[3], 'Upload hook receives all required arguments.' );
|
||||
same( true, is_callable( $filter[1] ), 'Upload callback is callable.' );
|
||||
unset( $required_filters[ $filter[0] ] );
|
||||
}
|
||||
}
|
||||
same( array(), $required_filters, 'All safe-upload hooks are registered.' );
|
||||
|
||||
$mimes = array( 'jpg|jpeg' => 'image/jpeg', 'txt' => 'text/plain' );
|
||||
same( $mimes, allow_cast_upload_mime( $mimes ), 'Anonymous/non-uploaders get no extra MIME permissions.' );
|
||||
$GLOBALS['ap_test']['capabilities'] = array( 'upload_files' => true );
|
||||
same( array_merge( $mimes, array( 'cast' => CAST_MIME ) ), allow_cast_upload_mime( $mimes ), 'Only .cast receives the canonical MIME.' );
|
||||
same( $mimes, allow_cast_upload_mime( $mimes, 42 ), 'Explicit non-uploading user does not inherit current user permissions.' );
|
||||
$GLOBALS['ap_test']['user_capabilities'][42] = array( 'upload_files' => true );
|
||||
same( CAST_MIME, allow_cast_upload_mime( $mimes, 42 )['cast'], 'An explicit eligible user can upload casts.' );
|
||||
$GLOBALS['ap_test']['multisite'] = true;
|
||||
$GLOBALS['ap_test']['site_options']['upload_filetypes'] = 'jpg jpeg txt';
|
||||
same( $mimes, allow_cast_upload_mime( $mimes ), 'Multisite network extension restrictions remain in effect.' );
|
||||
$GLOBALS['ap_test']['site_options']['upload_filetypes'] = "jpg\ncast txt";
|
||||
same( CAST_MIME, allow_cast_upload_mime( $mimes )['cast'], 'Network-authorized cast uploads are available.' );
|
||||
$GLOBALS['ap_test']['multisite'] = false;
|
||||
|
||||
$v2 = '{"version":2,"width":80,"height":24}';
|
||||
$v3 = '{"version":3,"term":{"cols":100,"rows":30}}';
|
||||
$v1 = array( 'version' => 1, 'width' => 80, 'height' => 24, 'duration' => 1.5, 'stdout' => array( array( 0.1, "Hello\r\n" ), array( 1.4, 'World' ) ) );
|
||||
foreach ( array(
|
||||
'pretty v1' => json_encode( $v1, JSON_PRETTY_PRINT ),
|
||||
'v2 output' => $v2 . "\n[0.1,\"o\",\"Hello\\r\\n\"]\n",
|
||||
'v3 relative events' => $v3 . "\n[5,\"o\",\"Hello\"]\n[0.1,\"r\",\"120x40\"]\n[0,\"x\",\"0\"]\n",
|
||||
'v3 comments' => $v3 . "\n# comment before events\n[0,\"o\",\"ok\"]\n# trailing comment\n",
|
||||
'v2 input markers resize extensions' => $v2 . "\n[0,\"i\",\"x\"]\n[0,\"m\",\"A\"]\n[1,\"r\",\"90x25\"]\n[1,\"future\",\"data\"]",
|
||||
'CRLF' => $v2 . "\r\n[0,\"o\",\"hello\"]\r\n",
|
||||
'header only' => $v2,
|
||||
'unknown header fields' => '{"version":2,"width":80,"height":24,"future":{"key":true}}' . "\n[0,\"o\",\"ok\"]\n",
|
||||
'literal terminal markup' => $v2 . "\n[0,\"o\",\"<script> is plain terminal output</script>\"]\n",
|
||||
) as $description => $contents ) {
|
||||
same( true, cast_contents_are_valid( $contents ), 'Accept valid ' . $description . '.' );
|
||||
}
|
||||
same( true, is_valid_cast_file( dirname( __DIR__ ) . '/fixtures/hello.cast' ), 'Accept repository hello recording.' );
|
||||
same( true, is_valid_cast_file( dirname( __DIR__ ) . '/fixtures/resize.cast' ), 'Accept repository resize recording.' );
|
||||
|
||||
foreach ( array(
|
||||
'empty' => '',
|
||||
'plain text' => 'Hello world',
|
||||
'JSON object' => '{"message":"arbitrary JSON"}',
|
||||
'JSON list' => '[1,2,3]',
|
||||
'HTML' => '<!doctype html><script>alert(1)</script>',
|
||||
'SVG' => '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>',
|
||||
'unsupported version' => '{"version":4,"width":80,"height":24}',
|
||||
'string version' => '{"version":"2","width":80,"height":24}',
|
||||
'zero width' => '{"version":2,"width":0,"height":24}',
|
||||
'oversized width' => '{"version":2,"width":1001,"height":24}',
|
||||
'negative height' => '{"version":2,"width":80,"height":-1}',
|
||||
'fractional width' => '{"version":2,"width":80.5,"height":24}',
|
||||
'string width' => '{"version":2,"width":"80","height":24}',
|
||||
'v3 old dimensions' => '{"version":3,"width":80,"height":24}',
|
||||
'v3 terminal array' => '{"version":3,"term":[100,30]}',
|
||||
'v1 absent stdout' => "{\n\"version\":1,\"width\":80,\"height\":24\n}",
|
||||
'v1 stdout object' => "{\n\"version\":1,\"width\":80,\"height\":24,\"stdout\":{\"0\":[0,\"x\"]}\n}",
|
||||
'compact v1 unsupported by bundled player' => json_encode( $v1 ),
|
||||
'large compact v1 unsupported by bundled player' => json_encode( array_merge( $v1, array( 'title' => str_repeat( 'a', CAST_MAX_LINE_BYTES + 1 ) ) ) ),
|
||||
'v1 negative delay' => json_encode( array_merge( $v1, array( 'stdout' => array( array( -1, 'x' ) ) ) ), JSON_PRETTY_PRINT ),
|
||||
'v1 malformed later frame' => json_encode( array_merge( $v1, array( 'stdout' => array( array( 0, 'ok' ), array( 0, array( 'x' ) ) ) ) ), JSON_PRETTY_PRINT ),
|
||||
'v1 extra frame element' => json_encode( array_merge( $v1, array( 'stdout' => array( array( 0, 'ok', 'extra' ) ) ) ), JSON_PRETTY_PRINT ),
|
||||
'v1 bad duration' => json_encode( array_merge( $v1, array( 'duration' => '1' ) ), JSON_PRETTY_PRINT ),
|
||||
'negative event time' => $v2 . "\n[-1,\"o\",\"bad\"]\n",
|
||||
'string event time' => $v2 . "\n[\"0\",\"o\",\"bad\"]\n",
|
||||
'boolean event time' => $v2 . "\n[false,\"o\",\"bad\"]\n",
|
||||
'infinite time' => $v2 . "\n[1e999,\"o\",\"bad\"]\n",
|
||||
'milliseconds overflow' => $v2 . "\n[1e308,\"o\",\"bad\"]\n",
|
||||
'v3 cumulative milliseconds overflow' => $v3 . "\n[1e305,\"o\",\"first\"]\n[1e305,\"o\",\"second\"]\n",
|
||||
'v2 out of order' => $v2 . "\n[2,\"o\",\"first\"]\n[1,\"o\",\"second\"]\n",
|
||||
'event object' => $v2 . "\n{\"0\":0,\"1\":\"o\",\"2\":\"bad\"}\n",
|
||||
'missing event data' => $v2 . "\n[0,\"o\"]\n",
|
||||
'extra event element' => $v2 . "\n[0,\"o\",\"bad\",1]\n",
|
||||
'event data array' => $v2 . "\n[0,\"o\",[\"bad\"]]\n",
|
||||
'empty event type' => $v2 . "\n[0,\"\",\"bad\"]\n",
|
||||
'zero resize' => $v2 . "\n[0,\"r\",\"0x20\"]\n",
|
||||
'oversized resize' => $v2 . "\n[0,\"r\",\"2000x20\"]\n",
|
||||
'malformed resize' => $v2 . "\n[0,\"r\",\"80,24\"]\n",
|
||||
'bad later JSON' => $v2 . "\n[0,\"o\",\"ok\"]\n[1,\"o\",\"truncated\"\n",
|
||||
'trailing HTML' => $v2 . "\n[0,\"o\",\"ok\"]\n<script>alert(1)</script>\n",
|
||||
'trailing JSON object' => $v2 . "\n[0,\"o\",\"ok\"]\n{\"unrelated\":true}\n",
|
||||
'blank event line' => $v2 . "\n\n",
|
||||
'indented event ignored by bundled player' => $v2 . "\n [0,\"o\",\"invisible\"]\n",
|
||||
'v2 comment' => $v2 . "\n# comment\n",
|
||||
'v3 indented comment' => $v3 . "\n # not a comment\n",
|
||||
'UTF-8 BOM' => "\xef\xbb\xbf" . $v2,
|
||||
'invalid UTF-8' => $v2 . "\n[0,\"o\",\"\xff\"]\n",
|
||||
'oversized JSONL line' => $v2 . "\n[0,\"o\",\"" . str_repeat( 'a', CAST_MAX_LINE_BYTES ) . "\"]\n",
|
||||
'oversized comment line' => $v3 . "\n#" . str_repeat( 'a', CAST_MAX_LINE_BYTES ) . "\n",
|
||||
'deep JSON' => $v2 . "\n[0,\"o\"," . str_repeat( '[', 20 ) . '0' . str_repeat( ']', 20 ) . "]\n",
|
||||
) as $description => $contents ) {
|
||||
same( false, cast_contents_are_valid( $contents ), 'Reject ' . $description . '.' );
|
||||
}
|
||||
same( false, is_valid_cast_file( dirname( __DIR__ ) . '/fixtures/malformed.cast' ), 'Reject repository malformed recording.' );
|
||||
same( false, is_valid_cast_file( '/does-not-exist/asciicast.cast' ), 'Reject missing files.' );
|
||||
same( false, is_valid_cast_file( __DIR__ ), 'Reject directories.' );
|
||||
same( false, is_valid_cast_file( 'data://text/plain,' . $v2 ), 'Reject stream wrappers before opening.' );
|
||||
same( false, is_valid_cast_file( null ), 'Reject missing temporary upload path.' );
|
||||
same( true, cast_contents_are_valid( $v2 . "\n" . str_repeat( "[0,\"o\",\"x\"]\n", CAST_MAX_EVENTS ) ), 'Accept the documented event-count boundary.' );
|
||||
same( false, cast_contents_are_valid( $v2 . "\n" . str_repeat( "[0,\"o\",\"x\"]\n", CAST_MAX_EVENTS + 1 ) ), 'Reject excessive event count.' );
|
||||
same( false, cast_contents_are_valid( json_encode( array_merge( $v1, array( 'title' => str_repeat( 'a', CAST_MAX_V1_BYTES ) ) ), JSON_PRETTY_PRINT ) ), 'Bound whole-document legacy decoding.' );
|
||||
|
||||
$path = tempnam( sys_get_temp_dir(), 'ap-cast-' );
|
||||
try {
|
||||
$handle = fopen( $path, 'wb' );
|
||||
ftruncate( $handle, CAST_MAX_BYTES + 1 );
|
||||
fclose( $handle );
|
||||
same( false, is_valid_cast_file( $path ), 'Reject files over the byte limit before reading their contents.' );
|
||||
file_put_contents( $path, $v2 . "\n[0,\"o\",\"ok\"]\n" );
|
||||
clearstatcache( true, $path );
|
||||
$upload = array( 'name' => 'recording.cast', 'tmp_name' => $path, 'error' => 0, 'type' => 'text/plain', 'size' => 1 );
|
||||
same( $upload, validate_cast_upload( $upload ), 'Valid content passes without trusting or changing browser MIME or size.' );
|
||||
$denied = array( 'ext' => false, 'type' => false, 'proper_filename' => false );
|
||||
$approved = array( 'ext' => 'cast', 'type' => CAST_MIME, 'proper_filename' => false );
|
||||
foreach ( array( 'text/plain', 'application/json', 'application/octet-stream', false ) as $detected_mime ) {
|
||||
same( $approved, check_cast_filetype( $denied, $path, 'recording.cast', null, $detected_mime ), 'Content validation safely handles generic fileinfo guesses.' );
|
||||
}
|
||||
same( $approved, check_cast_filetype( $denied, $path, 'recording.CAST' ), 'Uppercase cast extension is supported.' );
|
||||
same( $denied, check_cast_filetype( $denied, $path, 'recording.cast', array() ), 'An explicitly empty MIME allow-list stays empty.' );
|
||||
same( $denied, check_cast_filetype( $denied, $path, 'recording.cast', array( 'txt' => 'text/plain' ) ), 'An explicit MIME allow-list excluding cast remains restricted.' );
|
||||
same( $denied, check_cast_filetype( $denied, $path, 'recording.cast', array( 'cast' => 'text/plain' ) ), 'Only our canonical allowed type can receive the MIME override.' );
|
||||
$GLOBALS['ap_test']['allowed_mimes'] = array( 'txt' => 'text/plain' );
|
||||
same( $denied, check_cast_filetype( $denied, $path, 'recording.cast', array( 'cast' => CAST_MIME ) ), 'An explicit allow-list cannot bypass a later global MIME restriction.' );
|
||||
same( true, is_string( validate_cast_upload( $upload )['error'] ), 'Prefilter also preserves later global MIME restrictions.' );
|
||||
unset( $GLOBALS['ap_test']['allowed_mimes'] );
|
||||
$unrelated = array( 'ext' => 'svg', 'type' => 'image/svg+xml', 'proper_filename' => 'x.svg' );
|
||||
foreach ( array( 'x.json', 'x.html', 'x.svg', 'x.cast.php', "x.cast\n" ) as $filename ) {
|
||||
same( $unrelated, check_cast_filetype( $unrelated, $path, $filename ), 'Other extensions and double-extension executables remain untouched.' );
|
||||
}
|
||||
same( true, is_string( validate_cast_upload( array_merge( $upload, array( 'tmp_name' => '/missing' ) ) )['error'] ), 'Missing temporary upload fails closed.' );
|
||||
$GLOBALS['ap_test']['capabilities'] = array();
|
||||
same( true, is_string( validate_cast_upload( $upload )['error'] ), 'Upload permissions are enforced for valid content too.' );
|
||||
same( $denied, check_cast_filetype( $approved, $path, 'recording.cast' ), 'MIME override never grants upload capability.' );
|
||||
$GLOBALS['ap_test']['capabilities'] = array( 'upload_files' => true, 'unfiltered_upload' => true );
|
||||
file_put_contents( $path, $v2 . "\n<script>alert(1)</script>\n" );
|
||||
clearstatcache( true, $path );
|
||||
same( true, is_string( validate_cast_upload( $upload )['error'] ), 'Malformed content fails even with unfiltered_upload.' );
|
||||
same( $denied, check_cast_filetype( $approved, $path, 'recording.cast' ), 'Invalid content cannot keep a previous MIME approval.' );
|
||||
$other_upload = array_merge( $upload, array( 'name' => 'ordinary.txt' ) );
|
||||
same( $other_upload, validate_cast_upload( $other_upload ), 'Other extensions keep core upload behavior.' );
|
||||
$existing_error = array_merge( $upload, array( 'error' => 'Rejected by another plugin.' ) );
|
||||
same( $existing_error, validate_cast_upload( $existing_error ), 'Existing upload errors are preserved.' );
|
||||
$php_error = array_merge( $upload, array( 'error' => 3 ) );
|
||||
same( $php_error, validate_cast_upload( $php_error ), 'PHP partial-upload errors are preserved.' );
|
||||
} finally {
|
||||
unlink( $path );
|
||||
}
|
||||
|
||||
unset( $GLOBALS['ap_test']['capabilities'], $GLOBALS['ap_test']['user_capabilities'], $GLOBALS['ap_test']['multisite'], $GLOBALS['ap_test']['site_options'], $GLOBALS['ap_test']['allowed_mimes'] );
|
||||
Reference in New Issue
Block a user