Repository navigation
fix(runtime,tanstack): let a deferred section declare its skeleton's props - #588
Conversation
5cd27a7 to
96d5cd8
Compare
96d5cd8 to
72f1df4
Compare
There was a problem hiding this comment.
Review do PR, com testes que escrevi para checar o fluxo do rawProps de ponta a ponta. Não fiz commit deles no branch; o código está abaixo para reaproveitar.
1. deferred.rawProps ?? em skeletonProps é código morto
O delete deferred.rawProps roda dentro de resolveDecoPageImpl, antes de o resolve devolver qualquer coisa. Por isso nenhum render, nem SSR nem client nav, chega a ver rawProps. Testei chamando resolveDecoPage de verdade, com uma seção ⚡ e o flag nos dois estados:
rawProps no deferred devolvido |
fallbackProps |
|
|---|---|---|
| SSR / client nav, flag off | não existe | não existe |
| SSR / client nav, flag on | não existe | { galleryTitle, columns, … } |
O <h2> vazio no HTML servido, que aparece no "antes" da tabela de verificação do PR, confirma o mesmo: se o servidor tivesse os rawProps, o título já sairia no SSR. Sugiro deixar só deferred.fallbackProps ?? {} e ajustar o JSDoc de skeletonProps e a frase "servidor continua com as props completas" da descrição.
2. O filtro deixa passar strings de qualquer tamanho e valores que só deveriam ficar no servidor
pickFallbackProps aceita qualquer string não vazia. No teste, um prop de rich text com 5000 caracteres e um token em string pura (um prop que a seção só usava no loader) foram parar no fallbackProps e, portanto, no HTML.
- Payload: rich text é string. Com o flag ligado, cada seção deferida pode voltar a inchar o payload que o
delete rawPropsexistia para enxugar. - Exposição: um
Secretdo deco não vaza, porque é objeto e o filtro já descarta. Uma string crua passada a uma seção, porém, passa a ir para o cliente, coisa que antes não acontecia, já que uma seção eager serializa as props depois do loader.
Como o flag vale para o site inteiro, sugiro um opt-in por seção. Por exemplo, a seção exporta a lista de props liberadas para o fallback (export const fallbackProps = ["galleryTitle"]), ou o flag aceita um mapa por componente. No mínimo, um limite de tamanho por string.
3. Falta um teste de integração
Os testes do PR cobrem pickFallbackProps isolado e a persistência da config. Nada passa pelo resolveDecoPage com o flag ligado, então trocar a ordem entre pickFallbackProps e o delete não quebraria nenhum teste. Este é o que usei:
packages/blocks/src/cms/fallbackProps.probe.test.ts
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("./sectionLoaders", () => ({
isLayoutSection: () => false,
runSingleSectionLoader: vi.fn(async (section: any) => section),
}));
vi.mock("../sdk/normalizeUrls", () => ({ normalizeUrlsInObject: vi.fn(<T>(x: T) => x) }));
vi.mock("./loader", () => ({ findPageByPath: vi.fn(), loadBlocks: vi.fn(() => ({})) }));
vi.mock("./registry", () => ({ getSection: vi.fn(), getOnBeforeResolveProps: vi.fn() }));
import { findPageByPath } from "./loader";
import { getSection } from "./registry";
import { WELL_KNOWN_TYPES, resolveDecoPage, setAsyncRenderingConfig } from "./resolve";
const lazySec = {
__resolveType: WELL_KNOWN_TYPES.LAZY,
section: {
__resolveType: "site/sections/Gallery.tsx",
galleryTitle: "Você pode ter perdido",
columns: 4,
posts: { __resolveType: "blog/loaders/posts.ts", count: 12 },
},
};
describe("deferred section: what reaches the renderer", () => {
beforeEach(() => {
(getSection as ReturnType<typeof vi.fn>).mockReturnValue({ default: () => null });
(findPageByPath as ReturnType<typeof vi.fn>).mockReturnValue({
page: { name: "p", sections: [{ __resolveType: "site/sections/Banner.tsx" }, lazySec] },
params: {},
blockKey: "p",
});
});
afterEach(() => {
(getSection as ReturnType<typeof vi.fn>).mockReset();
(findPageByPath as ReturnType<typeof vi.fn>).mockReset();
});
for (const ctx of [{ name: "SSR", opts: {} }, { name: "client nav", opts: { isClientNavigation: true } }]) {
it(`${ctx.name}, flag off: rawProps stripped, no fallbackProps`, async () => {
setAsyncRenderingConfig({ foldThreshold: Infinity, respectCmsLazy: true, fallbackProps: false });
const d = (await resolveDecoPage("/p", ctx.opts as any))!.deferredSections[0];
expect("rawProps" in d).toBe(false);
expect("fallbackProps" in d).toBe(false);
});
it(`${ctx.name}, flag on: only the primitive projection survives`, async () => {
setAsyncRenderingConfig({ fallbackProps: true });
const d = (await resolveDecoPage("/p", ctx.opts as any))!.deferredSections[0];
expect("rawProps" in d).toBe(false);
expect(d.fallbackProps).toEqual({ galleryTitle: "Você pode ter perdido", columns: 4 });
});
}
});Também testei o DecoPageRenderer real com renderToString. Com o formato que o runtime emite, o resultado é <h2></h2> com o flag desligado e o título com o flag ligado, então o caminho do fallbackProps funciona.
4. Motivação
No site consumidor medido, o LoadingFallback já reserva a altura da linha do título com min-h, e o layout shift zerou do lado do site. O que sobra para o framework é o texto no HTML servido. Quando o título não varia pelo CMS, um default no fallback ({ galleryTitle = "…" }) resolve no próprio site. Vale deixar na descrição qual é o caso em que o texto realmente vem do CMS e muda.
Fora do escopo: bug pré-existente no Next, confirmado com teste
packages/nextjs/src/DecoPageRenderer.tsx:59 chama resolveDeferredSection(d.component, d.rawProps ?? {}, …) sobre page.deferredSections. Essa lista vem de resolveDecoPage, onde rawProps já foi apagado. Resultado: com async rendering ligado, toda seção ⚡ no Next renderiza com props {}. A binding TanStack não tem o problema porque busca as props no cache do servidor ou chama reExtractRawProps.
Teste: createDecoPage real, setAsyncRenderingConfig({ respectCmsLazy: true }), uma seção Lazy com label: "from-cms", render com renderToReadableStream + allReady.
- seção ⚡: o componente recebe
label === undefinede o HTML saihero-none❌ - controle, a mesma seção sem ⚡:
hero-from-cms✅
O resultado é o mesmo neste branch e na main, então não vem deste PR. Vale uma issue separada.
72f1df4 to
a4e8ad2
Compare
…props
A deferred section's `rawProps` are stripped before serialization — they can
carry whole product lists — and `DeferredSectionSkeleton` was left passing `{}`
to the section's `LoadingFallback`. Two things follow from that, and both show
up in the served HTML rather than only after hydration:
* Any CMS text the skeleton renders disappears. On a storefront's blog homepage
the recommended-posts section ships `<h2></h2>` where production (Deco on
Fresh, which passes the resolved props to the fallback) ships
"Você pode ter perdido". That is content a crawler never sees, and the text
differs per page — the same section ships "Você pode gostar" on the post
route — so a hardcoded default in the fallback cannot stand in for it.
* A skeleton that cannot render its own text also cannot reserve the real
section's height.
A section declares what its skeleton may render:
export const fallbackProps = ["galleryTitle"];
The scanner picks the list up into `sectionMeta`, `applySectionConventions`
registers it, and the serializer projects exactly those props onto the deferred
object. Declaring is the opt-in and it is per section: nothing a section did not
name reaches the client, so neither the payload nor a loader-only prop rides on
a size heuristic, and a section that declares nothing keeps rendering its
skeleton with `{}` — a site that merely bumps the framework serializes nothing
new. This is also why there is no site-wide switch: a fallback written against
`{}` may render differently once it receives props (one that spreads them into
the real component, say), and that must be a per-section decision.
Declared props are still filtered to primitives — an object or array would pull
back the graph `rawProps` was stripped to avoid — and empty strings are dropped,
since a parameter default only applies to `undefined`.
`skeletonProps` reads only the projection: `resolveDecoPage` deletes `rawProps`
before returning, so no render — SSR or client nav — ever saw them, and the
`rawProps ??` branch was dead. Three cases cover the whole path through
`resolveDecoPage`.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
a4e8ad2 to
29a83ab
Compare
|
🎉 This PR is included in version 7.72.2 🎉 The release is available on:
Your semantic-release bot 📦🚀 |
…tAny [7.x] (#778) ## Problem `@decocms/blocks` 7.x publishes its TypeScript source, so a consuming site's `tsc` and `next build` check `src/cms/schema.ts` with the site's own compiler options. `skipLibCheck` doesn't help, because it only covers `.d.ts` files. A site that enables `noImplicitAny` gets one error from the package: ``` node_modules/@decocms/blocks/src/cms/schema.ts: error TS7006: Parameter 'r' implicitly has an 'any' type. ``` `schema.root` is `Record<string, any>`, so `siteLoaderRefs` ends up as `any` and the `.filter((r) => ...)` callback has no contextual type. The site can't work around it from its side: the error blocks `next build`. ## Fix Annotate `siteLoaderRefs` as `{ $ref: string }[]`, which is what its type guard already says. This is type-only, so the emitted JS doesn't change. ## Verification In `packages/blocks`: - `tsc --noEmit`: 0 errors, as before. - `tsc --noEmit --noImplicitAny`: `src/cms/schema.ts` goes from 1 error to 0. The other 7 errors are in `sectionLoaders.test.ts` and `useScript.test.ts`, which this PR doesn't touch. - `vitest run packages/blocks/src/cms`: 333 tests pass. `biome check` on this file reports the same two items with and without this change (a format issue around line 955 and `useOptionalChain` at line 1139). I left them alone to keep the diff to one line. Found on the Pague Menos storefront (`pmenos/fast-store-pmenos`, PR #588), which has to run `noImplicitAny` in a separate script because of this error. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Fixes `@decocms/blocks` 7.x so `src/cms/schema.ts` compiles when consuming sites enable `noImplicitAny`. The package ships TypeScript source, so `tsc` and `next build` check it with each site's compiler options; `siteLoaderRefs` was inferred as `any`, which left the `.filter()` callback parameter implicitly typed and failed the build. Annotating it as `{ $ref: string }[]` is type-only, so the emitted JS is unchanged. <sup>Written for commit 32d8087. Summary will update on new commits.</sup> <a href="https://cubic.dev/pr/decocms/blocks/pull/778?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="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <a href="https://www.cubic.dev/action/auto-fix/pr/decocms/blocks/778?returnTo=https%3A%2F%2Fgithub.com%2Fdecocms%2Fblocks%2Fpull%2F778&source=description" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img alt="Turn on auto-fix" src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a> <!-- End of auto-generated description by cubic. --> Co-authored-by: Claude Opus 5.5 <[email protected]>
Por quê
Uma seção deferida (⚡) tem os
rawPropsremovidos antes da serialização — eles podem carregarlistas inteiras de produto — e o
DeferredSectionSkeletonficou passando{}para oLoadingFallbackda seção. Duas consequências, ambas no HTML servido, não só depois dahidratação:
recomendados entrega
<h2></h2>onde a produção (Deco no Fresh, que passa as propsresolvidas ao fallback) entrega
Você pode ter perdido. Crawler nenhum vê esse conteúdo. E otexto muda por página — a mesma seção entrega
Você pode gostarna rota do post —, então umdefault fixo no fallback não substitui o dado.
O que muda
A seção declara o que o esqueleto dela pode renderizar:
O caminho, em quatro pontos:
generate-sections.tsexport const fallbackPropsda seção e emite a lista emsectionMetaapplySectionConventionsregisterFallbackPropsSectionscom o mapa seção → propsresolve.ts— serializaçãodeferred.fallbackProps, antes dodelete deferred.rawProps. Seção sem declaração: nada é serializado.DecoPageRenderer.tsx— renderdeferred.fallbackProps ?? {}Declarar é o opt-in, e ele é por seção, não por site. Nada que a seção não tenha nomeado
chega ao cliente — nem payload nem uma prop que só o loader usava dependem de heurística de
tamanho. Seção que não declara nada segue desenhando o esqueleto com
{}: quem só sobe deversão não serializa um byte novo. É também por isso que não existe chave global: um fallback
escrito contra
{}pode renderizar diferente ao receber props (um que espalha{...props}nocomponente real, por exemplo), e essa decisão é de quem escreveu a seção.
Props declaradas ainda passam por um filtro de primitivos — objeto ou array traria de volta o
grafo que o
rawPropsfoi removido para evitar — e string vazia cai fora, porque um default deparâmetro (
{ title = DEFAULT }) só vale paraundefined.Conferido nos outros dois storefronts que rodam este runtime (
granadobr-tanstack7.64.3 ecasaevideo-tanstack7.71.5): nenhuma seção declarafallbackProps, então o payload deferidoé idêntico ao de hoje. No Casa&Vídeo, que defere a partir do índice 3, os fallbacks de
Header/NewHeader— os únicos que espalham props no componente real — seguem em{}.Verificação
Linkado num storefront consumidor real (
oficina-tanstack,/the-post, 4 seções deferidas),buildado e medido por CDP, com a seção declarando
galleryTitle:<h2>vazio no HTML servidogalleryTitleno HTML servido<img>no DOM antes de rolarTestes: 7 casos novos — 4 em
pickFallbackProps(props declaradas, chave não declaradaignorada mesmo sendo string, objeto numa chave declarada, string vazia) e 3 de integração pelo
resolveDecoPage: seção sem declaração (nemrawPropsnemfallbackPropsno objetodeferido), seção com declaração (só a prop declarada viaja,
rawPropssegue ausente) e clientnav.
resolve.test.ts: 86 passando, 0 falhando.tsc --noEmitlimpo emblocksetanstack.biome checknos seis arquivos tocados: 9 erros / 5 avisos na base e no branch —nenhum lint novo. As 29 falhas em
loader.test.ts/layoutCacheRace.test.tssão idênticas nabase (
matchPath, pré-existentes).Nota de revisão
skeletonPropsnão lê maisrawProps: oresolveDecoPageos apaga antes de devolver, entãonenhum render — SSR ou client nav — chegava a vê-los, e o
rawProps ??era ramo morto.