@enonic/nextjs-adapter 3.0.0-B3 → 3.0.0-B4

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 (163) hide show
  1. package/LICENSE +201 -0
  2. package/baseMappings.js.map +1 -1
  3. package/client.js.map +1 -1
  4. package/common/ComponentRegistry.js.map +1 -1
  5. package/common/UrlProcessor.js.map +1 -1
  6. package/common/constants.js.map +1 -1
  7. package/common/env.js.map +1 -1
  8. package/guillotine/applyProcessors.js.map +1 -1
  9. package/guillotine/buildComponentTree.js.map +1 -1
  10. package/guillotine/buildErrorResponse.js.map +1 -1
  11. package/guillotine/buildPage.js.map +1 -1
  12. package/guillotine/collectComponentDescriptors.js.map +1 -1
  13. package/guillotine/combineMultipleQueries.js.map +1 -1
  14. package/guillotine/createMetaData.js.map +1 -1
  15. package/guillotine/fetchContent.js.map +1 -1
  16. package/guillotine/fetchContentData.js.map +1 -1
  17. package/guillotine/fetchContentPathsForAllLocales.js.map +1 -1
  18. package/guillotine/fetchContentPathsForLocale.js.map +1 -1
  19. package/guillotine/fetchFromApi.js.map +1 -1
  20. package/guillotine/fetchGuillotine.js.map +1 -1
  21. package/guillotine/fetchMetaData.js.map +1 -1
  22. package/guillotine/getCleanContentPathArrayOrThrow400.js.map +1 -1
  23. package/guillotine/getComponentConfig.js.map +1 -1
  24. package/guillotine/getContentAndComponentPaths.js.map +1 -1
  25. package/guillotine/getMetaData.js.map +1 -1
  26. package/guillotine/getParentRegion.js.map +1 -1
  27. package/guillotine/getQueryAndVariables.js.map +1 -1
  28. package/guillotine/metadata/configQuery.js.map +1 -1
  29. package/guillotine/metadata/richTextQuery.js.map +1 -1
  30. package/guillotine/parseComponentPath.js.map +1 -1
  31. package/guillotine/prefixLayoutPath.js.map +1 -1
  32. package/guillotine/processComponentConfig.js.map +1 -1
  33. package/guillotine/restrictComponentsToPath.js.map +1 -1
  34. package/guillotine/validateData.js.map +1 -1
  35. package/guillotine/validateNotFound.js.map +1 -1
  36. package/guillotine/validateShortcut.js.map +1 -1
  37. package/i18n/LocaleContext.jsx.map +1 -1
  38. package/i18n/i18n.js.map +1 -1
  39. package/index.js.map +1 -1
  40. package/package.json +3 -4
  41. package/query/Shortcut.js.map +1 -1
  42. package/server.js +6 -0
  43. package/server.js.map +1 -1
  44. package/src/baseMappings.ts +53 -0
  45. package/src/client.ts +2 -0
  46. package/src/common/ComponentRegistry.ts +162 -0
  47. package/src/common/UrlProcessor.ts +142 -0
  48. package/src/common/constants.ts +85 -0
  49. package/src/common/env.ts +39 -0
  50. package/src/guillotine/applyProcessors.ts +38 -0
  51. package/src/guillotine/buildComponentTree.ts +63 -0
  52. package/src/guillotine/buildErrorResponse.ts +39 -0
  53. package/src/guillotine/buildPage.ts +15 -0
  54. package/src/guillotine/collectComponentDescriptors.ts +63 -0
  55. package/src/guillotine/combineMultipleQueries.ts +75 -0
  56. package/src/guillotine/createMetaData.ts +73 -0
  57. package/src/guillotine/fetchContent.ts +250 -0
  58. package/src/guillotine/fetchContentData.ts +33 -0
  59. package/src/guillotine/fetchContentPathsForAllLocales.ts +21 -0
  60. package/src/guillotine/fetchContentPathsForLocale.ts +42 -0
  61. package/src/guillotine/fetchFromApi.ts +69 -0
  62. package/src/guillotine/fetchGuillotine.ts +61 -0
  63. package/src/guillotine/fetchMetaData.ts +32 -0
  64. package/src/guillotine/getCleanContentPathArrayOrThrow400.ts +22 -0
  65. package/src/guillotine/getComponentConfig.ts +7 -0
  66. package/src/guillotine/getContentAndComponentPaths.ts +11 -0
  67. package/src/guillotine/getMetaData.ts +73 -0
  68. package/src/guillotine/getParentRegion.ts +59 -0
  69. package/src/guillotine/getQueryAndVariables.ts +52 -0
  70. package/src/guillotine/metadata/configQuery.ts +46 -0
  71. package/src/guillotine/metadata/richTextQuery.ts +34 -0
  72. package/src/guillotine/parseComponentPath.ts +29 -0
  73. package/src/guillotine/prefixLayoutPath.ts +16 -0
  74. package/src/guillotine/processComponentConfig.ts +38 -0
  75. package/src/guillotine/restrictComponentsToPath.ts +45 -0
  76. package/src/guillotine/validateData.ts +11 -0
  77. package/src/guillotine/validateNotFound.ts +20 -0
  78. package/src/guillotine/validateShortcut.ts +37 -0
  79. package/src/i18n/LocaleContext.tsx +54 -0
  80. package/src/i18n/i18n.ts +54 -0
  81. package/src/index.ts +42 -0
  82. package/src/query/Shortcut.ts +14 -0
  83. package/src/server.ts +5 -0
  84. package/src/types/component.ts +147 -0
  85. package/src/types/componentProps.ts +142 -0
  86. package/src/types/guillotine.ts +426 -0
  87. package/src/types/i18n.ts +8 -0
  88. package/src/types/index.ts +58 -0
  89. package/src/types/next.ts +7 -0
  90. package/src/types/util.ts +5 -0
  91. package/src/utils/addLineNumbers.ts +3 -0
  92. package/src/utils/buildGuillotineRequestHeaders.ts +32 -0
  93. package/src/utils/commonChars.ts +16 -0
  94. package/src/utils/fixDoubleSlashes.ts +3 -0
  95. package/src/utils/getContentApiUrl.ts +20 -0
  96. package/src/utils/getProjectLocaleConfig.ts +24 -0
  97. package/src/utils/getProjectLocaleConfigById.ts +21 -0
  98. package/src/utils/getProjectLocaleConfigByLocale.ts +19 -0
  99. package/src/utils/getProjectLocaleConfigs.ts +36 -0
  100. package/src/utils/getProjectLocales.ts +6 -0
  101. package/src/utils/getRenderMode.ts +14 -0
  102. package/src/utils/getRequestLocaleInfo.ts +29 -0
  103. package/src/utils/getXpBaseUrl.ts +12 -0
  104. package/src/utils/indent.ts +4 -0
  105. package/src/utils/sanitizeGraphqlName.ts +11 -0
  106. package/src/views/BaseComponent.tsx +153 -0
  107. package/src/views/BaseContent.tsx +47 -0
  108. package/src/views/BaseLayout.tsx +33 -0
  109. package/src/views/BaseMacro.tsx +94 -0
  110. package/src/views/BasePage.tsx +42 -0
  111. package/src/views/BasePart.tsx +34 -0
  112. package/src/views/Empty.tsx +5 -0
  113. package/src/views/Fragment.tsx +41 -0
  114. package/src/views/MainView.tsx +22 -0
  115. package/src/views/PropsView.tsx +38 -0
  116. package/src/views/Region.tsx +76 -0
  117. package/src/views/RichTextView.tsx +75 -0
  118. package/src/views/SingleComponent.tsx +19 -0
  119. package/src/views/StaticContent.tsx +39 -0
  120. package/src/views/Text.tsx +19 -0
  121. package/src/views/getClientHydratedHtml.tsx +12 -0
  122. package/src/views/macros/DefaultMacro.tsx +9 -0
  123. package/src/views/macros/DisableMacro.tsx +8 -0
  124. package/types/component.js.map +1 -1
  125. package/types/componentProps.js.map +1 -1
  126. package/types/guillotine.js.map +1 -1
  127. package/types/i18n.js.map +1 -1
  128. package/types/index.js.map +1 -1
  129. package/types/next.js.map +1 -1
  130. package/types/util.js.map +1 -1
  131. package/utils/addLineNumbers.js.map +1 -1
  132. package/utils/buildGuillotineRequestHeaders.js.map +1 -1
  133. package/utils/commonChars.js.map +1 -1
  134. package/utils/fixDoubleSlashes.js.map +1 -1
  135. package/utils/getContentApiUrl.js.map +1 -1
  136. package/utils/getProjectLocaleConfig.js.map +1 -1
  137. package/utils/getProjectLocaleConfigById.js.map +1 -1
  138. package/utils/getProjectLocaleConfigByLocale.js.map +1 -1
  139. package/utils/getProjectLocaleConfigs.js.map +1 -1
  140. package/utils/getProjectLocales.js.map +1 -1
  141. package/utils/getRenderMode.js.map +1 -1
  142. package/utils/getRequestLocaleInfo.js.map +1 -1
  143. package/utils/getXpBaseUrl.js.map +1 -1
  144. package/utils/indent.js.map +1 -1
  145. package/utils/sanitizeGraphqlName.js.map +1 -1
  146. package/views/BaseComponent.jsx.map +1 -1
  147. package/views/BaseContent.jsx.map +1 -1
  148. package/views/BaseLayout.jsx.map +1 -1
  149. package/views/BaseMacro.jsx.map +1 -1
  150. package/views/BasePage.jsx.map +1 -1
  151. package/views/BasePart.jsx.map +1 -1
  152. package/views/Empty.jsx.map +1 -1
  153. package/views/Fragment.jsx.map +1 -1
  154. package/views/MainView.jsx.map +1 -1
  155. package/views/PropsView.jsx.map +1 -1
  156. package/views/Region.jsx.map +1 -1
  157. package/views/RichTextView.jsx.map +1 -1
  158. package/views/SingleComponent.jsx.map +1 -1
  159. package/views/StaticContent.jsx.map +1 -1
  160. package/views/Text.jsx.map +1 -1
  161. package/views/getClientHydratedHtml.jsx.map +1 -1
  162. package/views/macros/DefaultMacro.jsx.map +1 -1
  163. package/views/macros/DisableMacro.jsx.map +1 -1
