@shopify/hydrogen-codegen 0.2.1 → 0.3.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.
@@ -1,19 +1,22 @@
1
1
  import {createRequire} from 'module'; const require = createRequire(import.meta.url);
2
- const getSchema = (api = "storefront") => {
2
+ function getSchema(api, options) {
3
3
  if (api !== "storefront" && api !== "customer-account") {
4
4
  throw new Error(
5
5
  `The provided API type "${api}" is unknown. Please use "storefront" or "customer-account".`
6
6
  );
7
7
  }
8
- return require.resolve(`@shopify/hydrogen-react/${api}.schema.json`);
9
- };
10
- let staticSFAPISchema = "";
11
- try {
12
- staticSFAPISchema = getSchema("storefront");
13
- } catch (error) {
8
+ try {
9
+ return require.resolve(`@shopify/hydrogen-react/${api}.schema.json`);
10
+ } catch {
11
+ if (options?.throwIfMissing !== false) {
12
+ throw new Error(
13
+ `Could not find a schema for "${api}".
14
+ Please make sure a recent version of \`@shopify/hydrogen\` is installed.`
15
+ );
16
+ }
17
+ }
14
18
  }
15
- const schema = staticSFAPISchema;
16
19
 
17
- export { getSchema, schema };
20
+ export { getSchema };
18
21
  //# sourceMappingURL=out.js.map
19
22
  //# sourceMappingURL=schema.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/schema.ts"],"names":[],"mappings":"AACA;AAQO,MAAM,YAAY,CACvB,MAAM,iBACH;AACH,MAAI,QAAQ,gBAAgB,QAAQ,oBAAoB;AACtD,UAAM,IAAI;AAAA,MACR,0BAA0B,GAAG;AAAA,IAC/B;AAAA,EACF;AAEA,SAAO,QAAQ,QAAQ,2BAA2B,GAAG,cAAc;AACrE;AAEA,IAAI,oBAAoB;AAExB,IAAI;AACF,sBAAoB,UAAU,YAAY;AAC5C,SAAS,OAAO;AAIhB;AAKO,MAAM,SAAS","sourcesContent":["// This comment is used during ESM build:\n//! import {createRequire} from 'module'; const require = createRequire(import.meta.url);\n\n/**\n * Resolves a schema path for the provided API type. Only the API types currently\n * bundled in Hydrogen are allowed: \"storefront\" and \"customer\".\n * @param api\n * @returns\n */\nexport const getSchema = (\n api = 'storefront' as 'storefront' | 'customer-account',\n) => {\n if (api !== 'storefront' && api !== 'customer-account') {\n throw new Error(\n `The provided API type \"${api}\" is unknown. Please use \"storefront\" or \"customer-account\".`,\n );\n }\n\n return require.resolve(`@shopify/hydrogen-react/${api}.schema.json`);\n};\n\nlet staticSFAPISchema = '';\n\ntry {\n staticSFAPISchema = getSchema('storefront');\n} catch (error) {\n // This can happen at build time or when '@shopify/hydrogen-react' is not found.\n // Generally this shouldn't be an issue in real apps so let's ignore the error.\n // Also, this package could be used in non-Hydrogen apps.\n}\n\n/**\n * The resolved schema path for the Storefront API.\n */\nexport const schema = staticSFAPISchema;\n"]}
1
+ {"version":3,"sources":["../../src/schema.ts"],"names":[],"mappings":"AACA;AAgBO,SAAS,UAAU,KAAU,SAA4B;AAC9D,MAAI,QAAQ,gBAAgB,QAAQ,oBAAoB;AACtD,UAAM,IAAI;AAAA,MACR,0BAA0B,GAAG;AAAA,IAC/B;AAAA,EACF;AAEA,MAAI;AACF,WAAO,QAAQ,QAAQ,2BAA2B,GAAG,cAAc;AAAA,EACrE,QAAQ;AACN,QAAI,SAAS,mBAAmB,OAAO;AACrC,YAAM,IAAI;AAAA,QACR,gCAAgC,GAAG;AAAA;AAAA,MACrC;AAAA,IACF;AAAA,EACF;AACF","sourcesContent":["// This comment is used during ESM build:\n//! import {createRequire} from 'module'; const require = createRequire(import.meta.url);\n\ntype Api = 'storefront' | 'customer-account';\ntype Options<T extends boolean> = {throwIfMissing?: T};\n\n/**\n * Resolves a schema path for the provided API type. Only the API types currently\n * bundled in Hydrogen are allowed: \"storefront\" and \"customer\".\n * @param api\n * @returns\n */\nexport function getSchema(api: Api, options?: Options<true>): string;\nexport function getSchema(\n api: Api,\n options: Options<false>,\n): string | undefined;\nexport function getSchema(api: Api, options?: Options<boolean>) {\n if (api !== 'storefront' && api !== 'customer-account') {\n throw new Error(\n `The provided API type \"${api}\" is unknown. Please use \"storefront\" or \"customer-account\".`,\n );\n }\n\n try {\n return require.resolve(`@shopify/hydrogen-react/${api}.schema.json`);\n } catch {\n if (options?.throwIfMissing !== false) {\n throw new Error(\n `Could not find a schema for \"${api}\".\\nPlease make sure a recent version of \\`@shopify/hydrogen\\` is installed.`,\n );\n }\n }\n}\n"]}
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "access": "public",
5
5
  "@shopify:registry": "https://registry.npmjs.org"
6
6
  },
7
- "version": "0.2.1",
7
+ "version": "0.3.0",
8
8
  "license": "MIT",
9
9
  "type": "module",
10
10
  "main": "dist/cjs/index.cjs",
@@ -25,12 +25,6 @@
25
25
  "import": "./dist/esm/index.js",
26
26
  "default": "./dist/esm/index.js"
27
27
  },
28
- "./patch": {
29
- "types": "./dist/esm/patch.d.ts",
30
- "require": "./dist/cjs/patch.cjs",
31
- "import": "./dist/esm/patch.js",
32
- "default": "./dist/esm/patch.js"
33
- },
34
28
  "./package.json": "./package.json"
35
29
  },
36
30
  "repository": {
@@ -44,16 +38,11 @@
44
38
  "devDependencies": {
45
39
  "@graphql-codegen/cli": "^5.0.1",
46
40
  "@graphql-codegen/plugin-helpers": "^5.0.2",
47
- "@graphql-tools/utils": "^10.0.13",
41
+ "dts-bundle-generator": "^9.3.1",
42
+ "type-fest": "^4.5.0",
48
43
  "vitest": "^1.0.4"
49
44
  },
50
45
  "dependencies": {
51
- "@graphql-codegen/add": "^5.0.1",
52
- "@graphql-codegen/typescript": "^4.0.2",
53
- "@graphql-codegen/typescript-operations": "^4.1.0",
54
- "type-fest": "^4.5.0"
55
- },
56
- "peerDependencies": {
57
- "graphql": "^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0"
46
+ "@shopify/graphql-codegen": "^0.0.1"
58
47
  }
59
48
  }
