@sitecore-content-sdk/nextjs 2.1.1 → 2.2.0-canary.20260527110239

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.
Files changed (43) hide show
  1. package/dist/cjs/cache/sitecore-cache-tags.js +130 -0
  2. package/dist/cjs/cache/sitecore-edge-webhook-revalidation.js +67 -0
  3. package/dist/cjs/cache/sitecore-page-cache-tags.js +83 -0
  4. package/dist/cjs/debug.js +1 -1
  5. package/dist/cjs/editing/utils.js +6 -10
  6. package/dist/cjs/index.js +9 -1
  7. package/dist/cjs/proxy/redirects-proxy.js +55 -23
  8. package/dist/cjs/route-handler/index.js +3 -1
  9. package/dist/cjs/route-handler/sitecore-revalidate-route-handler.js +124 -0
  10. package/dist/cjs/tools/generate-map.js +120 -115
  11. package/dist/cjs/tools/templating/utils.js +22 -10
  12. package/dist/esm/cache/sitecore-cache-tags.js +119 -0
  13. package/dist/esm/cache/sitecore-edge-webhook-revalidation.js +63 -0
  14. package/dist/esm/cache/sitecore-page-cache-tags.js +80 -0
  15. package/dist/esm/debug.js +2 -2
  16. package/dist/esm/editing/utils.js +6 -10
  17. package/dist/esm/index.js +6 -0
  18. package/dist/esm/proxy/redirects-proxy.js +55 -23
  19. package/dist/esm/route-handler/index.js +1 -0
  20. package/dist/esm/route-handler/sitecore-revalidate-route-handler.js +118 -0
  21. package/dist/esm/tools/generate-map.js +119 -115
  22. package/dist/esm/tools/templating/utils.js +21 -10
  23. package/package.json +10 -10
  24. package/types/cache/sitecore-cache-tags.d.ts +108 -0
  25. package/types/cache/sitecore-cache-tags.d.ts.map +1 -0
  26. package/types/cache/sitecore-edge-webhook-revalidation.d.ts +54 -0
  27. package/types/cache/sitecore-edge-webhook-revalidation.d.ts.map +1 -0
  28. package/types/cache/sitecore-page-cache-tags.d.ts +42 -0
  29. package/types/cache/sitecore-page-cache-tags.d.ts.map +1 -0
  30. package/types/debug.d.ts.map +1 -1
  31. package/types/editing/utils.d.ts.map +1 -1
  32. package/types/index.d.ts +2 -0
  33. package/types/index.d.ts.map +1 -1
  34. package/types/proxy/redirects-proxy.d.ts +18 -0
  35. package/types/proxy/redirects-proxy.d.ts.map +1 -1
  36. package/types/route-handler/index.d.ts +1 -0
  37. package/types/route-handler/index.d.ts.map +1 -1
  38. package/types/route-handler/sitecore-revalidate-route-handler.d.ts +68 -0
  39. package/types/route-handler/sitecore-revalidate-route-handler.d.ts.map +1 -0
  40. package/types/tools/generate-map.d.ts +11 -6
  41. package/types/tools/generate-map.d.ts.map +1 -1
  42. package/types/tools/templating/utils.d.ts +11 -0
  43. package/types/tools/templating/utils.d.ts.map +1 -1
