@shopify/hydrogen-codegen 0.0.2 → 0.1.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.
@@ -28,10 +28,6 @@ Object.defineProperty(exports, 'processSources', {
28
28
  enumerable: true,
29
29
  get: function () { return sources_js.processSources; }
30
30
  });
31
- Object.defineProperty(exports, 'patchGqlPluck', {
32
- enumerable: true,
33
- get: function () { return pluck_js.patchGqlPluck; }
34
- });
35
31
  Object.defineProperty(exports, 'pluckConfig', {
36
32
  enumerable: true,
37
33
  get: function () { return pluck_js.pluckConfig; }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,SAAQ,cAAa;AACrB,SAAQ,cAAa;AACrB,SAAQ,QAAQ,iBAAgB;AAChC,SAAQ,sBAAqB;AAC7B,SAAQ,aAAa,qBAAoB","sourcesContent":["export {preset} from './preset.js';\nexport {plugin} from './plugin.js';\nexport {schema, getSchema} from './schema.js';\nexport {processSources} from './sources.js';\nexport {pluckConfig, patchGqlPluck} from './pluck.js';\n"]}
1
+ {"version":3,"sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,SAAQ,cAAa;AACrB,SAAQ,cAAa;AACrB,SAAQ,QAAQ,iBAAgB;AAChC,SAAQ,sBAAqB;AAC7B,SAAQ,mBAAkB","sourcesContent":["export {preset} from './preset.js';\nexport {plugin} from './plugin.js';\nexport {schema, getSchema} from './schema.js';\nexport {processSources} from './sources.js';\nexport {pluckConfig} from './pluck.js';\n"]}
@@ -0,0 +1,53 @@
1
+ 'use strict';
2
+
3
+ var path = require('node:path');
4
+ var fs = require('node:fs');
5
+ var node_module = require('node:module');
6
+ var node_url = require('node:url');
7
+
8
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
9
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
+
11
+ var path__default = /*#__PURE__*/_interopDefault(path);
12
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
13
+
14
+ const require2 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('out.js', document.baseURI).href)));
15
+ const realGqlTagPluck = require2.resolve("@graphql-tools/graphql-tag-pluck");
16
+ const depth = path__default.default.extname((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('out.js', document.baseURI).href))) === ".ts" ? "../" : "../../";
17
+ const vendorGqlTagPluck = node_url.fileURLToPath(
18
+ new URL(depth + "/vendor/graphql-tag-pluck", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('out.js', document.baseURI).href)))
19
+ );
20
+ fs__default.default.copyFileSync(
21
+ path__default.default.join(vendorGqlTagPluck, "visitor.cjs"),
22
+ realGqlTagPluck.replace(/index\.js$/, "visitor.js")
23
+ );
24
+ fs__default.default.copyFileSync(
25
+ path__default.default.join(vendorGqlTagPluck, "visitor.mjs"),
26
+ realGqlTagPluck.replace("cjs", "esm").replace(/index\.js$/, "visitor.js")
27
+ );
28
+ const visitorPluginCommon = require2.resolve(
29
+ "@graphql-codegen/visitor-plugin-common"
30
+ );
31
+ const selectionSetToObjectFileCJS = visitorPluginCommon.replace(
32
+ "index.js",
33
+ "selection-set-to-object.js"
34
+ );
35
+ const selectionSetToObjectFileESM = selectionSetToObjectFileCJS.replace(
36
+ "cjs",
37
+ "esm"
38
+ );
39
+ fs__default.default.writeFileSync(
40
+ selectionSetToObjectFileCJS,
41
+ patchSelectionSet(fs__default.default.readFileSync(selectionSetToObjectFileCJS, "utf-8")),
42
+ "utf-8"
43
+ );
44
+ fs__default.default.writeFileSync(
45
+ selectionSetToObjectFileESM,
46
+ patchSelectionSet(fs__default.default.readFileSync(selectionSetToObjectFileESM, "utf-8")),
47
+ "utf-8"
48
+ );
49
+ function patchSelectionSet(content) {
50
+ return content.replace("&& s.union", "&& s?.union");
51
+ }
52
+ //# sourceMappingURL=out.js.map
53
+ //# sourceMappingURL=patch.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/patch.ts"],"names":["require"],"mappings":"AAAA,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,SAAQ,qBAAoB;AAC5B,SAAQ,qBAAoB;AAK5B,MAAMA,WAAU,cAAc,YAAY,GAAG;AAC7C,MAAM,kBAAkBA,SAAQ,QAAQ,kCAAkC;AAG1E,MAAM,QAAQ,KAAK,QAAQ,YAAY,GAAG,MAAM,QAAQ,QAAQ;AAChE,MAAM,oBAAoB;AAAA,EACxB,IAAI,IAAI,QAAQ,6BAA6B,YAAY,GAAG;AAC9D;AAGA,GAAG;AAAA,EACD,KAAK,KAAK,mBAAmB,aAAa;AAAA,EAC1C,gBAAgB,QAAQ,cAAc,YAAY;AACpD;AAEA,GAAG;AAAA,EACD,KAAK,KAAK,mBAAmB,aAAa;AAAA,EAC1C,gBAAgB,QAAQ,OAAO,KAAK,EAAE,QAAQ,cAAc,YAAY;AAC1E;AAMA,MAAM,sBAAsBA,SAAQ;AAAA,EAClC;AACF;AACA,MAAM,8BAA8B,oBAAoB;AAAA,EACtD;AAAA,EACA;AACF;AACA,MAAM,8BAA8B,4BAA4B;AAAA,EAC9D;AAAA,EACA;AACF;AAEA,GAAG;AAAA,EACD;AAAA,EACA,kBAAkB,GAAG,aAAa,6BAA6B,OAAO,CAAC;AAAA,EACvE;AACF;AAEA,GAAG;AAAA,EACD;AAAA,EACA,kBAAkB,GAAG,aAAa,6BAA6B,OAAO,CAAC;AAAA,EACvE;AACF;AAEA,SAAS,kBAAkB,SAAiB;AAC1C,SAAO,QAAQ,QAAQ,cAAc,aAAa;AACpD","sourcesContent":["import path from 'node:path';\nimport fs from 'node:fs';\nimport {createRequire} from 'node:module';\nimport {fileURLToPath} from 'node:url';\n\n/**\n * Patch graphql-tag-pluck to allow it to work with `#graphql` comment and other features.\n */\nconst require = createRequire(import.meta.url);\nconst realGqlTagPluck = require.resolve('@graphql-tools/graphql-tag-pluck');\n// During tests, this file is in src/xyz.ts but in dev/prod,\n// the file is in dist/(esm|cjs)/xyz.js\nconst depth = path.extname(import.meta.url) === '.ts' ? '../' : '../../';\nconst vendorGqlTagPluck = fileURLToPath(\n new URL(depth + '/vendor/graphql-tag-pluck', import.meta.url),\n);\n\n// Copy files sequencially to avoid `EBUSY` errors in Windows\nfs.copyFileSync(\n path.join(vendorGqlTagPluck, 'visitor.cjs'),\n realGqlTagPluck.replace(/index\\.js$/, 'visitor.js'),\n);\n\nfs.copyFileSync(\n path.join(vendorGqlTagPluck, 'visitor.mjs'),\n realGqlTagPluck.replace('cjs', 'esm').replace(/index\\.js$/, 'visitor.js'),\n);\n\n/**\n * Temporary patch for a bug in another package\n * https://github.com/dotansimha/graphql-code-generator/pull/9709\n */\nconst visitorPluginCommon = require.resolve(\n '@graphql-codegen/visitor-plugin-common',\n);\nconst selectionSetToObjectFileCJS = visitorPluginCommon.replace(\n 'index.js',\n 'selection-set-to-object.js',\n);\nconst selectionSetToObjectFileESM = selectionSetToObjectFileCJS.replace(\n 'cjs',\n 'esm',\n);\n\nfs.writeFileSync(\n selectionSetToObjectFileCJS,\n patchSelectionSet(fs.readFileSync(selectionSetToObjectFileCJS, 'utf-8')),\n 'utf-8',\n);\n\nfs.writeFileSync(\n selectionSetToObjectFileESM,\n patchSelectionSet(fs.readFileSync(selectionSetToObjectFileESM, 'utf-8')),\n 'utf-8',\n);\n\nfunction patchSelectionSet(content: string) {\n return content.replace('&& s.union', '&& s?.union');\n}\n"]}
@@ -1,27 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var fs = require('fs/promises');
4
- var path = require('path');
5
- var node_module = require('node:module');
6
- var node_url = require('node:url');
7
-
8
- async function patchGqlPluck() {
9
- const require2 = node_module.createRequire((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('out.js', document.baseURI).href)));
10
- const realGqlTagPluck = require2.resolve("@graphql-tools/graphql-tag-pluck");
11
- const depth = path.extname((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('out.js', document.baseURI).href))) === ".ts" ? "../" : "../../";
12
- const vendorGqlTagPluck = node_url.fileURLToPath(
13
- new URL(depth + "/vendor/graphql-tag-pluck", (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('out.js', document.baseURI).href)))
14
- );
15
- await fs.copyFile(
16
- path.join(vendorGqlTagPluck, "visitor.cjs"),
17
- realGqlTagPluck.replace(/index\.js$/, "visitor.js")
18
- );
19
- await fs.copyFile(
20
- path.join(vendorGqlTagPluck, "visitor.mjs"),
21
- realGqlTagPluck.replace("cjs", "esm").replace(/index\.js$/, "visitor.js")
22
- );
23
- }
24
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
+ */
25
8
  isGqlTemplateLiteral: (node, options) => {
26
9
  const hasInternalGqlComment = node.type === "TemplateLiteral" && /\s*#graphql\s*\n/i.test(node.quasis[0]?.value?.raw || "");
27
10
  if (hasInternalGqlComment)
@@ -31,6 +14,14 @@ const pluckConfig = {
31
14
  const leadingCommentValue = leadingComment?.value?.trim().toLowerCase();
32
15
  return leadingCommentValue === options?.gqlMagicComment;
33
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
+ */
34
25
  pluckStringFromFile: (code, { start, end, leadingComments }) => {
35
26
  let gqlTemplate = code.slice(start + 1, end - 1).replace(/\$\{([^}]*)\}/g, (_, m1) => "#REQUIRED_VAR=" + m1).split("\\`").join("`");
36
27
  const chunkStart = leadingComments?.[0]?.start ?? start;
@@ -43,7 +34,6 @@ const pluckConfig = {
43
34
  }
44
35
  };
45
36
 
46
- exports.patchGqlPluck = patchGqlPluck;
47
37
  exports.pluckConfig = pluckConfig;
48
38
  //# sourceMappingURL=out.js.map
49
39
  //# sourceMappingURL=pluck.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/pluck.ts"],"names":["require"],"mappings":"AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAQ,qBAAoB;AAC5B,SAAQ,qBAAoB;AAE5B,eAAsB,gBAAgB;AACpC,QAAMA,WAAU,cAAc,YAAY,GAAG;AAC7C,QAAM,kBAAkBA,SAAQ,QAAQ,kCAAkC;AAG1E,QAAM,QAAQ,KAAK,QAAQ,YAAY,GAAG,MAAM,QAAQ,QAAQ;AAChE,QAAM,oBAAoB;AAAA,IACxB,IAAI,IAAI,QAAQ,6BAA6B,YAAY,GAAG;AAAA,EAC9D;AAGA,QAAM,GAAG;AAAA,IACP,KAAK,KAAK,mBAAmB,aAAa;AAAA,IAC1C,gBAAgB,QAAQ,cAAc,YAAY;AAAA,EACpD;AAEA,QAAM,GAAG;AAAA,IACP,KAAK,KAAK,mBAAmB,aAAa;AAAA,IAC1C,gBAAgB,QAAQ,OAAO,KAAK,EAAE,QAAQ,cAAc,YAAY;AAAA,EAC1E;AACF;AAMO,MAAM,cAAc;AAAA,EAKzB,sBAAsB,CAAC,MAAW,YAAiB;AAEjD,UAAM,wBACJ,KAAK,SAAS,qBACd,oBAAoB,KAAK,KAAK,OAAO,IAAI,OAAO,OAAO,EAAE;AAE3D,QAAI;AAAuB,aAAO;AAGlC,UAAM,EAAC,gBAAe,IAAI;AAC1B,UAAM,iBAAiB,kBAAkB,iBAAiB,SAAS;AACnE,UAAM,sBAAsB,gBAAgB,OAAO,KAAK,EAAE,YAAY;AAEtE,WAAO,wBAAwB,SAAS;AAAA,EAC1C;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,IAAI,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":["import fs from 'fs/promises';\nimport path from 'path';\nimport {createRequire} from 'node:module';\nimport {fileURLToPath} from 'node:url';\n\nexport async function patchGqlPluck() {\n const require = createRequire(import.meta.url);\n const realGqlTagPluck = require.resolve('@graphql-tools/graphql-tag-pluck');\n // During tests, this file is in src/xyz.ts but in dev/prod,\n // the file is in dist/(esm|cjs)/xyz.js\n const depth = path.extname(import.meta.url) === '.ts' ? '../' : '../../';\n const vendorGqlTagPluck = fileURLToPath(\n new URL(depth + '/vendor/graphql-tag-pluck', import.meta.url),\n );\n\n // Copy files sequencially to avoid `EBUSY` errors in Windows\n await fs.copyFile(\n path.join(vendorGqlTagPluck, 'visitor.cjs'),\n realGqlTagPluck.replace(/index\\.js$/, 'visitor.js'),\n );\n\n await fs.copyFile(\n path.join(vendorGqlTagPluck, 'visitor.mjs'),\n realGqlTagPluck.replace('cjs', 'esm').replace(/index\\.js$/, 'visitor.js'),\n );\n}\n\n/**\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
+ {"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"]}
@@ -32,7 +32,10 @@ const buildTypeLines = (name, operations) => {
32
32
  `];
33
33
  for (const [originalString, typeNames] of operations) {
34
34
  lines.push(
35
- ` ${JSON.stringify(originalString)}: {return: ${typeNames.length === 1 ? typeNames[0] : "never"}, variables: ${typeNames.map((n) => n + "Variables").join(" & ")}},
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(" & ")}},
36
39
  `
37
40
  );
38
41
  }
@@ -1 +1 @@
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,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AiB,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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AM,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"]}
@@ -6,7 +6,8 @@ var typescriptOperationPlugin = require('@graphql-codegen/typescript-operations'
6
6
  var sources_js = require('./sources.cjs');
7
7
  var plugin_js = require('./plugin.cjs');
8
8
 
9
- function _interopNamespaceDefault(e) {
9
+ function _interopNamespace(e) {
10
+ if (e && e.__esModule) return e;
10
11
  var n = Object.create(null);
11
12
  if (e) {
12
13
  Object.keys(e).forEach(function (k) {
@@ -23,9 +24,9 @@ function _interopNamespaceDefault(e) {
23
24
  return Object.freeze(n);
24
25
  }
25
26
 
26
- var addPlugin__namespace = /*#__PURE__*/_interopNamespaceDefault(addPlugin);
27
- var typescriptPlugin__namespace = /*#__PURE__*/_interopNamespaceDefault(typescriptPlugin);
28
- var typescriptOperationPlugin__namespace = /*#__PURE__*/_interopNamespaceDefault(typescriptOperationPlugin);
27
+ var addPlugin__namespace = /*#__PURE__*/_interopNamespace(addPlugin);
28
+ var typescriptPlugin__namespace = /*#__PURE__*/_interopNamespace(typescriptPlugin);
29
+ var typescriptOperationPlugin__namespace = /*#__PURE__*/_interopNamespace(typescriptOperationPlugin);
29
30
 
30
31
  const defaultInterfaceExtensionCode = `
