@sitecore-jss/sitecore-jss-nextjs 22.0.0-canary.9 → 22.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 (104) hide show
  1. package/LICENSE.txt +202 -202
  2. package/README.md +12 -10
  3. package/context.d.ts +1 -0
  4. package/context.js +1 -0
  5. package/dist/cjs/ComponentBuilder.js +63 -0
  6. package/dist/cjs/components/BYOCWrapper.js +47 -0
  7. package/dist/cjs/components/FEaaSWrapper.js +49 -0
  8. package/dist/cjs/components/Link.js +5 -4
  9. package/dist/cjs/components/NextImage.js +3 -14
  10. package/dist/cjs/components/RichText.js +11 -15
  11. package/dist/cjs/context/context.js +83 -0
  12. package/dist/cjs/context/index.js +5 -0
  13. package/dist/cjs/editing/constants.js +6 -0
  14. package/dist/cjs/editing/editing-config-middleware.js +49 -0
  15. package/dist/cjs/editing/editing-data-middleware.js +3 -3
  16. package/dist/cjs/editing/editing-data-service.js +16 -8
  17. package/dist/cjs/editing/editing-render-middleware.js +25 -11
  18. package/dist/cjs/editing/feaas-render-middleware.js +87 -0
  19. package/dist/cjs/editing/index.js +7 -1
  20. package/dist/cjs/editing/render-middleware.js +27 -0
  21. package/dist/cjs/editing/vercel-editing-data-cache.js +48 -0
  22. package/dist/cjs/graphql/index.js +7 -0
  23. package/dist/cjs/index.js +38 -14
  24. package/dist/cjs/middleware/index.js +3 -5
  25. package/dist/cjs/middleware/middleware.js +18 -2
  26. package/dist/cjs/middleware/multisite-middleware.js +14 -8
  27. package/dist/cjs/middleware/personalize-middleware.js +62 -56
  28. package/dist/cjs/middleware/redirects-middleware.js +64 -21
  29. package/dist/cjs/services/base-graphql-sitemap-service.js +7 -6
  30. package/dist/cjs/services/component-props-service.js +6 -6
  31. package/dist/cjs/site/index.js +5 -0
  32. package/dist/cjs/utils/index.js +11 -0
  33. package/dist/cjs/{utils.js → utils/utils.js} +7 -16
  34. package/dist/esm/ComponentBuilder.js +59 -0
  35. package/dist/esm/components/BYOCWrapper.js +42 -0
  36. package/dist/esm/components/FEaaSWrapper.js +44 -0
  37. package/dist/esm/components/Link.js +5 -4
  38. package/dist/esm/components/NextImage.js +2 -12
  39. package/dist/esm/components/RichText.js +11 -15
  40. package/dist/esm/context/context.js +79 -0
  41. package/dist/esm/context/index.js +1 -0
  42. package/dist/esm/editing/constants.js +3 -0
  43. package/dist/esm/editing/editing-config-middleware.js +45 -0
  44. package/dist/esm/editing/editing-data-middleware.js +2 -2
  45. package/dist/esm/editing/editing-data-service.js +14 -6
  46. package/dist/esm/editing/editing-render-middleware.js +25 -11
  47. package/dist/esm/editing/feaas-render-middleware.js +83 -0
  48. package/dist/esm/editing/index.js +3 -0
  49. package/dist/esm/editing/render-middleware.js +23 -0
  50. package/dist/esm/editing/vercel-editing-data-cache.js +44 -0
  51. package/dist/esm/graphql/index.js +1 -0
  52. package/dist/esm/index.js +10 -7
  53. package/dist/esm/middleware/index.js +1 -2
  54. package/dist/esm/middleware/middleware.js +18 -2
  55. package/dist/esm/middleware/multisite-middleware.js +14 -8
  56. package/dist/esm/middleware/personalize-middleware.js +65 -59
  57. package/dist/esm/middleware/redirects-middleware.js +64 -21
  58. package/dist/esm/services/base-graphql-sitemap-service.js +7 -6
  59. package/dist/esm/services/component-props-service.js +6 -6
  60. package/dist/esm/site/index.js +1 -0
  61. package/dist/esm/utils/index.js +2 -0
  62. package/dist/esm/{utils.js → utils/utils.js} +7 -13
  63. package/graphql.d.ts +1 -0
  64. package/graphql.js +1 -0
  65. package/package.json +15 -12
  66. package/site.d.ts +1 -0
  67. package/site.js +1 -0
  68. package/types/ComponentBuilder.d.ts +61 -0
  69. package/types/components/BYOCWrapper.d.ts +19 -0
  70. package/types/components/ComponentPropsContext.d.ts +1 -0
  71. package/types/components/FEaaSWrapper.d.ts +21 -0
  72. package/types/components/Link.d.ts +2 -1
  73. package/types/components/NextImage.d.ts +3 -3
  74. package/types/components/Placeholder.d.ts +3 -1
  75. package/types/components/RichText.d.ts +6 -4
  76. package/types/context/context.d.ts +116 -0
  77. package/types/context/index.d.ts +1 -0
  78. package/types/editing/constants.d.ts +3 -0
  79. package/types/editing/editing-config-middleware.d.ts +29 -0
  80. package/types/editing/editing-data-service.d.ts +12 -4
  81. package/types/editing/editing-render-middleware.d.ts +2 -1
  82. package/types/editing/feaas-render-middleware.d.ts +32 -0
  83. package/types/editing/index.d.ts +3 -0
  84. package/types/editing/render-middleware.d.ts +15 -0
  85. package/types/editing/vercel-editing-data-cache.d.ts +19 -0
  86. package/types/graphql/index.d.ts +1 -0
  87. package/types/index.d.ts +12 -9
  88. package/types/middleware/index.d.ts +1 -2
  89. package/types/middleware/middleware.d.ts +8 -0
  90. package/types/middleware/multisite-middleware.d.ts +15 -0
  91. package/types/middleware/personalize-middleware.d.ts +53 -14
  92. package/types/middleware/redirects-middleware.d.ts +1 -1
  93. package/types/services/base-graphql-sitemap-service.d.ts +7 -10
  94. package/types/services/component-props-service.d.ts +2 -2
  95. package/types/sharedTypes/component-props.d.ts +5 -1
  96. package/types/sharedTypes/module-factory.d.ts +33 -0
  97. package/types/site/index.d.ts +1 -0
  98. package/types/utils/index.d.ts +2 -0
  99. package/types/{utils.d.ts → utils/utils.d.ts} +2 -0
  100. package/utils.d.ts +1 -0
  101. package/utils.js +1 -0
  102. package/types/sharedTypes/component-module.d.ts +0 -13
  103. /package/dist/cjs/sharedTypes/{component-module.js → module-factory.js} +0 -0
  104. /package/dist/esm/sharedTypes/{component-module.js → module-factory.js} +0 -0
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveUrl = exports.resetEditorChromes = exports.isEditorActive = exports.tryParseEnvValue = exports.handleEditorFastRefresh = exports.getPublicUrl = void 0;
4
+ var utils_1 = require("./utils");
5
+ Object.defineProperty(exports, "getPublicUrl", { enumerable: true, get: function () { return utils_1.getPublicUrl; } });
6
+ Object.defineProperty(exports, "handleEditorFastRefresh", { enumerable: true, get: function () { return utils_1.handleEditorFastRefresh; } });
7
+ var utils_2 = require("@sitecore-jss/sitecore-jss/utils");
8
+ Object.defineProperty(exports, "tryParseEnvValue", { enumerable: true, get: function () { return utils_2.tryParseEnvValue; } });
9
+ Object.defineProperty(exports, "isEditorActive", { enumerable: true, get: function () { return utils_2.isEditorActive; } });
10
+ Object.defineProperty(exports, "resetEditorChromes", { enumerable: true, get: function () { return utils_2.resetEditorChromes; } });
11
+ Object.defineProperty(exports, "resolveUrl", { enumerable: true, get: function () { return utils_2.resolveUrl; } });
@@ -1,10 +1,6 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.getJssEditingSecret = exports.handleEditorFastRefresh = exports.getPublicUrl = void 0;
7
- const chalk_1 = __importDefault(require("chalk"));
8
4
  const utils_1 = require("@sitecore-jss/sitecore-jss/utils");
