babel-plugin-import-graphql
Version:
Babel plugin to make .gql/.graphql files importable
189 lines (147 loc) • 6.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.requireGql = exports.defaultResolve = void 0;
var _fs = require("fs");
var _path = _interopRequireWildcard(require("path"));
var _graphqlTag = _interopRequireDefault(require("graphql-tag"));
var _multiOp = require("./multiOp");
var _constants = require("./constants");
var customImport = _interopRequireWildcard(require("./customImport"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
var defaultResolve = function defaultResolve(src, file) {
return _path.default.resolve((0, _path.dirname)(file), src);
};
exports.defaultResolve = defaultResolve;
var requireGql = function requireGql(filepath) {
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref$resolve = _ref.resolve,
resolve = _ref$resolve === void 0 ? defaultResolve : _ref$resolve,
_ref$nowrap = _ref.nowrap,
nowrap = _ref$nowrap === void 0 ? true : _ref$nowrap,
_ref$emitDeclarations = _ref.emitDeclarations,
emitDeclarations = _ref$emitDeclarations === void 0 ? false : _ref$emitDeclarations;
filepath = (0, _path.isAbsolute)(filepath) ? filepath : (0, _path.join)(callerDirname(), filepath);
var source = (0, _fs.readFileSync)(filepath).toString(); // If the file doesn't contain ops return raw text, else parse and return docsMap object.
if (isSchemaLike(source)) {
var imports = customImport.getFilepaths(source, filepath, resolve);
if (imports.length === 0) return source; // Resolve all #import statements (types, etc) recursively and concat them to the main source.
return imports.reduce(function (acc, fp) {
return _toConsumableArray(acc).concat(_toConsumableArray(customImport.getSources(fp, resolve, [])));
}, []).map(stripImportStatements).join('') + stripImportStatements(source);
}
var doc = processDoc(createDoc(source, filepath, resolve));
var docsMap = (0, _multiOp.createDocPerOp)(doc);
if (emitDeclarations) {
writeDTs(filepath, docsMap);
}
return nowrap && !doc.isMultiOp ? docsMap.default : docsMap;
};
exports.requireGql = requireGql;
function writeDTs(filepath, docsMap) {
var defLines = Object.keys(docsMap).map(function (key) {
var commentBody = docsMap[key].loc.source.body.trim().split('\n').map(function (line) {
return ` * ${line}`;
}).join('\n');
var docComment = `/**\n * \`\`\`gql\n${commentBody}\n * \`\`\`\n */\n`;
if (key === 'default') {
return `${docComment}declare const _ = ${JSON.stringify(docsMap[key]
/* null, 2 */
)} as const;\nexport default _;\n`;
}
return `${docComment}export const ${key} = ${JSON.stringify(docsMap[key]
/* null, 2 */
)} as const;\n`;
});
defLines.unshift(`/**\n * Generated at ${new Date().toISOString()}\n */\n`);
defLines.push('');
(0, _fs.writeFileSync)(filepath + '.d.ts', defLines.join('\n'));
}
function callerDirname() {
// To avoid dependencies, I borrowed this from gh (sindresorhus/callsites/blob/master/index.js)
var _ = Error.prepareStackTrace;
Error.prepareStackTrace = function (_, stack) {
return stack;
};
var stack = new Error().stack.slice(1);
Error.prepareStackTrace = _; // End borrowed code
var caller = stack.find(function (c) {
return c.getTypeName() !== null;
});
return (0, _path.dirname)(caller.getFileName());
}
function isSchemaLike(source) {
var content = source.split(_constants.newlinePattern).filter(function (line) {
return !_constants.newlinePattern.test(line);
}).filter(function (line) {
return !line.startsWith('#');
}).filter(function (line) {
return line.length > 0;
}).map(function (line) {
return line.trimLeft();
});
var operationsPattern = /^(fragment|query|mutation|subscription)/;
return !operationsPattern.test(content[0]);
}
function stripImportStatements(src) {
return src.replace(_constants.importPattern, '');
}
function createDoc(source, filepath, resolve) {
var ast = null;
var fragmentDefs = [];
return {
processFragments() {
// Resolve all #import statements (fragments) recursively and add them to the definitions
customImport.getFilepaths(source, filepath, resolve).forEach(function (fp) {
fragmentDefs = customImport.getSources(fp, resolve).reduce(function (acc, src) {
return _toConsumableArray(acc).concat(_toConsumableArray((0, _graphqlTag.default)(src).definitions));
}, fragmentDefs);
});
},
parse() {
var parsedAST = (0, _graphqlTag.default)(source);
parsedAST.definitions = _toConsumableArray(parsedAST.definitions).concat(_toConsumableArray(fragmentDefs));
ast = parsedAST;
},
dedupeFragments() {
var seenNames = {};
ast.definitions = ast.definitions.filter(function (def) {
if (def.kind !== 'FragmentDefinition') return true;
return seenNames[def.name.value] ? false : seenNames[def.name.value] = true;
});
},
makeSourceEnumerable() {
var newAST = JSON.parse(JSON.stringify(ast));
newAST.loc.source = ast.loc.source;
ast = newAST;
},
get ast() {
return ast;
},
get isMultiOp() {
var countReducer = function countReducer(acc, def) {
return def.kind === 'OperationDefinition' ? acc += 1 : acc;
};
var opCount = ast.definitions.reduce(countReducer, 0);
return opCount > 1;
},
get isOnlyFrags() {
return ast.definitions.every(function (d) {
return d.kind === 'FragmentDefinition';
});
}
};
}
function processDoc(doc) {
doc.processFragments();
doc.parse();
doc.dedupeFragments();
doc.makeSourceEnumerable();
return doc;
}