Skip to content

feat(tanstack): pull-based draft preview binding - #442

Merged
guitavano merged 3 commits into
mainfrom
guitavano/tanstack-draft-preview
Aug 6, 2026
Merged

guitavano merged 3 commits into
mainfrom
guitavano/tanstack-draft-preview

Conversation

@guitavano

@guitavano guitavano commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

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's draftSource (token parsing, origin validation, fetch, version cache, host allowlist), and the /deco/invoke path already honours drafts via blocks-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:

  1. Request scope. Next backs the per-request draft slot with React cache() and has the awkward "await ensureDraft from the page, not a layout" rule. TanStack already wraps every request in RequestContext.run, so the resolved draft rides the request bag and loadBlocks() reads it back through the injected getRequestDraftOverride getter — no cache(), no page-vs-layout rule.
  2. Static-vs-dynamic rewrite. Next rewrites drafted requests onto an encoded app/%5Fdraft/… route to escape ISR (dynamic/revalidate are 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 shared blocks-admin handler, 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/blocks reading the RequestContext bag
  • installPreviewHostsFromBlocks — sync the site.previewHosts allowlist from the base decofile (via onChange, never request-time merged blocks)
  • requestCarriesDraft — pure, network-free edge-cache-bypass predicate
  • bindRequestDraft — resolve + bind the draft to the request before render
  • applyDraftCookieAndHeaders — navigation cookie (SameSite=None; Secure; HttpOnly; Partitioned) + no-store / Vary: Cookie / X-Robots-Tag: noindex

workerEntry.ts wiring:

  • install once in createDecoWorkerEntry (idempotent)
  • bindRequestDraft inside RequestContext.run, before the render, so every loadBlocks() in the call stack sees the merged decofile
  • stamp cookie + anti-leak headers on the final response
  • bug fix in isCacheable: it was bypassing on a __deco_draft query param that never exists — the entry param is __draft and __deco_draft is the cookie. Now uses requestCarriesDraft (param or cookie, host-gated).
  • bypass the POST _serverFn edge 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 site block's previewHosts, or the DECO_ALLOWED_PREVIEW_HOSTS override, 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 through createDecoWorkerEntry proving 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; typecheck clean; new files pass biome. (Pre-existing lint/knip noise on main is untouched.)

Follow-ups (not in this PR)

  • Preview badge/indicator (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.
  • No new site-facing docs yet; wiring is automatic inside createDecoWorkerEntry, so sites need no code changes beyond setting previewHosts / 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

    • Bind resolved drafts to the request via RequestContext so loadBlocks() reads the merged decofile.
    • Auto-install preview host allowlist from base blocks; also respects DECO_ALLOWED_PREVIEW_HOSTS.
    • Keep drafted requests out of edge cache using requestCarriesDraft (param or cookie, host-gated).
    • Apply secure cookie and headers on preview: no-store, Vary: Cookie, X-Robots-Tag: noindex.
    • Auto-wired in createDecoWorkerEntry (register getter, bind before render, stamp headers).
    • Shared preview badge moved to @decocms/blocks/preview; @decocms/nextjs re-exports it.
    • New TanStack DraftPreviewIndicator mounts in DecoRootLayout; hydration-safe and hidden in Studio iframes; provides share/exit actions.
    • Inert unless the request host is allowlisted; upgrading alone won’t expose drafts.
  • Bug Fixes

    • isCacheable now keys off requestCarriesDraft (real ?__draft or __deco_draft cookie), not a non-existent __deco_draft param.
    • Drafted POST _serverFn calls bypass the edge cache to prevent leaks and stale responses.
    • Decode the __deco_draft cookie so the badge’s share link doesn’t double-encode the pointer.
    • Merge Vary non-destructively; append Cookie without dropping existing tokens (e.g. Accept-Encoding).

Written for commit 3274a46. Summary will update on new commits.

Review in cubic

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]>
@guitavano
guitavano requested a review from a team August 5, 2026 16:59
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]>
@guitavano

Copy link
Copy Markdown
Contributor Author

Added: shared preview-mode badge (Next + TanStack)

Follow-up commit 2662bdb closes the badge follow-up from the description — the "Preview mode" chip now renders on both bindings from a single implementation.

@decocms/blocks/preview (new client-safe subpath) — the badge is pure client React (pointer prop, inline styles, inlined deco mark), so it moved to the runtime core and neither binding owns a copy. buildShareUrl/buildExitUrl/isFramed came along; the badge unit + render tests moved here with the source.

@decocms/nextjs — DraftPreviewBadge.tsx is now a thin re-export; decoMark.ts deleted. DraftPreviewIndicator (server component) unchanged, so Next behaves exactly as before.

@decocms/tanstack — new isomorphic DraftPreviewIndicator, mounted automatically by DecoRootLayout (sites get it on bump, no code change). The tricky bit is hydration: the pointer only exists server-side, so SSR reads it 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 server and client compute the same pointer and the <script> node reconciles with no mismatch. bindRequestDraft now stashes the pointer in the bag when a draft binds; a client-safe draftShared.ts holds the bag-key/global constants shared by the server binding and the client indicator (keeps the indicator from importing the server-only ./draft).

Inert on published traffic; hidden inside Studio's own preview iframe (isFramed).

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]>
@guitavano
guitavano merged commit a0a7746 into main Aug 6, 2026
1 check passed
@github-actions

github-actions Bot commented Aug 6, 2026

Copy link
Copy Markdown

🎉 This PR is included in version 7.34.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

guitavano added a commit that referenced this pull request Aug 7, 2026
## 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant