@remkoj/optimizely-graph-functions 6.0.0-pre9 → 6.0.0-rc.1

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 (45) hide show
  1. package/README.md +60 -14
  2. package/dist/_transform/handleDependDirective.d.ts +11 -0
  3. package/dist/_transform/handleDependDirective.js +128 -0
  4. package/dist/_transform/handleDependDirective.js.map +1 -0
  5. package/dist/_transform/injectComponentDocuments.d.ts +3 -0
  6. package/dist/_transform/injectComponentDocuments.js +79 -24
  7. package/dist/_transform/injectComponentDocuments.js.map +1 -1
  8. package/dist/_transform/injectPageQueries.d.ts +1 -0
  9. package/dist/_transform/injectPageQueries.js +40 -7
  10. package/dist/_transform/injectPageQueries.js.map +1 -1
  11. package/dist/_transform/injectSectionQueries.d.ts +1 -0
  12. package/dist/_transform/injectSectionQueries.js +64 -17
  13. package/dist/_transform/injectSectionQueries.js.map +1 -1
  14. package/dist/_transform/normalizeFragmentNames.js +2 -0
  15. package/dist/_transform/normalizeFragmentNames.js.map +1 -1
  16. package/dist/_transform/performInjections.js +2 -35
  17. package/dist/_transform/performInjections.js.map +1 -1
  18. package/dist/cms/index.d.ts +4 -10
  19. package/dist/cms/index.js +57 -24
  20. package/dist/cms/index.js.map +1 -1
  21. package/dist/contenttype-loader.d.ts +1 -48
  22. package/dist/contenttype-loader.js +21 -286
  23. package/dist/contenttype-loader.js.map +1 -1
  24. package/dist/documents/fragments.cms13.js +77 -13
  25. package/dist/documents/fragments.cms13.js.map +1 -1
  26. package/dist/generator/collision-tracker.d.ts +22 -0
  27. package/dist/generator/collision-tracker.js +103 -0
  28. package/dist/generator/collision-tracker.js.map +1 -0
  29. package/dist/generator/generator.d.ts +77 -0
  30. package/dist/generator/generator.js +272 -0
  31. package/dist/generator/generator.js.map +1 -0
  32. package/dist/generator/index.d.ts +3 -0
  33. package/dist/generator/index.js +42 -0
  34. package/dist/generator/index.js.map +1 -0
  35. package/dist/generator/virtual-location.d.ts +41 -0
  36. package/dist/generator/virtual-location.js +139 -0
  37. package/dist/generator/virtual-location.js.map +1 -0
  38. package/dist/index.js +4 -1
  39. package/dist/index.js.map +1 -1
  40. package/dist/preset.js +103 -38
  41. package/dist/preset.js.map +1 -1
  42. package/dist/transform.d.ts +4 -3
  43. package/dist/transform.js +8 -1
  44. package/dist/transform.js.map +1 -1
  45. package/package.json +20 -16
package/README.md CHANGED
@@ -1,4 +1,8 @@
1
- # Optimizely GraphQL Codegen Plugin
1
+ # Optimizely GraphQL Codegen Plugin <!-- omit in toc -->
2
+
3
+ > [!WARNING]
4
+ > There'll be an update of Optimizely SaaS CMS that is incompatible with all SDK versions prior to 5.1.6. If you don't upgrade, you will see empty pages (main website) and "Component not found" messages (preview).
5
+
2
6
  GraphQL Codegen plugin and preset which generate both the GraphQL type definitions and a few convenienece methods for useage with [Optimizely Graph Client](../optimizely-graph-client/README.md).
3
7
 
