@shopify/hydrogen-codegen 0.0.2 → 0.2.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.
Files changed (43) hide show
  1. package/README.md +53 -0
  2. package/dist/cjs/client.cjs +4 -0
  3. package/dist/cjs/client.cjs.map +1 -0
  4. package/dist/cjs/defaults.cjs +31 -0
  5. package/dist/cjs/defaults.cjs.map +1 -0
  6. package/dist/cjs/index.cjs +0 -4
  7. package/dist/cjs/index.cjs.map +1 -1
  8. package/dist/cjs/patch.cjs +53 -0
  9. package/dist/cjs/patch.cjs.map +1 -0
  10. package/dist/cjs/pluck.cjs +12 -22
  11. package/dist/cjs/pluck.cjs.map +1 -1
  12. package/dist/cjs/plugin.cjs +4 -1
  13. package/dist/cjs/plugin.cjs.map +1 -1
  14. package/dist/cjs/preset.cjs +22 -13
  15. package/dist/cjs/preset.cjs.map +1 -1
  16. package/dist/cjs/schema.cjs +11 -8
  17. package/dist/cjs/schema.cjs.map +1 -1
  18. package/dist/esm/client.js +3 -0
  19. package/dist/esm/client.js.map +1 -0
  20. package/dist/esm/defaults.js +29 -0
  21. package/dist/esm/defaults.js.map +1 -0
  22. package/dist/esm/index.d.ts +142 -8
  23. package/dist/esm/index.js +1 -1
  24. package/dist/esm/index.js.map +1 -1
  25. package/dist/esm/patch.d.ts +2 -0
  26. package/dist/esm/patch.js +45 -0
  27. package/dist/esm/patch.js.map +1 -0
  28. package/dist/esm/pluck.js +13 -22
  29. package/dist/esm/pluck.js.map +1 -1
  30. package/dist/esm/plugin.js +4 -1
  31. package/dist/esm/plugin.js.map +1 -1
  32. package/dist/esm/preset.js +18 -9
  33. package/dist/esm/preset.js.map +1 -1
  34. package/dist/esm/schema.js +11 -8
  35. package/dist/esm/schema.js.map +1 -1
  36. package/package.json +19 -11
  37. package/vendor/graphql-tag-pluck/visitor.cjs +1 -1
  38. package/vendor/graphql-tag-pluck/visitor.mjs +3 -3
  39. package/dist/esm/pluck.d.ts +0 -23
  40. package/dist/esm/plugin.d.ts +0 -20
  41. package/dist/esm/preset.d.ts +0 -35
  42. package/dist/esm/schema.d.ts +0 -4
  43. package/dist/esm/sources.d.ts +0 -8
