New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@anders-nom/babel-plugin-import-graphql-string

Package Overview
Dependencies
Maintainers
1
Versions
13
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@anders-nom/babel-plugin-import-graphql-string - npm Package Compare versions

Comparing version 2.8.1-11 to 2.8.1-12

16

build/customImport.js

@@ -7,3 +7,3 @@ "use strict";

exports.getFilepaths = getFilepaths;
exports.getSources = getSources;
exports.getImportSources = getImportSources;

@@ -45,3 +45,3 @@ var _fs = require("fs");

function _getSources(filepath, resolve, acc) {
function getSources(filepath, resolve, acc) {
var path = filepath.replace(/'/g, '');

@@ -55,3 +55,3 @@ var importSrc = (0, _fs.readFileSync)(path).toString();

var srcs = nestedPaths.length > 0 ? _toConsumableArray(nestedPaths.reduce(function (srcArr, fp) {
return _toConsumableArray(srcArr).concat(_toConsumableArray(_getSources(fp, resolve, [])));
return _toConsumableArray(srcArr).concat(_toConsumableArray(getSources(fp, resolve, [])));
}, [])).concat([srcAndPath]) : [srcAndPath];

@@ -61,5 +61,8 @@ return _toConsumableArray(srcs).concat(_toConsumableArray(acc));

function getSources(filepath, resolve) {
var acc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
return _getSources(filepath, resolve, acc).filter(function (srcAndPath, index, array) {
function getImportSources(rootSource, filepath, resolve) {
var imports = getFilepaths(rootSource, filepath, resolve);
var sources = imports.reduce(function (acc, fp) {
return _toConsumableArray(acc).concat(_toConsumableArray(getSources(fp, resolve, [])));
}, []);
var finalSources = sources.filter(function (srcAndPath, index, array) {
return array.findIndex(function (item) {

@@ -71,2 +74,3 @@ return item.path === srcAndPath.path;

});
return finalSources;
}

@@ -12,16 +12,4 @@ "use strict";

var _language = require("graphql/language");
var _requireGql = require("./requireGql");
var _errorMessages = require("./errorMessages");
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

@@ -36,3 +24,2 @@

var resolve;
var seenJSFiles = new Set();

@@ -57,7 +44,3 @@ var _default = function _default(_ref) {

var _opts$extensions = opts.extensions,
extensions = _opts$extensions === void 0 ? [] : _opts$extensions,
_opts$emitDeclaration = opts.emitDeclarations,
emitDeclarations = _opts$emitDeclaration === void 0 ? false : _opts$emitDeclaration,
_opts$sourceOnly = opts.sourceOnly,
sourceOnly = _opts$sourceOnly === void 0 ? false : _opts$sourceOnly;
extensions = _opts$extensions === void 0 ? [] : _opts$extensions;
extensions = _toConsumableArray(extensions).concat(['.graphql', '.gql']);

@@ -68,11 +51,3 @@

})) {
if (opts.runtime) {
try {
require('graphql-tag');
} catch (e) {
throw new Error(_errorMessages.missingOptionalDep);
}
} // Find the file, using node resolution/NODE_PATH if necessary.
// Find the file, using node resolution/NODE_PATH if necessary.
var fallbackPaths = opts.nodePath ? opts.nodePath.split(_path.delimiter) : [process.env.NODE_PATH];

@@ -94,50 +69,8 @@ var absPath = resolve(importPath, jsFilename);

resolve,
nowrap: false,
emitDeclarations,
sourceOnly
nowrap: false
});
var importNames = curPath.node.specifiers;
if (typeof result === 'string') {
curPath.replaceWith(buildSrcVarNode(result, importNames[0].local.name));
} else {
var replacements = buildReplacements(result, importNames, opts, seenJSFiles);
replacements.length > 1 ? curPath.replaceWithMultiple(replacements) : curPath.replaceWith(replacements[0]);
}
curPath.replaceWith(buildSrcVarNode(result, importNames[0].local.name));
}
function buildReplacements(docs, specifiers, opts, seenJSFiles) {
var replacements = [];
var buildVarNode = opts.runtime ? buildRuntimeVarNode : buildASTVarNode; // Add the graphql-tag import to the first non-schema .graphql import in each .js file.
if (opts.runtime && !seenJSFiles.has(jsFilename)) {
replacements = _toConsumableArray(replacements).concat([template(`import gql from 'graphql-tag'`, {
sourceType: 'module'
})()]);
}
seenJSFiles.add(jsFilename);
var varNodes = specifiers.map(function (_ref4) {
var type = _ref4.type,
imported = _ref4.imported,
local = _ref4.local;
switch (type) {
case 'ImportDefaultSpecifier':
return buildVarNode(docs.default, local.name);
case 'ImportSpecifier':
return buildVarNode(docs[imported.name] || docs.default, local.name);
case 'ImportNamespaceSpecifier':
return buildVarNode(docs, local.name);
default:
throw new Error(`Unexpected import specifier type: ${type}`);
}
});
return _toConsumableArray(replacements).concat(_toConsumableArray(varNodes));
} // Use to inline raw source when a schema-like file is detected.
function buildSrcVarNode(graphqlSrc, importName) {

@@ -151,43 +84,2 @@ var buildNode = template('var IMPORT_NAME = SOURCE;', {

});
} // Use to inline the raw GraphQL source text to be processed by 'graphql-tag' at runtime.
function buildRuntimeVarNode(graphqlAST, importName) {
if (graphqlAST.default) {
var properties = Object.entries(graphqlAST).map(function (_ref5) {
var _ref6 = _slicedToArray(_ref5, 2),
key = _ref6[0],
value = _ref6[1];
var expr = t.callExpression(t.identifier('gql'), [t.stringLiteral((0, _language.print)(value))]);
return t.objectProperty(t.stringLiteral(key), expr);
});
return template('var IMPORT_NAME = SOURCE', {
sourceType: 'module'
})({
IMPORT_NAME: t.identifier(importName),
SOURCE: t.objectExpression(properties)
});
}
var buildNode = template('var IMPORT_NAME = gql(SOURCE);', {
sourceType: 'module'
});
return buildNode({
IMPORT_NAME: t.identifier(importName),
SOURCE: t.stringLiteral((0, _language.print)(graphqlAST))
});
} // Use to inline the preprocessed AST object when the 'runtime' option is off.
function buildASTVarNode(graphqlAST, importName) {
var buildNode = template('var IMPORT_NAME = AST;', {
sourceType: 'module'
});
var astNode = t.valueToNode(JSON.parse(JSON.stringify(graphqlAST)));
astNode._compact = true;
return buildNode({
IMPORT_NAME: t.identifier(importName),
AST: astNode
});
}

@@ -194,0 +86,0 @@ }

@@ -12,6 +12,2 @@ "use strict";

var _graphqlTag = _interopRequireDefault(require("graphql-tag"));
var _multiOp = require("./multiOp");
var _constants = require("./constants");

@@ -21,14 +17,4 @@

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) {

@@ -43,30 +29,15 @@ return _path.default.resolve((0, _path.dirname)(file), src);

_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,
_ref$sourceOnly = _ref.sourceOnly,
sourceOnly = _ref$sourceOnly === void 0 ? false : _ref$sourceOnly;
resolve = _ref$resolve === void 0 ? defaultResolve : _ref$resolve;
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 (unless the sourceOnly option is set)
var source = (0, _fs.readFileSync)(filepath).toString();
var imports = customImport.getFilepaths(source, filepath, resolve);
if (sourceOnly || 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.
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;
var importSources = customImport.getImportSources(source, filepath, resolve).map(stripImportStatements).join('');
return `${stripImportStatements(source)}${importSources}`;
};

@@ -76,24 +47,2 @@

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() {

@@ -116,81 +65,4 @@ // To avoid dependencies, I borrowed this from gh (sindresorhus/callsites/blob/master/index.js)

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;
}
{
"name": "@anders-nom/babel-plugin-import-graphql-string",
"version": "2.8.1-11",
"version": "2.8.1-12",
"description": "Babel plugin to make .gql/.graphql files importable",

@@ -29,8 +29,4 @@ "author": "A.J. Roberts <detrohutt@gmail.com>",

},
"dependencies": {
"graphql-tag": "^2.9.2"
},
"peerDependencies": {
"graphql": ">=0.9.6",
"graphql-tag": "^2.1.0"
"graphql": ">=0.9.6"
},

@@ -37,0 +33,0 @@ "devDependencies": {

Fork of [babel-plugin-import-graphql](https://github.com/detrohutt/babel-plugin-import-graphql)
Adds the option "sourceOnly" to resolve all files to raw GraphQL source strings.
Resolves all imports to graphql source strings
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc