Repository navigation
feat(tanstack): pull-based draft preview binding - #442
Conversation
Ports the `?__draft=` pull-based draft preview (shipped for Next in #409) to the TanStack Start / Cloudflare Workers binding. The framework-agnostic motor already lives in `@decocms/blocks`'s `draftSource` (token parsing, origin validation, fetch, version cache, host allowlist) and the `/deco/invoke` path already honours drafts via `blocks-admin`; this wires the page-render half for TanStack. Simpler than the Next binding because two App Router constraints don't exist here: - Request scope: TanStack already wraps every request in RequestContext.run, so the resolved draft rides the request bag and loadBlocks() reads it back via the injected getter — no React cache() / page-vs-layout await rule. - Static-vs-dynamic: the worker decides cacheability per request, so a drafted request just bypasses the edge cache — no `%5Fdraft` rewrite. New `sdk/draft.ts`: - registerDraftOverride: DI getter → RequestContext bag - installPreviewHostsFromBlocks: sync `site.previewHosts` allowlist - requestCarriesDraft: pure edge-cache-bypass predicate - bindRequestDraft: resolve + bind draft to the request - applyDraftCookieAndHeaders: navigation cookie (SameSite=None; Secure; HttpOnly; Partitioned) + no-store/Vary/X-Robots-Tag workerEntry wiring: install once in createDecoWorkerEntry; bind inside RequestContext.run before render; stamp cookie/headers on the final response; fix isCacheable (was checking a `__deco_draft` *param* that never exists — the param is `__draft`, `__deco_draft` is the cookie) and bypass the POST _serverFn cache for drafted SPA navigation. Inert unless the site opts in via `previewHosts` / DECO_ALLOWED_PREVIEW_HOSTS. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Promotes the preview-mode badge to the runtime core so both bindings render
one implementation, and wires it into the TanStack binding (Next already had
it).
@decocms/blocks:
- new client-safe `@decocms/blocks/preview` subpath: DraftPreviewBadge
(pure client component, `pointer` prop) + buildShareUrl/buildExitUrl/
isFramed + the inlined deco mark. No framework imports; DRAFT_PARAM kept
as a local literal so the module never pulls the server-only cms barrel.
- moved the badge unit + render tests here (they now cover the source).
@decocms/nextjs:
- DraftPreviewBadge.tsx is now a thin re-export of the shared module;
decoMark.ts deleted. DraftPreviewIndicator unchanged.
@decocms/tanstack:
- new isomorphic DraftPreviewIndicator, mounted automatically by
DecoRootLayout. Hydration-safe: SSR reads the pointer from the request
bag and publishes it on a window global via an inline script; the client
reads that global (RequestContext is a browser no-op stub), so both
renders compute the same pointer and the <script> reconciles cleanly.
- bindRequestDraft now stashes the active pointer in the bag when a draft
binds; new client-safe draftShared.ts holds the bag-key/global constants
the server binding and the client indicator share.
Inert on published traffic; the badge only mounts when a draft is bound, and
stays hidden inside Studio's own preview iframe (isFramed).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Added: shared preview-mode badge (Next + TanStack)Follow-up commit
Inert on published traffic; hidden inside Studio's own preview iframe ( Tests: blocks 1393, nextjs 73, tanstack 161 — all green; typecheck + biome clean on touched files. |
Self-review of the draft-preview binding: `readCookie` returned the raw cookie value, but the navigation cookie is written with `encodeURIComponent` (and `@decocms/blocks`'s own reader decodes). On cookie-carried navigation the pointer stashed for the preview badge was therefore URL-encoded, so the badge's "Share preview" link double-encoded it into a token that won't parse on the recipient's side. (The draft still rendered — `resolveDraftForRequest` decodes independently — so only the badge link was wrong.) Decode in `readCookie`, defensively: a malformed `%` sequence in a crafted cookie falls back to the raw value instead of throwing and 500-ing the request. Also make the `Vary` merge non-destructive (append `Cookie` without dropping existing tokens such as `Accept-Encoding`; moot under no-store, but correct). Regression tests for both. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
🎉 This PR is included in version 7.34.0 🎉 The release is available on:
Your semantic-release bot 📦🚀 |
## Problem The pull-based `?__draft=` preview (TanStack #442, Next #409) merges the Studio sandbox decofile on top of the site's published blocks in `loadBlocks()`. But the two decofiles **disagree on how block keys spell special characters**: | | `/` (home) block key | |---|---| | Published (`/.decofile`, the base) | `pages-Home%20(principal)-287364` (percent-encoded) | | Studio draft sandbox (`_sandbox/decofile`, the override) | `pages-Home (principal)-287364` (raw) | The merge was a literal key-merge: ```js const merged = { ...blockData }; // base key: "...%20..." merged[key] = value; // override key: "... ..." → ADDS, never REPLACES ``` So the raw-keyed draft block was **added alongside** the encoded published block, leaving **two `pages-` blocks with the same `.path`**. `findPageByPath` returns the first match in `getAllPages()` order — the published block was already in `blockData`, the draft was appended after, so ties resolve to **published**. The draft edit silently never rendered: preview badge showed, `no-store`/`noindex`/cookie/edge-cache-bypass were all correct, but the page content stayed published. ## Impact Measured against casaevideo's live published vs sandbox decofiles: **78 of 107 pages (~73%)** were affected — every page whose block name contains a space or accent (`Home (principal)`, `Afiliados - Performance`, …). The 29 pages with plain ASCII keys (`disney`, `login`, `natal`, `ofertas`) worked, which is exactly why it looked intermittent. All 70 special-char blocks in the sandbox URL-decode to the published key 1:1 — a systematic encoding contract mismatch, not a fluke. ## Fix Canonicalise base keys with `decodeURIComponent` when applying an override, so an override block finds and displaces its differently-encoded twin (a `null` override removes it too). Defensive: a malformed `%` sequence falls back to the raw key rather than throwing. Exact-match keys — including the admin `withBlocksOverride` partial-render path — are byte-for-byte unchanged. ## Tests 3 new regression tests in `loader.test.ts` (home encoded-vs-raw twin collapses to one block rendering the draft; plain keys still replace; `null` draft removes the encoded twin). Full `@decocms/blocks` suite green: **1396/1396**, typecheck clean. ## Follow-up (not here, cross-repo) The root contract mismatch is that preview-studio emits raw block keys while the published decofile encodes them. Aligning the source is worth doing separately; this framework-side canonicalisation is the defensive fix at the deterministic merge chokepoint (and an override *should* always replace, never duplicate). 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Fixes draft preview merging by matching override blocks to base blocks using percent-decoded keys, so raw Studio keys replace their encoded published twins. Restores draft rendering for pages with spaces/accents without changing exact-match override behavior. - **Bug Fixes** - Decode base block keys when merging `?__draft=` overrides; fall back to raw key on decode errors. - Overrides replace or delete the encoded twin to avoid duplicate `pages-` entries. - Added regression tests for home (encoded vs raw), plain keys, and null delete. <sup>Written for commit e2f66ec. Summary will update on new commits.</sup> <a href="https://cubic.dev/pr/decocms/blocks/pull/450?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. --> Co-authored-by: Claude Opus 4.8 <[email protected]>
Ports the
?__draft=pull-based draft preview — shipped for Next.js in #409 — to the TanStack Start / Cloudflare Workers binding.A site renders its own real pages against a Studio sandbox's working-tree draft, fetching the merged decofile itself over a plain
GET, keyed by version. The framework-agnostic motor already lives in@decocms/blocks'sdraftSource(token parsing, origin validation, fetch, version cache, host allowlist), and the/deco/invokepath already honours drafts viablocks-admin. This PR is the missing page-render half for TanStack.Why this is smaller than the Next port
Two App Router constraints that #409 had to fight simply don't exist on Workers:
cache()and has the awkward "awaitensureDraftfrom the page, not a layout" rule. TanStack already wraps every request inRequestContext.run, so the resolved draft rides the request bag andloadBlocks()reads it back through the injectedgetRequestDraftOverridegetter — nocache(), no page-vs-layout rule.app/%5Fdraft/…route to escape ISR (dynamic/revalidateare static route exports). The worker decides cacheability per request, so a drafted request simply bypasses the edge cache — no rewrite.Deferred/lazy sections (
/deco/invoke) already bind drafts through the sharedblocks-adminhandler, so that known-follow-up from #409 is covered here for free.What's in it
New
packages/tanstack/src/sdk/draft.ts:registerDraftOverride— DI getter into@decocms/blocksreading theRequestContextbaginstallPreviewHostsFromBlocks— sync thesite.previewHostsallowlist from the base decofile (viaonChange, never request-time merged blocks)requestCarriesDraft— pure, network-free edge-cache-bypass predicatebindRequestDraft— resolve + bind the draft to the request before renderapplyDraftCookieAndHeaders— navigation cookie (SameSite=None; Secure; HttpOnly; Partitioned) +no-store/Vary: Cookie/X-Robots-Tag: noindexworkerEntry.tswiring:createDecoWorkerEntry(idempotent)bindRequestDraftinsideRequestContext.run, before the render, so everyloadBlocks()in the call stack sees the merged decofileisCacheable: it was bypassing on a__deco_draftquery param that never exists — the entry param is__draftand__deco_draftis the cookie. Now usesrequestCarriesDraft(param or cookie, host-gated)._serverFnedge cache for drafted SPA navigation (its body-hash key doesn't vary on the cookie, so it would otherwise leak drafts / serve stale published)Gating
Fully inert unless the site opts in — the
siteblock'spreviewHosts, or theDECO_ALLOWED_PREVIEW_HOSTSoverride, must name the request's host. Upgrading the package can never start rendering unpublished content. A?__draft=on a non-preview host is structurally inert (no render, no cookie, not even a cache bypass).Tests
sdk/draft.test.ts— 16 unit tests:requestCarriesDraft,bindRequestDraft(entry / cookie-nav / resolve-failure-still-uncacheable / off / disallowed host), cookie + header application, host install.sdk/workerEntry.test.ts— 4 end-to-end tests throughcreateDecoWorkerEntryproving a drafted request binds the merged decofile into the render, bypasses the edge cache, and stamps the anti-leak cookie/headers — and stays inert on non-preview hosts and unconfigured builds.157/157 tanstack tests pass;
typecheckclean; new files passbiome. (Pre-existinglint/knipnoise onmainis untouched.)Follow-ups (not in this PR)
DraftPreviewBadge/DraftPreviewIndicator) still lives only in@decocms/nextjs; if we want the same visual "you're in preview" chip on TanStack it should be promoted to a shared spot.createDecoWorkerEntry, so sites need no code changes beyond settingpreviewHosts/ the env.🤖 Generated with Claude Code
Summary by cubic
Adds pull-based draft preview to TanStack Start/Cloudflare Workers and promotes a shared preview badge used by both bindings. Drafts bind per request, persist via a secure cookie across navigation, bypass edge caches, and are never indexed.
New Features
RequestContextsoloadBlocks()reads the merged decofile.DECO_ALLOWED_PREVIEW_HOSTS.requestCarriesDraft(param or cookie, host-gated).no-store,Vary: Cookie,X-Robots-Tag: noindex.createDecoWorkerEntry(register getter, bind before render, stamp headers).@decocms/blocks/preview;@decocms/nextjsre-exports it.DraftPreviewIndicatormounts inDecoRootLayout; hydration-safe and hidden in Studio iframes; provides share/exit actions.Bug Fixes
isCacheablenow keys offrequestCarriesDraft(real?__draftor__deco_draftcookie), not a non-existent__deco_draftparam._serverFncalls bypass the edge cache to prevent leaks and stale responses.__deco_draftcookie so the badge’s share link doesn’t double-encode the pointer.Varynon-destructively; appendCookiewithout dropping existing tokens (e.g.Accept-Encoding).Written for commit 3274a46. Summary will update on new commits.