UNPKG

2.44 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.getDocumentTransformByName = exports.getDocumentTransform = void 0;
4const path_1 = require("path");
5async function getDocumentTransform(documentTransform, loader, defaultName) {
6 if (typeof documentTransform === 'string') {
7 const transformObject = await getDocumentTransformByName(documentTransform, loader);
8 return { name: documentTransform, transformObject };
9 }
10 if (isTransformObject(documentTransform)) {
11 return { name: defaultName, transformObject: documentTransform };
12 }
13 if (isTransformFileConfig(documentTransform)) {
14 const name = Object.keys(documentTransform)[0];
15 const transformObject = await getDocumentTransformByName(name, loader);
16 return { name, transformObject, config: Object.values(documentTransform)[0] };
17 }
18 throw new Error(`
19 An unknown format document transform: '${defaultName}'.
20 `);
21}
22exports.getDocumentTransform = getDocumentTransform;
23function isTransformObject(config) {
24 return typeof config === 'object' && config.transform && typeof config.transform === 'function';
25}
26function isTransformFileConfig(config) {
27 const keys = Object.keys(config);
28 return keys.length === 1 && typeof keys[0] === 'string';
29}
30async function getDocumentTransformByName(name, loader) {
31 const possibleNames = [
32 `@graphql-codegen/${name}`,
33 `@graphql-codegen/${name}-document-transform`,
34 name,
35 (0, path_1.resolve)(process.cwd(), name),
36 ];
37 const possibleModules = possibleNames.concat((0, path_1.resolve)(process.cwd(), name));
38 for (const moduleName of possibleModules) {
39 try {
40 return await loader(moduleName);
41 }
42 catch (err) {
43 if (err.code !== 'MODULE_NOT_FOUND' && err.code !== 'ERR_MODULE_NOT_FOUND') {
44 throw new Error(`
45 Unable to load document transform matching '${name}'.
46 Reason:
47 ${err.message}
48 `);
49 }
50 }
51 }
52 const possibleNamesMsg = possibleNames
53 .map(name => `
54 - ${name}
55 `.trimEnd())
56 .join('');
57 throw new Error(`
58 Unable to find document transform matching '${name}'
59 Install one of the following packages:
60
61 ${possibleNamesMsg}
62 `);
63}
64exports.getDocumentTransformByName = getDocumentTransformByName;