@remkoj/optimizely-graph-functions 1.0.2 → 1.0.3

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.
package/dist/src/index.js DELETED
@@ -1,138 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.plugin = exports.validate = exports.pickPluginOptions = void 0;
4
- const graphql_1 = require("graphql");
5
- const utils_1 = require("./utils");
6
- function pickPluginOptions(options) {
7
- return {
8
- functions: options.functions ?? ['getContentByPath', 'getContentById'],
9
- prettyPrintQuery: options.prettyPrintQuery ?? false,
10
- clientPath: options.clientPath ?? "./graphql"
11
- };
12
- }
13
- exports.pickPluginOptions = pickPluginOptions;
14
- /**
15
- * Validate the plugin configuration
16
- *
17
- * @param schema
18
- * @param document
19
- * @param config
20
- * @param outputFile
21
- * @param allPlugins
22
- * @param pluginContext
23
- */
24
- const validate = (schema, document, config, outputFile, allPlugins, pluginContext) => {
25
- if (config.functions) {
26
- if (!Array.isArray(config.functions))
27
- throw new Error("If provided functions must be an array");
28
- if (config.functions.some(x => typeof (x) != 'string' || x.length == 0))
29
- throw new Error("If provided functions must only contain non-empty strings");
30
- }
31
- };
32
- exports.validate = validate;
33
- /**
34
- * Actual Plugin logic
35
- *
36
- * @param schema
37
- * @param documents
38
- * @param config
39
- * @param info
40
- * @returns
41
- */
42
- const plugin = async (schema, documents, config, info) => {
43
- // Read the functions to fully build & extend
44
- const functions = config.functions || [];
45
- if (functions.length == 0)
46
- return "// NO FUNCTIONS TO BE EXPORTED";
47
- // Output the functions
48
- const docs = (0, graphql_1.concatAST)(documents.map(x => x.document).filter(utils_1.isNotNullOrUndefined));
49
- const output = functions.map(fn => {
50
- try {
51
- const queryNode = (0, graphql_1.getOperationAST)(docs, fn);
52
- if (!(queryNode && queryNode.operation == graphql_1.OperationTypeNode.QUERY))
53
- return [`export async function ${fn}() { throw new Error('No query named ${fn} defined')}`];
54
- const fragments = resolveSpreads(queryNode, docs);
55
- const fnTypeName = fn.charAt(0).toUpperCase() + fn.slice(1);
56
- const varsType = `Types.${fnTypeName}QueryVariables`;
57
- const returnType = `Types.${fnTypeName}Query`;
58
- const query = [queryNode, ...fragments].map(node => (0, graphql_1.print)(node)).join("\n\n");
59
- const functionBody = [];
60
- functionBody.push(`export function ${fn}(client: GraphQLClient, variables: ${varsType}) : Promise<${returnType}>`);
61
- functionBody.push('{');
62
- functionBody.push(` const query = gql\`${config.prettyPrintQuery ? query : query.replace(/\s+/g, ' ').trim()}\``);
63
- functionBody.push(` return client.request<${returnType}, ${varsType}>(query, variables)`);
64
- functionBody.push('}');
65
- return functionBody;
66
- }
67
- catch (e) {
68
- return [`export async function ${fn}() { throw new Error('Function generation error')}`];
69
- }
70
- }).flat();
71
- const prepend = [];
72
- const append = [];
73
- prepend.push('import { gql, type GraphQLClient } from \'graphql-request\'');
74
- prepend.push('import { ContentGraphClient as BaseGraphClient } from \'@remkoj/optimizely-graph-client\'');
75
- prepend.push(`import type * as Types from './graphql'`);
76
- prepend.push("\n");
77
- append.push("\n\n");
78
- append.push(generateClientClass(functions));
79
- return { prepend, content: output.join("\n"), append };
80
- };
81
- exports.plugin = plugin;
82
- function resolveSpreads(definition, document, availableFragments = []) {
83
- // Collect the fragment names we need to add
84
- const spreadNames = [];
85
- (0, graphql_1.visit)(definition, {
86
- "FragmentSpread": {
87
- leave(node) {
88
- if (!availableFragments.includes(node.name.value))
89
- spreadNames.push(node.name.value);
90
- }
91
- }
92
- });
93
- // Collect these fragments from the document
94
- const fragments = [];
95
- (0, graphql_1.visit)(document, {
96
- FragmentDefinition: {
97
- leave(node) {
98
- if (spreadNames.includes(node.name.value))
99
- fragments.push(node);
100
- }
101
- }
102
- });
103
- // Recurse down the fragments to build the full query
104
- const dependencies = [];
105
- const availableFragmentNames = [...availableFragments, ...fragments.map(x => x.name.value)];
106
- fragments.forEach(fragment => {
107
- // Set the available names based on what was previously available, loaded above and loaded within this loop
108
- const resolvedSpreads = [...availableFragmentNames, ...dependencies.map(x => x.name.value)];
109
- // Recurse into fragments
110
- const fragmentDependencies = resolveSpreads(fragment, document, resolvedSpreads);
111
- dependencies.push(...fragmentDependencies);
112
- });
113
- return [...fragments, ...dependencies];
114
- }
115
- function generateClientClass(functions) {
116
- return `/**
117
- * Function client for Optimizely Graph, exposing both the raw request method,
118
- * as well as the high level convenience methods to read content from
119
- * Optimizely Graph. The actual format for each of the Content Items returned
120
- * by these convenience methods is defined by the GraphQL Fragments within the
121
- * application codebase.
122
- */
123
- export class OptimizelyGraphClient extends BaseGraphClient {
124
-
125
- ${functions.map(fn => {
126
- const fnTypeName = fn.charAt(0).toUpperCase() + fn.slice(1);
127
- const fnNamespace = "Types";
128
- const varsType = `${fnNamespace}.${fnTypeName}QueryVariables`;
129
- const returnType = `${fnNamespace}.${fnTypeName}Query`;
130
- return ` public ${fn}(variables: ${varsType}) : Promise<${returnType}>
131
- {
132
- return ${fn}(this, variables)
133
- }`;
134
- }).join('\n\n')}
135
- }`;
136
- }
137
- exports.default = { validate: exports.validate, plugin: exports.plugin };
138
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AACA,qCAAgK;AAChK,mCAAwE;AAQxE,SAAgB,iBAAiB,CAAC,OAA2B;IAEzD,OAAO;QACH,SAAS,EAAE,OAAO,CAAC,SAAS,IAAI,CAAE,kBAAkB,EAAE,gBAAgB,CAAE;QACxE,gBAAgB,EAAE,OAAO,CAAC,gBAAgB,IAAI,KAAK;QACnD,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,WAAW;KAChD,CAAA;AACL,CAAC;AAPD,8CAOC;AAED;;;;;;;;;GASG;AACI,MAAM,QAAQ,GAAoC,CAAC,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,UAAU,EAAE,aAAa,EAAE,EAAE;IAEzH,IAAI,MAAM,CAAC,SAAS,EAAE,CAA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S,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;QACzB,2GAA2G;QAC3G,MAAM,eAAe,GAAG,CAAE,GAAG,sBAAsB,EAAE,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAA;QAE5F,yBAAyB;QACzB,MAAM,oBAAoB,GAAG,cAAc,CAAC,QAAQ,EAAE,QAAQ,EAAE,eAAe,CAAC,CAAA;QAChF,YAAY,CAAC,IAAI,CAAC,GAAG,oBAAoB,CAAC,CAAA;IAC9C,CAAC,CAAC,CAAA;IACF,OAAO,CAAE,GAAG,SAAS,EAAE,GAAG,YAAY,CAAC,CAAA;AAC3C,CAAC;AAED,SAAS,mBAAmB,CAAC,SAAmB;IAE5C,OAAO;;;;;;;;;EASR,SAAS,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE;QAClB,MAAM,UAAU,GAAG,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;QAC3D,MAAM,WAAW,GAAG,OAAO,CAAA;QAC3B,MAAM,QAAQ,GAAG,GAAI,WAAY,IAAK,UAAW,gBAAgB,CAAA;QACjE,MAAM,UAAU,GAAG,GAAI,WAAY,IAAK,UAAW,OAAO,CAAA;QAC1D,OAAO,cAAe,EAAG,eAAgB,QAAQ,eAAgB,UAAW;;iBAE9D,EAAG;MACf,CAAA;IAAA,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC;EACnB,CAAA;AACF,CAAC;AAED,kBAAe,EAAE,QAAQ,EAAR,gBAAQ,EAAE,MAAM,EAAN,cAAM,EAAkC,CAAA"}
@@ -1,7 +0,0 @@
1
- import type { Types } from '@graphql-codegen/plugin-helpers';
2
- import { type ClientPresetConfig as ClientPresetOptions } from '@graphql-codegen/client-preset';
3
- import { type PluginOptions } from './index';
4
- import { type TransformOptions } from './transform';
5
- export type PresetOptions = ClientPresetOptions & PluginOptions & TransformOptions;
6
- export declare const preset: Types.OutputPreset<PresetOptions>;
7
- export default preset;
@@ -1,79 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.preset = void 0;
27
- const documents_1 = require("./documents");
28
- // Import base preset
29
- const client_preset_1 = require("@graphql-codegen/client-preset");
30
- // Import injected parts
31
- const index_1 = __importStar(require("./index"));
32
- const transform_1 = __importStar(require("./transform"));
33
- exports.preset = {
34
- prepareDocuments: async (outputFilePath, outputSpecificDocuments) => {
35
- // Get the base documents
36
- const documents = client_preset_1.preset.prepareDocuments ? await client_preset_1.preset.prepareDocuments(outputFilePath, outputSpecificDocuments) : [...outputSpecificDocuments, `!${outputFilePath}`];
37
- // Then add the implicit documents to it
38
- documents.push([...documents_1.fragments, ...documents_1.queries].join("\n"));
39
- // Finally return the extended array
40
- return documents;
41
- },
42
- buildGeneratesSection: async (options) => {
43
- options.documentTransforms = [
44
- {
45
- name: 'optly-transform',
46
- transformObject: transform_1.default,
47
- config: (0, transform_1.pickTransformOptions)(options.presetConfig)
48
- }
49
- ];
50
- const section = await client_preset_1.preset.buildGeneratesSection(options);
51
- // Add the functions file
52
- section.push({
53
- filename: `${options.baseOutputDir}functions.ts`,
54
- pluginMap: {
55
- ['optly-functions']: index_1.default
56
- },
57
- plugins: [
58
- {
59
- ['optly-functions']: {}
60
- }
61
- ],
62
- schema: options.schema,
63
- config: (0, index_1.pickPluginOptions)(options.presetConfig),
64
- documents: options.documents,
65
- documentTransforms: options.documentTransforms
66
- });
67
- // Add functions to index plugin
68
- section.forEach((fileConfig, idx) => {
69
- if (fileConfig.filename.endsWith("index.ts")) {
70
- const currentContent = section[idx].plugins[0]?.add?.content;
71
- if (currentContent)
72
- section[idx].plugins[0].add.content = `export * as Schema from "./graphql";\n${currentContent}\nexport * from "./functions";`;
73
- }
74
- });
75
- return section;
76
- },
77
- };
78
- exports.default = exports.preset;
79
- //# sourceMappingURL=preset.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"preset.js","sourceRoot":"","sources":["../../src/preset.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,2CAAgD;AAEhD,qBAAqB;AACrB,kEAAuH;AAEvH,wBAAwB;AACxB,iDAAuE;AACvE,yDAAoF;AAKvE,QAAA,MAAM,GACnB;IACI,gBAAgB,EAAE,KAAK,EAAE,cAAc,EAAE,uBAAuB,EAAE,EAAE;QAChE,yBAAyB;QACzB,MAAM,SAAS,GAAG,sBAAY,CAAC,gBAAgB,CAAC,CAAC,CAAC,MAAM,sBAAY,CAAC,gBAAgB,CAAC,cAAc,EAAE,uBAAuB,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,uBAAuB,EAAE,IAAI,cAAc,EAAE,CAAC,CAAA;QAEnL,wCAAwC;QACxC,SAAS,CAAC,IAAI,CAAC,CAAC,GAAG,qBAAS,EAAE,GAAG,mBAAO,CAAC,CAAC,IAAI,CAAC,IAAI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AAA;QAEF,OAAO,OAAO,CAAA;IAClB,CAAC;CACJ,CAAA;AAED,kBAAe,cAAM,CAAA"}
@@ -1,11 +0,0 @@
1
- import type { Types } from '@graphql-codegen/plugin-helpers';
2
- import type { Injection } from './types';
3
- export type TransformOptions = {
4
- injections?: Injection[];
5
- };
6
- export declare function pickTransformOptions(options: Record<string, any>): TransformOptions;
7
- export declare const transform: Types.DocumentTransformFunction<TransformOptions>;
8
- declare const _default: {
9
- transform: Types.DocumentTransformFunction<TransformOptions>;
10
- };
11
- export default _default;
@@ -1,136 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.transform = exports.pickTransformOptions = void 0;
4
- const graphql_1 = require("graphql");
5
- function pickTransformOptions(options) {
6
- return {
7
- injections: options.injections ?? []
8
- };
9
- }
10
- exports.pickTransformOptions = pickTransformOptions;
11
- function isArray(toTest) { return Array.isArray(toTest); }
12
- const transform = async ({ documents: files, config }) => {
13
- //console.log("[STARTED] Optimizely document transformation")
14
- const injections = config.injections ?? [];
15
- // Retrieve component fragments
16
- const componentFragments = {};
17
- files.forEach(file => {
18
- if (!file.document)
19
- return;
20
- const applicableInjections = injections.filter(injection => !injection.pathRegex || (new RegExp(injection.pathRegex)).test(file.location ?? ""));
21
- if (!applicableInjections || applicableInjections.length == 0)
22
- return;
23
- (0, graphql_1.visit)(file.document, {
24
- "FragmentDefinition": {
25
- enter(node) {
26
- const matchingInjections = applicableInjections.filter(injection => !injection.nameRegex || (new RegExp(injection.nameRegex)).test(node.name.value));
27
- if (!matchingInjections || matchingInjections.length == 0)
28
- return false;
29
- matchingInjections.forEach(injection => {
30
- //console.log(`[ DEBUG ] Matched ${ node.name.value } for ${ injection.into } in file ${ node.loc?.source?.name }`)
31
- if (!componentFragments[injection.into])
32
- componentFragments[injection.into] = [];
33
- if (!componentFragments[injection.into].some(f => f.name.value == node.name.value))
34
- componentFragments[injection.into].push(node);
35
- });
36
- return undefined;
37
- }
38
- }
39
- });
40
- });
41
- // Get the names we actually need to inject into, and return when none are present
42
- const intoNames = Object.getOwnPropertyNames(componentFragments);
43
- if (intoNames.length == 0)
44
- return files;
45
- // Process the fragments, add matching spreads if need be
46
- const recursiveFragments = ["BlockContentAreaItemSearchData", "BlockContentAreaItemData"];
47
- const componentSpreads = {};
48
- intoNames.forEach(intoName => {
49
- //console.log(`[ DEBUG ] Preparing mutations for ${ intoName }`)
50
- componentFragments[intoName].forEach(fragment => {
51
- //console.log(`[ DEBUG ] Preparing mutations for fragment ${ fragment.name.value } within ${ intoName }`)
52
- (0, graphql_1.visit)(fragment, {
53
- "FragmentSpread": {
54
- leave(node, key, parent, path, ancestors) {
55
- if (recursiveFragments.includes(node.name.value) && !isArray(ancestors[0]) && ancestors[0].kind == graphql_1.Kind.FRAGMENT_DEFINITION) {
56
- //console.log(`[ DEBUG ] Leaving ${ node.name.value } within ${ fragment.name.value } for ${ intoName}, creating recursive fragment`)
57
- const fields = ancestors.filter(a => !isArray(a) && a.kind != graphql_1.Kind.FRAGMENT_DEFINITION && a.kind != graphql_1.Kind.SELECTION_SET);
58
- if (fields.length < 1)
59
- return undefined;
60
- if (fields.length > 1)
61
- throw new Error("Recursive items on embedded blocks are not supported at the moment");
62
- const newNode = {
63
- kind: graphql_1.Kind.INLINE_FRAGMENT,
64
- typeCondition: ancestors[0].typeCondition,
65
- selectionSet: {
66
- kind: graphql_1.Kind.SELECTION_SET,
67
- selections: [{
68
- kind: graphql_1.Kind.FIELD,
69
- name: fields[0].name,
70
- alias: fields[0].alias,
71
- selectionSet: {
72
- kind: graphql_1.Kind.SELECTION_SET,
73
- selections: recursiveSelections
74
- }
75
- }]
76
- }
77
- };
78
- if (!componentSpreads[intoName])
79
- componentSpreads[intoName] = [];
80
- componentSpreads[intoName].push(newNode);
81
- }
82
- }
83
- }
84
- });
85
- });
86
- });
87
- const newFiles = files.map(file => {
88
- const document = file.document ? (0, graphql_1.visit)(file.document, {
89
- SelectionSet: {
90
- enter(node, key, parent) {
91
- if (!isArray(parent) && parent?.kind == graphql_1.Kind.FRAGMENT_DEFINITION && intoNames.includes(parent.name.value)) {
92
- const addedSelections = componentFragments[parent.name.value].map(fragment => {
93
- return {
94
- kind: graphql_1.Kind.FRAGMENT_SPREAD,
95
- directives: [],
96
- name: {
97
- kind: graphql_1.Kind.NAME,
98
- value: fragment.name.value
99
- }
100
- };
101
- });
102
- componentSpreads[parent.name.value]?.forEach(spread => {
103
- //console.log("[ DEBUG ] Pushing inline fragment for", parent.name.value)
104
- addedSelections.push(spread);
105
- });
106
- return {
107
- ...node,
108
- selections: [
109
- ...node.selections,
110
- ...addedSelections
111
- ]
112
- };
113
- }
114
- return undefined;
115
- }
116
- }
117
- }) : undefined;
118
- return {
119
- ...file,
120
- document: document,
121
- };
122
- });
123
- //console.log("[SUCCESS] Optimizely document transformation")
124
- return newFiles;
125
- };
126
- exports.transform = transform;
127
- exports.default = { transform: exports.transform };
128
- // The recursive sections to add
129
- const recursiveSelections = (0, graphql_1.parse)(`fragment BlockContentAreaItemData on ContentAreaItemModel {
130
- item: ContentLink {
131
- data: Expanded @recursive(depth: 3) {
132
- __typename
133
- }
134
- }
135
- }`).definitions[0]?.selectionSet.selections || [];
136
- //# sourceMappingURL=transform.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"transform.js","sourceRoot":"","sources":["../../src/transform.ts"],"names":[],"mappings":";;;AAGA,qCAA4C;AAM5C,SAAgB,oBAAoB,CAAC,OAA2B;IAE5D,OAAO;QACH,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,EAAE;KACvC,CAAA;AACL,CAAC;AALD,oDAKC;AAED,SAAS,OAAO,CAAI,MAAyB,IAA6B,OAAO,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAA,CAAC,CAAC;AAEjG,MAAM,SAAS,GAAuD,KAAK,EAAE,EAAC,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE;IAE/G,6DAA6D;IAC7D,MAAM,UAAU,GAAG,MAA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ionNode, OperationDefinitionNode } from 'graphql';
2
- export type Injection = {
3
- into: string;
4
- nameRegex?: string;
5
- pathRegex?: string;
6
- };
7
- export type IntoMatchType = {
8
- docId: number;
9
- path?: string;
10
- match: {
11
- defId: number;
12
- data: OperationDefinitionNode | FragmentDefinitionNode;
13
- } | null;
14
- };
15
- export type Mandatory<T> = {
16
- [P in keyof T]-?: NonNullable<T[P]>;
17
- };
18
- export type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Pick<Mandatory<T>, K>;
19
- export type Writeable<T> = {
20
- -readonly [P in keyof T]: T[P];
21
- };
package/dist/src/types.js DELETED
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=types.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":""}
@@ -1,8 +0,0 @@
1
- import type { DefinitionNode, FragmentDefinitionNode, OperationDefinitionNode } from 'graphql';
2
- import type { IntoMatchType, WithRequiredProp } from './types';
3
- import type { PluginOptions } from './index';
4
- export declare function isNotNullOrUndefined<T>(toTest: T | null | undefined): toTest is T;
5
- export declare function isFragmentDefinitionNode(node?: DefinitionNode): node is FragmentDefinitionNode;
6
- export declare function isSelectionDefinitionNode(node?: DefinitionNode): node is FragmentDefinitionNode | OperationDefinitionNode;
7
- export declare function isIntoMatch(toTest: IntoMatchType | null | undefined): toTest is WithRequiredProp<IntoMatchType, 'match'>;
8
- export declare function extractPluginConfigAndApplyDefaults(baseConfig: Record<string, any>, defaultValues: Partial<PluginOptions>): Partial<PluginOptions>;
package/dist/src/utils.js DELETED
@@ -1,38 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.extractPluginConfigAndApplyDefaults = exports.isIntoMatch = exports.isSelectionDefinitionNode = exports.isFragmentDefinitionNode = exports.isNotNullOrUndefined = void 0;
4
- const graphql_1 = require("graphql");
5
- function isNotNullOrUndefined(toTest) {
6
- return toTest ? true : false;
7
- }
8
- exports.isNotNullOrUndefined = isNotNullOrUndefined;
9
- function isFragmentDefinitionNode(node) {
10
- return node?.kind == graphql_1.Kind.FRAGMENT_DEFINITION && node.name.value ? true : false;
11
- }
12
- exports.isFragmentDefinitionNode = isFragmentDefinitionNode;
13
- function isSelectionDefinitionNode(node) {
14
- return node?.kind == graphql_1.Kind.OPERATION_DEFINITION || node?.kind == graphql_1.Kind.FRAGMENT_DEFINITION;
15
- }
16
- exports.isSelectionDefinitionNode = isSelectionDefinitionNode;
17
- function isIntoMatch(toTest) {
18
- if (!toTest)
19
- return false;
20
- return toTest.match ? true : false;
21
- }
22
- exports.isIntoMatch = isIntoMatch;
23
- function extractPluginConfigAndApplyDefaults(baseConfig, defaultValues) {
24
- const extractedConfig = {
25
- clientPath: baseConfig?.clientPath || undefined,
26
- functions: baseConfig?.functions || undefined,
27
- prettyPrintQuery: baseConfig?.prettyPrintQuery || undefined
28
- };
29
- for (const propName of Object.getOwnPropertyNames(extractedConfig))
30
- if (extractedConfig[propName] == null || extractedConfig[propName] == undefined)
31
- delete extractedConfig[propName];
32
- return {
33
- ...defaultValues,
34
- ...extractedConfig
35
- };
36
- }
37
- exports.extractPluginConfigAndApplyDefaults = extractPluginConfigAndApplyDefaults;
38
- //# sourceMappingURL=utils.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";;;AAGA,qCAA8B;AAE9B,SAAgB,oBAAoB,CAAI,MAA4B;IAEhE,OAAO,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAA;AAChC,CAAC;AAHD,oDAGC;AAED,SAAgB,wBAAwB,CAAE,IAAqB;IAE3D,OAAO,IAAI,EAAE,IAAI,IAAI,cAAI,CAAC,mBAAmB,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,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