@graphql-tools/code-file-loader 7.2.19 → 7.3.0-alpha-6c480b2d.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.
package/cjs/exports.js ADDED
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.pickExportFromModuleSync = exports.pickExportFromModule = void 0;
4
+ const graphql_1 = require("graphql");
5
+ const helpers_js_1 = require("./helpers.js");
6
+ const identifiersToLookFor = ['default', 'schema', 'typeDefs', 'data'];
7
+ // Pick exports
8
+ /**
9
+ * @internal
10
+ */
11
+ function pickExportFromModule({ module, filepath }) {
12
+ ensureModule({ module, filepath });
13
+ return resolveModule(ensureExports({ module, filepath }));
14
+ }
15
+ exports.pickExportFromModule = pickExportFromModule;
16
+ /**
17
+ * @internal
18
+ */
19
+ function pickExportFromModuleSync({ module, filepath }) {
20
+ ensureModule({ module, filepath });
21
+ return resolveModuleSync(ensureExports({ module, filepath }));
22
+ }
23
+ exports.pickExportFromModuleSync = pickExportFromModuleSync;
24
+ // module
25
+ async function resolveModule(identifiers) {
26
+ const exportValue = await (0, helpers_js_1.pick)(await identifiers, identifiersToLookFor);
27
+ return resolveExport(exportValue);
28
+ }
29
+ function resolveModuleSync(identifiers) {
30
+ const exportValue = (0, helpers_js_1.pick)(identifiers, identifiersToLookFor);
31
+ return resolveExport(exportValue);
32
+ }
33
+ // validate
34
+ function ensureModule({ module, filepath }) {
35
+ if (!module) {
36
+ throw new Error(`Invalid export from export file ${filepath}: empty export!`);
37
+ }
38
+ }
39
+ function ensureExports({ module, filepath }) {
40
+ const identifiers = (0, helpers_js_1.pick)(module, identifiersToLookFor);
41
+ if (!identifiers) {
42
+ throw new Error(`Invalid export from export file ${filepath}: missing default export or 'schema' export!`);
43
+ }
44
+ return identifiers;
45
+ }
46
+ // Decide what to do with an exported value
47
+ function resolveExport(fileExport) {
48
+ try {
49
+ if ((0, graphql_1.isSchema)(fileExport)) {
50
+ return fileExport;
51
+ }
52
+ if ((0, helpers_js_1.isSchemaText)(fileExport)) {
53
+ return (0, graphql_1.parse)(fileExport);
54
+ }
55
+ if ((0, helpers_js_1.isWrappedSchemaJson)(fileExport)) {
56
+ return (0, graphql_1.buildClientSchema)(fileExport.data);
57
+ }
58
+ if ((0, helpers_js_1.isSchemaJson)(fileExport)) {
59
+ return (0, graphql_1.buildClientSchema)(fileExport);
60
+ }
61
+ if ((0, helpers_js_1.isSchemaAst)(fileExport)) {
62
+ return fileExport;
63
+ }
64
+ return null;
65
+ }
66
+ catch (e) {
67
+ throw new Error('Exported schema must be of type GraphQLSchema, text, AST, or introspection JSON.');
68
+ }
69
+ }
package/cjs/helpers.js ADDED
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isSchemaAst = exports.isSchemaJson = exports.isWrappedSchemaJson = exports.isSchemaText = exports.pick = void 0;
4
+ /**
5
+ * @internal
6
+ */
7
+ function pick(obj, keys) {
8
+ for (const key of keys) {
9
+ if (obj[key]) {
10
+ return obj[key];
11
+ }
12
+ }
13
+ return obj;
14
+ }
15
+ exports.pick = pick;
16
+ // checkers
17
+ /**
18
+ * @internal
19
+ */
20
+ function isSchemaText(obj) {
21
+ return typeof obj === 'string';
22
+ }
23
+ exports.isSchemaText = isSchemaText;
24
+ /**
25
+ * @internal
26
+ */
27
+ function isWrappedSchemaJson(obj) {
28
+ const json = obj;
29
+ return json.data !== undefined && json.data.__schema !== undefined;
30
+ }
31
+ exports.isWrappedSchemaJson = isWrappedSchemaJson;
32
+ /**
33
+ * @internal
34
+ */
35
+ function isSchemaJson(obj) {
36
+ const json = obj;
37
+ return json !== undefined && json.__schema !== undefined;
38
+ }
39
+ exports.isSchemaJson = isSchemaJson;
40
+ /**
41
+ * @internal
42
+ */
43
+ function isSchemaAst(obj) {
44
+ return obj.kind !== undefined;
45
+ }
46
+ exports.isSchemaAst = isSchemaAst;
package/cjs/index.js ADDED
@@ -0,0 +1,256 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CodeFileLoader = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const graphql_1 = require("graphql");
6
+ const utils_1 = require("@graphql-tools/utils");
7
+ const graphql_tag_pluck_1 = require("@graphql-tools/graphql-tag-pluck");
8
+ const globby_1 = tslib_1.__importDefault(require("globby"));
9
+ const unixify_1 = tslib_1.__importDefault(require("unixify"));
10
+ const load_from_module_js_1 = require("./load-from-module.js");
11
+ const path_1 = require("path");
12
+ const process_1 = require("process");
13
+ const fs_1 = require("fs");
14
+ const module_1 = require("module");
15
+ const { readFile, access } = fs_1.promises;
16
+ const FILE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.vue', '.svelte'];
17
+ function createGlobbyOptions(options) {
18
+ return { absolute: true, ...options, ignore: [] };
19
+ }
20
+ const buildIgnoreGlob = (path) => `!${path}`;
21
+ /**
22
+ * This loader loads GraphQL documents and type definitions from code files
23
+ * using `graphql-tag-pluck`.
24
+ *
25
+ * ```js
26
+ * const documents = await loadDocuments('queries/*.js', {
27
+ * loaders: [
28
+ * new CodeFileLoader()
29
+ * ]
30
+ * });
31
+ * ```
32
+ *
33
+ * Supported extensions include: `.ts`, `.tsx`, `.js`, `.jsx`, `.vue`, `.svelte`
34
+ */
35
+ class CodeFileLoader {
36
+ constructor(config) {
37
+ this.config = config !== null && config !== void 0 ? config : {};
38
+ }
39
+ getMergedOptions(options) {
40
+ return { ...this.config, ...options };
41
+ }
42
+ async canLoad(pointer, options) {
43
+ options = this.getMergedOptions(options);
44
+ if ((0, utils_1.isValidPath)(pointer)) {
45
+ if (FILE_EXTENSIONS.find(extension => pointer.endsWith(extension))) {
46
+ const normalizedFilePath = (0, path_1.isAbsolute)(pointer) ? pointer : (0, path_1.resolve)(options.cwd || (0, process_1.cwd)(), pointer);
47
+ try {
48
+ await access(normalizedFilePath);
49
+ return true;
50
+ }
51
+ catch (_a) {
52
+ return false;
53
+ }
54
+ }
55
+ }
56
+ return false;
57
+ }
58
+ canLoadSync(pointer, options) {
59
+ options = this.getMergedOptions(options);
60
+ if ((0, utils_1.isValidPath)(pointer)) {
61
+ if (FILE_EXTENSIONS.find(extension => pointer.endsWith(extension))) {
62
+ const normalizedFilePath = (0, path_1.isAbsolute)(pointer) ? pointer : (0, path_1.resolve)(options.cwd || (0, process_1.cwd)(), pointer);
63
+ return (0, fs_1.existsSync)(normalizedFilePath);
64
+ }
65
+ }
66
+ return false;
67
+ }
68
+ _buildGlobs(glob, options) {
69
+ const ignores = (0, utils_1.asArray)(options.ignore || []);
70
+ const globs = [(0, unixify_1.default)(glob), ...ignores.map(v => buildIgnoreGlob((0, unixify_1.default)(v)))];
71
+ return globs;
72
+ }
73
+ async resolveGlobs(glob, options) {
74
+ options = this.getMergedOptions(options);
75
+ const globs = this._buildGlobs(glob, options);
76
+ return (0, globby_1.default)(globs, createGlobbyOptions(options));
77
+ }
78
+ resolveGlobsSync(glob, options) {
79
+ options = this.getMergedOptions(options);
80
+ const globs = this._buildGlobs(glob, options);
81
+ return globby_1.default.sync(globs, createGlobbyOptions(options));
82
+ }
83
+ async load(pointer, options) {
84
+ options = this.getMergedOptions(options);
85
+ const resolvedPaths = await this.resolveGlobs(pointer, options);
86
+ const finalResult = [];
87
+ const errors = [];
88
+ await Promise.all(resolvedPaths.map(async (path) => {
89
+ try {
90
+ const result = await this.handleSinglePath(path, options);
91
+ result === null || result === void 0 ? void 0 : result.forEach(result => finalResult.push(result));
92
+ }
93
+ catch (e) {
94
+ if (process_1.env['DEBUG']) {
95
+ console.error(e);
96
+ }
97
+ errors.push(e);
98
+ }
99
+ }));
100
+ if (errors.length > 0 && (options.noSilentErrors || finalResult.length === 0)) {
101
+ if (errors.length === 1) {
102
+ throw errors[0];
103
+ }
104
+ throw new utils_1.AggregateError(errors, `Reading from ${pointer} failed ; \n ` + errors.map((e) => e.message).join('\n'));
105
+ }
106
+ return finalResult;
107
+ }
108
+ loadSync(pointer, options) {
109
+ options = this.getMergedOptions(options);
110
+ const resolvedPaths = this.resolveGlobsSync(pointer, options);
111
+ const finalResult = [];
112
+ const errors = [];
113
+ for (const path of resolvedPaths) {
114
+ if (this.canLoadSync(path, options)) {
115
+ try {
116
+ const result = this.handleSinglePathSync(path, options);
117
+ result === null || result === void 0 ? void 0 : result.forEach(result => finalResult.push(result));
118
+ }
119
+ catch (e) {
120
+ if (process_1.env['DEBUG']) {
121
+ console.error(e);
122
+ }
123
+ errors.push(e);
124
+ }
125
+ }
126
+ }
127
+ if (errors.length > 0 && (options.noSilentErrors || finalResult.length === 0)) {
128
+ if (errors.length === 1) {
129
+ throw errors[0];
130
+ }
131
+ throw new utils_1.AggregateError(errors, `Reading from ${pointer} failed ; \n ` + errors.map((e) => e.message).join('\n'));
132
+ }
133
+ return finalResult;
134
+ }
135
+ async handleSinglePath(location, options) {
136
+ if (!(await this.canLoad(location, options))) {
137
+ return [];
138
+ }
139
+ options = this.getMergedOptions(options);
140
+ const normalizedFilePath = ensureAbsolutePath(location, options);
141
+ const errors = [];
142
+ if (!options.noPluck) {
143
+ try {
144
+ const content = await readFile(normalizedFilePath, { encoding: 'utf-8' });
145
+ const sources = await (0, graphql_tag_pluck_1.gqlPluckFromCodeString)(normalizedFilePath, content, options.pluckConfig);
146
+ if (sources.length) {
147
+ return sources.map(source => ({
148
+ rawSDL: source.body,
149
+ document: (0, graphql_1.parse)(source),
150
+ location,
151
+ }));
152
+ }
153
+ }
154
+ catch (e) {
155
+ if (process_1.env['DEBUG']) {
156
+ console.error(`Failed to load schema from code file "${normalizedFilePath}": ${e.message}`);
157
+ }
158
+ errors.push(e);
159
+ }
160
+ }
161
+ if (!options.noRequire) {
162
+ try {
163
+ if (options && options.require) {
164
+ await Promise.all((0, utils_1.asArray)(options.require).map(m => Promise.resolve().then(() => tslib_1.__importStar(require(m)))));
165
+ }
166
+ const loaded = await (0, load_from_module_js_1.tryToLoadFromExport)(normalizedFilePath);
167
+ const sources = (0, utils_1.asArray)(loaded)
168
+ .map(value => resolveSource(location, value, options))
169
+ .filter(Boolean);
170
+ if (sources.length) {
171
+ return sources;
172
+ }
173
+ }
174
+ catch (e) {
175
+ errors.push(e);
176
+ }
177
+ }
178
+ if (errors.length > 0) {
179
+ throw errors[0];
180
+ }
181
+ return [];
182
+ }
183
+ handleSinglePathSync(location, options) {
184
+ if (!this.canLoadSync(location, options)) {
185
+ return [];
186
+ }
187
+ options = this.getMergedOptions(options);
188
+ const normalizedFilePath = ensureAbsolutePath(location, options);
189
+ const errors = [];
190
+ if (!options.noPluck) {
191
+ try {
192
+ const content = (0, fs_1.readFileSync)(normalizedFilePath, { encoding: 'utf-8' });
193
+ const sources = (0, graphql_tag_pluck_1.gqlPluckFromCodeStringSync)(normalizedFilePath, content, options.pluckConfig);
194
+ if (sources.length) {
195
+ return sources.map(source => ({
196
+ rawSDL: source.body,
197
+ document: (0, graphql_1.parse)(source),
198
+ location,
199
+ }));
200
+ }
201
+ }
202
+ catch (e) {
203
+ if (process_1.env['DEBUG']) {
204
+ console.error(`Failed to load schema from code file "${normalizedFilePath}": ${e.message}`);
205
+ }
206
+ errors.push(e);
207
+ }
208
+ }
209
+ if (!options.noRequire) {
210
+ try {
211
+ if (options && options.require) {
212
+ const cwdRequire = (0, module_1.createRequire)(options.cwd || (0, process_1.cwd)());
213
+ for (const m of (0, utils_1.asArray)(options.require)) {
214
+ cwdRequire(m);
215
+ }
216
+ }
217
+ const loaded = (0, load_from_module_js_1.tryToLoadFromExportSync)(normalizedFilePath);
218
+ const sources = (0, utils_1.asArray)(loaded)
219
+ .map(value => resolveSource(location, value, options))
220
+ .filter(Boolean);
221
+ if (sources.length) {
222
+ return sources;
223
+ }
224
+ }
225
+ catch (e) {
226
+ errors.push(e);
227
+ }
228
+ }
229
+ if (errors.length > 0) {
230
+ throw errors[0];
231
+ }
232
+ return null;
233
+ }
234
+ }
235
+ exports.CodeFileLoader = CodeFileLoader;
236
+ function resolveSource(pointer, value, options) {
237
+ if (typeof value === 'string') {
238
+ return (0, utils_1.parseGraphQLSDL)(pointer, value, options);
239
+ }
240
+ else if ((0, graphql_1.isSchema)(value)) {
241
+ return {
242
+ location: pointer,
243
+ schema: value,
244
+ };
245
+ }
246
+ else if ((0, utils_1.isDocumentNode)(value)) {
247
+ return {
248
+ location: pointer,
249
+ document: value,
250
+ };
251
+ }
252
+ return null;
253
+ }
254
+ function ensureAbsolutePath(pointer, options) {
255
+ return (0, path_1.isAbsolute)(pointer) ? pointer : (0, path_1.resolve)(options.cwd || (0, process_1.cwd)(), pointer);
256
+ }
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.tryToLoadFromExportSync = exports.tryToLoadFromExport = void 0;
27
+ const exports_js_1 = require("./exports.js");
28
+ /**
29
+ * @internal
30
+ */
31
+ async function tryToLoadFromExport(rawFilePath) {
32
+ try {
33
+ const filepath = ensureFilepath(rawFilePath);
34
+ const mod = await Promise.resolve().then(() => __importStar(require(filepath)));
35
+ return await (0, exports_js_1.pickExportFromModule)({ module: mod, filepath });
36
+ }
37
+ catch (e) {
38
+ throw new Error(`Unable to load from file "${rawFilePath}": ${e.stack || e.message}`);
39
+ }
40
+ }
41
+ exports.tryToLoadFromExport = tryToLoadFromExport;
42
+ /**
43
+ * @internal
44
+ */
45
+ function tryToLoadFromExportSync(rawFilePath) {
46
+ try {
47
+ const filepath = ensureFilepath(rawFilePath);
48
+ const mod = require(filepath);
49
+ return (0, exports_js_1.pickExportFromModuleSync)({ module: mod, filepath });
50
+ }
51
+ catch (e) {
52
+ throw new Error(`Unable to load from file "${rawFilePath}": ${e.stack || e.message}`);
53
+ }
54
+ }
55
+ exports.tryToLoadFromExportSync = tryToLoadFromExportSync;
56
+ /**
57
+ * @internal
58
+ */
59
+ function ensureFilepath(filepath) {
60
+ if (typeof require !== 'undefined' && require.cache) {
61
+ filepath = require.resolve(filepath);
62
+ if (require.cache[filepath]) {
63
+ delete require.cache[filepath];
64
+ }
65
+ }
66
+ return filepath;
67
+ }
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
package/esm/exports.js ADDED
@@ -0,0 +1,64 @@
1
+ import { parse, buildClientSchema, isSchema } from 'graphql';
2
+ import { isSchemaAst, isSchemaJson, isSchemaText, isWrappedSchemaJson, pick } from './helpers.js';
3
+ const identifiersToLookFor = ['default', 'schema', 'typeDefs', 'data'];
4
+ // Pick exports
5
+ /**
6
+ * @internal
7
+ */
8
+ export function pickExportFromModule({ module, filepath }) {
9
+ ensureModule({ module, filepath });
10
+ return resolveModule(ensureExports({ module, filepath }));
11
+ }
12
+ /**
13
+ * @internal
14
+ */
15
+ export function pickExportFromModuleSync({ module, filepath }) {
16
+ ensureModule({ module, filepath });
17
+ return resolveModuleSync(ensureExports({ module, filepath }));
18
+ }
19
+ // module
20
+ async function resolveModule(identifiers) {
21
+ const exportValue = await pick(await identifiers, identifiersToLookFor);
22
+ return resolveExport(exportValue);
23
+ }
24
+ function resolveModuleSync(identifiers) {
25
+ const exportValue = pick(identifiers, identifiersToLookFor);
26
+ return resolveExport(exportValue);
27
+ }
28
+ // validate
29
+ function ensureModule({ module, filepath }) {
30
+ if (!module) {
31
+ throw new Error(`Invalid export from export file ${filepath}: empty export!`);
32
+ }
33
+ }
34
+ function ensureExports({ module, filepath }) {
35
+ const identifiers = pick(module, identifiersToLookFor);
36
+ if (!identifiers) {
37
+ throw new Error(`Invalid export from export file ${filepath}: missing default export or 'schema' export!`);
38
+ }
39
+ return identifiers;
40
+ }
41
+ // Decide what to do with an exported value
42
+ function resolveExport(fileExport) {
43
+ try {
44
+ if (isSchema(fileExport)) {
45
+ return fileExport;
46
+ }
47
+ if (isSchemaText(fileExport)) {
48
+ return parse(fileExport);
49
+ }
50
+ if (isWrappedSchemaJson(fileExport)) {
51
+ return buildClientSchema(fileExport.data);
52
+ }
53
+ if (isSchemaJson(fileExport)) {
54
+ return buildClientSchema(fileExport);
55
+ }
56
+ if (isSchemaAst(fileExport)) {
57
+ return fileExport;
58
+ }
59
+ return null;
60
+ }
61
+ catch (e) {
62
+ throw new Error('Exported schema must be of type GraphQLSchema, text, AST, or introspection JSON.');
63
+ }
64
+ }
package/esm/helpers.js ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * @internal
3
+ */
4
+ export function pick(obj, keys) {
5
+ for (const key of keys) {
6
+ if (obj[key]) {
7
+ return obj[key];
8
+ }
9
+ }
10
+ return obj;
11
+ }
12
+ // checkers
13
+ /**
14
+ * @internal
15
+ */
16
+ export function isSchemaText(obj) {
17
+ return typeof obj === 'string';
18
+ }
19
+ /**
20
+ * @internal
21
+ */
22
+ export function isWrappedSchemaJson(obj) {
23
+ const json = obj;
24
+ return json.data !== undefined && json.data.__schema !== undefined;
25
+ }
26
+ /**
27
+ * @internal
28
+ */
29
+ export function isSchemaJson(obj) {
30
+ const json = obj;
31
+ return json !== undefined && json.__schema !== undefined;
32
+ }
33
+ /**
34
+ * @internal
35
+ */
36
+ export function isSchemaAst(obj) {
37
+ return obj.kind !== undefined;
38
+ }
@@ -1,155 +1,14 @@
1
- import { isSchema, parse, buildClientSchema } from 'graphql';
2
- import { isValidPath, asArray, AggregateError, parseGraphQLSDL, isDocumentNode } from '@graphql-tools/utils';
3
- import { gqlPluckFromCodeString, gqlPluckFromCodeStringSync } from '@graphql-tools/graphql-tag-pluck';
1
+ import { isSchema, parse } from 'graphql';
2
+ import { asArray, isValidPath, parseGraphQLSDL, isDocumentNode, AggregateError, } from '@graphql-tools/utils';
3
+ import { gqlPluckFromCodeString, gqlPluckFromCodeStringSync, } from '@graphql-tools/graphql-tag-pluck';
4
4
  import globby from 'globby';