@@ -125,15 +125,9 @@ export const getPreviewCookies = (site) => {
125
125
  * @returns {string[]} list of required parameters for validation
126
126
  */
127
127
  export const getRequiredEditingParamsList = (mode) => {
128
- const editingRequiredParams = ['sc_site', 'sc_itemid', 'sc_lang', 'route', 'mode'];
129
- const componentRequiredParams = [
130
- 'sc_site',
131
- 'sc_itemid',
132
- 'sc_renderingId',
133
- 'sc_uid',
134
- 'sc_lang',
135
- 'mode',
136
- ];
128
+ const baseRequiredParams = ['sc_site', 'sc_itemid', 'sc_lang'];
129
+ const editingRequiredParams = [...baseRequiredParams, 'route', 'mode'];
130
+ const componentRequiredParams = [...baseRequiredParams, 'sc_uid', 'mode'];
137
131
  return isDesignLibraryMode(mode) ? componentRequiredParams : editingRequiredParams;
138
132
  };
139
133
  /**
@@ -201,7 +195,9 @@ export const getEditingRequestHtml = async (requestUrl, propagatedQsParams, prop
201
195
  // We need to handle not found error provided by Vercel
202
196
  // for `fallback: false` pages
203
197
  // Or preview content is not found or access is denied
204
- if (err.response.status === 404 || err.response.status === 403) {
198
+ if (err.response.status === 404 ||
199
+ err.response.status === 403 ||
200
+ err.response.status === 500) {
205
201
  return err.response;
206
202
  }
207
203
  throw err;
package/dist/esm/index.js CHANGED
@@ -27,3 +27,9 @@ export { personalizeProxyAdapter } from './initialization/proxy/personalize-adap
27
27
  export { analyticsProxyAdapter } from './initialization/proxy/analytics-adapter';
28
28
  export { DesignLibraryApp } from './components/DesignLibrary/DesignLibraryApp';
29
29
  export { getCachedPageParams, setCachedPageParams, } from './cache/page-params';
30
+ // Sitecore cache-tag public surface. Kept intentionally small: the cache helpers in the template
31
+ // (`getSitecorePage`, `getSitecoreErrorPage`, `getSitecoreDictionary`) and the `createSitecoreRevalidateRouteHandler`
32
+ // already cover the end-to-end Sitecore tag flow. Lower-level tag builders and webhook-body parsers remain
33
+ // internal so callers don't hand-build Sitecore cache tag strings or duplicate the route handler's logic.
34
+ export { buildSitecoreDictionaryCacheTag, } from './cache/sitecore-cache-tags';
35
+ export { collectSitecorePageCacheTags, } from './cache/sitecore-page-cache-tags';
@@ -1,7 +1,6 @@
1
1
  import { RedirectsService, REDIRECT_TYPE_301, REDIRECT_TYPE_302, REDIRECT_TYPE_SERVER_TRANSFER, } from '@sitecore-content-sdk/content/site';
2
2
  import { areURLSearchParamsEqual, escapeNonSpecialQuestionMarks, isRegexOrUrl, mergeURLSearchParams, } from '@sitecore-content-sdk/core/tools';
3
3
  import { NextResponse } from 'next/server';
4
- import regexParser from 'regex-parser';
5
4
  import { ProxyBase, REWRITE_HEADER_NAME } from './proxy';
6
5
  import debug from '../debug';
7
6
  const REGEXP_CONTEXT_SITE_LANG = new RegExp(/\$siteLang/, 'i');
@@ -120,9 +119,9 @@ export class RedirectsProxy extends ProxyBase {
120
119
  existsRedirect.target = existsRedirect.target.replace(REGEXP_CONTEXT_SITE_LANG, site.language);
121
120
  const reqUrl = this.normalizeUrl(req.nextUrl.clone());
122
121
  // Apply regex replacements to the target URL if the pattern is a regex
123
- const matched = reqUrl.pathname
124
- .replace(/\/*$/gi, '')
125
- .match(regexParser(existsRedirect.pattern));
122
+ const sourcePath = existsRedirect.matchedPath || reqUrl.pathname;
123
+ const pathForCaptureMatch = sourcePath.replace(/\/*$/gi, '') || '/';
124
+ const matched = pathForCaptureMatch.match(this.getRedirectPatternRegex(existsRedirect.pattern));
126
125
  if (matched) {
127
126
  existsRedirect.target = existsRedirect.target.replace(/\$(\d+)/g, (_, index) => {
128
127
  return matched[parseInt(index, 10)] || '';
@@ -193,6 +192,7 @@ export class RedirectsProxy extends ProxyBase {
193
192
  * Method returns RedirectInfo when matches
194
193
  * @param {NextRequest} req request
195
194
  * @param {string} siteName site name
195
+ * @param {string} requestLocale locale used for locale redirect matching
196
196
  * @returns Promise<RedirectInfo | undefined>
197
197
  * @private
198
198
  */
@@ -247,28 +247,28 @@ export class RedirectsProxy extends ProxyBase {
247
247
  areURLSearchParamsEqual(new URLSearchParams(patternQS), new URLSearchParams(incomingQS))));
248
248
  }
249
249
  // process regex rules
250
- // Modify the redirect pattern to ignore the language prefix in the path
251
- // And escapes non-special "?" characters in a string or regex.
252
- redirect.pattern = escapeNonSpecialQuestionMarks('^' + redirect.pattern.replace(new RegExp(`^[^]?/${urlLocale}/`, 'gi'), '') // ensure function thinks input is regex
253
- );
254
- // Prepare the redirect pattern as a regular expression, making it more flexible for matching URLs
255
- redirect.pattern = `/^\/${redirect.pattern
256
- .replace(/^\/|\/$/g, '') // Removes leading and trailing slashes
257
- .replace(/^\^\/|\/\$$/g, '') // Removes unnecessary start (^) and end ($) anchors
258
- .replace(/^\^|\$$/g, '') // Further cleans up anchors
259
- .replace(/\$\/g$/g, '')}[\/]?$/i`; // Ensures the pattern allows an optional trailing slash
260
- // Redirect pattern matches the full incoming URL with query string present
261
- matchedQueryString = [
262
- regexParser(redirect.pattern).test(`/${localePath}${incomingQS}`),
263
- regexParser(redirect.pattern).test(`${normalizedPath}${incomingQS}`),
264
- ].some(Boolean)
265
- ? incomingQS
250
+ const regex = this.getRedirectPatternRegex(redirect.pattern);
251
+ const testRegex = (value) => {
252
+ regex.lastIndex = 0;
253
+ return regex.test(value);
254
+ };
255
+ const localeStrippedIncoming = this.getLocaleStrippedPath(incomingURL, urlLocale);
256
+ const localeStrippedNormalized = this.getLocaleStrippedPath(normalizedPath, urlLocale);
257
+ const pathCandidates = [
258
+ incomingURL,
259
+ normalizedPath,
260
+ localeStrippedIncoming,
261
+ localeStrippedNormalized,
262
+ ].filter((candidate, index, array) => array.indexOf(candidate) === index);
263
+ const matchedPath = pathCandidates.find((candidate) => testRegex(candidate));
264
+ const matchedPathWithQuery = incomingQS
265
+ ? pathCandidates.find((candidate) => testRegex(`${candidate}${incomingQS}`))
266
266
  : undefined;
