@decocms/blocks 7.77.10 → 7.77.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/cms/blockSource.ts +11 -2
- package/src/cms/schema.test.ts +52 -0
- package/src/cms/schema.ts +86 -5
- package/src/sdk/index.ts +1 -0
- package/src/sdk/redirects.legacy.test.ts +164 -0
- package/src/sdk/redirects.test.ts +328 -0
- package/src/sdk/redirects.ts +384 -79
- package/src/sdk/splitExactRedirects.test.ts +9 -7
package/src/sdk/redirects.ts
CHANGED
|
@@ -5,26 +5,49 @@
|
|
|
5
5
|
* fast path matching for use in TanStack Start middleware.
|
|
6
6
|
*
|
|
7
7
|
* Supports:
|
|
8
|
-
* - Exact
|
|
8
|
+
* - Exact matches (/old-page -> /new-page), optionally scoped to a query
|
|
9
|
+
* (/old-page?map=ft -> /new-page)
|
|
9
10
|
* - Glob patterns (/old/* -> /new/*)
|
|
10
|
-
* - Permanent (301) and temporary (
|
|
11
|
+
* - Permanent (301) and temporary (307) redirects
|
|
11
12
|
* - CSV import for bulk redirects
|
|
12
13
|
*
|
|
14
|
+
* The semantics are those of the Fresh loaders and handlers this module
|
|
15
|
+
* replaced (deco-cx/apps `website/loaders/redirectsFromCsv.ts`,
|
|
16
|
+
* `website/loaders/redirects.ts`, `website/handlers/router.ts`,
|
|
17
|
+
* `website/handlers/redirect.ts`), so a site migrated from Fresh answers the
|
|
18
|
+
* same URL with the same status and `Location`:
|
|
19
|
+
*
|
|
20
|
+
* - a source matches the request's `pathname` (or `pathname + search`) byte
|
|
21
|
+
* for byte — no case folding, no trailing-slash folding. `/Calca-x/p` and
|
|
22
|
+
* `/calca-x/p` are two different rules, and a rule from `/Calca-x/p` to
|
|
23
|
+
* `/calca-x/p` is a redirect, not a loop;
|
|
24
|
+
* - `type` is `permanent` (301) or anything else (307 — `PERMANENT` in capitals
|
|
25
|
+
* included, as in Fresh);
|
|
26
|
+
* - the request's query string is appended to `Location` unless the rule sets
|
|
27
|
+
* `discardQueryParameters`, so campaign parameters survive the hop.
|
|
28
|
+
*
|
|
29
|
+
* Both: a rule whose source equals its target is dropped at load time (and, in
|
|
30
|
+
* `"legacy"`, a rule that folding turns into a self-redirect — `/Calca/p` →
|
|
31
|
+
* `/calca/p`), `Location` is never double-encoded (`%20` stays `%20`), a
|
|
32
|
+
* query-scoped source (`/x?map=ft`) matches `pathname + search` before the bare
|
|
33
|
+
* pathname, and the CSV is parsed like Fresh's (`,`/`;` split, `type` and
|
|
34
|
+
* `discardQueryParameters` read by value).
|
|
35
|
+
*
|
|
13
36
|
* @example
|
|
14
37
|
* ```ts
|
|
15
38
|
* // In TanStack Start middleware
|
|
16
|
-
* import { loadRedirects, matchRedirect } from "@decocms/
|
|
17
|
-
* import { loadBlocks } from "@decocms/
|
|
39
|
+
* import { loadRedirects, matchRedirect, redirectLocation } from "@decocms/blocks/sdk/redirects";
|
|
40
|
+
* import { loadBlocks } from "@decocms/blocks/cms";
|
|
18
41
|
*
|
|
19
42
|
* const redirects = loadRedirects(loadBlocks());
|
|
20
43
|
*
|
|
21
44
|
* const middleware = createMiddleware().server(async ({ next, request }) => {
|
|
22
45
|
* const url = new URL(request.url);
|
|
23
|
-
* const redirect = matchRedirect(url.pathname, redirects);
|
|
46
|
+
* const redirect = matchRedirect(url.pathname, redirects, url.search);
|
|
24
47
|
* if (redirect) {
|
|
25
48
|
* return new Response(null, {
|
|
26
49
|
* status: redirect.status,
|
|
27
|
-
* headers: { Location: redirect.
|
|
50
|
+
* headers: { Location: redirectLocation(redirect, url.search) },
|
|
28
51
|
* });
|
|
29
52
|
* }
|
|
30
53
|
* return next();
|
|
@@ -32,18 +55,56 @@
|
|
|
32
55
|
* ```
|
|
33
56
|
*/
|
|
34
57
|
|
|
58
|
+
// -------------------------------------------------------------------------
|
|
59
|
+
// Semantics
|
|
60
|
+
// -------------------------------------------------------------------------
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* `"legacy"`: case- and trailing-slash-insensitive match, 302 for temporary,
|
|
64
|
+
* query dropped. `"fresh"`: the Fresh handlers' byte-for-byte match, 307, query
|
|
65
|
+
* kept. See the module doc.
|
|
66
|
+
*/
|
|
67
|
+
export type RedirectSemantics = "legacy" | "fresh";
|
|
68
|
+
|
|
69
|
+
// globalThis-backed so every Vite server-function split-module copy reads the
|
|
70
|
+
// same value (same reason as `kvRedirects.ts`'s cache).
|
|
71
|
+
const G = globalThis as unknown as { __decoRedirectSemantics?: RedirectSemantics };
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Choose the redirect semantics for this isolate. Call once at boot, before the
|
|
75
|
+
* first `loadRedirects` — a map already built keeps the keys it was built with.
|
|
76
|
+
* `createDecoWorkerEntry({ redirects: { semantics } })` does this for you.
|
|
77
|
+
*/
|
|
78
|
+
export function setRedirectSemantics(semantics: RedirectSemantics): void {
|
|
79
|
+
G.__decoRedirectSemantics = semantics;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function getRedirectSemantics(): RedirectSemantics {
|
|
83
|
+
return G.__decoRedirectSemantics ?? "legacy";
|
|
84
|
+
}
|
|
85
|
+
|
|
35
86
|
// -------------------------------------------------------------------------
|
|
36
87
|
// Types
|
|
37
88
|
// -------------------------------------------------------------------------
|
|
38
89
|
|
|
39
90
|
export interface Redirect {
|
|
91
|
+
/**
|
|
92
|
+
* Source as matched: the map key (`normalizePath` in `"legacy"`,
|
|
93
|
+
* `sourcePath` in `"fresh"`), or that plus `?search` for a query-scoped rule.
|
|
94
|
+
*/
|
|
40
95
|
from: string;
|
|
41
96
|
to: string;
|
|
42
|
-
|
|
97
|
+
/** 301 for `permanent`; temporary is 302 in `"legacy"`, 307 in `"fresh"`. */
|
|
98
|
+
status: 301 | 302 | 307;
|
|
99
|
+
/**
|
|
100
|
+
* Answer with `to` as written instead of appending the request's query
|
|
101
|
+
* string to it. Only present when true; only read in `"fresh"`.
|
|
102
|
+
*/
|
|
103
|
+
discardQueryParameters?: boolean;
|
|
43
104
|
}
|
|
44
105
|
|
|
45
106
|
export interface RedirectMap {
|
|
46
|
-
/** Exact match redirects for O(1) lookup. */
|
|
107
|
+
/** Exact match redirects for O(1) lookup, keyed by `Redirect.from`. */
|
|
47
108
|
exact: Map<string, Redirect>;
|
|
48
109
|
/** Glob/prefix redirects checked sequentially (few in practice). */
|
|
49
110
|
patterns: Array<{ prefix: string; redirect: Redirect }>;
|
|
@@ -57,6 +118,7 @@ interface BlockRedirectEntry {
|
|
|
57
118
|
from: string;
|
|
58
119
|
to: string;
|
|
59
120
|
type?: "permanent" | "temporary";
|
|
121
|
+
discardQueryParameters?: boolean;
|
|
60
122
|
}
|
|
61
123
|
|
|
62
124
|
const REDIRECT_RESOLVE_TYPES = new Set([
|
|
@@ -78,11 +140,10 @@ export function registerRedirectResolveType(resolveType: string): void {
|
|
|
78
140
|
* Load all redirect definitions from CMS blocks.
|
|
79
141
|
*
|
|
80
142
|
* Scans the blocks for known redirect resolve types and builds
|
|
81
|
-
* a fast-lookup redirect map
|
|
143
|
+
* a fast-lookup redirect map, keyed for the current `getRedirectSemantics()`.
|
|
82
144
|
*/
|
|
83
145
|
export function loadRedirects(blocks: Record<string, unknown>): RedirectMap {
|
|
84
|
-
const
|
|
85
|
-
const patterns: Array<{ prefix: string; redirect: Redirect }> = [];
|
|
146
|
+
const map: RedirectMap = { exact: new Map(), patterns: [] };
|
|
86
147
|
|
|
87
148
|
for (const [_key, block] of Object.entries(blocks)) {
|
|
88
149
|
if (!block || typeof block !== "object") continue;
|
|
@@ -101,59 +162,76 @@ export function loadRedirects(blocks: Record<string, unknown>): RedirectMap {
|
|
|
101
162
|
const list = Array.isArray(entries) ? entries : [entries];
|
|
102
163
|
|
|
103
164
|
for (const entry of list) {
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
const redirect: Redirect = {
|
|
107
|
-
from: normalizePath(entry.from),
|
|
108
|
-
to: entry.to,
|
|
109
|
-
status: entry.type === "permanent" ? 301 : 302,
|
|
110
|
-
};
|
|
111
|
-
|
|
112
|
-
if (redirect.from.includes("*")) {
|
|
113
|
-
const prefix = redirect.from.replace(/\*+$/, "");
|
|
114
|
-
patterns.push({ prefix, redirect });
|
|
115
|
-
} else {
|
|
116
|
-
exact.set(redirect.from, redirect);
|
|
117
|
-
}
|
|
165
|
+
const redirect = toRedirect(entry);
|
|
166
|
+
if (redirect) addToMap(map, redirect);
|
|
118
167
|
}
|
|
119
168
|
}
|
|
120
169
|
|
|
121
|
-
return
|
|
170
|
+
return map;
|
|
122
171
|
}
|
|
123
172
|
|
|
124
173
|
// -------------------------------------------------------------------------
|
|
125
174
|
// CSV import
|
|
126
175
|
// -------------------------------------------------------------------------
|
|
127
176
|
|
|
177
|
+
export interface ParseRedirectsCsvOptions {
|
|
178
|
+
/**
|
|
179
|
+
* Rows without an explicit type are `permanent` (301) instead of
|
|
180
|
+
* `temporary` — the `forcePermanentRedirects` prop of the Fresh
|
|
181
|
+
* `redirectsFromCsv` loader.
|
|
182
|
+
*/
|
|
183
|
+
forcePermanentRedirects?: boolean;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const REDIRECT_TYPE_VALUES = ["temporary", "permanent", "301"];
|
|
187
|
+
const DISCARD_QUERY_VALUES = ["true", "false"];
|
|
188
|
+
|
|
189
|
+
/** Fresh's field split, verbatim: a comma always splits; a semicolon only outside quotes. */
|
|
190
|
+
const CSV_FIELD_SPLIT = /,|;(?=(?:(?:[^"]*"){2})*[^"]*$)/;
|
|
191
|
+
|
|
192
|
+
/** Remove and return the first element of `array` that is one of `values`. */
|
|
193
|
+
function findAndRemove(array: string[], values: string[]): string | null {
|
|
194
|
+
const index = array.findIndex((item) => values.includes(item));
|
|
195
|
+
return index === -1 ? null : array.splice(index, 1)[0];
|
|
196
|
+
}
|
|
197
|
+
|
|
128
198
|
/**
|
|
129
199
|
* Parse a CSV string into redirect entries.
|
|
130
200
|
*
|
|
131
|
-
* Expected format: `from,to[,type]` (one per line).
|
|
132
|
-
*
|
|
133
|
-
*
|
|
201
|
+
* Expected format: `from,to[,type][,discardQueryParameters]` (one per line).
|
|
202
|
+
* `type` and `discardQueryParameters` are recognized by value, in any column
|
|
203
|
+
* after the first two: `type` is `permanent` (301) or `temporary` (the
|
|
204
|
+
* default); `discardQueryParameters` is `true` or `false`. The comparison is
|
|
205
|
+
* exact, as in Fresh — `PERMANENT` is not `permanent` and yields a temporary.
|
|
206
|
+
*
|
|
207
|
+
* `from` is returned as written — the map it is added to keys it for its
|
|
208
|
+
* semantics.
|
|
209
|
+
*
|
|
210
|
+
* Lines starting with # are comments. Empty lines and the header row are
|
|
211
|
+
* skipped. A row whose source equals its target is dropped.
|
|
134
212
|
*/
|
|
135
|
-
export function parseRedirectsCsv(csv: string): Redirect[] {
|
|
213
|
+
export function parseRedirectsCsv(csv: string, options: ParseRedirectsCsvOptions = {}): Redirect[] {
|
|
136
214
|
const redirects: Redirect[] = [];
|
|
137
|
-
const lines = csv.split(
|
|
215
|
+
const lines = csv.split(/\r\n|\r|\n/);
|
|
138
216
|
|
|
139
217
|
for (const raw of lines) {
|
|
140
218
|
const line = raw.trim();
|
|
141
219
|
if (!line || line.startsWith("#")) continue;
|
|
142
220
|
|
|
143
|
-
const parts = line.split(
|
|
144
|
-
|
|
221
|
+
const parts = line.split(CSV_FIELD_SPLIT).map((p) => p.trim());
|
|
222
|
+
const type =
|
|
223
|
+
findAndRemove(parts, REDIRECT_TYPE_VALUES) ??
|
|
224
|
+
(options.forcePermanentRedirects ? "permanent" : "temporary");
|
|
225
|
+
const discardQueryParameters = findAndRemove(parts, DISCARD_QUERY_VALUES) === "true";
|
|
145
226
|
|
|
146
|
-
const [from, to
|
|
227
|
+
const [from, to] = parts;
|
|
147
228
|
if (!from || !to) continue;
|
|
148
229
|
// Skip a header row (`from,to[,type]`). Robust for CSVs with or without a
|
|
149
230
|
// header, and for a header repeated when multiple files are concatenated.
|
|
150
231
|
if (from.toLowerCase() === "from" && to.toLowerCase() === "to") continue;
|
|
151
232
|
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
to,
|
|
155
|
-
status: type === "permanent" || type === "301" ? 301 : 302,
|
|
156
|
-
});
|
|
233
|
+
const redirect = toRedirect({ from, to, type, discardQueryParameters });
|
|
234
|
+
if (redirect) redirects.push(redirect);
|
|
157
235
|
}
|
|
158
236
|
|
|
159
237
|
return redirects;
|
|
@@ -163,16 +241,71 @@ export function parseRedirectsCsv(csv: string): Redirect[] {
|
|
|
163
241
|
* Add parsed redirects to an existing redirect map.
|
|
164
242
|
*/
|
|
165
243
|
export function addRedirects(map: RedirectMap, redirects: Redirect[]): void {
|
|
166
|
-
for (const redirect of redirects)
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
244
|
+
for (const redirect of redirects) addToMap(map, redirect);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function addToMap(map: RedirectMap, redirect: Redirect): void {
|
|
248
|
+
const from = matchKey(redirect.from);
|
|
249
|
+
if (!from || loopsWhenFolded(from, redirect.to)) return;
|
|
250
|
+
const keyed = from === redirect.from ? redirect : { ...redirect, from };
|
|
251
|
+
if (from.includes("*")) {
|
|
252
|
+
const prefix = from.replace(/\*+$/, "");
|
|
253
|
+
map.patterns.push({ prefix, redirect: keyed });
|
|
254
|
+
} else {
|
|
255
|
+
// Later rules win, as in Fresh's route table.
|
|
256
|
+
map.exact.set(from, keyed);
|
|
173
257
|
}
|
|
174
258
|
}
|
|
175
259
|
|
|
260
|
+
/**
|
|
261
|
+
* One rule from any source (CMS block entry or CSV row), or `null` when it
|
|
262
|
+
* can't be a rule: missing a side, or a self-redirect (`from === to`, which
|
|
263
|
+
* the Fresh loader also skipped and which would otherwise loop forever).
|
|
264
|
+
* `from` is the source as written, not yet a map key.
|
|
265
|
+
*/
|
|
266
|
+
function toRedirect(entry: {
|
|
267
|
+
from?: string;
|
|
268
|
+
to?: string;
|
|
269
|
+
type?: string;
|
|
270
|
+
discardQueryParameters?: boolean;
|
|
271
|
+
}): Redirect | null {
|
|
272
|
+
if (!entry.from || !entry.to) return null;
|
|
273
|
+
// Kept as written: an absolute source keys differently per semantics
|
|
274
|
+
// (`"legacy"` drops its query, `"fresh"` keeps it).
|
|
275
|
+
const from = entry.from.trim();
|
|
276
|
+
const to = entry.to.trim();
|
|
277
|
+
if (!from || !to || sourcePath(from) === to) return null;
|
|
278
|
+
|
|
279
|
+
const redirect: Redirect = { from, to, status: statusFor(isPermanent(entry.type)) };
|
|
280
|
+
if (entry.discardQueryParameters) redirect.discardQueryParameters = true;
|
|
281
|
+
return redirect;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function isPermanent(type: string | undefined): boolean {
|
|
285
|
+
return type === "permanent" || type === "301";
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* `permanent` → 301; anything else → 302 in `"legacy"`, 307 in `"fresh"`
|
|
290
|
+
* (Fresh's `website/handlers/redirect.ts`).
|
|
291
|
+
*/
|
|
292
|
+
function statusFor(permanent: boolean): 301 | 302 | 307 {
|
|
293
|
+
if (permanent) return 301;
|
|
294
|
+
return getRedirectSemantics() === "fresh" ? 307 : 302;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* In `"legacy"` the match folds case and a trailing slash and ignores the
|
|
299
|
+
* query, so a rule whose target folds back to its own key (`/Calca/p` →
|
|
300
|
+
* `/calca/p`, `/x` → `/x?utm=1`) redirects to itself forever. Such a rule can
|
|
301
|
+
* never be served, so it is dropped. Only same-site targets (`/…`) can loop.
|
|
302
|
+
*/
|
|
303
|
+
function loopsWhenFolded(key: string, to: string): boolean {
|
|
304
|
+
if (getRedirectSemantics() !== "legacy") return false;
|
|
305
|
+
if (!to.startsWith("/") || to.startsWith("//")) return false;
|
|
306
|
+
return normalizePath(to.split(/[?#]/)[0]) === key;
|
|
307
|
+
}
|
|
308
|
+
|
|
176
309
|
// -------------------------------------------------------------------------
|
|
177
310
|
// Matching
|
|
178
311
|
// -------------------------------------------------------------------------
|
|
@@ -181,10 +314,12 @@ export function addRedirects(map: RedirectMap, redirects: Redirect[]): void {
|
|
|
181
314
|
* Find a redirect matching the given path.
|
|
182
315
|
*
|
|
183
316
|
* Checks exact matches first (O(1)), then glob patterns (O(n), but
|
|
184
|
-
* typically few patterns exist).
|
|
317
|
+
* typically few patterns exist). Pass the request's `search` (`url.search`)
|
|
318
|
+
* so a rule scoped to a query (`/x?map=ft`) can match: it is tried before the
|
|
319
|
+
* bare pathname, as the more specific rule.
|
|
185
320
|
*/
|
|
186
|
-
export function matchRedirect(pathname: string, map: RedirectMap): Redirect | null {
|
|
187
|
-
return matchExactRedirect(pathname, map) ?? matchPatternRedirect(pathname, map);
|
|
321
|
+
export function matchRedirect(pathname: string, map: RedirectMap, search = ""): Redirect | null {
|
|
322
|
+
return matchExactRedirect(pathname, map, search) ?? matchPatternRedirect(pathname, map);
|
|
188
323
|
}
|
|
189
324
|
|
|
190
325
|
/**
|
|
@@ -193,17 +328,27 @@ export function matchRedirect(pathname: string, map: RedirectMap): Redirect | nu
|
|
|
193
328
|
* `redirect:<id>:<path>` KV lookup, then patterns. Collapsing that to
|
|
194
329
|
* "matchRedirect, then KV" would let a glob win over an exact rule, inverting
|
|
195
330
|
* the precedence every other path has.
|
|
331
|
+
*
|
|
332
|
+
* `pathname + search` is looked up before `pathname`, as Fresh's router does
|
|
333
|
+
* (`hrefRoutes[pathname + search] ?? hrefRoutes[pathname]`).
|
|
196
334
|
*/
|
|
197
|
-
export function matchExactRedirect(
|
|
198
|
-
|
|
335
|
+
export function matchExactRedirect(
|
|
336
|
+
pathname: string,
|
|
337
|
+
map: RedirectMap,
|
|
338
|
+
search = "",
|
|
339
|
+
): Redirect | null {
|
|
340
|
+
const path = matchKey(pathname);
|
|
341
|
+
return (
|
|
342
|
+
(search ? map.exact.get(matchKey(path + search)) : undefined) ?? map.exact.get(path) ?? null
|
|
343
|
+
);
|
|
199
344
|
}
|
|
200
345
|
|
|
201
346
|
/** Pattern half of `matchRedirect` — ordered prefix scan, `*` suffix carried over. */
|
|
202
347
|
export function matchPatternRedirect(pathname: string, map: RedirectMap): Redirect | null {
|
|
203
|
-
const
|
|
348
|
+
const path = matchKey(pathname);
|
|
204
349
|
for (const { prefix, redirect } of map.patterns) {
|
|
205
|
-
if (
|
|
206
|
-
const suffix =
|
|
350
|
+
if (path.startsWith(prefix)) {
|
|
351
|
+
const suffix = path.slice(prefix.length);
|
|
207
352
|
const to = redirect.to.includes("*") ? redirect.to.replace("*", suffix) : redirect.to;
|
|
208
353
|
return { ...redirect, to };
|
|
209
354
|
}
|
|
@@ -211,25 +356,134 @@ export function matchPatternRedirect(pathname: string, map: RedirectMap): Redire
|
|
|
211
356
|
return null;
|
|
212
357
|
}
|
|
213
358
|
|
|
359
|
+
/**
|
|
360
|
+
* The `Location` header for a matched redirect.
|
|
361
|
+
*
|
|
362
|
+
* `"fresh"`: `to`, with the request's query string appended unless the rule
|
|
363
|
+
* discards it (Fresh's `website/handlers/redirect.ts`). Campaign parameters
|
|
364
|
+
* (`utm_*`, `gclid`) survive the hop that way. The query is appended sorted by
|
|
365
|
+
* key, each pair kept as it came (`%20` stays `%20`) — the Fresh runtime handed
|
|
366
|
+
* handlers a request whose query was already in that order, so
|
|
367
|
+
* `?utm_source=qa&gclid=x` answered `?gclid=x&utm_source=qa`.
|
|
368
|
+
*
|
|
369
|
+
* `"legacy"`: `to` alone; the request's query is dropped.
|
|
370
|
+
*
|
|
371
|
+
* Both: `to` travels as written, except for characters a header cannot carry
|
|
372
|
+
* (non-ASCII, spaces, controls), which are percent-encoded. An escape already
|
|
373
|
+
* in `to` (`%20`) is left alone — `encodeURI` would turn it into `%2520`.
|
|
374
|
+
*/
|
|
375
|
+
export function redirectLocation(
|
|
376
|
+
redirect: Pick<Redirect, "to" | "discardQueryParameters">,
|
|
377
|
+
search = "",
|
|
378
|
+
): string {
|
|
379
|
+
const to = encodeForHeader(redirect.to);
|
|
380
|
+
if (getRedirectSemantics() !== "fresh" || redirect.discardQueryParameters) return to;
|
|
381
|
+
const queryString = sortQueryByKey(search);
|
|
382
|
+
if (!queryString) return to;
|
|
383
|
+
return to.includes("?") ? `${to}&${queryString}` : `${to}?${queryString}`;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** Stable sort of `a=1&b=2` pairs by key; pairs are not re-encoded. */
|
|
387
|
+
function sortQueryByKey(search: string): string {
|
|
388
|
+
const raw = search.startsWith("?") ? search.slice(1) : search;
|
|
389
|
+
return raw
|
|
390
|
+
.split("&")
|
|
391
|
+
.filter(Boolean)
|
|
392
|
+
.map((pair, index) => ({ pair, index, key: pair.split("=")[0] }))
|
|
393
|
+
.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : a.index - b.index))
|
|
394
|
+
.map(({ pair }) => pair)
|
|
395
|
+
.join("&");
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
function encodeForHeader(value: string): string {
|
|
399
|
+
return value.replace(/[^\x21-\x7e]/gu, (ch) => encodeURIComponent(ch));
|
|
400
|
+
}
|
|
401
|
+
|
|
214
402
|
// -------------------------------------------------------------------------
|
|
215
|
-
//
|
|
403
|
+
// KV-keyed exact rules
|
|
216
404
|
// -------------------------------------------------------------------------
|
|
217
405
|
|
|
218
|
-
/**
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
406
|
+
/**
|
|
407
|
+
* Value stored at a `redirect:<id>:<path>` key — the same shape as
|
|
408
|
+
* `StoredRedirect` in `@decocms/blocks/cms` (kept structural here so this
|
|
409
|
+
* module doesn't import the CMS barrel). Temporary is always written as 307;
|
|
410
|
+
* `"legacy"` answers it as 302.
|
|
411
|
+
*/
|
|
412
|
+
export interface StoredExactRedirect {
|
|
413
|
+
/** Source as written (`sourcePath`). Absent on values written before it existed. */
|
|
414
|
+
from?: string;
|
|
222
415
|
to: string;
|
|
223
|
-
status: 301 |
|
|
416
|
+
status: 301 | 307;
|
|
417
|
+
discardQueryParameters?: boolean;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** One KV key's worth of exact rules, ready to be written. */
|
|
421
|
+
export interface ExactRedirect extends StoredExactRedirect {
|
|
422
|
+
/** `normalizePath(from)` — the KV key suffix. The same in both semantics. */
|
|
423
|
+
path: string;
|
|
424
|
+
/**
|
|
425
|
+
* Earlier rules whose source folds to the same `path` (`/Meia/p` and
|
|
426
|
+
* `/meia/p/`), in write order. `"legacy"` serves the last rule (this one),
|
|
427
|
+
* as it always has; `"fresh"` picks the one whose `from` is the request's
|
|
428
|
+
* pathname byte for byte. Only present when there are any.
|
|
429
|
+
*/
|
|
430
|
+
shadowed?: StoredExactRedirect[];
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/** The JSON written at an `ExactRedirect`'s key: one rule, or all that share it. */
|
|
434
|
+
export function storedExactRedirectValue({
|
|
435
|
+
path: _path,
|
|
436
|
+
shadowed,
|
|
437
|
+
...rule
|
|
438
|
+
}: ExactRedirect): StoredExactRedirect | StoredExactRedirect[] {
|
|
439
|
+
return shadowed?.length ? [...shadowed, rule] : rule;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* The rule a KV value answers for `pathname` under the current semantics, or
|
|
444
|
+
* `null`. Accepts one rule or the list `storedExactRedirectValue` writes.
|
|
445
|
+
*/
|
|
446
|
+
export function selectExactRedirect(
|
|
447
|
+
value: StoredExactRedirect | StoredExactRedirect[],
|
|
448
|
+
pathname: string,
|
|
449
|
+
): Redirect | null {
|
|
450
|
+
const rules = Array.isArray(value) ? value : [value];
|
|
451
|
+
const key = normalizePath(pathname);
|
|
452
|
+
if (getRedirectSemantics() === "fresh") {
|
|
453
|
+
const source = sourcePath(pathname);
|
|
454
|
+
for (let i = rules.length - 1; i >= 0; i--) {
|
|
455
|
+
const rule = rules[i];
|
|
456
|
+
// A value written before `from` was stored can only be checked by key.
|
|
457
|
+
if ((rule.from ?? source) === source) return toMatched(source, rule, 307);
|
|
458
|
+
}
|
|
459
|
+
return null;
|
|
460
|
+
}
|
|
461
|
+
const rule = rules[rules.length - 1];
|
|
462
|
+
if (!rule || loopsWhenFolded(key, rule.to)) return null;
|
|
463
|
+
return toMatched(key, rule, 302);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function toMatched(from: string, rule: StoredExactRedirect, temporary: 302 | 307): Redirect {
|
|
467
|
+
const redirect: Redirect = {
|
|
468
|
+
from,
|
|
469
|
+
to: rule.to,
|
|
470
|
+
status: rule.status === 301 ? 301 : temporary,
|
|
471
|
+
};
|
|
472
|
+
if (rule.discardQueryParameters) redirect.discardQueryParameters = true;
|
|
473
|
+
return redirect;
|
|
224
474
|
}
|
|
225
475
|
|
|
476
|
+
// -------------------------------------------------------------------------
|
|
477
|
+
// Splitting exact rules out of the decofile (KV-keyed redirects)
|
|
478
|
+
// -------------------------------------------------------------------------
|
|
479
|
+
|
|
226
480
|
export interface SplitRedirectsResult {
|
|
227
481
|
/** The blocks map with every EXACT rule removed. Glob rules stay (they can't
|
|
228
482
|
* be addressed by key), and a redirect block left with no entries at all is
|
|
229
483
|
* dropped entirely rather than left as an empty husk. */
|
|
230
484
|
blocks: Record<string, unknown>;
|
|
231
|
-
/** The extracted exact rules,
|
|
232
|
-
* `loadRedirects
|
|
485
|
+
/** The extracted exact rules, one per KV key (last wins for `"legacy"`,
|
|
486
|
+
* matching `loadRedirects`; the others ride along in `shadowed`). */
|
|
233
487
|
exact: ExactRedirect[];
|
|
234
488
|
}
|
|
235
489
|
|
|
@@ -242,6 +496,11 @@ export interface SplitRedirectsResult {
|
|
|
242
496
|
* request and usually matches nothing. Moved to one KV key each, the list is
|
|
243
497
|
* never loaded.
|
|
244
498
|
*
|
|
499
|
+
* Independent of the redirect semantics: it runs at sync time, where the
|
|
500
|
+
* worker's choice is unknown. Keys are `normalizePath` (what `"legacy"` has
|
|
501
|
+
* always looked up), and each value carries the source as written so the
|
|
502
|
+
* request-time lookup can apply either semantics (`selectExactRedirect`).
|
|
503
|
+
*
|
|
245
504
|
* Read-only over `blocks`: the returned map shares every untouched value and
|
|
246
505
|
* only clones the redirect blocks it had to rewrite.
|
|
247
506
|
*/
|
|
@@ -271,21 +530,38 @@ export function splitExactRedirects(blocks: Record<string, unknown>): SplitRedir
|
|
|
271
530
|
|
|
272
531
|
const kept: BlockRedirectEntry[] = [];
|
|
273
532
|
for (const entry of Array.isArray(raw) ? raw : [raw]) {
|
|
274
|
-
|
|
275
|
-
|
|
533
|
+
const redirect = entry ? toRedirect(entry) : null;
|
|
534
|
+
if (!redirect) continue;
|
|
535
|
+
const from = sourcePath(redirect.from);
|
|
536
|
+
const path = normalizePath(redirect.from);
|
|
276
537
|
// Globs must be scanned in order against the request path, so they can
|
|
277
538
|
// never be a key lookup — they stay in the decofile.
|
|
539
|
+
// Query-scoped rules stay too: the request-time lookup keys by pathname
|
|
540
|
+
// alone, so one KV read per request, not two.
|
|
278
541
|
// Paths too long for a KV key (512 bytes, minus `redirect:<id>:`) stay
|
|
279
542
|
// in memory too — loadRedirects still serves them from the exact map.
|
|
280
|
-
if (
|
|
543
|
+
if (
|
|
544
|
+
from.includes("*") ||
|
|
545
|
+
from.includes("?") ||
|
|
546
|
+
utf8.encode(path).length > MAX_KV_PATH_BYTES
|
|
547
|
+
) {
|
|
281
548
|
kept.push(entry);
|
|
282
549
|
continue;
|
|
283
550
|
}
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
to:
|
|
287
|
-
status: entry.type
|
|
288
|
-
}
|
|
551
|
+
const rule: StoredExactRedirect = {
|
|
552
|
+
from,
|
|
553
|
+
to: redirect.to,
|
|
554
|
+
status: isPermanent(entry.type) ? 301 : 307,
|
|
555
|
+
};
|
|
556
|
+
if (redirect.discardQueryParameters) rule.discardQueryParameters = true;
|
|
557
|
+
const previous = exact.get(path);
|
|
558
|
+
const shadowed = previous
|
|
559
|
+
? [
|
|
560
|
+
...(previous.shadowed ?? []),
|
|
561
|
+
storedExactRedirectValue({ ...previous, shadowed: undefined }) as StoredExactRedirect,
|
|
562
|
+
].filter((r) => r.from !== from)
|
|
563
|
+
: [];
|
|
564
|
+
exact.set(path, { path, ...rule, ...(shadowed.length ? { shadowed } : {}) });
|
|
289
565
|
}
|
|
290
566
|
|
|
291
567
|
// Nothing left to scan ⇒ drop the block rather than ship an empty husk.
|
|
@@ -304,30 +580,59 @@ export function splitExactRedirects(blocks: Record<string, unknown>): SplitRedir
|
|
|
304
580
|
// -------------------------------------------------------------------------
|
|
305
581
|
|
|
306
582
|
/**
|
|
307
|
-
*
|
|
308
|
-
|
|
583
|
+
* The map key for a source or a request path under the current semantics.
|
|
584
|
+
*/
|
|
585
|
+
function matchKey(path: string): string {
|
|
586
|
+
return getRedirectSemantics() === "fresh" ? sourcePath(path) : normalizePath(path);
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* A redirect source as Fresh's router compared it: the origin of an absolute
|
|
591
|
+
* URL stripped, everything else byte for byte as written — case, trailing
|
|
592
|
+
* slash and query included. A request pathname is already in this form.
|
|
593
|
+
*/
|
|
594
|
+
export function sourcePath(path: string): string {
|
|
595
|
+
const p = path.trim();
|
|
596
|
+
|
|
597
|
+
// If the "from" is a full URL, keep just the pathname (and query, if any).
|
|
598
|
+
if (p.startsWith("http://") || p.startsWith("https://")) {
|
|
599
|
+
try {
|
|
600
|
+
const url = new URL(p);
|
|
601
|
+
return url.pathname + url.search;
|
|
602
|
+
} catch {
|
|
603
|
+
// malformed URL, keep as-is and try the prefix fallback
|
|
604
|
+
const slashIdx = p.indexOf("/", p.indexOf("//") + 2);
|
|
605
|
+
return slashIdx >= 0 ? p.slice(slashIdx) : p;
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
return p;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/**
|
|
613
|
+
* Folded redirect-source form: origin stripped, leading `/` forced, trailing
|
|
614
|
+
* slash dropped, lower-cased. The `"legacy"` match key.
|
|
309
615
|
*
|
|
310
|
-
* Exported because it is the KV key contract for `redirect:<id>:<path>`
|
|
311
|
-
* sync script that WRITES the keys and the worker that
|
|
312
|
-
* byte for byte, or a rule is stored under a key nothing
|
|
313
|
-
* inline a different normalization on either side.
|
|
616
|
+
* Exported because it is the KV key contract for `redirect:<id>:<path>` in
|
|
617
|
+
* BOTH semantics — the sync script that WRITES the keys and the worker that
|
|
618
|
+
* READS them must agree byte for byte, or a rule is stored under a key nothing
|
|
619
|
+
* ever asks for. Never inline a different normalization on either side.
|
|
314
620
|
*/
|
|
315
621
|
export function normalizePath(path: string): string {
|
|
316
622
|
let p = path.trim();
|
|
317
623
|
|
|
318
|
-
//
|
|
624
|
+
// A full URL keeps just its pathname — the query is not part of this key.
|
|
319
625
|
if (p.startsWith("http://") || p.startsWith("https://")) {
|
|
320
626
|
try {
|
|
321
627
|
p = new URL(p).pathname;
|
|
322
628
|
} catch {
|
|
323
|
-
// malformed URL, keep as-is and try the prefix fallback
|
|
324
629
|
const slashIdx = p.indexOf("/", p.indexOf("//") + 2);
|
|
325
630
|
p = slashIdx >= 0 ? p.slice(slashIdx) : p;
|
|
326
631
|
}
|
|
327
632
|
}
|
|
328
633
|
|
|
329
634
|
if (!p.startsWith("/")) {
|
|
330
|
-
p =
|
|
635
|
+
p = `/${p}`;
|
|
331
636
|
}
|
|
332
637
|
if (p.length > 1 && p.endsWith("/")) {
|
|
333
638
|
p = p.slice(0, -1);
|