@@ -0,0 +1,61 @@
1
+ import type {ContentApiBaseBody, GuillotineResult, ProjectLocaleConfig} from '../types';
2
+
3
+
4
+ import {fetchFromApi} from './fetchFromApi';
5
+
6
+
7
+ /** Guillotine-specialized fetch, using the generic fetch above */
8
+ export async function fetchGuillotine<Data = Record<string, unknown>>(
9
+ contentApiUrl: string,
10
+ body: ContentApiBaseBody,
11
+ projectConfig: ProjectLocaleConfig,
12
+ headers?: {},
13
+ ): Promise<GuillotineResult> {
14
+ if (typeof body.query !== 'string' || !body.query.trim()) {
15
+ return {
16
+ error: {
17
+ code: '400',
18
+ message: `Invalid or missing query. JSON.stringify(query) = ${JSON.stringify(body.query)}`,
19
+ },
20
+ };
21
+ }
22
+ const path = body.variables?.path;
23
+ const pathMessage = path ? JSON.stringify(path) : '';
24
+ return await fetchFromApi<Data>(
25
+ contentApiUrl,
26
+ body,
27
+ projectConfig,
28
+ headers,
29
+ )
30
+ .then(json => {
31
+ let errors: any[] = json.errors; // fetchFromApi ensures json is an object
32
+
33
+ if (errors) {
34
+ if (!Array.isArray(errors)) {
35
+ errors = [errors];
36
+ }
37
+ console.error(`${errors.length} error(s) when fetching data from: ${contentApiUrl}`);
38
+ console.error(`headers: ${JSON.stringify(headers, null, 2)} \nvariables: ${JSON.stringify(body.variables, null, 2)}`);
39
+ errors.forEach(error => {
40
+ console.error(error);
41
+ });
42
+
43
+ return {
44
+ error: {
45
+ code: '500',
46
+ message: `Server responded with ${errors.length} error(s), probably from guillotine - see log.`,
47
+ },
48
+ };
49
+ }
50
+
51
+ return json.data;
52
+ })
53
+ .catch((err) => {
54
+ console.warn(`Client-side error when trying to fetch data ${pathMessage}`, err);
55
+ try {
56
+ return {error: JSON.parse(err.message)};
57
+ } catch (e2) {
58
+ return {error: {code: 'Client-side error', message: err.message}};
59
+ }
60
+ });
61
+ }
@@ -0,0 +1,32 @@
1
+ import type {
2
+ ContentApiBaseBody,
3
+ MetaResult,
4
+ ProjectLocaleConfig,
5
+ } from '../types';
6
+
7
+
8
+ import {getMetaQuery, pageFragmentQuery} from './getMetaData';
9
+ import {fetchGuillotine} from './fetchGuillotine';
10
+
11
+
12
+ export const fetchMetaData = async (
13
+ contentApiUrl: string,
14
+ xpContentPath: string,
15
+ projectConfig: ProjectLocaleConfig,
16
+ headers?: {},
17
+ ): Promise<MetaResult> => {
18
+ const body: ContentApiBaseBody = {
19
+ query: getMetaQuery(pageFragmentQuery()),
20
+ variables: {
21
+ path: xpContentPath,
22
+ },
23
+ };
24
+ const metaResult = await fetchGuillotine<MetaResult>(contentApiUrl, body, projectConfig, headers);
25
+ if (metaResult.error) {
26
+ return metaResult;
27
+ } else {
28
+ return {
29
+ meta: metaResult?.guillotine?.get,
30
+ };
31
+ }
32
+ };
@@ -0,0 +1,22 @@
1
+ /** Checks a site-relative contentPath as a slash-delimited string or a string array, and returns a pure site-relative path string (no double slashes, starts with a slash, does not end with one). */
2
+ export const getCleanContentPathArrayOrThrow400 = (contentPath: string | string[] | undefined): string => {
3
+ if (contentPath === undefined) {
4
+ return '';
5
+ }
6
+ const isArray = Array.isArray(contentPath);
7
+
8
+ if (!isArray) {
9
+ if (typeof contentPath !== 'string') {
10
+ throw Error(JSON.stringify({
11
+ code: 400,
12
+ message: `Unexpected target content _path: contentPath must be a string or pure string array (contentPath=${JSON.stringify(
13
+ contentPath)})`,
14
+ }));
15
+ }
16
+
17
+ return contentPath;
18
+
19
+ } else {
20
+ return (contentPath).join('/');
21
+ }
22
+ };
@@ -0,0 +1,7 @@
1
+ import type {PageComponent} from '../types';
2
+
3
+
4
+ export function getComponentConfig(cmp?: PageComponent) {
5
+ const cmpData = cmp && cmp[cmp.type];
6
+ return cmpData && 'config' in cmpData ? cmpData.config : undefined;
7
+ }
@@ -0,0 +1,11 @@
1
+ const COMPONENT_PATH_KEY = /\/?_\/component/; // first slash is optional for root components
2
+
3
+ export const getContentAndComponentPaths = (requestPath: string): string[] => {
4
+ let contentPath, componentPath;
5
+ if (COMPONENT_PATH_KEY.test(requestPath)) {
6
+ [contentPath, componentPath] = requestPath.split(COMPONENT_PATH_KEY);
7
+ } else {
8
+ contentPath = requestPath;
9
+ }
10
+ return [contentPath, componentPath];
11
+ };
@@ -0,0 +1,73 @@
1
+ import {ComponentRegistry} from '../common/ComponentRegistry';
2
+ import {configQuery} from './metadata/configQuery';
3
+ import {richTextQuery} from './metadata/richTextQuery';
4
+ import {indent} from '../utils/indent';
5
+
6
+
7
+ const partConfigQuery = (): string => {
8
+ return configQuery(ComponentRegistry.getParts());
9
+ };
10
+
11
+ const layoutConfigQuery = (): string => {
12
+ return configQuery(ComponentRegistry.getLayouts());
13
+ };
14
+
15
+ const pageConfigQuery = (): string => {
16
+ return configQuery(ComponentRegistry.getPages());
17
+ };
18
+
19
+
20
+ /*
21
+ IMPORTANT: make sure to transform your queries into functions too when using this function inside them !!!
22
+ */
23
+ const componentsQuery = () => `type
24
+ path
25
+ page {
26
+ descriptor
27
+ ${indent(pageConfigQuery(), 4)}
28
+ template {
29
+ _path
30
+ }
31
+ }
32
+ layout {
33
+ descriptor
34
+ ${indent(layoutConfigQuery(), 4)}
35
+ }
36
+ text {
37
+ ${indent(richTextQuery('value'), 4)}
38
+ }
39
+ part {
40
+ descriptor
41
+ ${indent(partConfigQuery(), 4)}
42
+ }
43
+ image {
44
+ caption
45
+ image {
46
+ imageUrl (type:absolute, scale: "width-768")
47
+ }
48
+ }`;
49
+
50
+ // THIS QUERY DOES NOT SUPPORT NESTED FRAGMENTS
51
+ export const pageFragmentQuery = () => `components(resolveFragment: false, resolveTemplate: true) {
52
+ fragment {
53
+ id
54
+ fragment {
55
+ components {
56
+ ${indent(componentsQuery(),16)}
57
+ }
58
+ }
59
+ }
60
+ ${indent(componentsQuery(),4)}
61
+ }`;
62
+
63
+ export function getMetaQuery(pageFragment?: string): string {
64
+ return `query($path:ID!) {
65
+ guillotine {
66
+ get(key:$path) {
67
+ _path
68
+ type
69
+ ${indent(pageFragment || '', 12)}
70
+ }
71
+ }
72
+ }`;
73
+ }
@@ -0,0 +1,59 @@
1
+ import type {
2
+ PageComponent,
3
+ PageRegion,
4
+ PathFragment,
5
+ RegionTree,
6
+ } from '../types';
7
+
8
+
9
+ import {XP_COMPONENT_TYPE} from '../common/constants';
10
+ import {prefixLayoutPath} from './prefixLayoutPath';
11
+
12
+
13
+ export function getParentRegion(
14
+ source: RegionTree,
15
+ contentType: string,
16
+ cmpPath: PathFragment[],
17
+ components: PageComponent[] = [],
18
+ createMissing ? : boolean,
19
+ ): PageRegion | undefined {
20
+ let currentTree: RegionTree = source;
21
+ let currentRegion: PageRegion | undefined;
22
+ let parentPath = '';
23
+
24
+ for (let i = 0; i < cmpPath.length; i++) {
25
+ const pathFragment = cmpPath[i];
26
+ const regionName = pathFragment.region;
27
+ parentPath += `/${pathFragment.region}/${pathFragment.index}`;
28
+ currentRegion = currentTree[regionName];
29
+
30
+ if (!currentRegion) {
31
+ if (createMissing) {
32
+ currentRegion = {
33
+ name: regionName,
34
+ components: [],
35
+ };
36
+ currentTree[regionName] = currentRegion;
37
+ } else {
38
+ throw `Region [${regionName}] was not found`;
39
+ }
40
+ }
41
+
42
+ if (i < cmpPath.length - 1) {
43
+ // look for layouts inside if this is not the last path fragment
44
+
45
+ const layout = components.find((cmp: PageComponent) => {
46
+ return cmp.type === XP_COMPONENT_TYPE.LAYOUT && prefixLayoutPath(contentType, cmp.path) === parentPath;
47
+ });
48
+ if (!layout) {
49
+ throw `Layout [${parentPath}] not found among components, but needed for component [${JSON.stringify(cmpPath, null, 2)}]`;
50
+ }
51
+ if (!layout.regions) {
52
+ layout.regions = {};
53
+ }
54
+ currentTree = layout.regions;
55
+ }
56
+ } // for
57
+
58
+ return currentRegion;
59
+ }
@@ -0,0 +1,52 @@
1
+ import type {
2
+ Context,
3
+ QueryAndVariables,
4
+ SelectedQueryMaybeVariablesFunc,
5
+ } from '../types';
6
+
7
+
8
+ export function getQueryAndVariables(
9
+ type: string,
10
+ path: string,
11
+ context: Context,
12
+ selectedQuery?: SelectedQueryMaybeVariablesFunc,
13
+ config?: any,
14
+ ): QueryAndVariables | undefined {
15
+
16
+ let query, getVariables;
17
+
18
+ if (
19
+ typeof selectedQuery === 'string' || typeof selectedQuery === 'function'
20
+ ) {
21
+ query = selectedQuery;
22
+
23
+ } else if (Array.isArray(selectedQuery)) {
24
+ query = selectedQuery[0];
25
+ getVariables = selectedQuery[1];
26
+
27
+ } else if (typeof selectedQuery === 'object') {
28
+ query = selectedQuery.query;
29
+ getVariables = selectedQuery.variables;
30
+ }
31
+
32
+ if (getVariables && typeof getVariables !== 'function') {
33
+ throw Error(`getVariables for content type ${type} should be a function, not: ${typeof getVariables}`);
34
+ }
35
+
36
+ if (query && typeof query !== 'string' && typeof query !== 'function') {
37
+ throw Error(`Query for content type ${type} should be a string or function, not: ${typeof query}`);
38
+ }
39
+
40
+ if (typeof query === 'function') {
41
+ query = query(path, context, config);
42
+ }
43
+
44
+ if (query) {
45
+ return {
46
+ query,
47
+ variables: getVariables ? getVariables(path, context, config) : {
48
+ path,
49
+ },
50
+ };
51
+ }
52
+ }
@@ -0,0 +1,46 @@
1
+ import type {ComponentDefinition} from '../../types';
2
+
3
+
4
+ import {sanitizeGraphqlName} from '../../utils/sanitizeGraphqlName';
5
+
6
+
7
+ export const configQuery = (
8
+ list: [string, ComponentDefinition][],
9
+ includeAppName = true,
10
+ canUseConfigAsJson = true,
11
+ ): string => {
12
+ const hasQueryList = list?.filter(([key, def]) => def.configQuery) || [];
13
+ if (hasQueryList.length === 0) {
14
+ return canUseConfigAsJson ? 'configAsJson' : '';
15
+ }
16
+
17
+ const configsByApp: Record<string,string[]> = {};
18
+ hasQueryList
19
+ .forEach((entry) => {
20
+ const nameParts = entry[0].split(':');
21
+ if (nameParts.length === 2) {
22
+ const sanitizedAppName = sanitizeGraphqlName(nameParts[0]);
23
+ let existingConfigs = configsByApp[sanitizedAppName];
24
+ if (!existingConfigs) {
25
+ existingConfigs = [];
26
+ configsByApp[sanitizedAppName] = existingConfigs;
27
+ }
28
+ existingConfigs.push(`${sanitizeGraphqlName(nameParts[1])}${entry[1].configQuery}`);
29
+ }
30
+ });
31
+
32
+ // Still query for configAsJson if at least one item has no configQuery defined
33
+ const configAsJsonQuery = canUseConfigAsJson && hasQueryList.length < list.length ? 'configAsJson' : '';
34
+
35
+ if (!includeAppName) {
36
+ return `${configAsJsonQuery}
37
+ config {
38
+ ${Object.values(configsByApp).reduce((arr, curr) => arr.concat(curr), []).join('\n')}
39
+ }`;
40
+ } else {
41
+ return `${configAsJsonQuery}
42
+ config {
43
+ ${Object.entries(configsByApp).map(entry => entry[0] + '{\n' + entry[1].join('\n') + '\n}')}
44
+ }`;
45
+ }
46
+ };
@@ -0,0 +1,34 @@
1
+ import {ComponentRegistry} from '../../common/ComponentRegistry';
2
+ import {configQuery} from './configQuery';
3
+ import {indent} from '../../utils/indent';
4
+
5
+
6
+ const macroConfigQuery = (): string => {
7
+ return configQuery(ComponentRegistry.getMacros(), false, false);
8
+ };
9
+
10
+ export const richTextQuery = (fieldName: string) => {
11
+ return `${fieldName}(processHtml:{type:absolute, imageWidths:[400, 800, 1200], imageSizes:"(max-width: 400px) 400px, (max-width: 800px) 800px, 1200px"}) {
12
+ processedHtml
13
+ macros {
14
+ ref
15
+ name
16
+ descriptor
17
+ ${indent(macroConfigQuery(), 8)}
18
+ }
19
+ links {
20
+ ref
21
+ media {
22
+ content {
23
+ _id
24
+ }
25
+ }
26
+ }
27
+ images {
28
+ ref
29
+ image {
30
+ _id
31
+ }
32
+ }
33
+ }`;
34
+ };
@@ -0,0 +1,29 @@
1
+ import type {PathFragment} from '../types';
2
+
3
+
4
+ import {
5
+ FRAGMENT_CONTENTTYPE_NAME,
6
+ FRAGMENT_DEFAULT_REGION_NAME,
7
+ } from '../common/constants';
8
+
9
+
10
+ export function parseComponentPath(contentType: string, path: string): PathFragment[] {
11
+ const matches: PathFragment[] = [];
12
+ let match;
13
+ const myRegexp = /(?:(\w+)\/(\d+))+/g;
14
+ while ((match = myRegexp.exec(path)) !== null) {
15
+ matches.push({
16
+ region: match[1],
17
+ index: +match[2],
18
+ });
19
+ }
20
+ if (contentType === FRAGMENT_CONTENTTYPE_NAME) {
21
+ // there is no main region in fragment content and the root component has '/' path
22
+ // prepend FRAGMENT_DEFAULT_REGION_NAME to path to conform to page structure
23
+ matches.unshift({
24
+ region: FRAGMENT_DEFAULT_REGION_NAME,
25
+ index: 0,
26
+ });
27
+ }
28
+ return matches;
29
+ }
@@ -0,0 +1,16 @@
1
+ import {
2
+ FRAGMENT_CONTENTTYPE_NAME,
3
+ FRAGMENT_DEFAULT_REGION_NAME,
4
+ } from '../common/constants';
5
+
6
+
7
+ export function prefixLayoutPath(contentType: string, path: string): string {
8
+ if (contentType !== FRAGMENT_CONTENTTYPE_NAME) {
9
+ return path;
10
+ } else {
11
+ // prepend FRAGMENT_DEFAULT_REGION_NAME to path to conform to page structure
12
+ // so that component with path '/' becomes /FRAGMENT_DEFAULT_REGION_NAME/0
13
+ // path /left/1 becomes /FRAGMENT_DEFAULT_REGION_NAME/0/left/1
14
+ return `/${FRAGMENT_DEFAULT_REGION_NAME}/0${path === '/' ? '' : path}`;
15
+ }
16
+ }
@@ -0,0 +1,38 @@
1
+ import type {PageComponent} from '../types';
2
+
3
+
4
+ import {sanitizeGraphqlName} from '../utils/sanitizeGraphqlName';
5
+
6
+
7
+ export function processComponentConfig(
8
+ myAppName: string,
9
+ myAppNameDashed: string,
10
+ cmp: PageComponent,
11
+ ): void {
12
+ const cmpData = cmp[cmp.type];
13
+ if (cmpData && 'descriptor' in cmpData && cmpData.descriptor) {
14
+ const [appName, cmpName] = cmpData.descriptor.split(':');
15
+ if (appName !== myAppName) {
16
+ return;
17
+ }
18
+ let config;
19
+ const configArray: Object[] = [];
20
+ if ('configAsJson' in cmpData && cmpData.configAsJson && cmpData.configAsJson[myAppNameDashed]) {
21
+ config = cmpData.configAsJson[myAppNameDashed][cmpName];
22
+ if (config) {
23
+ configArray.push(config);
24
+ delete cmpData.configAsJson;
25
+ }
26
+ }
27
+ const sanitizedAppName = sanitizeGraphqlName(appName);
28
+ if ('config' in cmpData && cmpData.config && cmpData.config[sanitizedAppName]) {
29
+ config = cmpData.config[sanitizedAppName][sanitizeGraphqlName(cmpName)];
30
+ if (config) {
31
+ configArray.push(config);
32
+ }
33
+ }
34
+ if (configArray.length) {
35
+ cmpData.config = Object.assign({}, ...configArray);
36
+ }
37
+ }
38
+ }
@@ -0,0 +1,45 @@
1
+ import type {PageComponent} from '../types';
2
+
3
+
4
+ import {XP_COMPONENT_TYPE} from '../common/constants';
5
+ import {parseComponentPath} from './parseComponentPath';
6
+
7
+
8
+ export function restrictComponentsToPath(
9
+ contentType: string,
10
+ components?: PageComponent[],
11
+ componentPath?: string,
12
+ ): PageComponent[] {
13
+ if (!componentPath || !components?.length) {
14
+ return components || [];
15
+ }
16
+
17
+ // filter components to the requested one only
18
+ const component = components.find(cmp => {
19
+ return cmp.path === componentPath;
20
+ });
21
+
22
+ if (!component) {
23
+ return [];
24
+ }
25
+
26
+ let result: PageComponent[] = [component];
27
+ if (component.type !== XP_COMPONENT_TYPE.LAYOUT) {
28
+ // remember to include all parent layouts too !
29
+ const cmpPath = parseComponentPath(contentType, component.path);
30
+ for (let i = cmpPath.length - 2; i >= 0; i--) {
31
+ const parentPath = cmpPath[i];
32
+ const parentCmp = components.find(cmp => cmp.path === `/${parentPath.region}/${parentPath.index}`);
33
+ if (parentCmp) {
34
+ result.unshift(parentCmp);
35
+ }
36
+ }
37
+ } else {
38
+ // It's a layout, include child components
39
+ const childCmps = components.filter(cmp => cmp.path !== component.path && cmp.path.startsWith(component.path));
40
+ if (childCmps.length) {
41
+ result = result.concat(childCmps);
42
+ }
43
+ }
44
+ return result;
45
+ }
@@ -0,0 +1,11 @@
1
+ import type {FetchContentResult} from '../types';
2
+
3
+
4
+ import {validateNotFound} from './validateNotFound';
5
+ import {validateShortcut} from './validateShortcut';
6
+
7
+
8
+ export function validateData(props: FetchContentResult): void {
9
+ validateNotFound(props);
10
+ validateShortcut(props);
11
+ }
@@ -0,0 +1,20 @@
1
+ import type {FetchContentResult} from '../types';
2
+
3
+
4
+ import {notFound} from 'next/navigation';
5
+
6
+
7
+ export function validateNotFound(props: FetchContentResult): void {
8
+ const {error} = props;
9
+ if (error) {
10
+ switch (error.code) {
11
+ case '404':
12
+ console.warn(error.code, error.message);
13
+ notFound();
14
+ break;
15
+ default:
16
+ console.error(error.code, error.message);
17
+ throw new Error(error.message);
18
+ }
19
+ }
20
+ }
@@ -0,0 +1,37 @@
1
+ import type {FetchContentResult} from '../types';
2
+
3
+
4
+ import {notFound, redirect, RedirectType} from 'next/navigation';
5
+ import {RENDER_MODE} from '../common/constants';
6
+ import {IS_DEV_MODE} from '../common/env';
7
+ import {UrlProcessor} from '../common/UrlProcessor';
8
+
9
+
10
+ export function validateShortcut(props: FetchContentResult): void {
11
+ const {data, meta, error} = props;
12
+ const pageUrl = data?.get?.data?.target?.pageUrl;
13
+ if (meta.type === 'base:shortcut' && pageUrl) {
14
+ if (meta.renderMode !== RENDER_MODE.NEXT) {
15
+ // do not show shortcut targets in preview/edit mode
16
+ console.warn(404, `Shortcuts are not available in ${RENDER_MODE.NEXT} render mode`);
17
+ notFound();
18
+ }
19
+
20
+ const destination = UrlProcessor.process(pageUrl, meta, true);
21
+ console.debug(`Redirecting shortcut content [${meta.path}] to`, destination);
22
+ redirect(destination, RedirectType.replace);
23
+ }
24
+
25
+ // we can not set 418 for static paths,
26
+ // but we can show 404 instead to be handled in CS
27
+ const canNotRender = meta && !meta.canRender && meta.renderMode !== RENDER_MODE.EDIT;
28
+
29
+ const catchAllInNextProdMode = meta.renderMode === RENDER_MODE.NEXT && !IS_DEV_MODE && meta.catchAll;
30
+
31
+ const isNotFound = (error && error.code === '404') || canNotRender || catchAllInNextProdMode;
32
+
33
+ if (isNotFound) {
34
+ console.warn(404, `Can not render content at [${meta.path}]`);
35
+ notFound();
36
+ }
37
+ }
@@ -0,0 +1,54 @@
1
+ 'use client';
2
+ import type {Dict, LocaleContextType} from '../types';
3
+
4
+ import React, {createContext, useContext, useEffect, useState} from 'react';
5
+ import {getPhrase, loadPhrases} from './i18n';
6
+
7
+
8
+ const LocaleContext = createContext<LocaleContextType>({
9
+ dictionary: {},
10
+ locale: '',
11
+ localize: (key: string, ...args: any[]) => key,
12
+ setLocale: (locale: string) => Promise.resolve({}),
13
+ });
14
+
15
+ export const useLocaleContext = () => useContext(LocaleContext);
16
+
17
+ export const LocaleContextProvider = ({
18
+ children,
19
+ locale: localeProps = '',
20
+ }: {
21
+ children: any
22
+ locale?: string
23
+ }) => {
24
+ const [currentLocale, setLocaleState] = useState(localeProps);
25
+ const [dictionary, setPhrasesState] = useState<Dict>({});
26
+
27
+ const setLocale = async (locale: string): Promise<Dict> => {
28
+ setLocaleState(locale);
29
+ return loadPhrases(locale).then((phrases) => {
30
+ setPhrasesState(phrases);
31
+ console.info(`Loaded client-side phrases for locale "${locale}"`);
32
+ return phrases;
33
+ });
34
+ };
35
+
36
+ useEffect(() => {
37
+ if (localeProps) {
38
+ void setLocale(localeProps); // void to avoid @typescript-eslint/no-floating-promises
39
+ }
40
+ }, []);
41
+
42
+ const localize = (key: string, ...args: any[]) => getPhrase(currentLocale, dictionary, key, ...args);
43
+
44
+ return (
45
+ <LocaleContext.Provider value={{
46
+ setLocale,
47
+ locale: currentLocale,
48
+ dictionary,
49
+ localize,
50
+ }}>
51
+ {children}
52
+ </LocaleContext.Provider>
53
+ );
54
+ };