@sitecore-jss/sitecore-jss-nextjs 22.4.0-canary.8 → 22.4.0-canary.9

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.
@@ -45,20 +45,28 @@ class RedirectsMiddleware extends middleware_1.MiddlewareBase {
45
45
  });
46
46
  const createResponse = () => __awaiter(this, void 0, void 0, function* () {
47
47
  var _a;
48
+ const response = res || server_1.NextResponse.next();
48
49
  if (this.config.disabled && this.config.disabled(req, res || server_1.NextResponse.next())) {
49
50
  sitecore_jss_1.debug.redirects('skipped (redirects middleware is disabled)');
50
- return res || server_1.NextResponse.next();
51
+ return response;
51
52
  }
52
53
  if (this.isPreview(req) || this.excludeRoute(pathname)) {
53
54
  sitecore_jss_1.debug.redirects('skipped (%s)', this.isPreview(req) ? 'preview' : 'route excluded');
54
- return res || server_1.NextResponse.next();
55
+ return response;
56
+ }
57
+ // Skip prefetch requests from Next.js, which are not original client requests
58
+ // as they load unnecessary requests that burden the redirects middleware with meaningless traffic
59
+ if (this.isPrefetch(req)) {
60
+ sitecore_jss_1.debug.redirects('skipped (prefetch)');
61
+ response.headers.set('x-middleware-cache', 'no-cache');
62
+ return response;
55
63
  }
56
64
  site = this.getSite(req, res);
57
65
  // Find the redirect from result of RedirectService
58
66
  const existsRedirect = yield this.getExistsRedirect(req, site.name);
59
67
  if (!existsRedirect) {
60
68
  sitecore_jss_1.debug.redirects('skipped (redirect does not exist)');
61
- return res || server_1.NextResponse.next();
69
+ return response;
62
70
  }
63
71
  // Find context site language and replace token
64
72
  if (REGEXP_CONTEXT_SITE_LANG.test(existsRedirect.target) &&
@@ -72,27 +80,26 @@ class RedirectsMiddleware extends middleware_1.MiddlewareBase {
72
80
  url.href = existsRedirect.target;
73
81
  }
74
82
  else {
75
- const source = `${url.pathname.replace(/\/*$/gi, '')}${existsRedirect.matchedQueryString}`;
76
- const urlFirstPart = existsRedirect.target.split('/')[1];
83
+ const isUrl = (0, utils_1.isRegexOrUrl)(existsRedirect.pattern) === 'url';
84
+ const targetParts = existsRedirect.target.split('/');
85
+ const urlFirstPart = targetParts[1];
77
86
  if (this.locales.includes(urlFirstPart)) {
78
87
  req.nextUrl.locale = urlFirstPart;
79
88
  existsRedirect.target = existsRedirect.target.replace(`/${urlFirstPart}`, '');
80
89
  }
81
- const target = source
82
- .replace((0, regex_parser_1.default)(existsRedirect.pattern), existsRedirect.target)
83
- .replace(/^\/\//, '/')
84
- .split('?');
85
- if (url.search && existsRedirect.isQueryStringPreserved) {
86
- const targetQueryString = (_a = target[1]) !== null && _a !== void 0 ? _a : '';
87
- url.search = '?' + new URLSearchParams(`${url.search}&${targetQueryString}`).toString();
88
- }
89
- else if (target[1]) {
90
- url.search = '?' + target[1];
91
- }
92
- else {
93
- url.search = '';
94
- }
95
- const prepareNewURL = new URL(`${target[0]}${url.search}`, url.origin);
90
+ const targetSegments = isUrl
91
+ ? existsRedirect.target.split('?')
92
+ : url.pathname.replace(/\/*$/gi, '') + existsRedirect.matchedQueryString;
93
+ const [targetPath, targetQueryString] = isUrl
94
+ ? targetSegments
95
+ : targetSegments
96
+ .replace((0, regex_parser_1.default)(existsRedirect.pattern), existsRedirect.target)
97
+ .replace(/^\/\//, '/')
98
+ .split('?');
99
+ const mergedQueryString = existsRedirect.isQueryStringPreserved
100
+ ? (0, utils_1.mergeURLSearchParams)(new URLSearchParams((_a = url.search) !== null && _a !== void 0 ? _a : ''), new URLSearchParams(targetQueryString || ''))
101
+ : targetQueryString || '';
102
+ const prepareNewURL = new URL(`${targetPath}${mergedQueryString ? '?' + mergedQueryString : ''}`, url.origin);
96
103
  url.href = prepareNewURL.href;
97
104
  url.pathname = prepareNewURL.pathname;
98
105
  url.search = prepareNewURL.search;
@@ -101,16 +108,16 @@ class RedirectsMiddleware extends middleware_1.MiddlewareBase {
101
108
  /** return Response redirect with http code of redirect type */
102
109
  switch (existsRedirect.redirectType) {
103
110
  case site_1.REDIRECT_TYPE_301: {
104
- return this.createRedirectResponse(url, res, 301, 'Moved Permanently');
111
+ return this.createRedirectResponse(url, response, 301, 'Moved Permanently');
105
112
  }
106
113
  case site_1.REDIRECT_TYPE_302: {
107
- return this.createRedirectResponse(url, res, 302, 'Found');
114
+ return this.createRedirectResponse(url, response, 302, 'Found');
108
115
  }
109
116
  case site_1.REDIRECT_TYPE_SERVER_TRANSFER: {
110
- return this.rewrite(url.href, req, res || server_1.NextResponse.next());
117
+ return this.rewrite(url.href, req, response);
111
118
  }
112
119
  default:
113
- return res || server_1.NextResponse.next();
120
+ return response;
114
121
  }
115
122
  });
116
123
  const response = yield createResponse();
@@ -152,59 +159,43 @@ class RedirectsMiddleware extends middleware_1.MiddlewareBase {
152
159
  */
153
160
  getExistsRedirect(req, siteName) {
154
161
  return __awaiter(this, void 0, void 0, function* () {
155
- const redirects = yield this.redirectsService.fetchRedirects(siteName);
156
162
  const { pathname: targetURL, search: targetQS = '', locale } = this.normalizeUrl(req.nextUrl.clone());
163
+ const normalizedPath = targetURL.replace(/\/*$/gi, '');
164
+ const redirects = yield this.redirectsService.fetchRedirects(siteName);
157
165
  const language = this.getLanguage(req);
158
166
  const modifyRedirects = structuredClone(redirects);
167
+ let matchedQueryString;
159
168
  return modifyRedirects.length
160
169
  ? modifyRedirects.find((redirect) => {
170
+ var _a;
171
+ if ((0, utils_1.isRegexOrUrl)(redirect.pattern) === 'url') {
172
+ const parseUrlPattern = redirect.pattern.endsWith('/')
173
+ ? redirect.pattern.slice(0, -1).split('?')
174
+ : redirect.pattern.split('?');
175
+ return ((parseUrlPattern[0] === normalizedPath ||
176
+ parseUrlPattern[0] === `/${locale}${normalizedPath}`) &&
177
+ (0, utils_1.areURLSearchParamsEqual)(new URLSearchParams((_a = parseUrlPattern[1]) !== null && _a !== void 0 ? _a : ''), new URLSearchParams(targetQS)));
178
+ }
161
179
  // Modify the redirect pattern to ignore the language prefix in the path
162
180
  // And escapes non-special "?" characters in a string or regex.
163
- redirect.pattern = this.escapeNonSpecialQuestionMarks(redirect.pattern.replace(RegExp(`^[^]?/${language}/`, 'gi'), ''));
181
+ redirect.pattern = (0, utils_1.escapeNonSpecialQuestionMarks)(redirect.pattern.replace(new RegExp(`^[^]?/${language}/`, 'gi'), ''));
164
182
  // Prepare the redirect pattern as a regular expression, making it more flexible for matching URLs
165
183
  redirect.pattern = `/^\/${redirect.pattern
166
184
  .replace(/^\/|\/$/g, '') // Removes leading and trailing slashes
167
185
  .replace(/^\^\/|\/\$$/g, '') // Removes unnecessary start (^) and end ($) anchors
168
186
  .replace(/^\^|\$$/g, '') // Further cleans up anchors
169
187
  .replace(/\$\/gi$/g, '')}[\/]?$/i`; // Ensures the pattern allows an optional trailing slash
170
- /**
171
- * This line checks whether the current URL query string (and all its possible permutations)
172
- * matches the redirect pattern.
173
- *
174
- * Query parameters in URLs can come in different orders, but logically they represent the
175
- * same information (e.g., "key1=value1&key2=value2" is the same as "key2=value2&key1=value1").
176
- * To account for this, the method `isPermutedQueryMatch` generates all possible permutations
177
- * of the query parameters and checks if any of those permutations match the regex pattern for the redirect.
178
- *
179
- * NOTE: This fix is specifically implemented for Netlify, where query parameters are sometimes
180
- * automatically sorted, which can cause issues with matching redirects if the order of query
181
- * parameters is important. By checking every possible permutation, we ensure that redirects
182
- * work correctly on Netlify despite this behavior.
183
- *
184
- * It passes several pieces of information to the function:
185
- * 1. `pathname`: The normalized URL path without query parameters (e.g., '/about').
186
- * 2. `queryString`: The current query string from the URL, which will be permuted and matched (e.g., '?key1=value1&key2=value2').
187
- * 3. `pattern`: The regex pattern for the redirect that we are trying to match against the URL (e.g., '/about?key1=value1').
188
- * 4. `locale`: The locale part of the URL (if any), which helps support multilingual URLs.
189
- *
190
- * If one of the permutations of the query string matches the redirect pattern, the function
191
- * returns the matched query string, which is stored in `matchedQueryString`. If no match is found,
192
- * it returns `undefined`. The `matchedQueryString` is later used to indicate whether the query
193
- * string contributed to a successful redirect match.
194
- */
195
- const matchedQueryString = this.isPermutedQueryMatch({
196
- pathname: targetURL,
197
- queryString: targetQS,
198
- pattern: redirect.pattern,
199
- locale,
200
- });
188
+ matchedQueryString = [
189
+ (0, regex_parser_1.default)(redirect.pattern).test(`${normalizedPath}${targetQS}`),
190
+ (0, regex_parser_1.default)(redirect.pattern).test(`/${locale}${normalizedPath}${targetQS}`),
191
+ ].some(Boolean)
192
+ ? targetQS
193
+ : undefined;
201
194
  // Save the matched query string (if found) into the redirect object
202
195
  redirect.matchedQueryString = matchedQueryString || '';
203
- // Return the redirect if the URL path or any query string permutation matches the pattern
204
- return (((0, regex_parser_1.default)(redirect.pattern).test(targetURL) ||
196
+ return (!!((0, regex_parser_1.default)(redirect.pattern).test(targetURL) ||
205
197
  (0, regex_parser_1.default)(redirect.pattern).test(`/${req.nextUrl.locale}${targetURL}`) ||
206
- matchedQueryString) &&
207
- (redirect.locale ? redirect.locale.toLowerCase() === locale.toLowerCase() : true));
198
+ matchedQueryString) && (redirect.locale ? redirect.locale.toLowerCase() === locale.toLowerCase() : true));
208
199
  })
209
200
  : undefined;
210
201
  });
@@ -269,64 +260,5 @@ class RedirectsMiddleware extends middleware_1.MiddlewareBase {
269
260
  }
270
261
  return redirect;
271
262
  }
272
- /**
273
- * Checks if the current URL query matches the provided pattern, considering all permutations of query parameters.
274
- * It constructs all possible query parameter permutations and tests them against the pattern.
275
- * @param {object} params - The parameters for the URL match.
276
- * @param {string} params.pathname - The current URL pathname.
277
- * @param {string} params.queryString - The current URL query string.
278
- * @param {string} params.pattern - The regex pattern to test the constructed URLs against.
279
- * @param {string} [params.locale] - The locale prefix to include in the URL if present.
280
- * @returns {string | undefined} - return query string if any of the query permutations match the provided pattern, undefined otherwise.
281
- */
282
- isPermutedQueryMatch({ pathname, queryString, pattern, locale, }) {
283
- const paramsArray = Array.from(new URLSearchParams(queryString).entries());
284
- const listOfPermuted = (0, utils_1.getPermutations)(paramsArray).map((permutation) => '?' + permutation.map(([key, value]) => `${key}=${value}`).join('&'));
285
- const normalizedPath = pathname.replace(/\/*$/gi, '');
286
- return listOfPermuted.find((query) => [
287
- (0, regex_parser_1.default)(pattern).test(`${normalizedPath}${query}`),
288
- (0, regex_parser_1.default)(pattern).test(`/${locale}${normalizedPath}${query}`),
289
- ].some(Boolean));
290
- }
291
- /**
292
- * Escapes non-special "?" characters in a string or regex.
293
- *
294
- * - For regular strings, it escapes all unescaped "?" characters by adding a backslash (`\`).
295
- * - For regex patterns (strings enclosed in `/.../`), it analyzes each "?" to determine if it has special meaning
296
- * (e.g., `?` in `(abc)?`, `.*?`) or is just a literal character. Only literal "?" characters are escaped.
297
- * @param {string} input - The input string or regex pattern.
298
- * @returns {string} - The modified string or regex with non-special "?" characters escaped.
299
- **/
300
- escapeNonSpecialQuestionMarks(input) {
301
- const regexPattern = /(?<!\\)\?/g; // Find unescaped "?" characters
302
- const isRegex = input.startsWith('/') && input.endsWith('/'); // Check if the string is a regex
303
- if (!isRegex) {
304
- // If not a regex, escape all unescaped "?" characters
305
- return input.replace(regexPattern, '\\?');
306
- }
307
- // If it's a regex, analyze each "?" character
308
- let result = '';
309
- let lastIndex = 0;
310
- let match;
311
- while ((match = regexPattern.exec(input)) !== null) {
312
- const index = match.index; // Position of "?" in the string
313
- const before = input.slice(0, index).replace(/\s+$/, ''); // Context before "?"
314
- const lastChar = before.slice(-1); // Last character before "?"
315
- // Determine if the "?" is a special regex symbol
316
- const isSpecialRegexSymbol = /[\.\*\+\)\[\]]$/.test(lastChar);
317
- if (isSpecialRegexSymbol) {
318
- // If it's special, keep it as is
319
- result += input.slice(lastIndex, index + 1);
320
- }
321
- else {
322
- // If it's not special, escape it
323
- result += input.slice(lastIndex, index) + '\\?';
324
- }
325
- lastIndex = index + 1;
326
- }
327
- // Append the remaining part of the string
328
- result += input.slice(lastIndex);
329
- return result;
330
- }
331
263
  }
332
264
  exports.RedirectsMiddleware = RedirectsMiddleware;
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  import { debug } from '@sitecore-jss/sitecore-jss';
11
11
  import { GraphQLRedirectsService, REDIRECT_TYPE_301, REDIRECT_TYPE_302, REDIRECT_TYPE_SERVER_TRANSFER, } from '@sitecore-jss/sitecore-jss/site';
12
- import { getPermutations } from '@sitecore-jss/sitecore-jss/utils';
12
+ import { areURLSearchParamsEqual, escapeNonSpecialQuestionMarks, isRegexOrUrl, mergeURLSearchParams, } from '@sitecore-jss/sitecore-jss/utils';
13
13
  import { NextResponse } from 'next/server';
14
14
  import regexParser from 'regex-parser';
15
15
  import { MiddlewareBase } from './middleware';
@@ -39,20 +39,28 @@ export class RedirectsMiddleware extends MiddlewareBase {
39
39
  });
40
40
  const createResponse = () => __awaiter(this, void 0, void 0, function* () {
41
41
  var _a;
42
+ const response = res || NextResponse.next();
42
43
  if (this.config.disabled && this.config.disabled(req, res || NextResponse.next())) {
43
44
  debug.redirects('skipped (redirects middleware is disabled)');
44
- return res || NextResponse.next();
45
+ return response;
45
46
  }
46
47
  if (this.isPreview(req) || this.excludeRoute(pathname)) {
47
48
  debug.redirects('skipped (%s)', this.isPreview(req) ? 'preview' : 'route excluded');
48
- return res || NextResponse.next();
49
+ return response;
50
+ }
51
+ // Skip prefetch requests from Next.js, which are not original client requests
52
+ // as they load unnecessary requests that burden the redirects middleware with meaningless traffic
53
+ if (this.isPrefetch(req)) {
54
+ debug.redirects('skipped (prefetch)');
55
+ response.headers.set('x-middleware-cache', 'no-cache');
56
+ return response;
49
57
  }
50
58
  site = this.getSite(req, res);
51
59
  // Find the redirect from result of RedirectService
52
60
  const existsRedirect = yield this.getExistsRedirect(req, site.name);
53
61
  if (!existsRedirect) {
54
62
  debug.redirects('skipped (redirect does not exist)');
55
- return res || NextResponse.next();
63
+ return response;
56
64
  }
57
65
  // Find context site language and replace token
58
66
  if (REGEXP_CONTEXT_SITE_LANG.test(existsRedirect.target) &&
@@ -66,27 +74,26 @@ export class RedirectsMiddleware extends MiddlewareBase {
66
74
  url.href = existsRedirect.target;
67
75
  }
68
76
  else {
69
- const source = `${url.pathname.replace(/\/*$/gi, '')}${existsRedirect.matchedQueryString}`;
70
- const urlFirstPart = existsRedirect.target.split('/')[1];
77
+ const isUrl = isRegexOrUrl(existsRedirect.pattern) === 'url';
78
+ const targetParts = existsRedirect.target.split('/');
79
+ const urlFirstPart = targetParts[1];
71
80
  if (this.locales.includes(urlFirstPart)) {
72
81
  req.nextUrl.locale = urlFirstPart;
73
82
  existsRedirect.target = existsRedirect.target.replace(`/${urlFirstPart}`, '');
74
83
  }
75
- const target = source
76
- .replace(regexParser(existsRedirect.pattern), existsRedirect.target)
77
- .replace(/^\/\//, '/')
78
- .split('?');
79
- if (url.search && existsRedirect.isQueryStringPreserved) {
80
- const targetQueryString = (_a = target[1]) !== null && _a !== void 0 ? _a : '';
81
- url.search = '?' + new URLSearchParams(`${url.search}&${targetQueryString}`).toString();
82
- }
83
- else if (target[1]) {
84
- url.search = '?' + target[1];
85
- }
86
- else {
87
- url.search = '';
88
- }
89
- const prepareNewURL = new URL(`${target[0]}${url.search}`, url.origin);
84
+ const targetSegments = isUrl
85
+ ? existsRedirect.target.split('?')
86
+ : url.pathname.replace(/\/*$/gi, '') + existsRedirect.matchedQueryString;
87
+ const [targetPath, targetQueryString] = isUrl
88
+ ? targetSegments
89
+ : targetSegments
90
+ .replace(regexParser(existsRedirect.pattern), existsRedirect.target)
91
+ .replace(/^\/\//, '/')
92
+ .split('?');
93
+ const mergedQueryString = existsRedirect.isQueryStringPreserved
94
+ ? mergeURLSearchParams(new URLSearchParams((_a = url.search) !== null && _a !== void 0 ? _a : ''), new URLSearchParams(targetQueryString || ''))
95
+ : targetQueryString || '';
96
+ const prepareNewURL = new URL(`${targetPath}${mergedQueryString ? '?' + mergedQueryString : ''}`, url.origin);
90
97
  url.href = prepareNewURL.href;
91
98
  url.pathname = prepareNewURL.pathname;
92
99
  url.search = prepareNewURL.search;
@@ -95,16 +102,16 @@ export class RedirectsMiddleware extends MiddlewareBase {
95
102
  /** return Response redirect with http code of redirect type */
96
103
  switch (existsRedirect.redirectType) {
97
104
  case REDIRECT_TYPE_301: {
98
- return this.createRedirectResponse(url, res, 301, 'Moved Permanently');
105
+ return this.createRedirectResponse(url, response, 301, 'Moved Permanently');
99
106
  }
100
107
  case REDIRECT_TYPE_302: {
101
- return this.createRedirectResponse(url, res, 302, 'Found');
108
+ return this.createRedirectResponse(url, response, 302, 'Found');
102
109
  }
103
110
  case REDIRECT_TYPE_SERVER_TRANSFER: {
104
- return this.rewrite(url.href, req, res || NextResponse.next());
111
+ return this.rewrite(url.href, req, response);
105
112
  }
106
113
  default:
107
- return res || NextResponse.next();
114
+ return response;
108
115
  }
109
116
  });
110
117
  const response = yield createResponse();
@@ -146,59 +153,43 @@ export class RedirectsMiddleware extends MiddlewareBase {
146
153
  */
147
154
  getExistsRedirect(req, siteName) {
148
155
  return __awaiter(this, void 0, void 0, function* () {
149
- const redirects = yield this.redirectsService.fetchRedirects(siteName);
150
156
  const { pathname: targetURL, search: targetQS = '', locale } = this.normalizeUrl(req.nextUrl.clone());
157
+ const normalizedPath = targetURL.replace(/\/*$/gi, '');
158
+ const redirects = yield this.redirectsService.fetchRedirects(siteName);
151
159
  const language = this.getLanguage(req);
152
160
  const modifyRedirects = structuredClone(redirects);
161
+ let matchedQueryString;
153
162
  return modifyRedirects.length
154
163
  ? modifyRedirects.find((redirect) => {
164
+ var _a;
165
+ if (isRegexOrUrl(redirect.pattern) === 'url') {
166
+ const parseUrlPattern = redirect.pattern.endsWith('/')
167
+ ? redirect.pattern.slice(0, -1).split('?')
168
+ : redirect.pattern.split('?');
169
+ return ((parseUrlPattern[0] === normalizedPath ||
170
+ parseUrlPattern[0] === `/${locale}${normalizedPath}`) &&
171
+ areURLSearchParamsEqual(new URLSearchParams((_a = parseUrlPattern[1]) !== null && _a !== void 0 ? _a : ''), new URLSearchParams(targetQS)));
172
+ }
155
173
  // Modify the redirect pattern to ignore the language prefix in the path
156
174
  // And escapes non-special "?" characters in a string or regex.
157
- redirect.pattern = this.escapeNonSpecialQuestionMarks(redirect.pattern.replace(RegExp(`^[^]?/${language}/`, 'gi'), ''));
175
+ redirect.pattern = escapeNonSpecialQuestionMarks(redirect.pattern.replace(new RegExp(`^[^]?/${language}/`, 'gi'), ''));
158
176
  // Prepare the redirect pattern as a regular expression, making it more flexible for matching URLs
159
177
  redirect.pattern = `/^\/${redirect.pattern
160
178
  .replace(/^\/|\/$/g, '') // Removes leading and trailing slashes
161
179
  .replace(/^\^\/|\/\$$/g, '') // Removes unnecessary start (^) and end ($) anchors
162
180
  .replace(/^\^|\$$/g, '') // Further cleans up anchors
163
181
  .replace(/\$\/gi$/g, '')}[\/]?$/i`; // Ensures the pattern allows an optional trailing slash
164
- /**
165
- * This line checks whether the current URL query string (and all its possible permutations)
166
- * matches the redirect pattern.
167
- *
168
- * Query parameters in URLs can come in different orders, but logically they represent the
169
- * same information (e.g., "key1=value1&key2=value2" is the same as "key2=value2&key1=value1").
170
- * To account for this, the method `isPermutedQueryMatch` generates all possible permutations
171
- * of the query parameters and checks if any of those permutations match the regex pattern for the redirect.
172
- *
173
- * NOTE: This fix is specifically implemented for Netlify, where query parameters are sometimes
174
- * automatically sorted, which can cause issues with matching redirects if the order of query
175
- * parameters is important. By checking every possible permutation, we ensure that redirects
176
- * work correctly on Netlify despite this behavior.
177
- *
178
- * It passes several pieces of information to the function:
179
- * 1. `pathname`: The normalized URL path without query parameters (e.g., '/about').
180
- * 2. `queryString`: The current query string from the URL, which will be permuted and matched (e.g., '?key1=value1&key2=value2').
181
- * 3. `pattern`: The regex pattern for the redirect that we are trying to match against the URL (e.g., '/about?key1=value1').
182
- * 4. `locale`: The locale part of the URL (if any), which helps support multilingual URLs.
183
- *
184
- * If one of the permutations of the query string matches the redirect pattern, the function
185
- * returns the matched query string, which is stored in `matchedQueryString`. If no match is found,
186
- * it returns `undefined`. The `matchedQueryString` is later used to indicate whether the query
187
- * string contributed to a successful redirect match.
188
- */
189
- const matchedQueryString = this.isPermutedQueryMatch({
190
- pathname: targetURL,
191
- queryString: targetQS,
192
- pattern: redirect.pattern,
193
- locale,
194
- });
182
+ matchedQueryString = [
183
+ regexParser(redirect.pattern).test(`${normalizedPath}${targetQS}`),
184
+ regexParser(redirect.pattern).test(`/${locale}${normalizedPath}${targetQS}`),
185
+ ].some(Boolean)
186
+ ? targetQS
187
+ : undefined;
195
188
  // Save the matched query string (if found) into the redirect object
196
189
  redirect.matchedQueryString = matchedQueryString || '';
197
- // Return the redirect if the URL path or any query string permutation matches the pattern
198
- return ((regexParser(redirect.pattern).test(targetURL) ||
190
+ return (!!(regexParser(redirect.pattern).test(targetURL) ||
199
191
  regexParser(redirect.pattern).test(`/${req.nextUrl.locale}${targetURL}`) ||
200
- matchedQueryString) &&
201
- (redirect.locale ? redirect.locale.toLowerCase() === locale.toLowerCase() : true));
192
+ matchedQueryString) && (redirect.locale ? redirect.locale.toLowerCase() === locale.toLowerCase() : true));
202
193
  })
203
194
  : undefined;
204
195
  });
@@ -263,63 +254,4 @@ export class RedirectsMiddleware extends MiddlewareBase {
263
254
  }
264
255
  return redirect;
265
256
  }
266
- /**
267
- * Checks if the current URL query matches the provided pattern, considering all permutations of query parameters.
268
- * It constructs all possible query parameter permutations and tests them against the pattern.
269
- * @param {object} params - The parameters for the URL match.
270
- * @param {string} params.pathname - The current URL pathname.
271
- * @param {string} params.queryString - The current URL query string.
272
- * @param {string} params.pattern - The regex pattern to test the constructed URLs against.
273
- * @param {string} [params.locale] - The locale prefix to include in the URL if present.
274
- * @returns {string | undefined} - return query string if any of the query permutations match the provided pattern, undefined otherwise.
275
- */
276
- isPermutedQueryMatch({ pathname, queryString, pattern, locale, }) {
277
- const paramsArray = Array.from(new URLSearchParams(queryString).entries());
278
- const listOfPermuted = getPermutations(paramsArray).map((permutation) => '?' + permutation.map(([key, value]) => `${key}=${value}`).join('&'));
279
- const normalizedPath = pathname.replace(/\/*$/gi, '');
280
- return listOfPermuted.find((query) => [
281
- regexParser(pattern).test(`${normalizedPath}${query}`),
282
- regexParser(pattern).test(`/${locale}${normalizedPath}${query}`),
283
- ].some(Boolean));
284
- }
285
- /**
286
- * Escapes non-special "?" characters in a string or regex.
287
- *
288
- * - For regular strings, it escapes all unescaped "?" characters by adding a backslash (`\`).
289
- * - For regex patterns (strings enclosed in `/.../`), it analyzes each "?" to determine if it has special meaning
290
- * (e.g., `?` in `(abc)?`, `.*?`) or is just a literal character. Only literal "?" characters are escaped.
291
- * @param {string} input - The input string or regex pattern.
292
- * @returns {string} - The modified string or regex with non-special "?" characters escaped.
293
- **/
294
- escapeNonSpecialQuestionMarks(input) {
295
- const regexPattern = /(?<!\\)\?/g; // Find unescaped "?" characters
296
- const isRegex = input.startsWith('/') && input.endsWith('/'); // Check if the string is a regex
297
- if (!isRegex) {
298
- // If not a regex, escape all unescaped "?" characters
299
- return input.replace(regexPattern, '\\?');
300
- }
301
- // If it's a regex, analyze each "?" character
302
- let result = '';
303
- let lastIndex = 0;
304
- let match;
305
- while ((match = regexPattern.exec(input)) !== null) {
306
- const index = match.index; // Position of "?" in the string
307
- const before = input.slice(0, index).replace(/\s+$/, ''); // Context before "?"
308
- const lastChar = before.slice(-1); // Last character before "?"
309
- // Determine if the "?" is a special regex symbol
310
- const isSpecialRegexSymbol = /[\.\*\+\)\[\]]$/.test(lastChar);
311
- if (isSpecialRegexSymbol) {
312
- // If it's special, keep it as is
313
- result += input.slice(lastIndex, index + 1);
314
- }
315
- else {
316
- // If it's not special, escape it
317
- result += input.slice(lastIndex, index) + '\\?';
318
- }
319
- lastIndex = index + 1;
320
- }
321
- // Append the remaining part of the string
322
- result += input.slice(lastIndex);
323
- return result;
324
- }
325
257
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sitecore-jss/sitecore-jss-nextjs",
3
- "version": "22.4.0-canary.8",
3
+ "version": "22.4.0-canary.9",
4
4
  "main": "dist/cjs/index.js",
5
5
  "module": "dist/esm/index.js",
6
6
  "sideEffects": false,
@@ -73,9 +73,9 @@
73
73
  "react-dom": "^18.2.0"
74
74
  },
75
75
  "dependencies": {
76
- "@sitecore-jss/sitecore-jss": "^22.4.0-canary.8",
77
- "@sitecore-jss/sitecore-jss-dev-tools": "^22.4.0-canary.8",
78
- "@sitecore-jss/sitecore-jss-react": "^22.4.0-canary.8",
76
+ "@sitecore-jss/sitecore-jss": "^22.4.0-canary.9",
77
+ "@sitecore-jss/sitecore-jss-dev-tools": "^22.4.0-canary.9",
78
+ "@sitecore-jss/sitecore-jss-react": "^22.4.0-canary.9",
79
79
  "@vercel/kv": "^0.2.1",
80
80
  "prop-types": "^15.8.1",
81
81
  "regex-parser": "^2.2.11",
@@ -83,7 +83,7 @@
83
83
  },
84
84
  "description": "",
85
85
  "types": "types/index.d.ts",
86
- "gitHead": "8f30b87b7f4ee14b37224c5858f072f21a130549",
86
+ "gitHead": "5d94e2017b872ca4c798162ff0392da0628ce69d",
87
87
  "files": [
88
88
  "dist",
89
89
  "types",
@@ -54,25 +54,4 @@ export declare class RedirectsMiddleware extends MiddlewareBase {
54
54
  * @returns {NextResponse<unknown>} The redirect response.
55
55
  */
56
56
  private createRedirectResponse;
57
- /**
58
- * Checks if the current URL query matches the provided pattern, considering all permutations of query parameters.
59
- * It constructs all possible query parameter permutations and tests them against the pattern.
60
- * @param {object} params - The parameters for the URL match.
61
- * @param {string} params.pathname - The current URL pathname.
62
- * @param {string} params.queryString - The current URL query string.
63
- * @param {string} params.pattern - The regex pattern to test the constructed URLs against.
64
- * @param {string} [params.locale] - The locale prefix to include in the URL if present.
65
- * @returns {string | undefined} - return query string if any of the query permutations match the provided pattern, undefined otherwise.
66
- */
67
- private isPermutedQueryMatch;
68
- /**
69
- * Escapes non-special "?" characters in a string or regex.
70
- *
71
- * - For regular strings, it escapes all unescaped "?" characters by adding a backslash (`\`).
72
- * - For regex patterns (strings enclosed in `/.../`), it analyzes each "?" to determine if it has special meaning
73
- * (e.g., `?` in `(abc)?`, `.*?`) or is just a literal character. Only literal "?" characters are escaped.
74
- * @param {string} input - The input string or regex pattern.
75
- * @returns {string} - The modified string or regex with non-special "?" characters escaped.
76
- **/
77
- private escapeNonSpecialQuestionMarks;
78
57
  }