Skip to content

Include a page's design system as a companion library item on save/import - #519

Merged
rahulwalunje merged 8 commits into
mainfrom
issues/518-ds-companion-library-items
Nov 19, 2026
Merged

rahulwalunje merged 8 commits into
mainfrom
issues/518-ds-companion-library-items

Conversation

@rahulwalunje

@rahulwalunje rahulwalunje commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #518.

  • Design system travels with the page: saving a page to a cloud library now carries its design system inside the page's own library item, so importing the page elsewhere brings the styling with it.
  • No duplicates on import: a design system that already exists at the destination (matched by UUID) is reused, not created again.
  • Blank and corrupted imports fixed: three bugs in the base import flow that left imported pages blank or their CSS broken are fixed. They affected every library import, not only design systems.

How it works

Assistant stays generic. The design-system knowledge lives in the Beaver Builder Platform behind two filters, mirroring the fl_assistant_post_types_known pattern from #517. The platform side is already merged (see Related).

Save and sync (get_save_data): Assistant asks plugins for companion posts through fl_assistant_library_companion_posts. Each companion's post, meta and terms are embedded in the page item's meta under _fl_asst_companions as one JSON string. Because the companion is part of the page item's data, it moves with the item, there is no second library item to keep in step or delete by accident, and saving several pages that share a design system does not fill the library with copies. sync_to_library uses the same data, so a sync refreshes the embedded copy.

Import (import_from_library): after the page is created through the shared import_item(), each embedded companion is created the same way unless a plugin reports it present through fl_assistant_library_companion_exists. A companion is only imported when its post type is library-portable, meaning it is on the list behind the existing fl_assistant_post_types_library filter (default fl-design-system); the embedded data can come from a library someone else authored, so it cannot choose its own post type. A companion that is refused or cannot be created is logged and listed in an additive companion_errors key on the response; the page import still succeeds.

Never stored locally: import_post_meta_from_library() skips _fl_asst_companions, so the embedded data is not written to the imported page on import, sync or preview, and get_save_data() never re-uploads a stale copy.

Preview: previewing a library page imports the page only, as before. A page whose design system is not already on the site previews unstyled; a real import brings the design system.

Where the code lives: post creation moved out of the controller into Services/LibraryPostImporter; import_post_meta_from_library(), import_post_terms_from_library() and regenerate_builder_cache() stay on the controller as delegates with unchanged signatures. The controller is smaller than on main.

Three fixes to the base import flow

Found while validating against real Beaver Builder pages. They also affect sync_from_library.

  1. Slash post content on import. wp_insert_post() unslashes its input, so JSON stored in post_content had every \n turned into a literal n. Fixed with wp_slash(). wp_insert_post() is also now called with the WP_Error flag, so a failed insert returns the documented { error: true } instead of continuing with post id 0.
  2. Store imported meta with $wpdb->insert(). Meta was written with addslashes() and a hand-built INSERT, which silently fails for large values on MySQL hosts running NO_BACKSLASH_ESCAPES, leaving the page blank.
  3. Preserve serialized meta through the media URL rewrite. update_post_meta() unslashes, which stripped the escaped quotes inside each module's ds_block_data JSON in _fl_builder_data. The value is now written with maybe_serialize() and $wpdb->update().

Behavior changes to know about

  • The media URL rewrite no longer fires update_post_metadata or updated_post_meta, because it writes through $wpdb. The post cache is cleaned afterwards.
  • Images referenced only by a companion are not uploaded or rewritten. Out of scope here.
  • A design system saved to a library on its own and imported twice is still created twice; a direct import does not ask the exists filter. That predates this PR.

Testing

backend/tests/Unit/Controllers/LibraryItemPostCompanionsTest.php covers: a declared companion is embedded once; no key without companions; a stale local value is not uploaded; an embedded companion is created with its content and meta byte for byte; a companion reported present is skipped; a companion that cannot be created comes back as an error while the others import; a companion whose post type is not library-portable is refused; malformed data is ignored; imported meta keeps backslashes and quotes; the media URL rewrite keeps the escapes inside nested ds_block_data.