9
5
  /**
10
6
  * Get the publicUrl.
@@ -12,25 +8,20 @@ const utils_1 = require("@sitecore-jss/sitecore-jss/utils");
12
8
  * This is set to http://localhost:3000 by default.
13
9
  * VERCEL_URL is provided by Vercel in case if we are in Preview deployment (deployment based on the custom branch),
14
10
  * preview deployment has unique url, we don't know exact url.
11
+ * Similarly, DEPLOY_URL is provided by Netlify and would give us the deploy URL
12
+ * In production non-editing environments it is desirable to use relative urls, so in that case set PUBLIC_URL = ''
15
13
  */
16
14
  const getPublicUrl = () => {
17
- if (process.env.VERCEL_URL)
18
- return `https://${process.env.VERCEL_URL}`;
19
15
  let url = process.env.PUBLIC_URL;
20
16
  if (url === undefined) {
21
- console.warn(`${chalk_1.default.yellow.bold('Warning:')} An PUBLIC_URL environment variable is not defined. Falling back to http://localhost:3000.`);
17
+ if (process.env.NETLIFY && process.env.DEPLOY_URL)
18
+ return process.env.DEPLOY_URL;
19
+ if (process.env.VERCEL_URL)
20
+ return `https://${process.env.VERCEL_URL}`;
22
21
  url = 'http://localhost:3000';
23
22
  }
24
- else {
25
- try {
26
- new URL(url);
27
- }
28
- catch (error) {
29
- throw new Error(`The PUBLIC_URL environment variable '${url}' is not a valid URL.`);
30
- }
31
- }
32
23
  // Ensure no trailing slash
33
- return url.toString().replace(/\/$/, '');
24
+ return url.replace(/\/$/, '');
34
25
  };