@@ -1,8 +1,142 @@
1
- export { preset } from './preset.js';
2
- export { plugin } from './plugin.js';
3
- export { getSchema, schema } from './schema.js';
4
- export { processSources } from './sources.js';
5
- export { patchGqlPluck, pluckConfig } from './pluck.js';
6
- import '@graphql-codegen/plugin-helpers';
7
- import '@graphql-tools/utils';
8
- import 'graphql';
1
+ import { Types, PluginFunction } from '@graphql-codegen/plugin-helpers';
2
+ import { Source } from '@graphql-tools/utils';
3
+ import { OperationDefinitionNode, FragmentDefinitionNode, ExecutionArgs } from 'graphql';
4
+ import { IsNever, SetOptional } from 'type-fest';
5
+
6
+ type HydrogenPresetConfig = {
7
+ /**
8
+ * Name for the variable that contains the imported types.
9
+ * @default 'StorefrontAPI'
10
+ */
11
+ namespacedImportName?: string;
12
+ /**
13
+ * Module to import the types from.
14
+ * @default '@shopify/hydrogen/storefront-api-types'
15
+ */
16
+ importTypesFrom?: string;
17
+ /**
18
+ * Whether types should be imported from the `importTypesFrom` module, or generated inline.
19
+ * @default true
20
+ */
21
+ importTypes?: boolean;
22
+ /**
23
+ * Whether to skip adding `__typename` to generated operation types.
24
+ * @default true
25
+ */
26
+ skipTypenameInOperations?: boolean;
27
+ /**
28
+ * Override the default interface extension.
29
+ */
30
+ interfaceExtension?: (options: {
31
+ queryType: string;
32
+ mutationType: string;
33
+ }) => string;
34
+ };
35
+ declare const preset: Types.OutputPreset<HydrogenPresetConfig>;
36
+
37
+ type OperationOrFragment = {
38
+ initialName: string;
39
+ definition: OperationDefinitionNode | FragmentDefinitionNode;
40
+ };
41
+ type SourceWithOperations = {
42
+ source: Source;
43
+ operations: Array<OperationOrFragment>;
44
+ };
45
+ declare const plugin: PluginFunction<{
46
+ sourcesWithOperations: Array<SourceWithOperations>;
47
+ interfaceExtensionCode: string;
48
+ }>;
49
+
50
+ /**
51
+ * Resolves a schema path for the provided API type. Only the API types currently
52
+ * bundled in Hydrogen are allowed: "storefront" and "customer".
53
+ * @param api
54
+ * @returns
55
+ */
56
+ declare const getSchema: (api?: "storefront" | "customer-account") => string;
57
+ /**
58
+ * The resolved schema path for the Storefront API.
59
+ */
60
+ declare const schema: string;
61
+
62
+ declare function processSources(sources: Array<Source>, buildName?: (node: OperationDefinitionNode | FragmentDefinitionNode) => string): SourceWithOperations[];
63
+
64
+ /**
65
+ * This is a modified version of graphql-tag-pluck's default config.
66
+ * https://github.com/ardatan/graphql-tools/issues/5127
67
+ */
68
+ declare const pluckConfig: {
69
+ /**
70
+ * Hook to determine if a node is a gql template literal.
71
+ * By default, graphql-tag-pluck only looks for leading comments or `gql` tag.
72
+ */
73
+ isGqlTemplateLiteral: (node: any, options: any) => boolean;
74
+ /**
75
+ * Instruct how to extract the gql template literal from the code.
76
+ * By default, embedded expressions in template literals (e.g. ${foo})
77
+ * are removed from the template string. This hook allows us to annotate
78
+ * the template string with the required embedded expressions instead of
79
+ * removing them. Later, we can use this information to reconstruct the
80
+ * embedded expressions.
81
+ */
82
+ pluckStringFromFile: (code: string, { start, end, leadingComments }: any) => string;
83
+ };
84
+
85
+ /**
86
+ * This file has utilities to create GraphQL clients
87
+ * that consume the types generated by the Hydrogen preset.
88
+ */
89
+
90
+ /**
91
+ * A generic type for `variables` in GraphQL clients
92
+ */
93
+ type GenericVariables = ExecutionArgs['variableValues'];
94
+ /**
95
+ * Use this type to make parameters optional in GraphQL clients
96
+ * when no variables need to be passed.
97
+ */
98
+ type EmptyVariables = {
99
+ [key: string]: never;
100
+ };
101
+ /**
102
+ * GraphQL client's generic operation interface.
103
+ */
104
+ interface CodegenOperations {
105
+ [key: string]: any;
106
+ }
107
+ /**
108
+ * Used as the return type for GraphQL clients. It picks
109
+ * the return type from the generated operation types.
110
+ * @example
111
+ * graphqlQuery: (...) => Promise<ClientReturn<...>>
112
+ * graphqlQuery: (...) => Promise<{data: ClientReturn<...>}>
113
+ */
114
+ type ClientReturn<GeneratedOperations extends CodegenOperations, RawGqlString extends string, OverrideReturnType extends any = never> = IsNever<OverrideReturnType> extends true ? RawGqlString extends keyof GeneratedOperations ? GeneratedOperations[RawGqlString]['return'] : any : OverrideReturnType;
115
+ /**
116
+ * Checks if the generated variables for an operation
117
+ * are optional or required.
118
+ */
119
+ type IsOptionalVariables<VariablesParam, OptionalVariableNames extends string = never, VariablesWithoutOptionals = Omit<VariablesParam, OptionalVariableNames>> = VariablesWithoutOptionals extends EmptyVariables ? true : GenericVariables extends VariablesParam ? true : Partial<VariablesWithoutOptionals> extends VariablesWithoutOptionals ? true : false;
120
+ /**
121
+ * Used as the type for the GraphQL client's variables. It checks
122
+ * the generated operation types to see if variables are optional.
123
+ * @example
124
+ * graphqlQuery: (query: string, param: ClientVariables<...>) => Promise<...>
125
+ * Where `param` is required.
126
+ */
127
+ type ClientVariables<GeneratedOperations extends CodegenOperations, RawGqlString extends string, OptionalVariableNames extends string = never, VariablesKey extends string = 'variables', GeneratedVariables = RawGqlString extends keyof GeneratedOperations ? SetOptional<GeneratedOperations[RawGqlString]['variables'], Extract<keyof GeneratedOperations[RawGqlString]['variables'], OptionalVariableNames>> : GenericVariables, VariablesWrapper = Record<VariablesKey, GeneratedVariables>> = IsOptionalVariables<GeneratedVariables, OptionalVariableNames> extends true ? Partial<VariablesWrapper> : VariablesWrapper;
128
+ /**
129
+ * Similar to ClientVariables, but makes the whole wrapper optional:
130
+ * @example
131
+ * graphqlQuery: (query: string, ...params: ClientVariablesInRestParams<...>) => Promise<...>
132
+ * Where the first item in `params` might be optional depending on the query.
133
+ */
134
+ type ClientVariablesInRestParams<GeneratedOperations extends CodegenOperations, RawGqlString extends string, OtherParams extends Record<string, any> = {}, OptionalVariableNames extends string = never, ProcessedVariables = OtherParams & ClientVariables<GeneratedOperations, RawGqlString, OptionalVariableNames>> = Partial<OtherParams> extends OtherParams ? IsOptionalVariables<GeneratedOperations[RawGqlString]['variables'], OptionalVariableNames> extends true ? [
135
+ ProcessedVariables?
136
+ ] : [
137
+ ProcessedVariables
138
+ ] : [
139
+ ProcessedVariables
140
+ ];
141
+
142
+ export { ClientReturn, ClientVariables, ClientVariablesInRestParams, EmptyVariables, GenericVariables, IsOptionalVariables, getSchema, pluckConfig, plugin, preset, processSources, schema };
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';\nexport type * from './client.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"]}
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;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"]}
@@ -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;AAAA,EACF;AAEA,SAAO;AACT;AAEA,MAAM,iBAAiB,CAAC,MAAc,eAAsC;AAC1E,QAAM,QAAQ,CAAC,aAAa;AAAA,CAAU;AAEtC,aAAW,CAAC,gBAAgB,SAAS,KAAK,YAAY;AACpD,UAAM;AAAA,MACJ,KAAK,KAAK,UAAU,cAAc,eAIhC,UAAU,WAAW,IAAI,UAAU,KAAK,uBAC1B,UAAU,IAAI,CAAC,MAAM,IAAI,WAAW,EAAE,KAAK,KAAK;AAAA;AAAA,IAClE;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;AAC/D,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
+ {"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"]}
@@ -2,14 +2,11 @@ import * as addPlugin from '@graphql-codegen/add';
2
2
  import * as typescriptPlugin from '@graphql-codegen/typescript';