Manual Testing
  1. On a site with Beaver Builder Platform active, save a page that uses a design system to a cloud library. Confirm one library item is created.
  2. On a second site without that design system, import the page. Confirm the page is styled and one design system exists.
  3. Import the same page again. Confirm no second design system is created.
  4. On a clean site, preview the library page. Confirm no design system is created.
  5. Save a page with no design system. Confirm it saves and imports as before.

Related

Platform side of the two filters, already merged: https://github.com/beaverbuilder/beaver-builder-platform/pull/738

🤖 Generated with Claude Code

rahulwalunje and others added 4 commits August 6, 2026 02:34
A page can reference companion posts it needs to render (e.g. a design system via _fl_ds_ref). Previously only the page uploaded to a cloud library, so it arrived at the destination with a dangling reference and no styling.

Assistant stays generic and the companion knowledge lives in the plugin that owns the relationship, via two filters mirroring the #517 fl_assistant_post_types_known pattern:

- save_to_library() uploads companions first (fl_assistant_library_companion_posts), $seen-deduped, and records their cloud ids on the page item as _fl_asst_companion_items. get_save_data() gains a $with_screenshot flag so companions that never render (a design system) skip a wasted headless capture.
- import_from_library() is refactored around a reusable, post-type-agnostic import_item(); import_companions_from_library() reads the recorded ids from the fetched item (not the just-written post meta, which a raw-INSERT leaves stale in cache), pulls each, skips any a plugin reports already present via fl_assistant_library_companion_exists, creates the rest, and strips the linkage meta.

Save-only for now; sync_to_library is untouched.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
wp_insert_post() unslashes its argument internally, but import_item() passed the fetched post data through unslashed. A design system item stores its CSS as JSON in post_content (with \n escapes), so the missing slash stripped every backslash and turned each \n into a literal 'n' — corrupting the stylesheet the design system builds from it (broken selectors like nn.bb-badge, mangled token/reset blocks) and leaving imported pages unstyled.

wp_slash() the array passed to wp_insert_post() so the content survives the internal unslash intact. Not visible on regular pages because their builder data lives in meta (imported via a slash-safe path); it surfaced once #518 started importing design-system posts whose content is post_content JSON.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…raw escaped INSERT

import_post_meta_from_library() wrote each meta value with addslashes() + a raw string-interpolated INSERT. On hosts running MySQL in NO_BACKSLASH_ESCAPES mode that query silently fails for large serialized values (e.g. a 49KB _fl_builder_data full of escaped quotes) — the return value was ignored, so the data was never stored and the imported page rendered blank while smaller meta imported fine.

