@sitecore-content-sdk/nextjs 0.1.0-beta.9 → 0.1.0-canary.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 (99) hide show
  1. package/README.md +5 -4
  2. package/client.d.ts +1 -0
  3. package/client.js +1 -0
  4. package/component-props-loader.d.ts +1 -0
  5. package/component-props-loader.js +3 -0
  6. package/dist/cjs/client/index.js +10 -0
  7. package/dist/cjs/client/sitecore-nextjs-client.js +117 -0
  8. package/dist/cjs/components/RichText.js +16 -4
  9. package/dist/cjs/config/define-cli-config.js +30 -0
  10. package/dist/cjs/config/index.js +3 -1
  11. package/dist/cjs/editing/editing-config-middleware.js +1 -3
  12. package/dist/cjs/editing/editing-render-middleware.js +13 -9
  13. package/dist/cjs/editing/index.js +2 -2
  14. package/dist/cjs/index.js +16 -18
  15. package/dist/cjs/middleware/index.js +3 -1
  16. package/dist/cjs/middleware/middleware.js +23 -12
  17. package/dist/cjs/middleware/multisite-middleware.js +19 -8
  18. package/dist/cjs/middleware/personalize-middleware.js +3 -3
  19. package/dist/cjs/middleware/redirects-middleware.js +28 -13
  20. package/dist/cjs/middleware/sitemap-middleware.js +47 -0
  21. package/dist/cjs/services/component-props-service.js +41 -50
  22. package/dist/cjs/tools/component-props.loader.js +101 -0
  23. package/dist/cjs/tools/index.js +9 -0
  24. package/dist/cjs/tools/templating/byoc-component.js +75 -0
  25. package/dist/cjs/tools/templating/constants.js +7 -0
  26. package/dist/cjs/tools/templating/default-component.js +54 -0
  27. package/dist/cjs/tools/templating/utils.js +18 -0
  28. package/dist/cjs/utils/index.js +2 -1
  29. package/dist/cjs/utils/utils.js +10 -1
  30. package/dist/esm/client/index.js +2 -0
  31. package/dist/esm/client/sitecore-nextjs-client.js +113 -0
  32. package/dist/esm/components/RichText.js +14 -2
  33. package/dist/esm/config/define-cli-config.js +26 -0
  34. package/dist/esm/config/index.js +1 -0
  35. package/dist/esm/editing/editing-config-middleware.js +1 -3
  36. package/dist/esm/editing/editing-render-middleware.js +11 -7
  37. package/dist/esm/editing/index.js +1 -1
  38. package/dist/esm/index.js +3 -5
  39. package/dist/esm/middleware/index.js +1 -0
  40. package/dist/esm/middleware/middleware.js +23 -12
  41. package/dist/esm/middleware/multisite-middleware.js +20 -9
  42. package/dist/esm/middleware/personalize-middleware.js +4 -4
  43. package/dist/esm/middleware/redirects-middleware.js +29 -14
  44. package/dist/esm/middleware/sitemap-middleware.js +43 -0
  45. package/dist/esm/services/component-props-service.js +41 -50
  46. package/dist/esm/tools/component-props.loader.js +65 -0
  47. package/dist/esm/tools/index.js +1 -0
  48. package/dist/esm/tools/templating/byoc-component.js +69 -0
  49. package/dist/esm/tools/templating/constants.js +4 -0
  50. package/dist/esm/tools/templating/default-component.js +48 -0
  51. package/dist/esm/tools/templating/utils.js +12 -0
  52. package/dist/esm/utils/index.js +1 -1
  53. package/dist/esm/utils/utils.js +8 -0
  54. package/package.json +16 -13
  55. package/tools.d.ts +1 -0
  56. package/tools.js +1 -0
  57. package/types/client/index.d.ts +2 -0
  58. package/types/client/sitecore-nextjs-client.d.ts +44 -0
  59. package/types/components/RichText.d.ts +7 -1
  60. package/types/config/define-cli-config.d.ts +8 -0
  61. package/types/config/index.d.ts +1 -0
  62. package/types/editing/editing-config-middleware.d.ts +4 -2
  63. package/types/editing/editing-render-middleware.d.ts +3 -31
  64. package/types/editing/index.d.ts +1 -1
  65. package/types/index.d.ts +6 -8
  66. package/types/middleware/index.d.ts +1 -0
  67. package/types/middleware/middleware.d.ts +13 -7
  68. package/types/middleware/sitemap-middleware.d.ts +12 -0
  69. package/types/services/component-props-service.d.ts +10 -26
  70. package/types/sharedTypes/component-props.d.ts +18 -0
  71. package/types/sharedTypes/sitecore-page-props.d.ts +5 -0
  72. package/types/tools/component-props.loader.d.ts +7 -0
  73. package/types/tools/index.d.ts +1 -0
  74. package/types/tools/templating/byoc-component.d.ts +2 -0
  75. package/types/tools/templating/constants.d.ts +4 -0
  76. package/types/tools/templating/default-component.d.ts +2 -0
  77. package/types/tools/templating/utils.d.ts +6 -0
  78. package/types/utils/index.d.ts +1 -1
  79. package/types/utils/utils.d.ts +2 -0
  80. package/dist/cjs/ComponentBuilder.js +0 -63
  81. package/dist/cjs/graphql/index.js +0 -7
  82. package/dist/cjs/services/base-graphql-sitemap-service.js +0 -206
  83. package/dist/cjs/services/graphql-sitemap-service.js +0 -64
  84. package/dist/cjs/services/mutisite-graphql-sitemap-service.js +0 -81
  85. package/dist/esm/ComponentBuilder.js +0 -59
  86. package/dist/esm/graphql/index.js +0 -1
  87. package/dist/esm/services/base-graphql-sitemap-service.js +0 -201
  88. package/dist/esm/services/graphql-sitemap-service.js +0 -59
  89. package/dist/esm/services/mutisite-graphql-sitemap-service.js +0 -77
  90. package/graphql.d.ts +0 -1
  91. package/graphql.js +0 -1
  92. package/types/ComponentBuilder.d.ts +0 -59
  93. package/types/graphql/index.d.ts +0 -1
  94. package/types/services/base-graphql-sitemap-service.d.ts +0 -148
  95. package/types/services/graphql-sitemap-service.d.ts +0 -51
  96. package/types/services/mutisite-graphql-sitemap-service.d.ts +0 -42
  97. package/types/sharedTypes/module-factory.d.ts +0 -32
  98. /package/dist/cjs/sharedTypes/{module-factory.js → sitecore-page-props.js} +0 -0
  99. /package/dist/esm/sharedTypes/{module-factory.js → sitecore-page-props.js} +0 -0