5
5
  import unixify from 'unixify';
6
+ import { tryToLoadFromExport, tryToLoadFromExportSync } from './load-from-module.js';
6
7
  import { isAbsolute, resolve } from 'path';
7
8
  import { cwd, env } from 'process';
8
- import { existsSync, readFileSync, promises } from 'fs';
9
+ import { readFileSync, promises as fsPromises, existsSync } from 'fs';
9
10
  import { createRequire } from 'module';
10
-
11
- /**
12
- * @internal
13
- */
14
- function pick(obj, keys) {
15
- for (const key of keys) {
16
- if (obj[key]) {
17
- return obj[key];
18
- }
19
- }
20
- return obj;
21
- }
22
- // checkers
23
- /**
24
- * @internal
25
- */
26
- function isSchemaText(obj) {
27
- return typeof obj === 'string';
28
- }
29
- /**
30
- * @internal
31
- */
32
- function isWrappedSchemaJson(obj) {
33
- const json = obj;
34
- return json.data !== undefined && json.data.__schema !== undefined;
35
- }
36
- /**
37
- * @internal
38
- */
39
- function isSchemaJson(obj) {
40
- const json = obj;
41
- return json !== undefined && json.__schema !== undefined;
42
- }
43
- /**
44
- * @internal
45
- */
46
- function isSchemaAst(obj) {
47
- return obj.kind !== undefined;
48
- }
49
-
50
- const identifiersToLookFor = ['default', 'schema', 'typeDefs', 'data'];
51
- // Pick exports
52
- /**
53
- * @internal
54
- */
55
- function pickExportFromModule({ module, filepath }) {
56
- ensureModule({ module, filepath });
57
- return resolveModule(ensureExports({ module, filepath }));
58
- }
59
- /**
60
- * @internal
61
- */
62
- function pickExportFromModuleSync({ module, filepath }) {
63
- ensureModule({ module, filepath });
64
- return resolveModuleSync(ensureExports({ module, filepath }));
65
- }
66
- // module
67
- async function resolveModule(identifiers) {
68
- const exportValue = await pick(await identifiers, identifiersToLookFor);
69
- return resolveExport(exportValue);
70
- }
71
- function resolveModuleSync(identifiers) {
72
- const exportValue = pick(identifiers, identifiersToLookFor);
73
- return resolveExport(exportValue);
74
- }
75
- // validate
76
- function ensureModule({ module, filepath }) {
77
- if (!module) {
78
- throw new Error(`Invalid export from export file ${filepath}: empty export!`);
79
- }
80
- }
81
- function ensureExports({ module, filepath }) {
82
- const identifiers = pick(module, identifiersToLookFor);
83
- if (!identifiers) {
84
- throw new Error(`Invalid export from export file ${filepath}: missing default export or 'schema' export!`);
85
- }
86
- return identifiers;
87
- }
88
- // Decide what to do with an exported value
89
- function resolveExport(fileExport) {
90
- try {
91
- if (isSchema(fileExport)) {
92
- return fileExport;
93
- }
94
- if (isSchemaText(fileExport)) {
95
- return parse(fileExport);
96
- }
97
- if (isWrappedSchemaJson(fileExport)) {
98
- return buildClientSchema(fileExport.data);
99
- }
100
- if (isSchemaJson(fileExport)) {
101
- return buildClientSchema(fileExport);
102
- }
103
- if (isSchemaAst(fileExport)) {
104
- return fileExport;
105
- }
106
- return null;
107
- }
108
- catch (e) {
109
- throw new Error('Exported schema must be of type GraphQLSchema, text, AST, or introspection JSON.');
110
- }
111
- }
112
-
113
- /**
114
- * @internal
115
- */
116
- async function tryToLoadFromExport(rawFilePath) {
117
- try {
118
- const filepath = ensureFilepath(rawFilePath);
119
- const mod = await import(filepath);
120
- return await pickExportFromModule({ module: mod, filepath });
121
- }
122
- catch (e) {
123
- throw new Error(`Unable to load from file "${rawFilePath}": ${e.stack || e.message}`);
124
- }
125
- }
126
- /**
127
- * @internal
128
- */
129
- function tryToLoadFromExportSync(rawFilePath) {
130
- try {
131
- const filepath = ensureFilepath(rawFilePath);
132
- const mod = require(filepath);
133
- return pickExportFromModuleSync({ module: mod, filepath });
134
- }
135
- catch (e) {
136
- throw new Error(`Unable to load from file "${rawFilePath}": ${e.stack || e.message}`);
137
- }
138
- }
139
- /**
140
- * @internal
141
- */
142
- function ensureFilepath(filepath) {
143
- if (typeof require !== 'undefined' && require.cache) {
144
- filepath = require.resolve(filepath);
145
- if (require.cache[filepath]) {
146
- delete require.cache[filepath];
147
- }
148
- }
149
- return filepath;
150
- }
151
-
152
- const { readFile, access } = promises;
11
+ const { readFile, access } = fsPromises;
153
12
  const FILE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.vue', '.svelte'];
