@sitecore-content-sdk/nextjs 2.0.0-canary.9 → 2.0.0

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 (86) hide show
  1. package/LICENSE.txt +202 -202
  2. package/dist/cjs/cache/page-params.js +30 -0
  3. package/dist/cjs/client/sitecore-nextjs-client.js +57 -94
  4. package/dist/cjs/components/BYOCWrapper.js +3 -12
  5. package/dist/cjs/components/DesignLibrary/DesignLibraryApp.js +31 -0
  6. package/dist/cjs/components/DesignLibrary/DesignLibraryClientEvents.js +139 -0
  7. package/dist/cjs/components/DesignLibrary/DesignLibraryServer.js +221 -0
  8. package/dist/cjs/components/DesignLibrary/index.js +5 -0
  9. package/dist/cjs/components/DesignLibrary/models.js +2 -0
  10. package/dist/cjs/components/FEaaSWrapper.js +3 -12
  11. package/dist/cjs/editing/editing-config-middleware.js +2 -11
  12. package/dist/cjs/editing/editing-render-middleware.js +3 -12
  13. package/dist/cjs/editing/feaas-render-middleware.js +2 -11
  14. package/dist/cjs/editing/utils.js +3 -12
  15. package/dist/cjs/index.js +12 -2
  16. package/dist/cjs/initialization/proxy/analytics-adapter.js +71 -0
  17. package/dist/cjs/initialization/proxy/personalize-adapter.js +72 -0
  18. package/dist/cjs/middleware/robots-middleware.js +16 -25
  19. package/dist/cjs/middleware/sitemap-middleware.js +19 -28
  20. package/dist/cjs/monitoring/healthcheck-middleware.js +2 -11
  21. package/dist/cjs/proxy/locale-proxy.js +2 -11
  22. package/dist/cjs/proxy/multisite-proxy.js +2 -11
  23. package/dist/cjs/proxy/personalize-proxy.js +40 -36
  24. package/dist/cjs/proxy/proxy.js +3 -12
  25. package/dist/cjs/proxy/redirects-proxy.js +58 -69
  26. package/dist/cjs/route-handler/editing-config-route-handler.js +4 -13
  27. package/dist/cjs/route-handler/editing-render-route-handler.js +17 -28
  28. package/dist/cjs/route-handler/robots-route-handler.js +5 -14
  29. package/dist/cjs/route-handler/sitemap-route-handler.js +5 -14
  30. package/dist/cjs/server-actions/update-server-component-action.js +56 -0
  31. package/dist/cjs/services/component-props-service.js +63 -80
  32. package/dist/esm/cache/page-params.js +25 -0
  33. package/dist/esm/client/sitecore-nextjs-client.js +57 -94
  34. package/dist/esm/components/BYOCWrapper.js +3 -12
  35. package/dist/esm/components/DesignLibrary/DesignLibraryApp.js +24 -0
  36. package/dist/esm/components/DesignLibrary/DesignLibraryClientEvents.js +100 -0
  37. package/dist/esm/components/DesignLibrary/DesignLibraryServer.js +178 -0
  38. package/dist/esm/components/DesignLibrary/index.js +1 -0
  39. package/dist/esm/components/DesignLibrary/models.js +1 -0
  40. package/dist/esm/components/FEaaSWrapper.js +3 -12
  41. package/dist/esm/editing/editing-config-middleware.js +2 -11
  42. package/dist/esm/editing/editing-render-middleware.js +3 -12
  43. package/dist/esm/editing/feaas-render-middleware.js +2 -11
  44. package/dist/esm/editing/utils.js +3 -12
  45. package/dist/esm/index.js +6 -1
  46. package/dist/esm/initialization/proxy/analytics-adapter.js +66 -0
  47. package/dist/esm/initialization/proxy/personalize-adapter.js +69 -0
  48. package/dist/esm/middleware/robots-middleware.js +16 -25
  49. package/dist/esm/middleware/sitemap-middleware.js +19 -28
  50. package/dist/esm/monitoring/healthcheck-middleware.js +2 -11
  51. package/dist/esm/proxy/locale-proxy.js +2 -11
  52. package/dist/esm/proxy/multisite-proxy.js +2 -11
  53. package/dist/esm/proxy/personalize-proxy.js +40 -36
  54. package/dist/esm/proxy/proxy.js +3 -12
  55. package/dist/esm/proxy/redirects-proxy.js +58 -69
  56. package/dist/esm/route-handler/editing-config-route-handler.js +4 -13
  57. package/dist/esm/route-handler/editing-render-route-handler.js +17 -28
  58. package/dist/esm/route-handler/robots-route-handler.js +5 -14
  59. package/dist/esm/route-handler/sitemap-route-handler.js +5 -14
  60. package/dist/esm/server-actions/update-server-component-action.js +52 -0
  61. package/dist/esm/services/component-props-service.js +63 -80
  62. package/package.json +10 -10
  63. package/types/cache/page-params.d.ts +30 -0
  64. package/types/cache/page-params.d.ts.map +1 -0
  65. package/types/components/DesignLibrary/DesignLibraryApp.d.ts +14 -0
  66. package/types/components/DesignLibrary/DesignLibraryApp.d.ts.map +1 -0
  67. package/types/components/DesignLibrary/DesignLibraryClientEvents.d.ts +21 -0
  68. package/types/components/DesignLibrary/DesignLibraryClientEvents.d.ts.map +1 -0
  69. package/types/components/DesignLibrary/DesignLibraryServer.d.ts +38 -0
  70. package/types/components/DesignLibrary/DesignLibraryServer.d.ts.map +1 -0
  71. package/types/components/DesignLibrary/index.d.ts +2 -0
  72. package/types/components/DesignLibrary/index.d.ts.map +1 -0
  73. package/types/components/DesignLibrary/models.d.ts +60 -0
  74. package/types/components/DesignLibrary/models.d.ts.map +1 -0
  75. package/types/index.d.ts +9 -1
  76. package/types/index.d.ts.map +1 -1
  77. package/types/initialization/proxy/analytics-adapter.d.ts +30 -0
  78. package/types/initialization/proxy/analytics-adapter.d.ts.map +1 -0
  79. package/types/initialization/proxy/personalize-adapter.d.ts +23 -0
  80. package/types/initialization/proxy/personalize-adapter.d.ts.map +1 -0
  81. package/types/middleware/robots-middleware.d.ts.map +1 -1
  82. package/types/middleware/sitemap-middleware.d.ts.map +1 -1
  83. package/types/proxy/personalize-proxy.d.ts +2 -1
  84. package/types/proxy/personalize-proxy.d.ts.map +1 -1
  85. package/types/server-actions/update-server-component-action.d.ts +63 -0
  86. package/types/server-actions/update-server-component-action.d.ts.map +1 -0
