-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathnpmHelpers.mjs
More file actions
235 lines (200 loc) · 7.76 KB
/
Copy pathnpmHelpers.mjs
File metadata and controls
235 lines (200 loc) · 7.76 KB
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// @ts-check
/**
* Rollup config docs: https://rollupjs.org/guide/en/#big-list-of-options
*/
import * as fs from 'fs';
import { builtinModules } from 'module';
import * as path from 'path';
import { fileURLToPath } from 'url';
import deepMerge from 'deepmerge';
import { defineConfig } from 'rollup';
import {
makeCleanupPlugin,
makeDebugBuildStatementReplacePlugin,
makeNodeResolvePlugin,
makeProductionReplacePlugin,
makeRrwebBuildPlugin,
makeSucrasePlugin,
} from './plugins/index.mjs';
import { makePackageNodeEsm } from './plugins/make-esm-plugin.mjs';
import { mergePlugins } from './utils.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const packageDotJSON = JSON.parse(fs.readFileSync(path.resolve(process.cwd(), './package.json'), { encoding: 'utf8' }));
const ignoreSideEffects = /[\\\/]debug-build\.ts$/;
export function makeBaseNPMConfig(options = {}) {
const {
entrypoints = ['src/index.ts'],
hasBundles = false,
packageSpecificConfig = {},
sucrase = {},
bundledBuiltins = [],
} = options;
const nodeResolvePlugin = makeNodeResolvePlugin();
const sucrasePlugin = makeSucrasePlugin({}, sucrase);
const debugBuildStatementReplacePlugin = makeDebugBuildStatementReplacePlugin();
const cleanupPlugin = makeCleanupPlugin();
const rrwebBuildPlugin = makeRrwebBuildPlugin({
excludeShadowDom: undefined,
excludeIframe: undefined,
});
const defaultBaseConfig = {
input: entrypoints,
output: {
// an appropriately-named directory will be added to this base value when we specify either a cjs or esm build
dir: hasBundles ? 'build/npm' : 'build',
sourcemap: true,
// Include __esModule property when there is a default prop
esModule: 'if-default-prop',
// output individual files rather than one big bundle
preserveModules: true,
// Allow wrappers or helper functions generated by rollup to use any ES2015 features
generatedCode: {
preset: 'es2015',
},
// don't add `"use strict"` to the top of cjs files
strict: false,
// Use simple exports format:
// exports.dogs = are.great
// rather than Object.defineProperty style exports
externalLiveBindings: false,
// Don't call `Object.freeze` on the results of `import * as someModule from '...'`
// (We don't need it, so why waste the bytes?)
freeze: false,
interop: 'esModule',
},
treeshake: {
moduleSideEffects: (id, external) => {
if (external === false && ignoreSideEffects.test(id)) {
// Tell Rollup this module has no side effects, so it can be tree-shaken
return false;
}
return true;
},
},
plugins: [nodeResolvePlugin, sucrasePlugin, debugBuildStatementReplacePlugin, rrwebBuildPlugin, cleanupPlugin],
// don't include imported modules from outside the package in the final output
external: [
...builtinModules.filter(m => !bundledBuiltins.includes(m)),
...Object.keys(packageDotJSON.dependencies || {}),
...Object.keys(packageDotJSON.peerDependencies || {}),
...Object.keys(packageDotJSON.optionalDependencies || {}),
],
};
return deepMerge(defaultBaseConfig, packageSpecificConfig, {
// Plugins have to be in the correct order or everything breaks, so when merging we have to manually re-order them
customMerge: key => (key === 'plugins' ? mergePlugins : undefined),
});
}
export function makeNPMConfigVariants(baseConfig, options = {}) {
const { emitEsm = true, emitCjs = true, splitDevProd = false } = options;
const variantSpecificConfigs = [];
if (emitCjs) {
if (splitDevProd) {
variantSpecificConfigs.push({ output: { format: 'cjs', dir: path.join(baseConfig.output.dir, 'cjs/dev') } });
variantSpecificConfigs.push({
output: { format: 'cjs', dir: path.join(baseConfig.output.dir, 'cjs/prod') },
plugins: [makeProductionReplacePlugin()],
});
} else {
variantSpecificConfigs.push({ output: { format: 'cjs', dir: path.join(baseConfig.output.dir, 'cjs') } });
}
}
if (emitEsm) {
if (splitDevProd) {
variantSpecificConfigs.push({
output: {
format: 'esm',
dir: path.join(baseConfig.output.dir, 'esm/dev'),
plugins: [makePackageNodeEsm()],
},
});
variantSpecificConfigs.push({
output: {
format: 'esm',
dir: path.join(baseConfig.output.dir, 'esm/prod'),
plugins: [makeProductionReplacePlugin(), makePackageNodeEsm()],
},
});
} else {
variantSpecificConfigs.push({
output: {
format: 'esm',
dir: path.join(baseConfig.output.dir, 'esm'),
plugins: [makePackageNodeEsm()],
},
});
}
}
return variantSpecificConfigs.map(variant => deepMerge(baseConfig, variant));
}
/**
* This creates a loader file at the target location as part of the rollup build.
* This loader script can then be used in combination with various Node.js flags (like --import=...) to monkeypatch 3rd party modules.
*/
export function makeOtelLoaders(outputFolder, hookVariant) {
if (hookVariant !== 'otel' && hookVariant !== 'sentry-node') {
throw new Error('hookVariant is neither "otel" nor "sentry-node". Pick one.');
}
const expectedRegisterLoaderLocation = `${outputFolder}/import-hook.mjs`;
const foundRegisterLoaderExport = Object.keys(packageDotJSON.exports ?? {}).some(key => {
return packageDotJSON?.exports?.[key]?.import?.default === expectedRegisterLoaderLocation;
});
if (!foundRegisterLoaderExport) {
throw new Error(
`You used the makeOtelLoaders() rollup utility without specifying the import hook inside \`exports[something].import.default\`. Please add "${expectedRegisterLoaderLocation}" as a value there (maybe check for typos - it needs to be "${expectedRegisterLoaderLocation}" exactly).`,
);
}
const expectedHooksLoaderLocation = `${outputFolder}/loader-hook.mjs`;
const foundHookLoaderExport = Object.keys(packageDotJSON.exports ?? {}).some(key => {
return packageDotJSON?.exports?.[key]?.import?.default === expectedHooksLoaderLocation;
});
if (!foundHookLoaderExport) {
throw new Error(
`You used the makeOtelLoaders() rollup utility without specifying the loader hook inside \`exports[something].import.default\`. Please add "${expectedHooksLoaderLocation}" as a value there (maybe check for typos - it needs to be "${expectedHooksLoaderLocation}" exactly).`,
);
}
const requiredDep = hookVariant === 'otel' ? '@opentelemetry/instrumentation' : '@sentry/node';
const foundImportInTheMiddleDep =
Object.keys(packageDotJSON.dependencies ?? {}).some(key => {
return key === requiredDep;
}) ||
Object.keys(packageDotJSON.devDependencies ?? {}).some(key => {
return key === requiredDep;
});
if (!foundImportInTheMiddleDep) {
throw new Error(
`You used the makeOtelLoaders() rollup utility but didn't specify the "${requiredDep}" dependency in ${path.resolve(
process.cwd(),
'package.json',
)}. Please add it to the dependencies.`,
);
}
return defineConfig([
// register() hook
{
input: path.join(
__dirname,
'code',
hookVariant === 'otel' ? 'otelEsmImportHookTemplate.js' : 'sentryNodeEsmImportHookTemplate.js',
),
external: /.*/,
output: {
format: 'esm',
file: path.join(outputFolder, 'import-hook.mjs'),
},
},
// --loader hook
{
input: path.join(
__dirname,
'code',
hookVariant === 'otel' ? 'otelEsmLoaderHookTemplate.js' : 'sentryNodeEsmLoaderHookTemplate.js',
),
external: /.*/,
output: {
format: 'esm',
file: path.join(outputFolder, 'loader-hook.mjs'),
},
},
]);
}