-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
211 lines (192 loc) · 7.86 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
var VirtualModulesPlugin = require('webpack-virtual-modules');
var RawSource = require('webpack-sources').RawSource;
var ExtractGQL = require('persistgraphql/lib/src/ExtractGQL').ExtractGQL;
var ExtractFromJs = require('persistgraphql/lib/src/extractFromJS');
var path = require('path');
var addTypenameTransformer = require('persistgraphql/lib/src/queryTransformers').addTypenameTransformer;
var graphql = require('graphql');
var _ = require('lodash');
var crypto = require('crypto');
function defaultHashQuery(query) {
return crypto
.createHash('sha256')
.update(query)
.digest('hex');
}
function PersistGraphQLPlugin(options) {
this.options = options || {};
if (!this.options.moduleName) throw new Error('moduleName option is required for PersistGraphQLPlugin');
if (this.options.provider) {
this.options.provider._addListener(this);
} else {
this._listeners = [];
}
this.options.addTypename = typeof this.options.addTypename !== 'undefined' ? this.options.addTypename : true;
this.options.hashQuery = typeof this.options.hashQuery !== 'undefined' ? this.options.hashQuery : defaultHashQuery;
this.options.excludeRegex = this.options.excludeRegex || /[\\/]node_modules[\\/]/;
this.options.graphqlRegex = this.options.graphqlRegex || /(.graphql|.gql)$/;
this.options.jsRegex = this.options.jsRegex || /(.jsx?|.tsx?)$/;
this.virtualModules = new VirtualModulesPlugin();
}
PersistGraphQLPlugin.prototype._addListener = function(listener) {
this._listeners.push(listener);
};
PersistGraphQLPlugin.prototype._notify = function(queryMap) {
var self = this;
if (self._queryMap !== queryMap) {
self.virtualModules.writeModule(self.options.moduleName, queryMap);
}
self._queryMap = queryMap;
if (self._callback) {
self._callback();
delete self._callback;
}
};
PersistGraphQLPlugin.prototype.apply = function(compiler) {
var self = this;
self.virtualModules.apply(compiler);
self._compiler = compiler;
compiler.plugin('compilation', function(compilation) {
if (!self._queryMap && !compilation.compiler.parentCompilation) {
self.virtualModules.writeModule(self.options.moduleName, '{}');
}
});
compiler.plugin('normal-module-factory', function(nmf) {
nmf.plugin('after-resolve', function(result, callback) {
if (!result) {
return callback();
}
if (self.options.provider && result.request.indexOf(self.options.moduleName) >= 0 && !self._queryMap) {
self._callback = function() {
return callback(null, result);
};
} else {
return callback(null, result);
}
});
});
if (!self.options.provider) {
compiler.plugin('compilation', function(compilation) {
if (!compilation.compiler.parentCompilation) {
compilation.plugin('seal', function() {
var graphQLString = '';
var allQueries = [];
compilation.modules.forEach(function(module) {
if (!self.options.excludeRegex.test(module.resource)) {
if (self.options.graphqlRegex.test(module.resource)) {
// Workaround for `graphql-persisted-document-loader`
// It does not generate eval-friendly source code at the moment
var sourceLines = module._source._value.split(/\r\n|\r|\n/);
var len = sourceLines.length;
if (
sourceLines
.slice(-1)
.pop()
.indexOf('doc.documentId') === 0
) {
// Swap last two lines of source code
sourceLines = sourceLines.slice(0, len - 2).concat([sourceLines[len - 1], sourceLines[len - 2]]);
} else if (self.options.hashQuery) {
var queryContents = graphql.print(eval(sourceLines.join('\n')));
var queryId = self.options.hashQuery(queryContents);
sourceLines = sourceLines
.slice(0, len - 1)
.concat(['doc.documentId = "' + queryId + '";', sourceLines[len - 1]]);
}
graphQLString += graphql.print(eval(sourceLines.join('\n')));
} else if (self.options.jsRegex.test(module.resource)) {
var literalContents = ExtractFromJs.findTaggedTemplateLiteralsInJS(module._source._value, 'gql');
var queryList = literalContents.map(ExtractFromJs.eliminateInterpolations);
for (var idx = 0; idx < queryList.length; idx++) {
var query = queryList[idx];
allQueries.push(
self.options.addTypename
? graphql.print(addTypenameTransformer(JSON.parse(JSON.stringify(graphql.parse(query)))))
: query
);
}
}
}
});
if (graphQLString) {
var extractor = new ExtractGQL({
inputFilePath: '',
queryTransformers: self.options.addTypename
? [
function(doc) {
return addTypenameTransformer(JSON.parse(JSON.stringify(doc)));
}
]
: undefined
});
var doc = graphql.parse(graphQLString);
var docMap = graphql.separateOperations(doc);
var queries = {};
Object.keys(docMap).forEach(function(operationName) {
var document = docMap[operationName];
var fragmentMap = {};
for (var i = document.definitions.length - 1; i >= 0; i--) {
var def = document.definitions[i];
if (def.kind === 'FragmentDefinition') {
if (!fragmentMap[def.name.value]) {
fragmentMap[def.name.value] = true;
} else {
document.definitions.splice(i, 1);
}
}
}
queries = _.merge(queries, extractor.createMapFromDocument(document));
});
Object.keys(queries).forEach(function(query) {
allQueries.push(query);
});
}
var mapObj;
if (allQueries.length) {
var finalExtractor = new ExtractGQL({
inputFilePath: '',
queryTransformers: self.options.addTypename
? [
function(doc) {
return addTypenameTransformer(JSON.parse(JSON.stringify(doc)));
}
]
: undefined
});
mapObj = finalExtractor.createOutputMapFromString(allQueries.join('\n'));
}
if (self.options.hashQuery && !!mapObj) {
Object.keys(mapObj).forEach(function(query) {
mapObj[query] = self.options.hashQuery(query);
});
}
var newQueryMap = JSON.stringify(mapObj);
if (newQueryMap !== self._queryMap) {
self._queryMap = newQueryMap;
self.virtualModules.writeModule(self.options.moduleName, self._queryMap);
compilation.modules.forEach(function(module) {
if (
module.resource === self.options.moduleName ||
module.resource === path.resolve(path.join(compiler.context, self.options.moduleName))
) {
module._source._value = 'module.exports = ' + self._queryMap + ';';
}
});
}
self._listeners.forEach(function(listener) {
listener._notify(self._queryMap);
});
});
}
});
}
if (self.options.filename) {
compiler.plugin('after-compile', function(compilation, callback) {
if (!compilation.compiler.parentCompilation) {
compilation.assets[self.options.filename] = new RawSource(self._queryMap);
}
callback();
});
}
};
module.exports = PersistGraphQLPlugin;