3
3
  import * as typescriptOperationPlugin from '@graphql-codegen/typescript-operations';
4
4
  import { processSources } from './sources.js';
5
+ import { getDefaultOptions } from './defaults.js';
5
6
  import { GENERATED_QUERY_INTERFACE_NAME, GENERATED_MUTATION_INTERFACE_NAME, plugin } from './plugin.js';
6
7
 
7
- const defaultInterfaceExtensionCode = `
8
- declare module '@shopify/hydrogen' {
9
- interface StorefrontQueries extends ${GENERATED_QUERY_INTERFACE_NAME} {}
10
- interface StorefrontMutations extends ${GENERATED_MUTATION_INTERFACE_NAME} {}
11
- }`;
12
8
  const preset = {
9
+ [Symbol.for("name")]: "hydrogen",
13
10
  buildGeneratesSection: (options) => {
14
11
  if (!options.baseOutputDir.endsWith(".d.ts")) {
15
12
  throw new Error("[hydrogen-preset] target output should be a .d.ts file");
@@ -21,13 +18,14 @@ const preset = {
21
18
  }
22
19
  const sourcesWithOperations = processSources(options.documents);
23
20
  const sources = sourcesWithOperations.map(({ source }) => source);
21
+ const defaultOptions = getDefaultOptions(options.baseOutputDir);
24
22
  const importTypes = options.presetConfig.importTypes ?? true;
25
- const namespacedImportName = options.presetConfig.namespacedImportName ?? "StorefrontAPI";
26
- const importTypesFrom = options.presetConfig.importTypesFrom ?? "@shopify/hydrogen/storefront-api-types";
23
+ const namespacedImportName = options.presetConfig.namespacedImportName ?? defaultOptions.namespacedImportName;
24
+ const importTypesFrom = options.presetConfig.importTypesFrom ?? defaultOptions.importTypesFrom;
27
25
  const interfaceExtensionCode = options.presetConfig.interfaceExtension?.({
28
26
  queryType: GENERATED_QUERY_INTERFACE_NAME,
29
27
  mutationType: GENERATED_MUTATION_INTERFACE_NAME
30
- }) ?? defaultInterfaceExtensionCode;
28
+ }) ?? defaultOptions.interfaceExtensionCode;
31
29
  const pluginMap = {
32
30
  ...options.pluginMap,
33
31
  [`add`]: addPlugin,
@@ -36,6 +34,7 @@ const preset = {
36
34
  [`gen-dts`]: { plugin: plugin }
37
35
  };
38
36
  const plugins = [
37
+ // 1. Disable eslint for the generated file
39
38
  {
40
39
  [`add`]: {
41
40
  content: `/* eslint-disable eslint-comments/disable-enable-pair */
@@ -43,6 +42,7 @@ const preset = {
43
42
  /* eslint-disable */`
44
43
  }
45
44
  },
45
+ // 2. Import all the generated API types from Hydrogen or generate all the types from the schema.
46
46
  importTypes ? {
47
47
  [`add`]: {
48
48
  content: `import * as ${namespacedImportName} from '${importTypesFrom}';
@@ -55,16 +55,23 @@ const preset = {
55
55
  enumsAsTypes: true
56
56
  }
57
57
  },
58
+ // 3. Generate the operations (i.e. queries, mutations, and fragments types)
58
59
  {
59
60
  [`typescript-operations`]: {
60
61
  useTypeImports: true,
62
+ // Use `import type` instead of `import`
61
63
  preResolveTypes: false,
64
+ // Use Pick<...> instead of primitives
62
65
  mergeFragmentTypes: true,
66
+ // Merge equal fragment interfaces. Avoids adding `| {}` to Metaobject
63
67
  skipTypename: options.presetConfig.skipTypenameInOperations ?? true,
68
+ // Skip __typename fields
64
69
  namespacedImportName: importTypes ? namespacedImportName : void 0
65
70
  }
66
71
  },
72
+ // 4. Augment Hydrogen query/mutation interfaces with the generated operations
67
73
  { [`gen-dts`]: { sourcesWithOperations, interfaceExtensionCode } },
74
+ // 5. Custom plugins from the user
68
75
  ...options.plugins
69
76
  ];
70
77
  return [
@@ -74,7 +81,9 @@ const preset = {
74
81
  pluginMap,
75
82
  schema: options.schema,
76
83
  config: {
84
+ // For the TS plugin:
77
85
  defaultScalarType: "unknown",
86
+ // Allow overwriting defaults:
78
87
  ...options.config
79
88
  },
80
89
  documents: sources,
@@ -84,6 +93,6 @@ const preset = {
84
93
  }
85
94
  };
86
95
 
87
- export { defaultInterfaceExtensionCode, preset };
96
+ export { preset };
88
97
  //# sourceMappingURL=out.js.map
89
98
  //# sourceMappingURL=preset.js.map
@@ -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,SAAQ,yBAAwB;AAChC;AAAA,EACE,UAAU;AAAA,EACV;AAAA,EACA;AAAA,OACK;AAgCA,MAAM,SAAmD;AAAA,EAC9D,CAAC,OAAO,IAAI,MAAM,CAAC,GAAG;AAAA,EACtB,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,iBAAiB,kBAAkB,QAAQ,aAAa;AAE9D,UAAM,cAAc,QAAQ,aAAa,eAAe;AACxD,UAAM,uBACJ,QAAQ,aAAa,wBACrB,eAAe;AACjB,UAAM,kBACJ,QAAQ,aAAa,mBAAmB,eAAe;AAEzD,UAAM,yBACJ,QAAQ,aAAa,qBAAqB;AAAA,MACxC,WAAW;AAAA,MACX,cAAc;AAAA,IAChB,CAAC,KAAK,eAAe;AAEvB,UAAM,YAAY;AAAA,MAChB,GAAG,QAAQ;AAAA,MACX,CAAC,KAAK,GAAG;AAAA,MACT,CAAC,YAAY,GAAG;AAAA,MAChB,CAAC,uBAAuB,GAAG;AAAA,MAC3B,CAAC,SAAS,GAAG,EAAC,QAAQ,UAAS;AAAA,IACjC;AAEA,UAAM,UAAyC;AAAA;AAAA,MAE7C;AAAA,QACE,CAAC,KAAK,GAAG;AAAA,UACP,SAAS;AAAA;AAAA;AAAA,QACX;AAAA,MACF;AAAA;AAAA,MAEA,cACI;AAAA,QACE,CAAC,KAAK,GAAG;AAAA,UACP,SAAS,eAAe,oBAAoB,UAAU,eAAe;AAAA;AAAA,QACvE;AAAA,MACF,IACA;AAAA,QACE,CAAC,YAAY,GAAG;AAAA,UACd,gBAAgB;AAAA,UAChB,sBAAsB;AAAA,UACtB,cAAc;AAAA,QAChB;AAAA,MACF;AAAA;AAAA,MAEJ;AAAA,QACE,CAAC,uBAAuB,GAAG;AAAA,UACzB,gBAAgB;AAAA;AAAA,UAChB,iBAAiB;AAAA;AAAA,UACjB,oBAAoB;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 {getDefaultOptions} from './defaults.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 preset: Types.OutputPreset<HydrogenPresetConfig> = {\n [Symbol.for('name')]: 'hydrogen',\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 defaultOptions = getDefaultOptions(options.baseOutputDir);\n\n const importTypes = options.presetConfig.importTypes ?? true;\n const namespacedImportName =\n options.presetConfig.namespacedImportName ??\n defaultOptions.namespacedImportName;\n const importTypesFrom =\n options.presetConfig.importTypesFrom ?? defaultOptions.importTypesFrom;\n\n const interfaceExtensionCode =\n options.presetConfig.interfaceExtension?.({\n queryType: GENERATED_QUERY_INTERFACE_NAME,\n mutationType: GENERATED_MUTATION_INTERFACE_NAME,\n }) ?? defaultOptions.interfaceExtensionCode;\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,15 +1,18 @@
1
1
  import {createRequire} from 'module'; const require = createRequire(import.meta.url);
2
- const getSchema = () => require.resolve("@shopify/hydrogen-react/storefront.schema.json");
3
- let staticSchema = "";
2
+ const getSchema = (api = "storefront") => {
3
+ if (api !== "storefront" && api !== "customer-account") {
4
+ throw new Error(
5
+ `The provided API type "${api}" is unknown. Please use "storefront" or "customer-account".`
6
+ );
7
+ }
8
+ return require.resolve(`@shopify/hydrogen-react/${api}.schema.json`);
9
+ };
10
+ let staticSFAPISchema = "";
4
11
  try {
5
- staticSchema = getSchema();
12
+ staticSFAPISchema = getSchema("storefront");
6
13
  } catch (error) {
7
- console.warn(
8
- "[hydrogen-codegen] storefront.schema.json not found. Is `@shopify/hydrogen` installed?\n",
9
- error.message
10
- );
11
14
  }
12
- const schema = staticSchema;
15
+ const schema = staticSFAPISchema;
13
16
 
14
17
  export { getSchema, schema };
15
18
  //# sourceMappingURL=out.js.map
@@ -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;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"]}
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.2.0",
8
8
  "license": "MIT",
9
9
  "type": "module",
10
10
  "main": "dist/cjs/index.cjs",
@@ -12,11 +12,11 @@
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
- "test": "cross-env SHOPIFY_UNIT_TEST=1 vitest run",
19
- "test:watch": "cross-env SHOPIFY_UNIT_TEST=1 vitest"
18
+ "test": "cross-env SHOPIFY_UNIT_TEST=1 vitest run --typecheck",
19
+ "test:watch": "cross-env SHOPIFY_UNIT_TEST=1 vitest --typecheck"
20
20
  },
21
21
  "exports": {
22
22
  ".": {
@@ -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,16 @@
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": "^1.0.4"
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",
55
+ "type-fest": "^4.5.0"
48
56
  },
49
57
  "peerDependencies": {
50
58
  "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
  {
@@ -1,23 +0,0 @@
1
- declare function patchGqlPluck(): Promise<void>;
2
- /**
3
- * This is a modified version of graphql-tag-pluck's default config.
4
- * https://github.com/ardatan/graphql-tools/issues/5127
5
- */
6
- declare const pluckConfig: {
7
- /**
8
- * Hook to determine if a node is a gql template literal.
9
- * By default, graphql-tag-pluck only looks for leading comments or `gql` tag.
10
- */
11
- isGqlTemplateLiteral: (node: any, options: any) => boolean;
12
- /**
13
- * Instruct how to extract the gql template literal from the code.
14
- * By default, embedded expressions in template literals (e.g. ${foo})
15
- * are removed from the template string. This hook allows us to annotate
16
- * the template string with the required embedded expressions instead of
17
- * removing them. Later, we can use this information to reconstruct the
18
- * embedded expressions.
19
- */
20
- pluckStringFromFile: (code: string, { start, end, leadingComments }: any) => string;
21
- };
22
-
23
- export { patchGqlPluck, pluckConfig };