35
26
  exports.getPublicUrl = getPublicUrl;
36
27
  /**
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Nextjs implementation of component builder class for building components based on the configuration.
3
+ */
4
+ export class ComponentBuilder {
5
+ constructor(config) {
6
+ this.config = config;
7
+ /**
8
+ * SXA uses custom default export name
9
+ */
10
+ this.DEFAULT_EXPORT_NAME = 'Default';
11
+ this.components = new Map([...config.components]);
12
+ }
13
+ /**
14
+ * Creates a new instance of module factory
15
+ * Module factory provides a module (file) including all exports.
16
+ * Module can be imported dynamically or statically.
17
+ * @returns {ModuleFactory} Module factory implementation
18
+ */
19
+ getModuleFactory() {
20
+ return (componentName) => {
21
+ const component = this.components.get(componentName);
22
+ if (!component)
23
+ return null;
24
+ // check if module should be imported dynamically
25
+ if (component.module) {
26
+ return component.module();
27
+ }
28
+ return component;
29
+ };
30
+ }
31
+ /**
32
+ * Creates a new instance of component factory
33
+ * Component can be imported dynamically or statically.
34
+ * @param {Object} [config] Component factory configuration
35
+ * @param {boolean} [config.isEditing] Indicates if component factory is used in editing mode
36
+ * @returns {ComponentFactory} Component factory implementation
37
+ */
38
+ getComponentFactory({ isEditing } = {}) {
39
+ return (componentName, exportName) => {
40
+ const component = this.components.get(componentName);
41
+ if (!component)
42
+ return null;
43
+ // check if component should be imported dynamically
44
+ if (component.element) {
45
+ // Editing mode doesn't work well with dynamic components in nextjs: dynamic components are not displayed without refresh after a rendering is added.
46
+ // This happens beacuse Sitecore editors simply insert updated HTML generated on server side. This conflicts with nextjs dynamic logic as no HTML gets rendered for dynamic component
47
+ // So we use require() to obtain dynamic components in editing mode while preserving dynamic logic for non-editing scenarios
48
+ // As we need to be able to seamlessly work with dynamic components in both editing and normal modes, different componentFactory functions will be passed to app
49
+ return component.element(isEditing);
50
+ }
51
+ if (exportName && exportName !== this.DEFAULT_EXPORT_NAME) {
52
+ return component[exportName];
53
+ }
54
+ return (component.Default ||
55
+ component.default ||
56
+ component);
57
+ };
58
+ }
59
+ }
@@ -0,0 +1,42 @@
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
+ import { BYOCWrapper, fetchBYOCComponentServerProps, } from '@sitecore-jss/sitecore-jss-react';
11
+ import { constants } from '@sitecore-jss/sitecore-jss';
12
+ /**
13
+ * This is a repackaged version of the React BYOCWrapper component with support for
14
+ * server rendering in Next.js (using component-level data-fetching feature of JSS).
15
+ */
16
+ /**
17
+ * Will be called during SSG
18
+ * @param {ComponentRendering} rendering
19
+ * @returns {GetStaticPropsContext} context
20
+ */
21
+ export const getStaticProps = (rendering) => __awaiter(void 0, void 0, void 0, function* () {
22
+ if (process.env.JSS_MODE === constants.JSS_MODE.DISCONNECTED) {
23
+ return null;
24
+ }
25
+ const params = rendering.params || {};
26
+ const result = yield fetchBYOCComponentServerProps(params);
27
+ return result;
28
+ });
29
+ /**
30
+ * Will be called during SSR
31
+ * @param {ComponentRendering} rendering
32
+ * @returns {GetStaticPropsContext} context
33
+ */
34
+ export const getServerSideProps = (rendering) => __awaiter(void 0, void 0, void 0, function* () {
35
+ if (process.env.JSS_MODE === constants.JSS_MODE.DISCONNECTED) {
36
+ return null;
37
+ }
38
+ const params = rendering.params || {};
39
+ const result = yield fetchBYOCComponentServerProps(params);
40
+ return result;
41
+ });
42
+ export default BYOCWrapper;
@@ -0,0 +1,44 @@
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
+ import { FEaaSWrapper, fetchFEaaSComponentServerProps, } from '@sitecore-jss/sitecore-jss-react';
11
+ import { constants } from '@sitecore-jss/sitecore-jss';
12
+ /**
13
+ * This is a repackaged version of the React FEaaSWrapper component with support for
14
+ * server rendering in Next.js (using component-level data-fetching feature of JSS).
15
+ */
16
+ /**
17
+ * Will be called during SSG
18
+ * @param {ComponentRendering} rendering
19
+ * @param {LayoutServiceData} layoutData
20
+ * @returns {GetStaticPropsContext} context
21
+ */
22
+ export const getStaticProps = (rendering, layoutData) => __awaiter(void 0, void 0, void 0, function* () {
23
+ if (process.env.JSS_MODE === constants.JSS_MODE.DISCONNECTED) {
24
+ return null;
25
+ }
26
+ const params = rendering.params || {};
27
+ const result = yield fetchFEaaSComponentServerProps(params, layoutData.sitecore.context.pageState);
28
+ return result;
29
+ });
30
+ /**
31
+ * Will be called during SSR
32
+ * @param {ComponentRendering} rendering
33
+ * @param {LayoutServiceData} layoutData
34
+ * @returns {GetStaticPropsContext} context
35
+ */
36
+ export const getServerSideProps = (rendering, layoutData) => __awaiter(void 0, void 0, void 0, function* () {
37
+ if (process.env.JSS_MODE === constants.JSS_MODE.DISCONNECTED) {
38
+ return null;
39
+ }
40
+ const params = rendering.params || {};
41
+ const result = yield fetchFEaaSComponentServerProps(params, layoutData.sitecore.context.pageState);
42
+ return result;
43
+ });
44
+ export default FEaaSWrapper;
@@ -14,7 +14,11 @@ import PropTypes from 'prop-types';
14
14
  import NextLink from 'next/link';
15
15
  import { Link as ReactLink, LinkPropTypes, } from '@sitecore-jss/sitecore-jss-react';
16
16
  export const Link = forwardRef((props, ref) => {
17
- const { field, editable, children, internalLinkMatcher = /^\//g, showLinkTextWithChildrenPresent } = props, htmlLinkProps = __rest(props, ["field", "editable", "children", "internalLinkMatcher", "showLinkTextWithChildrenPresent"]);
17
+ const { field, editable = true, children, internalLinkMatcher = /^\//g, showLinkTextWithChildrenPresent } = props, htmlLinkProps = __rest(props, ["field", "editable", "children", "internalLinkMatcher", "showLinkTextWithChildrenPresent"]);
18
+ if (!field ||
19
+ (!field.editable && !field.value && !field.href)) {
20
+ return null;
21
+ }
18
22
  const value = (field.href
19
23
  ? field
20
24
  : field.value);
@@ -34,8 +38,5 @@ export const Link = forwardRef((props, ref) => {
34
38
  delete reactLinkProps.internalLinkMatcher;
35
39
  return React.createElement(ReactLink, Object.assign({}, reactLinkProps, { ref: ref }));
36
40
  });
37
- Link.defaultProps = {
38
- editable: true,
39
- };
40
41
  Link.displayName = 'NextLink';
41
42
  Link.propTypes = Object.assign({ internalLinkMatcher: PropTypes.instanceOf(RegExp) }, LinkPropTypes);
@@ -14,14 +14,8 @@ import PropTypes from 'prop-types';
14
14
  import React from 'react';
15
15
  import { getEEMarkup, } from '@sitecore-jss/sitecore-jss-react';
16
16
  import Image from 'next/image';
17
- export const sitecoreLoader = ({ src, width }) => {
18
- const [root, paramString] = src.split('?');
19
- const params = new URLSearchParams(paramString);
20
- params.set('mw', width.toString());
21
- return `${root}?${params}`;
22
- };
23
17
  export const NextImage = (_a) => {
24
- var { editable, imageParams, field, mediaUrlPrefix, fill, priority } = _a, otherProps = __rest(_a, ["editable", "imageParams", "field", "mediaUrlPrefix", "fill", "priority"]);
18
+ var { editable = true, imageParams, field, mediaUrlPrefix, fill, priority } = _a, otherProps = __rest(_a, ["editable", "imageParams", "field", "mediaUrlPrefix", "fill", "priority"]);
25
19
  // next handles src and we use a custom loader,
26
20
  // throw error if these are present
27
21
  if (otherProps.src) {
@@ -55,9 +49,8 @@ export const NextImage = (_a) => {
55
49
  delete imageProps.width;
56
50
  delete imageProps.height;
57
51
  }
58
- const loader = (otherProps.loader ? otherProps.loader : sitecoreLoader);
59
52
  if (attrs) {
60
- return React.createElement(Image, Object.assign({ alt: "", loader: loader }, imageProps));
53
+ return React.createElement(Image, Object.assign({ alt: "" }, imageProps));
61
54
  }
62
55
  return null; // we can't handle the truth
63
56
  };
@@ -75,7 +68,4 @@ NextImage.propTypes = {
75
68
  mediaUrlPrefix: PropTypes.instanceOf(RegExp),
76
69
  imageParams: PropTypes.objectOf(PropTypes.oneOfType([PropTypes.number.isRequired, PropTypes.string.isRequired]).isRequired),
77
70
  };
78
- NextImage.defaultProps = {
79
- editable: true,
80
- };
81
71
  NextImage.displayName = 'NextImage';
@@ -15,9 +15,9 @@ import { useRouter } from 'next/router';
15
15
  import { RichText as ReactRichText, RichTextPropTypes, } from '@sitecore-jss/sitecore-jss-react';
16
16
  const prefetched = {};
17
17
  export const RichText = (props) => {
18
- const { internalLinksSelector = 'a[href^="/"]' } = props, rest = __rest(props, ["internalLinksSelector"]);
18
+ const { internalLinksSelector = 'a[href^="/"]', prefetchLinks = true, editable = true } = props, rest = __rest(props, ["internalLinksSelector", "prefetchLinks", "editable"]);
19
19
  const hasText = props.field && props.field.value;
20
- const isEditing = props.editable && props.field && props.field.editable;
20
+ const isEditing = editable && props.field && props.field.editable;
21
21
  const router = useRouter();
22
22
  const richTextRef = useRef(null);
23
23
  useEffect(() => {
@@ -25,12 +25,12 @@ export const RichText = (props) => {
25
25
  if (hasText && !isEditing) {
26
26
  initializeLinks();
27
27
  }
28
- }, []);
28
+ }, [hasText]);
29
29
  const routeHandler = (ev) => {
30
- if (!ev.target)
30
+ if (!ev.currentTarget)
31
31
  return;
32
32
  ev.preventDefault();
33
- const pathname = ev.target.href;
33
+ const pathname = ev.currentTarget.href;
34
34
  router.push(pathname, pathname, { locale: false });
35
35
  };
36
36
  const initializeLinks = () => {
@@ -40,20 +40,16 @@ export const RichText = (props) => {
40
40
  if (!internalLinks || !internalLinks.length)
41
41
  return;
42
42
  internalLinks.forEach((link) => {
43
- if (link.target !== '_blank') {
44
- if (!prefetched[link.pathname]) {
45
- router.prefetch(link.pathname, undefined, { locale: false });
46
- prefetched[link.pathname] = true;
47
- }
48
- link.addEventListener('click', routeHandler, false);
43
+ if (link.target === '_blank')
44
+ return;
45
+ if (prefetchLinks && !prefetched[link.pathname]) {
46
+ router.prefetch(link.pathname, undefined, { locale: false });
47
+ prefetched[link.pathname] = true;
49
48
  }
49
+ link.addEventListener('click', routeHandler, false);
50
50
  });
51
51
  };
52
52
  return React.createElement(ReactRichText, Object.assign({ ref: richTextRef }, rest));
53
53
  };
54
54
  RichText.propTypes = Object.assign({ internalLinksSelector: PropTypes.string }, RichTextPropTypes);
55
- RichText.defaultProps = {
56
- tag: 'div',
57
- editable: true,
58
- };
59
55
  RichText.displayName = 'NextRichText';
@@ -0,0 +1,79 @@
1
+ import { LayoutServicePageState } from '@sitecore-jss/sitecore-jss-react';
2
+ /**
3
+ * Context instance that is used to initialize the application Context and associated Software Development Kits (SDKs).
4
+ */
5
+ export class Context {
6
+ constructor(props) {
7
+ this.props = props;
8
+ /**
9
+ * Indicates whether the Context and SDK(s) have been initialized
10
+ */
11
+ this.isInitialized = false;
12
+ /**
13
+ * Software Development Kits (SDKs) to be initialized
14
+ */
15
+ this.sdks = {};
16
+ /**
17
+ * Promises for the SDKs
18
+ */
19
+ this.sdkPromises = {};
20
+ this.sdkErrors = {};
21
+ /**
22
+ * Retrieves the Software Development Kit (SDK) instance, ensuring it is initialized before returning
23
+ *
24
+ * @param {string} name SDK name
25
+ * @returns initialized SDK
26
+ */
27
+ this.getSDK = (name) => {
28
+ if (!this.sdkPromises[name]) {
29
+ return Promise.reject(`Unknown SDK '${String(name)}'`);
30
+ }
31
+ else {
32
+ return this.sdkPromises[name].then((result) => {
33
+ return ((this.sdkErrors[name] && Promise.reject(this.sdkErrors[name])) || Promise.resolve(result));
34
+ });
35
+ }
36
+ };
37
+ this.sitecoreEdgeUrl = props.sitecoreEdgeUrl;
38
+ this.sitecoreEdgeContextId = props.sitecoreEdgeContextId;
39
+ this.siteName = props.siteName;
40
+ this.pageState = LayoutServicePageState.Normal;
41
+ }
42
+ init(props = {}) {
43
+ // Context and SDKs are initialized only once
44
+ if (this.isInitialized)
45
+ return;
46
+ this.isInitialized = true;
47
+ if (props.siteName) {
48
+ this.siteName = props.siteName;
49
+ }
50
+ if (props.pageState) {
51
+ this.pageState = props.pageState;
52
+ }
53
+ // iterate over the SDKs and initialize them
54
+ for (const sdkName of Object.keys(this.props.sdks)) {
55
+ this.initSDK(sdkName);
56
+ }
57
+ }
58
+ /**
59
+ * Initializes the Software Development Kit (SDK)
60
+ *
61
+ * @param {T} name SDK name
62
+ * @returns {void}
63
+ */
64
+ initSDK(name) {
65
+ this.sdkPromises[name] = new Promise((resolve) => {
66
+ this.props.sdks[name]
67
+ .init(this)
68
+ .then(() => {
69
+ this.sdks[name] = this.props.sdks[name].sdk;
70
+ resolve(this.sdks[name]);
71
+ })
72
+ .catch((e) => {
73
+ // if init rejects, we mark SDK as failed - so getSDK call would reject with a reason
74
+ this.sdkErrors[name] = e;
75
+ resolve(undefined);
76
+ });
77
+ });
78
+ }
79
+ }
@@ -0,0 +1 @@
1
+ export { Context } from './context';
@@ -0,0 +1,3 @@
1
+ export const QUERY_PARAM_EDITING_SECRET = 'secret';
2
+ export const QUERY_PARAM_PROTECTION_BYPASS_SITECORE = 'x-sitecore-protection-bypass';
3
+ export const QUERY_PARAM_PROTECTION_BYPASS_VERCEL = 'x-vercel-protection-bypass';
@@ -0,0 +1,45 @@
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
+ import { QUERY_PARAM_EDITING_SECRET } from './constants';
11
+ import { getJssEditingSecret } from '../utils/utils';
12
+ import { debug } from '@sitecore-jss/sitecore-jss';
13
+ /**
14
+ * Middleware / handler used in the editing config API route in xmcloud add on (e.g. '/api/editing/config')
15
+ * provides configuration information to determine feature compatibility on Pages side.
16
+ */
17
+ export class EditingConfigMiddleware {
18
+ /**
19
+ * @param {EditingConfigMiddlewareConfig} [config] Editing configuration middleware config
20
+ */
21
+ constructor(config) {
22
+ this.config = config;
23
+ this.handler = (_req, res) => __awaiter(this, void 0, void 0, function* () {
24
+ const secret = _req.query[QUERY_PARAM_EDITING_SECRET];
25
+ if (secret !== getJssEditingSecret()) {
26
+ debug.editing('invalid editing secret - sent "%s" expected "%s"', secret, getJssEditingSecret());
27
+ return res.status(401).json({ message: 'Missing or invalid editing secret' });
28
+ }
29
+ const components = Array.isArray(this.config.components)
30
+ ? this.config.components
31
+ : Array.from(this.config.components.keys());
32
+ return res.status(200).json({
33
+ components,
34
+ packages: this.config.metadata.packages,
35
+ });
36
+ });
37
+ }
38
+ /**
39
+ * Gets the Next.js API route handler
40
+ * @returns middleware handler
41
+ */
42
+ getHandler() {
43
+ return this.handler;
44
+ }
45
+ }
@@ -9,8 +9,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  import { editingDataDiskCache } from './editing-data-cache';
11
11
  import { isEditingData } from './editing-data';
12
- import { QUERY_PARAM_EDITING_SECRET } from './editing-data-service';
13
- import { getJssEditingSecret } from '../utils';
12
+ import { QUERY_PARAM_EDITING_SECRET } from './constants';
13
+ import { getJssEditingSecret } from '../utils/utils';
14
14
  /**
15
15
  * Middleware / handler for use in the editing data Next.js API dynamic route (e.g. '/api/editing/data/[key]')
16
16
  * which is required for Sitecore editing support.
@@ -7,10 +7,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
+ import { QUERY_PARAM_EDITING_SECRET } from './constants';
10
11
  import { AxiosDataFetcher, debug } from '@sitecore-jss/sitecore-jss';
11
12
  import { editingDataDiskCache } from './editing-data-cache';
12
- import { getJssEditingSecret } from '../utils';
13
- export const QUERY_PARAM_EDITING_SECRET = 'secret';
13
+ import { getJssEditingSecret } from '../utils/utils';
14
14
  /**
15
15
  * Unique key generator.
16
16
  * Need more than just the item GUID since requests are made "live" during editing in EE.
@@ -93,13 +93,14 @@ export class ServerlessEditingDataService {
93
93
  * @param {string} serverUrl The server url to use for subsequent data API requests
94
94
  * @returns {Promise} The {@link EditingPreviewData} containing the generated key and serverUrl to use for retrieval
95
95
  */
96
- setEditingData(data, serverUrl) {
96
+ setEditingData(data, serverUrl, params) {
97
97
  return __awaiter(this, void 0, void 0, function* () {
98
98
  const key = this.generateKey(data);
99
- const url = this.getUrl(serverUrl, key);
99
+ const url = this.getUrl(serverUrl, key, params);
100
100
  const previewData = {
101
101
  key,
102
102
  serverUrl,
103
+ params,
103
104
  };
104
105
  debug.editing('storing editing data for %o: %o', previewData, data);
105
106
  return this.dataFetcher.put(url, data).then(() => {
@@ -118,20 +119,27 @@ export class ServerlessEditingDataService {
118
119
  if (!(editingPreviewData === null || editingPreviewData === void 0 ? void 0 : editingPreviewData.serverUrl)) {
119
120
  return undefined;
120
121
  }
121
- const url = this.getUrl(editingPreviewData.serverUrl, editingPreviewData.key);
122
+ const url = this.getUrl(editingPreviewData.serverUrl, editingPreviewData.key, editingPreviewData.params);
122
123
  debug.editing('retrieving editing data for %o', previewData);
123
124
  return this.dataFetcher.get(url).then((response) => {
124
125
  return response.data;
125
126
  });
126
127
  });
127
128
  }
128
- getUrl(serverUrl, key) {
129
+ getUrl(serverUrl, key, params) {
129
130
  var _a;
130
131
  // Example URL format:
131
132
  // http://localhost:3000/api/editing/data/52961eea-bafd-5287-a532-a72e36bd8a36-qkb4e3fv5x?secret=1234secret
132
133
  const apiRoute = (_a = this.apiRoute) === null || _a === void 0 ? void 0 : _a.replace('[key]', key);
133
134
  const url = new URL(apiRoute, serverUrl);
134
135
  url.searchParams.append(QUERY_PARAM_EDITING_SECRET, getJssEditingSecret());
136
+ if (params) {
137
+ for (const key in params) {
138
+ if ({}.hasOwnProperty.call(params, key)) {
139
+ url.searchParams.append(key, params[key]);
140
+ }
141
+ }
142
+ }
135
143
  return url.toString();
136
144
  }
137
145
  }
@@ -11,21 +11,25 @@ import { STATIC_PROPS_ID, SERVER_PROPS_ID } from 'next/constants';
11
11
  import { AxiosDataFetcher, debug } from '@sitecore-jss/sitecore-jss';
12
12
  import { EDITING_COMPONENT_ID, RenderingType } from '@sitecore-jss/sitecore-jss/layout';
13
13
  import { parse } from 'node-html-parser';
14
- import { editingDataService, QUERY_PARAM_EDITING_SECRET, } from './editing-data-service';
15
- import { getJssEditingSecret } from '../utils';
14
+ import { editingDataService } from './editing-data-service';
15
+ import { QUERY_PARAM_EDITING_SECRET } from './constants';
16
+ import { getJssEditingSecret } from '../utils/utils';
17
+ import { RenderMiddlewareBase } from './render-middleware';
16
18
  /**
17
19
  * Middleware / handler for use in the editing render Next.js API route (e.g. '/api/editing/render')
18
20
  * which is required for Sitecore editing support.
19
21
  */
20
- export class EditingRenderMiddleware {
22
+ export class EditingRenderMiddleware extends RenderMiddlewareBase {
21
23
  /**
22
24
  * @param {EditingRenderMiddlewareConfig} [config] Editing render middleware config
23
25
  */
24
26
  constructor(config) {
25
27
  var _a, _b, _c, _d;
28
+ super();
26
29
  this.handler = (req, res) => __awaiter(this, void 0, void 0, function* () {
27
30
  var _e, _f;
28
31
  const { method, query, body, headers } = req;
32
+ const startTimestamp = Date.now();
29
33
  debug.editing('editing render middleware start: %o', {
30
34
  method,
31
35
  query,
@@ -52,21 +56,28 @@ export class EditingRenderMiddleware {
52
56
  const editingData = extractEditingData(req);
53
57
  // Resolve server URL
54
58
  const serverUrl = this.resolveServerUrl(req);
59
+ // Get query string parameters to propagate on subsequent requests (e.g. for deployment protection bypass)
60
+ const params = this.getQueryParamsForPropagation(query);
55
61
  // Stash for use later on (i.e. within getStatic/ServerSideProps).
56
62
  // Note we can't set this directly in setPreviewData since it's stored as a cookie (2KB limit)
57
63
  // https://nextjs.org/docs/advanced-features/preview-mode#previewdata-size-limits)
58
- const previewData = yield this.editingDataService.setEditingData(editingData, serverUrl);
64
+ const previewData = yield this.editingDataService.setEditingData(editingData, serverUrl, params);
59
65
  // Enable Next.js Preview Mode, passing our preview data (i.e. editingData cache key)
60
66
  res.setPreviewData(previewData);
61
67
  // Grab the Next.js preview cookies to send on to the render request
62
68
  const cookies = res.getHeader('Set-Cookie');
63
- // Make actual render request for page route, passing on preview cookies.
69
+ // Make actual render request for page route, passing on preview cookies as well as any approved query string parameters.
64
70
  // Note timestamp effectively disables caching the request in Axios (no amount of cache headers seemed to do it)
65
- const requestUrl = this.resolvePageUrl(serverUrl, editingData.path);
66
71
  debug.editing('fetching page route for %s', editingData.path);
67
- const queryStringCharacter = requestUrl.indexOf('?') === -1 ? '?' : '&';
72
+ const requestUrl = new URL(this.resolvePageUrl(serverUrl, editingData.path));
73
+ for (const key in params) {
74
+ if ({}.hasOwnProperty.call(params, key)) {
75
+ requestUrl.searchParams.append(key, params[key]);
76
+ }
77
+ }
78
+ requestUrl.searchParams.append('timestamp', Date.now().toString());
68
79
  const pageRes = yield this.dataFetcher
69
- .get(`${requestUrl}${queryStringCharacter}timestamp=${Date.now()}`, {
80
+ .get(requestUrl.toString(), {
70
81
  headers: {
71
82
  Cookie: cookies.join(';'),
72
83
  },
@@ -81,7 +92,7 @@ export class EditingRenderMiddleware {
81
92
  });
82
93
  let html = pageRes.data;
83
94
  if (!html || html.length === 0) {
84
- throw new Error(`Failed to render html for ${requestUrl}`);
95
+ throw new Error(`Failed to render html for ${editingData.path}`);
85
96
  }
86
97
  // replace phkey attribute with key attribute so that newly added renderings
87
98
  // show correct placeholders, so save and refresh won't be needed after adding each rendering
@@ -97,11 +108,14 @@ export class EditingRenderMiddleware {
97
108
  // Handle component rendering. Extract component markup only
98
109
  html = (_f = parse(html).getElementById(EDITING_COMPONENT_ID)) === null || _f === void 0 ? void 0 : _f.innerHTML;
99
110
  if (!html)
100
- throw new Error(`Failed to render component for ${requestUrl}`);
111
+ throw new Error(`Failed to render component for ${editingData.path}`);
101
112
  }
102
113
  const body = { html };
103
114
  // Return expected JSON result
104
- debug.editing('editing render middleware end: %o', { status: 200, body });
115
+ debug.editing('editing render middleware end in %dms: %o', Date.now() - startTimestamp, {
116
+ status: 200,
117
+ body,
118
+ });
105
119
  res.status(200).json(body);
106
120
  }
107
121
  catch (err) {