@shopify/hydrogen-codegen 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +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
14
  }
8
- const schema = staticSchema;
15
+ const schema = staticSFAPISchema;
9
16
 
10
17
  export { getSchema, schema };
11
18
  //# sourceMappingURL=out.js.map
@@ -1 +1 @@
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"]}
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.1.0",
7
+ "version": "0.2.1",
8
8
  "license": "MIT",
9
9
  "type": "module",
10
10
  "main": "dist/cjs/index.cjs",
@@ -15,8 +15,8 @@
15
15
  "build": "tsup --clean",
16
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
  ".": {
@@ -39,19 +39,19 @@
39
39
  "directory": "packages/hydrogen-codegen"
40
40
  },
41
41
  "files": [
42
- "dist",
43
- "vendor"
42
+ "dist"
44
43
  ],
45
44
  "devDependencies": {
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"
45
+ "@graphql-codegen/cli": "^5.0.1",
46
+ "@graphql-codegen/plugin-helpers": "^5.0.2",
47
+ "@graphql-tools/utils": "^10.0.13",
48
+ "vitest": "^1.0.4"
50
49
  },
51
50
  "dependencies": {
52
- "@graphql-codegen/add": "^5.0.0",
53
- "@graphql-codegen/typescript": "^4.0.1",
54
- "@graphql-codegen/typescript-operations": "^4.0.1"
51
+ "@graphql-codegen/add": "^5.0.1",
52
+ "@graphql-codegen/typescript": "^4.0.2",
53
+ "@graphql-codegen/typescript-operations": "^4.1.0",
54
+ "type-fest": "^4.5.0"
55
55
  },