@@ -0,0 +1,178 @@
1
+ 'use server';
2
+ import React from 'react';
3
+ import { EDITING_COMPONENT_PLACEHOLDER } from '@sitecore-content-sdk/content/layout';
4
+ import { DesignLibraryPreviewEvents, DesignLibraryVariantGenerationEvents, } from './DesignLibraryClientEvents';
5
+ import * as globalCache from '@sitecore-content-sdk/core/tools';
6
+ import { DesignLibraryStatus, COMPONENT_UPDATE_CACHE_KEY_PREFIX, COMPONENT_PREVIEW_CACHE_KEY_PREFIX, updateComponent as updateComponentOriginal, } from '@sitecore-content-sdk/content/editing';
7
+ import * as codegen from '@sitecore-content-sdk/content/codegen';
8
+ import { AppPlaceholder, PlaceholderMetadata } from '@sitecore-content-sdk/react';
9
+ import { DesignLibraryErrorBoundary, ErrorComponent, } from '@sitecore-content-sdk/react';
10
+ let { getCacheAndClean, hasCache } = globalCache;
11
+ let { createComponentInstance, getImportMapInfo } = codegen;
12
+ let updateComponent = updateComponentOriginal;
13
+ export const __mockDependencies = async (mocks) => {
14
+ getCacheAndClean = mocks.getCacheAndClean;
15
+ hasCache = mocks.hasCache;
16
+ createComponentInstance = mocks.createComponentInstance;
17
+ if (mocks.updateComponent) {
18
+ updateComponent = mocks.updateComponent;
19
+ }
20
+ if (mocks.getImportMapInfo) {
21
+ getImportMapInfo = mocks.getImportMapInfo;
22
+ }
23
+ };
24
+ /**
25
+ * Design Library component for rendering server components in app router application.
26
+ *
27
+ * Renders the **real** Sitecore component for `library` / `library-metadata` modes and,
28
+ * when generation is enabled (`page.mode.designLibrary.isVariantGeneration === true`),
29
+ * wires the **variant generation** handshake so the parent (Design Library) can send
30
+ * generated code to preview and iterate on.
31
+ * Also renders the DesignLibraryClientEvents component which serves as a communication bridge between DesignLibraryServer and the Design Studio on the client side.
32
+ * @param {DesignLibraryServerProps} props The props. {@link DesignLibraryServerProps}
33
+ * @returns {JSX.Element} The preview surface, or `null` when not in Design Library mode.
34
+ */
35
+ export const DesignLibraryServer = async ({ page, componentMap, rendering, loadServerImportMap, }) => {
36
+ var _a;
37
+ if (!page.mode.isDesignLibrary) {
38
+ return null;
39
+ }
40
+ const isVariantGeneration = (_a = page.mode.designLibrary) === null || _a === void 0 ? void 0 : _a.isVariantGeneration;
41
+ if (isVariantGeneration) {
42
+ return (React.createElement(DesignLibraryServerVariantGeneration, { page: page, rendering: rendering, loadServerImportMap: loadServerImportMap, componentMap: componentMap }));
43
+ }
44
+ return (React.createElement(DesignLibraryServerPreview, { page: page, rendering: rendering, componentMap: componentMap }));
45
+ };
46
+ /**
47
+ * Design Library component for rendering server components in app router application in variant generation mode.
48
+ *
49
+ * Renders the **real** Sitecore component for `library` / `library-metadata` modes on first render and,
50
+ * wires the **variant generation** handshake so the parent (Design Library) can send
51
+ * generated code to preview and iterate on.
52
+ * Also renders the DesignLibraryVariantGenerationEvents component which serves as a communication bridge between DesignLibraryServer and the Design Studio on the client side.
53
+ * @param {DesignLibraryServerVariantGenerationProps} props The props. {@link DesignLibraryServerVariantGenerationProps}
54
+ * @returns {JSX.Element} The preview surface, or `null` when not in Design Library mode.
55
+ */
56
+ export const DesignLibraryServerVariantGeneration = async ({ page, rendering, loadServerImportMap, componentMap, }) => {
57
+ var _a, _b;
58
+ let designLibraryStatus = DesignLibraryStatus.READY;
59
+ let importMap;
60
+ let importMapInfo;
61
+ let Component;
62
+ let componentInitError;
63
+ let generatedComponentData;
64
+ const getComponentInitError = (type, error) => ({
65
+ type,
66
+ message: error instanceof Error ? error.message : String(error),
67
+ });
68
+ // load importmap and importmap payload to pass to FE
69
+ // if not provided, or errors during load set error to pass to FE
70
+ if (!loadServerImportMap) {
71
+ componentInitError = getComponentInitError(codegen.DesignLibraryPreviewError.ImportMapMissing, 'No loadImportMap provided');
72
+ }
73
+ else {
74
+ try {
75
+ const mod = await loadServerImportMap();
76
+ importMap = mod.default;
77
+ importMapInfo = getImportMapInfo(importMap);
78
+ }
79
+ catch (e) {
80
+ componentInitError = getComponentInitError(codegen.DesignLibraryPreviewError.ImportMapLoad, `Error loading import map: ${e}`);
81
+ }
82
+ }
83
+ let componentToUpdate = (_b = (_a = rendering === null || rendering === void 0 ? void 0 : rendering.placeholders) === null || _a === void 0 ? void 0 : _a[EDITING_COMPONENT_PLACEHOLDER]) === null || _b === void 0 ? void 0 : _b[0];
84
+ if (!componentToUpdate)
85
+ return React.createElement(ErrorComponent, { message: "Rendering data is missing" });
86
+ if (!componentToUpdate.uid)
87
+ return React.createElement(ErrorComponent, { message: "Rendering UID is missing in the rendering data" });
88
+ const uid = componentToUpdate.uid;
89
+ const componentUpdateKey = `${COMPONENT_UPDATE_CACHE_KEY_PREFIX}${uid}`;
90
+ const componentPreviewKey = `${COMPONENT_PREVIEW_CACHE_KEY_PREFIX}${uid}`;
91
+ // check if we have an update for this component in the global cache
92
+ if (hasCache(componentUpdateKey)) {
93
+ // we have fields/params update, get it and clean the cache
94
+ designLibraryStatus = DesignLibraryStatus.RENDERED;
95
+ const updateData = getCacheAndClean(componentUpdateKey);
96
+ // apply the updates to the component rendering
97
+ if (updateData === null || updateData === void 0 ? void 0 : updateData.rendering) {
98
+ updateComponent(componentToUpdate, updateData.rendering.fields, updateData.rendering.params);
99
+ }
100
+ // generate the component instance if we are dealing with an AI-generated component
101
+ if ((updateData === null || updateData === void 0 ? void 0 : updateData.generatedComponentData) && !componentInitError && importMap) {
102
+ generatedComponentData = updateData.generatedComponentData;
103
+ try {
104
+ // use provided code and import map to create the component instance
105
+ Component = createComponentInstance(importMap, updateData.generatedComponentData);
106
+ }
107
+ catch (error) {
108
+ // error during component initialization - send error to client
109
+ componentInitError = getComponentInitError(codegen.DesignLibraryPreviewError.RenderInit, error);
110
+ }
111
+ }
112
+ }
113
+ else if (hasCache(componentPreviewKey) && !componentInitError && importMap) {
114
+ // we have a preview update, get it and clean the cache
115
+ designLibraryStatus = DesignLibraryStatus.RENDERED;
116
+ const previewData = getCacheAndClean(componentPreviewKey);
117
+ if (previewData === null || previewData === void 0 ? void 0 : previewData.error) {
118
+ componentInitError = getComponentInitError(codegen.DesignLibraryPreviewError.GeneratedComponentFetch, previewData.error);
119
+ }
120
+ // apply the updates to the component rendering
121
+ if (previewData === null || previewData === void 0 ? void 0 : previewData.rendering) {
122
+ updateComponent(componentToUpdate, previewData.rendering.fields, previewData.rendering.params);
123
+ }
124
+ if (previewData === null || previewData === void 0 ? void 0 : previewData.generatedComponentData) {
125
+ generatedComponentData = previewData.generatedComponentData;
126
+ try {
127
+ // use provided code and import map to create the component instance
128
+ Component = createComponentInstance(importMap, previewData.generatedComponentData);
129
+ }
130
+ catch (error) {
131
+ // error during component initialization - send error to client
132
+ componentInitError = getComponentInitError(codegen.DesignLibraryPreviewError.RenderInit, error);
133
+ }
134
+ }
135
+ }
136
+ return (React.createElement(React.Fragment, null,
137
+ Component ? (React.createElement(DesignLibraryErrorBoundary, { uid: componentToUpdate.uid },
138
+ React.createElement(PlaceholderMetadata, { rendering: componentToUpdate },
139
+ React.createElement(Component, { fields: componentToUpdate.fields, params: componentToUpdate.params, key: Date.now() })))) : (React.createElement(AppPlaceholder, { name: EDITING_COMPONENT_PLACEHOLDER, page: page, rendering: rendering, componentMap: componentMap, key: Date.now() })),
140
+ React.createElement(DesignLibraryVariantGenerationEvents, { designLibraryStatus: designLibraryStatus, importMap: importMapInfo,
141
+ // pass a new object since we have mutated the original which leads to old reference passed to the client
142
+ component: Object.assign({}, componentToUpdate), componentInitError: componentInitError, generatedComponentData: generatedComponentData })));
143
+ };
144
+ /**
145
+ * Design Library component for rendering server components in app router application when variant generation is not enabled.
146
+ *
147
+ * Renders the **real** Sitecore component for `library` / `library-metadata` modes and,
148
+ * wires the **component update** handshake so the parent (Design Library) can send
149
+ * updated component props.
150
+ * Also renders the DesignLibraryPreviewEvents component which serves as a communication bridge between DesignLibraryServer and the Design Studio on the client side.
151
+ * @param {DesignLibraryServerPreviewProps} props The props. {@link DesignLibraryServerPreviewProps}
152
+ * @returns {JSX.Element} The preview surface, or `null` when not in Design Library mode.
153
+ */
154
+ export const DesignLibraryServerPreview = async ({ page, rendering, componentMap, }) => {
155
+ var _a, _b;
156
+ let designLibraryStatus = DesignLibraryStatus.READY;
157
+ let componentToUpdate = (_b = (_a = rendering === null || rendering === void 0 ? void 0 : rendering.placeholders) === null || _a === void 0 ? void 0 : _a[EDITING_COMPONENT_PLACEHOLDER]) === null || _b === void 0 ? void 0 : _b[0];
158
+ if (!componentToUpdate)
159
+ return React.createElement(ErrorComponent, { message: "Rendering data is missing" });
160
+ if (!componentToUpdate.uid)
161
+ return React.createElement(ErrorComponent, { message: "Rendering UID is missing in the rendering data" });
162
+ const componentUpdateKey = `${COMPONENT_UPDATE_CACHE_KEY_PREFIX}${componentToUpdate.uid}`;
163
+ // check if we have an update for this component in the global cache
164
+ if (hasCache(componentUpdateKey)) {
165
+ // we have an update, get it and clean the cache
166
+ designLibraryStatus = DesignLibraryStatus.RENDERED;
167
+ const updateData = getCacheAndClean(componentUpdateKey);
168
+ // apply the updates to the component rendering
169
+ if (updateData === null || updateData === void 0 ? void 0 : updateData.rendering) {
170
+ updateComponent(componentToUpdate, updateData.rendering.fields, updateData.rendering.params);
171
+ }
172
+ }
173
+ return (React.createElement(React.Fragment, null,
174
+ React.createElement(AppPlaceholder, { name: EDITING_COMPONENT_PLACEHOLDER, page: page, rendering: rendering, componentMap: componentMap, key: Date.now() }),
175
+ React.createElement(DesignLibraryPreviewEvents, { designLibraryStatus: designLibraryStatus,
176
+ // pass a new object since we have mutated the original which leads to old reference passed to the client
177
+ component: Object.assign({}, componentToUpdate) })));
178
+ };
@@ -0,0 +1 @@
1
+ export { DesignLibraryApp } from './DesignLibraryApp';
@@ -0,0 +1 @@
1
+ export {};
@@ -1,12 +1,3 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
1
  import { FEaaSWrapper, fetchFEaaSComponentServerProps, LayoutServicePageState, } from '@sitecore-content-sdk/react';