267
+ matchedQueryString = matchedPathWithQuery ? incomingQS : undefined;
267
268
  // Save the matched query string (if found) into the redirect object
268
269
  redirect.matchedQueryString = matchedQueryString || '';
269
- return (!!(regexParser(redirect.pattern).test(`/${urlLocale}${incomingURL}`) ||
270
- regexParser(redirect.pattern).test(incomingURL) ||
271
- matchedQueryString) &&
270
+ redirect.matchedPath = matchedPath || matchedPathWithQuery || '';
271
+ return (!!(matchedPath || matchedQueryString) &&
272
272
  (redirect.locale ? redirect.locale.toLowerCase() === urlLocale.toLowerCase() : true));
273
273
  })
274
274
  : undefined;
@@ -414,4 +414,36 @@ export class RedirectsProxy extends ProxyBase {
414
414
  }
415
415
  return redirect;
416
416
  }
417
+ /**
418
+ * Converts a redirect pattern string into a RegExp.
419
+ * Supports both JS literal form (`/pattern/i`) and plain regex source (`^/path$`).
420
+ * @param {string} pattern redirect pattern from redirect map
421
+ * @returns {RegExp} normalized regex instance
422
+ * @private
423
+ */
424
+ getRedirectPatternRegex(pattern) {
425
+ const normalizedPattern = escapeNonSpecialQuestionMarks(pattern);
426
+ const literalMatch = normalizedPattern.match(/^\/(.+)\/([a-z]*)$/i);
427
+ if (literalMatch) {
428
+ const [, source, flags] = literalMatch;
429
+ const safeFlags = flags || 'i';
430
+ return new RegExp(source, safeFlags);
431
+ }
432
+ return new RegExp(normalizedPattern, 'i');
433
+ }
434
+ /**
435
+ * Strips locale prefix from path when present.
436
+ * @param {string} path incoming request path
437
+ * @param {string} urlLocale locale from Next.js URL
438
+ * @returns {string} locale-stripped path
439
+ * @private
440
+ */
441
+ getLocaleStrippedPath(path, urlLocale) {
442
+ if (!urlLocale) {
443
+ return path;
444
+ }
445
+ const localePrefixRegex = new RegExp(`^/${urlLocale}(?=/|$)`, 'i');
446
+ const strippedPath = path.replace(localePrefixRegex, '') || '/';
447
+ return strippedPath.startsWith('/') ? strippedPath : `/${strippedPath}`;
448
+ }
417
449
  }
@@ -2,3 +2,4 @@ export { createSitemapRouteHandler } from './sitemap-route-handler';
2
2
  export { createRobotsRouteHandler } from './robots-route-handler';
3
3
  export { createEditingConfigRouteHandler } from './editing-config-route-handler';
4
4
  export { createEditingRenderRouteHandlers } from './editing-render-route-handler';
