Mirror: The small sibling of the graphql package, slimmed down for client-side libraries.
1import * as path from 'path';
2import { promises as fs } from 'fs';
3
4import resolve from '@rollup/plugin-node-resolve';
5import replace from '@rollup/plugin-replace';
6import terser from '@rollup/plugin-terser';
7import { babel } from '@rollup/plugin-babel';
8
9import babelModularGraphQL from 'babel-plugin-modular-graphql';
10import babelTransformComputedProps from '../babel/transformComputedProps.mjs';
11import babelTransformDevAssert from '../babel/transformDevAssert.mjs';
12import babelTransformObjectFreeze from '../babel/transformObjectFreeze.mjs';
13
14import { version } from './packageMetadata.mjs';
15import { generateImportMap } from './importMap.mjs';
16
17const cwd = process.cwd();
18const graphqlModule = path.posix.join(cwd, 'node_modules/graphql/');
19const virtualModule = path.posix.join(cwd, 'virtual/');
20const aliasModule = path.posix.join(cwd, 'alias/');
21
22const EXTERNAL = 'graphql';
23const externalModules = ['dns', 'fs', 'path', 'url'];
24const externalPredicate = new RegExp(`^(${externalModules.join('|')})($|/)`);
25
26function manualChunks(id, utils) {
27 let chunk;
28 if (id.startsWith(graphqlModule)) {
29 chunk = id.slice(graphqlModule.length);
30 } else if (id.startsWith(virtualModule)) {
31 chunk = id.slice(virtualModule.length);
32 } else if (id.startsWith(aliasModule)) {
33 chunk = id.slice(aliasModule.length);
34 }
35
36 if (chunk) {
37 return chunk.replace(/\.m?js$/, '');
38 }
39
40 const { importers } = utils.getModuleInfo(id);
41 return importers.length === 1 ? manualChunks(importers[0], utils) : 'shared';
42}
43
44function buildPlugin() {
45 const exports = {};
46 return {
47 async buildStart(options) {
48 const importMap = await generateImportMap();
49
50 for (const key in importMap) {
51 const { from, local } = importMap[key];
52 if (/\/jsutils\//g.test(from)) continue;
53
54 const name = from.replace(/^graphql\//, '');
55 exports[name] = (exports[name] || '') + `export { ${key} } from '${EXTERNAL}'\n`;
56
57 const parts = name.split('/');
58 for (let i = parts.length - 1; i > 0; i--) {
59 const name = `${parts.slice(0, i).join('/')}/index`;
60 const from = `./${parts.slice(i).join('/')}`;
61 if (from !== './index')
62 exports[name] = (exports[name] || '') + `export { ${local} } from '${from}'\n`;
63 }
64
65 const index = `export { ${local} } from './${name}'\n`;
66 exports.index = (exports.index || '') + index;
67 }
68
69 if (typeof options.input !== 'object') options.input = {};
70
71 for (const key in exports) {
72 options.input[key] = path.posix.join('./virtual', key);
73 }
74 },
75
76 async load(id) {
77 if (!id.startsWith(virtualModule)) return null;
78 const entry = path.posix.relative(virtualModule, id).replace(/\.m?js$/, '');
79 if (entry === 'version') return version;
80 return exports[entry] || null;
81 },
82
83 async resolveId(source, importer) {
84 if (!source.startsWith('.') && !source.startsWith('virtual/')) return null;
85
86 const target = path.posix.join(importer ? path.posix.dirname(importer) : cwd, source);
87
88 const virtualEntry = path.posix.relative(virtualModule, target);
89 if (!virtualEntry.startsWith('../')) {
90 const aliasSource = path.posix.join(aliasModule, virtualEntry);
91 const alias = await this.resolve(aliasSource, undefined, {
92 skipSelf: true,
93 });
94 return alias || target;
95 }
96
97 const graphqlEntry = path.posix.relative(graphqlModule, target);
98 if (!graphqlEntry.startsWith('../')) {
99 const aliasSource = path.posix.join(aliasModule, graphqlEntry);
100 const alias = await this.resolve(aliasSource, undefined, {
101 skipSelf: true,
102 });
103 return alias || target;
104 }
105
106 return null;
107 },
108
109 async renderChunk(_code, { fileName }) {
110 const name = fileName.replace(/\.m?js$/, '');
111
112 const getContents = async extension => {
113 try {
114 const name = fileName.replace(/\.m?js$/, '');
115 const contents = await fs.readFile(path.join(graphqlModule, name + extension));
116 return contents;
117 } catch (_error) {
118 return null;
119 }
120 };
121
122 const dts = await getContents('.d.ts');
123 const flow = await getContents('.js.flow');
124
125 if (dts) {
126 this.emitFile({
127 type: 'asset',
128 fileName: name + '.d.ts',
129 source: dts,
130 });
131 }
132
133 if (flow) {
134 this.emitFile({
135 type: 'asset',
136 fileName: name + '.js.flow',
137 source: flow,
138 });
139 }
140
141 return null;
142 },
143 };
144}
145
146export default {
147 input: {},
148 external(id) {
149 return externalPredicate.test(id);
150 },
151 treeshake: {
152 unknownGlobalSideEffects: false,
153 tryCatchDeoptimization: false,
154 moduleSideEffects: false,
155 },
156 plugins: [
157 buildPlugin(),
158
159 resolve({
160 extensions: ['.mjs', '.js'],
161 mainFields: ['module', 'browser', 'main'],
162 preferBuiltins: false,
163 browser: true,
164 }),
165
166 babel({
167 babelrc: false,
168 babelHelpers: 'bundled',
169 presets: [],
170 plugins: [
171 babelTransformDevAssert,
172 babelTransformObjectFreeze,
173 babelTransformComputedProps,
174 babelModularGraphQL,
175 ],
176 }),
177
178 replace({
179 preventAssignment: true,
180 values: {
181 'process.env.NODE_ENV': JSON.stringify('production'),
182 },
183 }),
184
185 terser({
186 warnings: true,
187 ecma: 2016,
188 keep_fnames: true,
189 compress: {
190 module: true,
191 pure_getters: true,
192 toplevel: true,
193 booleans_as_integers: false,
194 keep_fnames: true,
195 keep_fargs: true,
196 if_return: false,
197 ie8: false,
198 sequences: false,
199 loops: false,
200 conditionals: false,
201 join_vars: false,
202 },
203 mangle: false,
204 output: {
205 beautify: true,
206 braces: true,
207 indent_level: 2,
208 },
209 }),
210 ],
211
212 treeshake: 'smallest',
213 shimMissingExports: false,
214 preserveEntrySignatures: 'allow-extension',
215 preserveSymlinks: true,
216
217 output: [
218 {
219 chunkFileNames: '[name].js',
220 entryFileNames: '[name].js',
221 dir: '.',
222 exports: 'named',
223 format: 'cjs',
224 minifyInternalExports: false,
225 hoistTransitiveImports: false,
226 manualChunks,
227 },
228 {
229 chunkFileNames: '[name].mjs',
230 entryFileNames: '[name].mjs',
231 dir: '.',
232 exports: 'named',
233 format: 'esm',
234 minifyInternalExports: false,
235 hoistTransitiveImports: false,
236 manualChunks,
237 },
238 ],
239};