31
32
  declare module '@shopify/hydrogen' {
@@ -59,6 +60,7 @@ const preset = {
59
60
  [`gen-dts`]: { plugin: plugin_js.plugin }
60
61
  };
61
62
  const plugins = [
63
+ // 1. Disable eslint for the generated file
62
64
  {
63
65
  [`add`]: {
64
66
  content: `/* eslint-disable eslint-comments/disable-enable-pair */
@@ -66,6 +68,7 @@ const preset = {
66
68
  /* eslint-disable */`
67
69
  }
68
70
  },
71
+ // 2. Import all the generated API types from Hydrogen or generate all the types from the schema.
69
72
  importTypes ? {
70
73
  [`add`]: {
71
74
  content: `import * as ${namespacedImportName} from '${importTypesFrom}';
@@ -78,16 +81,23 @@ const preset = {
78
81
  enumsAsTypes: true
79
82
  }
80
83
  },
84
+ // 3. Generate the operations (i.e. queries, mutations, and fragments types)
81
85
  {
82
86
  [`typescript-operations`]: {
83
87
  useTypeImports: true,
88
+ // Use `import type` instead of `import`
84
89
  preResolveTypes: false,
90
+ // Use Pick<...> instead of primitives
85
91
  mergeFragmentTypes: true,
92
+ // Merge equal fragment interfaces. Avoids adding `| {}` to Metaobject
86
93
  skipTypename: options.presetConfig.skipTypenameInOperations ?? true,
94
+ // Skip __typename fields
87
95
  namespacedImportName: importTypes ? namespacedImportName : void 0
88
96
  }
89
97
  },
98
+ // 4. Augment Hydrogen query/mutation interfaces with the generated operations
90
99
  { [`gen-dts`]: { sourcesWithOperations, interfaceExtensionCode } },
100
+ // 5. Custom plugins from the user
91
101
  ...options.plugins
92
102
  ];
93
103
  return [
@@ -97,7 +107,9 @@ const preset = {
97
107
  pluginMap,
98
108
  schema: options.schema,
99
109
  config: {
110
+ // For the TS plugin:
100
111
  defaultScalarType: "unknown",
112
+ // Allow overwriting defaults:
101
113
  ...options.config
102
114
  },
103
115
  documents: sources,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/preset.ts"],"names":[],"mappings":"AACA,YAAY,eAAe;AAC3B,YAAY,sBAAsB;AAClC,YAAY,+BAA+B;AAC3C,SAAQ,sBAAqB;AAC7B;AAAA,EACE,UAAU;AAAA,EACV;AAAA,EACA;AAAA,OACK;AAgCA,MAAM,gCAAgC;AAAA;AAAA,wCAEL;A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ACjB,oBAAoB;AAAA,UACpB,cAAc,QAAQ,aAAa,4BAA4B;AAAA,UAC/D,sBAAsB,cAAc,uBAAuB;AAAA,QAC7D;AAAA,MACF;AAAA,MAEA,EAAC,CAAC,YAAY,EAAC,uBAAuB,uBAAsB,EAAC;AAAA,MAE7D,GAAG,QAAQ;AAAA,IACb;AAEA,WAAO;AAAA,MACL;AAAA,QACE,UAAU,QAAQ;AAAA,QAClB;AAAA,QACA;AAAA,QACA,QAAQ,QAAQ;AAAA,QAChB,QAAQ;AAAA,UAEN,mBAAmB;AAAA,UAEnB,GAAG,QAAQ;AAAA,QACb;AAAA,QACA,WAAW;AAAA,QACX,oBAAoB,QAAQ;AAAA,MAC9B;AAAA,IACF;AAAA,EACF;AACF","sourcesContent":["import type {Types} from '@graphql-codegen/plugin-helpers';\nimport * as addPlugin from '@graphql-codegen/add';\nimport * as typescriptPlugin from '@graphql-codegen/typescript';\nimport * as typescriptOperationPlugin from '@graphql-codegen/typescript-operations';\nimport {processSources} from './sources.js';\nimport {\n plugin as dtsPlugin,\n GENERATED_MUTATION_INTERFACE_NAME,\n GENERATED_QUERY_INTERFACE_NAME,\n} from './plugin.js';\n\nexport type HydrogenPresetConfig = {\n /**\n * Name for the variable that contains the imported types.\n * @default 'StorefrontAPI'\n */\n namespacedImportName?: string;\n /**\n * Module to import the types from.\n * @default '@shopify/hydrogen/storefront-api-types'\n */\n importTypesFrom?: string;\n /**\n * Whether types should be imported from the `importTypesFrom` module, or generated inline.\n * @default true\n */\n importTypes?: boolean;\n /**\n * Whether to skip adding `__typename` to generated operation types.\n * @default true\n */\n skipTypenameInOperations?: boolean;\n /**\n * Override the default interface extension.\n */\n interfaceExtension?: (options: {\n queryType: string;\n mutationType: string;\n }) => string;\n};\n\nexport const defaultInterfaceExtensionCode = `\ndeclare module '@shopify/hydrogen' {\n interface StorefrontQueries extends ${GENERATED_QUERY_INTERFACE_NAME} {}\n interface StorefrontMutations extends ${GENERATED_MUTATION_INTERFACE_NAME} {}\n}`;\n\nexport const preset: Types.OutputPreset<HydrogenPresetConfig> = {\n buildGeneratesSection: (options) => {\n if (!options.baseOutputDir.endsWith('.d.ts')) {\n throw new Error('[hydrogen-preset] target output should be a .d.ts file');\n }\n\n if (\n options.plugins?.length > 0 &&\n Object.keys(options.plugins).some((p) => p.startsWith('typescript'))\n ) {\n throw new Error(\n '[hydrogen-preset] providing additional typescript-based `plugins` leads to duplicated generated types',\n );\n }\n\n const sourcesWithOperations = processSources(options.documents);\n const sources = sourcesWithOperations.map(({source}) => source);\n\n const importTypes = options.presetConfig.importTypes ?? true;\n const namespacedImportName =\n options.presetConfig.namespacedImportName ?? 'StorefrontAPI';\n const importTypesFrom =\n options.presetConfig.importTypesFrom ??\n '@shopify/hydrogen/storefront-api-types';\n\n const interfaceExtensionCode =\n options.presetConfig.interfaceExtension?.({\n queryType: GENERATED_QUERY_INTERFACE_NAME,\n mutationType: GENERATED_MUTATION_INTERFACE_NAME,\n }) ?? defaultInterfaceExtensionCode;\n\n const pluginMap = {\n ...options.pluginMap,\n [`add`]: addPlugin,\n [`typescript`]: typescriptPlugin,\n [`typescript-operations`]: typescriptOperationPlugin,\n [`gen-dts`]: {plugin: dtsPlugin},\n };\n\n const plugins: Array<Types.ConfiguredPlugin> = [\n // 1. Disable eslint for the generated file\n {\n [`add`]: {\n content: `/* eslint-disable eslint-comments/disable-enable-pair */\\n/* eslint-disable eslint-comments/no-unlimited-disable */\\n/* eslint-disable */`,\n },\n },\n // 2. Import all the generated API types from Hydrogen or generate all the types from the schema.\n importTypes\n ? {\n [`add`]: {\n content: `import * as ${namespacedImportName} from '${importTypesFrom}';\\n`,\n },\n }\n : {\n [`typescript`]: {\n useTypeImports: true,\n useImplementingTypes: true,\n enumsAsTypes: true,\n },\n },\n // 3. Generate the operations (i.e. queries, mutations, and fragments types)\n {\n [`typescript-operations`]: {\n useTypeImports: true, // Use `import type` instead of `import`\n preResolveTypes: false, // Use Pick<...> instead of primitives\n mergeFragmentTypes: true, // Merge equal fragment interfaces. Avoids adding `| {}` to Metaobject\n skipTypename: options.presetConfig.skipTypenameInOperations ?? true, // Skip __typename fields\n namespacedImportName: importTypes ? namespacedImportName : undefined,\n },\n },\n // 4. Augment Hydrogen query/mutation interfaces with the generated operations\n {[`gen-dts`]: {sourcesWithOperations, interfaceExtensionCode}},\n // 5. Custom plugins from the user\n ...options.plugins,\n ];\n\n return [\n {\n filename: options.baseOutputDir,\n plugins,\n pluginMap,\n schema: options.schema,\n config: {\n // For the TS plugin:\n defaultScalarType: 'unknown',\n // Allow overwriting defaults:\n ...options.config,\n },\n documents: sources,\n documentTransforms: options.documentTransforms,\n },\n ];\n },\n};\n"]}
1
+ {"version":3,"sources":["../../src/preset.ts"],"names":[],"mappings":"AACA,YAAY,eAAe;AAC3B,YAAY,sBAAsB;AAClC,YAAY,+BAA+B;AAC3C,SAAQ,sBAAqB;AAC7B;AAAA,EACE,UAAU;AAAA,EACV;AAAA,EACA;AAAA,OACK;AAgCA,MAAM,gCAAgC;AAAA;AAAA,wCAEL,8BAA8B;AAAA,0CAC5B,iCAAiC;AAAA;AAGpE,MAAM,SAAmD;AAAA,EAC9D,uBAAuB,CAAC,YAAY;AAClC,QAAI,CAAC,QAAQ,cAAc,SAAS,OAAO,GAAG;AAC5C,YAAM,IAAI,MAAM,wDAAwD;AAAA,IAC1E;AAEA,QACE,QAAQ,SAAS,SAAS,KAC1B,OAAO,KAAK,QAAQ,OAAO,EAAE,KAAK,CAAC,MAAM,EAAE,WAAW,YAAY,CAAC,GACnE;AACA,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,UAAM,wBAAwB,eAAe,QAAQ,SAAS;AAC9D,UAAM,UAAU,sBAAsB,IAAI,CAAC,EAAC,OAAM,MAAM,MAAM;AAE9D,UAAM,cAAc,QAAQ,aAAa,eAAe;AACxD,UAAM,uBACJ,QAAQ,aAAa,wBAAwB;AAC/C,UAAM,kBACJ,QAAQ,aAAa,mBACrB;AAEF,UAAM,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AA,IACF;AAAA,EACF;AACF","sourcesContent":["import type {Types} from '@graphql-codegen/plugin-helpers';\nimport * as addPlugin from '@graphql-codegen/add';\nimport * as typescriptPlugin from '@graphql-codegen/typescript';\nimport * as typescriptOperationPlugin from '@graphql-codegen/typescript-operations';\nimport {processSources} from './sources.js';\nimport {\n plugin as dtsPlugin,\n GENERATED_MUTATION_INTERFACE_NAME,\n GENERATED_QUERY_INTERFACE_NAME,\n} from './plugin.js';\n\nexport type HydrogenPresetConfig = {\n /**\n * Name for the variable that contains the imported types.\n * @default 'StorefrontAPI'\n */\n namespacedImportName?: string;\n /**\n * Module to import the types from.\n * @default '@shopify/hydrogen/storefront-api-types'\n */\n importTypesFrom?: string;\n /**\n * Whether types should be imported from the `importTypesFrom` module, or generated inline.\n * @default true\n */\n importTypes?: boolean;\n /**\n * Whether to skip adding `__typename` to generated operation types.\n * @default true\n */\n skipTypenameInOperations?: boolean;\n /**\n * Override the default interface extension.\n */\n interfaceExtension?: (options: {\n queryType: string;\n mutationType: string;\n }) => string;\n};\n\nexport const defaultInterfaceExtensionCode = `\ndeclare module '@shopify/hydrogen' {\n interface StorefrontQueries extends ${GENERATED_QUERY_INTERFACE_NAME} {}\n interface StorefrontMutations extends ${GENERATED_MUTATION_INTERFACE_NAME} {}\n}`;\n\nexport const preset: Types.OutputPreset<HydrogenPresetConfig> = {\n buildGeneratesSection: (options) => {\n if (!options.baseOutputDir.endsWith('.d.ts')) {\n throw new Error('[hydrogen-preset] target output should be a .d.ts file');\n }\n\n if (\n options.plugins?.length > 0 &&\n Object.keys(options.plugins).some((p) => p.startsWith('typescript'))\n ) {\n throw new Error(\n '[hydrogen-preset] providing additional typescript-based `plugins` leads to duplicated generated types',\n );\n }\n\n const sourcesWithOperations = processSources(options.documents);\n const sources = sourcesWithOperations.map(({source}) => source);\n\n const importTypes = options.presetConfig.importTypes ?? true;\n const namespacedImportName =\n options.presetConfig.namespacedImportName ?? 'StorefrontAPI';\n const importTypesFrom =\n options.presetConfig.importTypesFrom ??\n '@shopify/hydrogen/storefront-api-types';\n\n const interfaceExtensionCode =\n options.presetConfig.interfaceExtension?.({\n queryType: GENERATED_QUERY_INTERFACE_NAME,\n mutationType: GENERATED_MUTATION_INTERFACE_NAME,\n }) ?? defaultInterfaceExtensionCode;\n\n const pluginMap = {\n ...options.pluginMap,\n [`add`]: addPlugin,\n [`typescript`]: typescriptPlugin,\n [`typescript-operations`]: typescriptOperationPlugin,\n [`gen-dts`]: {plugin: dtsPlugin},\n };\n\n const plugins: Array<Types.ConfiguredPlugin> = [\n // 1. Disable eslint for the generated file\n {\n [`add`]: {\n content: `/* eslint-disable eslint-comments/disable-enable-pair */\\n/* eslint-disable eslint-comments/no-unlimited-disable */\\n/* eslint-disable */`,\n },\n },\n // 2. Import all the generated API types from Hydrogen or generate all the types from the schema.\n importTypes\n ? {\n [`add`]: {\n content: `import * as ${namespacedImportName} from '${importTypesFrom}';\\n`,\n },\n }\n : {\n [`typescript`]: {\n useTypeImports: true,\n useImplementingTypes: true,\n enumsAsTypes: true,\n },\n },\n // 3. Generate the operations (i.e. queries, mutations, and fragments types)\n {\n [`typescript-operations`]: {\n useTypeImports: true, // Use `import type` instead of `import`\n preResolveTypes: false, // Use Pick<...> instead of primitives\n mergeFragmentTypes: true, // Merge equal fragment interfaces. Avoids adding `| {}` to Metaobject\n skipTypename: options.presetConfig.skipTypenameInOperations ?? true, // Skip __typename fields\n namespacedImportName: importTypes ? namespacedImportName : undefined,\n },\n },\n // 4. Augment Hydrogen query/mutation interfaces with the generated operations\n {[`gen-dts`]: {sourcesWithOperations, interfaceExtensionCode}},\n // 5. Custom plugins from the user\n ...options.plugins,\n ];\n\n return [\n {\n filename: options.baseOutputDir,\n plugins,\n pluginMap,\n schema: options.schema,\n config: {\n // For the TS plugin:\n defaultScalarType: 'unknown',\n // Allow overwriting defaults:\n ...options.config,\n },\n documents: sources,\n documentTransforms: options.documentTransforms,\n },\n ];\n },\n};\n"]}
@@ -6,10 +6,6 @@ let staticSchema = "";
6
6
  try {
7
7
  staticSchema = getSchema();
8
8
  } catch (error) {
9
- console.warn(
10
- "[hydrogen-codegen] storefront.schema.json not found. Is `@shopify/hydrogen` installed?\n",
11
- error.message
12
- );
13
9
  }
14
10
  const schema = staticSchema;
15
11
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/schema.ts"],"names":[],"mappings":"AACA;AACO,MAAM,YAAY,MACP;AAElB,IAAI,eAAe;AAEnB,IAAI;AACF,iBAAe,UAAU;AAC3B,SAAS,OAAP;AAGA,UAAQ;AAAA,IACN;AAAA,IACC,MAAgB;AAAA,EACnB;AACF;AAEO,MAAM,SAAS","sourcesContent":["// This comment is used during ESM build:\n//! import {createRequire} from 'module'; const require = createRequire(import.meta.url);\nexport const getSchema = () =>\n require.resolve('@shopify/hydrogen-react/storefront.schema.json');\n\nlet staticSchema = '';\n\ntry {\n staticSchema = getSchema();\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 console.warn(\n '[hydrogen-codegen] storefront.schema.json not found. Is `@shopify/hydrogen` installed?\\n',\n (error as Error).message,\n );\n}\n\nexport const schema = staticSchema;\n"]}
1
+ {"version":3,"sources":["../../src/schema.ts"],"names":[],"mappings":"AACA;AACO,MAAM,YAAY,MACvB,gBAAgB,gDAAgD;AAElE,IAAI,eAAe;AAEnB,IAAI;AACF,iBAAe,UAAU;AAC3B,SAAS,OAAO;AAIhB;AAEO,MAAM,SAAS","sourcesContent":["// This comment is used during ESM build:\n//! import {createRequire} from 'module'; const require = createRequire(import.meta.url);\nexport const getSchema = () =>\n require.resolve('@shopify/hydrogen-react/storefront.schema.json');\n\nlet staticSchema = '';\n\ntry {\n staticSchema = getSchema();\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\nexport const schema = staticSchema;\n"]}
@@ -2,7 +2,7 @@ export { preset } from './preset.js';
2
2
  export { plugin } from './plugin.js';
3
3
  export { getSchema, schema } from './schema.js';
4
4
  export { processSources } from './sources.js';
5
- export { patchGqlPluck, pluckConfig } from './pluck.js';
5
+ export { pluckConfig } from './pluck.js';
6
6
  import '@graphql-codegen/plugin-helpers';
7
7
  import '@graphql-tools/utils';
8
8
  import 'graphql';
package/dist/esm/index.js CHANGED
@@ -2,6 +2,6 @@ export { preset } from './preset.js';
2
2
  export { plugin } from './plugin.js';
3
3
  export { getSchema, schema } from './schema.js';
4
4
  export { processSources } from './sources.js';
5
- export { patchGqlPluck, pluckConfig } from './pluck.js';
5
+ export { pluckConfig } from './pluck.js';
6
6
  //# sourceMappingURL=out.js.map
7
7
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,SAAQ,cAAa;AACrB,SAAQ,cAAa;AACrB,SAAQ,QAAQ,iBAAgB;AAChC,SAAQ,sBAAqB;AAC7B,SAAQ,aAAa,qBAAoB","sourcesContent":["export {preset} from './preset.js';\nexport {plugin} from './plugin.js';\nexport {schema, getSchema} from './schema.js';\nexport {processSources} from './sources.js';\nexport {pluckConfig, patchGqlPluck} from './pluck.js';\n"]}
1
+ {"version":3,"sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,SAAQ,cAAa;AACrB,SAAQ,cAAa;AACrB,SAAQ,QAAQ,iBAAgB;AAChC,SAAQ,sBAAqB;AAC7B,SAAQ,mBAAkB","sourcesContent":["export {preset} from './preset.js';\nexport {plugin} from './plugin.js';\nexport {schema, getSchema} from './schema.js';\nexport {processSources} from './sources.js';\nexport {pluckConfig} from './pluck.js';\n"]}
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,45 @@
1
+ import path from 'node:path';
2
+ import fs from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ const require2 = createRequire(import.meta.url);
7
+ const realGqlTagPluck = require2.resolve("@graphql-tools/graphql-tag-pluck");
8
+ const depth = path.extname(import.meta.url) === ".ts" ? "../" : "../../";
9
+ const vendorGqlTagPluck = fileURLToPath(
10
+ new URL(depth + "/vendor/graphql-tag-pluck", import.meta.url)
11
+ );
12
+ fs.copyFileSync(
13
+ path.join(vendorGqlTagPluck, "visitor.cjs"),
14
+ realGqlTagPluck.replace(/index\.js$/, "visitor.js")
15
+ );
16
+ fs.copyFileSync(
17
+ path.join(vendorGqlTagPluck, "visitor.mjs"),
18
+ realGqlTagPluck.replace("cjs", "esm").replace(/index\.js$/, "visitor.js")
19
+ );
20
+ const visitorPluginCommon = require2.resolve(
21
+ "@graphql-codegen/visitor-plugin-common"
22
+ );
23
+ const selectionSetToObjectFileCJS = visitorPluginCommon.replace(
24
+ "index.js",
25
+ "selection-set-to-object.js"
26
+ );
27
+ const selectionSetToObjectFileESM = selectionSetToObjectFileCJS.replace(
28
+ "cjs",
29
+ "esm"
30
+ );
31
+ fs.writeFileSync(
32
+ selectionSetToObjectFileCJS,
33
+ patchSelectionSet(fs.readFileSync(selectionSetToObjectFileCJS, "utf-8")),
34
+ "utf-8"
35
+ );
36
+ fs.writeFileSync(
37
+ selectionSetToObjectFileESM,
38
+ patchSelectionSet(fs.readFileSync(selectionSetToObjectFileESM, "utf-8")),
39
+ "utf-8"
40
+ );
41
+ function patchSelectionSet(content) {
42
+ return content.replace("&& s.union", "&& s?.union");
43
+ }
44
+ //# sourceMappingURL=out.js.map
45
+ //# sourceMappingURL=patch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/patch.ts"],"names":["require"],"mappings":"AAAA,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,SAAQ,qBAAoB;AAC5B,SAAQ,qBAAoB;AAK5B,MAAMA,WAAU,cAAc,YAAY,GAAG;AAC7C,MAAM,kBAAkBA,SAAQ,QAAQ,kCAAkC;AAG1E,MAAM,QAAQ,KAAK,QAAQ,YAAY,GAAG,MAAM,QAAQ,QAAQ;AAChE,MAAM,oBAAoB;AAAA,EACxB,IAAI,IAAI,QAAQ,6BAA6B,YAAY,GAAG;AAC9D;AAGA,GAAG;AAAA,EACD,KAAK,KAAK,mBAAmB,aAAa;AAAA,EAC1C,gBAAgB,QAAQ,cAAc,YAAY;AACpD;AAEA,GAAG;AAAA,EACD,KAAK,KAAK,mBAAmB,aAAa;AAAA,EAC1C,gBAAgB,QAAQ,OAAO,KAAK,EAAE,QAAQ,cAAc,YAAY;AAC1E;AAMA,MAAM,sBAAsBA,SAAQ;AAAA,EAClC;AACF;AACA,MAAM,8BAA8B,oBAAoB;AAAA,EACtD;AAAA,EACA;AACF;AACA,MAAM,8BAA8B,4BAA4B;AAAA,EAC9D;AAAA,EACA;AACF;AAEA,GAAG;AAAA,EACD;AAAA,EACA,kBAAkB,GAAG,aAAa,6BAA6B,OAAO,CAAC;AAAA,EACvE;AACF;AAEA,GAAG;AAAA,EACD;AAAA,EACA,kBAAkB,GAAG,aAAa,6BAA6B,OAAO,CAAC;AAAA,EACvE;AACF;AAEA,SAAS,kBAAkB,SAAiB;AAC1C,SAAO,QAAQ,QAAQ,cAAc,aAAa;AACpD","sourcesContent":["import path from 'node:path';\nimport fs from 'node:fs';\nimport {createRequire} from 'node:module';\nimport {fileURLToPath} from 'node:url';\n\n/**\n * Patch graphql-tag-pluck to allow it to work with `#graphql` comment and other features.\n */\nconst require = createRequire(import.meta.url);\nconst realGqlTagPluck = require.resolve('@graphql-tools/graphql-tag-pluck');\n// During tests, this file is in src/xyz.ts but in dev/prod,\n// the file is in dist/(esm|cjs)/xyz.js\nconst depth = path.extname(import.meta.url) === '.ts' ? '../' : '../../';\nconst vendorGqlTagPluck = fileURLToPath(\n new URL(depth + '/vendor/graphql-tag-pluck', import.meta.url),\n);\n\n// Copy files sequencially to avoid `EBUSY` errors in Windows\nfs.copyFileSync(\n path.join(vendorGqlTagPluck, 'visitor.cjs'),\n realGqlTagPluck.replace(/index\\.js$/, 'visitor.js'),\n);\n\nfs.copyFileSync(\n path.join(vendorGqlTagPluck, 'visitor.mjs'),\n realGqlTagPluck.replace('cjs', 'esm').replace(/index\\.js$/, 'visitor.js'),\n);\n\n/**\n * Temporary patch for a bug in another package\n * https://github.com/dotansimha/graphql-code-generator/pull/9709\n */\nconst visitorPluginCommon = require.resolve(\n '@graphql-codegen/visitor-plugin-common',\n);\nconst selectionSetToObjectFileCJS = visitorPluginCommon.replace(\n 'index.js',\n 'selection-set-to-object.js',\n);\nconst selectionSetToObjectFileESM = selectionSetToObjectFileCJS.replace(\n 'cjs',\n 'esm',\n);\n\nfs.writeFileSync(\n selectionSetToObjectFileCJS,\n patchSelectionSet(fs.readFileSync(selectionSetToObjectFileCJS, 'utf-8')),\n 'utf-8',\n);\n\nfs.writeFileSync(\n selectionSetToObjectFileESM,\n patchSelectionSet(fs.readFileSync(selectionSetToObjectFileESM, 'utf-8')),\n 'utf-8',\n);\n\nfunction patchSelectionSet(content: string) {\n return content.replace('&& s.union', '&& s?.union');\n}\n"]}
@@ -1,4 +1,3 @@
1
- declare function patchGqlPluck(): Promise<void>;
2
1
  /**
3
2
  * This is a modified version of graphql-tag-pluck's default config.
4
3
  * https://github.com/ardatan/graphql-tools/issues/5127
@@ -20,4 +19,4 @@ declare const pluckConfig: {
20
19
  pluckStringFromFile: (code: string, { start, end, leadingComments }: any) => string;
21
20
  };
22
21
 
23
- export { patchGqlPluck, pluckConfig };
22
+ export { pluckConfig };
package/dist/esm/pluck.js CHANGED
@@ -1,25 +1,8 @@
1
- import fs from 'fs/promises';
2
- import path from 'path';
3
- import { createRequire } from 'node:module';
4
- import { fileURLToPath } from 'node:url';
5
-
6
- async function patchGqlPluck() {
7
- const require2 = createRequire(import.meta.url);
8
- const realGqlTagPluck = require2.resolve("@graphql-tools/graphql-tag-pluck");
9
- const depth = path.extname(import.meta.url) === ".ts" ? "../" : "../../";
10
- const vendorGqlTagPluck = fileURLToPath(
11
- new URL(depth + "/vendor/graphql-tag-pluck", import.meta.url)
12
- );
13
- await fs.copyFile(
14
- path.join(vendorGqlTagPluck, "visitor.cjs"),
15
- realGqlTagPluck.replace(/index\.js$/, "visitor.js")
16
- );
17
- await fs.copyFile(
18
- path.join(vendorGqlTagPluck, "visitor.mjs"),
19
- realGqlTagPluck.replace("cjs", "esm").replace(/index\.js$/, "visitor.js")
20
- );
21
- }
22
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
+ */
23
6
  isGqlTemplateLiteral: (node, options) => {
24
7
  const hasInternalGqlComment = node.type === "TemplateLiteral" && /\s*#graphql\s*\n/i.test(node.quasis[0]?.value?.raw || "");
25
8
  if (hasInternalGqlComment)
@@ -29,6 +12,14 @@ const pluckConfig = {
29
12
  const leadingCommentValue = leadingComment?.value?.trim().toLowerCase();
30
13
  return leadingCommentValue === options?.gqlMagicComment;
31
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
+ */
32
23
  pluckStringFromFile: (code, { start, end, leadingComments }) => {
33
24
  let gqlTemplate = code.slice(start + 1, end - 1).replace(/\$\{([^}]*)\}/g, (_, m1) => "#REQUIRED_VAR=" + m1).split("\\`").join("`");
34
25
  const chunkStart = leadingComments?.[0]?.start ?? start;
@@ -41,6 +32,6 @@ const pluckConfig = {
41
32
  }
42
33
  };
43
34
 
44
- export { patchGqlPluck, pluckConfig };
35
+ export { pluckConfig };
45
36
  //# sourceMappingURL=out.js.map
46
37
  //# sourceMappingURL=pluck.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/pluck.ts"],"names":["require"],"mappings":"AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAQ,qBAAoB;AAC5B,SAAQ,qBAAoB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S;AAGX,qBAAe,eAAe;AAAA,IAChC;AAEA,WAAO;AAAA,EACT;AACF","sourcesContent":["import fs from 'fs/promises';\nimport path from 'path';\nimport {createRequire} from 'node:module';\nimport {fileURLToPath} from 'node:url';\n\nexport async function patchGqlPluck() {\n const require = createRequire(import.meta.url);\n const realGqlTagPluck = require.resolve('@graphql-tools/graphql-tag-pluck');\n // During tests, this file is in src/xyz.ts but in dev/prod,\n // the file is in dist/(esm|cjs)/xyz.js\n const depth = path.extname(import.meta.url) === '.ts' ? '../' : '../../';\n const vendorGqlTagPluck = fileURLToPath(\n new URL(depth + '/vendor/graphql-tag-pluck', import.meta.url),\n );\n\n // Copy files sequencially to avoid `EBUSY` errors in Windows\n await fs.copyFile(\n path.join(vendorGqlTagPluck, 'visitor.cjs'),\n realGqlTagPluck.replace(/index\\.js$/, 'visitor.js'),\n );\n\n await fs.copyFile(\n path.join(vendorGqlTagPluck, 'visitor.mjs'),\n realGqlTagPluck.replace('cjs', 'esm').replace(/index\\.js$/, 'visitor.js'),\n );\n}\n\n/**\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
+ {"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"]}
@@ -30,7 +30,10 @@ const buildTypeLines = (name, operations) => {
30
30
  `];
31
31
  for (const [originalString, typeNames] of operations) {
32
32
  lines.push(
33
- ` ${JSON.stringify(originalString)}: {return: ${typeNames.length === 1 ? typeNames[0] : "never"}, variables: ${typeNames.map((n) => n + "Variables").join(" & ")}},
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(" & ")}},
34
37
  `
35
38
  );
36
39
  }
@@ -1 +1 @@
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;AAAA,UACf;AAAA,QACF;AAAA,MACF;AAAA,IACF;A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`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
+ {"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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,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"]}
@@ -29,7 +29,7 @@ type HydrogenPresetConfig = {
29
29
  mutationType: string;
30
30
  }) => string;
31
31
  };