Use $wpdb->insert(), which escapes per the connection and is safe on any sql_mode, and clean_post_cache() after the direct writes so same-request reads (asset regeneration) and object-cache hosts see the imported meta.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
replace_imported_attachment_urls_in_meta() re-saved each meta value with update_post_meta(), which unslashes internally. For _fl_builder_data — an array of module objects — that strips the escaped quotes (\") inside every module's ds_block_data JSON, making it invalid. The ds-block module can't parse it, so pages built from ds-blocks imported blank whenever the media step ran (i.e. pages with a featured image or other attachments). Slashing the input didn't help because the corruption is on a deeply nested object property.

Re-serialize the rewritten value with maybe_serialize() and write it with $wpdb->update() so the bytes are stored verbatim, then clean_post_cache(). Verified end to end: ds_block_data stays valid JSON and the page renders.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
rahulwalunje and others added 4 commits November 19, 2026 02:06
Resolve the get_save_data() conflict with the #530 screenshot fix: keep main's client-screenshot-only shape and gate it on $with_screenshot, so a companion item is not uploaded with the primary post's screenshot.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
A page's companions (its design system) now travel inside the page's own library item, as one JSON string under the `_fl_asst_companions` meta key, instead of as separate library items linked by cloud id. The link survives a library being duplicated or moved, saving several pages no longer uploads repeated copies, and there is no second item to delete by accident.

Import creates each embedded companion unless `fl_assistant_library_companion_exists` reports it present. A companion that cannot be created is logged and returned in an additive `companion_errors` response key. Preview imports the page only. The embedded data is never stored on the local post. `get_save_data()` returns to its signature on main.

Adds unit tests for the save, import and meta paths, including regressions for the three base import fixes.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… companion types (#518)

Post creation from a library item (insert, meta, terms, builder cache, embedded companions) moves from LibraryItemPostController into a new Services/LibraryPostImporter, so the controller stops growing past its size on main. The controller's public import methods stay as delegates with unchanged signatures.

A companion is now imported only when its post type is library-portable, the list behind the existing `fl_assistant_post_types_library` filter (default `fl-design-system`), read through the new PostsRepository::get_library_post_types(). Embedded companion data can come from a library another user authored, so it must not choose its own post type. A refused companion is reported as `companion_type_not_allowed`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@rahulwalunje

rahulwalunje commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator Author

Merge Check

State: tested at 5ba45531c, lane irreversible, verdict: merge with follow-ups. Unresolved: one approving review (advisory here). Lane irreversible recorded in the sticky only; this repo has not opted into the risk lanes (no risk: labels).

TLDR

When someone saves a page to a cloud library, the page's design system now travels inside that same library item. Importing the page on another site brings the design system with it, and a design system that is already there is reused, not duplicated. Three bugs that could leave any imported page blank or with broken CSS are fixed along the way.

Review

merge-check deep review, verdict Fix-then-ship: no blockers at head; six non-blocking concerns in the fold.

Review detail

Verdict: Fix-then-ship. The blocker from the previous round (controller grown past the file size ceiling) is fixed and verified at head: the controller is 665 lines against 707 on main, and the moved method bodies are identical to what was removed. The companion post type restriction asked for in that round is in and verified.

Concerns (non-blocking)

  • [Errors] backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php:375: the UI ignores companion_errors (src/apps/libraries/ui/library/items/actions/import.js:54), so a refused or failed companion still shows as a successful import with an unstyled page.
  • [Tests] backend/tests/Unit/Controllers/LibraryItemPostCompanionsTest.php:1: preview skipping companions and the companion_errors response key have no unit test, because the cloud fetch has no seam. Both were exercised in the round trip below.
  • [BC] backend/src/Services/LibraryPostImporter.php:146: a null meta value was stored as an empty string on main and is now stored as SQL NULL. Cast null to an empty string to keep the stored shape.
  • [BC] backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php:625: the media URL rewrite writes through $wpdb, so update_post_metadata and updated_post_meta no longer fire for it. Stated in the PR body.
  • [Architecture] backend/src/Controllers/Cloud/Libraries/LibraryItemPostController.php:417: sync_from_library does not import companions, so a synced page can reference a design system that is not on the site.
  • [Complexity] backend/src/Services/LibraryPostImporter.php:8: the new class is 230 lines, over the 200 line soft limit. import_meta and import_terms are over 30 lines but were moved as they were.

Nits

  • [Errors] backend/src/Helpers/CompanionPostsHelper.php:42: encode() returns false on invalid UTF-8, which silently drops the companions.
  • [Errors] backend/src/Services/LibraryPostImporter.php:220: regenerate_builder_cache() reads $item->data->meta unguarded while import_item() guards it.
  • [Security] backend/src/Helpers/CompanionPostsHelper.php:84: the companion title is written to error_log unsanitized; strip control characters.
  • [BC] backend/src/Data/Repository/PostsRepository.php:141: get_library_post_types() casts the filter result to an array, which the inline code on main did not.

deep review · 6 files / +787/-147 lines reviewed.

Sanity check

High depth. The approach holds: the cloud never indexes, validates or truncates the embedded value. The stored value ships as a bare list with no version wrapper, by the author's decision.

Sanity check detail

Lane: irreversible: a new persisted key, _fl_asst_companions, stored in the meta of cloud library items (a new stored shape). No UI trigger. Depth triggers: schema and data, BC surfaces.

  • Additive, no lane: filters fl_assistant_library_companion_posts and fl_assistant_library_companion_exists, the companion_errors response key, PostsRepository::get_library_post_types(). The filter contract matches the merged consumer in beaver-builder-platform PR 738.
  • 2026-11-19, @rahulwalunje (author): no version wrapper on the stored value; adding one now would be building for a need that does not exist yet.
  • The stored value is a bare JSON list. This version reads anything that is not a list as "no companions", so a later change of envelope would make shipped versions drop companions silently.
  • Older plugin versions import the embedded value as one large stray meta entry on the page and upload it again on their next save.
  • A companion is imported only when its post type is on the list behind fl_assistant_post_types_library; embedded data may come from a library another user authored.
  • Not caused by this PR, seen while reviewing: the cloud's library duplicate appears to copy items without their post data. Not verified by running.
  • No decision record. Suggested: agents/decisions/companion-posts-embedded-in-library-items.md.

Test plan

  1. On a site with Beaver Builder Platform active, save a page that uses a design system to a cloud library. Confirm one library item is created.
  2. On a site without that design system, import the page. Confirm it is styled and one design system now exists.
  3. Import the same page again. Confirm no second design system is created.
  4. On a site without the design system, preview the library page. Confirm no design system is created.
  5. Save and import a page that has no design system. Confirm it behaves as before.
  6. Import a page with a featured image and confirm its layout is not blank after the media step.
Agent playbook

Preconditions: local site at the workspace's bb site with Beaver Builder Platform active and at least one published page whose _fl_ds_ref resolves; the site's assistant-workspace plugin symlink pointing at this branch; a local Assistant cloud API (php artisan serve --port=8787 in assistant-cloud-api) with FL_ASSISTANT_CLOUD_URL set to it; a cloud user with one empty library; that user's token placed in the fl-cloud-token-<md5 of home_url> cookie for the request. PHPUnit needs PHP 7.4, composer install and backend/tests/wp-config.php.

  1. Run vendor/bin/phpunit --config=phpunit.xml --testsuite unit --filter LibraryItemPost. Expect 14 tests passing.
  2. Run vendor/bin/phpunit --config=phpunit.xml --testsuite unit. Expect only the failures that also occur on main: TermsControllerTest, four in PostRepositoryTest, SearchControllerTest.
  3. As an administrator, dispatch POST /fl-assistant/v1/posts/<page id>/library/<library id>. Expect a response with an item id and the library item count to rise by exactly one.
  4. Fetch that item from the cloud with post data. Expect data.meta._fl_asst_companions[0] to decode to one entry whose post.post_type is fl-design-system, whose post.post_content equals the local design system's content byte for byte, and whose meta equals the local design system's meta.
  5. With fl_assistant_library_companion_exists forced to false, dispatch POST /fl-assistant/v1/posts/preview_library_post with item={"id":<item id>}. Expect a preview URL and the count of published design systems unchanged.
  6. Still forced to false, dispatch POST /fl-assistant/v1/posts/import_from_library with the same item. Expect a new page id, no companion_errors, exactly one new design system with identical content and meta, no _fl_asst_companions meta on the new page, and _fl_ds_ref and _fl_builder_data equal to the source page's.
  7. Remove the forced filter and dispatch the import again. Expect a new page id and no new design system.
  8. Nothing-else-broke sweep: delete the posts and the cloud item the run created, confirm one design system remains for that UUID and no orphaned post meta, and restore the plugin symlink.
Run history
When (UTC) Head State Delta
2026-11-19 14:45 5ba4553 tested Author decision recorded: the stored value keeps its bare list form, no version wrapper. No retest; nothing else changed.
2026-11-19 14:43 5ba4553 tested Local run: follow-up review clean, previous blocker verified fixed; 14 of 14 companion unit tests; playbook steps 1 to 8 passed against a local cloud (design system of 11 KB with 273 backslashes round-tripped byte for byte). Not covered: the browser UI flow, a second real site, the media import step (test plan step 6), the refused post type path end to end. No labels written: the repo has no merge: or risk: labels.

bb-merge-check · head:5ba45531c · state:tested · risk:irreversible

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Auto-include an attached design system when a page is saved to a library

2 participants