forked from sveltejs/svelte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrapModule.ts
313 lines (251 loc) · 7.64 KB
/
wrapModule.ts
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import deindent from '../utils/deindent';
import list from '../utils/list';
import { CompileOptions, ModuleFormat, Node, ShorthandImport } from '../interfaces';
interface Dependency {
name: string;
statements: string[];
source: string;
}
const wrappers = { es, amd, cjs, iife, umd, eval: expr };
export default function wrapModule(
code: string,
format: ModuleFormat,
name: string,
options: CompileOptions,
banner: string,
sharedPath: string,
helpers: { name: string, alias: string }[],
imports: Node[],
shorthandImports: ShorthandImport[],
source: string
): string {
if (format === 'es') return es(code, name, options, banner, sharedPath, helpers, imports, shorthandImports, source);
const dependencies = imports.map((declaration, i) => {
const defaultImport = declaration.specifiers.find(
(x: Node) =>
x.type === 'ImportDefaultSpecifier' ||
(x.type === 'ImportSpecifier' && x.imported.name === 'default')
);
const namespaceImport = declaration.specifiers.find(
(x: Node) => x.type === 'ImportNamespaceSpecifier'
);
const namedImports = declaration.specifiers.filter(
(x: Node) =>
x.type === 'ImportSpecifier' && x.imported.name !== 'default'
);
const name = defaultImport || namespaceImport
? (defaultImport || namespaceImport).local.name
: `__import${i}`;
const statements: string[] = [];
namedImports.forEach((specifier: Node) => {
statements.push(
`var ${specifier.local.name} = ${name}.${specifier.imported.name};`
);
});
if (defaultImport) {
statements.push(
`${name} = (${name} && ${name}.__esModule) ? ${name}["default"] : ${name};`
);
}
return { name, statements, source: declaration.source.value };
})
.concat(
shorthandImports.map(({ name, source }) => ({
name,
statements: [
`${name} = (${name} && ${name}.__esModule) ? ${name}["default"] : ${name};`,
],
source,
}))
);
if (format === 'amd') return amd(code, name, options, banner, dependencies);
if (format === 'cjs') return cjs(code, name, options, banner, sharedPath, helpers, dependencies);
if (format === 'iife') return iife(code, name, options, banner, dependencies);
if (format === 'umd') return umd(code, name, options, banner, dependencies);
if (format === 'eval') return expr(code, name, options, banner, dependencies);
throw new Error(`options.format is invalid (must be ${list(Object.keys(wrappers))})`);
}
function es(
code: string,
name: string,
options: CompileOptions,
banner: string,
sharedPath: string,
helpers: { name: string, alias: string }[],
imports: Node[],
shorthandImports: ShorthandImport[],
source: string
) {
const importHelpers = helpers.length > 0 && (
`import { ${helpers.map(h => h.name === h.alias ? h.name : `${h.name} as ${h.alias}`).join(', ')} } from ${JSON.stringify(sharedPath)};`
);
const importBlock = imports.length > 0 && (
imports
.map((declaration: Node) => source.slice(declaration.start, declaration.end))
.join('\n')
);
const shorthandImportBlock = shorthandImports.length > 0 && (
shorthandImports.map(({ name, source }) => `import ${name} from ${JSON.stringify(source)};`).join('\n')
);
return deindent`
${banner}
${importHelpers}
${importBlock}
${shorthandImportBlock}
${code}
export default ${name};`;
}
function amd(
code: string,
name: string,
options: CompileOptions,
banner: string,
dependencies: Dependency[]
) {
const sourceString = dependencies.length
? `[${dependencies.map(d => `"${removeExtension(d.source)}"`).join(', ')}], `
: '';
const id = options.amd && options.amd.id;
return deindent`
define(${id ? `"${id}", ` : ''}${sourceString}function(${paramString(dependencies)}) { "use strict";
${getCompatibilityStatements(dependencies)}
${code}
return ${name};
});`;
}
function cjs(
code: string,
name: string,
options: CompileOptions,
banner: string,
sharedPath: string,
helpers: { name: string, alias: string }[],
dependencies: Dependency[]
) {
const helperDeclarations = helpers.map(h => `${h.alias === h.name ? h.name : `${h.name}: ${h.alias}`}`).join(', ');
const helperBlock = helpers.length > 0 && (
`var { ${helperDeclarations} } = require(${JSON.stringify(sharedPath)});\n`
);
const requireBlock = dependencies.length > 0 && (
dependencies
.map(d => `var ${d.name} = require("${d.source}");`)
.join('\n\n')
);
return deindent`
${banner}
"use strict";
${helperBlock}
${requireBlock}
${getCompatibilityStatements(dependencies)}
${code}
module.exports = ${name};`
}
function iife(
code: string,
name: string,
options: CompileOptions,
banner: string,
dependencies: Dependency[]
) {
if (!options.name) {
throw new Error(`Missing required 'name' option for IIFE export`);
}
const globals = getGlobals(dependencies, options);
return deindent`
${banner}
var ${options.name} = (function(${paramString(dependencies)}) { "use strict";
${getCompatibilityStatements(dependencies)}
${code}
return ${name};
}(${globals.join(', ')}));`;
}
function umd(
code: string,
name: string,
options: CompileOptions,
banner: string,
dependencies: Dependency[]
) {
if (!options.name) {
throw new Error(`Missing required 'name' option for UMD export`);
}
const amdId = options.amd && options.amd.id ? `'${options.amd.id}', ` : '';
const amdDeps = dependencies.length
? `[${dependencies.map(d => `"${removeExtension(d.source)}"`).join(', ')}], `
: '';
const cjsDeps = dependencies
.map(d => `require("${d.source}")`)
.join(', ');
const globals = getGlobals(dependencies, options);
return deindent`
${banner}
(function(global, factory) {
typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory(${cjsDeps}) :
typeof define === "function" && define.amd ? define(${amdId}${amdDeps}factory) :
(global.${options.name} = factory(${globals.join(', ')}));
}(this, (function (${paramString(dependencies)}) { "use strict";
${getCompatibilityStatements(dependencies)}
${code}
return ${name};
})));`;
}
function expr(
code: string,
name: string,
options: CompileOptions,
banner: string,
dependencies: Dependency[]
) {
const globals = getGlobals(dependencies, options);
return deindent`
(function (${paramString(dependencies)}) { "use strict";
${banner}
${getCompatibilityStatements(dependencies)}
${code}
return ${name};
}(${globals.join(', ')}))`;
}
function paramString(dependencies: Dependency[]) {
return dependencies.map(dep => dep.name).join(', ');
}
function removeExtension(file: string) {
const index = file.lastIndexOf('.');
return ~index ? file.slice(0, index) : file;
}
function getCompatibilityStatements(dependencies: Dependency[]) {
if (!dependencies.length) return null;
const statements: string[] = [];
dependencies.forEach(dependency => {
statements.push(...dependency.statements);
});
return statements.join('\n');
}
function getGlobals(dependencies: Dependency[], options: CompileOptions) {
const { globals, onwarn } = options;
const globalFn = getGlobalFn(globals);
return dependencies.map(d => {
let name = globalFn(d.source);
if (!name) {
if (d.name.startsWith('__import')) {
throw new Error(
`Could not determine name for imported module '${d.source}' – use options.globals`
);
} else {
const warning = {
code: `options-missing-globals`,
message: `No name was supplied for imported module '${d.source}'. Guessing '${d.name}', but you should use options.globals`,
};
onwarn(warning);
}
name = d.name;
}
return name;
});
}
function getGlobalFn(globals: any): (id: string) => string {
if (typeof globals === 'function') return globals;
if (typeof globals === 'object') {
return id => globals[id];
}
return () => undefined;
}