This repository has been archived by the owner on Aug 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 126
/
index.js
236 lines (190 loc) · 6.9 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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import { statSync } from 'fs';
import { dirname, extname, resolve, sep } from 'path';
import { sync as nodeResolveSync } from 'resolve';
import { createFilter } from 'rollup-pluginutils';
import { EXTERNAL, PREFIX, HELPERS_ID, HELPERS } from './helpers.js';
import defaultResolver from './defaultResolver.js';
import { checkFirstpass, checkEsModule, transformCommonjs } from './transform.js';
import { getName } from './utils.js';
function getCandidatesForExtension ( resolved, extension ) {
return [
resolved + extension,
resolved + `${sep}index${extension}`
];
}
function getCandidates ( resolved, extensions ) {
return extensions.reduce(
( paths, extension ) => paths.concat( getCandidatesForExtension ( resolved, extension ) ),
[resolved]
);
}
// Return the first non-falsy result from an array of
// maybe-sync, maybe-promise-returning functions
function first ( candidates ) {
return function ( ...args ) {
return candidates.reduce( ( promise, candidate ) => {
return promise.then( result => result != null ?
result :
Promise.resolve( candidate( ...args ) ) );
}, Promise.resolve() );
};
}
function startsWith ( str, prefix ) {
return str.slice( 0, prefix.length ) === prefix;
}
const isCjsPromises = Object.create(null);
export default function commonjs ( options = {} ) {
const extensions = options.extensions || ['.js'];
const filter = createFilter( options.include, options.exclude );
const ignoreGlobal = options.ignoreGlobal;
const customNamedExports = {};
if ( options.namedExports ) {
Object.keys( options.namedExports ).forEach( id => {
let resolvedId;
try {
resolvedId = nodeResolveSync( id, { basedir: process.cwd() });
} catch ( err ) {
resolvedId = resolve( id );
}
customNamedExports[ resolvedId ] = options.namedExports[ id ];
});
}
const esModulesWithoutDefaultExport = [];
const allowDynamicRequire = !!options.ignore; // TODO maybe this should be configurable?
const ignoreRequire = typeof options.ignore === 'function' ?
options.ignore :
Array.isArray( options.ignore ) ? id => ~options.ignore.indexOf( id ) :
() => false;
let entryModuleIdsPromise = null;
function resolveId ( importee, importer ) {
if ( importee === HELPERS_ID ) return importee;
if ( importer && startsWith( importer, PREFIX ) ) importer = importer.slice( PREFIX.length );
const isProxyModule = startsWith( importee, PREFIX );
if ( isProxyModule ) importee = importee.slice( PREFIX.length );
return resolveUsingOtherResolvers( importee, importer ).then( resolved => {
if ( resolved ) return isProxyModule ? PREFIX + resolved : resolved;
resolved = defaultResolver( importee, importer );
if ( isProxyModule ) {
if ( resolved ) return PREFIX + resolved;
return EXTERNAL + importee; // external
}
return resolved;
});
}
const sourceMap = options.sourceMap !== false;
let resolveUsingOtherResolvers;
function getIsCjsPromise ( id ) {
let isCjsPromise = isCjsPromises[id];
if (isCjsPromise)
return isCjsPromise.promise;
const promise = new Promise( resolve => {
isCjsPromises[id] = isCjsPromise = {
resolve: resolve,
promise: undefined
};
});
isCjsPromise.promise = promise;
return promise;
}
function setIsCjsPromise ( id, promise ) {
const isCjsPromise = isCjsPromises[id];
if (isCjsPromise) {
if (isCjsPromise.resolve) {
isCjsPromise.resolve(promise);
isCjsPromise.resolve = undefined;
}
}
else {
isCjsPromises[id] = { promise: promise, resolve: undefined };
}
}
return {
name: 'commonjs',
options ( options ) {
const resolvers = ( options.plugins || [] )
.map( plugin => {
if ( plugin.resolveId === resolveId ) {
// substitute CommonJS resolution logic
return ( importee, importer ) => {
if ( importee[0] !== '.' || !importer ) return; // not our problem
const resolved = resolve( dirname( importer ), importee );
const candidates = getCandidates( resolved, extensions );
for ( let i = 0; i < candidates.length; i += 1 ) {
try {
const stats = statSync( candidates[i] );
if ( stats.isFile() ) return candidates[i];
} catch ( err ) { /* noop */ }
}
};
}
return plugin.resolveId;
})
.filter( Boolean );
const isExternal = id => options.external ?
Array.isArray( options.external ) ? ~options.external.indexOf( id ) :
options.external(id) :
false;
resolvers.unshift( id => isExternal( id ) ? false : null );
resolveUsingOtherResolvers = first( resolvers );
const input = options.input || options.entry;
const entryModules = Array.isArray(input) ?
input :
typeof input === 'object' && input !== null ?
Object.values(input) :
[input];
entryModuleIdsPromise = Promise.all(
entryModules.map( entry => resolveId( entry ))
);
},
resolveId,
load ( id ) {
if ( id === HELPERS_ID ) return HELPERS;
// generate proxy modules
if ( startsWith( id, EXTERNAL ) ) {
const actualId = id.slice( EXTERNAL.length );
const name = getName( actualId );
return `import ${name} from ${JSON.stringify( actualId )}; export default ${name};`;
}
if ( startsWith( id, PREFIX ) ) {
const actualId = id.slice( PREFIX.length );
const name = getName( actualId );
return ( ( extensions.indexOf( extname( id ) ) === -1 ) ? Promise.resolve(false) : getIsCjsPromise( actualId ) )
.then( isCjs => {
if ( isCjs )
return `import { __moduleExports } from ${JSON.stringify( actualId )}; export default __moduleExports;`;
else if (esModulesWithoutDefaultExport.indexOf(actualId) !== -1)
return `import * as ${name} from ${JSON.stringify( actualId )}; export default ${name};`;
else
return `import * as ${name} from ${JSON.stringify( actualId )}; export default ( ${name} && ${name}['default'] ) || ${name};`;
});
}
},
transform ( code, id ) {
if ( !filter( id ) ) return null;
if ( extensions.indexOf( extname( id ) ) === -1 ) return null;
const transformPromise = entryModuleIdsPromise.then( (entryModuleIds) => {
const {isEsModule, hasDefaultExport, ast} = checkEsModule( this.parse, code, id );
if ( isEsModule ) {
if ( !hasDefaultExport )
esModulesWithoutDefaultExport.push( id );
return;
}
// it is not an ES module but not a commonjs module, too.
if ( !checkFirstpass( code, ignoreGlobal ) ) {
esModulesWithoutDefaultExport.push( id );
return;
}
const transformed = transformCommonjs( this.parse, code, id, entryModuleIds.indexOf(id) !== -1, ignoreGlobal, ignoreRequire, customNamedExports[ id ], sourceMap, allowDynamicRequire, ast );
if ( !transformed ) {
esModulesWithoutDefaultExport.push( id );
return;
}
return transformed;
}).catch(err => {
this.error(err, err.loc);
});
setIsCjsPromise(id, transformPromise.then( transformed => transformed ? true : false, () => true ));
return transformPromise;
}
};
}