feat: lit/divi-insert and lit/divi-update

All-or-nothing at ability level (S39), duplicate ids refused (S14),
set and attrs on the same path refused (S38), invalid_attr_path error.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01At3V6SjwbMe6eMzVGW3Hs7
This commit is contained in:
2026-09-26 15:15:37 +02:00
co-authored by Claude Opus 5.5
parent b8cb01812e
commit 110beb7698
11 changed files with 711 additions and 5 deletions
+2 -1
View File
@@ -20,7 +20,8 @@ des verbundenen WordPress-Benutzers.
Direkt sichtbar: `lit-guide`, `lit-site-status`, `lit-content-types`, `lit-content-query`, Direkt sichtbar: `lit-guide`, `lit-site-status`, `lit-content-types`, `lit-content-query`,
`lit-content-get`, `lit-content-create`, `lit-content-update`, `lit-post-publish`, `lit-media-search`, `lit-content-get`, `lit-content-create`, `lit-content-update`, `lit-post-publish`, `lit-media-search`,
`lit-media-preview`, `lit-media-download`, `lit-media-upload-from-url`, `lit-page-render-summary`, `lit-media-preview`, `lit-media-download`, `lit-media-upload-from-url`, `lit-page-render-summary`,
`lit-divi-outline`, `lit-divi-node-get`, `lit-divi-catalog`, `lit-divi-design-system`. `lit-divi-outline`, `lit-divi-node-get`, `lit-divi-catalog`, `lit-divi-design-system`, `lit-divi-insert`,
`lit-divi-update`.
Welche Tools direkt sichtbar sind, lässt sich unter Einstellungen → LIT MCP → Tools ändern (außer bei Welche Tools direkt sichtbar sind, lässt sich unter Einstellungen → LIT MCP → Tools ändern (außer bei
`lit-guide`, das immer direkt bleibt). `lit-guide`, das immer direkt bleibt).
+18
View File
@@ -101,6 +101,24 @@ final class Errors
return self::make('unsupported', $message, $hint, 400); return self::make('unsupported', $message, $hint, 400);
} }
/**
* Unknown Divi attribute paths (spec §5.4, §8.2). $fields names every problem of the call,
* the unknown paths with their closest known ones.
*
* @param array<string, string> $fields Input path => problem.
*/
public static function invalidAttrPath(array $fields): WP_Error
{
return self::make(
'invalid_attr_path',
'Unbekannte Attributpfade; nichts wurde gespeichert.',
'Vorschläge unter fields prüfen; alle gültigen Pfade eines Moduls liefert lit/divi-catalog '
. '(direkt: lit-divi-catalog) mit module.',
400,
['fields' => $fields]
);
}
/** /**
* A write failed and was rolled back completely. * A write failed and was rolled back completely.
* *
@@ -116,6 +116,7 @@ final class Composer
} }
} }
$this->overlaps($block->shortName(), $change, $field);
$attrs = $this->presetAndAttrs($block->name(), $attrs, $change, $field); $attrs = $this->presetAndAttrs($block->name(), $attrs, $change, $field);
if (array_key_exists('label', $change)) { if (array_key_exists('label', $change)) {
$attrs = $change['label'] === null || $change['label'] === '' $attrs = $change['label'] === null || $change['label'] === ''
@@ -126,6 +127,39 @@ final class Composer
return ['attrs' => $attrs, 'errors' => $this->errors, 'invalid_paths' => $this->invalidPaths]; return ['attrs' => $attrs, 'errors' => $this->errors, 'invalid_paths' => $this->invalidPaths];
} }
/**
* Ruling S38: one change may not reach the same attribute path through "set" and "attrs" –
* composite values are replaced whole per breakpoint, so combining them would silently lose
* sub-keys. Paths overlap when equal or when one lies below the other.
*
* @param array<array-key, mixed> $change
*/
private function overlaps(string $type, array $change, string $field): void
{
$set = $change['set'] ?? null;
$full = $change['attrs'] ?? null;
if (! is_array($set) || ! is_array($full) || $set === [] || $full === []) {
return;
}
$short = $this->shortform->paths($type, array_map('strval', array_keys($set)));
foreach (array_keys($full) as $path) {
$path = (string) $path;
foreach ($short as $name => $shortPath) {
if (
$path === $shortPath || str_starts_with($path, $shortPath . '.')
|| str_starts_with($shortPath, $path . '.')
) {
$this->errors[$field . '.attrs.' . $path] = sprintf(
'derselbe Attributpfad wird auch über set.%s geändert; bitte als zwei Änderungen senden',
$name
);
break;
}
}
}
}
/** Admin label for a new module: "<Abschnitt> – <Modultitel>" or the title alone. */ /** Admin label for a new module: "<Abschnitt> – <Modultitel>" or the title alone. */
public function autoLabel(string $name, string $context): string public function autoLabel(string $name, string $context): string
{ {
@@ -72,6 +72,25 @@ final class ShortformWriter
return ['attrs' => $attrs, 'errors' => $errors]; return ['attrs' => $attrs, 'errors' => $errors];
} }
/**
* Attribute paths the given short-form fields of $type write to (unknown fields left out).
*
* @param list<string> $names Field names.
* @return array<string, string> Field => attribute path.
*/
public function paths(string $type, array $names): array
{
$fields = $this->modules === null ? ShortformMap::fields($type) : ($this->modules[$type] ?? []);
$paths = [];
foreach ($names as $name) {
if (isset($fields[$name]['path'])) {
$paths[$name] = (string) $fields[$name]['path'];
}
}
return $paths;
}
/** /**
* The short-form color check (ruling S13; Task 3 reuses it for background_color): a * The short-form color check (ruling S13; Task 3 reuses it for background_color): a
* placeholder or reference that is a color reference, or a plain CSS color – checked * placeholder or reference that is a color reference, or a plain CSS color – checked
+13 -2
View File
@@ -4,11 +4,17 @@ declare(strict_types=1);
namespace LIT\MCP\Integrations\Divi; namespace LIT\MCP\Integrations\Divi;
use LIT\MCP\ChangeLog\ChangeLog;
use LIT\MCP\Integrations\Divi\Design\DesignSystemReader; use LIT\MCP\Integrations\Divi\Design\DesignSystemReader;
use LIT\MCP\Integrations\Divi\Design\DiviDesignSystemAbility; use LIT\MCP\Integrations\Divi\Design\DiviDesignSystemAbility;
use LIT\MCP\Integrations\Divi\Pages\DiviComposition;
use LIT\MCP\Integrations\Divi\Pages\DiviInsertAbility;
use LIT\MCP\Integrations\Divi\Pages\DiviNodeGetAbility; use LIT\MCP\Integrations\Divi\Pages\DiviNodeGetAbility;
use LIT\MCP\Integrations\Divi\Pages\DiviOutlineAbility; use LIT\MCP\Integrations\Divi\Pages\DiviOutlineAbility;
use LIT\MCP\Integrations\Divi\Pages\DiviPageLoader; use LIT\MCP\Integrations\Divi\Pages\DiviPageLoader;
use LIT\MCP\Integrations\Divi\Pages\DiviSaver;
use LIT\MCP\Integrations\Divi\Pages\DiviUpdateAbility;
use LIT\MCP\Integrations\Divi\Pages\DiviWriter;
use LIT\MCP\Integrations\Divi\Schema\DiviCatalogAbility; use LIT\MCP\Integrations\Divi\Schema\DiviCatalogAbility;
use LIT\MCP\Integrations\Divi\Schema\DiviModules; use LIT\MCP\Integrations\Divi\Schema\DiviModules;
use LIT\MCP\Integrations\Integration; use LIT\MCP\Integrations\Integration;
@@ -16,14 +22,15 @@ use LIT\MCP\Integrations\WordPress\Schema\ContentSchema;
/** /**
* Divi 5 pages (spec §5, Etappe 2). Only available when the Divi 5 builder is loaded * Divi 5 pages (spec §5, Etappe 2). Only available when the Divi 5 builder is loaded
* (spec §2 principle 4); Divi 4 is never edited (spec §3.4). * (spec §2 principle 4); Divi 4 is never edited (spec §3.4). The write abilities share one
* DiviWriter; each binds the composition to its entry via DiviWriter::composition().
*/ */
final class DiviIntegration implements Integration final class DiviIntegration implements Integration
{ {
private DiviModules $modules; private DiviModules $modules;
private DesignSystemReader $design; private DesignSystemReader $design;
public function __construct(private ContentSchema $schema) public function __construct(private ContentSchema $schema, private ChangeLog $log)
{ {
$this->modules = new DiviModules(); $this->modules = new DiviModules();
$this->design = new DesignSystemReader(); $this->design = new DesignSystemReader();
@@ -42,12 +49,16 @@ final class DiviIntegration implements Integration
public function abilities(): array public function abilities(): array
{ {
$loader = new DiviPageLoader($this->schema); $loader = new DiviPageLoader($this->schema);
$composition = new DiviComposition($this->modules, $this->design);
$writer = new DiviWriter($loader, new DiviSaver(), $this->log, $this->design, $composition);
return [ return [
new DiviOutlineAbility($loader, $this->design), new DiviOutlineAbility($loader, $this->design),
new DiviNodeGetAbility($loader, $this->design), new DiviNodeGetAbility($loader, $this->design),
new DiviCatalogAbility($this->modules), new DiviCatalogAbility($this->modules),
new DiviDesignSystemAbility($this->design), new DiviDesignSystemAbility($this->design),
new DiviInsertAbility($writer),
new DiviUpdateAbility($writer),
]; ];
} }
} }
@@ -0,0 +1,130 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Integrations\Divi\Pages;
use LIT\MCP\Abilities\Ability;
use LIT\MCP\Abilities\Errors;
use LIT\MCP\Abilities\ToolResult;
use WP_Error;
/**
* lit/divi-insert: inserts nodes in short and/or full form – modules, rows or whole sections –
* at parent / before / after (spec §5.7). All or nothing (ruling S39): the whole input is
* validated first and every error is returned together; the blocks come only from Composer
* (client values pass its choke point) and enter the tree only through TreeEditor::insert(),
* which also wraps the first section of an empty page in divi/placeholder (ruling S9).
*/
final class DiviInsertAbility implements Ability
{
public function __construct(private DiviWriter $writer)
{
}
public function name(): string
{
return 'lit/divi-insert';
}
public function label(): string
{
return 'Divi-Knoten einfügen';
}
public function description(): string
{
return 'Fügt Divi-Knoten ein: Module, Zeilen oder ganze Abschnitte in Kurzform (z. B. {"type": "button", '
. '"text": "Termin buchen", "url": "/kontakt", "preset": "CTA primär"}) und/oder Vollform ("attrs"). '
. 'Position über parent, before oder after (Pfad-IDs aus lit-divi-outline), sonst ans Seitenende. '
. 'Platzhalter wie {{color:primary}} statt fester Werte. tree_rev ist Pflicht; alles oder nichts. '
. 'Format: lit-guide topic "divi-shortform".';
}
public function inputSchema(): array
{
return [
'type' => 'object',
'properties' => array_merge(DiviWriter::inputProperties(), [
'nodes' => [
'type' => 'array',
'minItems' => 1,
'maxItems' => 20,
'items' => ['type' => 'object'],
'description' => 'Einzufügende Knoten in Reihenfolge; Abschnitte mit rows/modules, Zeilen mit '
. 'columns und modules, Module mit Kurzform-Feldern, items (Kind-Module) und attrs.',
],
], DiviWriter::positionProperties()),
'required' => ['post_id', 'tree_rev', 'nodes'],
'additionalProperties' => false,
];
}
public function outputSchema(): ?array
{
return ToolResult::schema(['tree_rev' => ['type' => 'string']], ['tree_rev']);
}
public function annotations(): array
{
return ['readonly' => false, 'destructive' => false, 'idempotent' => false];
}
public function isDirect(): bool
{
return true;
}
public function permission(array $input): bool|WP_Error
{
$page = $this->writer->page($input);
return $page instanceof WP_Error ? $page : true;
}
public function execute(array $input): mixed
{
$page = $this->writer->page($input);
if ($page instanceof WP_Error) {
return $page;
}
$composition = $this->writer->composition($page);
$editor = $composition->editor();
$position = $editor->position($page->index, $input);
if (is_string($position)) {
// The nodes are checked against their parent – without a valid position there is none.
return Errors::invalidInput('Ungültige Position; nichts wurde gespeichert.', ['position' => $position]);
}
$context = DiviWriter::sectionLabel($page->index, $position['parent']);
$nodes = is_array($input['nodes'] ?? null) ? array_values($input['nodes']) : [];
if ($nodes === []) {
return Errors::invalidInput('Keine Knoten angegeben; nichts wurde gespeichert.', [
'nodes' => 'mindestens ein Knoten',
]);
}
$composed = $composition->composer()->compose($nodes, $position['parent'], 'nodes', $context);
if ($composed['errors'] !== []) {
return $composed['invalid_paths'] !== []
? Errors::invalidAttrPath($composed['errors'])
: Errors::invalidInput('Knoten sind ungültig; nichts wurde gespeichert.', $composed['errors']);
}
$violation = $editor->insert($position, $composed['blocks']);
if ($violation !== null) {
return Errors::invalidInput(
'Knoten passen nicht an diese Stelle; nichts wurde gespeichert.',
['nodes' => $violation]
);
}
$change = new DiviChange(sprintf('%d Divi-Knoten eingefügt', count($composed['blocks'])));
foreach ($composed['blocks'] as $block) {
$change->changed($block, 'inserted');
}
return $this->writer->save($this->name(), $page, $change, $input);
}
}
@@ -0,0 +1,175 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Integrations\Divi\Pages;
use LIT\MCP\Abilities\Ability;
use LIT\MCP\Abilities\Errors;
use LIT\MCP\Abilities\ToolResult;
use LIT\MCP\Integrations\Divi\BlockTree\Block;
use WP_Error;
/**
* lit/divi-update: sets or removes values of existing nodes – short-form fields ("set"), full
* form ("attrs", null removes a path or breakpoint), preset and admin label (spec §5.7). Several
* nodes per call, all or nothing (ruling S39): every change is validated first and all errors
* come back together; only then are the attributes Composer::update() computed set. A node may
* appear once per call (ruling S14); set and attrs of one change must not reach the same path
* (ruling S38, checked by Composer::update()).
*/
final class DiviUpdateAbility implements Ability
{
public function __construct(private DiviWriter $writer)
{
}
public function name(): string
{
return 'lit/divi-update';
}
public function label(): string
{
return 'Divi-Knoten ändern';
}
public function description(): string
{
return 'Ändert vorhandene Divi-Knoten: changes = Liste von {id, set: {Kurzform-Felder}, attrs: {Attributpfad: '
. '{Breakpoint: Wert}}, preset, label}. null entfernt einen Wert. Nicht genannte Einstellungen bleiben '
. 'unverändert. Jeder Knoten nur einmal pro Aufruf; denselben Pfad nicht zugleich über set und attrs. '
. 'tree_rev aus lit-divi-outline ist Pflicht; alles oder nichts.';
}
public function inputSchema(): array
{
return [
'type' => 'object',
'properties' => array_merge(DiviWriter::inputProperties(), [
'changes' => [
'type' => 'array',
'minItems' => 1,
'maxItems' => 50,
'items' => [
'type' => 'object',
'properties' => [
'id' => ['type' => 'string'],
'set' => ['type' => 'object', 'description' => 'Kurzform-Felder, z. B. {"text": "Neu"}.'],
'attrs' => [
'type' => 'object',
'description' => 'Vollform: Attributpfad → Breakpoint-Werte.',
],
'preset' => ['type' => ['string', 'null'], 'description' => 'Preset-Name; null entfernt.'],
'label' => [
'type' => ['string', 'null'],
'description' => 'Admin-Label im Divi-Builder; null entfernt.',
],
],
'required' => ['id'],
'additionalProperties' => false,
],
],
]),
'required' => ['post_id', 'tree_rev', 'changes'],
'additionalProperties' => false,
];
}
public function outputSchema(): ?array
{
return ToolResult::schema(['tree_rev' => ['type' => 'string']], ['tree_rev']);
}
public function annotations(): array
{
return ['readonly' => false, 'destructive' => false, 'idempotent' => true];
}
public function isDirect(): bool
{
return true;
}
public function permission(array $input): bool|WP_Error
{
$page = $this->writer->page($input);
return $page instanceof WP_Error ? $page : true;
}
public function execute(array $input): mixed
{
$page = $this->writer->page($input);
if ($page instanceof WP_Error) {
return $page;
}
$changes = is_array($input['changes'] ?? null) ? array_values($input['changes']) : [];
if ($changes === []) {
return Errors::invalidInput('Keine Änderungen angegeben; nichts wurde gespeichert.', [
'changes' => 'mindestens eine Änderung',
]);
}
$composer = $this->writer->composition($page)->composer();
$errors = [];
$invalidPaths = false;
/** @var array<string, int> $seen id => position of its first change */
$seen = [];
/** @var list<array{0: Block, 1: array<string, mixed>}> $updates */
$updates = [];
foreach ($changes as $position => $change) {
$field = sprintf('changes[%d]', $position);
if (! is_array($change)) {
$errors[$field] = 'Objekt mit id erwartet';
continue;
}
$id = is_string($change['id'] ?? null) ? $change['id'] : '';
if ($id !== '' && isset($seen[$id])) {
// Ruling S14: a second change of the same node would overwrite the first silently.
$errors[$field . '.id'] = sprintf(
'Knoten "%s" steht schon in changes[%d]; alle Änderungen eines Knotens in einer Änderung bündeln',
$id,
$seen[$id]
);
continue;
}
$block = $id === '' ? null : $page->index->find($id);
if ($id !== '') {
$seen[$id] = $position;
}
if ($block === null) {
$errors[$field . '.id'] = sprintf('Knoten "%s" gibt es nicht (lit-divi-outline neu lesen)', $id);
continue;
}
$result = $composer->update($block, $change, $field);
$errors += $result['errors'];
$invalidPaths = $invalidPaths || $result['invalid_paths'] !== [];
$updates[] = [$block, $result['attrs']];
}
if ($errors !== []) {
return $invalidPaths
? Errors::invalidAttrPath($errors)
: Errors::invalidInput('Änderungen sind ungültig; nichts wurde gespeichert.', $errors);
}
$updates = array_values(array_filter(
$updates,
static fn (array $update): bool => $update[1] !== $update[0]->attrs()
));
$change = new DiviChange(sprintf('%d Divi-Knoten geändert', count($updates)));
foreach ($updates as [$block, $attrs]) {
// Composer::update() output: every client value already passed the choke point.
$block->setAttrs($attrs);
$change->changed($block, 'updated');
}
return $this->writer->save($this->name(), $page, $change, $input);
}
}
+1 -1
View File
@@ -68,7 +68,7 @@ final class Plugin
new CoreIntegration(self::pluginDir() . '/docs/guides'), new CoreIntegration(self::pluginDir() . '/docs/guides'),
new WordPressIntegration($schema, $changeLog), new WordPressIntegration($schema, $changeLog),
new MediaIntegration($schema, $changeLog, $limits), new MediaIntegration($schema, $changeLog, $limits),
new DiviIntegration($schema) new DiviIntegration($schema, $changeLog)
); );
$policy = ExposurePolicy::fromOption(); $policy = ExposurePolicy::fromOption();
@@ -183,6 +183,26 @@ final class ComposerTest extends TestCase
self::assertStringContainsString('nur lesbar', $readOnly['errors']['changes[2].id']); self::assertStringContainsString('nur lesbar', $readOnly['errors']['changes[2].id']);
} }
/** Ruling S38: one change may not reach the same attribute path through set and attrs. */
public function testUpdateRefusesSetAndAttrsOnTheSamePath(): void
{
$block = Block::create('divi/button', ['button' => ['innerContent' => ['desktop' => ['value' => ['text' => 'Alt']]]]]);
$result = ComposeFixture::composer()->update($block, [
'set' => ['text' => 'Neu'],
'attrs' => ['button.innerContent' => ['desktop' => ['linkUrl' => '/kontakt']]],
], 'changes[0]');
self::assertStringContainsString('set.text', $result['errors']['changes[0].attrs.button.innerContent']);
self::assertSame([], $result['invalid_paths']);
$separate = ComposeFixture::composer()->update($block, [
'set' => ['text' => 'Neu'],
'attrs' => ['button.decoration.background' => ['desktop' => ['color' => '#ffffff']]],
], 'changes[0]');
self::assertSame([], $separate['errors'], 'different paths may be combined');
}
/** Ruling S13: labels go through the choke point; a label that fails is an error, never stored raw. */ /** Ruling S13: labels go through the choke point; a label that fails is an error, never stored raw. */
public function testLabelsAreCleanedOrReported(): void public function testLabelsAreCleanedOrReported(): void
{ {
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace LIT\MCP\Tests\Unit\Integrations\Divi; namespace LIT\MCP\Tests\Unit\Integrations\Divi;
use LIT\MCP\Abilities\Ability; use LIT\MCP\Abilities\Ability;
use LIT\MCP\ChangeLog\ChangeLog;
use LIT\MCP\Integrations\Divi\DiviIntegration; use LIT\MCP\Integrations\Divi\DiviIntegration;
use LIT\MCP\Integrations\WordPress\Schema\ContentSchema; use LIT\MCP\Integrations\WordPress\Schema\ContentSchema;
use LIT\MCP\Tests\Unit\TestCase; use LIT\MCP\Tests\Unit\TestCase;
@@ -18,11 +19,13 @@ final class DiviIntegrationTest extends TestCase
'lit/divi-node-get', 'lit/divi-node-get',
'lit/divi-catalog', 'lit/divi-catalog',
'lit/divi-design-system', 'lit/divi-design-system',
'lit/divi-insert',
'lit/divi-update',
]; ];
public function testProvidesTheDiviAbilitiesOnlyWithDivi5(): void public function testProvidesTheDiviAbilitiesOnlyWithDivi5(): void
{ {
$integration = new DiviIntegration(Mockery::mock(ContentSchema::class)); $integration = new DiviIntegration(Mockery::mock(ContentSchema::class), Mockery::mock(ChangeLog::class));
self::assertSame('divi', $integration->id()); self::assertSame('divi', $integration->id());
self::assertFalse($integration->isAvailable(), 'no Divi classes in unit tests'); self::assertFalse($integration->isAvailable(), 'no Divi classes in unit tests');
@@ -0,0 +1,295 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Tests\Unit\Integrations\Divi\Pages;
use Brain\Monkey\Functions;
use LIT\MCP\Abilities\Rev;
use LIT\MCP\ChangeLog\ChangeLog;
use LIT\MCP\Integrations\Divi\BlockTree\NodeIndex;
use LIT\MCP\Integrations\Divi\BlockTree\Parser;
use LIT\MCP\Integrations\Divi\Design\DesignSystemReader;
use LIT\MCP\Integrations\Divi\Pages\DiviComposition;
use LIT\MCP\Integrations\Divi\Pages\DiviInsertAbility;
use LIT\MCP\Integrations\Divi\Pages\DiviPageLoader;
use LIT\MCP\Integrations\Divi\Pages\DiviSaver;
use LIT\MCP\Integrations\Divi\Pages\DiviUpdateAbility;
use LIT\MCP\Integrations\Divi\Pages\DiviWriter;
use LIT\MCP\Integrations\Divi\Schema\DiviModules;
use LIT\MCP\Tests\Unit\Integrations\Divi\Compose\ComposeFixture;
use LIT\MCP\Tests\Unit\Integrations\Divi\Design\DesignSystemTest;
use LIT\MCP\Tests\Unit\Integrations\Divi\Schema\ModuleCatalogTest;
use LIT\MCP\Tests\Unit\TestCase;
use Mockery;
use WP_Error;
use WP_Post;
final class DiviWriteAbilitiesTest extends TestCase
{
private WP_Post $post;
private string $original = '';
/** @var list<string> Contents handed to DiviSaver::save(). */
private array $saved = [];
private DiviWriter $writer;
protected function setUp(): void
{
parent::setUp();
$this->original = DiviPageLoaderTest::fixture('synthetic-basic.html');
$this->post = DiviPageLoaderTest::givenPost($this->original);
Functions\when('get_preview_post_link')->justReturn('https://kunde.test/?page_id=7&preview=true');
$modules = Mockery::mock(DiviModules::class);
$modules->allows('catalog')->andReturn(ModuleCatalogTest::sampleCatalog());
$modules->allows('builderVersion')->andReturn('5.2.1');
$design = Mockery::mock(DesignSystemReader::class);
$design->allows('read')->andReturn(DesignSystemTest::sample());
$composition = new DiviComposition($modules, $design, ComposeFixture::sanitizer(), ComposeFixture::media());
$saver = Mockery::mock(DiviSaver::class);
$saver->allows('save')->andReturnUsing(function (WP_Post $post, string $content): array {
$this->saved[] = $content;
$post->post_content = $content;
return ['revision_id' => 811, 'warnings' => []];
});
$log = Mockery::mock(ChangeLog::class);
$log->allows('record')->andReturn(4711);
$this->writer = new DiviWriter(
new DiviPageLoader(DiviPageLoaderTest::schema()),
$saver,
$log,
$design,
$composition
);
}
private function treeRev(): string
{
return Rev::of($this->original);
}
private function insert(): DiviInsertAbility
{
return new DiviInsertAbility($this->writer);
}
private function update(): DiviUpdateAbility
{
return new DiviUpdateAbility($this->writer);
}
/** @return array<string, mixed> The structured error the client sees (message JSON, spec §8.2). */
private static function clientError(WP_Error $error): array
{
return (array) json_decode($error->get_error_message(), true);
}
public function testInsertComposesAndSavesWithTreeRevAndPostRev(): void
{
$result = $this->insert()->execute([
'post_id' => 7,
'tree_rev' => $this->treeRev(),
'after' => 's0.r0.c1.m1',
'nodes' => [['type' => 'text', 'content' => '<p>Neu</p>']],
]);
self::assertTrue($result['ok'], (string) json_encode($result));
self::assertCount(1, $this->saved);
self::assertSame([['id' => 's0.r0.c1.m2', 'type' => 'divi/text', 'action' => 'inserted', 'label' => 'Hero – Text']], $result['changed']);
self::assertSame(Rev::of($this->saved[0]), $result['tree_rev']);
self::assertSame(Rev::ofPost($this->post), $result['rev']);
self::assertSame(811, $result['revision_id']);
self::assertSame(4711, $result['log_id']);
self::assertStringStartsWith('s0 section "Hero"', (string) $result['outline']);
self::assertSame('https://kunde.test/?page_id=7&et_fb=1', $result['edit_url']);
// Byte identity: only the new block was added, every other byte is unchanged.
$inserted = '<!-- wp:divi/text {"builderVersion":"5.2.1","content":{"innerContent":{"desktop":{"value":'
. '"\u003cp\u003eNeu\u003c/p\u003e"}}},"module":{"meta":{"adminLabel":{"desktop":{"value":"Hero – Text"}}}}} '
. '--><!-- /wp:divi/text -->';
self::assertSame(str_replace('<!-- /wp:divi/text --><!-- wp:divi/button', '<!-- /wp:divi/text -->' . $inserted . '<!-- wp:divi/button', $this->original), $this->saved[0]);
}
public function testStaleTreeRevAndInvalidNodesWriteNothing(): void
{
$stale = $this->insert()->execute(['post_id' => 7, 'tree_rev' => '000000000000', 'nodes' => [['type' => 'section']]]);
self::assertSame('lit_rev_mismatch', $stale->get_error_code());
self::assertSame('rev_mismatch', self::clientError($stale)['code'], 'the client sees the code without lit_');
self::assertStringContainsString('lit-divi-outline', $stale->get_error_data()['hint']);
self::assertSame($stale->get_error_code(), $this->insert()->permission(['post_id' => 7, 'tree_rev' => 'x'])->get_error_code());
$invalid = $this->insert()->execute([
'post_id' => 7,
'tree_rev' => $this->treeRev(),
'parent' => 's0.r0.c0',
'nodes' => [
['type' => 'heading', 'attrs' => ['title.fnt' => ['desktop' => 'x']]],
['type' => 'button', 'url' => 'javascript:alert(1)', 'text' => 'x', 'nope' => 1],
],
]);
self::assertSame('lit_invalid_attr_path', $invalid->get_error_code());
$client = self::clientError($invalid);
self::assertSame('invalid_attr_path', $client['code']);
self::assertArrayHasKey('nodes[0].attrs.title.fnt', $client['fields']);
self::assertGreaterThanOrEqual(2, count($client['fields']), 'every error of the call in one response (S39)');
self::assertStringContainsString('lit-divi-catalog', $client['hint']);
$wrongPlace = $this->insert()->execute(['post_id' => 7, 'tree_rev' => $this->treeRev(), 'nodes' => [['type' => 'button']]]);
self::assertSame('lit_validation_failed', $wrongPlace->get_error_code());
$badPosition = $this->insert()->execute([
'post_id' => 7,
'tree_rev' => $this->treeRev(),
'parent' => 's0.r0.c0',
'after' => 's0.r0.c1.m1',
'nodes' => [['type' => 'text']],
]);
self::assertSame('lit_validation_failed', $badPosition->get_error_code());
self::assertArrayHasKey('position', self::clientError($badPosition)['fields']);
$unknown = $this->insert()->execute([
'post_id' => 7,
'tree_rev' => $this->treeRev(),
'parent' => 's9',
'nodes' => [['type' => 'section']],
]);
self::assertSame('lit_validation_failed', $unknown->get_error_code());
self::assertSame([], $this->saved);
self::assertSame($this->original, $this->post->post_content);
}
/** Ruling S9: the first section of an empty page goes into a divi/placeholder. */
public function testInsertIntoAnEmptyPageWrapsInAPlaceholder(): void
{
$this->post->post_content = '';
$result = $this->insert()->execute([
'post_id' => 7,
'tree_rev' => Rev::of(''),
'nodes' => [['type' => 'section', 'label' => 'Start', 'modules' => [['type' => 'heading', 'text' => 'Hallo']]]],
]);
self::assertTrue($result['ok'], (string) json_encode($result));
self::assertCount(1, $this->saved);
self::assertStringStartsWith('<!-- wp:divi/placeholder --><!-- wp:divi/section ', $this->saved[0]);
self::assertStringEndsWith('<!-- /wp:divi/section --><!-- /wp:divi/placeholder -->', $this->saved[0]);
self::assertSame('s0', $result['changed'][0]['id']);
self::assertSame('Start', $result['changed'][0]['label']);
}
public function testUpdateChangesSeveralNodesAllOrNothing(): void
{
$failed = $this->update()->execute(['post_id' => 7, 'tree_rev' => $this->treeRev(), 'changes' => [
['id' => 's0.r0.c1.m2', 'set' => ['text' => 'Jetzt buchen']],
['id' => 's0.r0.c1.m0', 'set' => ['level' => 'h9']],
['id' => 's0.r0.c1.m9', 'label' => 'x'],
]]);
self::assertSame('lit_validation_failed', $failed->get_error_code());
$fields = self::clientError($failed)['fields'];
self::assertArrayHasKey('changes[1].set.level', $fields);
self::assertArrayHasKey('changes[2].id', $fields, 'every error of the call in one response (S39)');
self::assertSame([], $this->saved);
$result = $this->update()->execute(['post_id' => 7, 'tree_rev' => $this->treeRev(), 'changes' => [
['id' => 's0.r0.c1.m2', 'set' => ['text' => 'Jetzt buchen']],
['id' => 's0.r0.c1.m0', 'attrs' => ['title.decoration.font.font' => ['phone' => null]]],
]]);
self::assertTrue($result['ok']);
self::assertSame(['s0.r0.c1.m2', 's0.r0.c1.m0'], array_column($result['changed'], 'id'));
self::assertSame(['updated', 'updated'], array_column($result['changed'], 'action'));
self::assertSame(Rev::of($this->saved[0]), $result['tree_rev']);
$index = NodeIndex::build((new Parser())->parse($this->saved[0]));
self::assertSame('Jetzt buchen', $index->find('s0.r0.c1.m2')?->attrs()['button']['innerContent']['desktop']['value']['text']);
self::assertArrayNotHasKey('phone', $index->find('s0.r0.c1.m0')?->attrs()['title']['decoration']['font']['font']);
// Untouched section s1 keeps its exact bytes.
self::assertStringContainsString(substr($this->original, (int) strpos($this->original, '<!-- wp:divi/section {"module":{"meta":{"adminLabel":{"desktop":{"value":"Leistungen"'), -1), $this->saved[0]);
}
public function testUpdateWithoutRealChangeSavesNothing(): void
{
$result = $this->update()->execute([
'post_id' => 7,
'tree_rev' => $this->treeRev(),
'changes' => [['id' => 's0.r0.c1.m2', 'set' => ['text' => 'Termin buchen']]],
]);
self::assertStringStartsWith('Keine Änderung', $result['summary']);
self::assertSame($this->treeRev(), $result['tree_rev']);
self::assertSame([], $this->saved);
}
public function testUpdateRefusesAStaleTreeRev(): void
{
$result = $this->update()->execute([
'post_id' => 7,
'tree_rev' => '000000000000',
'changes' => [['id' => 's0.r0.c1.m2', 'label' => 'x']],
]);
self::assertSame('lit_rev_mismatch', $result->get_error_code());
self::assertSame([], $this->saved);
}
public function testReadOnlyNodesCannotBeUpdated(): void
{
$this->post->post_content = DiviPageLoaderTest::fixture('synthetic-mixed.html');
$result = $this->update()->execute([
'post_id' => 7,
'tree_rev' => Rev::of($this->post->post_content),
'changes' => [['id' => 's1.g1', 'label' => 'x']],
]);
self::assertSame('lit_validation_failed', $result->get_error_code());
self::assertStringContainsString('nur lesbar', $result->get_error_message());
self::assertSame([], $this->saved);
}
/** Ruling S14: the same node twice in one call would silently lose the first change. */
public function testUpdateRefusesADuplicateId(): void
{
$result = $this->update()->execute(['post_id' => 7, 'tree_rev' => $this->treeRev(), 'changes' => [
['id' => 's0.r0.c1.m2', 'set' => ['text' => 'Eins']],
['id' => 's0.r0.c1.m2', 'set' => ['url' => '/zwei']],
]]);
self::assertSame('lit_validation_failed', $result->get_error_code());
self::assertStringContainsString('changes[0]', self::clientError($result)['fields']['changes[1].id']);
self::assertSame([], $this->saved);
}
/** Ruling S38: set and attrs of one change must not reach the same attribute path. */
public function testUpdateRefusesSetAndAttrsOnTheSamePath(): void
{
$result = $this->update()->execute(['post_id' => 7, 'tree_rev' => $this->treeRev(), 'changes' => [[
'id' => 's0.r0.c1.m2',
'set' => ['text' => 'Neu'],
'attrs' => ['button.innerContent' => ['desktop' => ['linkUrl' => '/neu']]],
]]]);
self::assertSame('lit_validation_failed', $result->get_error_code());
self::assertArrayHasKey('changes[0].attrs.button.innerContent', self::clientError($result)['fields']);
self::assertSame([], $this->saved);
}
/** Ruling S7: builder-only paths are refused for users without unfiltered_html – visible to the client. */
public function testBuilderOnlyPathsAreRefusedForEditors(): void
{
$result = $this->update()->execute(['post_id' => 7, 'tree_rev' => $this->treeRev(), 'changes' => [[
'id' => 's0.r0.c1.m1',
'attrs' => ['module.decoration.attributes' => ['desktop' => ['attributes' => [['name' => 'onclick', 'value' => 'x']]]]],
]]]);
self::assertSame('lit_validation_failed', $result->get_error_code());
$client = self::clientError($result);
self::assertSame('validation_failed', $client['code']);
self::assertStringContainsString('nur im Divi-Builder', $client['fields']['changes[0].attrs.module.decoration.attributes']);
self::assertSame([], $this->saved);
}
}