11
2
  /**
12
3
  * Will be called during SSG or SSR
@@ -15,10 +6,10 @@ import { FEaaSWrapper, fetchFEaaSComponentServerProps, LayoutServicePageState, }
15
6
  * @returns {GetStaticPropsContext | GetServerSideProps} context
16
7
  * @internal
17
8
  */
18
- export const getComponentServerProps = (rendering, layoutData) => __awaiter(void 0, void 0, void 0, function* () {
9
+ export const getComponentServerProps = async (rendering, layoutData) => {
19
10
  const params = rendering.params || {};
20
11
  const isPageStateNormal = !layoutData.sitecore.context.pageState ||
21
12
  layoutData.sitecore.context.pageState === LayoutServicePageState.Normal;
22
- return yield fetchFEaaSComponentServerProps(params, isPageStateNormal);
23
- });
13
+ return await fetchFEaaSComponentServerProps(params, isPageStateNormal);
14
+ };
24
15
  export default FEaaSWrapper;
@@ -1,12 +1,3 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
1
  import { EDITING_ALLOWED_ORIGINS, QUERY_PARAM_EDITING_SECRET, } from '@sitecore-content-sdk/content/editing';
11
2
  import debug from '../debug';
12
3
  import { getEnforcedCorsHeaders } from '@sitecore-content-sdk/core/tools';