@@ -1,17 +1,23 @@
1
1
  import { SiteInfo, SiteResolver } from '@sitecore-content-sdk/core/site';
2
2
  import { NextRequest, NextFetchEvent, NextResponse } from 'next/server';
3
+ export declare const REWRITE_HEADER_NAME = "x-sc-rewrite";
3
4
  export type MiddlewareBaseConfig = {
4
5
  /**
5
- * function, determines if middleware should be turned off, based on cookie, header, or other considerations
6
+ * function, determines if middleware execution should be skipped, based on cookie, header, or other considerations
6
7
  * @param {NextRequest} req request object from middleware handler
7
8
  * @param {NextResponse} res response object from middleware handler
8
9
  */
9
- disabled?: (req: NextRequest, res: NextResponse) => boolean;
10
+ skip?: (req: NextRequest, res: NextResponse) => boolean;
10
11
  /**
11
12
  * Fallback hostname in case `host` header is not present
12
13
  * @default localhost
13
14
  */
14
15
  defaultHostname?: string;
16
+ /**
17
+ * Fallback language in locale cannot be extracted from request URL
18
+ * @default 'en'
19
+ */
20
+ defaultLanguage?: string;
15
21
  /**
16
22
  * Site resolution implementation by name/hostname
17
23
  */
@@ -34,8 +40,6 @@ export declare abstract class Middleware {
34
40
  */
35
41
  export declare abstract class MiddlewareBase extends Middleware {
36
42
  protected config: MiddlewareBaseConfig;
37
- protected SITE_SYMBOL: string;
38
- protected REWRITE_HEADER_NAME: string;
39
43
  protected defaultHostname: string;
40
44
  protected siteResolver: SiteResolver;
41
45
  constructor(config: MiddlewareBaseConfig);
@@ -73,8 +77,9 @@ export declare abstract class MiddlewareBase extends Middleware {
73
77
  */
74
78
  protected getHostHeader(req: NextRequest): string | undefined;
75
79
  /**
76
- * Get site information.
77
- * Can not be used in **Preview** mode, since site will not be resolved
80
+ * Get site information. If site name is stored in cookie, use it, otherwise resolve by hostname
81
+ * - If site can't be resolved by site name cookie use default site info based on provided parameters
82
+ * - If site can't be resolved by hostname throw an error
78
83
  * @param {NextRequest} req request
79
84
  * @param {NextResponse} [res] response
80
85
  * @returns {SiteInfo} site information
@@ -85,8 +90,9 @@ export declare abstract class MiddlewareBase extends Middleware {
85
90
  * @param {string} rewritePath the destionation path
86
91
  * @param {NextRequest} req the current request
87
92
  * @param {NextResponse} res the current response
93
+ * @param {boolean} [skipHeader] don't write 'x-sc-rewrite' header
88
94
  */
89
- protected rewrite(rewritePath: string, req: NextRequest, res: NextResponse): NextResponse;
95
+ protected rewrite(rewritePath: string, req: NextRequest, res: NextResponse, skipHeader?: boolean): NextResponse;
90
96
  }
91
97
  /**
92
98
  * Define a middleware with a list of middlewares
@@ -0,0 +1,12 @@
1
+ import { NextApiRequest, NextApiResponse } from 'next';
2
+ import { SitecoreClient } from '@sitecore-content-sdk/core/client';
3
+ /**
4
+ * Middleware for handling sitemap requests in a Next.js application.
5
+ * Encapsulates all HTTP-related logic for sitemap generation and delivery.
6
+ */
7
+ export declare class SitemapMiddleware {
8
+ private client;
9
+ constructor(client: SitecoreClient);
10
+ getHandler(): (req: NextApiRequest, res: NextApiResponse) => Promise<void>;
11
+ private handler;
12
+ }
@@ -1,11 +1,11 @@
1
1
  import { GetServerSidePropsContext, GetStaticPropsContext } from 'next';
2
2
  import { LayoutServiceData, ComponentRendering, PlaceholdersData } from '@sitecore-content-sdk/core/layout';
3
- import { ComponentPropsCollection, ComponentPropsFetchFunction } from '../sharedTypes/component-props';
4
- import { ModuleFactory } from '../sharedTypes/module-factory';
3
+ import { ComponentPropsCollection, ComponentPropsFetchFunction, NextjsJssComponent } from '../sharedTypes/component-props';
4
+ import { ComponentMap } from '@sitecore-content-sdk/react';
5
5
  export type FetchComponentPropsArguments<NextContext> = {
6
6
  layoutData: LayoutServiceData;
7
7
  context: NextContext;
8
- moduleFactory: ModuleFactory;
8
+ components: ComponentMap<NextjsJssComponent>;
9
9
  };
10
10
  export type ComponentPropsRequest<NextContext> = {
11
11
  fetch: ComponentPropsFetchFunction<NextContext>;
@@ -15,29 +15,7 @@ export type ComponentPropsRequest<NextContext> = {
15
15
  };
16
16
  type FetchFunctionFactory<NextContext> = (componentName: string) => Promise<ComponentPropsFetchFunction<NextContext> | undefined>;
17
17
  export declare class ComponentPropsService {
18
- /**
19
- * SSR mode
20
- * Fetch component props using getServerSideProps function
21
- * @param {FetchComponentPropsArguments<GetServerSidePropsContext>} params fetch params
22
- * @returns {Promise<ComponentPropsCollection>} props
23
- */
24
- fetchServerSideComponentProps(params: FetchComponentPropsArguments<GetServerSidePropsContext>): Promise<ComponentPropsCollection>;
25
- /**
26
- * SSG mode
27
- * Fetch component props using getStaticProps function
28
- * @param {FetchComponentPropsArguments<GetStaticPropsContext>} params fetch arguments
29
- * @returns {Promise<ComponentPropsCollection>} props
30
- */
31
- fetchStaticComponentProps(params: FetchComponentPropsArguments<GetStaticPropsContext>): Promise<ComponentPropsCollection>;
32
- /**
33
- * Traverse Layout Service data tree and call side effects on component level.
34
- * Side effect function can be: getStaticProps (SSG) or getServerSideProps (SSR)
35
- * @param {FetchFunctionFactory<NextContext>} fetchFunctionFactory fetch function factory
36
- * @param {LayoutServiceData} layoutData layout data
37
- * @param {NextContext} context next context
38
- * @returns {Promise<ComponentPropsCollection>} component props
39
- */
40
- protected fetchComponentProps<NextContext>(fetchFunctionFactory: FetchFunctionFactory<NextContext>, layoutData: LayoutServiceData, context: NextContext): Promise<ComponentPropsCollection>;
18
+ fetchComponentProps(params: FetchComponentPropsArguments<GetServerSidePropsContext | GetStaticPropsContext>): Promise<ComponentPropsCollection>;
41
19
  /**
42
20
  * Go through layout service data, check all renderings using displayName, which should make some side effects.
43
21
  * Write result in requests variable
@@ -77,5 +55,11 @@ export declare class ComponentPropsService {
77
55
  * @returns {ComponentRendering[]} renderings
78
56
  */
79
57
  protected flatRenderings(placeholders: PlaceholdersData): ComponentRendering[];
58
+ /**
59
+ * Determines whether context is GetServerSidePropsContext (SSR) or GetStaticPropsContext (SSG)
60
+ * @param {GetServerSidePropsContext | GetStaticPropsContext} context
61
+ */
62
+ private isServerSidePropsContext;
63
+ private getModule;
80
64
  }
81
65
  export {};
@@ -1,5 +1,6 @@
1
1
  import { GetServerSidePropsContext, GetStaticPropsContext } from 'next';
2
2
  import { ComponentRendering, LayoutServiceData } from '@sitecore-content-sdk/core/layout';
3
+ import { ReactJssComponent } from '@sitecore-content-sdk/react';
3
4
  export type ComponentPropsError = {
4
5
  error: string;
5
6
  componentName: string;
@@ -24,3 +25,20 @@ export type GetServerSideComponentProps = ComponentPropsFetchFunction<GetServerS
24
25
  * Shape of getStaticProps function on component level
25
26
  */
26
27
  export type GetStaticComponentProps = ComponentPropsFetchFunction<GetStaticPropsContext>;
28
+ /**
29
+ * Represents a nextjs component import
30
+ */
31
+ export type NextjsJssComponent = ReactJssComponent & {
32
+ /**
33
+ * function for component level data fetching in SSR mode
34
+ */
35
+ getServerSideProps?: GetServerSideComponentProps;
36
+ /**
37
+ * function for component level data fetching in SSG mode
38
+ */
39
+ getStaticProps?: GetStaticComponentProps;
40
+ /**
41
+ * Optional dynamic import for lazy components - allows component props retrieval
42
+ */
43
+ dynamicModule?: () => Promise<ReactJssComponent>;
44
+ };
@@ -0,0 +1,5 @@
1
+ import { DictionaryPhrases } from '@sitecore-content-sdk/core/i18n';
2
+ import { NextjsPage } from '../client';
3
+ export type SitecorePageProps = NextjsPage & {
4
+ dictionary: DictionaryPhrases;
5
+ };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Webpack loader to strip functions from the source code
3
+ * Strips the `getServerSideProps` and `getStaticProps` functions from the source code
4
+ * @param {string} source file source code
5
+ * @returns {string} output file source code with stripped functions
6
+ */
7
+ export default function componentPropsLoader(source: string): string;
@@ -0,0 +1 @@
1
+ export { generateSites, GenerateSitesConfig, generateMetadata, ComponentFile, PackageDefinition, getComponentList, PluginDefinition, generatePlugins, ModuleType, } from '@sitecore-content-sdk/core/tools';
@@ -0,0 +1,2 @@
1
+ import { ScaffoldTemplate } from '@sitecore-content-sdk/core/config';
2
+ export declare const byocTemplate: ScaffoldTemplate;
@@ -0,0 +1,4 @@
1
+ /**
2
+ * The file extension for nextjs components
3
+ */
4
+ export declare const COMPONENT_FILE_EXTENSION = "tsx";
@@ -0,0 +1,2 @@
1
+ import { ScaffoldTemplate } from '@sitecore-content-sdk/core/config';
2
+ export declare const defaultTemplate: ScaffoldTemplate;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Run watch mode, watching on @var paths
3
+ * @param {string[]} paths paths to watch by chokidar
4
+ * @param {Function<void>} cb callback to run on file change
5
+ */
6
+ export declare function watchItems(paths: string[], cb: () => void): void;
@@ -1,3 +1,3 @@
1
- export { handleEditorFastRefresh } from './utils';
1
+ export { handleEditorFastRefresh, extractPath } from './utils';
2
2
  export { tryParseEnvValue, resolveUrl } from '@sitecore-content-sdk/core/utils';
3
3
  export { isEditorActive, resetEditorChromes } from '@sitecore-content-sdk/core/editing';
@@ -1,3 +1,4 @@
1
+ import { GetServerSidePropsContext, GetStaticPropsContext } from 'next';
1
2
  /**
2
3
  * Since Sitecore editors do not support Fast Refresh:
3
4
  * 1. Subscribe on events provided by webpack.
@@ -6,3 +7,4 @@
6
7
  */
7
8
  export declare const handleEditorFastRefresh: (forceReload?: boolean) => void;
8
9
  export declare const getJssEditingSecret: () => string;
10
+ export declare const extractPath: (context: GetStaticPropsContext | GetServerSidePropsContext) => string;
@@ -1,63 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ComponentBuilder = void 0;
4
- /**
5
- * Nextjs implementation of component builder class for building components based on the configuration.
6
- */
7
- class ComponentBuilder {
8
- constructor(config) {
9
- this.config = config;
10
- /**
11
- * SXA uses custom default export name
12
- */
13
- this.DEFAULT_EXPORT_NAME = 'Default';
14
- this.components = new Map([...config.components]);
15
- }
16
- /**
17
- * Creates a new instance of module factory
18
- * Module factory provides a module (file) including all exports.
19
- * Module can be imported dynamically or statically.
20
- * @returns {ModuleFactory} Module factory implementation
21
- */
22
- getModuleFactory() {
23
- return (componentName) => {
24
- const component = this.components.get(componentName);
25
- if (!component)
26
- return null;
27
- // check if module should be imported dynamically
28
- if (component.module) {
29
- return component.module();
30
- }
31
- return component;
32
- };
33
- }
34
- /**
35
- * Creates a new instance of component factory
36
- * Component can be imported dynamically or statically.
37
- * @param {object} [config] Component factory configuration
38
- * @param {boolean} [config.isEditing] Indicates if component factory is used in editing mode
39
- * @returns {ComponentFactory} Component factory implementation
40
- */
41
- getComponentFactory({ isEditing } = {}) {
42
- return (componentName, exportName) => {
43
- const component = this.components.get(componentName);
44
- if (!component)
45
- return null;
46
- // check if component should be imported dynamically
47
- if (component.element) {
48
- // Editing mode doesn't work well with dynamic components in nextjs: dynamic components are not displayed without refresh after a rendering is added.
49
- // 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
50
- // So we use require() to obtain dynamic components in editing mode while preserving dynamic logic for non-editing scenarios
51
- // 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
52
- return component.element(isEditing);
53
- }
54
- if (exportName && exportName !== this.DEFAULT_EXPORT_NAME) {
55
- return component[exportName];
56
- }
57
- return (component.Default ||
58
- component.default ||
59
- component);
60
- };
61
- }
62
- }
63
- exports.ComponentBuilder = ComponentBuilder;
@@ -1,7 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getEdgeProxyContentUrl = exports.GraphQLRequestClient = exports.DefaultRetryStrategy = void 0;
4
- var graphql_1 = require("@sitecore-content-sdk/core/graphql");
5
- Object.defineProperty(exports, "DefaultRetryStrategy", { enumerable: true, get: function () { return graphql_1.DefaultRetryStrategy; } });
6
- Object.defineProperty(exports, "GraphQLRequestClient", { enumerable: true, get: function () { return graphql_1.GraphQLRequestClient; } });
7
- Object.defineProperty(exports, "getEdgeProxyContentUrl", { enumerable: true, get: function () { return graphql_1.getEdgeProxyContentUrl; } });
@@ -1,206 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.BaseGraphQLSitemapService = exports.siteError = exports.languageError = void 0;
13
- exports.getSiteEmptyError = getSiteEmptyError;
14
- const core_1 = require("@sitecore-content-sdk/core");
15
- const personalize_1 = require("@sitecore-content-sdk/core/personalize");
16
- /** @private */
17
- exports.languageError = 'The list of languages cannot be empty';
18
- exports.siteError = 'The service needs a site name';
19
- /**
20
- * @param {string} siteName to inject into error text
21
- * @private
22
- */
23
- function getSiteEmptyError(siteName) {
24
- return `Site "${siteName}" does not exist or site item tree is missing`;
25
- }
26
- const languageEmptyError = 'The language must be a non-empty string';
27
- /**
28
- * GQL query made dynamic based whether personalization is enabled or not
29
- * @param {boolean} usesPersonalize flag to detrmine which variation of a query to run
30
- * @returns GraphQL query to fetch site paths with
31
- */
32
- const defaultQuery = (usesPersonalize) => /* GraphQL */ `
33
- query ${usesPersonalize ? 'PersonalizeSitemapQuery' : 'DefaultSitemapQuery'}(
34
- $siteName: String!
35
- $language: String!
36
- $includedPaths: [String]
37
- $excludedPaths: [String]
38
- $pageSize: Int = 100
39
- $after: String
40
- ) {
41
- site {
42
- siteInfo(site: $siteName) {
43
- routes(
44
- language: $language
45
- includedPaths: $includedPaths
46
- excludedPaths: $excludedPaths
47
- first: $pageSize
48
- after: $after
49
- ){
50
- total
51
- pageInfo {
52
- endCursor
53
- hasNext
54
- }
55
- results {
56
- path: routePath
57
- ${usesPersonalize
58
- ? `
59
- route {
60
- personalization {
61
- variantIds
62
- }
63
- }`
64
- : ''}
65
- }
66
- }
67
- }
68
- }
69
- }
70
- `;
71
- /**
72
- * Service that fetches the list of site pages using Sitecore's GraphQL API.
73
- * Used to handle a single site
74
- * This list is used for SSG and Export functionality.
75
- * @mixes SearchQueryService<PageListQueryResult>
76
- */
77
- class BaseGraphQLSitemapService {
78
- /**
79
- * Creates an instance of graphQL sitemap service with the provided options
80
- * @param {GraphQLSitemapServiceConfig} options instance
81
- */
82
- constructor(options) {
83
- this.options = options;
84
- this._graphQLClient = this.getGraphQLClient();
85
- }
86
- /**
87
- * GraphQL client accessible by descendant classes when needed
88
- */
89
- get graphQLClient() {
90
- return this._graphQLClient;
91
- }
92
- /**
93
- * Gets the default query used for fetching the list of site pages
94
- */
95
- get query() {
96
- return defaultQuery(this.options.includePersonalizedRoutes);
97
- }
98
- /**
99
- * Fetch sitemap which could be used for generation of static pages during `next export`.
100
- * The `locale` parameter will be used in the item query, but since i18n is not supported,
101
- * the output paths will not include a `language` property.
102
- * @param {string} locale which application supports
103
- * @returns an array of @see StaticPath objects
104
- */
105
- fetchExportSitemap(locale) {
106
- return __awaiter(this, void 0, void 0, function* () {
107
- const formatPath = (path) => ({
108
- params: {
109
- path,
110
- },
111
- });
112
- return this.fetchSitemap([locale], formatPath);
113
- });
114
- }
115
- /**
116
- * Fetch sitemap which could be used for generation of static pages using SSG mode
117
- * @param {string[]} locales locales which application supports
118
- * @returns an array of @see StaticPath objects
119
- */
120
- fetchSSGSitemap(locales) {
121
- return __awaiter(this, void 0, void 0, function* () {
122
- const formatPath = (path, locale) => ({
123
- params: {
124
- path,
125
- },
126
- locale,
127
- });
128
- return this.fetchSitemap(locales, formatPath);
129
- });
130
- }
131
- getTranformedPaths(siteName, languages, formatStaticPath) {
132
- return __awaiter(this, void 0, void 0, function* () {
133
- const paths = new Array();
134
- for (const language of languages) {
135
- if (language === '') {
136
- throw new RangeError(languageEmptyError);
137
- }
138
- core_1.debug.sitemap('fetching sitemap data for %s %s', language, siteName);
139
- const results = yield this.fetchLanguageSitePaths(language, siteName);
140
- const transformedPaths = yield this.transformLanguageSitePaths(results, formatStaticPath, language);
141
- paths.push(...transformedPaths);
142
- }
143
- return paths;
144
- });
145
- }
146
- transformLanguageSitePaths(sitePaths, formatStaticPath, language) {
147
- return __awaiter(this, void 0, void 0, function* () {
148
- const formatPath = (path) => formatStaticPath(path.replace(/^\/|\/$/g, '').split('/'), language);
149
- const aggregatedPaths = [];
150
- sitePaths.forEach((item) => {
151
- var _a, _b, _c;
152
- if (!item)
153
- return;
154
- aggregatedPaths.push(formatPath(item.path));
155
- const variantIds = (_c = (_b = (_a = item.route) === null || _a === void 0 ? void 0 : _a.personalization) === null || _b === void 0 ? void 0 : _b.variantIds) === null || _c === void 0 ? void 0 : _c.filter((variantId) => !variantId.includes('_') // exclude component A/B test variants
156
- );
157
- if (variantIds === null || variantIds === void 0 ? void 0 : variantIds.length) {
158
- aggregatedPaths.push(...variantIds.map((varId) => formatPath((0, personalize_1.getPersonalizedRewrite)(item.path, [varId]))));
159
- }
160
- });
161
- return aggregatedPaths;
162
- });
163
- }
164
- fetchLanguageSitePaths(language, siteName) {
165
- return __awaiter(this, void 0, void 0, function* () {
166
- var _a, _b, _c, _d;
167
- const args = {
168
- siteName: siteName,
169
- language: language,
170
- pageSize: this.options.pageSize,
171
- includedPaths: this.options.includedPaths,
172
- excludedPaths: this.options.excludedPaths,
173
- };
174
- let results = [];
175
- let hasNext = true;
176
- let after = '';
177
- while (hasNext) {
178
- const fetchResponse = yield this.graphQLClient.request(this.query, Object.assign(Object.assign({}, args), { after }));
179
- if (!((_a = fetchResponse === null || fetchResponse === void 0 ? void 0 : fetchResponse.site) === null || _a === void 0 ? void 0 : _a.siteInfo)) {
180
- throw new RangeError(getSiteEmptyError(siteName));
181
- }
182
- else {
183
- results = results.concat((_b = fetchResponse.site.siteInfo.routes) === null || _b === void 0 ? void 0 : _b.results);
184
- hasNext = (_c = fetchResponse.site.siteInfo.routes) === null || _c === void 0 ? void 0 : _c.pageInfo.hasNext;
185
- after = (_d = fetchResponse.site.siteInfo.routes) === null || _d === void 0 ? void 0 : _d.pageInfo.endCursor;
186
- }
187
- }
188
- return results;
189
- });
190
- }
191
- /**
192
- * Gets a GraphQL client that can make requests to the API. Uses graphql-request as the default
193
- * library for fetching graphql data (@see GraphQLRequestClient). Override this method if you
194
- * want to use something else.
195
- * @returns {GraphQLClient} implementation
196
- */
197
- getGraphQLClient() {
198
- if (!this.options.clientFactory) {
199
- throw new Error('clientFactory needs to be provided when initializing GraphQL client.');
200
- }
201
- return this.options.clientFactory({
202
- debugger: core_1.debug.sitemap,
203
- });
204
- }
205
- }
206
- exports.BaseGraphQLSitemapService = BaseGraphQLSitemapService;
@@ -1,64 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.GraphQLSitemapService = exports.siteError = exports.languageError = void 0;
13
- exports.getSiteEmptyError = getSiteEmptyError;
14
- const base_graphql_sitemap_service_1 = require("./base-graphql-sitemap-service");
15
- /** @private */
16
- exports.languageError = 'The list of languages cannot be empty';
17
- exports.siteError = 'The service needs a site name';
18
- /**
19
- * @param {string} siteName to inject into error text
20
- * @private
21
- */
22
- function getSiteEmptyError(siteName) {
23
- return `Site "${siteName}" does not exist or site item tree is missing`;
24
- }
25
- /**
26
- * Service that fetches the list of site pages using Sitecore's GraphQL API.
27
- * Used to handle a single site
28
- * This list is used for SSG and Export functionality.
29
- * @mixes SearchQueryService<PageListQueryResult>
30
- */
31
- class GraphQLSitemapService extends base_graphql_sitemap_service_1.BaseGraphQLSitemapService {
32
- /**
33
- * Creates an instance of graphQL sitemap service with the provided options
34
- * @param {GraphQLSitemapServiceConfig} options instance
35
- */
36
- constructor(options) {
37
- super(options);
38
- this.options = options;
39
- }
40
- /**
41
- * Fetch a flat list of all pages that belong to the specificed site and have a
42
- * version in the specified language(s).
43
- * @param {string[]} languages Fetch pages that have versions in this language(s).
44
- * @param {Function} formatStaticPath Function for transforming the raw search results into (@see StaticPath) types.
45
- * @returns list of pages
46
- * @throws {RangeError} if the list of languages is empty.
47
- * @throws {RangeError} if the any of the languages is an empty string.
48
- */
49
- fetchSitemap(languages, formatStaticPath) {
50
- return __awaiter(this, void 0, void 0, function* () {
51
- const paths = new Array();
52
- if (!languages.length) {
53
- throw new RangeError(exports.languageError);
54
- }
55
- const siteName = this.options.siteName;
56
- if (!siteName) {
57
- throw new RangeError(exports.siteError);
58
- }
59
- paths.push(...(yield this.getTranformedPaths(siteName, languages, formatStaticPath)));
60
- return [].concat(...paths);
61
- });
62
- }
63
- }
64
- exports.GraphQLSitemapService = GraphQLSitemapService;
@@ -1,81 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.MultisiteGraphQLSitemapService = exports.sitesError = void 0;
13
- const site_1 = require("@sitecore-content-sdk/core/site");
14
- const base_graphql_sitemap_service_1 = require("./base-graphql-sitemap-service");
15
- exports.sitesError = 'The list of sites cannot be empty';
16
- /**
17
- * Service that fetches the list of site pages using Sitecore's GraphQL API.
18
- * Used to handle multiple sites
19
- * This list is used for SSG and Export functionality.
20
- * @mixes SearchQueryService<PageListQueryResult>
21
- */
22
- class MultisiteGraphQLSitemapService extends base_graphql_sitemap_service_1.BaseGraphQLSitemapService {
23
- /**
24
- * Creates an instance of graphQL sitemap service with the provided options
25
- * @param {MultisiteGraphQLSitemapServiceConfig} options instance
26
- */
27
- constructor(options) {
28
- super(options);
29
- this.options = options;
30
- }
31
- /**
32
- * Fetch a flat list of all pages that belong to all the requested sites and have a
33
- * version in the specified language(s).
34
- * @param {string[]} languages Fetch pages that have versions in this language(s).
35
- * @param {Function} formatStaticPath Function for transforming the raw search results into (@see StaticPath) types.
36
- * @returns list of pages
37
- * @throws {RangeError} if the list of languages is empty.
38
- * @throws {RangeError} if the any of the languages is an empty string.
39
- */
40
- fetchSitemap(languages, formatStaticPath) {
41
- return __awaiter(this, void 0, void 0, function* () {
42
- const paths = new Array();
43
- if (!languages.length) {
44
- throw new RangeError(base_graphql_sitemap_service_1.languageError);
45
- }
46
- // Get all sites
47
- const sites = this.options.sites;
48
- if (!sites || !sites.length) {
49
- throw new RangeError(exports.sitesError);
50
- }
51
- // Fetch paths for each site
52
- for (let i = 0; i < sites.length; i++) {
53
- const siteName = sites[i];
54
- // Fetch paths using all locales
55
- paths.push(...(yield this.getTranformedPaths(siteName, languages, formatStaticPath)));
56
- }
57
- return [].concat(...paths);
58
- });
59
- }
60
- /**
61
- * Fetch and return site paths for multisite implementation, with prefixes included
62
- * @param {string} language path language
63
- * @param {string} siteName site name
64
- * @returns modified paths
65
- */
66
- fetchLanguageSitePaths(language, siteName) {
67
- const _super = Object.create(null, {
68
- fetchLanguageSitePaths: { get: () => super.fetchLanguageSitePaths }
69
- });
70
- return __awaiter(this, void 0, void 0, function* () {
71
- const results = yield _super.fetchLanguageSitePaths.call(this, language, siteName);
72
- results.forEach((item) => {
73
- if (item) {
74
- item.path = (0, site_1.getSiteRewrite)(item.path, { siteName: siteName });
75
- }
76
- });
77
- return results;
78
- });
79
- }
80
- }
81
- exports.MultisiteGraphQLSitemapService = MultisiteGraphQLSitemapService;