5
+ export { createSitecoreRevalidateRouteHandler, } from './sitecore-revalidate-route-handler';
@@ -0,0 +1,118 @@
1
+ import { collectSitecoreTagsFromEdgeRevalidateRequestBody, } from '../cache/sitecore-edge-webhook-revalidation';
2
+ import { buildSitecoreDictionaryCacheTagsFromSites, dedupeSitecoreCacheTags } from '../cache/sitecore-cache-tags';
3
+ import debug from '../debug';
4
+ import { revalidateTag } from 'next/cache';
5
+ import { NextResponse } from 'next/server';
6
+ const DEFAULT_SECRET_ENV_VAR = 'SITECORE_REVALIDATE_SECRET';
7
+ const DEFAULT_SECRET_HEADER = 'x-revalidate-secret';
8
+ /**
9
+ * Returns a non-empty trimmed secret, or `undefined` when unset or whitespace-only.
10
+ * @param {string | undefined} secretOption - Explicit secret from handler options.
11
+ * @param {string | undefined} envValue - Secret from `process.env` (e.g. `SITECORE_REVALIDATE_SECRET`).
12
+ */
13
+ function resolveConfiguredRevalidateSecret(secretOption, envValue) {
14
+ const raw = secretOption !== undefined ? secretOption : envValue;
15
+ const trimmed = raw === null || raw === void 0 ? void 0 : raw.trim();
16
+ return trimmed || undefined;
17
+ }
18
+ /**
19
+ * Creates a single `POST` handler for `/api/revalidate` that consumes Sitecore Experience Edge / Content
20
+ * Operations webhook bodies (and equivalent ad-hoc calls that reuse the same body shape).
21
+ *
22
+ * The body is expected to be a JSON object that resolves to at least one Sitecore cache tag:
23
+ *
24
+ * - **`updates[]`** — Sitecore publish-event rows. Each row's `identifier` (with `-media` / `-layout`
25
+ * suffix stripped) maps to an `sc:item:<id>:<locale>:latest` tag, using `entity_culture` for locale
26
+ * (falling back to the handler's `defaultLocale`).
27
+ * - **`tags[]`** — pass-through and convenience array:
28
+ * - Strings already starting with `sc:` are used verbatim (e.g. `sc:route:...`, `sc:item:...`, `sc:dict:...`).
29
+ * - Bare values are treated as Sitecore item ids and mapped to `sc:item:<id>:<defaultLocale>:latest`.
30
+ *
31
+ * When **`sites`** is configured, the handler also appends one `sc:dict:<site>:<locale>` tag per
32
+ * site so dictionary updates flow through the same call.
33
+ *
34
+ * Auth (optional): when `SITECORE_REVALIDATE_SECRET` (or the `secret` option) is non-empty, callers must
35
+ * send the same value in the **`x-revalidate-secret`** header. When unset or blank, no header is required.
36
+ * @param {SitecoreRevalidateRouteHandlerOptions} [options] - Optional inline `secret`, `cacheProfile`, locale, sites, and dictionary options.
37
+ * @public
38
+ */
39
+ export function createSitecoreRevalidateRouteHandler(options = {}) {
40
+ const { defaultLocale = 'en', sites, secret, cacheProfile = 'max' } = options;
41
+ const dictionaryTags = sites !== undefined
42
+ ? buildSitecoreDictionaryCacheTagsFromSites({
43
+ sites,
44
+ baseLocale: defaultLocale,
45
+ })
46
+ : [];
47
+ const POST = async (req) => {
48
+ var _a, _b, _c, _d, _e, _f, _g, _h;
49
+ const startTimestamp = Date.now();
50
+ try {
51
+ const configuredSecret = resolveConfiguredRevalidateSecret(secret, process.env[DEFAULT_SECRET_ENV_VAR]);
52
+ if (configuredSecret) {
53
+ const providedSecret = req.headers.get(DEFAULT_SECRET_HEADER);
54
+ if (providedSecret !== configuredSecret) {
55
+ debug.revalidate('sitecore revalidate: unauthorized (secret mismatch or missing header)');
56
+ return NextResponse.json({ error: 'Unauthorized.' }, { status: 401 });
57
+ }
58
+ }
59
+ else {
60
+ debug.revalidate('sitecore revalidate: no secret configured, skipping auth');
61
+ }
62
+ let body;
63
+ try {
64
+ body = await req.json();
65
+ }
66
+ catch (_j) {
67
+ debug.revalidate('sitecore revalidate: invalid JSON body');
68
+ return NextResponse.json({ error: 'Request body must be valid JSON.' }, { status: 400 });
69
+ }
70
+ if (typeof body !== 'object' || body === null || Array.isArray(body)) {
71
+ debug.revalidate('sitecore revalidate: body must be a JSON object');
72
+ return NextResponse.json({ error: 'Request body must be a JSON object.' }, { status: 400 });
73
+ }
74
+ const webhookBody = body;
75
+ debug.revalidate('sitecore revalidate start: %o', {
76
+ invocation_id: (_a = webhookBody.invocation_id) !== null && _a !== void 0 ? _a : null,
77
+ continues: (_b = webhookBody.continues) !== null && _b !== void 0 ? _b : false,
78
+ updatesCount: (_d = (_c = webhookBody.updates) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0,
79
+ tagsCount: Array.isArray(webhookBody.tags) ? webhookBody.tags.length : 0,
80
+ dictionaryTagsCount: dictionaryTags.length,
81
+ defaultLocale,
82
+ });
83
+ const tags = dedupeSitecoreCacheTags([
84
+ ...collectSitecoreTagsFromEdgeRevalidateRequestBody(webhookBody, { defaultLocale }),
85
+ ...dictionaryTags,
86
+ ]);
87
+ if (tags.length === 0) {
88
+ debug.revalidate('sitecore revalidate: no tags resolved in %dms', Date.now() - startTimestamp);
89
+ return NextResponse.json({
90
+ error: 'Provide non-empty `updates` (with identifiers) and/or `tags` that resolve to at least one cache tag.',
91
+ }, { status: 400 });
92
+ }
93
+ for (const tag of tags) {
94
+ revalidateTag(tag, cacheProfile);
95
+ }
96
+ debug.revalidate('sitecore revalidate end in %dms: %o', Date.now() - startTimestamp, {
97
+ tagsCount: tags.length,
98
+ invocation_id: (_e = webhookBody.invocation_id) !== null && _e !== void 0 ? _e : null,
99
+ continues: (_f = webhookBody.continues) !== null && _f !== void 0 ? _f : false,
100
+ });
101
+ return NextResponse.json({
102
+ revalidated: true,
103
+ tagsCount: tags.length,
104
+ invocation_id: (_g = webhookBody.invocation_id) !== null && _g !== void 0 ? _g : null,
105
+ continues: (_h = webhookBody.continues) !== null && _h !== void 0 ? _h : false,
106
+ });
107
+ }
108
+ catch (error) {
109
+ if (error instanceof Error && error.digest === 'NEXT_PRERENDER_INTERRUPTED') {
110
+ throw error;
111
+ }
112
+ console.log('Sitecore revalidate route handler failed:');
113
+ console.log(error);
114
+ return NextResponse.json({ error: 'Internal Server Error.' }, { status: 500 });
115
+ }
116
+ };
117
+ return { POST };
118
+ }
@@ -1,7 +1,35 @@
1
1
  import { filterComponentsByType, } from '@sitecore-content-sdk/content/tools';
2
2
  import * as path from 'path';
3
3
  import * as fs from 'fs';
4
- import { detectRouterType, getComponentListWithTypes } from './templating/utils';
4
+ import { detectRouterType, getComponentListWithTypes, ROUTER_TYPE } from './templating/utils';
5
+ const DEFAULT_HEADER_COMMENT = "Below are built-in components that are available in the app, it's recommended to keep them as is";
6
+ const APP_ROUTER_BUILTIN_IMPORTS = `
7
+ import { BYOCServerWrapper, NextjsContentSdkComponent, FEaaSServerWrapper } from '@sitecore-content-sdk/nextjs';
8
+ import { Form } from '@sitecore-content-sdk/nextjs';
9
+ `;
10
+ const APP_ROUTER_BUILTIN_ENTRIES = [
11
+ `['BYOCWrapper', BYOCServerWrapper]`,
12
+ `['FEaaSWrapper', FEaaSServerWrapper]`,
13
+ `['Form', { ...Form, componentType: 'client' }]`,
14
+ ];
15
+ const PAGES_ROUTER_BUILTIN_IMPORTS = `
16
+ import { BYOCWrapper, NextjsContentSdkComponent, FEaaSWrapper } from '@sitecore-content-sdk/nextjs';
17
+ import { Form } from '@sitecore-content-sdk/nextjs';
18
+ `;
19
+ const PAGES_ROUTER_BUILTIN_ENTRIES = [
20
+ `['BYOCWrapper', BYOCWrapper]`,
21
+ `['FEaaSWrapper', FEaaSWrapper]`,
22
+ `['Form', Form]`,
23
+ ];
24
+ const CLIENT_MAP_BUILTIN_IMPORTS = `
25
+ import { BYOCClientWrapper, NextjsContentSdkComponent, FEaaSClientWrapper } from '@sitecore-content-sdk/nextjs';
26
+ import { Form } from '@sitecore-content-sdk/nextjs';
27
+ `;
28
+ const CLIENT_MAP_BUILTIN_ENTRIES = [
29
+ `['BYOCWrapper', BYOCClientWrapper]`,
30
+ `['FEaaSWrapper', FEaaSClientWrapper]`,
31
+ `['Form', Form]`,
32
+ ];
5
33
  // Common builder for Next.js component map content
6
34
  const prepareComponentsForMap = (components, opts) => {
7
35
  const groups = new Map();
@@ -77,21 +105,16 @@ const prepareComponentsForMap = (components, opts) => {
77
105
  }
78
106
  return entries;
79
107
  };
80
- const buildNextjsMapContent = (entries, componentImports, options = {}) => {
81
- const isAppRouter = detectRouterType() === 'app';
82
- const { headerComment = "Below are built-in components that are available in the app, it's recommended to keep them as is", isClientMap = false, } = options;
108
+ /**
109
+ * Distinguishes the simple 2-arity ComponentMapTemplate from the 3-arity EnhancedComponentMapTemplate.
110
+ * @param {ComponentMapTemplate | EnhancedComponentMapTemplate} fn The template function to check.
111
+ * @internal
112
+ */
113
+ const isComponentMapTemplate = (fn) => fn.length === 2;
114
+ const buildNextjsMapContent = (entries, componentImports, options) => {
115
+ const { headerComment = DEFAULT_HEADER_COMMENT, isClientMap = false, builtInImports, builtInMapEntries, } = options;
83
116
  const wildcardImports = [];
84
117
  const namedImports = [];
85
- const builtInImports = options.builtInImports ||
86
- `
87
- import { BYOCWrapper, NextjsContentSdkComponent, FEaaSWrapper } from '@sitecore-content-sdk/nextjs';
88
- import { Form } from '@sitecore-content-sdk/nextjs';
89
- `;
90
- const builtInMapEntries = options.builtInMapEntries || [
91
- `['BYOCWrapper', BYOCWrapper]`,
92
- `['FEaaSWrapper', FEaaSWrapper]`,
93
- `['Form', ${isAppRouter ? '{ ...Form, componentType: \'client\' }' : 'Form'}]`,
94
- ];
95
118
  // Add per-entry imports
96
119
  entries.forEach((e) => wildcardImports.push(...e.imports));
97
120
  // Handle package imports
@@ -109,8 +132,8 @@ import { Form } from '@sitecore-content-sdk/nextjs';
109
132
  ...namedImports,
110
133
  ].filter(Boolean);
111
134
  const importsSection = importLines.length ? `\n${importLines.join('\n')}` : '';
112
- // Build entry lines (package named imports are appended below)
113
- const componentMapEntries = builtInMapEntries;
135
+ // Clone to avoid mutating the caller's array
136
+ const componentMapEntries = structuredClone(builtInMapEntries);
114
137
  for (const e of entries) {
115
138
  const value = !isClientMap && e.annotateClient
116
139
  ? `{ ${e.valueExpr}, componentType: 'client' }`
@@ -143,26 +166,30 @@ ${componentMapEntries
143
166
  export default componentMap;
144
167
  `;
145
168
  };
146
- // default client template
169
+ // Default App Router (server) component map template
170
+ export const defaultServerMapTemplate = (components, componentImports, ctx) => {
171
+ var _a, _b;
172
+ const entries = (_a = ctx === null || ctx === void 0 ? void 0 : ctx.entries) !== null && _a !== void 0 ? _a : prepareComponentsForMap(components, {
173
+ includeVariants: (_b = ctx === null || ctx === void 0 ? void 0 : ctx.includeVariants) !== null && _b !== void 0 ? _b : true,
174
+ });
175
+ return buildNextjsMapContent(entries, componentImports, {
176
+ headerComment: DEFAULT_HEADER_COMMENT,
177
+ isClientMap: false,
178
+ builtInImports: APP_ROUTER_BUILTIN_IMPORTS,
179
+ builtInMapEntries: APP_ROUTER_BUILTIN_ENTRIES,
180
+ });
181
+ };
182
+ // Default client-safe component map template for App Router
147
183
  export const defaultClientMapTemplate = (components, componentImports, ctx) => {
148
184
  var _a, _b;
149
- const builtInImports = `
150
- import { BYOCClientWrapper, NextjsContentSdkComponent, FEaaSClientWrapper } from '@sitecore-content-sdk/nextjs';
151
- import { Form } from '@sitecore-content-sdk/nextjs';
152
- `;
153
- const builtInMapEntries = [
154
- `['BYOCWrapper', BYOCClientWrapper]`,
155
- `['FEaaSWrapper', FEaaSClientWrapper]`,
156
- `['Form', Form]`,
157
- ];
158
185
  const entries = (_a = ctx === null || ctx === void 0 ? void 0 : ctx.entries) !== null && _a !== void 0 ? _a : prepareComponentsForMap(components, {
159
186
  includeVariants: (_b = ctx === null || ctx === void 0 ? void 0 : ctx.includeVariants) !== null && _b !== void 0 ? _b : true,
160
187
  });
161
188
  return buildNextjsMapContent(entries, componentImports, {
162
189
  headerComment: 'Client-safe component map for App Router',
163
190
  isClientMap: true,
164
- builtInImports,
165
- builtInMapEntries,
191
+ builtInImports: CLIENT_MAP_BUILTIN_IMPORTS,
192
+ builtInMapEntries: CLIENT_MAP_BUILTIN_ENTRIES,
166
193
  });
167
194
  };
168
195
  // Collect components from specified paths, apply exclude and type filter, and prepare map entries.
@@ -182,115 +209,92 @@ const collectComponents = (opts) => {
182
209
  /**
183
210
  * Generate and write componentMap.ts files based on provided params.
184
211
  *
185
- * When clientComponentMap is true, generates:
212
+ * Pages Router:
213
+ * - component-map.ts : Single component map with Pages Router wrappers
214
+ *
215
+ * App Router (clientComponentMap=true or undefined):
186
216
  * - component-map.ts : Full component map with all components (server, client, universal)
187
- * - component-map.client.ts : Client-safe map with only client + universal components
217
+ * - component-map.client.ts : Client-safe map with client + universal components
188
218
  *
189
- * When clientComponentMap is false, generates:
190
- * - component-map.ts : Single component map (traditional behavior)
219
+ * App Router (clientComponentMap=false):
220
+ * - component-map.ts : Full component map with all components (server, client, universal)
221
+ * - component-map.client.ts : Client-safe map with built-in components only (no user components)
191
222
  *
192
- * When includeVariants is true (in either mode):
223
+ * When includeVariants is true:
193
224
  * - Includes component **variants** in the generated map(s) alongside base components
194
225
  * - Preserves the same client/server filtering rules (variants obey clientComponentMap filtering)
195
226
  * - Variant entries are emitted using the same naming/keys convention as their base components
196
227
  *
197
228
  * Template Customization:
198
229
  * - mapTemplate: Custom template for main component map (works for both single and dual map modes)
199
- * - clientMapTemplate: Custom template for client component map (only used when clientComponentMap is true)
230
+ * - clientMapTemplate: Custom template for client component map (App Router only)
200
231
  * @param {GenerateMapArgs} params - The parameters for the generateMap function.
201
232
  * @public
202
233
  */
203
234
  export const generateMap = ({ paths, destination = '.sitecore', exclude, componentImports, mapTemplate, clientMapTemplate, clientComponentMap, includeVariants = true, }) => {
204
- const isAppRouter = detectRouterType() === 'app';
205
- const shouldGenerateClientMap = clientComponentMap !== null && clientComponentMap !== void 0 ? clientComponentMap : isAppRouter;
206
- if (shouldGenerateClientMap) {
207
- // App Router case, main map
208
- const getComponents = collectComponents({ paths, exclude, includeVariants, filter: 'all' });
209
- let mainContent;
210
- if (mapTemplate) {
211
- mainContent = mapTemplate(getComponents.raw, componentImports, {
212
- entries: getComponents.entries,
235
+ const routerType = detectRouterType();
236
+ const allComponents = collectComponents({ paths, exclude, includeVariants, filter: 'all' });
237
+ if (routerType === ROUTER_TYPE.PAGES) {
238
+ const content = mapTemplate
239
+ ? mapTemplate(allComponents.raw, componentImports, {
240
+ entries: allComponents.entries,
213
241
  includeVariants,
214
242
  isClientMap: false,
215
- });
216
- }
217
- else {
218
- // default app router server map
219
- const builtInImports = `
220
- import { BYOCServerWrapper, NextjsContentSdkComponent, FEaaSServerWrapper } from '@sitecore-content-sdk/nextjs';
221
- import { Form } from '@sitecore-content-sdk/nextjs';
222
- `;
223
- const builtInMapEntries = [
224
- `['BYOCWrapper', BYOCServerWrapper]`,
225
- `['FEaaSWrapper', FEaaSServerWrapper]`,
226
- `['Form', { ...Form, componentType: 'client' }]`,
227
- ];
228
- mainContent = buildNextjsMapContent(getComponents.entries, componentImports, {
229
- headerComment: "Below are built-in components that are available in the app, it's recommended to keep them as is",
243
+ })
244
+ : buildNextjsMapContent(allComponents.entries, componentImports, {
230
245
  isClientMap: false,
231
- builtInImports,
232
- builtInMapEntries,
246
+ builtInImports: PAGES_ROUTER_BUILTIN_IMPORTS,
247
+ builtInMapEntries: PAGES_ROUTER_BUILTIN_ENTRIES,
233
248
  });
249
+ try {
250
+ fs.writeFileSync(path.join(process.cwd(), destination, 'component-map.ts'), content, 'utf8');
234
251
  }
235
- fs.writeFileSync(path.join(process.cwd(), destination, 'component-map.ts'), mainContent, 'utf8');
236
- // App Router, client map
237
- const clientComponents = collectComponents({
238
- paths,
239
- exclude,
240
- includeVariants,
241
- filter: 'client',
242
- });
243
- const clientTemplate = clientMapTemplate || defaultClientMapTemplate;
244
- let clientContent;
245
- if (clientTemplate.length >= 2) {
246
- clientContent = clientTemplate(clientComponents.raw, componentImports);
247
- }
248
- else {
249
- clientContent = clientTemplate(clientComponents.raw, componentImports, {
250
- entries: clientComponents.entries,
251
- includeVariants,
252
- isClientMap: true,
253
- });
252
+ catch (error) {
253
+ console.error(`Component Map generation failed. Error writing to file ${destination}:`, error);
254
+ throw error;
254
255
  }
255
- fs.writeFileSync(path.join(process.cwd(), destination, 'component-map.client.ts'), clientContent, 'utf8');
256
+ return;
256
257
  }
257
- else {
258
- // Either in pages/app router or clientComponentMap = false
259
- const components = collectComponents({
260
- paths,
261
- exclude,
258
+ const mainContent = mapTemplate
259
+ ? mapTemplate(allComponents.raw, componentImports, {
260
+ entries: allComponents.entries,
261
+ includeVariants,
262
+ isClientMap: false,
263
+ })
264
+ : defaultServerMapTemplate(allComponents.raw, componentImports, {
265
+ entries: allComponents.entries,
262
266
  includeVariants,
263
- filter: 'all',
264
- }).entries;
265
- const content = buildNextjsMapContent(components, componentImports, {
266
- headerComment: "Below are built-in components that are available in the app, it's recommended to keep them as is",
267
267
  isClientMap: false,
268
268
  });
269
- fs.writeFileSync(path.join(process.cwd(), destination, 'component-map.ts'), content, 'utf8');
270
- // For App Router compatibility, always generate client map file even when clientComponentMap is false
271
- // When clientComponentMap is false, only include built-in components (no custom client components)
272
- if (shouldGenerateClientMap || isAppRouter) {
273
- const clientMapTemplateToUse = clientMapTemplate || defaultClientMapTemplate;
274
- const components = collectComponents({ paths: [], includeVariants, filter: 'all' });
275
- let clientMapContent;
276
- if (clientMapTemplateToUse.length >= 2) {
277
- clientMapContent = clientMapTemplateToUse([], componentImports);
278
- }
279
- else {
280
- clientMapContent = clientMapTemplateToUse([], componentImports, {
281
- entries: components.entries,
282
- includeVariants,
283
- isClientMap: true,
284
- });
285
- }
286
- const clientMapFile = path.join(process.cwd(), destination, 'component-map.client.ts');
287
- try {
288
- fs.writeFileSync(clientMapFile, clientMapContent, { encoding: 'utf8' });
289
- }
290
- catch (error) {
291
- console.error(`Client Component Map generation failed. Error writing to file ${destination}:`, error);
292
- throw error;
293
- }
294
- }
269
+ try {
270
+ fs.writeFileSync(path.join(process.cwd(), destination, 'component-map.ts'), mainContent, 'utf8');
271
+ }
272
+ catch (error) {
273
+ console.error(`Main Component Map generation failed. Error writing to file ${destination}:`, error);
274
+ throw error;
275
+ }
276
+ // clientComponentMap=true -> include user client+universal components
277
+ // clientComponentMap=undefined -> include user client+universal components
278
+ // clientComponentMap=false -> built-ins only
279
+ const shouldGenerateClientMap = clientComponentMap !== null && clientComponentMap !== void 0 ? clientComponentMap : true;
280
+ const clientComponents = shouldGenerateClientMap
281
+ ? collectComponents({ paths, exclude, includeVariants, filter: 'client' })
282
+ : { raw: [], entries: [] };
283
+ const clientTemplate = clientMapTemplate || defaultClientMapTemplate;
284
+ let clientContent;
285
+ if (isComponentMapTemplate(clientTemplate))
286
+ clientContent = clientTemplate(clientComponents.raw, componentImports);
287
+ else
288
+ clientContent = clientTemplate(clientComponents.raw, componentImports, {
289
+ entries: clientComponents.entries,
290
+ includeVariants,
291
+ isClientMap: true,
292
+ });
293
+ try {
294
+ fs.writeFileSync(path.join(process.cwd(), destination, 'component-map.client.ts'), clientContent, 'utf8');
295
+ }
296
+ catch (error) {
297
+ console.error(`Client Component Map generation failed. Error writing to file ${destination}:`, error);
298
+ throw error;
295
299
  }
296
300
  };
@@ -1,6 +1,17 @@
1
1
  import { getComponentList, defaultImportMapTemplate, } from '@sitecore-content-sdk/content/node-tools';
2
2
  import ts from 'typescript';
3
3
  import fs from 'fs';
4
+ /**
5
+ * Constants for Next.js router types. Used for consistent detection and comparison throughout the codebase.
6
+ * Values are based on Next.js conventions:
7
+ * - 'app' for App Router (src/app or app directory)
8
+ * - 'pages' for Pages Router (src/pages or pages directory)
9
+ * @internal
10
+ */
11
+ export const ROUTER_TYPE = {
12
+ APP: 'app',
13
+ PAGES: 'pages',
14
+ };
4
15
  /**
5
16
  * Detects the Next.js router type (App Router or Pages Router) based on directory structure.
6
17
  * @param {string} projectRoot - The project root directory. Defaults to current working directory.
@@ -8,15 +19,15 @@ import fs from 'fs';
8
19
  * @internal
9
20
  */
10
21
  export function detectRouterType(projectRoot = process.cwd()) {
11
- const appDirExists = fs.existsSync(`${projectRoot}/src/app`) || fs.existsSync(`${projectRoot}/app`);
12
- const pagesDirExists = fs.existsSync(`${projectRoot}/src/pages`) || fs.existsSync(`${projectRoot}/pages`);
13
- if (appDirExists) {
14
- return 'app';
15
- }
16
- if (pagesDirExists) {
17
- return 'pages';
18
- }
19
- return 'pages';
22
+ const appDirExists = fs.existsSync(`${projectRoot}/src/${ROUTER_TYPE.APP}`) ||
23
+ fs.existsSync(`${projectRoot}/${ROUTER_TYPE.APP}`);
24
+ const pagesDirExists = fs.existsSync(`${projectRoot}/src/${ROUTER_TYPE.PAGES}`) ||
25
+ fs.existsSync(`${projectRoot}/${ROUTER_TYPE.PAGES}`);
26
+ if (appDirExists)
27
+ return ROUTER_TYPE.APP;
28
+ if (pagesDirExists)
29
+ return ROUTER_TYPE.PAGES;
30
+ return ROUTER_TYPE.PAGES;
20
31
  }
21
32
  /**
22
33
  * Detects the component type based on directives, imports, and router context.
@@ -144,7 +155,7 @@ export function detectComponentType(filePath, routerType) {
144
155
  // Router-aware defaults:
145
156
  // - App Router: defaults to server (RSC by default)
146
157
  // - Pages Router: defaults to universal (isomorphic by default)
147
- if (detectedRouterType === 'app') {
158
+ if (detectedRouterType === ROUTER_TYPE.APP) {
148
159
  return 'server';
149
160
  }
150
161
  else {