@@ -1,4 +0,0 @@
1
- 'use strict';
2
-
3
- //# sourceMappingURL=out.js.map
4
- //# sourceMappingURL=client.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"names":[],"mappings":""}
@@ -1,4 +0,0 @@
1
- 'use strict';
2
-
3
- //# sourceMappingURL=out.js.map
4
- //# sourceMappingURL=patch.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"names":[],"mappings":""}
@@ -1,39 +0,0 @@
1
- 'use strict';
2
-
3
- const pluckConfig = {
4
- /**
5
- * Hook to determine if a node is a gql template literal.
6
- * By default, graphql-tag-pluck only looks for leading comments or `gql` tag.
7
- */
8
- isGqlTemplateLiteral: (node, options) => {
9
- const hasInternalGqlComment = node.type === "TemplateLiteral" && /\s*#graphql\s*\n/i.test(node.quasis[0]?.value?.raw || "");
10
- if (hasInternalGqlComment)
11
- return true;
12
- const { leadingComments } = node;
13
- const leadingComment = leadingComments?.[leadingComments?.length - 1];
14
- const leadingCommentValue = leadingComment?.value?.trim().toLowerCase();
15
- return leadingCommentValue === options?.gqlMagicComment;
16
- },
17
- /**
18
- * Instruct how to extract the gql template literal from the code.
19
- * By default, embedded expressions in template literals (e.g. ${foo})
20
- * are removed from the template string. This hook allows us to annotate
21
- * the template string with the required embedded expressions instead of
22
- * removing them. Later, we can use this information to reconstruct the
23
- * embedded expressions.
24
- */
25
- pluckStringFromFile: (code, { start, end, leadingComments }) => {
26
- let gqlTemplate = code.slice(start + 1, end - 1).replace(/\$\{([^}]*)\}/g, (_, m1) => "#REQUIRED_VAR=" + m1).split("\\`").join("`");
27
- const chunkStart = leadingComments?.[0]?.start ?? start;
28
- const codeBeforeNode = code.slice(0, chunkStart);
29
- const [, varName] = codeBeforeNode.match(/\s(\w+)\s*=\s*$/) || [];
30
- if (varName) {
31
- gqlTemplate += "#VAR_NAME=" + varName;
32
- }
33
- return gqlTemplate;
34
- }
35
- };
36
-
37
- exports.pluckConfig = pluckConfig;
38
- //# sourceMappingURL=out.js.map
39
- //# sourceMappingURL=pluck.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/pluck.ts"],"names":[],"mappings":"AAIO,MAAM,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA,EAKzB,sBAAsB,CAAC,MAAW,YAAiB;AAEjD,UAAM,wBACJ,KAAK,SAAS,qBACd,oBAAoB,KAAK,KAAK,OAAO,CAAC,GAAG,OAAO,OAAO,EAAE;AAE3D,QAAI;AAAuB,aAAO;AAGlC,UAAM,EAAC,gBAAe,IAAI;AAC1B,UAAM,iBAAiB,kBAAkB,iBAAiB,SAAS,CAAC;AACpE,UAAM,sBAAsB,gBAAgB,OAAO,KAAK,EAAE,YAAY;AAEtE,WAAO,wBAAwB,SAAS;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,qBAAqB,CAAC,MAAc,EAAC,OAAO,KAAK,gBAAe,MAAW;AACzE,QAAI,cAAc,KAEf,MAAM,QAAQ,GAAG,MAAM,CAAC,EAGxB,QAAQ,kBAAkB,CAAC,GAAG,OAAO,mBAAmB,EAAE,EAC1D,MAAM,KAAK,EACX,KAAK,GAAG;AAEX,UAAM,aAAa,kBAAkB,CAAC,GAAG,SAAS;AAClD,UAAM,iBAAiB,KAAK,MAAM,GAAG,UAAU;AAC/C,UAAM,CAAC,EAAE,OAAO,IAAI,eAAe,MAAM,iBAAiB,KAAK,CAAC;AAEhE,QAAI,SAAS;AAGX,qBAAe,eAAe;AAAA,IAChC;AAEA,WAAO;AAAA,EACT;AACF","sourcesContent":["/**\n * This is a modified version of graphql-tag-pluck's default config.\n * https://github.com/ardatan/graphql-tools/issues/5127\n */\nexport const pluckConfig = {\n /**\n * Hook to determine if a node is a gql template literal.\n * By default, graphql-tag-pluck only looks for leading comments or `gql` tag.\n */\n isGqlTemplateLiteral: (node: any, options: any) => {\n // Check for internal gql comment: const QUERY = `#graphql ...`\n const hasInternalGqlComment =\n node.type === 'TemplateLiteral' &&\n /\\s*#graphql\\s*\\n/i.test(node.quasis[0]?.value?.raw || '');\n\n if (hasInternalGqlComment) return true;\n\n // Check for leading gql comment: const QUERY = /* GraphQL */ `...`\n const {leadingComments} = node;\n const leadingComment = leadingComments?.[leadingComments?.length - 1];\n const leadingCommentValue = leadingComment?.value?.trim().toLowerCase();\n\n return leadingCommentValue === options?.gqlMagicComment;\n },\n\n /**\n * Instruct how to extract the gql template literal from the code.\n * By default, embedded expressions in template literals (e.g. ${foo})\n * are removed from the template string. This hook allows us to annotate\n * the template string with the required embedded expressions instead of\n * removing them. Later, we can use this information to reconstruct the\n * embedded expressions.\n */\n pluckStringFromFile: (code: string, {start, end, leadingComments}: any) => {\n let gqlTemplate = code\n // Slice quotes\n .slice(start + 1, end - 1)\n // Annotate embedded expressions\n // e.g. ${foo} -> #REQUIRED_VAR=foo\n .replace(/\\$\\{([^}]*)\\}/g, (_, m1) => '#REQUIRED_VAR=' + m1)\n .split('\\\\`')\n .join('`');\n\n const chunkStart = leadingComments?.[0]?.start ?? start;\n const codeBeforeNode = code.slice(0, chunkStart);\n const [, varName] = codeBeforeNode.match(/\\s(\\w+)\\s*=\\s*$/) || [];\n\n if (varName) {\n // Annotate with the name of the variable that stores this gql template.\n // This is used to reconstruct the embedded expressions later.\n gqlTemplate += '#VAR_NAME=' + varName;\n }\n\n return gqlTemplate;\n },\n};\n"]}
@@ -1,81 +0,0 @@
1
- 'use strict';
2
-
3
- const plugin = (_, __, { sourcesWithOperations, interfaceExtensionCode }, _info) => {
4
- const code = getDocumentRegistryChunk(sourcesWithOperations);
5
- code.push(interfaceExtensionCode);
6
- return code.join("") + "\n";
7
- };
8
- const GENERATED_QUERY_INTERFACE_NAME = "GeneratedQueryTypes";
9
- const GENERATED_MUTATION_INTERFACE_NAME = "GeneratedMutationTypes";
10
- const isMutationRE = /(^|}\s|\n\s*)mutation[\s({]/im;
11
- const normalizeOperation = (rawSDL, variablesMap) => {
12
- let variableNotFound = false;
13
- while (/#REQUIRED_VAR=/.test(rawSDL) && !variableNotFound) {
14
- let requiredVariables = rawSDL.matchAll(/#REQUIRED_VAR=(\w+)/g);
15
- for (const [match, variableName] of requiredVariables) {
16
- if (variablesMap.has(variableName)) {
17
- rawSDL = rawSDL.replace(match, variablesMap.get(variableName));
18
- } else {
19
- variableNotFound = true;
20
- console.error(
21
- new Error(
22
- `Variable "${variableName}" not found. This might be a bug in hydrogen-codegen, please report it.`
23
- )
24
- );
25
- }
26
- }
27
- }
28
- return rawSDL;
29
- };
30
- const buildTypeLines = (name, operations) => {
31
- const lines = [`interface ${name} {
32
- `];
33
- for (const [originalString, typeNames] of operations) {
34
- lines.push(
35
- ` ${JSON.stringify(originalString)}: {return: ${// SFAPI does not support multiple operations in a single document.
36
- // Use 'never' here if that's the case so that the user gets a type error.
37
- // e.g. `'query q1 {...} query q2 {...}'` is invalid.
38
- typeNames.length === 1 ? typeNames[0] : "never"}, variables: ${typeNames.map((n) => n + "Variables").join(" & ")}},
39
- `
40
- );
41
- }
42
- lines.push(`}
43
- `);
44
- return lines;
45
- };
46
- function getDocumentRegistryChunk(sourcesWithOperations = []) {
47
- const queries = /* @__PURE__ */ new Map();
48
- const mutations = /* @__PURE__ */ new Map();
49
- const variablesMap = /* @__PURE__ */ new Map();
50
- for (const { source } of sourcesWithOperations) {
51
- const variableName = source.rawSDL?.match(/#VAR_NAME=(\w+)/)?.[1];
52
- if (variableName) {
53
- source.rawSDL = source.rawSDL.replace(/#VAR_NAME=\w+$/, "");
54
- variablesMap.set(variableName, source.rawSDL);
55
- }
56
- }
57
- for (const { operations, source } of sourcesWithOperations) {
58
- const actualOperations = operations.filter(
59
- (op) => op.definition.kind === "OperationDefinition"
60
- );
61
- if (actualOperations.length === 0)
62
- continue;
63
- const sdlString = source.rawSDL;
64
- const target = isMutationRE.test(sdlString) ? mutations : queries;
65
- target.set(
66
- normalizeOperation(sdlString, variablesMap),
67
- actualOperations.map((o) => o.initialName)
68
- );
69
- }
70
- return [
71
- ...buildTypeLines(GENERATED_QUERY_INTERFACE_NAME, queries),
72
- "\n",
73
- ...buildTypeLines(GENERATED_MUTATION_INTERFACE_NAME, mutations)
74
- ];
75
- }
76
-
77
- exports.GENERATED_MUTATION_INTERFACE_NAME = GENERATED_MUTATION_INTERFACE_NAME;
78
- exports.GENERATED_QUERY_INTERFACE_NAME = GENERATED_QUERY_INTERFACE_NAME;
79
- exports.plugin = plugin;
80
- //# sourceMappingURL=out.js.map
81
- //# sourceMappingURL=plugin.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/plugin.ts"],"names":[],"mappings":"AAiBO,MAAM,SAGR,CAAC,GAAG,IAAI,EAAC,uBAAuB,uBAAsB,GAAG,UAAU;AACtE,QAAM,OAAO,yBAAyB,qBAAqB;AAE3D,OAAK,KAAK,sBAAsB;AAEhC,SAAO,KAAK,KAAK,EAAE,IAAI;AACzB;AAEO,MAAM,iCAAiC;AACvC,MAAM,oCAAoC;AAEjD,MAAM,eAAe;AAIrB,MAAM,qBAAqB,CACzB,QACA,iBACG;AACH,MAAI,mBAAmB;AAEvB,SAAO,iBAAiB,KAAK,MAAM,KAAK,CAAC,kBAAkB;AACzD,QAAI,oBAAoB,OAAO,SAAS,sBAAsB;AAC9D,eAAW,CAAC,OAAO,YAAY,KAAK,mBAAmB;AACrD,UAAI,aAAa,IAAI,YAAY,GAAG;AAClC,iBAAS,OAAO,QAAQ,OAAO,aAAa,IAAI,YAAY,CAAE;AAAA,MAChE,OAAO;AAIL,2BAAmB;AACnB,gBAAQ;AAAA,UACN,IAAI;AAAA,YACF,aAAa,YAAY;AAAA,UAC3B;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEA,MAAM,iBAAiB,CAAC,MAAc,eAAsC;AAC1E,QAAM,QAAQ,CAAC,aAAa,IAAI;AAAA,CAAM;AAEtC,aAAW,CAAC,gBAAgB,SAAS,KAAK,YAAY;AACpD,UAAM;AAAA,MACJ,KAAK,KAAK,UAAU,cAAc,CAAC;AAAA;AAAA;AAAA,MAIjC,UAAU,WAAW,IAAI,UAAU,CAAC,IAAI,OAC1C,gBAAgB,UAAU,IAAI,CAAC,MAAM,IAAI,WAAW,EAAE,KAAK,KAAK,CAAC;AAAA;AAAA,IACnE;AAAA,EACF;AAEA,QAAM,KAAK;AAAA,CAAK;AAEhB,SAAO;AACT;AAEA,SAAS,yBACP,wBAAqD,CAAC,GACtD;AACA,QAAM,UAAU,oBAAI,IAAsB;AAC1C,QAAM,YAAY,oBAAI,IAAsB;AAE5C,QAAM,eAAe,oBAAI,IAAoB;AAC7C,aAAW,EAAC,OAAM,KAAK,uBAAuB;AAC5C,UAAM,eAAe,OAAO,QAAQ,MAAM,iBAAiB,IAAI,CAAC;AAChE,QAAI,cAAc;AAChB,aAAO,SAAS,OAAO,OAAQ,QAAQ,kBAAkB,EAAE;AAC3D,mBAAa,IAAI,cAAc,OAAO,MAAO;AAAA,IAC/C;AAAA,EACF;AAEA,aAAW,EAAC,YAAY,OAAM,KAAK,uBAAuB;AACxD,UAAM,mBAAmB,WAAW;AAAA,MAClC,CAAC,OAAO,GAAG,WAAW,SAAS;AAAA,IACjC;AAEA,QAAI,iBAAiB,WAAW;AAAG;AAEnC,UAAM,YAAY,OAAO;AACzB,UAAM,SAAS,aAAa,KAAK,SAAS,IAAI,YAAY;AAC1D,WAAO;AAAA,MACL,mBAAmB,WAAW,YAAY;AAAA,MAC1C,iBAAiB,IAAI,CAAC,MAAM,EAAE,WAAW;AAAA,IAC3C;AAAA,EACF;AAEA,SAAO;AAAA,IACL,GAAG,eAAe,gCAAgC,OAAO;AAAA,IACzD;AAAA,IACA,GAAG,eAAe,mCAAmC,SAAS;AAAA,EAChE;AACF","sourcesContent":["// This plugin is based on `gql-tag-operations-preset`\n// https://www.npmjs.com/package/@graphql-codegen/gql-tag-operations-preset\n\nimport type {PluginFunction} from '@graphql-codegen/plugin-helpers';\nimport type {Source} from '@graphql-tools/utils';\nimport type {FragmentDefinitionNode, OperationDefinitionNode} from 'graphql';\n\nexport type OperationOrFragment = {\n initialName: string;\n definition: OperationDefinitionNode | FragmentDefinitionNode;\n};\n\nexport type SourceWithOperations = {\n source: Source;\n operations: Array<OperationOrFragment>;\n};\n\nexport const plugin: PluginFunction<{\n sourcesWithOperations: Array<SourceWithOperations>;\n interfaceExtensionCode: string;\n}> = (_, __, {sourcesWithOperations, interfaceExtensionCode}, _info) => {\n const code = getDocumentRegistryChunk(sourcesWithOperations);\n\n code.push(interfaceExtensionCode);\n\n return code.join('') + '\\n';\n};\n\nexport const GENERATED_QUERY_INTERFACE_NAME = 'GeneratedQueryTypes';\nexport const GENERATED_MUTATION_INTERFACE_NAME = 'GeneratedMutationTypes';\n\nconst isMutationRE = /(^|}\\s|\\n\\s*)mutation[\\s({]/im;\n\n// Iteratively replace fragment annotations with the actual fragment content\n// until there are no more annotations in the operation.\nconst normalizeOperation = (\n rawSDL: string,\n variablesMap: Map<string, string>,\n) => {\n let variableNotFound = false;\n\n while (/#REQUIRED_VAR=/.test(rawSDL) && !variableNotFound) {\n let requiredVariables = rawSDL.matchAll(/#REQUIRED_VAR=(\\w+)/g);\n for (const [match, variableName] of requiredVariables) {\n if (variablesMap.has(variableName)) {\n rawSDL = rawSDL.replace(match, variablesMap.get(variableName)!);\n } else {\n // An annotation cannot be replaced, so the operation is invalid.\n // This should not happen, but we'll handle it just in case\n // to prevent infinite loops. This should be logged as an error and fixed.\n variableNotFound = true; // break;\n console.error(\n new Error(\n `Variable \"${variableName}\" not found. This might be a bug in hydrogen-codegen, please report it.`,\n ),\n );\n }\n }\n }\n\n return rawSDL;\n};\n\nconst buildTypeLines = (name: string, operations: Map<string, string[]>) => {\n const lines = [`interface ${name} {\\n`];\n\n for (const [originalString, typeNames] of operations) {\n lines.push(\n ` ${JSON.stringify(originalString)}: {return: ${\n // SFAPI does not support multiple operations in a single document.\n // Use 'never' here if that's the case so that the user gets a type error.\n // e.g. `'query q1 {...} query q2 {...}'` is invalid.\n typeNames.length === 1 ? typeNames[0] : 'never'\n }, variables: ${typeNames.map((n) => n + 'Variables').join(' & ')}},\\n`,\n );\n }\n\n lines.push(`}\\n`);\n\n return lines;\n};\n\nfunction getDocumentRegistryChunk(\n sourcesWithOperations: Array<SourceWithOperations> = [],\n) {\n const queries = new Map<string, string[]>();\n const mutations = new Map<string, string[]>();\n\n const variablesMap = new Map<string, string>();\n for (const {source} of sourcesWithOperations) {\n const variableName = source.rawSDL?.match(/#VAR_NAME=(\\w+)/)?.[1];\n if (variableName) {\n source.rawSDL = source.rawSDL!.replace(/#VAR_NAME=\\w+$/, '');\n variablesMap.set(variableName, source.rawSDL!);\n }\n }\n\n for (const {operations, source} of sourcesWithOperations) {\n const actualOperations = operations.filter(\n (op) => op.definition.kind === 'OperationDefinition',\n );\n\n if (actualOperations.length === 0) continue;\n\n const sdlString = source.rawSDL!;\n const target = isMutationRE.test(sdlString) ? mutations : queries;\n target.set(\n normalizeOperation(sdlString, variablesMap),\n actualOperations.map((o) => o.initialName),\n );\n }\n\n return [\n ...buildTypeLines(GENERATED_QUERY_INTERFACE_NAME, queries),\n '\\n',\n ...buildTypeLines(GENERATED_MUTATION_INTERFACE_NAME, mutations),\n ];\n}\n"]}
@@ -1,43 +0,0 @@
1
- 'use strict';
2
-
3
- const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
4
- const capitalizeQueries = (node) => {
5
- if (node.kind === "FragmentDefinition") {
6
- return "not used";
7
- }
8
- return capitalize(node.name.value) + capitalize(node.operation);
9
- };
10
- function processSources(sources, buildName = capitalizeQueries) {
11
- const sourcesWithOperations = [];
12
- for (const originalSource of sources) {
13
- const source = fixLinebreaks(originalSource);
14
- const { document } = source;
15
- const operations = [];
16
- for (const definition of document?.definitions ?? []) {
17
- if (definition?.kind !== "OperationDefinition" && definition?.kind !== "FragmentDefinition")
18
- continue;
19
- if (definition.name?.kind !== `Name`)
20
- continue;
21
- operations.push({
22
- initialName: buildName(definition),
23
- definition
24
- });
25
- }
26
- if (operations.length === 0)
27
- continue;
28
- sourcesWithOperations.push({
29
- source,
30
- operations
31
- });
32
- }
33
- return sourcesWithOperations;
34
- }
35
- function fixLinebreaks(source) {
36
- const fixedSource = { ...source };
37
- fixedSource.rawSDL = source.rawSDL?.replace(/\r\n/g, "\n");
38
- return fixedSource;
39
- }
40
-
41
- exports.processSources = processSources;
42
- //# sourceMappingURL=out.js.map
43
- //# sourceMappingURL=sources.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/sources.ts"],"names":[],"mappings":"AAIA,MAAM,aAAa,CAAC,QAAgB,IAAI,OAAO,CAAC,EAAE,YAAY,IAAI,IAAI,MAAM,CAAC;AAE7E,MAAM,oBAAoB,CACxB,SACG;AACH,MAAI,KAAK,SAAS,sBAAsB;AACtC,WAAO;AAAA,EACT;AAKA,SAAO,WAAW,KAAK,KAAM,KAAK,IAAI,WAAW,KAAK,SAAS;AACjE;AAEO,SAAS,eACd,SACA,YAAY,mBACZ;AACA,QAAM,wBAAqD,CAAC;AAE5D,aAAW,kBAAkB,SAAS;AACpC,UAAM,SAAS,cAAc,cAAc;AAC3C,UAAM,EAAC,SAAQ,IAAI;AACnB,UAAM,aAAyC,CAAC;AAEhD,eAAW,cAAc,UAAU,eAAe,CAAC,GAAG;AACpD,UACE,YAAY,SAAS,yBACrB,YAAY,SAAS;AAErB;AAEF,UAAI,WAAW,MAAM,SAAS;AAAQ;AAEtC,iBAAW,KAAK;AAAA,QACd,aAAa,UAAU,UAAU;AAAA,QACjC;AAAA,MACF,CAAC;AAAA,IACH;AAEA,QAAI,WAAW,WAAW;AAAG;AAE7B,0BAAsB,KAAK;AAAA,MACzB;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO;AACT;AA6CA,SAAS,cAAc,QAAgB;AACrC,QAAM,cAAc,EAAC,GAAG,OAAM;AAE9B,cAAY,SAAS,OAAO,QAAQ,QAAQ,SAAS,IAAI;AAEzD,SAAO;AACT","sourcesContent":["import type {OperationOrFragment, SourceWithOperations} from './plugin.js';\nimport type {Source} from '@graphql-tools/utils';\nimport type {FragmentDefinitionNode, OperationDefinitionNode} from 'graphql';\n\nconst capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);\n\nconst capitalizeQueries = (\n node: OperationDefinitionNode | FragmentDefinitionNode,\n) => {\n if (node.kind === 'FragmentDefinition') {\n return 'not used';\n }\n\n // Match the names generated by typescript-operations plugin:\n // e.g. 'query Hello {...}' => HelloQuery\n // -- Anonymous queries are not supported.\n return capitalize(node.name!.value) + capitalize(node.operation);\n};\n\nexport function processSources(\n sources: Array<Source>,\n buildName = capitalizeQueries,\n) {\n const sourcesWithOperations: Array<SourceWithOperations> = [];\n\n for (const originalSource of sources) {\n const source = fixLinebreaks(originalSource);\n const {document} = source;\n const operations: Array<OperationOrFragment> = [];\n\n for (const definition of document?.definitions ?? []) {\n if (\n definition?.kind !== 'OperationDefinition' &&\n definition?.kind !== 'FragmentDefinition'\n )\n continue;\n\n if (definition.name?.kind !== `Name`) continue;\n\n operations.push({\n initialName: buildName(definition),\n definition,\n });\n }\n\n if (operations.length === 0) continue;\n\n sourcesWithOperations.push({\n source,\n operations,\n });\n }\n\n return sourcesWithOperations;\n}\n\n/**\n * https://github.com/dotansimha/graphql-code-generator/issues/7362\n *\n * Source file is read by @graphql/tools using fs.promises.readFile,\n * which means that the linebreaks are read as-is and the result will be different\n * depending on the OS: it will contain LF (\\n) on Linux/MacOS and CRLF (\\r\\n) on Windows.\n *\n * In most scenarios that would be OK. However, gql-tag-operation is using the resulting string\n * as a TypeScript type. Which means that the string will be compared against a template literal,\n * for example:\n *\n * <pre><code>\n * `\n * query a {\n * a\n * }\n * ` === '\\n query a {\\n a\\n }\\n '\n * </code></pre>\n *\n * According to clause 12.8.6.2 of ECMAScript Language Specification\n * (https://tc39.es/ecma262/#sec-static-semantics-trv),\n * when comparing strings, JavaScript doesn't care which linebreaks does the source file contain,\n * any linebreak (CR, LF or CRLF) is LF from JavaScript standpoint\n * (otherwise the result of the above comparison would be OS-dependent, which doesn't make sense).\n *\n * Therefore gql-tag-operation would break on Windows as it would generate\n *\n * '\\r\\n query a {\\r\\n a\\r\\n }\\r\\n '\n *\n * which is NOT equal to\n *\n * <pre><code>\n * `\n * query a {\n * a\n * }\n * `\n * </code></pre>\n *\n * Therefore we need to replace \\r\\n with \\n in the string.\n *\n * @param source\n */\nfunction fixLinebreaks(source: Source) {\n const fixedSource = {...source};\n\n fixedSource.rawSDL = source.rawSDL?.replace(/\\r\\n/g, '\\n');\n\n return fixedSource;\n}\n"]}
@@ -1,3 +0,0 @@
1
-
2
- //# sourceMappingURL=out.js.map
3
- //# sourceMappingURL=client.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"names":[],"mappings":""}
@@ -1,2 +0,0 @@
1
-
2
- export { }
package/dist/esm/patch.js DELETED
@@ -1,3 +0,0 @@
1
-
2
- //# sourceMappingURL=out.js.map
3
- //# sourceMappingURL=patch.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"names":[],"mappings":""}
package/dist/esm/pluck.js DELETED
@@ -1,37 +0,0 @@
1
- const pluckConfig = {
2
- /**
3
- * Hook to determine if a node is a gql template literal.
4
- * By default, graphql-tag-pluck only looks for leading comments or `gql` tag.
5
- */
6
- isGqlTemplateLiteral: (node, options) => {
7
- const hasInternalGqlComment = node.type === "TemplateLiteral" && /\s*#graphql\s*\n/i.test(node.quasis[0]?.value?.raw || "");
8
- if (hasInternalGqlComment)
9
- return true;
10
- const { leadingComments } = node;
11
- const leadingComment = leadingComments?.[leadingComments?.length - 1];
12
- const leadingCommentValue = leadingComment?.value?.trim().toLowerCase();
13
- return leadingCommentValue === options?.gqlMagicComment;
14
- },
15
- /**
16
- * Instruct how to extract the gql template literal from the code.
17
- * By default, embedded expressions in template literals (e.g. ${foo})
18
- * are removed from the template string. This hook allows us to annotate
19
- * the template string with the required embedded expressions instead of
20
- * removing them. Later, we can use this information to reconstruct the
21
- * embedded expressions.
22
- */
23
- pluckStringFromFile: (code, { start, end, leadingComments }) => {
24
- let gqlTemplate = code.slice(start + 1, end - 1).replace(/\$\{([^}]*)\}/g, (_, m1) => "#REQUIRED_VAR=" + m1).split("\\`").join("`");
25
- const chunkStart = leadingComments?.[0]?.start ?? start;
26
- const codeBeforeNode = code.slice(0, chunkStart);
27
- const [, varName] = codeBeforeNode.match(/\s(\w+)\s*=\s*$/) || [];
28
- if (varName) {
29
- gqlTemplate += "#VAR_NAME=" + varName;
30
- }
31
- return gqlTemplate;
32
- }
33
- };
34
-
35
- export { pluckConfig };
36
- //# sourceMappingURL=out.js.map
37
- //# sourceMappingURL=pluck.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/pluck.ts"],"names":[],"mappings":"AAIO,MAAM,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA,EAKzB,sBAAsB,CAAC,MAAW,YAAiB;AAEjD,UAAM,wBACJ,KAAK,SAAS,qBACd,oBAAoB,KAAK,KAAK,OAAO,CAAC,GAAG,OAAO,OAAO,EAAE;AAE3D,QAAI;AAAuB,aAAO;AAGlC,UAAM,EAAC,gBAAe,IAAI;AAC1B,UAAM,iBAAiB,kBAAkB,iBAAiB,SAAS,CAAC;AACpE,UAAM,sBAAsB,gBAAgB,OAAO,KAAK,EAAE,YAAY;AAEtE,WAAO,wBAAwB,SAAS;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,qBAAqB,CAAC,MAAc,EAAC,OAAO,KAAK,gBAAe,MAAW;AACzE,QAAI,cAAc,KAEf,MAAM,QAAQ,GAAG,MAAM,CAAC,EAGxB,QAAQ,kBAAkB,CAAC,GAAG,OAAO,mBAAmB,EAAE,EAC1D,MAAM,KAAK,EACX,KAAK,GAAG;AAEX,UAAM,aAAa,kBAAkB,CAAC,GAAG,SAAS;AAClD,UAAM,iBAAiB,KAAK,MAAM,GAAG,UAAU;AAC/C,UAAM,CAAC,EAAE,OAAO,IAAI,eAAe,MAAM,iBAAiB,KAAK,CAAC;AAEhE,QAAI,SAAS;AAGX,qBAAe,eAAe;AAAA,IAChC;AAEA,WAAO;AAAA,EACT;AACF","sourcesContent":["/**\n * This is a modified version of graphql-tag-pluck's default config.\n * https://github.com/ardatan/graphql-tools/issues/5127\n */\nexport const pluckConfig = {\n /**\n * Hook to determine if a node is a gql template literal.\n * By default, graphql-tag-pluck only looks for leading comments or `gql` tag.\n */\n isGqlTemplateLiteral: (node: any, options: any) => {\n // Check for internal gql comment: const QUERY = `#graphql ...`\n const hasInternalGqlComment =\n node.type === 'TemplateLiteral' &&\n /\\s*#graphql\\s*\\n/i.test(node.quasis[0]?.value?.raw || '');\n\n if (hasInternalGqlComment) return true;\n\n // Check for leading gql comment: const QUERY = /* GraphQL */ `...`\n const {leadingComments} = node;\n const leadingComment = leadingComments?.[leadingComments?.length - 1];\n const leadingCommentValue = leadingComment?.value?.trim().toLowerCase();\n\n return leadingCommentValue === options?.gqlMagicComment;\n },\n\n /**\n * Instruct how to extract the gql template literal from the code.\n * By default, embedded expressions in template literals (e.g. ${foo})\n * are removed from the template string. This hook allows us to annotate\n * the template string with the required embedded expressions instead of\n * removing them. Later, we can use this information to reconstruct the\n * embedded expressions.\n */\n pluckStringFromFile: (code: string, {start, end, leadingComments}: any) => {\n let gqlTemplate = code\n // Slice quotes\n .slice(start + 1, end - 1)\n // Annotate embedded expressions\n // e.g. ${foo} -> #REQUIRED_VAR=foo\n .replace(/\\$\\{([^}]*)\\}/g, (_, m1) => '#REQUIRED_VAR=' + m1)\n .split('\\\\`')\n .join('`');\n\n const chunkStart = leadingComments?.[0]?.start ?? start;\n const codeBeforeNode = code.slice(0, chunkStart);\n const [, varName] = codeBeforeNode.match(/\\s(\\w+)\\s*=\\s*$/) || [];\n\n if (varName) {\n // Annotate with the name of the variable that stores this gql template.\n // This is used to reconstruct the embedded expressions later.\n gqlTemplate += '#VAR_NAME=' + varName;\n }\n\n return gqlTemplate;\n },\n};\n"]}
@@ -1,77 +0,0 @@
1
- const plugin = (_, __, { sourcesWithOperations, interfaceExtensionCode }, _info) => {
2
- const code = getDocumentRegistryChunk(sourcesWithOperations);
3
- code.push(interfaceExtensionCode);
4
- return code.join("") + "\n";
5
- };
6
- const GENERATED_QUERY_INTERFACE_NAME = "GeneratedQueryTypes";
7
- const GENERATED_MUTATION_INTERFACE_NAME = "GeneratedMutationTypes";
8
- const isMutationRE = /(^|}\s|\n\s*)mutation[\s({]/im;
9
- const normalizeOperation = (rawSDL, variablesMap) => {
10
- let variableNotFound = false;
11
- while (/#REQUIRED_VAR=/.test(rawSDL) && !variableNotFound) {
12
- let requiredVariables = rawSDL.matchAll(/#REQUIRED_VAR=(\w+)/g);
13
- for (const [match, variableName] of requiredVariables) {
14
- if (variablesMap.has(variableName)) {
15
- rawSDL = rawSDL.replace(match, variablesMap.get(variableName));
16
- } else {
17
- variableNotFound = true;
18
- console.error(
19
- new Error(
20
- `Variable "${variableName}" not found. This might be a bug in hydrogen-codegen, please report it.`
21
- )
22
- );
23
- }
24
- }
25
- }
26
- return rawSDL;
27
- };
28
- const buildTypeLines = (name, operations) => {
29
- const lines = [`interface ${name} {
30
- `];
31
- for (const [originalString, typeNames] of operations) {
32
- lines.push(
33
- ` ${JSON.stringify(originalString)}: {return: ${// SFAPI does not support multiple operations in a single document.
34
- // Use 'never' here if that's the case so that the user gets a type error.
35
- // e.g. `'query q1 {...} query q2 {...}'` is invalid.
36
- typeNames.length === 1 ? typeNames[0] : "never"}, variables: ${typeNames.map((n) => n + "Variables").join(" & ")}},
37
- `
38
- );
39
- }
40
- lines.push(`}
41
- `);
42
- return lines;
43
- };
44
- function getDocumentRegistryChunk(sourcesWithOperations = []) {
45
- const queries = /* @__PURE__ */ new Map();
46
- const mutations = /* @__PURE__ */ new Map();
47
- const variablesMap = /* @__PURE__ */ new Map();
48
- for (const { source } of sourcesWithOperations) {
49
- const variableName = source.rawSDL?.match(/#VAR_NAME=(\w+)/)?.[1];
50
- if (variableName) {
51
- source.rawSDL = source.rawSDL.replace(/#VAR_NAME=\w+$/, "");
52
- variablesMap.set(variableName, source.rawSDL);
53
- }
54
- }
55
- for (const { operations, source } of sourcesWithOperations) {
56
- const actualOperations = operations.filter(
57
- (op) => op.definition.kind === "OperationDefinition"
58
- );
59
- if (actualOperations.length === 0)
60
- continue;
61
- const sdlString = source.rawSDL;
62
- const target = isMutationRE.test(sdlString) ? mutations : queries;
63
- target.set(
64
- normalizeOperation(sdlString, variablesMap),
65
- actualOperations.map((o) => o.initialName)
66
- );
67
- }
68
- return [
69
- ...buildTypeLines(GENERATED_QUERY_INTERFACE_NAME, queries),
70
- "\n",
71
- ...buildTypeLines(GENERATED_MUTATION_INTERFACE_NAME, mutations)
72
- ];
73
- }
74
-
75
- export { GENERATED_MUTATION_INTERFACE_NAME, GENERATED_QUERY_INTERFACE_NAME, plugin };
76
- //# sourceMappingURL=out.js.map
77
- //# sourceMappingURL=plugin.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/plugin.ts"],"names":[],"mappings":"AAiBO,MAAM,SAGR,CAAC,GAAG,IAAI,EAAC,uBAAuB,uBAAsB,GAAG,UAAU;AACtE,QAAM,OAAO,yBAAyB,qBAAqB;AAE3D,OAAK,KAAK,sBAAsB;AAEhC,SAAO,KAAK,KAAK,EAAE,IAAI;AACzB;AAEO,MAAM,iCAAiC;AACvC,MAAM,oCAAoC;AAEjD,MAAM,eAAe;AAIrB,MAAM,qBAAqB,CACzB,QACA,iBACG;AACH,MAAI,mBAAmB;AAEvB,SAAO,iBAAiB,KAAK,MAAM,KAAK,CAAC,kBAAkB;AACzD,QAAI,oBAAoB,OAAO,SAAS,sBAAsB;AAC9D,eAAW,CAAC,OAAO,YAAY,KAAK,mBAAmB;AACrD,UAAI,aAAa,IAAI,YAAY,GAAG;AAClC,iBAAS,OAAO,QAAQ,OAAO,aAAa,IAAI,YAAY,CAAE;AAAA,MAChE,OAAO;AAIL,2BAAmB;AACnB,gBAAQ;AAAA,UACN,IAAI;AAAA,YACF,aAAa,YAAY;AAAA,UAC3B;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEA,MAAM,iBAAiB,CAAC,MAAc,eAAsC;AAC1E,QAAM,QAAQ,CAAC,aAAa,IAAI;AAAA,CAAM;AAEtC,aAAW,CAAC,gBAAgB,SAAS,KAAK,YAAY;AACpD,UAAM;AAAA,MACJ,KAAK,KAAK,UAAU,cAAc,CAAC;AAAA;AAAA;AAAA,MAIjC,UAAU,WAAW,IAAI,UAAU,CAAC,IAAI,OAC1C,gBAAgB,UAAU,IAAI,CAAC,MAAM,IAAI,WAAW,EAAE,KAAK,KAAK,CAAC;AAAA;AAAA,IACnE;AAAA,EACF;AAEA,QAAM,KAAK;AAAA,CAAK;AAEhB,SAAO;AACT;AAEA,SAAS,yBACP,wBAAqD,CAAC,GACtD;AACA,QAAM,UAAU,oBAAI,IAAsB;AAC1C,QAAM,YAAY,oBAAI,IAAsB;AAE5C,QAAM,eAAe,oBAAI,IAAoB;AAC7C,aAAW,EAAC,OAAM,KAAK,uBAAuB;AAC5C,UAAM,eAAe,OAAO,QAAQ,MAAM,iBAAiB,IAAI,CAAC;AAChE,QAAI,cAAc;AAChB,aAAO,SAAS,OAAO,OAAQ,QAAQ,kBAAkB,EAAE;AAC3D,mBAAa,IAAI,cAAc,OAAO,MAAO;AAAA,IAC/C;AAAA,EACF;AAEA,aAAW,EAAC,YAAY,OAAM,KAAK,uBAAuB;AACxD,UAAM,mBAAmB,WAAW;AAAA,MAClC,CAAC,OAAO,GAAG,WAAW,SAAS;AAAA,IACjC;AAEA,QAAI,iBAAiB,WAAW;AAAG;AAEnC,UAAM,YAAY,OAAO;AACzB,UAAM,SAAS,aAAa,KAAK,SAAS,IAAI,YAAY;AAC1D,WAAO;AAAA,MACL,mBAAmB,WAAW,YAAY;AAAA,MAC1C,iBAAiB,IAAI,CAAC,MAAM,EAAE,WAAW;AAAA,IAC3C;AAAA,EACF;AAEA,SAAO;AAAA,IACL,GAAG,eAAe,gCAAgC,OAAO;AAAA,IACzD;AAAA,IACA,GAAG,eAAe,mCAAmC,SAAS;AAAA,EAChE;AACF","sourcesContent":["// This plugin is based on `gql-tag-operations-preset`\n// https://www.npmjs.com/package/@graphql-codegen/gql-tag-operations-preset\n\nimport type {PluginFunction} from '@graphql-codegen/plugin-helpers';\nimport type {Source} from '@graphql-tools/utils';\nimport type {FragmentDefinitionNode, OperationDefinitionNode} from 'graphql';\n\nexport type OperationOrFragment = {\n initialName: string;\n definition: OperationDefinitionNode | FragmentDefinitionNode;\n};\n\nexport type SourceWithOperations = {\n source: Source;\n operations: Array<OperationOrFragment>;\n};\n\nexport const plugin: PluginFunction<{\n sourcesWithOperations: Array<SourceWithOperations>;\n interfaceExtensionCode: string;\n}> = (_, __, {sourcesWithOperations, interfaceExtensionCode}, _info) => {\n const code = getDocumentRegistryChunk(sourcesWithOperations);\n\n code.push(interfaceExtensionCode);\n\n return code.join('') + '\\n';\n};\n\nexport const GENERATED_QUERY_INTERFACE_NAME = 'GeneratedQueryTypes';\nexport const GENERATED_MUTATION_INTERFACE_NAME = 'GeneratedMutationTypes';\n\nconst isMutationRE = /(^|}\\s|\\n\\s*)mutation[\\s({]/im;\n\n// Iteratively replace fragment annotations with the actual fragment content\n// until there are no more annotations in the operation.\nconst normalizeOperation = (\n rawSDL: string,\n variablesMap: Map<string, string>,\n) => {\n let variableNotFound = false;\n\n while (/#REQUIRED_VAR=/.test(rawSDL) && !variableNotFound) {\n let requiredVariables = rawSDL.matchAll(/#REQUIRED_VAR=(\\w+)/g);\n for (const [match, variableName] of requiredVariables) {\n if (variablesMap.has(variableName)) {\n rawSDL = rawSDL.replace(match, variablesMap.get(variableName)!);\n } else {\n // An annotation cannot be replaced, so the operation is invalid.\n // This should not happen, but we'll handle it just in case\n // to prevent infinite loops. This should be logged as an error and fixed.\n variableNotFound = true; // break;\n console.error(\n new Error(\n `Variable \"${variableName}\" not found. This might be a bug in hydrogen-codegen, please report it.`,\n ),\n );\n }\n }\n }\n\n return rawSDL;\n};\n\nconst buildTypeLines = (name: string, operations: Map<string, string[]>) => {\n const lines = [`interface ${name} {\\n`];\n\n for (const [originalString, typeNames] of operations) {\n lines.push(\n ` ${JSON.stringify(originalString)}: {return: ${\n // SFAPI does not support multiple operations in a single document.\n // Use 'never' here if that's the case so that the user gets a type error.\n // e.g. `'query q1 {...} query q2 {...}'` is invalid.\n typeNames.length === 1 ? typeNames[0] : 'never'\n }, variables: ${typeNames.map((n) => n + 'Variables').join(' & ')}},\\n`,\n );\n }\n\n lines.push(`}\\n`);\n\n return lines;\n};\n\nfunction getDocumentRegistryChunk(\n sourcesWithOperations: Array<SourceWithOperations> = [],\n) {\n const queries = new Map<string, string[]>();\n const mutations = new Map<string, string[]>();\n\n const variablesMap = new Map<string, string>();\n for (const {source} of sourcesWithOperations) {\n const variableName = source.rawSDL?.match(/#VAR_NAME=(\\w+)/)?.[1];\n if (variableName) {\n source.rawSDL = source.rawSDL!.replace(/#VAR_NAME=\\w+$/, '');\n variablesMap.set(variableName, source.rawSDL!);\n }\n }\n\n for (const {operations, source} of sourcesWithOperations) {\n const actualOperations = operations.filter(\n (op) => op.definition.kind === 'OperationDefinition',\n );\n\n if (actualOperations.length === 0) continue;\n\n const sdlString = source.rawSDL!;\n const target = isMutationRE.test(sdlString) ? mutations : queries;\n target.set(\n normalizeOperation(sdlString, variablesMap),\n actualOperations.map((o) => o.initialName),\n );\n }\n\n return [\n ...buildTypeLines(GENERATED_QUERY_INTERFACE_NAME, queries),\n '\\n',\n ...buildTypeLines(GENERATED_MUTATION_INTERFACE_NAME, mutations),\n ];\n}\n"]}
@@ -1,41 +0,0 @@
1
- const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
2
- const capitalizeQueries = (node) => {
3
- if (node.kind === "FragmentDefinition") {
4
- return "not used";
5
- }
6
- return capitalize(node.name.value) + capitalize(node.operation);
7
- };
8
- function processSources(sources, buildName = capitalizeQueries) {
9
- const sourcesWithOperations = [];
10
- for (const originalSource of sources) {
11
- const source = fixLinebreaks(originalSource);
12
- const { document } = source;
13
- const operations = [];
14
- for (const definition of document?.definitions ?? []) {
15
- if (definition?.kind !== "OperationDefinition" && definition?.kind !== "FragmentDefinition")
16
- continue;
17
- if (definition.name?.kind !== `Name`)
18
- continue;
19
- operations.push({
20
- initialName: buildName(definition),
21
- definition
22
- });
23
- }
24
- if (operations.length === 0)
25
- continue;
26
- sourcesWithOperations.push({
27
- source,
28
- operations
29
- });
30
- }
31
- return sourcesWithOperations;
32
- }
33
- function fixLinebreaks(source) {
34
- const fixedSource = { ...source };
35
- fixedSource.rawSDL = source.rawSDL?.replace(/\r\n/g, "\n");
36
- return fixedSource;
37
- }
38
-
39
- export { processSources };
40
- //# sourceMappingURL=out.js.map
41
- //# sourceMappingURL=sources.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/sources.ts"],"names":[],"mappings":"AAIA,MAAM,aAAa,CAAC,QAAgB,IAAI,OAAO,CAAC,EAAE,YAAY,IAAI,IAAI,MAAM,CAAC;AAE7E,MAAM,oBAAoB,CACxB,SACG;AACH,MAAI,KAAK,SAAS,sBAAsB;AACtC,WAAO;AAAA,EACT;AAKA,SAAO,WAAW,KAAK,KAAM,KAAK,IAAI,WAAW,KAAK,SAAS;AACjE;AAEO,SAAS,eACd,SACA,YAAY,mBACZ;AACA,QAAM,wBAAqD,CAAC;AAE5D,aAAW,kBAAkB,SAAS;AACpC,UAAM,SAAS,cAAc,cAAc;AAC3C,UAAM,EAAC,SAAQ,IAAI;AACnB,UAAM,aAAyC,CAAC;AAEhD,eAAW,cAAc,UAAU,eAAe,CAAC,GAAG;AACpD,UACE,YAAY,SAAS,yBACrB,YAAY,SAAS;AAErB;AAEF,UAAI,WAAW,MAAM,SAAS;AAAQ;AAEtC,iBAAW,KAAK;AAAA,QACd,aAAa,UAAU,UAAU;AAAA,QACjC;AAAA,MACF,CAAC;AAAA,IACH;AAEA,QAAI,WAAW,WAAW;AAAG;AAE7B,0BAAsB,KAAK;AAAA,MACzB;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO;AACT;AA6CA,SAAS,cAAc,QAAgB;AACrC,QAAM,cAAc,EAAC,GAAG,OAAM;AAE9B,cAAY,SAAS,OAAO,QAAQ,QAAQ,SAAS,IAAI;AAEzD,SAAO;AACT","sourcesContent":["import type {OperationOrFragment, SourceWithOperations} from './plugin.js';\nimport type {Source} from '@graphql-tools/utils';\nimport type {FragmentDefinitionNode, OperationDefinitionNode} from 'graphql';\n\nconst capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);\n\nconst capitalizeQueries = (\n node: OperationDefinitionNode | FragmentDefinitionNode,\n) => {\n if (node.kind === 'FragmentDefinition') {\n return 'not used';\n }\n\n // Match the names generated by typescript-operations plugin:\n // e.g. 'query Hello {...}' => HelloQuery\n // -- Anonymous queries are not supported.\n return capitalize(node.name!.value) + capitalize(node.operation);\n};\n\nexport function processSources(\n sources: Array<Source>,\n buildName = capitalizeQueries,\n) {\n const sourcesWithOperations: Array<SourceWithOperations> = [];\n\n for (const originalSource of sources) {\n const source = fixLinebreaks(originalSource);\n const {document} = source;\n const operations: Array<OperationOrFragment> = [];\n\n for (const definition of document?.definitions ?? []) {\n if (\n definition?.kind !== 'OperationDefinition' &&\n definition?.kind !== 'FragmentDefinition'\n )\n continue;\n\n if (definition.name?.kind !== `Name`) continue;\n\n operations.push({\n initialName: buildName(definition),\n definition,\n });\n }\n\n if (operations.length === 0) continue;\n\n sourcesWithOperations.push({\n source,\n operations,\n });\n }\n\n return sourcesWithOperations;\n}\n\n/**\n * https://github.com/dotansimha/graphql-code-generator/issues/7362\n *\n * Source file is read by @graphql/tools using fs.promises.readFile,\n * which means that the linebreaks are read as-is and the result will be different\n * depending on the OS: it will contain LF (\\n) on Linux/MacOS and CRLF (\\r\\n) on Windows.\n *\n * In most scenarios that would be OK. However, gql-tag-operation is using the resulting string\n * as a TypeScript type. Which means that the string will be compared against a template literal,\n * for example:\n *\n * <pre><code>\n * `\n * query a {\n * a\n * }\n * ` === '\\n query a {\\n a\\n }\\n '\n * </code></pre>\n *\n * According to clause 12.8.6.2 of ECMAScript Language Specification\n * (https://tc39.es/ecma262/#sec-static-semantics-trv),\n * when comparing strings, JavaScript doesn't care which linebreaks does the source file contain,\n * any linebreak (CR, LF or CRLF) is LF from JavaScript standpoint\n * (otherwise the result of the above comparison would be OS-dependent, which doesn't make sense).\n *\n * Therefore gql-tag-operation would break on Windows as it would generate\n *\n * '\\r\\n query a {\\r\\n a\\r\\n }\\r\\n '\n *\n * which is NOT equal to\n *\n * <pre><code>\n * `\n * query a {\n * a\n * }\n * `\n * </code></pre>\n *\n * Therefore we need to replace \\r\\n with \\n in the string.\n *\n * @param source\n */\nfunction fixLinebreaks(source: Source) {\n const fixedSource = {...source};\n\n fixedSource.rawSDL = source.rawSDL?.replace(/\\r\\n/g, '\\n');\n\n return fixedSource;\n}\n"]}