56
56
  "peerDependencies": {
57
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,22 +0,0 @@
1
- /**
2
- * This is a modified version of graphql-tag-pluck's default config.
3
- * https://github.com/ardatan/graphql-tools/issues/5127
4
- */
5
- declare const pluckConfig: {
6
- /**
7
- * Hook to determine if a node is a gql template literal.
8
- * By default, graphql-tag-pluck only looks for leading comments or `gql` tag.
9
- */
10
- isGqlTemplateLiteral: (node: any, options: any) => boolean;
11
- /**
12
- * Instruct how to extract the gql template literal from the code.
13
- * By default, embedded expressions in template literals (e.g. ${foo})
14
- * are removed from the template string. This hook allows us to annotate
15
- * the template string with the required embedded expressions instead of
16
- * removing them. Later, we can use this information to reconstruct the
17
- * embedded expressions.
18
- */
19
- pluckStringFromFile: (code: string, { start, end, leadingComments }: any) => string;
20
- };
21
-
22
- export { pluckConfig };
@@ -1,20 +0,0 @@
1
- import { PluginFunction } from '@graphql-codegen/plugin-helpers';
2
- import { Source } from '@graphql-tools/utils';
3
- import { OperationDefinitionNode, FragmentDefinitionNode } from 'graphql';
4
-
5
- type OperationOrFragment = {
6
- initialName: string;
7
- definition: OperationDefinitionNode | FragmentDefinitionNode;
8
- };
9
- type SourceWithOperations = {
10
- source: Source;
11
- operations: Array<OperationOrFragment>;
12
- };
13
- declare const plugin: PluginFunction<{
14
- sourcesWithOperations: Array<SourceWithOperations>;
15
- interfaceExtensionCode: string;
16
- }>;
17
- declare const GENERATED_QUERY_INTERFACE_NAME = "GeneratedQueryTypes";
18
- declare const GENERATED_MUTATION_INTERFACE_NAME = "GeneratedMutationTypes";
19
-
20
- export { GENERATED_MUTATION_INTERFACE_NAME, GENERATED_QUERY_INTERFACE_NAME, OperationOrFragment, SourceWithOperations, plugin };
@@ -1,35 +0,0 @@
1
- import { Types } from '@graphql-codegen/plugin-helpers';
2
-
3
- type HydrogenPresetConfig = {
4
- /**
5
- * Name for the variable that contains the imported types.
6
- * @default 'StorefrontAPI'
7
- */
8
- namespacedImportName?: string;
9
- /**
10
- * Module to import the types from.
11
- * @default '@shopify/hydrogen/storefront-api-types'
12
- */
13
- importTypesFrom?: string;
14
- /**
15
- * Whether types should be imported from the `importTypesFrom` module, or generated inline.
16
- * @default true
17
- */
18
- importTypes?: boolean;
19
- /**
20
- * Whether to skip adding `__typename` to generated operation types.
21
- * @default true
22
- */
23
- skipTypenameInOperations?: boolean;
24
- /**
25
- * Override the default interface extension.
26
- */
27
- interfaceExtension?: (options: {
28
- queryType: string;
29
- mutationType: string;
30
- }) => string;
31
- };
32
- declare const defaultInterfaceExtensionCode = "\ndeclare module '@shopify/hydrogen' {\n interface StorefrontQueries extends GeneratedQueryTypes {}\n interface StorefrontMutations extends GeneratedMutationTypes {}\n}";
33
- declare const preset: Types.OutputPreset<HydrogenPresetConfig>;
34
-
35
- export { HydrogenPresetConfig, defaultInterfaceExtensionCode, preset };
@@ -1,4 +0,0 @@
1
- declare const getSchema: () => string;
2
- declare const schema: string;
3
-
4
- export { getSchema, schema };
@@ -1,8 +0,0 @@
1
- import { SourceWithOperations } from './plugin.js';
2
- import { Source } from '@graphql-tools/utils';
3
- import { OperationDefinitionNode, FragmentDefinitionNode } from 'graphql';
4
- import '@graphql-codegen/plugin-helpers';
5
-
6
- declare function processSources(sources: Array<Source>, buildName?: (node: OperationDefinitionNode | FragmentDefinitionNode) => string): SourceWithOperations[];
7
-
8
- export { processSources };
@@ -1,377 +0,0 @@
1
- 'use strict';
2
- Object.defineProperty(exports, '__esModule', {value: true});
3
- const types_1 = require('@babel/types');
4
- const utils_1 = require('@graphql-tools/utils');
5
- const utils_js_1 = require('./utils.js');
6
- const defaults = {
7
- modules: [
8
- {
9
- name: 'graphql-tag',
10
- },
11
- {
12
- name: 'graphql-tag.macro',
13
- },
14
- {
15
- name: '@apollo/client',
16
- identifier: 'gql',
17
- },
18
- {
19
- name: '@apollo/client/core',
20
- identifier: 'gql',
21
- },
22
- {
23
- name: 'apollo-angular',
24
- identifier: 'gql',
25
- },
26
- {
27
- name: 'gatsby',
28
- identifier: 'graphql',
29
- },
30
- {
31
- name: 'apollo-server-express',
32
- identifier: 'gql',
33
- },
34
- {
35
- name: 'apollo-server',
36
- identifier: 'gql',
37
- },
38
- {
39
- name: 'react-relay',
40
- identifier: 'graphql',
41
- },
42
- {
43
- name: 'react-relay/hooks',
44
- identifier: 'graphql',
45
- },
46
- {
47
- name: 'relay-runtime',
48
- identifier: 'graphql',
49
- },
50
- {
51
- name: 'babel-plugin-relay/macro',
52
- identifier: 'graphql',
53
- },
54
- {
55
- name: 'apollo-boost',
56
- identifier: 'gql',
57
- },
58
- {
59
- name: 'apollo-server-koa',
60
- identifier: 'gql',
61
- },
62
- {
63
- name: 'apollo-server-hapi',
64
- identifier: 'gql',
65
- },
66
- {
67
- name: 'apollo-server-fastify',
68
- identifier: 'gql',
69
- },
70
- {
71
- name: ' apollo-server-lambda',
72
- identifier: 'gql',
73
- },
74
- {
75
- name: 'apollo-server-micro',
76
- identifier: 'gql',
77
- },
78
- {
79
- name: 'apollo-server-azure-functions',
80
- identifier: 'gql',
81
- },
82
- {
83
- name: 'apollo-server-cloud-functions',
84
- identifier: 'gql',
85
- },
86
- {
87
- name: 'apollo-server-cloudflare',
88
- identifier: 'gql',
89
- },
90
- {
91
- name: 'graphql.macro',
92
- identifier: 'gql',
93
- },
94
- {
95
- name: '@urql/core',
96
- identifier: 'gql',
97
- },
98
- {
99
- name: 'urql',
100
- identifier: 'gql',
101
- },
102
- {
103
- name: '@urql/preact',
104
- identifier: 'gql',
105
- },
106
- {
107
- name: '@urql/svelte',
108
- identifier: 'gql',
109
- },
110
- {
111
- name: '@urql/vue',
112
- identifier: 'gql',
113
- },
114
- ],
115
- gqlMagicComment: 'graphql',
116
- globalGqlIdentifierName: ['gql', 'graphql'],
117
- };
118
- function defaultPluckStringFromFile(code, {start, end}, options = {}) {
119
- return (0, utils_js_1.freeText)(
120
- code
121
- // Slice quotes
122
- .slice(start + 1, end - 1)
123
- // Erase string interpolations as we gonna export everything as a single
124
- // string anyway
125
- .replace(/\$\{[^}]*\}/g, '')
126
- .split('\\`')
127
- .join('`'),
128
- options.skipIndent,
129
- );
130
- }
131
- function defaultIsGqlTemplateLiteral(node, options) {
132
- const leadingComments = node.leadingComments;
133
- if (!leadingComments) {
134
- return;
135
- }
136
- if (!leadingComments.length) {
137
- return;
138
- }
139
- const leadingComment = leadingComments[leadingComments.length - 1];
140
- const leadingCommentValue = leadingComment.value.trim().toLowerCase();
141
- if (leadingCommentValue === options.gqlMagicComment) {
142
- return true;
143
- }
144
- return false;
145
- }
146
- exports.default = (code, out, options = {}) => {
147
- // Apply defaults to options
148
- let {
149
- modules = [],
150
- globalGqlIdentifierName,
151
- gqlMagicComment,
152
- skipIndent,
153
- isGqlTemplateLiteral = defaultIsGqlTemplateLiteral,
154
- pluckStringFromFile = defaultPluckStringFromFile,
155
- } = {
156
- ...defaults,
157
- ...options,
158
- };
159
- // Prevent case related potential errors
160
- gqlMagicComment = gqlMagicComment.toLowerCase();
161
- // normalize `name` and `identifier` values
162
- modules = modules.map((mod) => {
163
- return {
164
- name: mod.name,
165
- identifier: mod.identifier && mod.identifier.toLowerCase(),
166
- };
167
- });
168
- globalGqlIdentifierName = (0, utils_1.asArray)(globalGqlIdentifierName).map(
169
- (s) => s.toLowerCase(),
170
- );
171
- const hooksOptions = {
172
- skipIndent,
173
- gqlMagicComment,
174
- modules,
175
- globalGqlIdentifierName,
176
- };
177
- // Keep imported identifiers
178
- // import gql from 'graphql-tag' -> gql
179
- // import { graphql } from 'gatsby' -> graphql
180
- // Will result with ['gql', 'graphql']
181
- const definedIdentifierNames = [];
182
- const alreadyProcessedOperationsCache = new Set();
183
- // Will accumulate all template literals
184
- const gqlTemplateLiterals = [];
185
- // Check if package is registered
186
- function isValidPackage(name) {
187
- return modules.some(
188
- (pkg) =>
189
- pkg.name && name && pkg.name.toLowerCase() === name.toLowerCase(),
190
- );
191
- }
192
- // Check if identifier is defined and imported from registered packages
193
- function isValidIdentifier(name) {
194
- return (
195
- definedIdentifierNames.some((id) => id === name) ||
196
- globalGqlIdentifierName.includes(name)
197
- );
198
- }
199
- const addTemplateLiteralToResult = (content) => {
200
- const cacheKey = `end/${content.end}/start/${content.start}/${content.content}`;
201
- if (alreadyProcessedOperationsCache.has(cacheKey)) {
202
- return;
203
- }
204
- alreadyProcessedOperationsCache.add(cacheKey);
205
- gqlTemplateLiterals.push(content);
206
- };
207
- // Push all template literals leaded by graphql magic comment
208
- // e.g. /* GraphQL */ `query myQuery {}` -> query myQuery {}
209
- const pluckMagicTemplateLiteral = (node, takeExpression = false) => {
210
- if (!isGqlTemplateLiteral(node, hooksOptions)) {
211
- return;
212
- }
213
- const nodeToUse = takeExpression ? node.expression : node;
214
- const gqlTemplateLiteral = pluckStringFromFile(
215
- code,
216
- nodeToUse,
217
- hooksOptions,
218
- );
219
- if (gqlTemplateLiteral) {
220
- addTemplateLiteralToResult({
221
- content: gqlTemplateLiteral,
222
- loc: node.loc,
223
- end: node.end,
224
- start: node.start,
225
- });
226
- }
227
- };
228
- const visitor = {
229
- CallExpression: {
230
- enter(path) {
231
- // Find the identifier name used from graphql-tag, commonJS
232
- // e.g. import gql from 'graphql-tag' -> gql
233
- const arg0 = path.node.arguments[0];
234
- if (
235
- 'name' in path.node.callee &&
236
- path.node.callee.name === 'require' &&
237
- 'value' in arg0 &&
238
- typeof arg0.value === 'string' &&
239
- isValidPackage(arg0.value)
240
- ) {
241
- if (!(0, types_1.isVariableDeclarator)(path.parent)) {
242
- return;
243
- }
244
- if (!(0, types_1.isIdentifier)(path.parent.id)) {
245
- return;
246
- }
247
- definedIdentifierNames.push(path.parent.id.name);
248
- return;
249
- }
250
- // Checks to see if a node represents a typescript '<expression> as const' expression
251
- function isTSAsConstExpression(node) {
252
- return (
253
- (0, types_1.isTSAsExpression)(node) &&
254
- (0, types_1.isTSTypeReference)(node.typeAnnotation) &&
255
- (0, types_1.isIdentifier)(node.typeAnnotation.typeName) &&
256
- node.typeAnnotation.typeName.name === 'const'
257
- );
258
- }
259
- // Extract template literal from as const expression if applicable
260
- // e.g. gql(`query myQuery {}` as const)
261
- const unwrappedExpression = isTSAsConstExpression(arg0)
262
- ? arg0.expression
263
- : arg0;
264
- // Push strings template literals to gql calls
265
- // e.g. gql(`query myQuery {}`) -> query myQuery {}
266
- if (
267
- (0, types_1.isIdentifier)(path.node.callee) &&
268
- isValidIdentifier(path.node.callee.name) &&
269
- (0, types_1.isTemplateLiteral)(unwrappedExpression)
270
- ) {
271
- const {start, end, loc} = unwrappedExpression;
272
- if (start != null && end != null && start != null && loc != null) {
273
- const gqlTemplateLiteral = pluckStringFromFile(
274
- code,
275
- unwrappedExpression,
276
- hooksOptions,
277
- );
278
- // If the entire template was made out of interpolations it should be an empty
279
- // string by now and thus should be ignored
280
- if (gqlTemplateLiteral) {
281
- addTemplateLiteralToResult({
282
- content: gqlTemplateLiteral,
283
- loc,
284
- end,
285
- start,
286
- });
287
- }
288
- }
289
- }
290
- },
291
- },
292
- ImportDeclaration: {
293
- enter(path) {
294
- // Find the identifier name used from graphql-tag, es6
295
- // e.g. import gql from 'graphql-tag' -> gql
296
- if (!isValidPackage(path.node.source.value)) {
297
- return;
298
- }
299
- const moduleNode = modules.find(
300
- (pkg) =>
301
- pkg.name.toLowerCase() === path.node.source.value.toLowerCase(),
302
- );
303
- if (moduleNode == null) {
304
- return;
305
- }
306
- const gqlImportSpecifier = path.node.specifiers.find(
307
- (importSpecifier) => {
308
- // When it's a default import and registered package has no named identifier
309
- if (
310
- (0, types_1.isImportDefaultSpecifier)(importSpecifier) &&
311
- !moduleNode.identifier
312
- ) {
313
- return true;
314
- }
315
- // When it's a named import that matches registered package's identifier
316
- if (
317
- (0, types_1.isImportSpecifier)(importSpecifier) &&
318
- 'name' in importSpecifier.imported &&
319
- importSpecifier.imported.name === moduleNode.identifier
320
- ) {
321
- return true;
322
- }
323
- return false;
324
- },
325
- );
326
- if (!gqlImportSpecifier) {
327
- return;
328
- }
329
- definedIdentifierNames.push(gqlImportSpecifier.local.name);
330
- },
331
- },
332
- ExpressionStatement: {
333
- exit(path) {
334
- // Push all template literals leaded by graphql magic comment
335
- // e.g. /* GraphQL */ `query myQuery {}` -> query myQuery {}
336
- if (!(0, types_1.isTemplateLiteral)(path.node.expression)) {
337
- return;
338
- }
339
- pluckMagicTemplateLiteral(path.node, true);
340
- },
341
- },
342
- TemplateLiteral: {
343
- exit(path) {
344
- pluckMagicTemplateLiteral(path.node);
345
- },
346
- },
347
- TaggedTemplateExpression: {
348
- exit(path) {
349
- // Push all template literals provided to the found identifier name
350
- // e.g. gql `query myQuery {}` -> query myQuery {}
351
- if (
352
- !(0, types_1.isIdentifier)(path.node.tag) ||
353
- !isValidIdentifier(path.node.tag.name)
354
- ) {
355
- return;
356
- }
357
- const gqlTemplateLiteral = pluckStringFromFile(
358
- code,
359
- path.node.quasi,
360
- hooksOptions,
361
- );
362
- if (gqlTemplateLiteral) {
363
- addTemplateLiteralToResult({
364
- content: gqlTemplateLiteral,
365
- end: path.node.quasi.end,
366
- start: path.node.quasi.start,
367
- loc: path.node.quasi.loc,
368
- });
369
- }
370
- },
371
- },
372
- exit() {
373
- out.returnValue = gqlTemplateLiterals;
374
- },
375
- };
376
- return visitor;
377
- };