@@ -23,7 +14,7 @@ export class EditingConfigMiddleware {
23
14
  */
24
15
  constructor(config) {
25
16
  this.config = config;
26
- this.handler = (_req, res) => __awaiter(this, void 0, void 0, function* () {
17
+ this.handler = async (_req, res) => {
27
18
  const secret = _req.query[QUERY_PARAM_EDITING_SECRET];
28
19
  const corsHeaders = getEnforcedCorsHeaders({
29
20
  requestMethod: _req.method,
@@ -53,7 +44,7 @@ export class EditingConfigMiddleware {
53
44
  packages: this.config.metadata.packages,
54
45
  editMode: EditMode.Metadata,
55
46
  });
56
- });
47
+ };
57
48
  }
58
49
  /**
59
50
  * Gets the Next.js API route handler
@@ -1,12 +1,3 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
1
  import { NativeDataFetcher } from '@sitecore-content-sdk/core';
11
2
  import { QUERY_PARAM_EDITING_SECRET, INVALID_SECRET_HTML_MESSAGE, EDITING_ALLOWED_ORIGINS, } from '@sitecore-content-sdk/content/editing';
12
3
  import { LayoutServicePageState } from '@sitecore-content-sdk/content/layout';
@@ -27,7 +18,7 @@ export class EditingRenderMiddleware extends RenderMiddlewareBase {
27
18
  constructor(config) {
28
19
  super();
29
20
  this.config = config;
30
- this.handler = (req, res) => __awaiter(this, void 0, void 0, function* () {
21
+ this.handler = async (req, res) => {
31
22
  var _a, _b, _c, _d, _e, _f;
32
23
  const { body, method, headers, query } = req;
33
24
  debug.editing('editing render middleware start: %o', {
@@ -114,7 +105,7 @@ export class EditingRenderMiddleware extends RenderMiddlewareBase {
114
105
  const propagatedQsParams = getQueryParamsForPropagation(query);
115
106
  // Get headers to propagate on subsequent requests
116
107
  const propagatedHeaders = getHeadersForPropagation(headers);
117
- const html = yield getEditingRequestHtml(requestUrl, propagatedQsParams, propagatedHeaders, cookies, this.dataFetcher);
108
+ const html = await getEditingRequestHtml(requestUrl, propagatedQsParams, propagatedHeaders, cookies, this.dataFetcher);
118
109
  // remove preview cookies to not leak them to the browser
119
110
  if (cookies && Array.isArray(cookies)) {
120
111
  const filteredCookies = cleanupNextPreviewCookies(cookies);
@@ -137,7 +128,7 @@ export class EditingRenderMiddleware extends RenderMiddlewareBase {
137
128
  }
138
129
  res.status(500).send(`<html><body>${error}</body></html>`);
139
130
  }
140
- });
131
+ };
141
132
  this.dataFetcher = new NativeDataFetcher({ debugger: debug.editing });
142
133
  }
143
134
  /**
@@ -1,12 +1,3 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
1
  import { EDITING_ALLOWED_ORIGINS, QUERY_PARAM_EDITING_SECRET, INVALID_SECRET_HTML_MESSAGE, } from '@sitecore-content-sdk/content/editing';
11
2
  import { getEditingSecret } from '../utils/utils';
12
3
  import { RenderMiddlewareBase } from './render-middleware';
@@ -26,7 +17,7 @@ export class FEAASRenderMiddleware extends RenderMiddlewareBase {
26
17
  super();
27
18
  this.config = config;
28
19
  this.defaultPageUrl = '/feaas/render';
29
- this.handler = (req, res) => __awaiter(this, void 0, void 0, function* () {
20
+ this.handler = async (req, res) => {
30
21
  var _a;
31
22
  const { method, query, headers } = req;
32
23
  const startTimestamp = Date.now();
@@ -93,7 +84,7 @@ export class FEAASRenderMiddleware extends RenderMiddlewareBase {
93
84
  "Hint: for non-standard server or Next.js route configurations, you may need to override the 'pageUrl' available on the 'FEAASRenderMiddleware' config.");
94
85
  res.status(500).send(`<html><body>${error}</body></html>`);
95
86
  }
96
- });
87
+ };
97
88
  this.pageUrl = (_a = config === null || config === void 0 ? void 0 : config.pageUrl) !== null && _a !== void 0 ? _a : this.defaultPageUrl;
98
89
  }
99
90
  /**
@@ -1,12 +1,3 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
1
  import { EDITING_ALLOWED_ORIGINS, isDesignLibraryMode, PREVIEW_KEY, QUERY_PARAM_EDITING_SECRET, } from '@sitecore-content-sdk/content/editing';
11
2
  import { DEFAULT_VARIANT } from '@sitecore-content-sdk/content/personalize';
12
3
  import { SITE_KEY } from '@sitecore-content-sdk/content/site';
@@ -180,7 +171,7 @@ export const getHeadersForPropagation = (headers) => {
180
171
  * @param {NativeDataFetcher} dataFetcher NativeFetcher instance to send request with
181
172
  * @returns {string} HTML with editing markup
182
173
  */
183
- export const getEditingRequestHtml = (requestUrl, propagatedQsParams, propagatedHeaders, cookies, dataFetcher) => __awaiter(void 0, void 0, void 0, function* () {
174
+ export const getEditingRequestHtml = async (requestUrl, propagatedQsParams, propagatedHeaders, cookies, dataFetcher) => {
184
175
  // Grab the Next.js preview cookies to send on to the render request
185
176
  propagatedHeaders.cookie = `${propagatedHeaders.cookie ? propagatedHeaders.cookie + ';' : ''}${cookies.join(';')}`;
186
177
  // enable content sdk preview
@@ -191,7 +182,7 @@ export const getEditingRequestHtml = (requestUrl, propagatedQsParams, propagated
191
182
  }
192
183
  }
193
184
  requestUrl.searchParams.append('timestamp', Date.now().toString());
194
- const pageRes = yield dataFetcher
185
+ const pageRes = await dataFetcher
195
186
  .get(requestUrl.toString(), {
196
187
  credentials: 'include',
197
188
  headers: propagatedHeaders,
@@ -219,7 +210,7 @@ export const getEditingRequestHtml = (requestUrl, propagatedQsParams, propagated
219
210
  // The following line will trick it into thinking we're SSR, thus avoiding any router.replace.
220
211
  html = html.replace(STATIC_PROPS_ID, SERVER_PROPS_ID);
221
212
  return html;
222
- });
213
+ };
223
214
  /**
224
215
  * Type guard for Design Library mode
225
216
  * @param {object} data preview data to check
package/dist/esm/index.js CHANGED
@@ -21,4 +21,9 @@ import * as BYOCWrapper from './components/BYOCWrapper';
21
21
  export { FEaaSClientWrapper, FEaaSServerWrapper, BYOCClientWrapper, BYOCServerWrapper, } from '@sitecore-content-sdk/react';
22
22
  export { FEaaSWrapper };
23
23
  export { BYOCWrapper };
24
- export { Image, Text, DateField, FEaaSComponent, fetchFEaaSComponentServerProps, BYOCComponent, getDesignLibraryStylesheetLinks, File, DesignLibrary, DesignLibraryApp, DefaultEmptyFieldEditingComponentImage, DefaultEmptyFieldEditingComponentText, SitecoreProvider, SitecoreProviderReactContext, withSitecore, useSitecore, withEditorChromes, withAppPlaceholder, withPlaceholder, withDatasourceCheck, withFieldMetadata, withEmptyFieldEditingComponent, EditingScripts, Form, ClientEditingChromesUpdate, AppPlaceholder, renderEmptyPlaceholder, } from '@sitecore-content-sdk/react';
24
+ export { Image, Text, DateField, FEaaSComponent, fetchFEaaSComponentServerProps, BYOCComponent, getDesignLibraryStylesheetLinks, File, DesignLibrary, DefaultEmptyFieldEditingComponentImage, DefaultEmptyFieldEditingComponentText, SitecoreProvider, SitecoreProviderReactContext, withSitecore, useSitecore, withEditorChromes, withAppPlaceholder, withPlaceholder, withDatasourceCheck, withFieldMetadata, withEmptyFieldEditingComponent, EditingScripts, Form, ClientEditingChromesUpdate, AppPlaceholder, renderEmptyPlaceholder, } from '@sitecore-content-sdk/react';
25
+ export { initContentSdk } from '@sitecore-content-sdk/core';
26
+ export { personalizeProxyAdapter } from './initialization/proxy/personalize-adapter';
27
+ export { analyticsProxyAdapter } from './initialization/proxy/analytics-adapter';
28
+ export { DesignLibraryApp } from './components/DesignLibrary/DesignLibraryApp';
29
+ export { getCachedPageParams, setCachedPageParams, } from './cache/page-params';
@@ -0,0 +1,66 @@
1
+ import { COOKIE_NAME_PREFIX, fetchClientIdFromEdgeProxy, getDefaultCookieAttributes, } from '@sitecore-content-sdk/analytics-core/internal';
2
+ import { getAnalyticsPlugin, } from '@sitecore-content-sdk/analytics-core/internal';
3
+ import { getCoreContext } from '@sitecore-content-sdk/core';
4
+ /**
5
+ * Creates a proxy-based analytics adapter that reads and writes the visitor ID
6
+ * using cookies and can resolve a new client ID from the Edge proxy when needed.
7
+ * The adapter also provides access to the current URL search parameters.
8
+ * @param {NextRequest} request - The Next.js request object.
9
+ * @param {NextResponse} response - The Next.js response object.
10
+ * @returns {AnalyticsProxyAdapter} The analytics proxy adapter.
11
+ * @public
12
+ */
13
+ export function analyticsProxyAdapter(request, response) {
14
+ return {
15
+ type: 'proxy',
16
+ getClientId: () => {
17
+ return getClientId(request);
18
+ },
19
+ setClientId: async () => {
20
+ var _a;
21
+ const coreConfig = getCoreContext().config;
22
+ const analyticsOptions = getAnalyticsPlugin().options;
23
+ const cookieOptions = analyticsOptions.cookies;
24
+ const clientIdCookieName = cookieOptions.name;
25
+ const legacyClientIdCookieName = `${COOKIE_NAME_PREFIX}${coreConfig.contextId}`;
26
+ const cookieAttributes = getDefaultCookieAttributes(cookieOptions.expiryDays, cookieOptions.domain);
27
+ const legacyClientIdCookie = (_a = request.cookies.get(legacyClientIdCookieName)) === null || _a === void 0 ? void 0 : _a.value;
28
+ if (legacyClientIdCookie) {
29
+ request.cookies.set(clientIdCookieName, legacyClientIdCookie);
30
+ response.cookies.set(clientIdCookieName, legacyClientIdCookie, Object.assign(Object.assign({}, cookieAttributes), { sameSite: 'none' }));
31
+ request.cookies.delete(legacyClientIdCookieName);
32
+ response.cookies.delete(legacyClientIdCookieName);
33
+ return;
34
+ }
35
+ const clientIdCookie = getClientId(request);
36
+ let newClientIdCookieValue;
37
+ if (!clientIdCookie) {
38
+ const cookieValues = await fetchClientIdFromEdgeProxy(coreConfig.edgeUrl, coreConfig.contextId, analyticsOptions.timeout);
39
+ newClientIdCookieValue = cookieValues.clientId;
40
+ analyticsOptions.visitorIds = cookieValues;
41
+ }
42
+ else
43
+ newClientIdCookieValue = clientIdCookie;
44
+ if (!clientIdCookie)
45
+ request.cookies.set(clientIdCookieName, newClientIdCookieValue);
46
+ const attributes = getDefaultCookieAttributes(cookieOptions.expiryDays, cookieOptions.domain);
47
+ response.cookies.set(clientIdCookieName, newClientIdCookieValue, Object.assign(Object.assign({}, attributes), { sameSite: 'none' }));
48
+ },
49
+ location: {
50
+ getSearchParams: () => {
51
+ return request.nextUrl.searchParams.toString();
52
+ },
53
+ },
54
+ };
55
+ }
56
+ /**
57
+ * Retrieves the client ID from the request cookies.
58
+ * @param {NextRequest} request
59
+ * @returns {string | null} The client ID or null if not found.
60
+ * @internal
61
+ */
62
+ export const getClientId = (request) => {
63
+ var _a;
64
+ const clientIdCookieName = getAnalyticsPlugin().options.cookies.name;
65
+ return ((_a = request.cookies.get(clientIdCookieName)) === null || _a === void 0 ? void 0 : _a.value) || null;
66
+ };
@@ -0,0 +1,69 @@
1
+ import { COOKIE_NAME_PREFIX, getDefaultCookieAttributes, } from '@sitecore-content-sdk/analytics-core/internal';
2
+ import { getAnalyticsPlugin } from '@sitecore-content-sdk/analytics-core/internal';
3
+ import { getCoreContext } from '@sitecore-content-sdk/core';
4
+ import { fetchProfileIdFromEdgeProxy, getPersonalizePlugin, } from '@sitecore-content-sdk/personalize/internal';
5
+ import { getClientId } from './analytics-adapter';
6
+ /**
7
+ * Creates a proxy-based personalize adapter that reads and writes the profile ID
8
+ * using cookies and can resolve a new profile ID from the Edge proxy when needed.
9
+ * The adapter also provides access user agent from the request headers.
10
+ * @param {NextRequest} request - The HTTP request object.
11
+ * @param {NextResponse} response - The HTTP response object.
12
+ * @returns {PersonalizeProxyAdapter} The personalize proxy adapter.
13
+ * @public
14
+ */
15
+ export function personalizeProxyAdapter(request, response) {
16
+ return {
17
+ type: 'proxy',
18
+ getUserAgent: () => request.headers.get('user-agent') || undefined,
19
+ getProfileId: () => {
20
+ return getProfileId(request);
21
+ },
22
+ setProfileId: async () => {
23
+ var _a;
24
+ const coreConfig = getCoreContext().config;
25
+ const cookieOptions = getAnalyticsPlugin().options.cookies;
26
+ const personalizePlugin = getPersonalizePlugin();
27
+ const profileIdCookieName = personalizePlugin.options.cookies.name;
28
+ const cookieAttributes = getDefaultCookieAttributes(cookieOptions.expiryDays, cookieOptions.domain);
29
+ const legacyProfileIdCookieName = `${COOKIE_NAME_PREFIX}${coreConfig.contextId}_personalize`;
30
+ const legacyProfileIdCookie = (_a = request.cookies.get(legacyProfileIdCookieName)) === null || _a === void 0 ? void 0 : _a.value;
31
+ if (legacyProfileIdCookie) {
32
+ request.cookies.set(profileIdCookieName, legacyProfileIdCookie);
33
+ response.cookies.set(profileIdCookieName, legacyProfileIdCookie, Object.assign(Object.assign({}, cookieAttributes), { sameSite: 'none' }));
34
+ request.cookies.delete(legacyProfileIdCookieName);
35
+ response.cookies.delete(legacyProfileIdCookieName);
36
+ return;
37
+ }
38
+ const cookiesValuesFromEdgeServer = getAnalyticsPlugin().options.visitorIds;
39
+ const profileIdCookie = getProfileId(request);
40
+ const clientIdCookie = getClientId(request);
41
+ let newProfileIdCookieValue;
42
+ if (profileIdCookie)
43
+ newProfileIdCookieValue = profileIdCookie;
44
+ else if (cookiesValuesFromEdgeServer === null || cookiesValuesFromEdgeServer === void 0 ? void 0 : cookiesValuesFromEdgeServer.profileId)
45
+ newProfileIdCookieValue = cookiesValuesFromEdgeServer.profileId;
46
+ else if (clientIdCookie) {
47
+ const profileIdCookieValueFromEdgeProxy = await fetchProfileIdFromEdgeProxy(clientIdCookie, coreConfig.contextId, coreConfig.edgeUrl);
48
+ newProfileIdCookieValue = profileIdCookieValueFromEdgeProxy;
49
+ }
50
+ else
51
+ return;
52
+ if (!profileIdCookie)
53
+ request.cookies.set(profileIdCookieName, newProfileIdCookieValue);
54
+ const attributes = getDefaultCookieAttributes(cookieOptions.expiryDays, cookieOptions.domain);
55
+ response.cookies.set(profileIdCookieName, newProfileIdCookieValue, Object.assign(Object.assign({}, attributes), { sameSite: 'none' }));
56
+ },
57
+ };
58
+ }
59
+ /**
60
+ * Retrieves the profile ID from request cookies.
61
+ * @param {NextRequest} request
62
+ * @returns {string | null} The profile ID or null if not found.
63
+ * @internal
64
+ */
65
+ function getProfileId(request) {
66
+ var _a;
67
+ const profileIdCookieName = getPersonalizePlugin().options.cookies.name;
68
+ return ((_a = request.cookies.get(profileIdCookieName)) === null || _a === void 0 ? void 0 : _a.value) || null;
69
+ }
@@ -1,13 +1,6 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
1
+ import { constants } from '@sitecore-content-sdk/core';
10
2
  import { SiteResolver } from '../site';
3
+ const { ERROR_MESSAGES } = constants;
11
4
  /**
12
5
  * Middleware for handling robots.txt requests in a Next.js application.
13
6
  * @public
@@ -20,22 +13,20 @@ export class RobotsMiddleware {
20
13
  getHandler() {
21
14
  return this.handler.bind(this);
22
15
  }
23
- handler(req, res) {
24
- return __awaiter(this, void 0, void 0, function* () {
25
- var _a;
26
- res.setHeader('Content-Type', 'text/plain');
27
- const hostName = req.headers['x-forwarded-host'] || ((_a = req.headers.host) === null || _a === void 0 ? void 0 : _a.split(':')[0]) || 'localhost';
28
- const site = this.siteResolver.getByHost(hostName);
29
- try {
30
- const robotsContent = yield this.client.getRobots(site.name);
31
- if (!robotsContent) {
32
- return res.status(404).send('User-agent: *\nDisallow: /');
33
- }
34
- res.status(200).send(robotsContent);
16
+ async handler(req, res) {
17
+ var _a;
18
+ res.setHeader('Content-Type', 'text/plain');
19
+ const hostName = req.headers['x-forwarded-host'] || ((_a = req.headers.host) === null || _a === void 0 ? void 0 : _a.split(':')[0]) || 'localhost';
20
+ const site = this.siteResolver.getByHost(hostName);
21
+ try {
22
+ const robotsContent = await this.client.getRobots(site.name);
23
+ if (!robotsContent) {
24
+ return res.status(404).send('User-agent: *\nDisallow: /');
35
25
  }
36
- catch (_b) {
37
- res.status(500).send('Internal Server Error');
38
- }
39
- });
26
+ res.status(200).send(robotsContent);
27
+ }
28
+ catch (_b) {
29
+ res.status(500).send(`Internal Server Error. ${ERROR_MESSAGES.CONTACT_SUPPORT}`);
30
+ }
40
31
  }
41
32
  }
@@ -1,13 +1,6 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
1
+ import { constants } from '@sitecore-content-sdk/core';
10
2
  import { SiteResolver } from '../site';
3
+ const { ERROR_MESSAGES } = constants;
11
4
  /**
12
5
  * Middleware for handling sitemap requests in a Next.js application.
13
6
  * Encapsulates all HTTP-related logic for sitemap generation and delivery.
@@ -21,26 +14,24 @@ export class SitemapMiddleware {
21
14
  getHandler() {
22
15
  return this.handler.bind(this);
23
16
  }
24
- handler(req, res) {
25
- return __awaiter(this, void 0, void 0, function* () {
26
- const id = Array.isArray(req.query.id) ? req.query.id[0] : req.query.id;
27
- const reqHost = req.headers['x-forwarded-host'] || req.headers.host || '';
28
- const reqProtocol = req.headers['x-forwarded-proto'] || 'https';
29
- const site = this.siteResolver.getByHost(reqHost);
30
- const options = { reqHost, reqProtocol, id, siteName: site.name };
31
- try {
32
- const xmlContent = yield this.client.getSiteMap(options);
33
- res.setHeader('Content-Type', 'text/xml;charset=utf-8');
34
- res.send(xmlContent);
17
+ async handler(req, res) {
18
+ const id = Array.isArray(req.query.id) ? req.query.id[0] : req.query.id;
19
+ const reqHost = req.headers['x-forwarded-host'] || req.headers.host || '';
20
+ const reqProtocol = req.headers['x-forwarded-proto'] || 'https';
21
+ const site = this.siteResolver.getByHost(reqHost);
22
+ const options = { reqHost, reqProtocol, id, siteName: site.name };
23
+ try {
24
+ const xmlContent = await this.client.getSiteMap(options);
25
+ res.setHeader('Content-Type', 'text/xml;charset=utf-8');
26
+ res.send(xmlContent);
27
+ }
28
+ catch (error) {
29
+ if (error instanceof Error && error.message === 'REDIRECT_404') {
30
+ res.redirect('/404');
35
31
  }
36
- catch (error) {
37
- if (error instanceof Error && error.message === 'REDIRECT_404') {
38
- res.redirect('/404');
39
- }
40
- else {
41
- res.status(500).send('Internal Server Error');
42
- }
32
+ else {
33
+ res.status(500).send(`Internal Server Error. ${ERROR_MESSAGES.CONTACT_SUPPORT}`);
43
34
  }
44
- });
35
+ }
45
36
  }
46
37
  }
@@ -1,21 +1,12 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
1
  /**
11
2
  * Middleware / handler for use in healthcheck Next.js API route (e.g. '/api/healthz').
12
3
  * @public
13
4
  */
14
5
  export class HealthcheckMiddleware {
15
6
  constructor() {
16
- this.handler = (_req, res) => __awaiter(this, void 0, void 0, function* () {
7
+ this.handler = async (_req, res) => {
17
8
  res.status(200).send('Healthy');
18
- });
9
+ };
19
10
  }
20
11
  /**
21
12
  * Gets the Next.js API route handler