4
8
  [Release notes](https://github.com/remkoj/optimizely-dxp-clients/releases)
@@ -6,7 +10,22 @@ GraphQL Codegen plugin and preset which generate both the GraphQL type definitio
6
10
  > [!WARNING]
7
11
  > The GraphQL Codegen preset requires a patch to enable it to work with recursive queries. Make sure to run this command after every update to ensure you're using the latest patches: `yarn opti-graph patches:apply`. Adjust when used in a mono-repo to patch the correct package.json, for example: `yarn workspace frontend opti-graph patches:apply -p ../../`
8
12
 
9
- ## Install package
13
+ ## Contents <!-- omit in toc -->
14
+ - [1. Install package](#1-install-package)
15
+ - [2. Configure package](#2-configure-package)
16
+ - [3. GraphQL Document Processing](#3-graphql-document-processing)
17
+ - [3.1. Allow overwriting of built-in fragments \& queries](#31-allow-overwriting-of-built-in-fragments--queries)
18
+ - [3.2. Injection of fragments \& queries for ContentTypes](#32-injection-of-fragments--queries-for-contenttypes)
19
+ - [3.3. Auto inject fragments](#33-auto-inject-fragments)
20
+ - [3.4. Remove fragments and spreads that target non-existing types](#34-remove-fragments-and-spreads-that-target-non-existing-types)
21
+ - [3.5. Dedicated Queries \& Fragments](#35-dedicated-queries--fragments)
22
+ - [Compiler field directive `@depend`](#compiler-field-directive-depend)
23
+ - [4. Usage](#4-usage)
24
+ - [4.1. Option 1: Direct methods](#41-option-1-direct-methods)
25
+ - [4.2. Option 2: Enhanced Client](#42-option-2-enhanced-client)
26
+
27
+
28
+ ## 1. Install package
10
29
  To install using Yarn, use the following command:
11
30
 
12
31
  ```bash
@@ -19,7 +38,7 @@ yarn add --dev @remkoj/optimizely-graph-cli
19
38
  yarn opti-graph patches:apply
20
39
  ```
21
40
 
22
- ## Configure package
41
+ ## 2. Configure package
23
42
  Create a codegen.ts within your application root folder (e.g. apps/frontend/codegen.ts within the example site). Within the codegen.ts create the following configuration:
24
43
 
25
44
  ```typescript
@@ -104,11 +123,46 @@ The presetConfig of the `OptimizelyGraphPreset` is an extension of the configura
104
123
  | functions | The list of GraphQL Functions that should be made available in the `functions.ts` file. When specified, this overrides the default list.<br/>*Default value: `['getContentType','getContentByPath','getContentById']`*
105
124
  | verbose | Set to `true` to enable debugging output of the preset, loader, plugin and transform |
106
125
 
126
+ ## 3. GraphQL Document Processing
127
+ ### 3.1. Allow overwriting of built-in fragments & queries
128
+ All fragment and query names injected / generated by this package start with an underscore (for example: `_getContentById`). During the document pre-processing, all these fragments and queries will be processed with this logic:
129
+ - If there's no query or fragment with the name without the leading underscore, it will be renamed. (i.e. `_getContentById` becomes `getContentById`)
130
+ - If a query or fragment with the name without leading underscore does exist, the built-in version with underscore will be removed from the document set.
131
+
132
+ This allows a project to overwrite built-in fragments and queries, while still ensuring type-safety.
133
+
134
+ ### 3.2. Injection of fragments & queries for ContentTypes
135
+ For each content type the appropriate fragments and queries will be auto generated an injected into the document set.
136
+
137
+ ### 3.3. Auto inject fragments
138
+ Dynamically build queries & fragments based upon the `injections` configuration, and the default injections from the auto-generated fragments & queries.
139
+
140
+ This allows you to tell wich group of fragments you want at a given location and then during GraphQL compilation generate the full queries based upon the current content schema in Optimizely CMS and your project configuration.
141
+
142
+ ### 3.4. Remove fragments and spreads that target non-existing types
143
+ Depending on the features you have enabled in your CMS, not all types might actually be present in Optimizely Graph. This logic removes these fragments and spreads from the documents.
144
+
145
+ This approach assumes you're using TypeScript, as missing, but required types or fields should cause an error in the TypeScript compilation step of you application. Hence it moves the error from GraphQL Codegen to TypeScript, allowing some of the changes to be handled in the code.
146
+
147
+ ### 3.5. Dedicated Queries & Fragments
148
+ The preset automatically injects a number of fragments and documents into the generated code. These can be found in their respective document:
149
+
150
+ - [`opti-cms:/queries/13`](./src/documents/queries.cms13.ts)
151
+ - [`opti-cms:/queries/12`](./src/documents/queries.cms12.ts)
152
+ - [`opti-cms:/fragments/13`](./src/documents/fragments.cms13.ts)
153
+ - [`opti-cms:/fragments/12`](./src/documents/fragments.cms12.ts)
154
+
155
+ ### Compiler field directive `@depend`
156
+ A compile time directive `@depend` is processed, allowing you to make selections depend on a field to present in the schema.
107
157
 
108
- ## Usage
158
+ For example: `componentData: item @depend(on: "ContentReference.item") {}` will remove the field selection `componentData` from the document if there's no type with the name `ContentReference` that has a field named `item`.
159
+
160
+ This allows to write generic queries that can cope with differen configurations within the CMS.
161
+
162
+ ## 4. Usage
109
163
  After running the code generation, you can use the following API's (assuming the folder where the generated files are stored is available at `@/gql`):
110
164
 
111
- ### Option 1: Direct methods
165
+ ### 4.1. Option 1: Direct methods
112
166
  Only the methods specified by the `functions` preset configuration are available using this method.
113
167
 
114
168
  ```typescript
@@ -123,7 +177,7 @@ const contentFromId = await getContentById(client, { guidValue: '00000000-0000-0
123
177
  const contentFromPath = await getContentByPath(client, { path: '/en' })
124
178
  ```
125
179
 
126
- ### Option 2: Enhanced Client
180
+ ### 4.2. Option 2: Enhanced Client
127
181
  All GraphQL operations (e.g. Queries, Mutations, ...) defined within the documents are available using this method.
128
182
 
129
183
  ```typescript
@@ -138,11 +192,3 @@ const locale = Schema.Locales.En
138
192
 
139
193
  const contentItem = await client.getContentById({ guidValue: contentId, locale })
140
194
  ```
141
-
142
- ## Query Fragments
143
- The preset automatically injects a number of fragments and documents into the generated code. These can be found in their respective document:
144
-
145
- - [`opti-cms:/queries/13`](./src/documents/queries.cms13.ts)
146
- - [`opti-cms:/queries/12`](./src/documents/queries.cms12.ts)
147
- - [`opti-cms:/fragments/13`](./src/documents/fragments.cms13.ts)
148
- - [`opti-cms:/fragments/12`](./src/documents/fragments.cms12.ts)
@@ -0,0 +1,11 @@
1
+ import type { Types } from '@graphql-codegen/plugin-helpers';
2
+ import type { PresetOptions } from '../types';
3
+ /**
4
+ * Remove the "item" field in queries and fragments from the "ContentReference" type if it's not in the schema
5
+ *
6
+ * @param files
7
+ * @param options
8
+ * @returns
9
+ */
10
+ export declare function handleDependDirective(files: Types.DocumentFile[], options: Types.PresetFnArgs<PresetOptions>): Promise<Types.DocumentFile[]>;
11
+ export default handleDependDirective;
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.handleDependDirective = handleDependDirective;
4
+ const graphql_1 = require("graphql");
5
+ /**
6
+ * Remove the "item" field in queries and fragments from the "ContentReference" type if it's not in the schema
7
+ *
8
+ * @param files
9
+ * @param options
10
+ * @returns
11
+ */
12
+ async function handleDependDirective(files, options) {
13
+ // Debug output
14
+ if (options.presetConfig.verbose)
15
+ console.log(`✨ [Optimizely] Checking ContentReference to determine if it has an "item" field`);
16
+ // Ouch, this is an old SaaS CMS instance, so we're going to clean this field
17
+ if (options.presetConfig.verbose)
18
+ console.log(`✨ [Optimizely] Nope it hasn't removing any reference to it`);
19
+ const filteredFiles = files.map((file) => {
20
+ let isModified = false;
21
+ const newDocument = file.document ? (0, graphql_1.visit)(file.document, {
22
+ Field: {
23
+ enter(node) {
24
+ // Check if the field has the `depend` directive
25
+ const dependDirective = node.directives?.find(x => x.name.value === 'depend');
26
+ if (dependDirective) {
27
+ // If so read the arguments and validate if the required "on" argument is there
28
+ const args = parseArgs(dependDirective.arguments);
29
+ const dependency = args.get('on');
30
+ if (typeof dependency !== 'string' || dependency.length === 0)
31
+ throw new Error(`The "@depend" directive requires the parameter "on" to be a non-empty string ${buildLocString(dependDirective)}`);
32
+ // Parse & validate the argument
33
+ const [typeName, fieldName, ...remaining] = dependency.split('.');
34
+ if (remaining.length > 0)
35
+ throw new Error(`The "on" parameter of the "@depend" directive must have the form "typeName.fieldName" ${buildLocString(dependDirective)}`);
36
+ // Retrieve the type fields
37
+ const fields = getObjectFieldNames(options.schema, typeName);
38
+ isModified = true;
39
+ if (!(fields?.includes(fieldName) ?? false)) {
40
+ return null; // Remove the item
41
+ }
42
+ else {
43
+ const newNode = {
44
+ ...node,
45
+ directives: node.directives?.filter(x => x.name.value !== 'depend')
46
+ };
47
+ return newNode;
48
+ }
49
+ }
50
+ }
51
+ }
52
+ }) : undefined;
53
+ return isModified
54
+ ? {
55
+ ...file,
56
+ rawSDL: newDocument ? (0, graphql_1.print)(newDocument) : undefined,
57
+ document: newDocument,
58
+ }
59
+ : file;
60
+ });
61
+ return filteredFiles;
62
+ }
63
+ exports.default = handleDependDirective;
64
+ function buildLocString(node) {
65
+ if (!node.loc)
66
+ return "";
67
+ const sourceName = node.loc.source.name;
68
+ const startLine = node.loc.startToken.line;
69
+ const startChar = node.loc.startToken.column;
70
+ return `in ${sourceName} at line ${startLine}, position ${startChar}`;
71
+ }
72
+ function parseArgs(args) {
73
+ return args?.reduce((out, arg) => {
74
+ const argName = arg.name.value;
75
+ switch (arg.value.kind) {
76
+ case graphql_1.Kind.INT:
77
+ out.set(argName, parseInt(arg.value.value));
78
+ break;
79
+ case graphql_1.Kind.BOOLEAN:
80
+ out.set(argName, new Boolean(arg.value.value));
81
+ break;
82
+ case graphql_1.Kind.STRING:
83
+ out.set(argName, arg.value.value);
84
+ break;
85
+ default:
86
+ throw new Error(`Error parsing directive arguments, encountered unsupported argument kind ${arg.value.kind} for ${argName} ${buildLocString(arg)}`);
87
+ }
88
+ return out;
89
+ }, new Map()) ?? new Map();
90
+ }
91
+ function getObjectFieldNames(schema, objectName) {
92
+ let currentObjectName;
93
+ let objectFields = [];
94
+ let hasType = false;
95
+ (0, graphql_1.visit)(schema, {
96
+ ObjectTypeDefinition: {
97
+ enter(node) {
98
+ if (node.name.value === objectName)
99
+ hasType = true;
100
+ currentObjectName = node.name.value;
101
+ },
102
+ leave(node) {
103
+ if (currentObjectName === node.name.value)
104
+ currentObjectName = undefined;
105
+ },
106
+ },
107
+ FieldDefinition: {
108
+ enter(node) {
109
+ if (currentObjectName === objectName)
110
+ objectFields.push(node.name.value);
111
+ },
112
+ },
113
+ });
114
+ return objectFields;
115
+ }
116
+ function isASTNode(node) {
117
+ return !Array.isArray(node);
118
+ }
119
+ function isNotNullOrUndefined(toTest) {
120
+ return toTest !== null && toTest !== undefined;
121
+ }
122
+ function isFragmentOrOperation(x) {
123
+ if (Array.isArray(x) || x == undefined || x == null)
124
+ return false;
125
+ return (x.kind == graphql_1.Kind.FRAGMENT_DEFINITION ||
126
+ x.kind == graphql_1.Kind.OPERATION_DEFINITION);
127
+ }
128
+ //# sourceMappingURL=handleDependDirective.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handleDependDirective.js","sourceRoot":"","sources":["../../src/_transform/handleDependDirective.ts"],"names":[],"mappings":";;AAsBA,sDA0DC;AA/ED,qCAWgB;AAGhB;;;;;;GAMG;AACI,KAAK,UAAU,qBAAqB,CACzC,KAA2B,EAC3B,OAA0C;IAE1C,eAAe;IACf,IAAI,OAAO,CAAC,YAAY,CAAC,OAAO;QAC9B,OAAO,CAAC,GAAG,CACT,iFAAiF,CAClF,CAAA;IAEH,6EAA6E;IAC7E,IAAI,OAAO,CAAC,YAAY,CAAC,OAAO;QAC9B,OAAO,CAAC,GAAG,CAAC,4DAA4D,CAAC,CAAA;IAE3E,MAAM,aAAa,GAAyB,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;QAC7D,IAAI,UAAU,GAAG,KAAK,CAAA;QACtB,MAAM,WAAW,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CA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A;IACF,OAAO,YAAY,CAAA;AACrB,CAAC;AAED,SAAS,SAAS,CAAC,IAAkC;IAEnD,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAA;AAC7B,CAAC;AAED,SAAS,oBAAoB,CAAI,MAAiB;IAChD,OAAO,MAAM,KAAK,IAAI,IAAI,MAAM,KAAK,SAAS,CAAA;AAChD,CAAC;AACD,SAAS,qBAAqB,CAC5B,CAAmD;IAEnD,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,SAAS,IAAI,CAAC,IAAI,IAAI;QAAE,OAAO,KAAK,CAAA;IACjE,OAAO,CACJ,CAAa,CAAC,IAAI,IAAI,cAAI,CAAC,mBAAmB;QAC9C,CAAa,CAAC,IAAI,IAAI,cAAI,CAAC,oBAAoB,CACjD,CAAA;AACH,CAAC"}
@@ -1,5 +1,8 @@
1
1
  import type { Types } from '@graphql-codegen/plugin-helpers';
2
2
  import type { PresetOptions } from '../types';
3
+ export declare function getComponentDocuments(loader?: string): Promise<Types.CustomDocumentLoader[]>;
4
+ export declare function getInjectionTargetDocuments(loader?: string): Promise<Types.CustomDocumentLoader[]>;
5
+ export declare function injectInjectionTargets(files: Types.DocumentFile[], options: Types.PresetFnArgs<PresetOptions>): Promise<Types.DocumentFile[]>;
3
6
  /**
4
7
  * Check all fragments within the project and ensure that there's at least a fragment for every
5
8
  * content type defined in Optimizely CMS. This assumes that when overriding the fragments the
@@ -33,27 +33,66 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.getComponentDocuments = getComponentDocuments;
37
+ exports.getInjectionTargetDocuments = getInjectionTargetDocuments;
38
+ exports.injectInjectionTargets = injectInjectionTargets;
36
39
  exports.injectComponentDocuments = injectComponentDocuments;
37
40
  const graphql_1 = require("graphql");
38
- const QueryGen = __importStar(require("../contenttype-loader"));
41
+ const generator_1 = require("../generator");
39
42
  const OptiCMS = __importStar(require("../cms"));
40
43
  const tools_1 = require("./tools");
41
- /**
42
- * Check all fragments within the project and ensure that there's at least a fragment for every
43
- * content type defined in Optimizely CMS. This assumes that when overriding the fragments the
44
- * project will ensure that the injections are correct.
45
- *
46
- * @param files
47
- * @param options
48
- * @returns
49
- */
50
- async function injectComponentDocuments(files, options) {
44
+ const utils_1 = require("../utils");
45
+ async function getComponentDocuments(loader = '@remkoj/optimizely-graph-functions/contenttype-loader') {
46
+ const componentTypes = await OptiCMS.getContentTypesList(undefined, (ct) => {
47
+ if (!ct.key) // The key is required
48
+ return false;
49
+ if (ct.source === 'graph' || ct.source === 'globalcontract' || ct.source === '_system') // Only CMS managed types are allowed
50
+ return false;
51
+ //@ts-expect-error
52
+ if (ct.isContract) // Contracts must be ignored
53
+ return false;
54
+ return true;
55
+ });
56
+ const documents = [];
57
+ for (const componentType of componentTypes) {
58
+ const vLoc = generator_1.VirtualLocation.build(componentType, { type: 'fragment', forProperty: false });
59
+ if (vLoc) {
60
+ // Inject virtual location
61
+ const def = {};
62
+ def[vLoc] = { loader };
63
+ documents.push(def);
64
+ // Get properties
65
+ const propertyComponentTypeNames = generator_1.DocumentGenerator.getReferencedPropertyComponents(componentType);
66
+ const propertyComponentTypes = (await Promise.all(propertyComponentTypeNames.map(componentTypeName => OptiCMS.getContentType(componentTypeName)))).filter(utils_1.isNotNullOrUndefined);
67
+ for (const propertyComponentType of propertyComponentTypes) {
68
+ const propVLoc = generator_1.VirtualLocation.build(propertyComponentType, { type: 'fragment', forProperty: true });
69
+ if (propVLoc && !documents.some(x => typeof x === 'object' && x[propVLoc])) {
70
+ // Inject virtual location
71
+ const def = {};
72
+ def[propVLoc] = { loader };
73
+ documents.push(def);
74
+ }
75
+ }
76
+ }
77
+ }
78
+ return documents;
79
+ }
80
+ async function getInjectionTargetDocuments(loader = '@remkoj/optimizely-graph-functions/contenttype-loader') {
81
+ const documents = [];
82
+ for (const injectionTarget of generator_1.VirtualLocation.getInjectionTargets()) {
83
+ const vLoc = generator_1.VirtualLocation.build(injectionTarget);
84
+ const def = {};
85
+ def[vLoc] = { loader };
86
+ documents.push(def);
87
+ }
88
+ return documents;
89
+ }
90
+ async function injectInjectionTargets(files, options) {
51
91
  const allFragments = (0, tools_1.getAllFragments)(files);
52
- const allGraphTypes = (0, tools_1.getAllTypeNames)(options.schema);
53
92
  const addedFiles = [];
54
93
  if (options.presetConfig.verbose)
55
- console.log(`✨ [Optimizely] Generating injection target fragments that have not been defined by the implementation`);
56
- for (const injectionTarget of Object.getOwnPropertyNames(QueryGen.ContentTypeTarget)) {
94
+ console.log(`✨ [Optimizely] Generating injection target fragments`);
95
+ for (const injectionTarget of generator_1.VirtualLocation.getInjectionTargets()) {
57
96
  if (!allFragments.some(x => x.fragmentName === injectionTarget)) {
58
97
  const vLoc = `opti-cms:/injectiontarget/${injectionTarget}`;
59
98
  const rawSDL = `fragment ${injectionTarget} on _IContent { ...IContentData }`;
@@ -67,28 +106,44 @@ async function injectComponentDocuments(files, options) {
67
106
  });
68
107
  }
69
108
  }
109
+ return [...files, ...addedFiles];
110
+ }
111
+ /**
112
+ * Check all fragments within the project and ensure that there's at least a fragment for every
113
+ * content type defined in Optimizely CMS. This assumes that when overriding the fragments the
114
+ * project will ensure that the injections are correct.
115
+ *
116
+ * @param files
117
+ * @param options
118
+ * @returns
119
+ */
120
+ async function injectComponentDocuments(files, options) {
121
+ const allFragments = (0, tools_1.getAllFragments)(files);
122
+ const allGraphTypes = (0, tools_1.getAllTypeNames)(options.schema);
123
+ const addedFiles = [];
70
124
  if (options.presetConfig.verbose)
71
125
  console.log(`✨ [Optimizely] Generating component fragments that have not been defined by the implementation`);
72
- const allContentTypes = OptiCMS.getAllContentTypes(options.presetConfig.cmsClient, 100, (ct) => {
126
+ const allContentTypes = await OptiCMS.getContentTypes(options.presetConfig.cmsClient, (ct) => {
73
127
  return ct.key && ct.source !== 'graph' ? true : false;
74
128
  });
129
+ const queryGen = new generator_1.DocumentGenerator(allContentTypes);
75
130
  const propTracker = new Map();
76
- for await (const contentType of allContentTypes) {
131
+ for (const [_, contentType] of allContentTypes) {
77
132
  // Skip over content types without a key
78
133
  if (!contentType.key)
79
134
  continue;
80
135
  // Construct the type names expected to be in Graph
81
- const graphType = QueryGen.getGraphType(contentType);
82
- const graphPropertyType = QueryGen.getGraphPropertyType(contentType);
83
- const fragmentName = QueryGen.Tools.ucFirst(graphType) + "Data";
84
- const propertyFragmentName = QueryGen.Tools.ucFirst(graphPropertyType) + "Data";
136
+ const graphType = queryGen.getGraphType(contentType);
137
+ const graphPropertyType = queryGen.getGraphPropertyType(contentType);
138
+ const fragmentName = queryGen.getDefaultFragmentName(contentType);
139
+ const propertyFragmentName = queryGen.getDefaultPropertyFragmentName(contentType);
85
140
  // Check if the types exist
86
141
  const graphTypeExists = allGraphTypes.includes(graphType);
87
142
  const graphPropertyTypeExists = allGraphTypes.includes(graphPropertyType);
88
143
  // Add Component Data Fragment
89
144
  if (graphTypeExists && !allFragments.has(fragmentName)) {
90
- const rawSDL = QueryGen.buildFragment(contentType, fragmentName, false, propTracker);
91
- const vLoc = QueryGen.buildVirtualLocation(contentType);
145
+ const rawSDL = queryGen.buildFragment(contentType, fragmentName, false, propTracker);
146
+ const vLoc = generator_1.VirtualLocation.build(contentType);
92
147
  if (rawSDL) {
93
148
  if (options.presetConfig.verbose)
94
149
  console.log(` - Generated fragment ${fragmentName} for ${contentType.key} at ${vLoc}`);
@@ -102,8 +157,8 @@ async function injectComponentDocuments(files, options) {
102
157
  }
103
158
  // Add Component Property Data Fragment
104
159
  if (graphPropertyTypeExists && contentType.baseType === '_component' && !allFragments.has(propertyFragmentName)) {
105
- const rawSDL = QueryGen.buildFragment(contentType, propertyFragmentName, true, propTracker);
106
- const vLoc = QueryGen.buildVirtualLocation(contentType, { forProperty: true });
160
+ const rawSDL = queryGen.buildFragment(contentType, propertyFragmentName, true, propTracker);
161
+ const vLoc = generator_1.VirtualLocation.build(contentType, { forProperty: true });
107
162
  if (rawSDL) {
108
163
  if (options.presetConfig.verbose)
109
164
  console.log(` - Generated property fragment ${propertyFragmentName} for ${contentType.key} at ${vLoc}`);
@@ -1 +1 @@
1
- {"version":3,"file":"injectComponentDocuments.js","sourceRoot":"","sources":["../../src/_transform/injectComponentDocuments.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,4DAiFC;AAhGD,qCAA+B;AAC/B,gEAAiD;AACjD,gDAAiC;AAEjC,mCAA0D;AAE1D;;;;;;;;GAQG;AACI,KAAK,UAAU,wBAAwB,CAAC,KAA2B,EAAE,OAA0C;IACpH,MAAM,YAAY,GAAG,IAAA,uBAAe,EAAC,KAAK,CAAC,CAAA;IAC3C,MAAM,aAAa,GAAG,IAAA,uBAAe,EAAC,OAAO,CAAC,MAAM,CAAC,CAAA;IACrD,MAAM,UAAU,GAAyB,EAAE,CAAA;IAE3C,IAAI,OAAO,CAAC,YAAY,CAAC,OAAO;QAC9B,OAAO,CAAC,GAAG,CAAC,uGAAuG,CAAC,CAAA;IAEtH,KAAK,MAAM,eAAe,IAAI,MAAM,CAAC,mBAAmB,CAAC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,CAAC;QACrF,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,YAAY,KAAK,eAAe,CAAC,EAAE,CAAC;YAChE,MAAM,IAAI,GAAG,6BAA6B,eAAe,EAAE,CAAA;YAC3D,MAAM,MAAM,GAAG,YAAY,eAAe,mCAAmC,CAAA;YAC7E,IAAI,OAAO,CAAC,YAAY,CAAC,OAAO;gBAC9B,OAAO,CAAC,GAAG,CAAC,4BAA4B,eAAe,OAAO,IAAI,EAAE,CAAC,CAAA;YACvE,UAAU,CAAC,IAAI,CAAC;gBACd,MAAM;gBACN,QAAQ,EAAE,IAAA,eAAK,EAAC,MAAM,CAAC;gBACvB,QAAQ,EAAE,IAAI;gBACd,IAAI,EAAE,IAAI;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AED,kBAAe,wBAAwB,CAAA"}
@@ -1,4 +1,5 @@
1
1
  import type { Types } from '@graphql-codegen/plugin-helpers';
2
2
  import type { PresetOptions } from '../types';
3
+ export declare function getPageDocuments(loader?: string): Promise<Types.CustomDocumentLoader[]>;
3
4
  export declare function injectPageQueries(files: Types.DocumentFile[], options: Types.PresetFnArgs<PresetOptions>): Promise<Types.DocumentFile[]>;
4
5
  export default injectPageQueries;
@@ -33,25 +33,58 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.getPageDocuments = getPageDocuments;
36
37
  exports.injectPageQueries = injectPageQueries;
37
38
  const graphql_1 = require("graphql");
38
- const QueryGen = __importStar(require("../contenttype-loader"));
39
39
  const OptiCMS = __importStar(require("../cms"));
40
40
  const tools_1 = require("./tools");
41
+ const utils_1 = require("../utils");
42
+ const generator_1 = require("../generator");
43
+ async function getPageDocuments(loader = '@remkoj/optimizely-graph-functions/contenttype-loader') {
44
+ const pageTypes = OptiCMS.getContentTypesList(undefined, (ct) => {
45
+ if (ct.source == "graph")
46
+ return false;
47
+ return ["_page", "_experience"].includes((ct.baseType || "").toLowerCase());
48
+ });
49
+ const documents = [];
50
+ for (const pageType of await pageTypes) {
51
+ const vLoc = generator_1.VirtualLocation.build(pageType, { type: 'query' });
52
+ if (vLoc) {
53
+ const def = {};
54
+ def[vLoc] = { loader };
55
+ documents.push(def);
56
+ }
57
+ // Get properties
58
+ const propertyComponentTypeNames = generator_1.DocumentGenerator.getReferencedPropertyComponents(pageType);
59
+ const propertyComponentTypes = (await Promise.all(propertyComponentTypeNames.map(componentTypeName => OptiCMS.getContentType(componentTypeName)))).filter(utils_1.isNotNullOrUndefined);
60
+ for (const propertyComponentType of propertyComponentTypes) {
61
+ const propVLoc = generator_1.VirtualLocation.build(propertyComponentType, { type: 'fragment', forProperty: true });
62
+ if (propVLoc && !documents.some(x => typeof x === 'object' && x[propVLoc])) {
63
+ // Inject virtual location
64
+ const def = {};
65
+ def[propVLoc] = { loader };
66
+ documents.push(def);
67
+ }
68
+ }
69
+ }
70
+ return documents;
71
+ }
41
72
  async function injectPageQueries(files, options) {
42
73
  if (options.presetConfig.verbose)
43
74
  console.log(`✨ [Optimizely] Generating page queries that have not been defined by the implementation`);
44
75
  const existingQueries = (0, tools_1.getAllQueries)(files);
45
76
  const existingTypes = (0, tools_1.getAllTypeNames)(options.schema);
46
- const pageLevelTypes = OptiCMS.getAllContentTypes(undefined, 100, (ct) => {
77
+ const allTypes = OptiCMS.getContentTypes(undefined);
78
+ const pageLevelTypes = OptiCMS.getContentTypesList(undefined, (ct) => {
47
79
  if (ct.source == "graph")
48
80
  return false;
49
81
  return ["_page", "_experience"].includes((ct.baseType || "").toLowerCase());
50
82
  });
83
+ const queryGen = new generator_1.DocumentGenerator(await allTypes);
51
84
  const newFiles = [];
52
- for await (const pageContentType of pageLevelTypes) {
53
- const graphDataType = QueryGen.getGraphType(pageContentType);
54
- const queryName = `get${QueryGen.Tools.ucFirst(graphDataType)}Data`;
85
+ for (const pageContentType of await pageLevelTypes) {
86
+ const graphDataType = queryGen.getGraphType(pageContentType);
87
+ const queryName = queryGen.getDefaultQueryName(pageContentType);
55
88
  // Check if the type exists in the Schema, if not skip it
56
89
  if (!existingTypes.includes(graphDataType)) {
57
90
  if (options.presetConfig.verbose)
@@ -64,8 +97,8 @@ async function injectPageQueries(files, options) {
64
97
  console.log(` - Skipping query generation for ${pageContentType.key}, the project already includes a definition for ${queryName}`);
65
98
  continue;
66
99
  }
67
- const rawSDL = QueryGen.buildGetQuery(pageContentType, queryName);
68
- const vLoc = QueryGen.buildVirtualLocation(pageContentType, { type: 'query' });
100
+ const rawSDL = queryGen.buildGetQuery(pageContentType, queryName);
101
+ const vLoc = generator_1.VirtualLocation.build(pageContentType, { type: 'query' });
69
102
  if (options.presetConfig.verbose)
70
103
  console.log(` - Generated query for ${pageContentType.key} at ${vLoc}`);
71
104
  newFiles.push({
@@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mB,CAAC,eAAe,CAAC,CAAA;QAE/D,yDAAyD;QACzD,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,CAAC;YAC3C,IAAI,OAAO,CAAC,YAAY,CAAC,OAAO;gBAC9B,OAAO,CAAC,GAAG,CAAC,uCAAuC,eAAe,CAAC,GAAG,0CAA0C,aAAa,EAAE,CAAC,CAAA;YAClI,SAAQ;QACV,CAAC;QAED,6DAA6D;QAC7D,IAAI,eAAe,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC;YACnC,IAAI,OAAO,CAAC,YAAY,CAAC,OAAO;gBAC9B,OAAO,CAAC,GAAG,CAAC,uCAAuC,eAAe,CAAC,GAAG,mDAAmD,SAAS,EAAE,CAAC,CAAA;YACvI,SAAQ;QACV,CAAC;QAED,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,CAAC,eAAe,EAAE,SAAS,CAAC,CAAA;QACjE,MAAM,IAAI,GAAG,2BAAe,CAAC,KAAK,CAAC,eAAe,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAA;QACtE,IAAI,OAAO,CAAC,YAAY,CAAC,OAAO;YAC9B,OAAO,CAAC,GAAG,CAAC,6BAA6B,eAAe,CAAC,GAAG,OAAO,IAAI,EAAE,CAAC,CAAA;QAE5E,QAAQ,CAAC,IAAI,CAAC;YACZ,MAAM;YACN,QAAQ,EAAE,IAAA,eAAK,EAAC,MAAM,CAAC;YACvB,QAAQ,EAAE,IAAI;YACd,IAAI,EAAE,IAAI;SACX,CAAC,CAAA;IACJ,CAAC;IAED,OAAO,CAAC,GAAG,KAAK,EAAE,GAAG,QAAQ,CAAC,CAAA;AAChC,CAAC;AAED,kBAAe,iBAAiB,CAAA"}
@@ -1,4 +1,5 @@
1
1
  import type { Types } from '@graphql-codegen/plugin-helpers';
2
2
  import type { PresetOptions } from '../types';
3
+ export declare function getSectionDocuments(loader?: string): Promise<Types.CustomDocumentLoader[]>;
3
4
  export declare function injectSectionQueries(files: Types.DocumentFile[], options: Types.PresetFnArgs<PresetOptions>): Promise<Types.DocumentFile[]>;
4
5
  export default injectSectionQueries;