154
13
  function createGlobbyOptions(options) {
155
14
  return { absolute: true, ...options, ignore: [] };
@@ -169,7 +28,7 @@ const buildIgnoreGlob = (path) => `!${path}`;
169
28
  *
170
29
  * Supported extensions include: `.ts`, `.tsx`, `.js`, `.jsx`, `.vue`, `.svelte`
171
30
  */
172
- class CodeFileLoader {
31
+ export class CodeFileLoader {
173
32
  constructor(config) {
174
33
  this.config = config !== null && config !== void 0 ? config : {};
175
34
  }
@@ -390,5 +249,3 @@ function resolveSource(pointer, value, options) {
390
249
  function ensureAbsolutePath(pointer, options) {
391
250
  return isAbsolute(pointer) ? pointer : resolve(options.cwd || cwd(), pointer);
392
251
  }
393
-
394
- export { CodeFileLoader };
@@ -0,0 +1,39 @@
1
+ import { pickExportFromModule, pickExportFromModuleSync } from './exports.js';
2
+ /**
3
+ * @internal
4
+ */
5
+ export async function tryToLoadFromExport(rawFilePath) {
6
+ try {
7
+ const filepath = ensureFilepath(rawFilePath);
8
+ const mod = await import(filepath);
9
+ return await pickExportFromModule({ module: mod, filepath });
10
+ }
11
+ catch (e) {
12
+ throw new Error(`Unable to load from file "${rawFilePath}": ${e.stack || e.message}`);
13
+ }
14
+ }
15
+ /**
16
+ * @internal
17
+ */
18
+ export function tryToLoadFromExportSync(rawFilePath) {
19
+ try {
20
+ const filepath = ensureFilepath(rawFilePath);
21
+ const mod = require(filepath);
22
+ return pickExportFromModuleSync({ module: mod, filepath });
23
+ }
24
+ catch (e) {
25
+ throw new Error(`Unable to load from file "${rawFilePath}": ${e.stack || e.message}`);
26
+ }
27
+ }
28
+ /**
29
+ * @internal
30
+ */
31
+ function ensureFilepath(filepath) {
32
+ if (typeof require !== 'undefined' && require.cache) {
33
+ filepath = require.resolve(filepath);
34
+ if (require.cache[filepath]) {
35
+ delete require.cache[filepath];
36
+ }
37
+ }
38
+ return filepath;
39
+ }
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@graphql-tools/code-file-loader",
3
- "version": "7.2.19",
3
+ "version": "7.3.0-alpha-6c480b2d.0",
4
4
  "description": "A set of utils for faster development of GraphQL tools",
5
5
  "sideEffects": false,
6
6
  "peerDependencies": {
7
7
  "graphql": "^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0"
8
8
  },
9
9
  "dependencies": {
10
- "@graphql-tools/graphql-tag-pluck": "7.2.11",
11
- "@graphql-tools/utils": "8.7.0",
10
+ "@graphql-tools/utils": "8.8.0-alpha-6c480b2d.0",
11
+ "@graphql-tools/graphql-tag-pluck": "7.3.0-alpha-6c480b2d.0",
12
12
  "globby": "^11.0.3",
13
13
  "tslib": "^2.4.0",
14
14
  "unixify": "^1.0.0"
@@ -20,21 +20,42 @@
20
20
  },
21
21
  "author": "Dotan Simha <dotansimha@gmail.com>",
22
22
  "license": "MIT",
23
- "main": "index.js",
24
- "module": "index.mjs",
25
- "typings": "index.d.ts",
23
+ "main": "cjs/index.js",
24
+ "module": "esm/index.js",
25
+ "typings": "typings/index.d.ts",
26
26
  "typescript": {
27
- "definition": "index.d.ts"
27
+ "definition": "typings/index.d.ts"
28
28
  },
29
+ "type": "module",
29
30
  "exports": {
30
31
  ".": {
31
- "require": "./index.js",
32
- "import": "./index.mjs"
32
+ "require": {
33
+ "types": "./typings/index.d.ts",
34
+ "default": "./cjs/index.js"
35
+ },
36
+ "import": {
37
+ "types": "./typings/index.d.ts",
38
+ "default": "./esm/index.js"
39
+ },
40
+ "default": {
41
+ "types": "./typings/index.d.ts",
42
+ "default": "./esm/index.js"
43
+ }
33
44
  },
34
45
  "./*": {
35
- "require": "./*.js",
36
- "import": "./*.mjs"
46
+ "require": {
47
+ "types": "./typings/*.d.ts",
48
+ "default": "./cjs/*.js"
49
+ },
50
+ "import": {
51
+ "types": "./typings/*.d.ts",
52
+ "default": "./esm/*.js"
53
+ },
54
+ "default": {
55
+ "types": "./typings/*.d.ts",
56
+ "default": "./esm/*.js"
57
+ }
37
58
  },
38
59
  "./package.json": "./package.json"
39
60
  }
40
- }
61
+ }
File without changes
File without changes
File without changes
package/index.js DELETED
@@ -1,419 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
-
7
- function _interopNamespace(e) {
8
- if (e && e.__esModule) { return e; } else {
9
- var n = {};
10
- if (e) {
11
- Object.keys(e).forEach(function (k) {
12
- var d = Object.getOwnPropertyDescriptor(e, k);
13
- Object.defineProperty(n, k, d.get ? d : {
14
- enumerable: true,
15
- get: function () {
16
- return e[k];
17
- }
18
- });
19
- });
20
- }
21
- n['default'] = e;
22
- return n;
23
- }
24
- }
25
-
26
- const graphql = require('graphql');
27
- const utils = require('@graphql-tools/utils');
28
- const graphqlTagPluck = require('@graphql-tools/graphql-tag-pluck');
29
- const globby = _interopDefault(require('globby'));
30
- const unixify = _interopDefault(require('unixify'));
31
- const path = require('path');
32
- const process = require('process');
33
- const fs = require('fs');
34
- const module$1 = require('module');
35
-
36
- /**
37
- * @internal
38
- */
39
- function pick(obj, keys) {
40
- for (const key of keys) {
41
- if (obj[key]) {
42
- return obj[key];
43
- }
44
- }
45
- return obj;
46
- }
47
- // checkers
48
- /**
49
- * @internal
50
- */
51
- function isSchemaText(obj) {
52
- return typeof obj === 'string';
53
- }
54
- /**
55
- * @internal
56
- */
57
- function isWrappedSchemaJson(obj) {
58
- const json = obj;
59
- return json.data !== undefined && json.data.__schema !== undefined;
60
- }
61
- /**
62
- * @internal
63
- */
64
- function isSchemaJson(obj) {
65
- const json = obj;
66
- return json !== undefined && json.__schema !== undefined;
67
- }
68
- /**
69
- * @internal
70
- */
71
- function isSchemaAst(obj) {
72
- return obj.kind !== undefined;
73
- }
74
-
75
- const identifiersToLookFor = ['default', 'schema', 'typeDefs', 'data'];
76
- // Pick exports
77
- /**
78
- * @internal
79
- */
80
- function pickExportFromModule({ module, filepath }) {
81
- ensureModule({ module, filepath });
82
- return resolveModule(ensureExports({ module, filepath }));
83
- }
84
- /**
85
- * @internal
86
- */
87
- function pickExportFromModuleSync({ module, filepath }) {
88
- ensureModule({ module, filepath });
89
- return resolveModuleSync(ensureExports({ module, filepath }));
90
- }
91
- // module
92
- async function resolveModule(identifiers) {
93
- const exportValue = await pick(await identifiers, identifiersToLookFor);
94
- return resolveExport(exportValue);
95
- }
96
- function resolveModuleSync(identifiers) {
97
- const exportValue = pick(identifiers, identifiersToLookFor);
98
- return resolveExport(exportValue);
99
- }
100
- // validate
101
- function ensureModule({ module, filepath }) {
102
- if (!module) {
103
- throw new Error(`Invalid export from export file ${filepath}: empty export!`);
104
- }
105
- }
106
- function ensureExports({ module, filepath }) {
107
- const identifiers = pick(module, identifiersToLookFor);
108
- if (!identifiers) {
109
- throw new Error(`Invalid export from export file ${filepath}: missing default export or 'schema' export!`);
110
- }
111
- return identifiers;
112
- }
113
- // Decide what to do with an exported value
114
- function resolveExport(fileExport) {
115
- try {
116
- if (graphql.isSchema(fileExport)) {
117
- return fileExport;
118
- }
119
- if (isSchemaText(fileExport)) {
120
- return graphql.parse(fileExport);
121
- }
122
- if (isWrappedSchemaJson(fileExport)) {
123
- return graphql.buildClientSchema(fileExport.data);
124
- }
125
- if (isSchemaJson(fileExport)) {
126
- return graphql.buildClientSchema(fileExport);
127
- }
128
- if (isSchemaAst(fileExport)) {
129
- return fileExport;
130
- }
131
- return null;
132
- }
133
- catch (e) {
134
- throw new Error('Exported schema must be of type GraphQLSchema, text, AST, or introspection JSON.');
135
- }
136
- }
137
-
138
- /**
139
- * @internal
140
- */
141
- async function tryToLoadFromExport(rawFilePath) {
142
- try {
143
- const filepath = ensureFilepath(rawFilePath);
144
- const mod = await new Promise(function (resolve) { resolve(_interopNamespace(require(filepath))); });
145
- return await pickExportFromModule({ module: mod, filepath });
146
- }
147
- catch (e) {
148
- throw new Error(`Unable to load from file "${rawFilePath}": ${e.stack || e.message}`);
149
- }
150
- }
151
- /**
152
- * @internal
153
- */
154
- function tryToLoadFromExportSync(rawFilePath) {
155
- try {
156
- const filepath = ensureFilepath(rawFilePath);
157
- const mod = require(filepath);
158
- return pickExportFromModuleSync({ module: mod, filepath });
159
- }
160
- catch (e) {
161
- throw new Error(`Unable to load from file "${rawFilePath}": ${e.stack || e.message}`);
162
- }
163
- }
164
- /**
165
- * @internal
166
- */
167
- function ensureFilepath(filepath) {
168
- if (typeof require !== 'undefined' && require.cache) {
169
- filepath = require.resolve(filepath);
170
- if (require.cache[filepath]) {
171
- delete require.cache[filepath];
172
- }
173
- }
174
- return filepath;
175
- }
176
-
177
- const { readFile, access } = fs.promises;
178
- const FILE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.vue', '.svelte'];
179
- function createGlobbyOptions(options) {
180
- return { absolute: true, ...options, ignore: [] };
181
- }
182
- const buildIgnoreGlob = (path) => `!${path}`;
183
- /**
184
- * This loader loads GraphQL documents and type definitions from code files
185
- * using `graphql-tag-pluck`.
186
- *
187
- * ```js
188
- * const documents = await loadDocuments('queries/*.js', {
189
- * loaders: [
190
- * new CodeFileLoader()
191
- * ]
192
- * });
193
- * ```
194
- *
195
- * Supported extensions include: `.ts`, `.tsx`, `.js`, `.jsx`, `.vue`, `.svelte`
196
- */
197
- class CodeFileLoader {
198
- constructor(config) {
199
- this.config = config !== null && config !== void 0 ? config : {};
200
- }
201
- getMergedOptions(options) {
202
- return { ...this.config, ...options };
203
- }
204
- async canLoad(pointer, options) {
205
- options = this.getMergedOptions(options);
206
- if (utils.isValidPath(pointer)) {
207
- if (FILE_EXTENSIONS.find(extension => pointer.endsWith(extension))) {
208
- const normalizedFilePath = path.isAbsolute(pointer) ? pointer : path.resolve(options.cwd || process.cwd(), pointer);
209
- try {
210
- await access(normalizedFilePath);
211
- return true;
212
- }
213
- catch (_a) {
214
- return false;
215
- }
216
- }
217
- }
218
- return false;
219
- }
220
- canLoadSync(pointer, options) {
221
- options = this.getMergedOptions(options);
222
- if (utils.isValidPath(pointer)) {
223
- if (FILE_EXTENSIONS.find(extension => pointer.endsWith(extension))) {
224
- const normalizedFilePath = path.isAbsolute(pointer) ? pointer : path.resolve(options.cwd || process.cwd(), pointer);
225
- return fs.existsSync(normalizedFilePath);
226
- }
227
- }
228
- return false;
229
- }
230
- _buildGlobs(glob, options) {
231
- const ignores = utils.asArray(options.ignore || []);
232
- const globs = [unixify(glob), ...ignores.map(v => buildIgnoreGlob(unixify(v)))];
233
- return globs;
234
- }
235
- async resolveGlobs(glob, options) {
236
- options = this.getMergedOptions(options);
237
- const globs = this._buildGlobs(glob, options);
238
- return globby(globs, createGlobbyOptions(options));
239
- }
240
- resolveGlobsSync(glob, options) {
241
- options = this.getMergedOptions(options);
242
- const globs = this._buildGlobs(glob, options);
243
- return globby.sync(globs, createGlobbyOptions(options));
244
- }
245
- async load(pointer, options) {
246
- options = this.getMergedOptions(options);
247
- const resolvedPaths = await this.resolveGlobs(pointer, options);
248
- const finalResult = [];
249
- const errors = [];
250
- await Promise.all(resolvedPaths.map(async (path) => {
251
- try {
252
- const result = await this.handleSinglePath(path, options);
253
- result === null || result === void 0 ? void 0 : result.forEach(result => finalResult.push(result));
254
- }
255
- catch (e) {
256
- if (process.env['DEBUG']) {
257
- console.error(e);
258
- }
259
- errors.push(e);
260
- }
261
- }));
262
- if (errors.length > 0 && (options.noSilentErrors || finalResult.length === 0)) {
263
- if (errors.length === 1) {
264
- throw errors[0];
265
- }
266
- throw new utils.AggregateError(errors, `Reading from ${pointer} failed ; \n ` + errors.map((e) => e.message).join('\n'));
267
- }
268
- return finalResult;
269
- }
270
- loadSync(pointer, options) {
271
- options = this.getMergedOptions(options);
272
- const resolvedPaths = this.resolveGlobsSync(pointer, options);
273
- const finalResult = [];
274
- const errors = [];
275
- for (const path of resolvedPaths) {
276
- if (this.canLoadSync(path, options)) {
277
- try {
278
- const result = this.handleSinglePathSync(path, options);
279
- result === null || result === void 0 ? void 0 : result.forEach(result => finalResult.push(result));
280
- }
281
- catch (e) {
282
- if (process.env['DEBUG']) {
283
- console.error(e);
284
- }
285
- errors.push(e);
286
- }
287
- }
288
- }
289
- if (errors.length > 0 && (options.noSilentErrors || finalResult.length === 0)) {
290
- if (errors.length === 1) {
291
- throw errors[0];
292
- }
293
- throw new utils.AggregateError(errors, `Reading from ${pointer} failed ; \n ` + errors.map((e) => e.message).join('\n'));
294
- }
295
- return finalResult;
296
- }
297
- async handleSinglePath(location, options) {
298
- if (!(await this.canLoad(location, options))) {
299
- return [];
300
- }
301
- options = this.getMergedOptions(options);
302
- const normalizedFilePath = ensureAbsolutePath(location, options);
303
- const errors = [];
304
- if (!options.noPluck) {
305
- try {
306
- const content = await readFile(normalizedFilePath, { encoding: 'utf-8' });
307
- const sources = await graphqlTagPluck.gqlPluckFromCodeString(normalizedFilePath, content, options.pluckConfig);
308
- if (sources.length) {
309
- return sources.map(source => ({
310
- rawSDL: source.body,
311
- document: graphql.parse(source),
312
- location,
313
- }));
314
- }
315
- }
316
- catch (e) {
317
- if (process.env['DEBUG']) {
318
- console.error(`Failed to load schema from code file "${normalizedFilePath}": ${e.message}`);
319
- }
320
- errors.push(e);
321
- }
322
- }
323
- if (!options.noRequire) {
324
- try {
325
- if (options && options.require) {
326
- await Promise.all(utils.asArray(options.require).map(m => new Promise(function (resolve) { resolve(_interopNamespace(require(m))); })));
327
- }
328
- const loaded = await tryToLoadFromExport(normalizedFilePath);
329
- const sources = utils.asArray(loaded)
330
- .map(value => resolveSource(location, value, options))
331
- .filter(Boolean);
332
- if (sources.length) {
333
- return sources;
334
- }
335
- }
336
- catch (e) {
337
- errors.push(e);
338
- }
339
- }
340
- if (errors.length > 0) {
341
- throw errors[0];
342
- }
343
- return [];
344
- }
345
- handleSinglePathSync(location, options) {
346
- if (!this.canLoadSync(location, options)) {
347
- return [];
348
- }
349
- options = this.getMergedOptions(options);
350
- const normalizedFilePath = ensureAbsolutePath(location, options);
351
- const errors = [];
352
- if (!options.noPluck) {
353
- try {
354
- const content = fs.readFileSync(normalizedFilePath, { encoding: 'utf-8' });
355
- const sources = graphqlTagPluck.gqlPluckFromCodeStringSync(normalizedFilePath, content, options.pluckConfig);
356
- if (sources.length) {
357
- return sources.map(source => ({
358
- rawSDL: source.body,
359
- document: graphql.parse(source),
360
- location,
361
- }));
362
- }
363
- }
364
- catch (e) {
365
- if (process.env['DEBUG']) {
366
- console.error(`Failed to load schema from code file "${normalizedFilePath}": ${e.message}`);
367
- }
368
- errors.push(e);
369
- }
370
- }
371
- if (!options.noRequire) {
372
- try {
373
- if (options && options.require) {
374
- const cwdRequire = module$1.createRequire(options.cwd || process.cwd());
375
- for (const m of utils.asArray(options.require)) {
376
- cwdRequire(m);
377
- }
378
- }
379
- const loaded = tryToLoadFromExportSync(normalizedFilePath);
380
- const sources = utils.asArray(loaded)
381
- .map(value => resolveSource(location, value, options))
382
- .filter(Boolean);
383
- if (sources.length) {
384
- return sources;
385
- }
386
- }
387
- catch (e) {
388
- errors.push(e);
389
- }
390
- }
391
- if (errors.length > 0) {
392
- throw errors[0];
393
- }
394
- return null;
395
- }
396
- }
397
- function resolveSource(pointer, value, options) {
398
- if (typeof value === 'string') {
399
- return utils.parseGraphQLSDL(pointer, value, options);
400
- }
401
- else if (graphql.isSchema(value)) {
402
- return {
403
- location: pointer,
404
- schema: value,
405
- };
406
- }
407
- else if (utils.isDocumentNode(value)) {
408
- return {
409
- location: pointer,
410
- document: value,
411
- };
412
- }
413
- return null;
414
- }
415
- function ensureAbsolutePath(pointer, options) {
416
- return path.isAbsolute(pointer) ? pointer : path.resolve(options.cwd || process.cwd(), pointer);
417
- }
418
-
419
- exports.CodeFileLoader = CodeFileLoader;