Repository navigation
Conversation
…nsitively
Two independent parsing bugs found while investigating a redirect loop; neither
causes the loop, both corrupt real data.
Quoted fields: `parseRedirectsCsv` split on every comma, but bulk exports quote
rows whose query contains one:
"https://site/relogios?map=category-1,category-2",/relogios,PERMANENT
That row parsed as from=`/"https://site/relogios?map=category-1`,
to=`category-2"`. In one production CSV, 643 of 3017 rows came out with a
fragment of a query as their target (`to: "c"`, `to: "priceFrom"`). They are
inert today only because the mangled source never matches a request.
Type spelling: only lowercase `permanent` mapped to 301. Exports commonly write
`PERMANENT`, so every one of that site's ~3000 redirects served 302 — a
temporary redirect passes no ranking signal to the new URL, silently discarding
the SEO value of the migration.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Contributor
|
Cross-reference: #647 keeps the type comparison exact on purpose — in deco-apps |
guitavano
pushed a commit
that referenced
this pull request
Oct 9, 2026
… handlers (307, query kept, no double-encode) (#647) ## Update — Fresh semantics are opt-in The Fresh semantics below change what every site **already** on `@decocms/*` answers on upgrade (302 → 307, `/Old` no longer matching `/old`, the query now in `Location`). They are now **opt-in per site**: ```ts createDecoWorkerEntry(serverEntry, { redirects: { semantics: "fresh" } }); ``` (`setRedirectSemantics` in `@decocms/blocks/sdk/redirects` for code outside the worker entry). The default, `"legacy"`, keeps today's answers: case- and trailing-slash-insensitive match, temporary → 302, query dropped. **In both semantics** (rules that could never be served correctly): - self-redirects dropped — `from === to`, and in `"legacy"` also the ones folding creates (`/Calca/p → /calca/p`, `/x → /x?utm=1`), which loop forever on `main`; - `Location` not double-encoded (`%20` stays `%20`; non-ASCII/space still encoded); - a query-scoped source (`/x?map=ft`) matches `pathname + search` before `pathname` (it never matched before); - the CSV is parsed like Fresh's (`,`/`;` split, `type`/`discardQueryParameters` by value, `forcePermanentRedirects`). **KV-keyed redirects stay semantics-agnostic** (the sync runs where the worker's choice is unknown): keys are `normalizePath` again — folded, byte-identical to `main` — and each value carries the source as written, as an array when several sources fold to one key (`ExactRedirect.shadowed`). `selectExactRedirect` serves the last rule for `"legacy"` (as `main`) and the byte-for-byte one for `"fresh"`. Temporary is stored as 307 and answered 302 under `"legacy"`. Values written before `from` existed are still read. **Checked against `main`'s implementation with the redirect blocks of two live `@decocms/tanstack` sites** (every rule × case/trailing-slash/query variants, in-memory and KV paths): - site A (9 rules): 54/54 probes and 9/9 KV keys identical; - site B (170 rules): 1008/1020 identical; the 12 differences are its 2 self-redirect rules (`/kit-…` → itself), which answer a 301 loop on `main` and are now dropped. Tests: `redirects.test.ts` now runs under `"fresh"`; new `redirects.legacy.test.ts` (16) pins the default; `kvRedirects.test.ts` (+3) covers folded lookup and both selections; `workerEntry.test.ts` runs the Fresh cases with the option and adds an end-to-end legacy case. `blocks`/`tanstack` typecheck clean; same pre-existing failures as before (`loader`/`layoutCacheRace` on Node 22 without `URLPattern`, 3 draft-preview/CDN in `workerEntry.test.ts`). The section below describes the `"fresh"` semantics. --- ## Problem `@decocms/blocks/sdk/redirects` materializes a site's `redirects.csv` (and `website/loaders/redirect(s).ts` blocks) with rules that differ from the Fresh loaders/handlers it replaced. Validating deco-sites/oficina-tanstack (5 835-row CSV) against the Fresh production site, every one of them changed what a visitor gets: | | Fresh (deco-apps) | `main` | Effect measured on the site | |---|---|---|---| | Source key | `pathname` (or `pathname + search`), byte for byte | `normalizePath`: lower-cased, trailing slash dropped, `/` forced | `/Calca-Linho-Santorini-Off-White-0077631037/p → /calca-…/p` became a self-redirect: **3 live PDPs looped (`ERR_TOO_MANY_REDIRECTS`)**. Rows differing only by case/slash overwrote each other (`/meia-pima-…/p` sent to the `…/p/` row's destination). 206 lower-case paths that 404 in prod started redirecting. | | `type` | `permanent` → 301, anything else → 307 (exact compare) | `permanent`/`301` → 301, else **302** | 107/310 sampled URLs: prod 307, candidate 302 (82 % of the file is `PERMANENT`, which is 307 in Fresh). | | Query string | appended to `Location` unless `discardQueryParameters` | dropped | `?utm_source=qa&gclid=x` lost on every CSV redirect — campaign attribution. | | `?query` in source | matches `pathname + search` first | never matches (key kept the `?`, lookup used `pathname` only) | `/garrafa-kouda-preta-…/p?listName=Kouda`: prod 307 → `/roupas/acessorios?listName=Kouda`; candidate served the PDP. | | `Location` | `to` as written | `encodeURI(to)` | `…/Regulamento%20Oficina….pdf` → `%2520` → CDN 403. | | `from === to` | dropped at load | kept | loop | Full report with the 310-row table (prod × candidate, line by line): `.context/qa-162-redirects.md` in deco-sites/oficina-tanstack#479. ## Reference behaviour deco-apps as pinned by the Fresh site (`oficina-dev/deco-apps@60695e7`): - [`website/loaders/redirectsFromCsv.ts`](https://github.com/oficina-dev/deco-apps/blob/60695e70370e41b0b532066563c6e564b52c58e2/website/loaders/redirectsFromCsv.ts) — field split `/,|;(?=(?:(?:[^"]*"){2})*[^"]*$)/`, `type`/`discardQueryParameters` found by value (`findAndRemove`), `if (!from || !to || from === to) continue`, `isHref: true`. - [`website/handlers/router.ts`](https://github.com/oficina-dev/deco-apps/blob/60695e70370e41b0b532066563c6e564b52c58e2/website/handlers/router.ts) — `hrefRoutes[pathname + search] ?? hrefRoutes[pathname]`, exact, case-sensitive. - [`website/handlers/redirect.ts`](https://github.com/oficina-dev/deco-apps/blob/60695e70370e41b0b532066563c6e564b52c58e2/website/handlers/redirect.ts) — `temporary → 307`, `permanent → 301`, `Location = to + request query` unless `discardQueryParameters`. Curated blocks (`website/loaders/redirects.ts`) go through the same router/handler, so the same semantics apply to them here. ## Fix `packages/blocks/src/sdk/redirects.ts` - `normalizePath` strips the origin of an absolute source and nothing else (case, trailing slash and query are part of the URL). It is still the KV key contract; the request pathname is already in that form. - `matchRedirect` / `matchExactRedirect` take the request's `search` and look up `pathname + search` before `pathname`. - `parseRedirectsCsv` uses Fresh's split and reads `type` / `discardQueryParameters` by value in any column; `forcePermanentRedirects` is honoured (the loader prop). - `permanent` → 301, anything else → 307. The `301` spelling the previous parser accepted is kept. - `from === to` rows dropped at load (CSV and blocks). - New `redirectLocation(redirect, search)`: `to` + the request's query sorted by key (pairs kept as sent — what the Fresh runtime handed the handler), honouring `discardQueryParameters`; only characters a header cannot carry are percent-encoded, so an existing `%20` stays `%20`. - `splitExactRedirects` keeps query-scoped rules in the decofile (like globs), so the fast-deploy KV lookup stays one read per request, keyed by pathname. `ExactRedirect`/`StoredRedirect` carry `discardQueryParameters`. `packages/tanstack/src/sdk/workerEntry.ts` passes `url.search` and answers with `redirectLocation`. `kvRedirects.ts` reads the new value shape. `packages/blocks-cli/scripts/lib/csv-redirects.ts` carries `discardQueryParameters` and `forcePermanentRedirects` into the synthetic block. `docs/fast-deploy.md` updated. ## Behaviour change under `semantics: "fresh"` (opt-in — the default keeps today's answers) A site that opts in answers its redirects like the Fresh site it was migrated from: 1. **Temporary redirects are 307, not 302.** Same semantics for GET; 307 is what Fresh served. 2. **Matching is case-sensitive and trailing-slash exact.** A rule written as `/Old` no longer matches `/old`. Fresh never matched that way, so a migrated CSV cannot have depended on it; a rule authored after migration that relied on the folding would need its source fixed. 3. The request's query now travels with the `Location` (including `?asJson`, so a client following the redirect still gets JSON — test updated accordingly). 4. ~~KV redirect keys change shape~~ — superseded by the update above: keys stay folded; the value carries the source. Not reproduced on purpose, because it is site-level ordering in Fresh rather than redirect semantics: Fresh answered a trailing-slash request with a 307 strip *before* the CSV, so a `from` ending in `/` was dead there; here it matches `/x/` requests. The reference site handles that in its own worker entry. ## Validation Replayed the 310 probes of the QA sample (real CSV, prod's first hop recorded) through the new SDK: **285/310 identical** (status + `Location`); 18 are trailing-slash sources (the site-level ordering above); 5 are URLs with no rule where prod answers the site's own lower-case 301; 2 are probes where prod itself returned `ENOTFOUND` (malformed probe URL, and the CSV has the slash-prefixed duplicate the SDK matched). ## Tests - New `packages/blocks/src/sdk/redirects.test.ts` (27 cases, built from the real rows): case/slash-exact matching, percent-encoded pathname, no-leading-slash and non-ASCII sources never match, query-scoped precedence, status table (`PERMANENT` → 307, `forcePermanentRedirects`), columns by value, `;` split, CRLF, self-redirects, `redirectLocation` (sorted query, discard, `%20` kept, non-ASCII encoded), `splitExactRedirects` (query rows stay, flag carried). - `workerEntry.test.ts`: +2 end-to-end cases (query appended/discarded; query-scoped before bare path and `/Calca/p → /calca/p` is a redirect, not a loop); 302 → 307 and `?asJson` expectations updated. - `csv-redirects.test.ts`: +1 (`discardQueryParameters` + `forcePermanentRedirects`); `splitExactRedirects.test.ts`, `kvRedirects.test.ts`, `fast-deploy-kv.test.ts`: 302 → 307 / key-contract expectations updated. Ran per package: `blocks` 895 passed (the 40 failures in `layoutCacheRace.test.ts` / `loader.test.ts` fail identically on `main`), `tanstack` 280 passed (3 draft-preview failures identical on `main`), `blocks-cli` 849 passed. `tsc --noEmit` clean for `blocks` and `tanstack` (`blocks-cli` has pre-existing errors in `scripts/migrate/*.test.ts`, untouched). `biome check` clean on the files changed (remaining warnings in `workerEntry.ts`/`index.ts`/`fast-deploy-kv.test.ts` are pre-existing on `main`). ## Related Supersedes the approach in the draft PRs #519 (self-loop guard on the folded key), #520 (query-scoped rules via a separate map) and #521 (case-insensitive `PERMANENT`, quoted-field split): with exact keys the loop and the collision disappear at the source, `pathname + search` lookup is what Fresh did, and `PERMANENT` is deliberately 307 because that is what the Fresh site serves. The quoted-field split is not Fresh behaviour either (its regex only quote-guards `;`). Found while validating deco-sites/oficina-tanstack#479. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Aligns redirect handling in `@decocms/blocks/sdk/redirects` and the TanStack worker with the Fresh loaders and handlers it replaced. The Fresh semantics are now opt-in per site via `createDecoWorkerEntry({ redirects: { semantics: "fresh" } })`; the default `"legacy"` keeps what sites already on `@decocms/*` answer today, so enabling `"fresh"` for one site changes nothing for the others. **Behavior change** - `"fresh"`: sources match the request's pathname byte for byte (case, trailing slash, query included) instead of a lower-cased, slash-folded key, which turned `/Calca-x/p → /calca-x/p` into a self-redirect that looped on three live PDPs. Temporary redirects answer 307 instead of 302, query-scoped rules match `pathname + search` before the bare path, and the request's query is appended to `Location` unless `discardQueryParameters` is set. - Both semantics: `from === to` rows are dropped at load, `Location` is no longer double-encoded (`%20` stays `%20`), and the CSV is parsed like Fresh's (`type`/`discardQueryParameters` read by value, `;` split outside quotes). - KV keys stay folded (`redirect:<id>:<path>` via `normalizePath`, as on `main`); each value now carries the source as written plus every rule folding to the same key, so the request-time reader can serve either semantics. `docs/fast-deploy.md` documents the value shape and the folded-key contract in both semantics. <sup>Written for commit 8198bdf. Summary will update on new commits.</sup> <a href="https://cubic.dev/pr/decocms/blocks/pull/647?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/647?returnTo=https%3A%2F%2Fgithub.com%2Fdecocms%2Fblocks%2Fpull%2F647&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 Fable 5.1 <[email protected]>
Contributor
|
Retargeted to |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Dois bugs de parsing achados investigando um loop de redirect. Nenhum dos dois causa o loop (isso é o #519) e nenhum depende do outro — mas os dois corrompem dado real, e são pequenos o bastante para irem juntos.
Independente do #519 e do #520; pode mergear em qualquer ordem. Encosta em
parseRedirectsCsv, então espere um conflito trivial com o #519.1.
split(",")ignorava aspasExports de redirect em massa citam linhas cuja query contém vírgula — o padrão de URL de categoria do VTEX:
O split cru quebrava nas vírgulas de dentro das aspas, produzindo:
Num CSV de produção, 643 das 3017 linhas saíram assim, com um pedaço da query como destino:
to: "c",to: "priceFrom",to: "specificationFilter_29". Hoje elas são inofensivas só por acidente — a origem mutilada (/"https://…) nunca casa com request nenhuma. Mas é 1/5 do arquivo virando lixo silencioso, e a próxima linha citada que não comece comhttpvira uma regra ativa apontando para um destino inventado.Agora o split respeita aspas, incluindo
""escapado (RFC 4180).2.
PERMANENTvirava 302Exports escrevem
PERMANENTem caixa alta. Como só a grafia minúscula casava, todos os ~3000 redirects daquele site serviam 302. Redirect temporário não passa sinal de ranking para a URL nova — a migração inteira jogou fora o valor de SEO das URLs antigas, sem erro nenhum em log.Agora o tipo é lido sem diferenciar caixa, no CSV e nos blocos de CMS.
Testes
packages/blocks/src/sdk/redirectsCsvParsing.test.ts, 8 casos. 5 falham nomain:Um dos casos documenta a fronteira em vez de esconder: uma linha sem aspas cuja query tem vírgula continua sendo picada. Aspas são o que torna a vírgula literal; adivinhar seria pior que falhar.
Suíte do pacote: 746 passed (56 arquivos).
Contexto
🤖 Generated with Claude Code
Summary by cubic
Fixes two independent bugs in
parseRedirectsCsv— quoted CSV fields were split on commas inside quotes, and uppercasePERMANENTredirect types were served as 302.""is unescaped per RFC 4180; previously, 643 of 3017 rows in one production export had a query fragment as their target.PERMANENT,Permanent,permanent, and301all map to 301, in both CSV and CMS block redirects.Written for commit 59f5477. Summary will update on new commits.