32
- declare const defaultInterfaceExtensionCode: string;
32
+ declare const defaultInterfaceExtensionCode = "\ndeclare module '@shopify/hydrogen' {\n interface StorefrontQueries extends GeneratedQueryTypes {}\n interface StorefrontMutations extends GeneratedMutationTypes {}\n}";
33
33
  declare const preset: Types.OutputPreset<HydrogenPresetConfig>;
34
34
 
35
35
  export { HydrogenPresetConfig, defaultInterfaceExtensionCode, preset };
@@ -36,6 +36,7 @@ const preset = {
36
36
  [`gen-dts`]: { plugin: plugin }
37
37
  };
38
38
  const plugins = [
39
+ // 1. Disable eslint for the generated file
39
40
  {
40
41
  [`add`]: {
41
42
  content: `/* eslint-disable eslint-comments/disable-enable-pair */
@@ -43,6 +44,7 @@ const preset = {
43
44
  /* eslint-disable */`
44
45
  }
45
46
  },
47
+ // 2. Import all the generated API types from Hydrogen or generate all the types from the schema.
46
48
  importTypes ? {
47
49
  [`add`]: {
48
50
  content: `import * as ${namespacedImportName} from '${importTypesFrom}';
@@ -55,16 +57,23 @@ const preset = {
55
57
  enumsAsTypes: true
56
58
  }
57
59
  },
60
+ // 3. Generate the operations (i.e. queries, mutations, and fragments types)
58
61
  {
59
62
  [`typescript-operations`]: {
60
63
  useTypeImports: true,
64
+ // Use `import type` instead of `import`
61
65
  preResolveTypes: false,
66
+ // Use Pick<...> instead of primitives
62
67
  mergeFragmentTypes: true,
68
+ // Merge equal fragment interfaces. Avoids adding `| {}` to Metaobject
63
69
  skipTypename: options.presetConfig.skipTypenameInOperations ?? true,
70
+ // Skip __typename fields
64
71
  namespacedImportName: importTypes ? namespacedImportName : void 0
65
72
  }
66
73
  },
74
+ // 4. Augment Hydrogen query/mutation interfaces with the generated operations
67
75
  { [`gen-dts`]: { sourcesWithOperations, interfaceExtensionCode } },
76
+ // 5. Custom plugins from the user
68
77
  ...options.plugins
69
78
  ];
70
79
  return [
@@ -74,7 +83,9 @@ const preset = {
74
83
  pluginMap,
75
84
  schema: options.schema,
76
85
  config: {
86
+ // For the TS plugin:
77
87
  defaultScalarType: "unknown",
88
+ // Allow overwriting defaults:
78
89
  ...options.config
79
90
  },
80
91
  documents: sources,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/preset.ts"],"names":[],"mappings":"AACA,YAAY,eAAe;AAC3B,YAAY,sBAAsB;AAClC,YAAY,+BAA+B;AAC3C,SAAQ,sBAAqB;AAC7B;AAAA,EACE,UAAU;AAAA,EACV;AAAA,EACA;AAAA,OACK;AAgCA,MAAM,gCAAgC;AAAA;AAAA,wCAEL;AAAA,0CACE;AAAA;AAGnC,MAAM,SAAmD;AAAA,EAC9D,uBAAuB,CAAC,YAAY;AAClC,QAAI,CAAC,QAAQ,cAAc,SAAS,OAAO,GAAG;AAC5C,YAAM,IAAI,MAAM,wDAAwD;AAAA,IAC1E;AAEA,QACE,QAAQ,SAAS,SAAS,KAC1B,OAAO,KAAK,QAAQ,OAAO,EAAE,KAAK,CAAC,MAAM,EAAE,WAAW,YAAY,CAAC,GACnE;AACA,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,UAAM,wBAAwB,eAAe,QAAQ,SAAS;AAC9D,UAAM,UAAU,sBAAsB,IAAI,CAAC,EAAC,OAAM,MAAM,MAAM;AAE9D,UAAM,cAAc,QAAQ,aAAa,eAAe;AACxD,UAAM,uBACJ,QAAQ,aAAa,wBAAwB;AAC/C,UAAM,kBACJ,QAAQ,aAAa,mBACrB;AAEF,UAAM,yBACJ,QAAQ,aAAa,qBAAqB;AAAA,MACxC,WAAW;AAAA,MACX,cAAc;AAAA,IAChB,CAAC,KAAK;AAER,UAAM,YAAY;AAAA,MAChB,GAAG,QAAQ;AAAA,MACX,CAAC,QAAQ;AAAA,MACT,CAAC,eAAe;AAAA,MAChB,CAAC,0BAA0B;AAAA,MAC3B,CAAC,YAAY,EAAC,QAAQ,UAAS;AAAA,IACjC;AAEA,UAAM,UAAyC;AAAA,MAE7C;AAAA,QACE,CAAC,QAAQ;AAAA,UACP,SAAS;AAAA;AAAA;AAAA,QACX;AAAA,MACF;AAAA,MAEA,cACI;AAAA,QACE,CAAC,QAAQ;AAAA,UACP,SAAS,eAAe,8BAA8B;AAAA;AAAA,QACxD;AAAA,MACF,IACA;AAAA,QACE,CAAC,eAAe;AAAA,UACd,gBAAgB;AAAA,UAChB,sBAAsB;AAAA,UACtB,cAAc;AAAA,QAChB;AAAA,MACF;AAAA,MAEJ;AAAA,QACE,CAAC,0BAA0B;AAAA,UACzB,gBAAgB;AAAA,UAChB,iBAAiB;AAAA,UACjB,oBAAoB;AAAA,UACpB,cAAc,QAAQ,aAAa,4BAA4B;AAAA,UAC/D,sBAAsB,cAAc,uBAAuB;AAAA,QAC7D;AAAA,MACF;AAAA,MAEA,EAAC,CAAC,YAAY,EAAC,uBAAuB,uBAAsB,EAAC;AAAA,MAE7D,GAAG,QAAQ;AAAA,IACb;AAEA,WAAO;AAAA,MACL;AAAA,QACE,UAAU,QAAQ;AAAA,QAClB;AAAA,QACA;AAAA,QACA,QAAQ,QAAQ;AAAA,QAChB,QAAQ;AAAA,UAEN,mBAAmB;AAAA,UAEnB,GAAG,QAAQ;AAAA,QACb;AAAA,QACA,WAAW;AAAA,QACX,oBAAoB,QAAQ;AAAA,MAC9B;AAAA,IACF;AAAA,EACF;AACF","sourcesContent":["import type {Types} from '@graphql-codegen/plugin-helpers';\nimport * as addPlugin from '@graphql-codegen/add';\nimport * as typescriptPlugin from '@graphql-codegen/typescript';\nimport * as typescriptOperationPlugin from '@graphql-codegen/typescript-operations';\nimport {processSources} from './sources.js';\nimport {\n plugin as dtsPlugin,\n GENERATED_MUTATION_INTERFACE_NAME,\n GENERATED_QUERY_INTERFACE_NAME,\n} from './plugin.js';\n\nexport type HydrogenPresetConfig = {\n /**\n * Name for the variable that contains the imported types.\n * @default 'StorefrontAPI'\n */\n namespacedImportName?: string;\n /**\n * Module to import the types from.\n * @default '@shopify/hydrogen/storefront-api-types'\n */\n importTypesFrom?: string;\n /**\n * Whether types should be imported from the `importTypesFrom` module, or generated inline.\n * @default true\n */\n importTypes?: boolean;\n /**\n * Whether to skip adding `__typename` to generated operation types.\n * @default true\n */\n skipTypenameInOperations?: boolean;\n /**\n * Override the default interface extension.\n */\n interfaceExtension?: (options: {\n queryType: string;\n mutationType: string;\n }) => string;\n};\n\nexport const defaultInterfaceExtensionCode = `\ndeclare module '@shopify/hydrogen' {\n interface StorefrontQueries extends ${GENERATED_QUERY_INTERFACE_NAME} {}\n interface StorefrontMutations extends ${GENERATED_MUTATION_INTERFACE_NAME} {}\n}`;\n\nexport const preset: Types.OutputPreset<HydrogenPresetConfig> = {\n buildGeneratesSection: (options) => {\n if (!options.baseOutputDir.endsWith('.d.ts')) {\n throw new Error('[hydrogen-preset] target output should be a .d.ts file');\n }\n\n if (\n options.plugins?.length > 0 &&\n Object.keys(options.plugins).some((p) => p.startsWith('typescript'))\n ) {\n throw new Error(\n '[hydrogen-preset] providing additional typescript-based `plugins` leads to duplicated generated types',\n );\n }\n\n const sourcesWithOperations = processSources(options.documents);\n const sources = sourcesWithOperations.map(({source}) => source);\n\n const importTypes = options.presetConfig.importTypes ?? true;\n const namespacedImportName =\n options.presetConfig.namespacedImportName ?? 'StorefrontAPI';\n const importTypesFrom =\n options.presetConfig.importTypesFrom ??\n '@shopify/hydrogen/storefront-api-types';\n\n const interfaceExtensionCode =\n options.presetConfig.interfaceExtension?.({\n queryType: GENERATED_QUERY_INTERFACE_NAME,\n mutationType: GENERATED_MUTATION_INTERFACE_NAME,\n }) ?? defaultInterfaceExtensionCode;\n\n const pluginMap = {\n ...options.pluginMap,\n [`add`]: addPlugin,\n [`typescript`]: typescriptPlugin,\n [`typescript-operations`]: typescriptOperationPlugin,\n [`gen-dts`]: {plugin: dtsPlugin},\n };\n\n const plugins: Array<Types.ConfiguredPlugin> = [\n // 1. Disable eslint for the generated file\n {\n [`add`]: {\n content: `/* eslint-disable eslint-comments/disable-enable-pair */\\n/* eslint-disable eslint-comments/no-unlimited-disable */\\n/* eslint-disable */`,\n },\n },\n // 2. Import all the generated API types from Hydrogen or generate all the types from the schema.\n importTypes\n ? {\n [`add`]: {\n content: `import * as ${namespacedImportName} from '${importTypesFrom}';\\n`,\n },\n }\n : {\n [`typescript`]: {\n useTypeImports: true,\n useImplementingTypes: true,\n enumsAsTypes: true,\n },\n },\n // 3. Generate the operations (i.e. queries, mutations, and fragments types)\n {\n [`typescript-operations`]: {\n useTypeImports: true, // Use `import type` instead of `import`\n preResolveTypes: false, // Use Pick<...> instead of primitives\n mergeFragmentTypes: true, // Merge equal fragment interfaces. Avoids adding `| {}` to Metaobject\n skipTypename: options.presetConfig.skipTypenameInOperations ?? true, // Skip __typename fields\n namespacedImportName: importTypes ? namespacedImportName : undefined,\n },\n },\n // 4. Augment Hydrogen query/mutation interfaces with the generated operations\n {[`gen-dts`]: {sourcesWithOperations, interfaceExtensionCode}},\n // 5. Custom plugins from the user\n ...options.plugins,\n ];\n\n return [\n {\n filename: options.baseOutputDir,\n plugins,\n pluginMap,\n schema: options.schema,\n config: {\n // For the TS plugin:\n defaultScalarType: 'unknown',\n // Allow overwriting defaults:\n ...options.config,\n },\n documents: sources,\n documentTransforms: options.documentTransforms,\n },\n ];\n },\n};\n"]}
1
+ {"version":3,"sources":["../../src/preset.ts"],"names":[],"mappings":"AACA,YAAY,eAAe;AAC3B,YAAY,sBAAsB;AAClC,YAAY,+BAA+B;AAC3C,SAAQ,sBAAqB;AAC7B;AAAA,EACE,UAAU;AAAA,EACV;AAAA,EACA;AAAA,OACK;AAgCA,MAAM,gCAAgC;AAAA;AAAA,wCAEL,8BAA8B;AAAA,0CAC5B,iCAAiC;AAAA;AAGpE,MAAM,SAAmD;AAAA,EAC9D,uBAAuB,CAAC,YAAY;AAClC,QAAI,CAAC,QAAQ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AoB;AAAA;AAAA,UACpB,cAAc,QAAQ,aAAa,4BAA4B;AAAA;AAAA,UAC/D,sBAAsB,cAAc,uBAAuB;AAAA,QAC7D;AAAA,MACF;AAAA;AAAA,MAEA,EAAC,CAAC,SAAS,GAAG,EAAC,uBAAuB,uBAAsB,EAAC;AAAA;AAAA,MAE7D,GAAG,QAAQ;AAAA,IACb;AAEA,WAAO;AAAA,MACL;AAAA,QACE,UAAU,QAAQ;AAAA,QAClB;AAAA,QACA;AAAA,QACA,QAAQ,QAAQ;AAAA,QAChB,QAAQ;AAAA;AAAA,UAEN,mBAAmB;AAAA;AAAA,UAEnB,GAAG,QAAQ;AAAA,QACb;AAAA,QACA,WAAW;AAAA,QACX,oBAAoB,QAAQ;AAAA,MAC9B;AAAA,IACF;AAAA,EACF;AACF","sourcesContent":["import type {Types} from '@graphql-codegen/plugin-helpers';\nimport * as addPlugin from '@graphql-codegen/add';\nimport * as typescriptPlugin from '@graphql-codegen/typescript';\nimport * as typescriptOperationPlugin from '@graphql-codegen/typescript-operations';\nimport {processSources} from './sources.js';\nimport {\n plugin as dtsPlugin,\n GENERATED_MUTATION_INTERFACE_NAME,\n GENERATED_QUERY_INTERFACE_NAME,\n} from './plugin.js';\n\nexport type HydrogenPresetConfig = {\n /**\n * Name for the variable that contains the imported types.\n * @default 'StorefrontAPI'\n */\n namespacedImportName?: string;\n /**\n * Module to import the types from.\n * @default '@shopify/hydrogen/storefront-api-types'\n */\n importTypesFrom?: string;\n /**\n * Whether types should be imported from the `importTypesFrom` module, or generated inline.\n * @default true\n */\n importTypes?: boolean;\n /**\n * Whether to skip adding `__typename` to generated operation types.\n * @default true\n */\n skipTypenameInOperations?: boolean;\n /**\n * Override the default interface extension.\n */\n interfaceExtension?: (options: {\n queryType: string;\n mutationType: string;\n }) => string;\n};\n\nexport const defaultInterfaceExtensionCode = `\ndeclare module '@shopify/hydrogen' {\n interface StorefrontQueries extends ${GENERATED_QUERY_INTERFACE_NAME} {}\n interface StorefrontMutations extends ${GENERATED_MUTATION_INTERFACE_NAME} {}\n}`;\n\nexport const preset: Types.OutputPreset<HydrogenPresetConfig> = {\n buildGeneratesSection: (options) => {\n if (!options.baseOutputDir.endsWith('.d.ts')) {\n throw new Error('[hydrogen-preset] target output should be a .d.ts file');\n }\n\n if (\n options.plugins?.length > 0 &&\n Object.keys(options.plugins).some((p) => p.startsWith('typescript'))\n ) {\n throw new Error(\n '[hydrogen-preset] providing additional typescript-based `plugins` leads to duplicated generated types',\n );\n }\n\n const sourcesWithOperations = processSources(options.documents);\n const sources = sourcesWithOperations.map(({source}) => source);\n\n const importTypes = options.presetConfig.importTypes ?? true;\n const namespacedImportName =\n options.presetConfig.namespacedImportName ?? 'StorefrontAPI';\n const importTypesFrom =\n options.presetConfig.importTypesFrom ??\n '@shopify/hydrogen/storefront-api-types';\n\n const interfaceExtensionCode =\n options.presetConfig.interfaceExtension?.({\n queryType: GENERATED_QUERY_INTERFACE_NAME,\n mutationType: GENERATED_MUTATION_INTERFACE_NAME,\n }) ?? defaultInterfaceExtensionCode;\n\n const pluginMap = {\n ...options.pluginMap,\n [`add`]: addPlugin,\n [`typescript`]: typescriptPlugin,\n [`typescript-operations`]: typescriptOperationPlugin,\n [`gen-dts`]: {plugin: dtsPlugin},\n };\n\n const plugins: Array<Types.ConfiguredPlugin> = [\n // 1. Disable eslint for the generated file\n {\n [`add`]: {\n content: `/* eslint-disable eslint-comments/disable-enable-pair */\\n/* eslint-disable eslint-comments/no-unlimited-disable */\\n/* eslint-disable */`,\n },\n },\n // 2. Import all the generated API types from Hydrogen or generate all the types from the schema.\n importTypes\n ? {\n [`add`]: {\n content: `import * as ${namespacedImportName} from '${importTypesFrom}';\\n`,\n },\n }\n : {\n [`typescript`]: {\n useTypeImports: true,\n useImplementingTypes: true,\n enumsAsTypes: true,\n },\n },\n // 3. Generate the operations (i.e. queries, mutations, and fragments types)\n {\n [`typescript-operations`]: {\n useTypeImports: true, // Use `import type` instead of `import`\n preResolveTypes: false, // Use Pick<...> instead of primitives\n mergeFragmentTypes: true, // Merge equal fragment interfaces. Avoids adding `| {}` to Metaobject\n skipTypename: options.presetConfig.skipTypenameInOperations ?? true, // Skip __typename fields\n namespacedImportName: importTypes ? namespacedImportName : undefined,\n },\n },\n // 4. Augment Hydrogen query/mutation interfaces with the generated operations\n {[`gen-dts`]: {sourcesWithOperations, interfaceExtensionCode}},\n // 5. Custom plugins from the user\n ...options.plugins,\n ];\n\n return [\n {\n filename: options.baseOutputDir,\n plugins,\n pluginMap,\n schema: options.schema,\n config: {\n // For the TS plugin:\n defaultScalarType: 'unknown',\n // Allow overwriting defaults:\n ...options.config,\n },\n documents: sources,\n documentTransforms: options.documentTransforms,\n },\n ];\n },\n};\n"]}
@@ -4,10 +4,6 @@ let staticSchema = "";
4
4
  try {
5
5
  staticSchema = getSchema();
6
6
  } catch (error) {
7
- console.warn(
8
- "[hydrogen-codegen] storefront.schema.json not found. Is `@shopify/hydrogen` installed?\n",
9
- error.message
10
- );
11
7
  }
12
8
  const schema = staticSchema;
13
9
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/schema.ts"],"names":[],"mappings":"AACA;AACO,MAAM,YAAY,MACP;AAElB,IAAI,eAAe;AAEnB,IAAI;AACF,iBAAe,UAAU;AAC3B,SAAS,OAAP;AAGA,UAAQ;AAAA,IACN;AAAA,IACC,MAAgB;AAAA,EACnB;AACF;AAEO,MAAM,SAAS","sourcesContent":["// This comment is used during ESM build:\n//! import {createRequire} from 'module'; const require = createRequire(import.meta.url);\nexport const getSchema = () =>\n require.resolve('@shopify/hydrogen-react/storefront.schema.json');\n\nlet staticSchema = '';\n\ntry {\n staticSchema = getSchema();\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 console.warn(\n '[hydrogen-codegen] storefront.schema.json not found. Is `@shopify/hydrogen` installed?\\n',\n (error as Error).message,\n );\n}\n\nexport const schema = staticSchema;\n"]}
1
+ {"version":3,"sources":["../../src/schema.ts"],"names":[],"mappings":"AACA;AACO,MAAM,YAAY,MACvB,gBAAgB,gDAAgD;AAElE,IAAI,eAAe;AAEnB,IAAI;AACF,iBAAe,UAAU;AAC3B,SAAS,OAAO;AAIhB;AAEO,MAAM,SAAS","sourcesContent":["// This comment is used during ESM build:\n//! import {createRequire} from 'module'; const require = createRequire(import.meta.url);\nexport const getSchema = () =>\n require.resolve('@shopify/hydrogen-react/storefront.schema.json');\n\nlet staticSchema = '';\n\ntry {\n staticSchema = getSchema();\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\nexport const schema = staticSchema;\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.0.2",
7
+ "version": "0.1.0",
8
8
  "license": "MIT",
9
9
  "type": "module",
10
10
  "main": "dist/cjs/index.cjs",
@@ -12,8 +12,8 @@
12
12
  "types": "dist/esm/index.d.ts",
13
13
  "sideEffects": false,
14
14
  "scripts": {
15
- "build": "tsup --clean --config ./tsup.config.ts",
16
- "dev": "tsup --watch --config ./tsup.config.ts",
15
+ "build": "tsup --clean",
16
+ "dev": "tsup --watch",
17
17
  "typecheck": "tsc --noEmit",
18
18
  "test": "cross-env SHOPIFY_UNIT_TEST=1 vitest run",
19
19
  "test:watch": "cross-env SHOPIFY_UNIT_TEST=1 vitest"
@@ -25,6 +25,12 @@
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
+ },
28
34
  "./package.json": "./package.json"
29
35
  },
30
36
  "repository": {
@@ -37,14 +43,15 @@
37
43
  "vendor"
38
44
  ],
39
45
  "devDependencies": {
40
- "@graphql-codegen/cli": "3.3.1",
41
- "@graphql-codegen/plugin-helpers": "^4.1.0",
42
- "@graphql-tools/utils": "^9.0.0"
46
+ "@graphql-codegen/cli": "^5.0.0",
47
+ "@graphql-codegen/plugin-helpers": "^5.0.0",
48
+ "@graphql-tools/utils": "^10.0.3",
49
+ "vitest": "^0.33.0"
43
50
  },
44
51
  "dependencies": {
45
- "@graphql-codegen/add": "^4.0.1",
46
- "@graphql-codegen/typescript": "^3.0.1",
47
- "@graphql-codegen/typescript-operations": "^3.0.1"
52
+ "@graphql-codegen/add": "^5.0.0",
53
+ "@graphql-codegen/typescript": "^4.0.1",
54
+ "@graphql-codegen/typescript-operations": "^4.0.1"
48
55
  },
49
56
  "peerDependencies": {
50
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"
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
  Object.defineProperty(exports, '__esModule', {value: true});
3
- const utils_js_1 = require('./utils.js');
4
3
  const types_1 = require('@babel/types');
5
4
  const utils_1 = require('@graphql-tools/utils');
5
+ const utils_js_1 = require('./utils.js');
6
6
  const defaults = {
7
7
  modules: [
8
8
  {
@@ -1,14 +1,14 @@
1
- import {freeText} from './utils.js';
2
1
  import {
3
- isVariableDeclarator,
4
2
  isIdentifier,
5
- isTemplateLiteral,
6
3
  isImportDefaultSpecifier,
7
4
  isImportSpecifier,
5
+ isTemplateLiteral,
8
6
  isTSAsExpression,
9
7
  isTSTypeReference,
8
+ isVariableDeclarator,
10
9
  } from '@babel/types';
11
10
  import {asArray} from '@graphql-tools/utils';
11
+ import {freeText} from './utils.js';
12
12
  const defaults = {
13
13
  modules: [
14
14
  {